PineForge v1.4.0-4-g873b25da
Deterministic PineScript v6 backtest runtime — C ABI reference
Loading...
Searching...
No Matches
pineforge::engine_script_run_v19::NativeStrategyHost Class Referenceabstract

The public native host: an abstract subclass of BacktestEngine with no PineScript on it. More...

#include <native_host.hpp>

Public Member Functions

 NativeStrategyHost ()
 
 NativeStrategyHost (const NativeStrategyHost &)=delete
 
NativeStrategyHost & operator= (const NativeStrategyHost &)=delete
 
 NativeStrategyHost (NativeStrategyHost &&)=delete
 
NativeStrategyHost & operator= (NativeStrategyHost &&)=delete
 
 ~NativeStrategyHost () override
 
void on_bar (const Bar &bar) final
 The engine's own bar entry, taken over by the native consumer and sealed.
 
virtual void prepare_native_begin (const NativeBeginArgs &)
 Offered once per begin, before the run starts, with the begin's own arguments — the bars, the timeframe literals, the magnifier settings, and the rich overload's InputsMap / SymInfo / opaque overrides.
 
virtual void on_native_run_begin ()
 Offered once per successful begin, after the reset and before any bar.
 
virtual void on_native_input (const Bar &, const NativeInputContext &)
 Called once for every accepted confirmed input bar, before that bar is aggregated or matched.
 
virtual void on_native_tick (const Bar &, const NativeTickContext &)
 Called once for every accepted realtime print, before matching at that point.
 
virtual void on_native_timeframe_bar (const Bar &, const NativeTimeframeBarContext &)
 One completed bucket of a declared higher-timeframe subscription, delivered on an accepted input bar before that input is aggregated, matched or calculated.
 
virtual void on_native_bar_open (const Bar &, const NativeDecisionContext &)
 Precedes the matching pass at the script bar's open decision point.
 
virtual void on_native_bar (const Bar &bar, const NativeDecisionContext &context)=0
 The current decision point remains valid for the complete callback.
 
virtual void on_native_recalculate (const Bar &bar, const NativeDecisionContext &ctx, NativeCalculationReason reason, const native_order::ExecutionAppliedEvent *cause)
 EVERY calculation of the run arrives here first, including the script bar's own close calculation (reason BarClose, cause nullptr), whose default forwarding keeps on_native_bar the complete contract for a host that never opts into another cadence.
 
virtual void on_native_sub_bar (const Bar &sub, const NativeDecisionContext &ctx)
 One completed lower-timeframe sub-bar of an IntrabarPath::lower_tf path, delivered after that sub-bar's whole matching path and before the next sub-bar's.
 
virtual void on_native_applied (const native_order::ExecutionAppliedEvent &, const NativeDecisionContext &)
 The calculate-on-fill hook: offered once per applied execution, FIFO, after the account record and the group/owner/dependency drains.
 
virtual native_order::ExecutionTerms resolve_execution_terms (const NativeExecutionTermsFacts &facts) const
 The fill-terms hook, consulted at every matching candidate.
 
virtual NativePrecommitVerdict validate_execution_precommit (const NativePrecommitView &) const
 The last gate before a physical effect, offered once per Applied-ready attempt and never during inspect_current_execution.
 
virtual std::optional< NativeMarginDecision > resolve_margin_requirement (const NativeMarginRequirementView &) const
 Consulted at EVERY kernel check point, BEFORE the breach test, exactly as resolve_execution_terms is consulted before a fill is booked.
 
virtual bool margin_check_allowed (const NativeMarginCheckPoint &) const
 Consulted at each kernel check point before anything is evaluated.
 
virtual std::optional< double > resolve_margin_call_units (const NativeMarginCallView &) const
 The kernel's own liquidation sizing, offered to the host before the reduction rests.
 
virtual void on_native_margin_call (const native_order::MarginCallEvent &)
 A kernel-issued liquidation that filled.
 
virtual std::optional< double > resolve_anchored_level (const NativeAnchoredLevelView &) const
 The level an anchored leg (FromOwnerFill) is about to be armed at, offered to the host exactly once per materialization, before the ArmedEvent is built.
 
virtual bool owns_lot_excursions () const noexcept
 RULING A48 — the ONE generic per-lot excursion capability.
 
virtual ClosedLotExcursion closed_lot_excursion (const ClosedLotExcursionFacts &) const
 The per-lot excursion a host owns, consulted for every closing row once owns_lot_excursions() answers true.
 
void declare_native_bar_open_hook (bool implemented)
 Which of two optional hooks this host implements (R5 lane D2-A).
 
void declare_native_precommit_hook (bool implemented)
 declare_native_precommit_hook(false): validate_execution_precommit is the default admission, so the kernel does not consult it, and builds the settlement preview it would have been shown (prepare, then project) only for a host that owns lot excursions, whose closed_lot_excursion every closing row of that preview consults.
 
std::optional< Bar > current_partial_bar () const
 The bar so far, folded from the path points this script bar has already consumed: open of its first point, running high/low, close at the last point consumed.
 
std::uint64_t native_recalculation_count () const
 How many recalculations the kernel has driven this run, and how many it suppressed because a point had already spent its max_recalculations_per_point budget.
 
std::uint64_t native_recalculations_skipped () const
 How many recalculations max_recalculations_per_point dropped at their matching point.
 
std::optional< NativeCurrentPointView > current_execution_point () const
 The active callback's quote and calendar-derived decision context, as an owning value.
 
std::optional< NativeTrailState > trail_state (const native_order::RequestHandle &target) const
 Where one live trail's own trigger has reached: activated, the running best, the current level and the ordinal it activated at.
 
NativeCurrentExecutionPreview inspect_current_execution (const NativeCurrentExecution &) const
 A read-only preview of a current execution: the settlement readiness, any typed refusal or terms outcome, and the ordered closed-row P&L for an Applied-ready command.
 
NativeCurrentExecutionResult execute_current (const NativeCurrentExecution &)
 Consume, synchronously, a request accepted or replaced in this very callback.
 
bool mark_native_report_point (int64_t report_ts)
 Append one kernel-owned equity point at this host's report mark.
 
std::optional< Bar > native_series_bar (std::size_t subscription) const
 The latest completed bucket delivered for a declared subscription, or nullopt before its first delivery / for an unknown index.
 
bool declare_timeframe_subscriptions (std::vector< NativeTimeframeSubscription > subscriptions)
 Declare this run's higher-timeframe series from inside on_native_run_begin, for a host whose series are known only to its own begin-time registration.
 
NativeSetupResult declare_timeframe_subscriptions_result (std::vector< NativeTimeframeSubscription > subscriptions)
 The same call, answered the way configure_native answers the identical validation: Applied, or Failed with the first error field validate_native_timeframe_subscriptions found.
 
bool declare_auxiliary_feed (std::optional< NativeAuxiliaryFeed > feed)
 The same begin-time hook for NativeRunSpec::auxiliary_feed: the feed REPLACES the staged spec's own (nullopt withdraws it), and the kernel registers from the staged spec after on_native_run_begin returns.
 
NativeSetupResult declare_auxiliary_feed_result (std::optional< NativeAuxiliaryFeed > feed)
 The same call, answered the way configure_native answers the identical validation: Applied, or Failed with the first error field the judged feed-and-series pair produced (AuxiliaryFeedNotFinerThanInput for a feed the input refuses, SubscriptionWithoutAuxiliaryFeed for a withdrawal that would strand a staged series).
 
bool append_auxiliary_bars (const Bar *bars, std::size_t n)
 A realtime stream's later bars of its declared auxiliary feed.
 
NativeAuxiliaryAppendResult append_auxiliary_bars_result (const Bar *bars, std::size_t n)
 The same call, answering NativeAuxiliaryAppendError and the bar of this call it stopped on.
 
NativeSetupResult configure_native (const NativeRunSpec &spec)
 The only setup call.
 
NativeFxCurveSetupResult configure_native_fx_curve (const NativeFxCurve &curve)
 Stage the run's immutable FX epoch, legal only while Ready.
 
NativeStateView native_state () const
 The whole run state as one owning read.
 
native_order::SubmitResult submit (const native_order::Request &request)
 Accept one complete request.
 
native_order::ReplaceResult replace (const native_order::RequestHandle &target, const native_order::Request &request)
 Replace one live request: validate first, then retire that incarnation and birth a successor with a new handle, a new priority and a predecessor link.
 
native_order::SubmitResult submit_market (const native_order::Request &request)
 The deliberately narrow market-default convenience: the same acceptance path as submit, but it REFUSES a nondefault trigger, capacity, owner or group rather than dropping it.
 
native_order::ReplaceResult replace_market (const native_order::RequestHandle &target, const native_order::Request &request)
 The same market-default convenience for a replace; see submit_market.
 
native_order::ReplaceResult replace (const native_order::RequestHandle &target, const native_order::Request &request, native_order::ReplaceOptions options)
 Replace with options.
 
native_order::CancelResult cancel (const native_order::RequestHandle &target)
 Cancel one live request by handle.
 
std::vector< NativeWorkingRequest > native_working_requests () const
 Working-book snapshot and bulk cancellation.
 
std::size_t cancel_all ()
 Withdraw every live request, dependants of a cancelled owner included, and answer how many left the book.
 
