PineForge unreleased
Deterministic PineScript v6 backtest runtime — C ABI reference
Loading...
Searching...
No Matches
Strategy lifecycle

Create, run, and destroy a compiled strategy instance. More...

Data Structures

struct  pf_native_run_spec_v1
 Versioned native run specification. More...
 
struct  pf_native_fx_curve_v1
 Immutable timestamped account-currency FX curve for a native run. More...
 

Enumerations

enum  pf_execution_contract_t {
  PF_EXECUTION_CONTRACT_LEGACY = 1 ,
  PF_EXECUTION_CONTRACT_NATIVE_MARKET_V1 = 2
}
 What strategy_execution_contract answers for a valid handle. More...
 
enum  pf_native_spec_optional_t {
  PF_NATIVE_SPEC_OPTIONAL_QUANTITY_GRID = 1u << 0 ,
  PF_NATIVE_SPEC_OPTIONAL_MAX_ABS_UNITS = 1u << 1 ,
  PF_NATIVE_SPEC_OPTIONAL_INITIAL_MARGIN_FRACTION = 1u << 2 ,
  PF_NATIVE_SPEC_OPTIONAL_MAX_OPEN_LOTS = 1u << 3
}
 The bits of pf_native_run_spec_v1::optional_mask: each names the one optional field it makes meaningful. More...
 
enum  pf_native_fx_curve_error_t {
  PF_NATIVE_FX_CURVE_ERROR_NONE = 0 ,
  PF_NATIVE_FX_CURVE_ERROR_LENGTH_MISMATCH = 1 ,
  PF_NATIVE_FX_CURVE_ERROR_NOT_STRICTLY_INCREASING = 2 ,
  PF_NATIVE_FX_CURVE_ERROR_NOT_FINITE_POSITIVE = 3 ,
  PF_NATIVE_FX_CURVE_ERROR_ALLOCATION_FAILURE = 4 ,
  PF_NATIVE_FX_CURVE_ERROR_WRONG_PHASE = 5
}
 Why a native FX curve was refused — the C twin of pineforge::NativeFxCurveError. More...
 

Functions

int strategy_execution_contract (pf_strategy_t s)
 Native execution contract query: a pf_execution_contract_t, or -1 for a NULL handle.
 
int strategy_configure_native_v1 (pf_strategy_t s, const pf_native_run_spec_v1 *spec)
 Apply a native v1 specification.
 
 PF_STATIC_ASSERT (sizeof(pf_native_fx_curve_error_t)==4)
 
int strategy_configure_native_fx_curve_v1 (pf_strategy_t s, const pf_native_fx_curve_v1 *curve)
 Stage an immutable account-currency FX curve on a Ready native handle.
 
int strategy_configure_native_fx_curve_ext_v1 (pf_strategy_t s, const pf_native_fx_curve_v1 *curve, pf_native_fx_curve_error_t *error, uint64_t *index)
 Typed additive spelling of strategy_configure_native_fx_curve_v1.
 
pf_strategy_t strategy_create (const char *params_json)
 Allocate a new strategy instance.
 
void strategy_free (pf_strategy_t s)
 Release a strategy handle previously returned by strategy_create.
 
void run_backtest (pf_strategy_t s, pf_bar_t *bars, int n, pf_report_t *out)
 Run a backtest with auto-detected timeframe and no bar magnifier.
 
void run_backtest_full (pf_strategy_t s, pf_bar_t *bars, int n, const char *input_tf, const char *script_tf, int bar_magnifier, int magnifier_samples, pf_magnifier_distribution_t magnifier_dist, pf_report_t *out)
 Run a backtest with explicit timeframe and magnifier configuration.
 
void report_free (pf_report_t *report)
 Free heap arrays attached to a filled report.
 
int pf_report_scratch_arena_stats (uint64_t *high_water_bytes, uint64_t *arena_bytes)
 Read process-wide scratch-arena diagnostics, outside canonical report bytes.
 
int pf_report_cache_stats (pf_strategy_t s, uint64_t *resident_bytes, uint64_t *allocation_bypass_count)
 Read the handle's admitted-run command-cache and trade-ledger diagnostics.
 
int strategy_require_report_scratch_arena_v1 (pf_strategy_t s)
 Admit a jailed handle only with an attached scratch arena.
 
