|
PineForge v1.4.0-4-g873b25da
Deterministic PineScript v6 backtest runtime — C ABI reference
|
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 |
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.
| pineforge::engine_script_run_v19::NativeStrategyHost::NativeStrategyHost | ( | ) |
Referenced by NativeStrategyHost(), NativeStrategyHost(), operator=(), and operator=().
|
delete |
References NativeStrategyHost().
|
delete |
References NativeStrategyHost().
|
override |
|
delete |
References NativeStrategyHost().
|
delete |
References NativeStrategyHost().
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
|
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().
|
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().
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
|
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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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).
| 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.
| 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.
| 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.
| NativePhysicalPosition pineforge::engine_script_run_v19::NativeStrategyHost::physical_position | ( | ) | const |
The book as one aggregate, copied out.
C spelling: strategy_native_position_v1.
| 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.
| 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.
| 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.
| 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).
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
| 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.
|
overrideprotectedvirtual |
Reimplemented from pineforge::engine_script_run_v19::BacktestEngine.