std::size_t cancel_where (std::string_view comment)
 Withdraw exactly the live requests carrying this comment, and answer how many of those left the book.
 
std::size_t cancel_where (std::string_view text, NativeRequestField field)
 The same predicate over either identity text.
 
native_order::CohortHandle cohort_open ()
 Open a roster a later close can bind to.
 
void cohort_add (native_order::CohortHandle cohort, native_order::RequestHandle origin)
 Enroll one accepted opening's handle in a roster.
 
void cohort_remove (native_order::CohortHandle cohort, native_order::RequestHandle origin)
 Take one opening back off a roster.
 
NativePhysicalPosition physical_position () const
 The book as one aggregate, copied out.
 
std::vector< NativeOpenLot > native_open_lots (double mark) const
 The book lot by lot, oldest first, marked at mark: one NativeOpenLot per physical lot (physical_position().lot_count rows), copied at query time.
 
double native_marked_equity (double mark) const
 The account's equity marked at this price: the realized balance plus every open lot's own fee-net term, which is exactly what native_open_lots(mark) sums.
 
std::optional< double > native_sized_units (const native_order::Sized &sized, double price, double equity, double fx) const
 The units a kernel-sized intent resolves to under this run's spec at a sizing price, a marked equity and an account FX rate – as a pure query.
 
std::optional< double > native_liquidation_price () const
 The price at which the marked equity falls below the run's maintenance requirement for the live position's side.
 
bool native_aggregates_input_bars () const
 Whether the configured run's script bars are buckets the kernel gathers from its input bars – native_calendar::pairing_aggregates of the pairing it resolved for the spec's input and script timeframes – rather than the input bars themselves.
 
NativeRiskState native_risk_state () const
 The run's generic risk ledger.
 
std::vector< NativeMarketEvent > native_events (uint64_t after_ordinal) const
 Owning snapshots copied at query time.
 
void native_acknowledge_events (uint64_t through_ordinal)
 The host has read every event through through_ordinal (R5 lane V19-B).
 
uint64_t native_event_window_start () const
 The oldest ordinal a read can still return: every command event at or above it is retained, and native_events(after) for an after below it starts here, the events before it having been dropped by the window.
 
int64_t native_decision_floor () const
 The run's monotonic decision floor in epoch milliseconds — the same value NativeStateView::decision_floor_ms carries.
 
uint64_t native_consumed_high_water () const
 The highest run_number this host has consumed.
 
uint64_t native_continuation_hash () const
 The consumer's continuation identity: what a stream resumes against.
 