int strategy_report_sink_diagnostics_v1 (pf_strategy_t s, struct pf_report_sink_diagnostics_v1 *out)
 Read bounded sink provenance without reading the sink or replaying rows.
 
int pf_run_abort_install_sigterm_v1 (void)
 Install the invocation's cooperative SIGTERM handler.
 
int pf_run_abort_requested_v1 (void)
 Read the invocation stop flag: 0 or 1.
 
int pf_run_abort_restore_sigterm_v1 (void)
 Restore the disposition saved by pf_run_abort_install_sigterm_v1.
 
uint64_t strategy_closed_trade_entry_incarnation (pf_strategy_t s, int trade_index)
 Return the physical entry incarnation for one closed-trade row.
 

Detailed Description

Create, run, and destroy a compiled strategy instance.

NOTE: Per-strategy symbols (strategy_create, run_backtest, etc.) are emitted by the codegen with internal C++ types (ReportC, Bar) that are layout-compatible but type-distinct from the public C PODs below. Guard with PINEFORGE_NO_STRATEGY_DECLS so engine.hpp can include this header for its POD types without conflicting with per-strategy TU definitions.

Enumeration Type Documentation

◆ pf_execution_contract_t

What strategy_execution_contract answers for a valid handle.

Enumerator
PF_EXECUTION_CONTRACT_LEGACY 

The retired legacy execution path.

PF_EXECUTION_CONTRACT_NATIVE_MARKET_V1 

The native market kernel; every handle this runtime creates.

Definition at line 456 of file pineforge.h.

◆ pf_native_spec_optional_t

The bits of pf_native_run_spec_v1::optional_mask: each names the one optional field it makes meaningful.

A bit outside this set is refused.

Enumerator
PF_NATIVE_SPEC_OPTIONAL_QUANTITY_GRID 

quantity_grid.

PF_NATIVE_SPEC_OPTIONAL_MAX_ABS_UNITS 

max_abs_units.

PF_NATIVE_SPEC_OPTIONAL_INITIAL_MARGIN_FRACTION 

initial_margin_fraction.

PF_NATIVE_SPEC_OPTIONAL_MAX_OPEN_LOTS 

max_open_lots.

Definition at line 469 of file pineforge.h.

◆ pf_native_fx_curve_error_t

Why a native FX curve was refused — the C twin of pineforge::NativeFxCurveError.

The typed additive route writes this word beside the offending array index.

Enumerator
PF_NATIVE_FX_CURVE_ERROR_NONE 
PF_NATIVE_FX_CURVE_ERROR_LENGTH_MISMATCH 
PF_NATIVE_FX_CURVE_ERROR_NOT_STRICTLY_INCREASING 
PF_NATIVE_FX_CURVE_ERROR_NOT_FINITE_POSITIVE 
PF_NATIVE_FX_CURVE_ERROR_ALLOCATION_FAILURE 
PF_NATIVE_FX_CURVE_ERROR_WRONG_PHASE 

Definition at line 529 of file pineforge.h.

Function Documentation

◆ strategy_execution_contract()

int strategy_execution_contract ( pf_strategy_t s)

Native execution contract query: a pf_execution_contract_t, or -1 for a NULL handle.

Absence of this symbol on a known ABI4/stream-v1 library means legacy.

References PF_API.

◆ strategy_configure_native_v1()

int strategy_configure_native_v1 ( pf_strategy_t s,
const pf_native_run_spec_v1 * spec )

Apply a native v1 specification.

Returns 0 on success, -1 on failure. Legacy handles refuse without native state mutation.

References PF_API.

Referenced by main().

◆ PF_STATIC_ASSERT()

PF_STATIC_ASSERT ( sizeof(pf_native_fx_curve_error_t) = =4)

◆ strategy_configure_native_fx_curve_v1()

int strategy_configure_native_fx_curve_v1 ( pf_strategy_t s,
const pf_native_fx_curve_v1 * curve )

Stage an immutable account-currency FX curve on a Ready native handle.

Timestamps must be strictly increasing and rates finite and positive. Pass n == 0 to clear the staged curve; the scalar account_fx remains the pre-first fallback. Curves are applied when the native run begins. Legacy handles and non-Ready native handles refuse without mutation.

