Repository navigation
Expand file tree
/
Copy pathpineforge.h
More file actions
2407 lines (2240 loc) · 141 KB
/
Copy pathpineforge.h
File metadata and controls
2407 lines (2240 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SPDX-License-Identifier: Apache-2.0
*
* pineforge.h — public C ABI for the PineForge runtime.
*
* This header is the single source of truth for the harness ↔ compiled-
* strategy boundary. Every PineForge-generated .so exports a fixed set
* of C symbols declared below; the Python harness (validate_detailed_
* report.py) and any C/C++/FFI consumer of compiled strategies links
* against this contract.
*
* STABILITY GUARANTEE
* ───────────────────
* Within the same PINEFORGE_VERSION_MAJOR, this header's POD struct
* layouts and `extern "C"` symbol signatures are append-only. Fields
* are never reordered, removed, or retyped; new fields may only be
* appended at the end of structs. New functions may be added; existing
* functions are not removed or signature-changed.
*
* Across major versions all bets are off. Bump
* PINEFORGE_VERSION_MAJOR when breaking the ABI.
*
* SCOPE — WHAT THIS HEADER COVERS
* ───────────────────────────────
* ✓ Lifecycle of a compiled strategy (create / destroy)
* ✓ Running a backtest (auto-detect or fully configured)
* ✓ Per-strategy configuration (inputs, overrides, magnifier, trace)
* ✓ The shape of the report returned to the harness
*
* SCOPE — WHAT THIS HEADER DOES NOT COVER (BY DESIGN)
* ───────────────────────────────────────────────────
* ✗ The contract between codegen-emitted strategy code and the runtime
* internals (TA classes, math, series, strategy commands). That
* contract stays C++ — codegen and runtime ship together and are
* versioned in lockstep within the closed transpiler.
* ✗ Source-compiling strategies. Use the closed transpiler binary.
*
* The C++ headers under `<pineforge/engine.hpp>` etc. are *internal*
* implementation surface — not part of this stability guarantee.
*/
#ifndef PINEFORGE_H
#define PINEFORGE_H
#include <stdint.h>
#include <stddef.h>
/* Public C words with enum types must retain their published width even when
* a consumer enables -fshort-enums. The C99 fallback keeps the strict-C99
* header build valid; the two newer languages get a native static assertion. */
#if defined(__cplusplus)
#define PF_STATIC_ASSERT(condition) static_assert((condition), #condition)
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
#define PF_STATIC_ASSERT(condition) _Static_assert((condition), #condition)
#else
#define PF_STATIC_ASSERT_JOIN_(a, b) a##b
#define PF_STATIC_ASSERT_JOIN(a, b) PF_STATIC_ASSERT_JOIN_(a, b)
#define PF_STATIC_ASSERT(condition) \
typedef char PF_STATIC_ASSERT_JOIN(pf_static_assertion_, __LINE__)[(condition) ? 1 : -1]
#endif
/* ── Version ─────────────────────────────────────────────────────── */
/* Macros (PINEFORGE_VERSION_MAJOR / _MINOR / _PATCH / _STRING / _FULL,
* PINEFORGE_GIT_SHA) live in the generated <pineforge/version.h>. */
#include <pineforge/version.h>
/* pf_pending_order_v1_t / pf_field_desc_t -- the generated, C-compatible POD
* mirror of the engine's resting-order record (ABI v4, task 7). Regenerate
* with scripts/gen_pending_order_mirror.py; never edit by hand. */
#include <pineforge/pending_order_mirror.hpp>
/* ── Visibility ──────────────────────────────────────────────────── */
#if defined(_WIN32) || defined(__CYGWIN__)
#if defined(PINEFORGE_BUILD_SHARED)
#define PF_API __declspec(dllexport)
#else
#define PF_API __declspec(dllimport)
#endif
#elif defined(__GNUC__) || defined(__clang__)
#define PF_API __attribute__((visibility("default")))
#else
#define PF_API
#endif
/** Monotonic strategy-module compatibility version. Bumped for layout growth
* or a required module rebuild. Consumers MUST verify
* pf_abi_version() == PF_ABI_VERSION before calling run_backtest.
* pf_report_t is caller-allocated: growth silently corrupts an undersized buffer.
* pf_trade_t is runtime-allocated: growth changes the array stride.
* Value 2 introduced metrics and the equity curve. Modules predating this
* macro have no pf_abi_version symbol; treat dlsym failure as version 1.
* Value 3 appended pf_trade_t::open_at_end (the range-end close
* flag); a v2 reader would misindex every row after the first.
* Value 4 appended live-runtime accessors and the per-bar broker-state
* hash array to pf_report_t.
* Value 5 requires a 1.8.0 module rebuild for the native order layouts,
* without growing the caller-allocated C report/trade layouts.
* Value 6 (1.15.0) appends limit_fill_penetration_ticks to the size-prefixed
* pf_native_run_spec_v1. The caller's report and trade layouts do not change.
* A module stamped 5 must be rebuilt. */
#define PF_ABI_VERSION 6
/** Feature probe for the opt-in split chart/request.security feed boundary.
* When defined, #strategy_set_aux_security_feed is available. */
#define PINEFORGE_HAS_AUX_SECURITY_FEED_V1 1
/** Feature probe for native higher-timeframe request.security feeds.
* When defined, #strategy_set_native_security_feed is available. */
#define PINEFORGE_HAS_NATIVE_SECURITY_FEED_V1 1
/** Feature probe for immutable native-run account-currency FX curves.
* When defined, #strategy_configure_native_fx_curve_v1 is available. */
#define PINEFORGE_HAS_NATIVE_FX_CURVE_V1 1
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup pf_types Types
* @brief POD types and enums passed across the C ABI.
* @{
*/
/** Bar-magnifier sub-bar sampling distribution.
*
* Selects how intra-bar synthetic ticks are placed when the bar
* magnifier is enabled in #run_backtest_full. Layout-compatible with the
* internal C++ `pineforge::MagnifierDistribution` enum class — a
* `static_assert` in `c_abi.cpp` guarantees the integer values match. */
typedef enum pf_magnifier_distribution_e {
PF_MAGNIFIER_UNIFORM = 0, /**< Uniform spacing across the parent bar. */
PF_MAGNIFIER_COSINE = 1, /**< Cosine-tapered density. */
PF_MAGNIFIER_TRIANGLE = 2, /**< Triangle-tapered density. */
PF_MAGNIFIER_ENDPOINTS = 3, /**< Default — exact O,H,L,C points plus uniform fill between. */
PF_MAGNIFIER_FRONT_LOADED = 4, /**< Sample density biased toward bar open. */
PF_MAGNIFIER_BACK_LOADED = 5 /**< Sample density biased toward bar close. */
} pf_magnifier_distribution_t;
/** Single OHLCV bar pushed into the engine.
*
* Layout-compatible with the internal C++ `pineforge::Bar` struct. */
typedef struct pf_bar_s {
double open; /**< Open price. */
double high; /**< High price. */
double low; /**< Low price. */
double close; /**< Close price. */
double volume; /**< Bar volume. */
int64_t timestamp; /**< Bar open time, Unix milliseconds. */
} pf_bar_t;
/** One provider-neutral realtime executed-trade update.
*
* `sequence` is optional: pass 0 when the normalized source has no stable
* ordering key. Non-zero values must increase strictly within a stream.
* `quantity` is expressed in the configured symbol's volume units and is
* accumulated into the input bar's volume. The source adapter owns all
* provider-specific fields and normalization. */
typedef struct pf_trade_tick_s {
int64_t timestamp; /**< Source event time, Unix milliseconds. */
uint64_t sequence; /**< Normalized per-stream sequence, or 0. */
double price; /**< Executed trade price (> 0). */
double quantity; /**< Traded quantity in symbol volume units (>= 0). */
} pf_trade_tick_t;
/** Closed-trade record returned in pf_report_t::trades.
*
* Layout-compatible with internal `pineforge::TradeC`. */
typedef struct pf_trade_s {
int64_t entry_time; /**< Entry fill time (Unix ms). */
int64_t exit_time; /**< Exit fill time (Unix ms). */
double entry_price; /**< Entry fill price (incl. slippage). */
double exit_price; /**< Exit fill price (incl. slippage). */
double pnl; /**< Net realized PnL in account currency (commission-inclusive). */
double pnl_pct; /**< Net return-on-cost in percent: pnl (NET of commission) /
* entry cost (entry_price * qty * pointvalue) * 100. This is
* TradingView's "Net P&L %" convention (synthetic one-unit
* short: 90.00 net PnL on a 2000.00 entry cost =>
* 4.50%). Degenerates to the old gross
* (exit/entry-1)*100 form for longs with zero commission;
* the previous short form (entry/exit-1)*100 was wrong on
* large moves. Sign always matches pnl. */
int is_long; /**< 1 if long, 0 if short. */
double max_runup; /**< Peak favorable whole-trade excursion, account currency, net of entry fees. */
double max_drawdown; /**< Peak adverse whole-trade excursion, account currency, net of entry fees. */
double qty; /**< Filled quantity. */
double commission; /**< Entry+exit commission actually deducted from pnl
* (account currency). pnl is already net of this. */
int32_t entry_bar_index;/**< Script-bar index of the entry fill (0-based). */
int32_t exit_bar_index; /**< Script-bar index of the exit fill (0-based). */
int32_t open_at_end; /**< 1 when this row is the RANGE-END close of a position
* that was still open after the final bar; 0 for an
* exit the script or a bracket produced. TradingView's
* deep-backtest report does not leave the last position
* open: it reports it as a closed trade whose exit leg is
* the range's last bar at that bar's CLOSE, with an
* empty exit Signal, and counts it in closedTrades
* (synthetic NYSE:F daily example: Entry short @ 25.00,
* Exit @ 26.00 on the final daily bar = the last close,
* closedTrades:1). The engine emulates that row
* (operator decision 2026-09-02): exit_time is the last
* script bar's label, exit_price its mintick-rounded
* close with no slippage, commission per the strategy's
* rules, pnl/pnl_pct/excursions as for any close.
* Appended in ABI v3. */
} pf_trade_t;
/** Trade-level statistics block — computed once each for all / long / short.
*
* Loss-side fields (`gross_loss`, `avg_loss`, `largest_loss`) are
* **positive magnitudes** (absolute values of the underlying negative PnL). */
typedef struct pf_trade_stats_s {
int32_t num_trades; /**< Closed trades in this block (all / long-only / short-only). */
int32_t num_wins; /**< Trades with pnl > 0. */
int32_t num_losses; /**< Trades with pnl < 0. */
int32_t num_even; /**< Trades with pnl == 0.0 exactly; breaks both win and loss
* streaks; excluded from win/loss averages.
* Invariant: num_trades == num_wins + num_losses + num_even. */
double percent_profitable; /**< 100 * num_wins / num_trades, in PERCENT (0-100).
* NaN when num_trades == 0. */
double net_profit; /**< Sum of pnl (account currency, net of commission). */
double net_profit_pct; /**< net_profit as a percent of initial capital (0-100 scale).
* NaN when initial capital <= 0. */
double gross_profit; /**< Sum of winning pnl. */
double gross_profit_pct; /**< gross_profit as a percent of initial capital (0-100 scale).
* NaN when initial capital <= 0. */
double gross_loss; /**< Sum of |losing pnl| — POSITIVE magnitude (TV display convention). */
double gross_loss_pct; /**< gross_loss as a percent of initial capital (0-100 scale).
* NaN when initial capital <= 0. */
double profit_factor; /**< gross_profit / gross_loss. NaN when gross_loss == 0. */
double avg_trade; /**< net_profit / num_trades. NaN when num_trades == 0. */
double avg_trade_pct; /**< Mean of per-trade pnl_pct over all trades.
* NaN when num_trades == 0. */
double avg_win; /**< gross_profit / num_wins. NaN when num_wins == 0. */
double avg_win_pct; /**< Mean of per-trade pnl_pct over winning trades.
* NaN when num_wins == 0. */
double avg_loss; /**< gross_loss / num_losses (positive magnitude).
* NaN when num_losses == 0. */
double avg_loss_pct; /**< Mean of the NEGATED pnl_pct of the losing trades. Since
* pnl_pct is net return-on-cost (sign matches pnl), this is
* a genuinely POSITIVE magnitude. Basis = pf_trade_t::pnl_pct.
* NaN when num_losses == 0. */
double ratio_avg_win_avg_loss; /**< avg_win / avg_loss. NaN unless both sides non-empty. */
double largest_win; /**< Single largest pnl among winning trades.
* NaN when num_wins == 0. */
double largest_win_pct; /**< Maximum pnl_pct over winning trades — an INDEPENDENT
* maximum, not the pct of the largest-USD win (TV convention,
* validated 2026-06-12 vs TV export).
* NaN when num_wins == 0. */
double largest_loss; /**< Single largest |pnl| among losing trades (positive magnitude).
* NaN when num_losses == 0. */
double largest_loss_pct; /**< Maximum of -pnl_pct over losing trades (positive magnitude) —
* an INDEPENDENT maximum, not the pct of the largest-USD loss
* (TV convention, validated 2026-06-12 vs TV export: All
* "Largest loss %" came from a different trade than the
* largest USD loss). NaN when num_losses == 0. */
double commission_paid; /**< Sum of pf_trade_t::commission in the block. */
double expectancy; /**< (num_wins/num_trades)*avg_win - (num_losses/num_trades)*avg_loss,
* account currency per trade. NaN when num_trades == 0. */
int32_t max_consecutive_wins; /**< Longest winning run; even trades reset both streaks. */
int32_t max_consecutive_losses; /**< Longest losing run; even trades reset both streaks. */
double avg_bars_in_trade; /**< Mean of (exit_bar_index - entry_bar_index + 1) in SCRIPT
* bars, over all trades — inclusive of the entry bar (TV
* convention, validated 2026-06-12).
* NaN when num_trades == 0. */
double avg_bars_in_wins; /**< Mean bar duration of winning trades, inclusive of the entry
* bar (TV convention, validated 2026-06-12).
* NaN when num_wins == 0. */
double avg_bars_in_losses; /**< Mean bar duration of losing trades, inclusive of the entry
* bar (TV convention, validated 2026-06-12).
* NaN when num_losses == 0. */
} pf_trade_stats_t;
/** Equity-curve-derived statistics (all-trades only, like TV). */
typedef struct pf_equity_stats_s {
double max_equity_drawdown; /**< Peak-to-trough equity drop, positive currency magnitude. */
double max_equity_drawdown_pct; /**< max_equity_drawdown relative to the peak in effect
* (PERCENT 0-100). */
double max_equity_runup; /**< Trough-to-peak rise where the trough resets on each new
* equity peak (mirrors the engine's intra-run extremes). */
double max_equity_runup_pct; /**< max_equity_runup relative to that trough (PERCENT 0-100). */
double buy_hold_return; /**< initial_capital * (last_close/first_open - 1), currency.
* NaN when first chart open is non-finite or <= 0. */
double buy_hold_return_pct; /**< buy_hold_return as PERCENT.
* NaN when first chart open is non-finite or <= 0. */
/** Month-end-resampled equity simple returns (chart timezone, open-time
* bucketing), risk-free 2%/yr (2/12 per month), annualized by sqrt(12).
* Uses sample (N-1) stddev. NaN with <2 monthly returns or zero deviation.
*
* Its pre-1.0 spelling `sharpe_tv` named this same double at this same
* offset (48) and was removed for 1.0; the serialized report key is still
* `sharpe_tv` (report-schema name). */
double sharpe_monthly;
/** Same resampling as sharpe_monthly; uses population downside deviation
* vs the monthly risk-free. NaN with <2 monthly returns or zero deviation.
*
* Its pre-1.0 spelling `sortino_tv` (offset 56) was removed the same way;
* the serialized report key is still `sortino_tv`. */
double sortino_monthly;
double sharpe_bar; /**< Per-script-bar returns, annualized by observed bar density
* (bars per year = (len-1)/calendar span), NOT a fixed
* calendar formula. Uses sample (N-1) stddev.
* NaN with <2 returns or zero deviation. */
double sortino_bar; /**< Same construction as sharpe_bar over per-bar returns;
* uses population downside deviation.
* NaN with <2 returns or zero deviation. */
double cagr; /**< PERCENT per year: 100*((final_equity/initial_capital)^(1/years)-1).
* NaN when span <= 0 or either side <= 0. */
double calmar; /**< cagr / max_equity_drawdown_pct — BOTH IN PERCENT, so the
* ratio is dimensionless. NaN when drawdown is 0. */
double recovery_factor; /**< net_profit / max_equity_drawdown (currency / currency).
* NaN when drawdown is 0. */
double time_in_market_pct; /**< PERCENT (0-100) of script bars with an open position
* at bar close. */
double open_pl; /**< Mark-to-market open profit at the final bar. */
} pf_equity_stats_t;
/** Composite metrics container: trade stats (all / long / short) +
* equity-curve stats. */
typedef struct pf_metrics_s {
pf_trade_stats_t all, longs, shorts;
pf_equity_stats_t equity;
} pf_metrics_t;
/** Single per-script-bar equity point.
*
* `time_ms` is the script-bar **open** timestamp (Unix ms).
* `equity` = `initial_capital` + `net_profit` + `open_profit` at bar close. */
typedef struct pf_equity_point_s {
int64_t time_ms; /**< Script-bar OPEN timestamp (Unix ms). */
double equity; /**< initial_capital + net_profit + open_profit. */
double open_profit; /**< Mark-to-market open P&L at bar close. */
} pf_equity_point_t;
/** Per-`request.security()` site diagnostic counters.
*
* Layout-compatible with internal `pineforge::SecurityDiagC`. */
typedef struct pf_security_diag_s {
int sec_id; /**< Stable id for the request.security site. */
int64_t feed_count; /**< Higher-TF feed bars consumed. */
int64_t complete_count; /**< Evaluations on completed parent bars. */
int64_t partial_count; /**< Evaluations on still-forming parent bars. */
} pf_security_diag_t;
/** Single per-bar trace entry.
*
* Emitted when the source script contains `// @pf-trace name=expr`
* pragmas and tracing is enabled via #strategy_set_trace_enabled.
* Layout-compatible with internal `pineforge::TraceEntryC`. */
typedef struct pf_trace_entry_s {
int64_t timestamp; /**< Bar timestamp (Unix ms). */
int32_t bar_index; /**< Zero-based bar index. */
int32_t name_id; /**< Index into pf_report_t::trace_names. */
double value; /**< Traced expression value on this bar. */
} pf_trace_entry_t;
/** Backtest report filled by #run_backtest / #run_backtest_full.
*
* Layout-compatible with internal `pineforge::ReportC`.
*
* ### Ownership and lifetime
* The struct itself is caller-owned (typically stack). The embedded
* arrays (`trades`, `security_diag`, `trace`, `trace_names`,
* `equity_curve`, `broker_state_hash`) are heap-allocated by the
* runtime; the caller frees each filled report exactly once, with #report_free
* or, on the kernel archive, #strategy_native_report_free_v1. `trace_names`
* strings stay owned by the strategy handle until #strategy_free. */
typedef struct pf_report_s {
/* Trades */
int total_trades; /**< Logical closed-trade count, including
* the range-end close of a position still open
* after the final bar. Equals trades_len on the
* owning-array route; with a sink trades_len is 0.
* The opt-in report envelope declares capture
* separately in <pineforge/report_mode.h>. */
pf_trade_t* trades; /**< Heap array of closed trades; script-driven exits
* first, then the range-end rows (open_at_end=1). */
int trades_len; /**< Resident length of #trades, not the logical total. */
double net_profit; /**< Sum of all closed-trade PnL. */
/* Bar processing counts */
int64_t input_bars_processed; /**< Source-feed bars consumed. */
int64_t script_bars_processed; /**< Script-timeframe bars evaluated. */
/* Security diagnostics */
int64_t security_feeds_total; /**< Total higher-TF feed bars across all security sites. */
int64_t security_complete_total; /**< Total complete-bar evals across all security sites. */
int64_t security_partial_total; /**< Total partial-bar evals across all security sites. */
/* Bar magnifier diagnostics */
int64_t magnifier_sub_bars_total; /**< Sub-bars synthesized by the magnifier. */
int64_t magnifier_sample_ticks_total; /**< Sample ticks visited by the magnifier. */
/* Timeframe metadata */
int input_tf_seconds; /**< Detected/configured input timeframe (seconds). */
int script_tf_seconds; /**< Script timeframe (seconds). */
int script_tf_ratio; /**< script_tf_seconds / input_tf_seconds. */
int needs_aggregation; /**< 1 if input → script TF aggregation was performed. */
int bar_magnifier_enabled; /**< 1 if magnifier was active for this run. */
/* Per-security feed/eval counters */
pf_security_diag_t* security_diag; /**< One entry per request.security site. */
int security_diag_len; /**< Length of #security_diag. */
/* Per-bar trace records */
pf_trace_entry_t* trace; /**< Per-bar trace records (empty unless tracing enabled). */
int trace_len; /**< Length of #trace. */
const char** trace_names; /**< Names indexed by pf_trace_entry_t::name_id. */
int trace_names_len; /**< Length of #trace_names. */
/* Computed trading metrics. Trade-based blocks reported for all /
* long-only / short-only; equity-based stats are all-trades only.
* Loss-side fields are positive magnitudes. Undefined values are NaN
* (see per-field docs). */
pf_metrics_t metrics;
/* Per-script-bar equity curve (bare host: KernelRecorded); time_ms is the script-bar OPEN
* timestamp; equity = initial_capital + net_profit + open_profit at
* bar close. Free via #report_free or #strategy_native_report_free_v1.
* On a completed KernelRecorded run len == script_bars_processed; a
* Failed or Aborted run can expose a shorter prefix (check
* strategy_get_last_error), and metrics describe that prefix. NOTE int64_t
* length (ctypes: c_int64). With a report sink: NULL / 0 length.
* The opt-in <pineforge/report_mode.h> envelope exposes logical point
* count and capture flags separately; this field is resident length. */
pf_equity_point_t* equity_curve;
int64_t equity_curve_len;
/* Per-script-bar broker-state hash when recording is on and report
* points exist (KernelRecorded for a bare native host); freed by
* #report_free or #strategy_native_report_free_v1. NULL / 0-length when off or no points were recorded.
* On a completed run, len == script_bars_processed and the last row
* equals #strategy_broker_state_hash after the run for Pine and bare
* native hosts alike: each point latches the continuation, and the
* scalar folds the last latch. A Failed or Aborted run can have a
* shorter recorded prefix; its last row need not equal the scalar.
* ABI v4. With a report sink: NULL / 0 length. */
uint64_t* broker_state_hash;
int64_t broker_state_hash_len;
} pf_report_t;
/** @} */ /* end of pf_types */
/** Opaque handle to a compiled strategy instance. */
typedef void* pf_strategy_t;
/** @defgroup pf_lifecycle Strategy lifecycle
* @brief 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.
*/
/** What #strategy_execution_contract answers for a valid handle. */
typedef enum pf_execution_contract_e {
PF_EXECUTION_CONTRACT_LEGACY = 1, /**< The retired legacy execution path. */
PF_EXECUTION_CONTRACT_NATIVE_MARKET_V1 = 2 /**< The native market kernel; every
* handle this runtime creates. */
} pf_execution_contract_t;
/** 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. */
PF_API int strategy_execution_contract(pf_strategy_t s);
/** 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. */
typedef enum pf_native_spec_optional_e {
PF_NATIVE_SPEC_OPTIONAL_QUANTITY_GRID = 1u << 0, /**< `quantity_grid`. */
PF_NATIVE_SPEC_OPTIONAL_MAX_ABS_UNITS = 1u << 1, /**< `max_abs_units`. */
PF_NATIVE_SPEC_OPTIONAL_INITIAL_MARGIN_FRACTION = 1u << 2, /**< `initial_margin_fraction`. */
PF_NATIVE_SPEC_OPTIONAL_MAX_OPEN_LOTS = 1u << 3 /**< `max_open_lots`. */
} pf_native_spec_optional_t;
/** Versioned native run specification. All string pointers are non-null.
* session may be empty (all-day literal). session_key, timeframes, timezone
* and tickerid are nonempty. `optional_mask` carries
* #pf_native_spec_optional_t bits.
*
* Its three enum-valued words are named in <pineforge/native_c_api.h>:
* `fee_kind` is a #pf_native_fee_kind_t, `close_execution` a
* #pf_native_close_execution_t and `allowed_open_directions` a
* #pf_native_open_directions_t (zero-filled, that word admits no opening at
* all). #strategy_configure_native_v1 hands the whole value to the kernel,
* which answers an invalid spec with -1 and a Failed native handle
* (PF_NATIVE_FAILURE_INVALID_SPECIFICATION). A Ready handle still fails by
* the kernel's Contract rule. A Running handle is refused at the C boundary
* without changing its native state, including from a callback. A Completed
* handle or one Failed by a cooperative abort may be configured for another
* run outside callbacks; the kernel judges reuse constraints (an aborted
* handle is reused with the same session key and a higher run number), and a
* handle whose configure call failed remains Failed. A Completed
* host's `on_hash_extension` callback cannot reconfigure it during a read-only hash query.
* This call has no typed out-parameters. The
* extended path validates before configuring: #strategy_configure_native_ext_v1
* keeps the handle Unconfigured on a validation refusal, and
* #strategy_configure_native_ext_result_v1 additionally writes the exact
* #pf_native_spec_error_t / #pf_native_spec_field_t pair.
*
* Append-only `struct_size` versioning (within PINEFORGE_VERSION_MAJOR):
* callers set `struct_size = sizeof(pf_native_run_spec_v1)`. Callers compiled
* against the pre-penetration prefix (ending at `max_open_lots`) pass that
* smaller `struct_size` and default `limit_fill_penetration_ticks` to 0;
* any other `struct_size` is refused. */
typedef struct pf_native_run_spec_v1 {
uint32_t struct_size;
const char *session_key; uint64_t run_number;
const char *input_tf, *script_tf;
const char *ticker, *tickerid, *type, *currency, *basecurrency, *description, *volumetype;
const char *timezone, *session, *chart_timezone;
double initial_capital, point_value, account_fx, price_tick;
uint32_t slippage_ticks, fee_kind; double fee_value;
uint32_t optional_mask, close_execution, allowed_open_directions;
double quantity_grid, max_abs_units, initial_margin_fraction;
uint64_t max_open_lots;
uint32_t limit_fill_penetration_ticks;
} pf_native_run_spec_v1;
/** Apply a native v1 specification. Returns 0 on success, -1 on failure.
* Legacy handles refuse without native state mutation. */
PF_API int strategy_configure_native_v1(pf_strategy_t s, const pf_native_run_spec_v1* spec);
/** Immutable timestamped account-currency FX curve for a native run.
* The two arrays have exactly @c n elements and are copied by the runtime. */
typedef struct pf_native_fx_curve_v1 {
uint32_t struct_size;
uint32_t n;
const int64_t* effective_from_ms;
const double* account_per_quote;
} pf_native_fx_curve_v1;
/** 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. */
typedef enum pf_native_fx_curve_error_e {
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
} pf_native_fx_curve_error_t;
PF_STATIC_ASSERT(sizeof(pf_native_fx_curve_error_t) == 4);
/** Stage an immutable account-currency FX curve on a Ready native handle.
*
* Timestamps must be strictly increasing and rates finite and positive.
* Pass @c n == 0 to clear the staged curve; the scalar @c 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.
*
* @return 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. */
PF_API int strategy_configure_native_fx_curve_v1(
pf_strategy_t s, const pf_native_fx_curve_v1* curve);
/** 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. */
PF_API 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);
/* ───────────────────────────────────────────────────────────────────
* STRATEGY .SO EXPORTS — implemented per compiled strategy
* ───────────────────────────────────────────────────────────────────
*
* Each .so emitted by the codegen exports the following symbols. The
* runtime library itself does NOT define them — they are per-strategy
* implementations generated by the transpiler.
*
* Note on naming: these are the legacy unprefixed names retained for
* backward compatibility with the existing harness. Future major
* versions may introduce `pf_`-prefixed equivalents and deprecate the
* unprefixed forms.
*/
#ifndef PINEFORGE_NO_STRATEGY_DECLS
/** Allocate a new strategy instance.
*
* @param params_json Currently ignored; pass `NULL`.
* @return Strategy handle, or `NULL` on allocation failure.
*
* Caller owns the returned handle and must release it via #strategy_free. */
PF_API pf_strategy_t strategy_create(const char* params_json);
/** 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. */
PF_API void strategy_free(pf_strategy_t s);
/** Run a backtest with auto-detected timeframe and no bar magnifier.
*
* @param s Strategy handle from #strategy_create.
* @param bars Non-NULL pointer to OHLCV bars (length @p n).
* @param n Bar count (>= 0).
* @param out Non-NULL output report. Fields are populated with heap
* allocations the caller must release via #report_free. */
PF_API void run_backtest(pf_strategy_t s,
pf_bar_t* bars,
int n,
pf_report_t* out);
/** Run a backtest with explicit timeframe and magnifier configuration.
*
* @param s Strategy handle.
* @param bars Bar feed.
* @param n Bar count.
* @param input_tf Input timeframe ("1", "5", "15", "60", "1D", ...).
* Empty string → auto-detect from bar timestamps.
* @param script_tf Script timeframe. Empty string → defaults to @p input_tf.
* @param bar_magnifier Boolean (0 / non-zero) — enable bar magnifier.
* @param magnifier_samples Sub-bar samples per parent bar (typical: 4).
* @param magnifier_dist Sampling distribution (see #pf_magnifier_distribution_t).
* @param out Output report. Free with #report_free. */
PF_API 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);
/** 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. */
PF_API void report_free(pf_report_t* report);
/** @} */ /* end of pf_lifecycle */
/** @defgroup pf_config Per-strategy configuration
* @brief Override @c input.*() values, `strategy(...)` params, and runtime knobs.
* @{
*/
/** Override a Pine @c input.*() value before the next run.
*
* @param s Strategy handle.
* @param key The input's title (or fallback identifier).
* @param value Serialized value — numbers as decimal strings,
* booleans as `"true"` / `"false"`.
*
* Calls after #run_backtest are accepted but only take effect on
* subsequent runs. */
PF_API void strategy_set_input(pf_strategy_t s,
const char* key,
const char* value);
/** Override a `strategy(...)` declaration parameter.
*
* Recognised @p key values: `initial_capital`, `commission_value`,
* `default_qty_value`, `pyramiding`, `slippage`,
* `process_orders_on_close`, `close_entries_rule`, `default_qty_type`,
* `commission_type`. */
PF_API void strategy_set_override(pf_strategy_t s,
const char* key,
const char* value);
/** Toggle volume-weighted bar-magnifier sampling.
*
* Has no effect unless the bar magnifier is enabled in
* #run_backtest_full. */
PF_API void strategy_set_magnifier_volume_weighted(pf_strategy_t s,
int on);
/** Report the script's `strategy(..., use_bar_magnifier = true)` declaration.
*
* Exported only by a strategy whose declaration is that literal; every
* other `.so` lacks the symbol. TradingView backtests such a script on its
* bar magnifier, so a host runs it on a finer input with the magnifier on
* (#run_backtest_full).
*
* @return 1. */
PF_API int strategy_declares_bar_magnifier(void);
#endif /* PINEFORGE_NO_STRATEGY_DECLS */
/* ───────────────────────────────────────────────────────────────────
* RUNTIME LIBRARY EXPORTS — implemented in libpineforge
* ─────────────────────────────────────────────────────────────────── */
/** Toggle per-bar trace recording. Default off (zero-cost when off).
*
* Enables capture for `// @pf-trace name=expr` pragmas already compiled
* into the strategy `.so`. Trace records appear in pf_report_t::trace. */
PF_API void strategy_set_trace_enabled(pf_strategy_t s, int on);
/** Set the earliest Unix-ms timestamp at which strategy order commands
* may fire.
*
* Earlier bars still execute user code and warm TA/series state, but
* `strategy.entry/order/exit/close` commands are ignored. */
PF_API void strategy_set_trade_start_time(pf_strategy_t s, int64_t timestamp_ms);
/** @} */ /* end of pf_config */
/** @addtogroup pf_lifecycle
* @{
*/
/** 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. */
PF_API int pf_report_scratch_arena_stats(uint64_t* high_water_bytes,
uint64_t* arena_bytes);
/** 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. */
PF_API int pf_report_cache_stats(pf_strategy_t s, uint64_t* resident_bytes,
uint64_t* allocation_bypass_count);
/** 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. */
PF_API int strategy_require_report_scratch_arena_v1(pf_strategy_t s);
struct pf_report_sink_diagnostics_v1;
/** 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. */
PF_API int strategy_report_sink_diagnostics_v1(
pf_strategy_t s, struct pf_report_sink_diagnostics_v1* out);
/** 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. */
PF_API int pf_run_abort_install_sigterm_v1(void);
/** Read the invocation stop flag: 0 or 1. No allocation or state mutation. */
PF_API int pf_run_abort_requested_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. */
PF_API int pf_run_abort_restore_sigterm_v1(void);
/** 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.
*
* @param s Strategy handle whose most recent run filled a report.
* @param trade_index Zero-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.
* @return Non-zero physical-entry identity, or 0 for an invalid index or a
* legacy/synthetic trade without request record provenance. */
PF_API uint64_t strategy_closed_trade_entry_incarnation(
pf_strategy_t s, int trade_index);
/** @} */ /* end of pf_lifecycle */
/** @defgroup pf_streaming Historical to realtime streaming
* @brief Warm on confirmed OHLCV and continue the same strategy instance on
* normalized ordered trades from any data source.
* @{
*/
/** Warm a strategy with confirmed OHLCV, then switch the same instance to a
* realtime trade stream without resetting position, equity, pending orders,
* Pine variables, TA state, request.security state, or timeframe aggregation.
*
* The warmup must contain at least one complete fixed-duration input bar.
* Normalized ticks start at or after the next input bar's open. This
* lifecycle uses close-only strategy calculation (the Pine strategy default)
* while resting broker orders are evaluated on every normalized trade.
*
* A generated Pine strategy using this entry point rejects calc_on_order_fills,
* historical probe/tail overrides, timestamped FX and auxiliary/native
* security feeds. A C native host can also use this entry point and accepts
* the native FX curve, auxiliary feeds and calculation trigger where its
* run specification permits them.
* @return 0 on success, -1 on failure. Inspect #strategy_get_last_error. */
PF_API int strategy_stream_begin(pf_strategy_t s,
const pf_bar_t* warmup_bars,
int n_warmup,
const char* input_tf,
const char* script_tf);
/** Native live extension version (1). Additive to ABI v4; callers must probe
* this symbol before using the confirmed-bar/action API in older modules. */
PF_API int strategy_stream_api_version(void);
/** One physical emulator lot action. is_long describes the position side:
* buy = is_entry == is_long. A reversal is exits followed by an entry.
* price/time are emulator reference values, not external broker fills.
* Strings are borrowed until the next stream mutation or queue clear. */
typedef struct pf_stream_order_action {
uint64_t sequence;
int64_t timestamp_ms;
int32_t bar_index;
int32_t is_entry;
int32_t is_long;
double quantity;
double price;
const char* order_id;
const char* comment;
uint64_t entry_incarnation;
} pf_stream_order_action_t;
/** Consume one confirmed input-timeframe bar. Its script-timeframe aggregate
* uses the existing batch OHLC fill kernel when complete. Close-only strategy
* calculation; no bar magnifier or synthetic trade ticks. The first tick/bar
* locks the feed mode. Off-grid/out-of-order data, invalid OHLCV and missing
* in-session bars fail. Calendar-closed intervals may be skipped. No padding.
* Returns 0/-1. On ANY input-processing failure discard/recover the instance:
* the operation is not transactional and can have advanced native state. */
PF_API int strategy_stream_push_bar(pf_strategy_t s, const pf_bar_t* bar);
/** Queued physical fills since the last clear, in execution order. Historical
* warmup and report-only range-end rows never enqueue. Sequence starts at 1
* after warmup and is not reset by clear. Returns -1 on a null handle. */
PF_API int strategy_stream_order_actions_len(pf_strategy_t s);
/** Copy one action; return 0 on success, -1 on invalid handle/index/output. */
PF_API int strategy_stream_order_action_get(pf_strategy_t s, int index,
pf_stream_order_action_t* out);
/** Clear observed events after the caller durably journals them. */
PF_API void strategy_stream_order_actions_clear(pf_strategy_t s);
/** Versioned deterministic fingerprint of observable broker/stream state.
* Excludes the consumable queue and arbitrary private strategy members.
* This is a replay check, not a complete state snapshot or cryptographic hash.
* Fresh replay must use deterministic strategy code, the same pinned engine
* build and configuration. The fingerprint's recipe belongs to the script
* ABI epoch: from 1.0.0 it is fixed for every 1.x engine
* (engine_script_run_v19 to 1.10, then v20), and a new recipe is a new epoch; a value from a
* build before 1.0.0 is not comparable. Returns 0 for NULL.
*
* A refused read also returns 0, so a 0 alone does not tell it from an
* answer: a handle that carries selected-window provenance refuses this
* query once its run has sealed, and #strategy_state_query_status_v1 names
* that refusal. The recorded broker-state rows
* (#strategy_set_broker_state_hash_recording) are not values of this token:
* it has no recorded counterpart, so a refused read leaves no witness. */
PF_API uint64_t strategy_stream_state_hash(pf_strategy_t s);
/** Push one normalized realtime trade. Returns 0 on success, -1 on failure. */
PF_API int strategy_stream_push_tick(pf_strategy_t s,
const pf_trade_tick_t* tick);
/** Push an ordered batch of realtime trades. Semantically identical to
* repeated #strategy_stream_push_tick calls, with lower FFI overhead. */
PF_API int strategy_stream_push_ticks(pf_strategy_t s,
const pf_trade_tick_t* ticks,
int n);
/** Advance the stream clock and close every input bar whose end is <= the
* supplied time. Quiet in-session intervals become zero-volume carry-forward
* bars; intervals outside the configured syminfo session are skipped. */
PF_API int strategy_stream_advance_time(pf_strategy_t s, int64_t timestamp_ms);
/** End a realtime stream. When @p finalize_partial_input_bar is non-zero, the
* currently forming input bar is dispatched before ending; normally callers
* should first advance to a confirmed boundary and pass zero here. */
PF_API int strategy_stream_end(pf_strategy_t s, int finalize_partial_input_bar);
/** Snapshot the cumulative warmup + realtime report. The embedded arrays are
* caller-owned after return and must be released with #report_free, or with
* #strategy_native_report_free_v1 by a host that links the kernel archive,
* which has no #report_free. After #strategy_release_run_results_v1, returns
* nonzero with `engine_invariant` and publishes no arrays. */
PF_API int strategy_stream_fill_report(pf_strategy_t s, pf_report_t* out);
/** @} */ /* end of pf_streaming */
/** @defgroup pf_live Live-runtime surface (ABI v4)
* Default-off flags and read-only accessors used by pineforge-live. None of
* them changes a historical run unless enabled. @{ */
#define PINEFORGE_HAS_SCRATCH_TABLES_V1 1
#define PINEFORGE_HAS_CACHE_POLICY_V1 1
/** Append-only cache-kind vocabulary. Zero is reserved and is rejected as
* an unknown kind. Values are contiguous, starting at one; new kinds take
* the next unused value and existing values are never renumbered.
* A kind whose cache a later release deletes remains accepted as a
* documented retired no-op, never an unknown-kind error. */
typedef uint32_t pf_cache_kind_t;
#define PF_CACHE_KIND_LEDGER_CACHE 1u
#define PF_CACHE_KIND_TRADE_PAGES 2u
#define PF_CACHE_KIND_DEPENDENCY_PAGES 3u
#define PF_CACHE_KIND_EXIT_PAGES 4u
#define PF_CACHE_KIND_BOOK_PAGES 5u
#define PF_CACHE_KIND_RETAINED_SEQUENCE_PAGES 6u
#define PF_CACHE_KIND_COHORT_ID_PAGES 7u
#define PF_CACHE_KIND_EXIT_RANK_PAGES 8u
#define PF_CACHE_KIND_ERASED_MINIMA_PAGES 9u
#define PF_CACHE_KIND_CONSUMED_CYCLE_PAGES 10u
#define PF_CACHE_KIND_POSITION_TAIL_PAGES 11u
#define PF_CACHE_KIND_SUCCESSOR_ROOT_PAGES 12u
#define PF_CACHE_KIND_RECEIPT_TAIL_PAGES 13u
#define PF_CACHE_KIND_CHAIN_SEGMENT_PAGES 14u
#define PF_CACHE_KIND_EQUITY_CURVE_PAGES 15u
#define PF_CACHE_KIND_TA_HISTORY_PAGES 16u
#define PF_CACHE_KIND_FEED_CALENDAR_PAGES 17u
#define PF_CACHE_KIND_RECORDED_SERIES_PAGES 18u
#define PF_CACHE_KIND_PROJECTION_EXIT_PAGES 19u
/** One optional resident cache size. Ordinary C alignment applies: kind is
* uint32_t and capacity_bytes is uint64_t, with no packed wire layout.
* Every capacity is in bytes. For PF_CACHE_KIND_LEDGER_CACHE, the engine
* selects the largest row count R with
* R * TradeLedger::kLedgerEntryBytes + ceil(R / 256) * sizeof(void*) <= capacity_bytes
* (312 bytes per decoded entry and 8 bytes per page pointer on LP64).
* Omitting this entry selects the provisional default of 67,108,864 bytes
* (64 MiB), which holds 215,070 entries on LP64 and never grows with the
* retained history; a failed optional allocation retries only after the
* retained population has doubled since the failed attempt, and the first
* failure remains observable until clear. Retirement and a rewind release
* every optional page. Every present ledger entry selects an explicit finite
* row policy, including an allowance equal to the default or to 65,536 rows
* (20,449,280 bytes on LP64).
* Zero selects the existing zero-row
* bypass minimum. A nonzero capacity converting to fewer than one row fails
* with setting_rejected, input="cache_policy", reason="value_below_minimum";
* above the existing 1,048,576-row ceiling it fails with the same input and
* reason="value_above_maximum". No clamping or sub-row bypass occurs.
* The ledger keeps private pages; its allowance includes their page directory.
* Allocated pointers and pages are reported once in cache resident bytes.
* A finite policy's optional directory/page allocation failure permanently
* bypasses further allocation for that ledger, preserving backing reads and
* writes. The omitted default keeps its old hits on a failed allocation and
* retries as described above; its first allocation failure remains
* observable until clear. Required backing I/O failures still propagate.
* Other kinds include optional line metadata in their byte allowances and
* bypass when below one line. Reads still use backing at zero capacity.
* reserved must be zero; a nonzero word is a typed setting_rejected error. */
typedef struct pf_cache_policy_entry_v1 {
uint32_t kind;
uint32_t reserved;
uint64_t capacity_bytes;
} pf_cache_policy_entry_v1;
/** Versioned resident cache policy. Set struct_size = sizeof(pf_cache_policy_v1)
* and version = 1; both reserved words and every entry's reserved word must
* be zero. Nonzero reserved words fail with setting_rejected,
* input="cache_policy", reason="unparseable_value".
* The caller owns this descriptor and its entries; the setter copies their
* values before returning and retains neither pointer.
* entry_count is a uint64_t count; entries may be NULL only when it is zero.
* Each successful replacement starts from internal defaults, then applies
* the entries. Omitted kinds use defaults (the 64 MiB ledger default); duplicate
* and unknown kinds fail. NULL/empty descriptors restore the ledger default.
* No entry limits logical records, retained history or backing extent. */
typedef struct pf_cache_policy_v1 {
uint32_t struct_size;
uint32_t version;