void native_closed_rows_amended (std::size_t first_row)
 The closed rows (the engine's trades_) are part of broker_state_hash(), folded once each through a running digest (pineforge-broker-state/v19).
 
- Public Member Functions inherited from pineforge::engine_script_run_v19::BacktestEngine
virtual ~BacktestEngine ()
 
int execution_contract () const
 
bool native_bound () const
 
void run (const Bar *bars, int n)
 
void run (const Bar *input_bars, int n_input, const std::string &input_tf, const std::string &script_tf, bool bar_magnifier=false, int magnifier_samples=4, MagnifierDistribution magnifier_dist=MagnifierDistribution::ENDPOINTS)
 
virtual bool set_aux_security_feed (const Bar *bars, int n, const std::string &input_tf)
 
bool set_native_security_feed (const std::string &timeframe, const Bar *bars, int n)
 
bool native_security_feed_enabled () const
 
int64_t native_security_substitutions () const
 
int64_t native_security_misses () const
 
bool chart_day_partition_installed () const
 
virtual bool set_symbol_feed (const std::string &key, const std::string &timeframe, const Bar *bars, const int64_t *close_ms, int n)
 
virtual bool set_symbol_feed_column (const std::string &key, const std::string &timeframe, const std::string &name, const double *values, int n)
 
virtual bool set_symbol_facts (const std::string &key, const std::string &field, const std::string &value)
 
virtual bool set_recorded_series (const std::string &key, const int64_t *chart_open_ms, const double *values, int n)
 
bool stream_begin (const Bar *warmup_bars, int n_warmup, const std::string &input_tf, const std::string &script_tf="")
 
bool stream_push_bar (const Bar &bar)
 
bool stream_push_tick (const TradeTick &tick)
 
bool stream_push_ticks (const TradeTick *ticks, int n)
 
bool stream_advance_time (int64_t timestamp_ms)
 
bool stream_end (bool finalize_partial_input_bar=false)
 
bool stream_is_realtime () const
 
int stream_order_actions_len () const
 
const StreamOrderAction & stream_order_action_at (int i) const
 
void stream_order_actions_clear ()
 
uint64_t stream_state_hash () const
 
bool set_account_currency_fx_series (const int64_t *timestamps_ms, const double *rates, int n)
 
void run (const Bar *input_bars, int n_input, const std::string &input_tf, const std::string &script_tf, const std::unordered_map< std::string, std::string > &inputs, const SymInfo &syminfo, const void *overrides=nullptr, bool bar_magnifier=false, int magnifier_samples=4, MagnifierDistribution magnifier_dist=MagnifierDistribution::ENDPOINTS)
 
int trade_count () const
 
const Trade & get_trade (int i) const
 
std::size_t closed_trade_count () const noexcept
 
const Trade & closed_trade (std::size_t i) const
 
int report_trade_count () const
 
const Trade & get_report_trade (int i) const
 
int closed_trade_close_cause (int i) const
 
double max_contracts_held_all () const
 
double max_contracts_held_long () const
 
double max_contracts_held_short () const
 
int eventrades () const
 
void fill_report (ReportC *out) const
 
const std::string & last_error () const
 
void set_input (const std::string &key, const std::string &value)
 
void clear_inputs ()
 
void set_trade_start_time (int64_t timestamp_ms)
 
void set_chart_timezone (const std::string &tz)
 
const std::string & chart_timezone () const
 
void set_syminfo_timezone (const std::string &tz)
 
void set_syminfo_session (const std::string &s)
 
void set_syminfo_type (const std::string &t)
 
bool session_template_knows_early_close () const
 Whether TradingView's session template for this symbol carries the exchange's early closes and holidays, so a D/W/M request.security bucket completes on a shortened session's actual last chart bar (TimeframeAggregator::set_early_close_completes): exchange-listed kinds (stock, futures, index, fund, dr, ...) yes – NYSE:F's 12:45 ET half-day bar and CME's 11:45 CT early-close bar are pinned; the OTC quote streams – forex, cfd, crypto – no: their period ends at the nominal close and a session ending early completes lazily on the next period's first bar (OANDA:XAUUSD 15m, lab tv oanda pin, ledger log-20260905t034240z-30be11fe).
 
bool set_syminfo_string (const std::string &key, const std::string &value)
 
void set_syminfo_mintick (double m)
 
void set_syminfo_pointvalue (double pv)
 
virtual void set_syminfo_metadata (const std::string &key, double value)
 
const std::string & main_period () const
 
virtual bool set_realtime_tail (bool on, int horizon_bars)
 
virtual bool set_probe_suppress_tail_logic (bool on)
 
void set_path_order (int mode)
 
uint64_t broker_state_hash () const
 
double position_avg_price () const
 
int64_t position_cycle_seq () const
 
double trail_best_price () const
 
virtual double live_position_size () const
 
virtual int observe_last_bar_dual_entry_path_v1 () const
 
virtual int observe_pending_count_v1 () const
 
virtual int observe_pending_copy_v1 (int index, pf_pending_order_v1_t *out) const
 
virtual int observe_probe_fill_qty (int index, double fill_price, double *qty, int *close_only, int *partition) const
 
virtual int observe_pending_level_resolved (int index) const
 
virtual int observe_pending_effective_levels (int index, double *stop, double *limit, double *trail_activation) const
 
virtual double observe_trail_best_price_v1 () const
 
double live_current_equity () const
 
int64_t script_bars_processed () const
 
void set_broker_state_hash_recording (bool on)
 
void set_magnifier_volume_weighted (bool on)
 
void set_trace_enabled (bool on)
 
bool trace_enabled () const
 
int last_run_status () const
 
void request_abort ()
 
void trace (const std::string &name, double value)
 
void trace (const std::string &name, bool value)
 
void trace (const std::string &name, int value)
 
bool outputs_declared () const
 
bool set_outputs_enabled (bool on)
 
int output_series_count () const
 
int64_t output_bars_len () const
 
bool output_bar_times_copy (int64_t from_bar, int64_t *open_ms, int64_t *close_ms, int64_t capacity, int64_t *written) const
 
bool output_series_copy (int slot, int64_t from_bar, double *out, int64_t capacity, int64_t *written) const
 
int output_events_len () const
 
const OutputEvent * output_event_at (int index) const
 
void output_events_clear ()
 
int output_constants_count () const
 
double output_constant_value (int index) const
 

Protected Member Functions

std::uint64_t broker_state_hash_projection () const override
 
- Protected Member Functions inherited from pineforge::engine_script_run_v19::BacktestEngine
 BacktestEngine (NativeConsumerBindTag)
 
IExecutionConsumer & execution_consumer ()
 
const IExecutionConsumer & execution_consumer () const
 
virtual void hash_host_extension (BrokerStateHashSink &) const
 
virtual void hash_source_extension (BrokerStateHashSink &) const
 
std::uint64_t broker_state_hash_from_execution_hash (std::uint64_t) const
 
double get_input_double (const std::string &key, double default_val) const
 
int get_input_int (const std::string &key, int default_val) const
 
int64_t get_input_int64 (const std::string &key, int64_t default_val) const
 
bool get_input_bool (const std::string &key, bool default_val) const
 
std::string get_input_string (const std::string &key, const std::string &default_val) const
 
double get_syminfo_metadata (const std::string &key) const
 
void declare_opened_lot_entry_bar_mask (uint64_t entry_incarnation, const Bar &entry_bar, OpenedLotFillPoint fill_point)
 
execution::Result settle_native_execution_at (const execution::Action &action, const execution::Fill &fill, const execution::PhysicalExecutionContext &context)
 
execution::Result settle_with_context (const execution::Action &action, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::PhysicalExecutionContext &context)
 
execution::SettlementInspection inspect_native_settlement (const execution::Action &action, const execution::Fill &fill) const
 
execution::SettlementInspection inspect_native_settlement_scoped (const execution::Action &action, const execution::Fill &fill, execution::CloseScope scope) const
 
execution::SettlementInspection inspect_native_settlement_scoped_at (const execution::Action &action, const execution::Fill &fill, execution::CloseScope scope, double fx) const
 
execution::Result settle_native_execution_scoped_at (const execution::Action &action, const execution::Fill &fill, const execution::PhysicalExecutionContext &context, execution::CloseScope scope)
 
execution::SettlementInspection inspect_native_settlement_selected (const execution::Action &action, const execution::Fill &fill, const execution::SelectedOpeningSet &selection) const
 
execution::SettlementInspection inspect_native_settlement_selected_at (const execution::Action &action, const execution::Fill &fill, const execution::SelectedOpeningSet &selection, double fx) const
 
execution::Result settle_native_execution_selected_at (const execution::Action &action, const execution::Fill &fill, const execution::PhysicalExecutionContext &context, const execution::SelectedOpeningSet &selection)
 
execution::Result settle_execution_selected_with_lifecycle (const execution::Action &action, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::SelectedOpeningSet &selection)
 
execution::AccountEffectProjection project_native_settlement_v1 (const execution::Action &action, const execution::Fill &fill) const
 
execution::AccountEffectProjection project_native_settlement_at (const execution::Action &action, const execution::Fill &fill, double fx) const
 
execution::AccountEffectProjection project_native_settlement_scoped_v1 (const execution::Action &action, const execution::Fill &fill, execution::CloseScope scope) const
 
execution::AccountEffectProjection project_native_settlement_selected_v1 (const execution::Action &action, const execution::Fill &fill, const execution::SelectedOpeningSet &selection) const
 
execution::SettlementInspection inspect_native_reversal_v1 (const execution::ReverseTo &reversal, const execution::Fill &fill) const
 
execution::SettlementInspection inspect_native_reversal_at (const execution::ReverseTo &reversal, const execution::Fill &fill, double fx) const
 
execution::AccountEffectProjection project_native_reversal_v1 (const execution::ReverseTo &reversal, const execution::Fill &fill) const
 
execution::Result settle_native_reversal_at_v1 (const execution::ReverseTo &reversal, const execution::Fill &fill, const execution::PhysicalExecutionContext &context)
 
execution::Result settle_reversal_with_lifecycle_v1 (const execution::ReverseTo &reversal, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle)
 
double marked_equity (double price) const
 
double marked_equity_at (double price, double fx) const
 
double round_to_mintick (double price) const
 
double bar_fill_price (double raw_bar_price) const
 
double tick_grid_price (double price) const
 
int price_grid_decimals () const
 
double level_on_price_grid (double level) const
 
double calc_commission (double fill_price, double qty) const
 
double calc_commission_at (double fill_price, double qty, double fx) const
 
double open_entry_commission (const PyramidEntry &pe) const
 
double allocated_entry_commission (const PyramidEntry &pe, double units) const
 
void snapshot_entry_commission (PyramidEntry &pe) const
 
double apply_qty_step (double qty) const
 
double apply_exit_qty_step (double qty) const
 
double net_profit () const
 
double gross_profit () const
 
double gross_loss () const
 
double current_equity () const
 
double max_runup_percent () const
 
double grossprofit_percent () const
 
double grossloss_percent () const
 
double avg_trade () const
 
double avg_trade_percent () const
 
double avg_winning_trade () const
 
double avg_losing_trade () const
 
double avg_winning_trade_percent () const
 
double avg_losing_trade_percent () const
 
double open_trades_capital_held () const
 
double open_profit (double current_price) const
 
double open_profit_at (double current_price, double fx) const
 
int count_wintrades () const
 
int count_losstrades () const
 
BarTime _decompose_bar_time () const
 
int _bar_hour () const
 
int _bar_minute () const
 
int _bar_second () const
 
int _bar_dayofmonth () const
 
int _bar_dayofweek () const
 
int _bar_month () const
 
int _bar_year () const
 
int _bar_weekofyear () const
 
void check_abort ()
 
int32_t intern_trace_name (const std::string &name)
 
void register_security_eval (int sec_id, const std::string &requested_tf, const std::string &input_tf)
 
void dispatch_security_eval (SecurityEvalState &state, const Bar &bar, bool publish, int64_t bar_index)
 
void feed_security_eval_state (SecurityEvalState &state, const Bar &input_bar)
 
virtual void prepare_script_run (const Bar *, int, bool)
 
virtual void configure_security_evaluators ()
 
virtual void evaluate_security (int sec_id, const Bar &bar, bool is_complete)
 
virtual void clear_security (int sec_id)
 
virtual void snapshot_script_state ()
 
virtual void restore_script_state ()
 
virtual void commit_script_state ()
 
virtual void finalize_bar ()
 
void fold_equity_extreme (double eq)
 
void update_equity_extremes ()
 
void record_equity_point (int64_t script_bar_ts)
 
double closed_trade_profit (int index) const
 
double closed_trade_profit_percent (int idx) const
 
double closed_trade_commission (int idx) const
 
int closed_trade_entry_bar_index (int idx) const
 
int closed_trade_exit_bar_index (int idx) const
 
std::string closed_trade_entry_comment (int idx) const
 
std::string closed_trade_exit_comment (int idx) const
 
std::string closed_trade_entry_id (int idx) const
 
std::string closed_trade_exit_id (int idx) const
 
uint64_t closed_trade_entry_incarnation (int idx) const
 
double closed_trade_entry_price (int idx) const
 
double closed_trade_exit_price (int idx) const
 
int64_t closed_trade_entry_time (int idx) const
 
int64_t closed_trade_exit_time (int idx) const
 
double closed_trade_size (int idx) const
 
double closed_trade_max_runup (int idx) const
 
double closed_trade_max_runup_percent (int idx) const
 
double closed_trade_max_drawdown (int idx) const
 
double closed_trade_max_drawdown_percent (int idx) const
 
std::string closed_trade_direction (int idx) const
 
std::string open_trade_direction (int idx) const
 
double open_trade_profit (int idx) const
 
double open_trade_profit_percent (int idx) const
 
double open_trade_commission (int idx) const
 
int open_trade_entry_bar_index (int idx) const
 
std::string open_trade_entry_comment (int idx) const
 
std::string open_trade_entry_id (int idx) const
 
double open_trade_entry_price (int idx) const
 
int64_t open_trade_entry_time (int idx) const
 
double open_trade_size (int idx) const
 
double open_trade_max_drawdown (int idx) const
 
double open_trade_max_drawdown_percent (int idx) const
 
double open_trade_max_runup (int idx) const
 
double open_trade_max_runup_percent (int idx) const
 
std::string position_entry_name () const
 
double max_drawdown_percent () const
 
execution::Result settle_with_context_scoped (const execution::Action &action, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::PhysicalExecutionContext &context, execution::CloseScope scope)
 
execution::Result settle_with_context_selected (const execution::Action &action, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::PhysicalExecutionContext &context, const execution::SelectedOpeningSet &selection)
 
execution::AccountEffectProjection project_with_membership (const execution::Action &action, const execution::Fill &fill, execution::CloseScope book_or_opening, const execution::SelectedOpeningSet *selected, double fx) const
 
execution::SettlementInspection inspect_with_membership (const execution::Action &action, const execution::Fill &fill, execution::CloseScope book_or_opening, const execution::SelectedOpeningSet *selected, double fx) const
 
execution::Result settle_with_membership (const execution::Action &action, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::PhysicalExecutionContext &context, execution::CloseScope book_or_opening, const execution::SelectedOpeningSet *selected)
 
execution::Status preview_native_settlement_commit (const execution::Action &action, const execution::Fill &fill, const execution::PhysicalExecutionContext &context, execution::CloseScope scope, const execution::SelectedOpeningSet *selected, execution::AccountEffectProjection &account, std::vector< double > &row_pnl) const
 
execution::Status preview_native_settlement_commit (const execution::ReverseTo &reversal, const execution::Fill &fill, const execution::PhysicalExecutionContext &context, execution::AccountEffectProjection &account, std::vector< double > &row_pnl) const
 
execution::Status validate_native_settlement_book (double &held) const
 
execution::Status allocate_native_settlement_closes (NativeSettlementStage &stage, const execution::CloseScope &book_or_opening, double &remaining) const
 
void finish_native_settlement_stage (NativeSettlementStage &stage, const execution::Fill &fill) const
 
execution::SettlementInspection inspect_native_settlement_stage (const NativeSettlementStage &stage, const execution::Fill &fill) const
 
execution::AccountEffectProjection project_native_settlement_stage (const NativeSettlementStage &stage, const execution::Fill &fill) const
 
execution::Result commit_native_settlement_stage (NativeSettlementStage &stage, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::PhysicalExecutionContext &context)
 
void build_native_settlement_close_rows (const NativeSettlementStage &stage, const execution::Fill &fill, const execution::PhysicalExecutionContext &context, NativeSettlementRows &rows) const
 
execution::Status prepare_native_settlement_commit (const NativeSettlementStage &stage, const execution::Fill &fill, const execution::PhysicalExecutionContext &context, NativeSettlementRows &rows) const
 
execution::Status preflight_native_settlement_effects (const NativeSettlementStage &stage, const execution::LifecycleEffects &lifecycle, const NativeSettlementRows &rows)
 
execution::Result commit_prepared_native_settlement_stage (NativeSettlementStage &stage, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::PhysicalExecutionContext &context, NativeSettlementRows &rows)
 
execution::Result settle_source_staged_execution (NativeSettlementStage &stage, const execution::Fill &fill, const execution::LifecycleEffects &lifecycle, const execution::PhysicalExecutionContext &context)
 
void stage_native_settlement (NativeSettlementStage &stage, const execution::Action &action, const execution::Fill &fill, execution::CloseScope book_or_opening, const execution::SelectedOpeningSet *selected, const execution::LifecycleEffects *lifecycle, double fx) const
 
void stage_native_settlement (NativeSettlementStage &stage, const execution::ReverseTo &reversal, const execution::Fill &fill, const execution::LifecycleEffects *lifecycle, double fx) const
 
void append_quoted_lot (PyramidEntry lot, double total_qty, double average_price)
 
void open_quoted_position (PositionSide requested, PyramidEntry lot)
 
void record_close_trade (Trade trade)
 
void validate_close_trade_counters (const Trade *rows, size_t count) const
 
std::vector< double > quote_execution_commissions (const std::vector< double > &closed_units, double opening_units, const execution::Fill &fill, double fx) const
 
Trade build_close_trade_with_costs (const PyramidEntry &pe, double close_qty, double fill_price, bool was_long, double entry_commission, double exit_commission, const execution::PhysicalExecutionContext &context) const
 
void reset_position_state_to_flat ()
 
void reset_run_state ()
 
double account_currency_fx_at (int64_t timestamp_ms) const
 
double active_account_currency_fx () const
 
void prepare_native_security_feeds (const Bar *input_bars, int n_input)
 
void prepare_chart_day_partition (const Bar *input_bars, int n_input)
 
bool substitute_native_security_bar (SecurityEvalState &state, Bar &bar, bool count_miss=true)
 
virtual bool source_aux_security_feed_enabled () const
 
virtual void source_aux_security_input_view (const Bar *&bars, int &n) const
 
bool aux_security_feed_enabled () const
 
void stream_observe_entry (const PyramidEntry &pe)
 
virtual void source_stream_entry_comment (const PyramidEntry &, std::string &) const
 
void stream_observe_exit (size_t trade_index)
 
void stream_refresh_action_metadata (size_t first_action, size_t first_trade)
 
void fill_trades_section (ReportC *out) const
 
virtual void present_report (ReportC *) const
 
void fill_metrics_section (ReportC *out) const
 
void fill_security_diag_section (ReportC *out) const
 
void fill_trace_section (ReportC *out) const
 
void guard_native_mutation (const char *operation)
 
void declare_outputs (int series_slots, int outputs, int run_constants=0)
 
void output_run_begin ()
 
void output_bar (int64_t open_ms, int64_t close_ms)
 
void output_value (int slot, double value)
 
void output_event (int output, double value)
 
void output_event (int output, double value, const std::string &message)
 
void output_constant (int index, double value)
 

Additional Inherited Members

- Static Public Member Functions inherited from pineforge::engine_script_run_v19::BacktestEngine
static void free_report (ReportC *report)
 
- Protected Types inherited from pineforge::engine_script_run_v19::BacktestEngine
enum class  StreamPhase {
  IDLE ,
  REALTIME ,
  ENDED
}
 
enum class  StreamInputMode {
  UNSET ,
  TICKS ,
  BARS
}
 
- Protected Attributes inherited from pineforge::engine_script_run_v19::BacktestEngine
PositionSide position_side_ = PositionSide::FLAT
 
double position_entry_price_ = 0.0
 
broker::OpeningObligations opening_obligations_
 
int64_t position_entry_time_ = 0
 
double position_qty_ = 0.0
 
int position_entry_count_ = 0
 
int position_open_bar_ = -1
 
int64_t position_cycle_seq_ = 0
 
int64_t next_position_cycle_seq_ = 1
 
std::vector< PyramidEntry > pyramid_entries_
 
double initial_capital_ = 1000000.0
 
CommissionType commission_type_ = CommissionType::PERCENT
 
double commission_value_ = 0.0
 
int slippage_ = 0
 
double syminfo_mintick_ = 0.01
 
double qty_step_ = 0.0
 
double account_currency_fx_ = 1.0
 
std::vector< int64_t > account_currency_fx_timestamps_
 
std::vector< double > account_currency_fx_rates_
 
bool account_currency_fx_broker_epoch_initialized_ = false
 
std::size_t account_currency_fx_broker_epoch_ = 0
 
double account_currency_fx_broker_rate_ = 1.0
 
int64_t trade_start_time_ = std::numeric_limits<int64_t>::min()
 
SymInfo syminfo_
 
int64_t last_bar_time_ = 0
 
int last_bar_index_ = 0
 
int path_order_mode_ = 0
 
bool is_tail_bar_ = false
 
std::string chart_timezone_
 
std::unordered_map< std::string, std::string > inputs_
 
std::unordered_map< std::string, double > syminfo_metadata_
 
Bar current_bar_
 
int bar_index_ = 0
 
int64_t security_next_input_ms_ = 0
 
uint64_t next_order_incarnation_ = 1
 
double fold_exit_trail_peak_ = std::numeric_limits<double>::quiet_NaN()
 
std::vector< Trade > trades_
 
std::vector< Trade > range_end_trades_
 
double trail_best_price_ = std::numeric_limits<double>::quiet_NaN()
 
broker::PositionCloseObligation position_close_obligation_
 
double net_profit_sum_ = 0.0
 
double net_profit_roundoff_bound_ = 0.0
 
double net_profit_roundoff_value_ = 0.0
 
double gross_profit_sum_ = 0.0
 
double gross_loss_sum_ = 0.0
 
int win_trades_count_ = 0
 
int loss_trades_count_ = 0
 
double max_equity_ = 0.0
 
double max_drawdown_ = 0.0
 
double max_runup_ = 0.0
 
double min_equity_ = 0.0
 
std::vector< pf_equity_point_t > equity_curve_
 
int64_t bars_in_market_ = 0
 
double first_bar_open_ = std::numeric_limits<double>::quiet_NaN()
 
bool broker_state_hash_recording_ = false
 
std::vector< uint64_t > broker_state_hashes_
 
double max_contracts_held_all_ = 0.0
 
double max_contracts_held_long_ = 0.0
 
double max_contracts_held_short_ = 0.0
 
int eventrades_count_ = 0
 
LotExcursionHook lot_excursion_hook_
 
uint64_t last_script_continuation_hash_ = 0
 
bool last_script_continuation_valid_ = false
 
int64_t bar_time_memo_ts_ = std::numeric_limits<int64_t>::min()
 
BarTime bar_time_memo_ {}
 
bool bar_magnifier_enabled_ = false
 
bool barstate_islast_ = false
 
int magnifier_samples_ = 4
 
MagnifierDistribution magnifier_dist_ = MagnifierDistribution::ENDPOINTS
 
bool magnifier_volume_weighted_ = false
 
uint64_t broker_fill_event_seq_ = 0
 
std::string input_tf_
 
std::string script_tf_
 
int script_tf_seconds_ = 0
 
TimeframeAggregator script_tf_agg_
 
int64_t prev_bar_timestamp_ = 0
 
StreamPhase stream_phase_ = StreamPhase::IDLE
 
bool stream_warmup_mode_ = false
 
bool host_mutation_guard_inert_ = false
 
int64_t stream_input_tf_ms_ = 0
 
int64_t stream_next_input_open_ms_ = 0
 
int64_t stream_clock_ms_ = 0
 
int64_t stream_last_tick_ms_ = 0
 
uint64_t stream_last_sequence_ = 0
 
bool stream_seen_sequence_ = false
 
bool stream_has_input_bar_ = false
 
Bar stream_input_bar_ {}
 
double stream_last_price_ = 0.0
 
bool stream_has_last_price_ = false
 
int stream_next_script_bar_index_ = 0
 
bool stream_script_bar_had_tick_ = false
 
bool stream_script_tick_seen_ = false
 
StreamInputMode stream_input_mode_ = StreamInputMode::UNSET
 
bool stream_observe_actions_ = false
 
uint64_t stream_action_sequence_ = 0
 
std::vector< StreamOrderAction > stream_order_actions_
 
std::vector< SecurityEvalState > security_eval_states_
 
std::string security_input_tf_
 
std::vector< NativeSecurityFeed > native_security_feeds_
 
int64_t diag_native_security_substitutions_ = 0
 
int64_t diag_native_security_misses_ = 0
 
NativeDayPartition chart_day_partition_
 
bool trace_enabled_ = false
 
int last_run_status_ = 0
 
AbortFlag abort_requested_
 
std::vector< TraceEntryC > trace_buffer_
 
std::vector< std::string > trace_names_
 
std::unordered_map< std::string, int32_t > trace_name_index_
 
int64_t diag_input_bars_processed_ = 0
 
int64_t diag_script_bars_processed_ = 0
 
int64_t diag_magnifier_sub_bars_processed_ = 0
 
int64_t diag_magnifier_sample_ticks_processed_ = 0
 
int diag_script_tf_ratio_ = 0
 
bool diag_needs_aggregation_ = false
 
std::string last_error_
 
ExecutionConsumerSlot execution_consumer_slot_
 
bool outputs_enabled_ = false
 
- Static Protected Attributes inherited from pineforge::engine_script_run_v19::BacktestEngine
static constexpr double kLevelGridBandPoints = 0.01
 

Detailed Description

The public native host: an abstract subclass of BacktestEngine with no PineScript on it.

Subclass it, override on_native_bar (the only pure-virtual), configure_native(spec), then run() or the stream_* family. Noncopyable and nonmovable: the constructor binds the native consumer, and there is no attach/replace switch. Do not override the inherited on_bar (it is final) and do not write protected engine fields. The whole surface, feature by feature, is docs/pages/native-engine.md; a worked host is examples/native/hello_kernel.cpp.

Definition at line 845 of file native_host.hpp.

Constructor & Destructor Documentation

◆ NativeStrategyHost() [1/3]

pineforge::engine_script_run_v19::NativeStrategyHost::NativeStrategyHost ( )

◆ NativeStrategyHost() [2/3]

pineforge::engine_script_run_v19::NativeStrategyHost::NativeStrategyHost ( const NativeStrategyHost & )
delete

References NativeStrategyHost().

◆ NativeStrategyHost() [3/3]

pineforge::engine_script_run_v19::NativeStrategyHost::NativeStrategyHost ( NativeStrategyHost && )
delete

References NativeStrategyHost().

◆ ~NativeStrategyHost()

pineforge::engine_script_run_v19::NativeStrategyHost::~NativeStrategyHost ( )
override

Member Function Documentation

◆ operator=() [1/2]

NativeStrategyHost & pineforge::engine_script_run_v19::NativeStrategyHost::operator= ( const NativeStrategyHost & )
delete

References NativeStrategyHost().

◆ operator=() [2/2]

NativeStrategyHost & pineforge::engine_script_run_v19::NativeStrategyHost::operator= ( NativeStrategyHost && )
delete

References NativeStrategyHost().

◆ on_bar()

void pineforge::engine_script_run_v19::NativeStrategyHost::on_bar ( const Bar & bar)
finalvirtual

The engine's own bar entry, taken over by the native consumer and sealed.

A native host calculates in on_native_bar; this override is what makes overriding on_bar a compile error rather than a silently dead callback.

Implements pineforge::engine_script_run_v19::BacktestEngine.

◆ prepare_native_begin()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::prepare_native_begin ( const NativeBeginArgs & )
inlinevirtual

Offered once per begin, before the run starts, with the begin's own arguments — the bars, the timeframe literals, the magnifier settings, and the rich overload's InputsMap / SymInfo / opaque overrides.

A provider that reads them must copy what it needs before returning: the views expire with the call. The default does nothing, which is every bare host. No C spelling: a C run is declared up front with strategy_configure_native_ext_v1.

Definition at line 865 of file native_host.hpp.

◆ on_native_run_begin()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_run_begin ( )
inlinevirtual

Offered once per successful begin, after the reset and before any bar.

It is the one place declare_timeframe_subscriptions and declare_auxiliary_feed are legal, and the kernel registers the declared series only after it returns — so a host that registers evaluators of its own here keeps them. native_series_bar answers nullopt for every index inside it, because nothing is registered yet. C spelling: pf_native_callbacks_v1::on_run_begin.

Definition at line 872 of file native_host.hpp.

◆ on_native_input()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_input ( const Bar & ,
const NativeInputContext &  )
inlinevirtual

Called once for every accepted confirmed input bar, before that bar is aggregated or matched.

It has no current execution point.

Definition at line 875 of file native_host.hpp.

◆ on_native_tick()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_tick ( const Bar & ,
const NativeTickContext &  )
inlinevirtual

Called once for every accepted realtime print, before matching at that point.

inspect_current_execution/execute_current are legal here.

Definition at line 878 of file native_host.hpp.

◆ on_native_timeframe_bar()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_timeframe_bar ( const Bar & ,
const NativeTimeframeBarContext &  )
inlinevirtual

One completed bucket of a declared higher-timeframe subscription, delivered on an accepted input bar before that input is aggregated, matched or calculated.

Never called for a spec whose subscriptions are empty. native_series_bar() already answers with this bar here. A series built from the auxiliary feed may deliver several buckets on one input, oldest first.

Definition at line 885 of file native_host.hpp.

◆ on_native_bar_open()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_bar_open ( const Bar & ,
const NativeDecisionContext &  )
inlinevirtual

Precedes the matching pass at the script bar's open decision point.

inspect_current_execution/execute_current are legal in this hook. A host that has none says so: declare_native_bar_open_hook(false).

Definition at line 889 of file native_host.hpp.

◆ on_native_bar()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_bar ( const Bar & bar,
const NativeDecisionContext & context )
pure virtual

The current decision point remains valid for the complete callback.

A host may therefore execute a command after its own script-body work returns, before the consumer advances beyond this calculation point.

Referenced by on_native_recalculate().

◆ on_native_recalculate()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_recalculate ( const Bar & bar,
const NativeDecisionContext & ctx,
NativeCalculationReason reason,
const native_order::ExecutionAppliedEvent * cause )
inlinevirtual

EVERY calculation of the run arrives here first, including the script bar's own close calculation (reason BarClose, cause nullptr), whose default forwarding keeps on_native_bar the complete contract for a host that never opts into another cadence.

reason OrderFill: one recalculation at an applied execution's cursor, driven from the applied-notification drain after that event's on_native_applied and bounded by NativeRunSpec::max_recalculations_per_point. cause is that event and is valid only for this call. reason Tick: one recalculation at a modeled path point or an observed print, with a null cause.

bar is the bar the calculation is about: the script bar under delivery in batch, the print's value bar for a stream Tick. It is the COMPLETE script bar even mid-path; current_partial_bar() is the lookahead-free bar so far, through the last path point consumed (at an OrderFill inside a segment, the segment's origin). Commands and execute_current are legal here exactly as in on_native_applied.