Returns
0 only when staging is applied; -1 for invalid input, an invalid handle, a non-native or non-host native handle, or a non-Ready host. The typed additive strategy_configure_native_fx_curve_ext_v1 writes the pf_native_fx_curve_error_t and offending index when the kernel judged the curve.

References PF_API.

◆ strategy_configure_native_fx_curve_ext_v1()

int strategy_configure_native_fx_curve_ext_v1 ( pf_strategy_t s,
const pf_native_fx_curve_v1 * curve,
pf_native_fx_curve_error_t * error,
uint64_t * index )

Typed additive spelling of strategy_configure_native_fx_curve_v1.

On a kernel validation refusal, writes the pf_native_fx_curve_error_t and the offending element index (length mismatch uses index 0). C-layer argument, handle and layout refusals leave the out-parameters untouched.

References PF_API.

◆ strategy_create()

pf_strategy_t strategy_create ( const char * params_json)

Allocate a new strategy instance.

Parameters
params_jsonCurrently ignored; pass NULL.
Returns
Strategy handle, or NULL on allocation failure.

Caller owns the returned handle and must release it via strategy_free.

References PF_API.

◆ strategy_free()

void strategy_free ( pf_strategy_t s)

Release a strategy handle previously returned by strategy_create.

Safe to call with NULL. Invalidates any pf_report_t::trace_names pointers obtained from this strategy.

References PF_API.

◆ run_backtest()

void run_backtest ( pf_strategy_t s,
pf_bar_t * bars,
int n,
pf_report_t * out )

Run a backtest with auto-detected timeframe and no bar magnifier.

Parameters
sStrategy handle from strategy_create.
barsNon-NULL pointer to OHLCV bars (length n).
nBar count (>= 0).
outNon-NULL output report. Fields are populated with heap allocations the caller must release via report_free.

References PF_API.

◆ run_backtest_full()

void run_backtest_full ( pf_strategy_t s,
pf_bar_t * bars,
int n,
const char * input_tf,
const char * script_tf,
int bar_magnifier,
int magnifier_samples,
pf_magnifier_distribution_t magnifier_dist,
pf_report_t * out )

Run a backtest with explicit timeframe and magnifier configuration.

Parameters
sStrategy handle.
barsBar feed.
nBar count.
input_tfInput timeframe ("1", "5", "15", "60", "1D", ...). Empty string → auto-detect from bar timestamps.
script_tfScript timeframe. Empty string → defaults to input_tf.
bar_magnifierBoolean (0 / non-zero) — enable bar magnifier.
magnifier_samplesSub-bar samples per parent bar (typical: 4).
magnifier_distSampling distribution (see pf_magnifier_distribution_t).
outOutput report. Free with report_free.

References PF_API.

◆ report_free()

void report_free ( pf_report_t * report)

Free heap arrays attached to a filled report.

Idempotent. Safe to call with NULL or an already-freed report. The pf_report_t struct itself is caller-owned.

References PF_API.

◆ pf_report_scratch_arena_stats()

int pf_report_scratch_arena_stats ( uint64_t * high_water_bytes,
uint64_t * arena_bytes )

Read process-wide scratch-arena diagnostics, outside canonical report bytes.

Writes the peak bytes of simultaneously claimed chunks since attachment and the exact supplied backing size (including any unallocatable tail). Returns 0; with no arena attached both values are 0. Returns -1 with both outputs unchanged if either pointer is NULL, the pointers alias, or the snapshot cannot be read. Never throws or changes a strategy's last error. Query after report finalization and before arena detach. The counters belong to the attachment, not a strategy or repeat; detach resets them. No pf_report_t, sink receipt, trailer or broker-state hash layout changes.

References PF_API.

◆ pf_report_cache_stats()

int pf_report_cache_stats ( pf_strategy_t s,
uint64_t * resident_bytes,
uint64_t * allocation_bypass_count )

Read the handle's admitted-run command-cache and trade-ledger diagnostics.

resident_bytes is the current sum of live command-cache control/slabs and the ledger's fixed workspace, allocated directory and decoded-entry pages. Each allocation owner contributes once; borrowed shared-cache storage does not add another charge. Arena chunks and backing-file extents are separate. allocation_bypass_count counts optional command-slab and ledger-directory/ page allocation failures, once per sticky bypass, including released owners. Both outputs are 0 before the first admitted run; admission resets them. Returns 0, or -1 with both outputs unchanged for a NULL handle/output or aliased outputs. Never allocates, throws or changes last_error. Query on the invoking thread after report finalization and before freeing the strategy. No existing report, receipt or diagnostics layout changes.

References PF_API.

◆ strategy_require_report_scratch_arena_v1()

int strategy_require_report_scratch_arena_v1 ( pf_strategy_t s)

Admit a jailed handle only with an attached scratch arena.

Attach the inherited environment arena, if configured (fixed fd 5: PF_SCRATCH_ARENA_FD=5, positive PF_SCRATCH_ARENA_BYTES); validate its backing and mapping configuration before execution. On Linux, require a sealed memfd whose seal mask contains F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL. F_SEAL_EXEC and other non-write seals may be added (e.g. MFD_NOEXEC_SEAL). F_SEAL_WRITE or F_SEAL_FUTURE_WRITE is refused at attachment with report_sink_failed/arena_backing. These requirements hold regardless of PF_SCRATCH_ARENA_JAILED; off Linux, admit any attached arena. Returns 0 accepted; -1 for a NULL handle or an unavailable/invalid arena. Arena failures set the handle's typed report_sink_failed/arena_backing failure. Never creates a backing file or falls back to TMPDIR. Existing unjailed callers do not need to call this opt-in admission. The first successful attach sets SIGXFSZ to SIG_IGN process-wide; the prior disposition is not restored. Same fd/size reattaches are no-ops. Hosts relying on their SIGXFSZ handler or default termination must account for this before attaching an arena.

References PF_API.

◆ strategy_report_sink_diagnostics_v1()

int strategy_report_sink_diagnostics_v1 ( pf_strategy_t s,
struct pf_report_sink_diagnostics_v1 * out )

Read bounded sink provenance without reading the sink or replaying rows.

Include report_sink.h for the descriptor; initialize struct_size and version=1. Returns 0 filled; -1 with *out unchanged for a bad handle, size, version or NULL output. Completion follows the sink trailer. Queries never execute callbacks, advance a cursor or change last_error.

References PF_API.

◆ pf_run_abort_install_sigterm_v1()

int pf_run_abort_install_sigterm_v1 ( void )

Install the invocation's cooperative SIGTERM handler.

The handler only stores a volatile sig_atomic_t flag; batch runs observe it at completed input-bar boundaries, independently of strategy_request_abort. Opt-in, process-wide, for one serialized child invocation. Call on the invoking thread with SIGTERM blocked, then unblock it; pending SIGTERM is preserved. Returns 0, or -1 on signal-setup failure. Repeated installation preserves an already requested stop. This opt-in installs only the abort handler for SIGTERM; it does not change any ABI layout.

References PF_API.

◆ pf_run_abort_requested_v1()

int pf_run_abort_requested_v1 ( void )

Read the invocation stop flag: 0 or 1.

No allocation or state mutation.

References PF_API.

◆ pf_run_abort_restore_sigterm_v1()

int pf_run_abort_restore_sigterm_v1 ( void )

Restore the disposition saved by pf_run_abort_install_sigterm_v1.

Call with SIGTERM blocked, after native cleanup and failure publication. Returns 0 (also when uninstalled), or -1 on signal-setup failure.

References PF_API.

◆ strategy_closed_trade_entry_incarnation()

uint64_t strategy_closed_trade_entry_incarnation ( pf_strategy_t s,
int trade_index )

Return the physical entry incarnation for one closed-trade row.

Partial-close/FIFO fragments emitted from the same physical entry share this value. Distinct broker entry objects receive distinct monotonically increasing values even when Pine reuses the same user-visible entry ID. The value is scoped to one strategy run and is intended as report provenance, not as a stable cross-run identifier.

Parameters
sStrategy handle whose most recent run filled a report.
trade_indexZero-based row index into that report's trades array — the script's closed trades followed by the range-end rows (open_at_end, ABI v3), which carry the incarnation of the lot they mark like any other close.
Returns
Non-zero physical-entry identity, or 0 for an invalid index or a legacy/synthetic trade without request record provenance.

References PF_API.