Definition at line 913 of file native_host.hpp.

References on_native_bar().

◆ on_native_sub_bar()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_sub_bar ( const Bar & sub,
const NativeDecisionContext & ctx )
inlinevirtual

One completed lower-timeframe sub-bar of an IntrabarPath::lower_tf path, delivered after that sub-bar's whole matching path and before the next sub-bar's.

Never called for a run without a retained lower feed: a synthesized path and a plain confirmed bar have no sub-bars of their own. The decision point is the sub-bar's last modeled point, so commands and execute_current are legal and a request born here follows the ordinary birth rule.

Definition at line 928 of file native_host.hpp.

◆ on_native_applied()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_applied ( const native_order::ExecutionAppliedEvent & ,
const NativeDecisionContext &  )
inlinevirtual

The calculate-on-fill hook: offered once per applied execution, FIFO, after the account record and the group/owner/dependency drains.

Commands are legal here, and a request born here is eligible on the remaining path suffix of a continuous segment. Event values stay valid for the call. Throwing latches CallbackException. C spelling: pf_native_callbacks_v1::on_applied.

Definition at line 938 of file native_host.hpp.

◆ resolve_execution_terms()

virtual native_order::ExecutionTerms pineforge::engine_script_run_v19::NativeStrategyHost::resolve_execution_terms ( const NativeExecutionTermsFacts & facts) const
inlinevirtual

The fill-terms hook, consulted at every matching candidate.

Return a resolved price, and units for an unresolved HostSized request; the default is the identity price with no units, which is what every bare host wants. Answering no units for a HostSized candidate is MatchRejectReason::TermsUnresolved. It does not supply a second matcher, book or cash path. C spelling: on_execution_terms (price, shape, grid) and on_close_units (a host-sized close's units only).

Definition at line 947 of file native_host.hpp.

References pineforge::engine_script_run_v19::NativeExecutionTermsFacts::default_resolved_price.

◆ validate_execution_precommit()

virtual NativePrecommitVerdict pineforge::engine_script_run_v19::NativeStrategyHost::validate_execution_precommit ( const NativePrecommitView & ) const
inlinevirtual

The last gate before a physical effect, offered once per Applied-ready attempt and never during inspect_current_execution.

Proceed takes the kernel's own path, Refuse records a nonfinancial HostPrecommit rejection, and AdmitWithHostMargin hands that one opening margin check to the host. The default proceeds; a host that keeps it says so: declare_native_precommit_hook(false). C spelling: pf_native_callbacks_v1::on_precommit, the view flattened into pf_native_precommit_view_v1.

Definition at line 960 of file native_host.hpp.

References pineforge::engine_script_run_v19::Admit.

◆ resolve_margin_requirement()

virtual std::optional< NativeMarginDecision > pineforge::engine_script_run_v19::NativeStrategyHost::resolve_margin_requirement ( const NativeMarginRequirementView & ) const
inlinevirtual

Consulted at EVERY kernel check point, BEFORE the breach test, exactly as resolve_execution_terms is consulted before a fill is booked.

The kernel still owns the mechanism – the level solve, the check points, the kernel-originated request, its Superseded re-pricing, the receipt and on_native_margin_call; this hook only supplies the two numbers that comparison is made of, where brokers legitimately differ. nullopt keeps the kernel's own. A host may therefore raise a call the kernel would not make (a rounded requirement, a fee-adjusted equity, force_breach) or veto one it would (answer numbers that do not breach). Source- language money quirks – TradingView's ten-significant-digit rounding, for one – belong in this hook, never in the run spec.

Definition at line 976 of file native_host.hpp.

◆ margin_check_allowed()

virtual bool pineforge::engine_script_run_v19::NativeStrategyHost::margin_check_allowed ( const NativeMarginCheckPoint & ) const
inlinevirtual

Consulted at each kernel check point before anything is evaluated.

A host whose broker model does not check there answers false, and the kernel does not evaluate, re-arm or withdraw at that point: the margin state is left exactly as the last admitted check point left it. Every point the run's check mode reaches is offered, including the ones where the book is flat or the live side has no maintenance fraction – withdrawing a resting liquidation is part of the check. CalculationOnly rests nothing, so it offers only the points it could act on.

Definition at line 988 of file native_host.hpp.

◆ resolve_margin_call_units()

virtual std::optional< double > pineforge::engine_script_run_v19::NativeStrategyHost::resolve_margin_call_units ( const NativeMarginCallView & ) const
inlinevirtual

The kernel's own liquidation sizing, offered to the host before the reduction rests.

Returning nullopt keeps the run spec's sizing policy; a returned value is clamped into (0, held] and wins over it. It keeps the last word on units, including over a forced breach.

Definition at line 995 of file native_host.hpp.

◆ on_native_margin_call()

virtual void pineforge::engine_script_run_v19::NativeStrategyHost::on_native_margin_call ( const native_order::MarginCallEvent & )
inlinevirtual

A kernel-issued liquidation that filled.

It is delivered after the ordinary on_native_applied for the same fill, with the same cursor.

Definition at line 1001 of file native_host.hpp.

◆ resolve_anchored_level()

virtual std::optional< double > pineforge::engine_script_run_v19::NativeStrategyHost::resolve_anchored_level ( const NativeAnchoredLevelView & ) const
inlinevirtual

The level an anchored leg (FromOwnerFill) is about to be armed at, offered to the host exactly once per materialization, before the ArmedEvent is built.

Returning nullopt installs the kernel level (fill + offset after the anchor's rounding); a returned value is the level to install, still subject to the kernel's representability check, whose failure is the existing PreparationError path. The mechanism (the arm, the once-only materialization, the ArmedEvent, matching) stays the kernel's; only the policy of where the level sits is the host's, exactly as resolve_execution_terms owns the fill price.

Definition at line 1012 of file native_host.hpp.

◆ owns_lot_excursions()

virtual bool pineforge::engine_script_run_v19::NativeStrategyHost::owns_lot_excursions ( ) const
inlinevirtualnoexcept

RULING A48 — the ONE generic per-lot excursion capability.

A host that returns true here takes ownership of every open lot's favorable/adverse excursion: the consumer stops sampling excursion at matched trigger prices and the closing row takes both magnitudes from closed_lot_excursion(). Facts in, magnitudes out; nothing about the host's price model crosses the boundary in either direction.

Definition at line 1023 of file native_host.hpp.

◆ closed_lot_excursion()

virtual ClosedLotExcursion pineforge::engine_script_run_v19::NativeStrategyHost::closed_lot_excursion ( const ClosedLotExcursionFacts & ) const
inlinevirtual

The per-lot excursion a host owns, consulted for every closing row once owns_lot_excursions() answers true.

Returning the declined value gives that row the kernel's own zero magnitudes, because nothing was sampled for it — the consumer stops sampling at matched trigger prices for the whole run as soon as ownership is declared. C spelling: pf_native_callbacks_v1::on_lot_excursion, where installing the hook IS declaring ownership.

Definition at line 1030 of file native_host.hpp.

◆ declare_native_bar_open_hook()

void pineforge::engine_script_run_v19::NativeStrategyHost::declare_native_bar_open_hook ( bool implemented)

Which of two optional hooks this host implements (R5 lane D2-A).

A host that declares nothing implements both, which is every host written before the declarations existed; a declaration stands, across runs, until the host makes another. Neither moves a value: each lets the kernel skip work whose only reader is a hook the host does not have.

declare_native_bar_open_hook(false): on_native_bar_open does nothing, so the kernel does not call it. It keeps every effect of the call's boundary that is its own – the decision context, the point's epoch, the complete bar at the point's instant, the abort check and the drain of the applied notifications – so the run is the run of a host whose hook is empty. C spelling: a pf_native_callbacks_v1 without on_bar_open declares it.

◆ declare_native_precommit_hook()

void pineforge::engine_script_run_v19::NativeStrategyHost::declare_native_precommit_hook ( bool implemented)

declare_native_precommit_hook(false): validate_execution_precommit is the default admission, so the kernel does not consult it, and builds the settlement preview it would have been shown (prepare, then project) only for a host that owns lot excursions, whose closed_lot_excursion every closing row of that preview consults.

The abort check that follows the hook is kept. C spelling: a pf_native_callbacks_v1 without on_precommit declares it.

◆ current_partial_bar()

std::optional< Bar > pineforge::engine_script_run_v19::NativeStrategyHost::current_partial_bar ( ) const

The bar so far, folded from the path points this script bar has already consumed: open of its first point, running high/low, close at the last point consumed.

A discrete point — the open of the bar or of a sub-bar, a distribution sample, an observed print — is folded before its callbacks run, so there the bar closes at the cursor. A fill inside a segment (a trigger crossed between two path points) comes before the walk reaches the segment's destination: its on_native_applied and its OrderFill recalculation read a bar that still ends at the segment's origin and does not hold the fill price. It never runs ahead of the cursor. Volume is the activity actually consumed so far — the completed lower-timeframe sub-bars of an intrabar path, or the prints of an observed stream — and stays 0 for a modeled path with no intrabar volume of its own. Valid in the bar-open, applied, tick, sub-bar and recalculation callbacks; nullopt outside a path walk, including in the bar's own close calculation, where the host already holds the complete bar.

◆ native_recalculation_count()

std::uint64_t pineforge::engine_script_run_v19::NativeStrategyHost::native_recalculation_count ( ) const

How many recalculations the kernel has driven this run, and how many it suppressed because a point had already spent its max_recalculations_per_point budget.

Observation only.

◆ native_recalculations_skipped()

std::uint64_t pineforge::engine_script_run_v19::NativeStrategyHost::native_recalculations_skipped ( ) const

How many recalculations max_recalculations_per_point dropped at their matching point.

The executions themselves were still applied and still delivered to on_native_applied; only the calculation they would have driven was skipped. C spelling: strategy_native_recalculations_v1, beside the driven count.

◆ current_execution_point()

std::optional< NativeCurrentPointView > pineforge::engine_script_run_v19::NativeStrategyHost::current_execution_point ( ) const

The active callback's quote and calendar-derived decision context, as an owning value.

nullopt outside a decision point. C spelling: pf_native_decision_v1::price / ::quote_kind, on every callback.

◆ trail_state()

std::optional< NativeTrailState > pineforge::engine_script_run_v19::NativeStrategyHost::trail_state ( const native_order::RequestHandle & target) const

Where one live trail's own trigger has reached: activated, the running best, the current level and the ordinal it activated at.

nullopt when the handle is not a live trail. C spelling: strategy_native_trail_state_v1, with PF_NATIVE_ABSENT for the empty. Pinned by tests/test_native_trail_state_l5k.cpp.

◆ inspect_current_execution()

NativeCurrentExecutionPreview pineforge::engine_script_run_v19::NativeStrategyHost::inspect_current_execution ( const NativeCurrentExecution & ) const

A read-only preview of a current execution: the settlement readiness, any typed refusal or terms outcome, and the ordered closed-row P&L for an Applied-ready command.

It is never an apply token — execute_current revalidates, and editing the preview cannot authorize or alter a fill. No C spelling in 1.0 (C-SURFACE-2, 1.1.0): strategy_native_execute_current_v1 applies the command, so it is no preview.

◆ execute_current()

NativeCurrentExecutionResult pineforge::engine_script_run_v19::NativeStrategyHost::execute_current ( const NativeCurrentExecution & )

Consume, synchronously, a request accepted or replaced in this very callback.

Answers a refusal or the applied outcome; applied effects and relationship drains are visible before the call returns. Only the named target is consumed. C spelling: strategy_native_execute_current_v1.

◆ mark_native_report_point()

bool pineforge::engine_script_run_v19::NativeStrategyHost::mark_native_report_point ( int64_t report_ts)

Append one kernel-owned equity point at this host's report mark.

Returns true only in a running KernelRecordedAtHostMarks run; false changes nothing. Call at the desired mark inside a native callback. This is reporting only: it does not book cash or place an order. A host that records per-point broker hashes still owns those hash rows. No C spelling: the C spec cannot select KernelRecordedAtHostMarks.

◆ native_series_bar()

std::optional< Bar > pineforge::engine_script_run_v19::NativeStrategyHost::native_series_bar ( std::size_t subscription) const

The latest completed bucket delivered for a declared subscription, or nullopt before its first delivery / for an unknown index.

Legal inside every native callback, including on_native_timeframe_bar itself. A gaps = true series answers nullopt again on every input bar it delivered nothing on.

◆ declare_timeframe_subscriptions()

bool pineforge::engine_script_run_v19::NativeStrategyHost::declare_timeframe_subscriptions ( std::vector< NativeTimeframeSubscription > subscriptions)

Declare this run's higher-timeframe series from inside on_native_run_begin, for a host whose series are known only to its own begin-time registration.

The list REPLACES the staged spec's subscriptions, and the kernel registers from the staged spec after this callback returns, so a host's own registration cannot erase the kernel's and the run's continuation identity folds what actually ran. Legal only inside on_native_run_begin: anywhere else, and for a list this run's input timeframe would refuse (the same validation configure_native applies), it stages nothing, changes nothing and answers false. Not virtual: the host calls the kernel here, never the other way round.

The bool cannot tell those two refusals apart: declare_timeframe_subscriptions_result below answers the same call by name and this spelling is exactly ... .status == Applied.

◆ declare_timeframe_subscriptions_result()

NativeSetupResult pineforge::engine_script_run_v19::NativeStrategyHost::declare_timeframe_subscriptions_result ( std::vector< NativeTimeframeSubscription > subscriptions)

The same call, answered the way configure_native answers the identical validation: Applied, or Failed with the first error field validate_native_timeframe_subscriptions found.

A call made outside on_native_run_begin – or on a host that has already failed – judged no list at all and is NativeRunSpecError::WrongPhase at NativeRunSpecField::None. Same commands, same staging, same refusals as the bool spelling above.

◆ declare_auxiliary_feed()

bool pineforge::engine_script_run_v19::NativeStrategyHost::declare_auxiliary_feed ( std::optional< NativeAuxiliaryFeed > feed)

The same begin-time hook for NativeRunSpec::auxiliary_feed: the feed REPLACES the staged spec's own (nullopt withdraws it), and the kernel registers from the staged spec after on_native_run_begin returns.

It is judged together with the series staged at that moment, so a host that names both here declares the feed first and its AuxiliaryFeed series second. Legal only inside on_native_run_begin: anywhere else, for a feed this run's input timeframe would refuse, and for one that would leave a staged AuxiliaryFeed series without its bars, it changes nothing and answers false. Not virtual.

Three refusals, one bit: declare_auxiliary_feed_result below answers the same call by name, and this spelling is ... .status == Applied.

◆ declare_auxiliary_feed_result()

NativeSetupResult pineforge::engine_script_run_v19::NativeStrategyHost::declare_auxiliary_feed_result ( std::optional< NativeAuxiliaryFeed > feed)

The same call, answered the way configure_native answers the identical validation: Applied, or Failed with the first error field the judged feed-and-series pair produced (AuxiliaryFeedNotFinerThanInput for a feed the input refuses, SubscriptionWithoutAuxiliaryFeed for a withdrawal that would strand a staged series).

Outside on_native_run_begin nothing was judged: WrongPhase at NativeRunSpecField::None.

◆ append_auxiliary_bars()

bool pineforge::engine_script_run_v19::NativeStrategyHost::append_auxiliary_bars ( const Bar * bars,
std::size_t n )

A realtime stream's later bars of its declared auxiliary feed.

They join the feed behind every bar it holds and ride on the next accepted input whose period they opened before — the routing rule a batch of the same bars applies. Legal between stream inputs on a Realtime run that declared a feed. Refused by name, changing nothing and without failing the host: bars out of order or not after the feed's last bar, a bar with invalid OHLCV, and a bar that opened inside an input period already accepted (its slice is closed; no batch could build that series). Calling it from inside a callback is the contract failure every reentrant stream input is.

"By name" is what append_auxiliary_bars_result below answers; this spelling is its status == NativeSetupStatus::Applied and carries none of the names.

◆ append_auxiliary_bars_result()

NativeAuxiliaryAppendResult pineforge::engine_script_run_v19::NativeStrategyHost::append_auxiliary_bars_result ( const Bar * bars,
std::size_t n )

The same call, answering NativeAuxiliaryAppendError and the bar of this call it stopped on.

Same commands, same appended bars, same latched Contract failure for a reentrant call; last_error() stays the presentation text beside it.

◆ configure_native()

NativeSetupResult pineforge::engine_script_run_v19::NativeStrategyHost::configure_native ( const NativeRunSpec & spec)

The only setup call.

Copies the candidate spec, normalizes it and stages it atomically: Unconfigured or a Completed run with a larger run number becomes Ready, and a refusal is Failed with no partial apply. Calling it again while Ready is a Contract failure — use a new host to change unconsumed setup. C spelling: strategy_configure_native_v1 / _ext_v1, typed refusal _ext_result_v1.

◆ configure_native_fx_curve()

NativeFxCurveSetupResult pineforge::engine_script_run_v19::NativeStrategyHost::configure_native_fx_curve ( const NativeFxCurve & curve)

Stage the run's immutable FX epoch, legal only while Ready.

Parallel timestamp/rate arrays of equal length, strictly increasing timestamps, finite positive rates; an empty curve clears it and restores the scalar account_fx fallback. Refused with WrongPhase once the run is Running. C spelling: strategy_configure_native_fx_curve_v1, typed refusal _fx_curve_ext_v1.

◆ native_state()

NativeStateView pineforge::engine_script_run_v19::NativeStrategyHost::native_state ( ) const

The whole run state as one owning read.

The only observation of the lifecycle and of the durable failure; last_error() is presentation text beside it. C spelling: strategy_native_state_v1.

◆ submit()

native_order::SubmitResult pineforge::engine_script_run_v19::NativeStrategyHost::submit ( const native_order::Request & request)

Accept one complete request.

Answers Accepted with a timeline ordinal and a RequestHandle, or Rejected with a rejection ordinal and a reason. Acceptance is not a fill: no lot and no fee moves here. Legal from a native callback in Batch/Warmup/Realtime, or between realtime inputs on the same thread. C spelling: strategy_native_submit_v1.

◆ replace() [1/2]

native_order::ReplaceResult pineforge::engine_script_run_v19::NativeStrategyHost::replace ( const native_order::RequestHandle & target,
const native_order::Request & request )

Replace one live request: validate first, then retire that incarnation and birth a successor with a new handle, a new priority and a predecessor link.

A ReplaceRejected leaves the target live; a same-run absent, replaced or terminal handle is NotWorking, a foreign or malformed one InvalidHandle. Every outcome is an event, and no outcome moves a lot. C spelling: strategy_native_replace_v1.

◆ submit_market()

native_order::SubmitResult pineforge::engine_script_run_v19::NativeStrategyHost::submit_market ( const native_order::Request & request)

The deliberately narrow market-default convenience: the same acceptance path as submit, but it REFUSES a nondefault trigger, capacity, owner or group rather than dropping it.

No C spelling, by design — the same request is strategy_native_submit_v1 with PF_NATIVE_TRIGGER_MARKET and a zero-filled struct.

◆ replace_market()

native_order::ReplaceResult pineforge::engine_script_run_v19::NativeStrategyHost::replace_market ( const native_order::RequestHandle & target,
const native_order::Request & request )

The same market-default convenience for a replace; see submit_market.

◆ replace() [2/2]

native_order::ReplaceResult pineforge::engine_script_run_v19::NativeStrategyHost::replace ( const native_order::RequestHandle & target,
const native_order::Request & request,
native_order::ReplaceOptions options )

Replace with options.

ReplaceOptions{retain_trigger_state = true} carries the predecessor's live trigger state — a tracking trail's best, an already active stop — into the successor instead of restarting it. Predecessor and successor must hold the same trigger alternative, and a retained best must still produce a representable level; otherwise the replacement is rejected and the predecessor stays live. keep_handle re-prices the request in place: the answer's successor is the target itself, its waiting children and roster entries stay, and it ranks as the newest request, where a successor would. keep_binding lets a close bound to the book keep that binding when the book still has it at the successor's first evaluation, with no CloseBound event. No C spelling: the C replace takes no options.

◆ cancel()

native_order::CancelResult pineforge::engine_script_run_v19::NativeStrategyHost::cancel ( const native_order::RequestHandle & target)

Cancel one live request by handle.

A live request becomes Cancelled; a same-run absent, replaced or already terminal handle is NotWorking; a foreign or malformed handle is InvalidHandle. Every outcome is an event. C spelling: strategy_native_cancel_v1.

◆ native_working_requests()

std::vector< NativeWorkingRequest > pineforge::engine_script_run_v19::NativeStrategyHost::native_working_requests ( ) const

Working-book snapshot and bulk cancellation.

cancel_all returns how many requests left the book (one CancelledEvent each, dependants included); cancel_where cancels exactly the live requests carrying that comment and returns how many of them it cancelled.

The second form chooses which identity field the text is compared against: NativeRequestField::Comment is the one-argument form, and NativeRequestField::Label addresses the requests by their label, the one-call equivalent of cancelling every order a host issued under its own id. Neither form indexes anything: both walk the live book once, like cancel_all, so a label may be reused, replaced or left empty without any bookkeeping to keep in step. Text that matches nothing is not a command.

◆ cancel_all()

std::size_t pineforge::engine_script_run_v19::NativeStrategyHost::cancel_all ( )

Withdraw every live request, dependants of a cancelled owner included, and answer how many left the book.

One CancelledEvent per request. C spelling: strategy_native_cancel_all_v1.

◆ cancel_where() [1/2]

std::size_t pineforge::engine_script_run_v19::NativeStrategyHost::cancel_where ( std::string_view comment)

Withdraw exactly the live requests carrying this comment, and answer how many of those left the book.

An unknown comment is not a command. The comment is free host text the kernel only copies and compares, and it is not indexed: this walks the live book once, exactly as cancel_all does.

◆ cancel_where() [2/2]

std::size_t pineforge::engine_script_run_v19::NativeStrategyHost::cancel_where ( std::string_view text,
NativeRequestField field )

The same predicate over either identity text.

NativeRequestField::Label addresses requests by Request::label — the one call that withdraws every live request a host issued under one of its own order ids. "" is the text a request carrying no such field matches. C spelling: strategy_native_cancel_where_v1(host, text, PF_NATIVE_FIELD_LABEL).

◆ cohort_open()

native_order::CohortHandle pineforge::engine_script_run_v19::NativeStrategyHost::cohort_open ( )

Open a roster a later close can bind to.

The handle is what a native_order::BindCohort owner names. C spelling: strategy_native_cohort_open_v1.

◆ cohort_add()

void pineforge::engine_script_run_v19::NativeStrategyHost::cohort_add ( native_order::CohortHandle cohort,
native_order::RequestHandle origin )

Enroll one accepted opening's handle in a roster.

C spelling: strategy_native_cohort_add_v1.

◆ cohort_remove()

void pineforge::engine_script_run_v19::NativeStrategyHost::cohort_remove ( native_order::CohortHandle cohort,
native_order::RequestHandle origin )

Take one opening back off a roster.

C spelling: strategy_native_cohort_remove_v1.

◆ physical_position()

NativePhysicalPosition pineforge::engine_script_run_v19::NativeStrategyHost::physical_position ( ) const

The book as one aggregate, copied out.

C spelling: strategy_native_position_v1.

◆ native_open_lots()

std::vector< NativeOpenLot > pineforge::engine_script_run_v19::NativeStrategyHost::native_open_lots ( double mark) const

The book lot by lot, oldest first, marked at mark: one NativeOpenLot per physical lot (physical_position().lot_count rows), copied at query time.

Legal wherever physical_position() is; observation only, it moves no fill, no hash and no row.

◆ native_marked_equity()

double pineforge::engine_script_run_v19::NativeStrategyHost::native_marked_equity ( double mark) const

The account's equity marked at this price: the realized balance plus every open lot's own fee-net term, which is exactly what native_open_lots(mark) sums.

It moves nothing. C spelling: strategy_native_marked_equity_v1.

◆ native_sized_units()

std::optional< double > pineforge::engine_script_run_v19::NativeStrategyHost::native_sized_units ( const native_order::Sized & sized,
double price,
double equity,
double fx ) const

The units a kernel-sized intent resolves to under this run's spec at a sizing price, a marked equity and an account FX rate – as a pure query.

units = cash / (price * point_value * fx), cash the basis value or fraction * equity, net of the percent fee reserve when the intent asks for it, then the intent's grid policy: this is the same function the kernel runs at acceptance (SizeTime::AtAcceptance) and at the candidate (AtMatch), so a host that gates a command on its quantity before it submits reads the number here rather than keeping its own copy of the conversion. nullopt when the run is not configured or the basis is unresolvable at those inputs (non-positive money or denominator, a below-one-step quotient under SnapToGrid). Observation only: it moves nothing and freezes nothing.

References pineforge::price.

◆ native_liquidation_price()

std::optional< double > pineforge::engine_script_run_v19::NativeStrategyHost::native_liquidation_price ( ) const

The price at which the marked equity falls below the run's maintenance requirement for the live position's side.

nullopt when the run declares no margin model, the side has no maintenance fraction, the book is flat, or no finite price solves the breach (a long at full maintenance).

◆ native_aggregates_input_bars()

bool pineforge::engine_script_run_v19::NativeStrategyHost::native_aggregates_input_bars ( ) const

Whether the configured run's script bars are buckets the kernel gathers from its input bars – native_calendar::pairing_aggregates of the pairing it resolved for the spec's input and script timeframes – rather than the input bars themselves.

False for a chart-timeframe run (byte-identical literals), an undetected timeframe, or no configured spec.

◆ native_risk_state()

NativeRiskState pineforge::engine_script_run_v19::NativeStrategyHost::native_risk_state ( ) const

The run's generic risk ledger.

Every field is its zero for a run that declares no NativeRunSpec::risk; observation only, it moves nothing.

◆ native_events()

std::vector< NativeMarketEvent > pineforge::engine_script_run_v19::NativeStrategyHost::native_events ( uint64_t after_ordinal) const

Owning snapshots copied at query time.

Later commands/reset do not invalidate already returned values. The rows are what the run's NativeRunSpec::event_retention keeps: under Window the command events the host has not yet acknowledged, and no driver point or account row; a read from below native_event_window_start() starts there.

◆ native_acknowledge_events()

void pineforge::engine_script_run_v19::NativeStrategyHost::native_acknowledge_events ( uint64_t through_ordinal)

The host has read every event through through_ordinal (R5 lane V19-B).

Under NativeEventRetention::Window the kernel drops the acknowledged command events at the next script-bar boundary – never one its own live state still reads – and keeps every event above the acknowledgement for a later read. The first call also marks the host as one that polls: until a host acknowledges, the kernel treats it as served by its callbacks alone and closes its window at every script-bar end, so a polling host acknowledges at its run begin (0 is legal: "nothing read yet"). An acknowledgement is never lowered by a later, smaller one; one above the event high water acknowledges the high water, never events that have not happened; and before a run begins, or once it has ended, it records nothing (the next begin starts a new journal). Full and Commands keep the whole journal whatever is acknowledged. C spelling: strategy_native_acknowledge_events_v1.

◆ native_event_window_start()

uint64_t pineforge::engine_script_run_v19::NativeStrategyHost::native_event_window_start ( ) const

The oldest ordinal a read can still return: every command event at or above it is retained, and native_events(after) for an after below it starts here, the events before it having been dropped by the window.

1 while nothing was dropped, which is every run under Full or Commands. C spelling: strategy_native_event_window_v1.

◆ native_decision_floor()

int64_t pineforge::engine_script_run_v19::NativeStrategyHost::native_decision_floor ( ) const

The run's monotonic decision floor in epoch milliseconds — the same value NativeStateView::decision_floor_ms carries.

Every request's birth is compared against this floor, not against a later lowered clock, and a refused preflight does not raise it. C spelling: pf_native_state_v1::decision_floor_ms.

◆ native_consumed_high_water()

uint64_t pineforge::engine_script_run_v19::NativeStrategyHost::native_consumed_high_water ( ) const

The highest run_number this host has consumed.

It lives OUTSIDE per-run reset, so a later run on the same host needs a strictly larger number; a fresh host reads 0 and may therefore replay the same logical run. C spelling: pf_native_state_v1::consumed_high_water.

◆ native_continuation_hash()

uint64_t pineforge::engine_script_run_v19::NativeStrategyHost::native_continuation_hash ( ) const

The consumer's continuation identity: what a stream resumes against.

It folds the run's resolved timezone identity by its content — the kind, the effective definition and a digest of the zone resources actually read — and not by where they live, so two hosts carrying the same tzdata release answer the same value for the same spec over the same bars (R5 lane E23). A tzdata update that rewrites the zone's rules moves it, which is why it is still not a source constant: pin native_run_spec_digest(spec) for that, and compare continuation values between runs. C spelling: strategy_native_continuation_hash_v1.

◆ native_closed_rows_amended()

void pineforge::engine_script_run_v19::NativeStrategyHost::native_closed_rows_amended ( std::size_t first_row)

The closed rows (the engine's trades_) are part of broker_state_hash(), folded once each through a running digest (pineforge-broker-state/v19).

A row is final once the applied notification of the execution that booked it has returned; a host may amend it until then. A host that amends or reorders a final row names the first row it changed here, before the next hash read, and the kernel folds the rows from there again. Debug builds re-fold every digested row at a run's end and abort if one changed unannounced.

◆ broker_state_hash_projection()

std::uint64_t pineforge::engine_script_run_v19::NativeStrategyHost::broker_state_hash_projection ( ) const
overrideprotectedvirtual

The documentation for this class was generated from the following file: