Repository navigation
Expand file tree
/
Copy pathc_abi.cpp
More file actions
1749 lines (1594 loc) · 82.9 KB
/
Copy pathc_abi.cpp
File metadata and controls
1749 lines (1594 loc) · 82.9 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
/*
* c_abi.cpp — runtime-side implementation of the public C ABI declared
* in <pineforge/pineforge.h>.
*
* Contains:
* - Layout-compatibility static_asserts between the public C PODs
* and the internal C++ types they mirror. If any of these trip,
* the C ABI has drifted from the internal representation — fix
* BEFORE shipping a .so that consumers depend on.
* - The runtime-library-side `extern "C"` symbols (the closed-trade
* incarnation accessor, setters, strategy_get_last_error,
* strategy_get_last_error_code, strategy_get_last_error_args,
* strategy_get_run_warnings, the
* security-feed and symbol-data setters (including the borrowed feed
* export), the strategy_stream_*
* lifecycle, the strategy_outputs_* readers, native stream bar
* input/action polling/fingerprint/API-version exports, strategy_stream_engine_layout_version, the live-runtime
* surface (strategy_request_abort, strategy_last_run_status,
* strategy_set_realtime_tail, strategy_set_probe_suppress_tail_logic,
* strategy_set_path_order, strategy_last_bar_dual_entry_path,
* strategy_set_broker_state_hash_recording, strategy_broker_state_hash,
* strategy_state_query_status_v1,
* strategy_pending_orders_len, strategy_pending_order_get,
* strategy_pending_order_layout, strategy_pending_order_fill_qty,
* strategy_pending_order_level_resolved,
* strategy_pending_order_effective_levels, strategy_trail_best_price,
* strategy_position_avg_price, strategy_position_cycle_seq,
* strategy_closed_trade_entry_id, strategy_closed_trade_entry_comment,
* strategy_closed_trade_exit_id, strategy_closed_trade_exit_comment,
* strategy_closed_trade_close_cause,
* strategy_release_run_results_v1 (completed run scratch release),
* strategy_position_size, strategy_current_equity,
* strategy_initial_capital, strategy_net_profit_sum,
* strategy_report_pointvalue, strategy_set_report_replay_v1,
* strategy_script_bars_processed), pf_output_series_limit_set_checked/pf_output_series_limit_failure,
* pf_map_pairs_limit_set_checked, pf_ta_lookback_limit_set_checked,
* strategy_set_account_currency_fx_scalar, pf_version_get/pf_version_string,
* pf_abi_version, strategy_execution_contract,
* strategy_configure_native_v1, strategy_configure_native_fx_curve_v1,
* strategy_configure_native_fx_curve_ext_v1,
* pf_execution_observer_version, strategy_set_execution_observer_v1,
* strategy_execution_observation_v1, pf_selected_window_version, pf_report_sink_version,
* strategy_set_selected_window_v1, strategy_selected_window_counts_v1,
* strategy_set_report_sink_v1, strategy_set_report_sink_fd_v1, strategy_report_sink_receipt_v1,
* strategy_set_scratch_tables_v1, strategy_set_scratch_live_order_ids_limit_v1,
* strategy_report_sink_summary_v1, strategy_set_cache_policy_v1, strategy_set_scratch_io_policy_v1,
* pf_report_scratch_arena_stats, pf_report_cache_stats,
* strategy_require_report_scratch_arena_v1,
* strategy_report_sink_diagnostics_v1,
* pf_run_abort_install_sigterm_v1, pf_run_abort_requested_v1,
* pf_run_abort_restore_sigterm_v1 — the
* authoritative list is EXPECTED_RUNTIME in scripts/check_c_abi_runtime.py (CI). Other
* `extern "C"` symbols listed in pineforge.h (strategy_create,
* run_backtest, etc.) are emitted per-compiled-strategy by the
* codegen, not here.
*/
// Include order is load-bearing: pineforge.h BEFORE engine.hpp keeps the
// per-strategy declarations visible so definitions here are prototype-checked.
// engine.hpp defines PINEFORGE_NO_STRATEGY_DECLS, which suppresses them. The
// two v1 headers follow pineforge.h for the same reason.
#include <pineforge/pineforge.h>
#include <pineforge/execution_observer.h>
#include <pineforge/selected_window.h>
#include <pineforge/engine.hpp>
#include <pineforge/native_host.hpp>
#include <pineforge/run_failure.hpp>
#include <pineforge/query_refusal.hpp>
#include <pineforge/map_capacity.hpp>
#include <pineforge/detail/scratch_arena.hpp>
#include <pineforge/bar.hpp>
#include <pineforge/magnifier.hpp>
#include <cstddef>
#include <cstdint>
#include <cerrno>
#include <limits>
#include <cstring>
#include <exception>
#include <string>
#include <utility>
#include <vector>
#include <signal.h>
#include "run_abort.hpp"
#include "retired_trade_history_read.hpp"
#include "native_execution_consumer.hpp"
#include "run_results_errors.hpp"
namespace pineforge {
void clear_native_c_host_refusal_error(BacktestEngine* engine) noexcept;
bool native_c_host_in_postrun_hook_frame(BacktestEngine* engine) noexcept;
inline namespace engine_script_run_v20 { void native_stream_snapshot_report(BacktestEngine* engine, ReportC* out); }
inline namespace engine_script_run_v20 { bool native_selected_query_closed(const BacktestEngine* engine) noexcept; }
inline namespace engine_script_run_v20 {
const char* native_run_warnings(const BacktestEngine*) noexcept;
// The private bridges behind the execution observer and selected-window
// exports at the end of this file. The native consumer defines them and owns
// every null, size, version and state check; the exports only delegate.
int native_set_execution_observer_v1(BacktestEngine*, const pf_execution_observer_v1*) noexcept;
int native_execution_observation_v1(const BacktestEngine*, pf_execution_observation_v1*) noexcept;
int native_set_selected_window_v1(BacktestEngine*, const pf_selected_window_config_v1*) noexcept;
int native_selected_window_counts_v1(const BacktestEngine*, pf_selected_window_counts_v1*) noexcept;
void native_latch_void_setter_refusal(BacktestEngine*, const std::exception*) noexcept;
}
}
namespace {
volatile sig_atomic_t run_sigterm_stop = 0;
struct sigaction previous_sigterm {};
bool sigterm_installed = false;
void run_sigterm_handler(int) noexcept {
run_sigterm_stop = 1;
}
/* A refusal that escaped a non-void C entry point as an exception: its what() and
* its run-failure code (run_failure.hpp) beside the handle, so a refusal reads
* back the reason through strategy_get_last_error / _code. A NULL handle has
* nowhere to keep it, and a handle whose run already failed keeps that run's
* own text and code. Never throws: it runs on the C boundary. */
void note_cabi_refusal(pf_strategy_t s, const std::exception* error) noexcept {
if (!s) return;
try {
auto& engine = *static_cast<pineforge::BacktestEngine*>(s);
if (engine.last_run_status() != 0
&& pineforge::run_failure_value_of(engine).code != pineforge::RunFailureCode::none) {
return;
}
if (error) {
pineforge::note_run_failure(engine, std::string(error->what()),
pineforge::classify_run_failure(*error));
} else {
pineforge::note_run_failure(engine, "unknown C++ exception",
pineforge::RunFailureCode::engine_unclassified_error);
}
} catch (...) {
}
}
template <typename Fn>
void pf_cabi_void(pf_strategy_t s, Fn&& fn) noexcept {
try {
std::forward<Fn>(fn)();
} catch (const pineforge::SelectedWindowQueryAfterSeal&) {
// A documented refusal, observed through strategy_state_query_status_v1.
// It leaves the run's error, status and first cause untouched.
} catch (const std::exception& error) {
if (s) pineforge::native_latch_void_setter_refusal(
static_cast<pineforge::BacktestEngine*>(s), &error);
} catch (...) {
if (s) pineforge::native_latch_void_setter_refusal(
static_cast<pineforge::BacktestEngine*>(s), nullptr);
}
}
template <typename Fn>
int pf_cabi_int(pf_strategy_t s, Fn&& fn) noexcept {
try {
return std::forward<Fn>(fn)();
} catch (const std::exception& error) {
note_cabi_refusal(s, &error);
return -1;
} catch (...) {
note_cabi_refusal(s, nullptr);
return -1;
}
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wswitch"
#endif
pf_native_fx_curve_error_t fx_curve_error_word(
pineforge::NativeFxCurveError error) noexcept {
switch (error) {
case pineforge::NativeFxCurveError::None:
return PF_NATIVE_FX_CURVE_ERROR_NONE;
case pineforge::NativeFxCurveError::LengthMismatch:
return PF_NATIVE_FX_CURVE_ERROR_LENGTH_MISMATCH;
case pineforge::NativeFxCurveError::NotStrictlyIncreasing:
return PF_NATIVE_FX_CURVE_ERROR_NOT_STRICTLY_INCREASING;
case pineforge::NativeFxCurveError::NotFinitePositive:
return PF_NATIVE_FX_CURVE_ERROR_NOT_FINITE_POSITIVE;
case pineforge::NativeFxCurveError::AllocationFailure:
return PF_NATIVE_FX_CURVE_ERROR_ALLOCATION_FAILURE;
case pineforge::NativeFxCurveError::WrongPhase:
return PF_NATIVE_FX_CURVE_ERROR_WRONG_PHASE;
}
std::terminate();
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
int configure_native_fx_curve_cabi(
pf_strategy_t s, const pf_native_fx_curve_v1* curve,
pf_native_fx_curve_error_t* error, std::uint64_t* index) noexcept {
return pf_cabi_int(s, [&] {
if (!s) return -1;
auto* engine = static_cast<pineforge::BacktestEngine*>(s);
if (!engine->native_bound()) return -1;
auto* host = dynamic_cast<pineforge::NativeStrategyHost*>(engine);
if (!host) return -1;
pineforge::clear_native_c_host_refusal_error(engine);
if (!curve) return -1;
if (curve->struct_size != sizeof(pf_native_fx_curve_v1)) return -1;
if (curve->n > 0 && (!curve->effective_from_ms || !curve->account_per_quote)) return -1;
pineforge::NativeFxCurve cpp;
if (curve->n > 0) {
const std::size_t n = curve->n;
cpp.effective_from_ms.assign(curve->effective_from_ms,
curve->effective_from_ms + n);
cpp.account_per_quote.assign(curve->account_per_quote,
curve->account_per_quote + n);
}
const auto result = host->configure_native_fx_curve(cpp);
if (error) *error = fx_curve_error_word(result.validation.error);
if (index) *index = static_cast<std::uint64_t>(result.validation.index);
return result.status == pineforge::NativeSetupStatus::Applied ? 0 : -1;
});
}
} // namespace
namespace pineforge {
const pf_field_desc_t* pending_order_layout(int* count);
} // namespace pineforge
static_assert(offsetof(pf_cache_policy_v1, struct_size) == 0,
"cache policy size must be the first field");
static_assert(offsetof(pf_cache_policy_entry_v1, kind) == 0,
"cache policy entry kind must be the first field");
static_assert(sizeof(void*) != 8 ||
(sizeof(pf_cache_policy_entry_v1) == 16
&& alignof(pf_cache_policy_entry_v1) == 8
&& offsetof(pf_cache_policy_entry_v1, reserved) == 4
&& offsetof(pf_cache_policy_entry_v1, capacity_bytes) == 8
&& sizeof(pf_cache_policy_v1) == 32
&& alignof(pf_cache_policy_v1) == 8
&& offsetof(pf_cache_policy_v1, version) == 4
&& offsetof(pf_cache_policy_v1, entry_count) == 8
&& offsetof(pf_cache_policy_v1, entries) == 16
&& offsetof(pf_cache_policy_v1, reserved) == 24),
"cache policy LP64 layout must match the host descriptor");
/* ── Bar layout parity ──────────────────────────────────────────── */
static_assert(sizeof(pf_bar_t) == sizeof(pineforge::Bar),
"pf_bar_t / pineforge::Bar size mismatch");
static_assert(offsetof(pf_bar_t, open) == offsetof(pineforge::Bar, open),
"pf_bar_t::open offset mismatch");
static_assert(offsetof(pf_bar_t, high) == offsetof(pineforge::Bar, high),
"pf_bar_t::high offset mismatch");
static_assert(offsetof(pf_bar_t, low) == offsetof(pineforge::Bar, low),
"pf_bar_t::low offset mismatch");
static_assert(offsetof(pf_bar_t, close) == offsetof(pineforge::Bar, close),
"pf_bar_t::close offset mismatch");
static_assert(offsetof(pf_bar_t, volume) == offsetof(pineforge::Bar, volume),
"pf_bar_t::volume offset mismatch");
static_assert(offsetof(pf_bar_t, timestamp) == offsetof(pineforge::Bar, timestamp),
"pf_bar_t::timestamp offset mismatch");
/* ── Normalized trade-tick layout parity ───────────────────────── */
static_assert(sizeof(pf_trade_tick_t) == sizeof(pineforge::TradeTick),
"pf_trade_tick_t / pineforge::TradeTick size mismatch");
static_assert(offsetof(pf_trade_tick_t, timestamp)
== offsetof(pineforge::TradeTick, timestamp),
"pf_trade_tick_t::timestamp offset mismatch");
static_assert(offsetof(pf_trade_tick_t, sequence)
== offsetof(pineforge::TradeTick, sequence),
"pf_trade_tick_t::sequence offset mismatch");
static_assert(offsetof(pf_trade_tick_t, price)
== offsetof(pineforge::TradeTick, price),
"pf_trade_tick_t::price offset mismatch");
static_assert(offsetof(pf_trade_tick_t, quantity)
== offsetof(pineforge::TradeTick, quantity),
"pf_trade_tick_t::quantity offset mismatch");
/* ── Trade layout parity ────────────────────────────────────────── */
static_assert(sizeof(pf_trade_t) == sizeof(pineforge::TradeC),
"pf_trade_t / pineforge::TradeC size mismatch");
static_assert(offsetof(pf_trade_t, entry_time) == offsetof(pineforge::TradeC, entry_time),
"pf_trade_t::entry_time offset mismatch");
static_assert(offsetof(pf_trade_t, exit_time) == offsetof(pineforge::TradeC, exit_time),
"pf_trade_t::exit_time offset mismatch");
static_assert(offsetof(pf_trade_t, entry_price) == offsetof(pineforge::TradeC, entry_price),
"pf_trade_t::entry_price offset mismatch");
static_assert(offsetof(pf_trade_t, qty) == offsetof(pineforge::TradeC, qty),
"pf_trade_t::qty offset mismatch");
static_assert(offsetof(pf_trade_t, commission) == offsetof(pineforge::TradeC, commission),
"pf_trade_t::commission offset mismatch");
static_assert(offsetof(pf_trade_t, entry_bar_index) == offsetof(pineforge::TradeC, entry_bar_index),
"pf_trade_t::entry_bar_index offset mismatch");
static_assert(offsetof(pf_trade_t, exit_bar_index) == offsetof(pineforge::TradeC, exit_bar_index),
"pf_trade_t::exit_bar_index offset mismatch");
static_assert(offsetof(pf_trade_t, open_at_end) == offsetof(pineforge::TradeC, open_at_end),
"pf_trade_t::open_at_end offset mismatch");
/* ── SecurityDiag layout parity ─────────────────────────────────── */
/* The middle two fields differ in name (complete_count / partial_count
* vs the internal C++ names) but layout is identical. Size + first +
* last field offsets cover the whole struct. */
static_assert(sizeof(pf_security_diag_t) == sizeof(pineforge::SecurityDiagC),
"pf_security_diag_t / pineforge::SecurityDiagC size mismatch");
static_assert(offsetof(pf_security_diag_t, sec_id) == offsetof(pineforge::SecurityDiagC, sec_id),
"pf_security_diag_t::sec_id offset mismatch");
static_assert(offsetof(pf_security_diag_t, feed_count) == offsetof(pineforge::SecurityDiagC, feed_count),
"pf_security_diag_t::feed_count offset mismatch");
/* ── TraceEntry layout parity ───────────────────────────────────── */
static_assert(sizeof(pf_trace_entry_t) == sizeof(pineforge::TraceEntryC),
"pf_trace_entry_t / pineforge::TraceEntryC size mismatch");
static_assert(offsetof(pf_trace_entry_t, timestamp) == offsetof(pineforge::TraceEntryC, timestamp),
"pf_trace_entry_t::timestamp offset mismatch");
static_assert(offsetof(pf_trace_entry_t, value) == offsetof(pineforge::TraceEntryC, value),
"pf_trace_entry_t::value offset mismatch");
/* ── Report layout parity ───────────────────────────────────────── */
static_assert(sizeof(pf_report_t) == sizeof(pineforge::ReportC),
"pf_report_t / pineforge::ReportC size mismatch");
static_assert(offsetof(pf_report_t, total_trades) == offsetof(pineforge::ReportC, total_trades),
"pf_report_t::total_trades offset mismatch");
static_assert(offsetof(pf_report_t, trades) == offsetof(pineforge::ReportC, trades),
"pf_report_t::trades offset mismatch");
static_assert(offsetof(pf_report_t, net_profit) == offsetof(pineforge::ReportC, net_profit),
"pf_report_t::net_profit offset mismatch");
static_assert(offsetof(pf_report_t, security_diag) == offsetof(pineforge::ReportC, security_diag),
"pf_report_t::security_diag offset mismatch");
static_assert(offsetof(pf_report_t, trace_names_len) == offsetof(pineforge::ReportC, trace_names_len),
"pf_report_t::trace_names_len tail offset mismatch");
static_assert(offsetof(pf_report_t, metrics) == offsetof(pineforge::ReportC, metrics),
"pf_report_t::metrics offset mismatch");
static_assert(offsetof(pf_report_t, equity_curve) == offsetof(pineforge::ReportC, equity_curve),
"pf_report_t::equity_curve offset mismatch");
static_assert(offsetof(pf_report_t, equity_curve_len) == offsetof(pineforge::ReportC, equity_curve_len),
"pf_report_t::equity_curve_len offset mismatch");
static_assert(offsetof(pf_report_t, broker_state_hash) == offsetof(pineforge::ReportC, broker_state_hash),
"pf_report_t::broker_state_hash offset mismatch");
static_assert(offsetof(pf_report_t, broker_state_hash_len) == offsetof(pineforge::ReportC, broker_state_hash_len),
"pf_report_t::broker_state_hash_len offset mismatch");
/* ── Equity-stats layout (R5 gap lane P2c; removal for 1.0, lane REL10) ── */
/* sharpe_monthly / sortino_monthly are plain doubles again: their pre-1.0
* spellings sharpe_tv / sortino_tv, which shared that storage through an
* anonymous union, were removed for 1.0. These assertions pin the numbers
* measured on 1974e87e, the commit before the union (arm64 macOS and the
* LP64 C ABI generally): sizeof 120, the pair at 48 and 56, and
* pf_metrics_t::equity at 648. Neither the union nor its removal moved an
* offset or a size. */
static_assert(sizeof(pf_equity_stats_t) == 120,
"pf_equity_stats_t size moved");
static_assert(offsetof(pf_equity_stats_t, sharpe_monthly) == 48,
"pf_equity_stats_t::sharpe_monthly offset moved");
static_assert(offsetof(pf_equity_stats_t, sortino_monthly) == 56,
"pf_equity_stats_t::sortino_monthly offset moved");
static_assert(offsetof(pf_equity_stats_t, sharpe_bar) == 64,
"pf_equity_stats_t::sharpe_bar offset moved");
static_assert(offsetof(pf_equity_stats_t, open_pl) == 112,
"pf_equity_stats_t::open_pl tail offset moved");
static_assert(offsetof(pf_metrics_t, equity) == 648,
"pf_metrics_t::equity offset moved");
static_assert(sizeof(pf_metrics_t) == 768, "pf_metrics_t size moved");
/* ── Magnifier distribution enum parity ─────────────────────────── */
static_assert(static_cast<int>(pineforge::MagnifierDistribution::UNIFORM) == PF_MAGNIFIER_UNIFORM,
"MagnifierDistribution::UNIFORM enum value mismatch");
static_assert(static_cast<int>(pineforge::MagnifierDistribution::COSINE) == PF_MAGNIFIER_COSINE,
"MagnifierDistribution::COSINE enum value mismatch");
static_assert(static_cast<int>(pineforge::MagnifierDistribution::TRIANGLE) == PF_MAGNIFIER_TRIANGLE,
"MagnifierDistribution::TRIANGLE enum value mismatch");
static_assert(static_cast<int>(pineforge::MagnifierDistribution::ENDPOINTS) == PF_MAGNIFIER_ENDPOINTS,
"MagnifierDistribution::ENDPOINTS enum value mismatch");
static_assert(static_cast<int>(pineforge::MagnifierDistribution::FRONT_LOADED) == PF_MAGNIFIER_FRONT_LOADED,
"MagnifierDistribution::FRONT_LOADED enum value mismatch");
static_assert(static_cast<int>(pineforge::MagnifierDistribution::BACK_LOADED) == PF_MAGNIFIER_BACK_LOADED,
"MagnifierDistribution::BACK_LOADED enum value mismatch");
/* ───────────────────────────────────────────────────────────────────
* Runtime-library-side extern "C" implementations.
*
* These live in libpineforge.a (statically linked into every compiled
* strategy .so), so consumers find them via dlsym on any .so. The
* other extern "C" symbols listed in pineforge.h are emitted PER
* STRATEGY by the codegen (in emit_top.py::_emit_extern_c).
* ─────────────────────────────────────────────────────────────────── */
namespace pineforge {
bool run_sigterm_requested() noexcept {
return sigterm_installed && run_sigterm_stop != 0;
}
} // namespace pineforge
extern "C" {
PF_API int pf_run_abort_install_sigterm_v1(void) {
// The caller blocks SIGTERM across installation. Repeated installation
// must not clear a cancellation that already arrived.
if (sigterm_installed) return 0;
struct sigaction action {};
action.sa_handler = run_sigterm_handler;
action.sa_flags = SA_RESTART;
if (sigemptyset(&action.sa_mask) != 0) return -1;
run_sigterm_stop = 0;
if (::sigaction(SIGTERM, &action, &previous_sigterm) != 0) return -1;
sigterm_installed = true;
return 0;
}
PF_API int pf_run_abort_requested_v1(void) {
return pineforge::run_sigterm_requested() ? 1 : 0;
}
PF_API int pf_run_abort_restore_sigterm_v1(void) {
if (!sigterm_installed) return 0;
if (::sigaction(SIGTERM, &previous_sigterm, nullptr) != 0) return -1;
sigterm_installed = false;
return 0;
}
/* trade_index is a REPORT row index: pf_report_t::trades is trades_ followed
* by range_end_trades_ (fill_trades_section, engine_report.cpp), so the
* accessor uses closed_trade_close_cause's -1 as the report-index check;
* get_report_trade keeps global indices, including after a sealed prefix.
*
* round-4b F3: this bounded the index by trade_count() == trades_.size(),
* so every range-end row (the position still open after the final bar,
* ABI v3's open_at_end) read as out of range and returned 0 — an empty
* "Engine entry incarnation" on the run_strategy.py CSV. The grader then
* failed closed on the identity gate and the verifier ladder rejected the
* TV-identical trim candidate for ena-grid (XAUUSD 1D), even though the
* engine's per-lot range-end rows themselves matched TV (xau-grid 6/6,
* silicon 9/9 rows). The row is built from the open
* pyramid lot, so it carries that lot's entry_incarnation like any other
* close. No struct changed by this accessor (PF_ABI_VERSION is 5). */
PF_API uint64_t strategy_closed_trade_entry_incarnation(
pf_strategy_t s, int trade_index) {
if (!s) return 0;
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
try {
if (engine->closed_trade_close_cause(trade_index) < 0) return 0;
return engine->get_report_trade(trade_index).entry_incarnation;
} catch (const pineforge::detail::RetiredTradeHistoryRead& error) {
note_cabi_refusal(s, &error);
return 0;
} catch (...) {
return 0;
}
}
/* ABI v4 live-runtime surface (task 9): closed-trade id / comment
* string accessors, indexing the same REPORT row space as
* strategy_closed_trade_entry_incarnation above (trades_ then
* range_end_trades_). These read Trade::entry_id / entry_comment / exit_id /
* exit_comment directly rather than through the protected BacktestEngine::
* closed_trade_entry_id / _entry_comment / _exit_id / _exit_comment methods
* -- those are a DIFFERENT, narrower accessor (strategy.closedtrades.* scope:
* trades_ only, no range-end rows) already declared with these exact names,
* so a same-name report-row overload is not possible.
*
* Returned pointers are valid until the next run(), stream call, or
* strategy_release_run_results_v1 on this handle. This legacy pointer API
* materializes each requested row; value/page readers use bounded storage.
* NULL on a NULL handle, out-of-range, policy-erased or released row; retained
* sealed rows are readable until release. Released rows set the last error. */
PF_API const char* strategy_closed_trade_entry_id(pf_strategy_t s, int trade_index) {
if (!s) return nullptr;
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
try {
if (engine->closed_trade_close_cause(trade_index) < 0) return nullptr;
return engine->materialize_report_trade(trade_index).entry_id.c_str();
} catch (const pineforge::detail::RetiredTradeHistoryRead& error) {
note_cabi_refusal(s, &error);
return nullptr;
} catch (...) {
return nullptr;
}
}
PF_API const char* strategy_closed_trade_entry_comment(pf_strategy_t s, int trade_index) {
if (!s) return nullptr;
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
try {
if (engine->closed_trade_close_cause(trade_index) < 0) return nullptr;
return engine->materialize_report_trade(trade_index).entry_comment.c_str();
} catch (const pineforge::detail::RetiredTradeHistoryRead& error) {
note_cabi_refusal(s, &error);
return nullptr;
} catch (...) {
return nullptr;
}
}
PF_API const char* strategy_closed_trade_exit_id(pf_strategy_t s, int trade_index) {
if (!s) return nullptr;
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
try {
if (engine->closed_trade_close_cause(trade_index) < 0) return nullptr;
return engine->materialize_report_trade(trade_index).exit_id.c_str();
} catch (const pineforge::detail::RetiredTradeHistoryRead& error) {
note_cabi_refusal(s, &error);
return nullptr;
} catch (...) {
return nullptr;
}
}
PF_API const char* strategy_closed_trade_exit_comment(pf_strategy_t s, int trade_index) {
if (!s) return nullptr;
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
try {
if (engine->closed_trade_close_cause(trade_index) < 0) return nullptr;
return engine->materialize_report_trade(trade_index).exit_comment.c_str();
} catch (const pineforge::detail::RetiredTradeHistoryRead& error) {
note_cabi_refusal(s, &error);
return nullptr;
} catch (...) {
return nullptr;
}
}
/* ABI v4 live-runtime surface (task 9): why a REPORT-row closed trade
* exited (BacktestEngine::closed_trade_close_cause, engine_trade_
* accessors.cpp, has the full derivation order). 0 UNKNOWN (reserved for
* the documented "no cause" value on a VALID trade -- no live derivation
* currently produces it), 1 SCRIPT (strategy.close/close_all or a
* reversal-driven close), 2 BRACKET (a strategy.exit stop/limit/trail/
* profit/loss leg), 3 MARGIN_CALL, 4 INTRADAY_LOSS_CAP, 5
* INTRADAY_FILL_CAP, 6 RANGE_END (the still-open position closed at the
* end of a flag-off run). -1 (final review F7) on a NULL handle OR an
* out-of-range trade_index -- delegated to the engine method for the
* latter, matching every sibling indexed accessor's -1-on-bad-index
* convention (strategy_pending_order_fill_qty/_level_resolved/
* _effective_levels). */
PF_API int strategy_closed_trade_close_cause(pf_strategy_t s, int trade_index) {
if (!s) return -1;
try {
return static_cast<const pineforge::BacktestEngine*>(s)->closed_trade_close_cause(trade_index);
} catch (const pineforge::detail::RetiredTradeHistoryRead& error) {
note_cabi_refusal(s, &error);
return -1;
} catch (...) {
return -1;
}
}
/* ABI v4 live-runtime surface (task 9): the script-facing position size
* (strategy.position_size -- signed, freeze-aware) and equity after
* the most recent run(). strategy_current_equity is initial capital plus
* realized net profit (strategy.initial_capital + strategy.netprofit) --
* NOT Pine's strategy.equity, which adds open profit on top of this. NaN
* on a NULL handle. */
PF_API double strategy_position_size(pf_strategy_t s) {
if (!s) return std::numeric_limits<double>::quiet_NaN();
return static_cast<const pineforge::BacktestEngine*>(s)->live_position_size();
}
PF_API double strategy_current_equity(pf_strategy_t s) {
if (!s) return std::numeric_limits<double>::quiet_NaN();
return static_cast<const pineforge::BacktestEngine*>(s)->live_current_equity();
}
PF_API double strategy_net_profit_sum(pf_strategy_t s) {
if (!s) return std::numeric_limits<double>::quiet_NaN();
return static_cast<const pineforge::BacktestEngine*>(s)->raw_net_profit_sum();
}
PF_API double strategy_report_pointvalue(pf_strategy_t s) {
if (!s) return std::numeric_limits<double>::quiet_NaN();
return static_cast<const pineforge::BacktestEngine*>(s)->report_pointvalue();
}
PF_API int strategy_set_report_replay_v1(pf_strategy_t s, const char* path, const char* run_id) {
try {
if (!s) return -1;
return static_cast<pineforge::BacktestEngine*>(s)->set_report_replay_v1(path, run_id);
} catch (const std::exception& error) {
note_cabi_refusal(s, &error);
return -1;
} catch (...) {
note_cabi_refusal(s, nullptr);
return -1;
}
}
/* ABI v4 live-runtime surface (task 9): total SCRIPT bars dispatched by the
* most recent run() (mirrors pf_report_t::script_bars_processed, including
* a stream's warmup leg and every realtime tick-driven bar dispatched
* afterward). -1 on a NULL handle. */
PF_API int64_t strategy_script_bars_processed(pf_strategy_t s) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->script_bars_processed();
}
/* Toggle per-bar trace recording on a live strategy. Default off; the
* harness flips it on per-strategy via this entry point before running
* a backtest whose per-bar values it wants to cross-reference against
* TradingView. */
PF_API void strategy_set_trace_enabled(pf_strategy_t s, int on) {
pf_cabi_void(s, [&] {
if (!s) return;
static_cast<pineforge::BacktestEngine*>(s)->set_trace_enabled(on != 0);
});
}
/* Returns the most recent run or setter error text; empty when none was
* recorded. A void setter setup failure survives the next refused start;
* the following start clears it. The failed setter did not apply its value;
* retrying the start without reapplying it uses the previous value.
* The recorded text begins "Error before the first bar: " (or
* "Error on bar N: " when a bar is being executed).
* The pointer lasts until an operation
* replaces or clears the error. Returns NULL only when ``s`` is NULL.
* The runtime catches all std::exception derivatives inside
* BacktestEngine::run() so the C ABI never unwinds an exception across
* the extern "C" boundary; consumers must check this after every run
* to surface engine-rejected configurations (e.g. script_tf finer than
* input_tf, request.security TF below the chart TF without a supported
* lower-TF emulation, missing input_tf when securities are registered).
*/
PF_API const char* strategy_get_last_error(pf_strategy_t s) {
if (!s) return nullptr;
const auto& engine = *static_cast<const pineforge::BacktestEngine*>(s);
if (pineforge::NativeExecutionConsumer::cabi_run_results_release_refused(engine))
return pineforge::detail::ActiveRunResultsRelease::message;
return engine.last_error().c_str();
}
/* The stable code of the failure strategy_get_last_error reports, and its
* arguments as canonical JSON (include/pineforge/run_failure.hpp): "" when the
* most recent run or setter recorded no failure, NULL only for a NULL handle.
* Static names and the record's own string: valid until the next run or
* setter, like the text. */
PF_API const char* strategy_get_last_error_code(pf_strategy_t s) {
if (!s) return nullptr;
const auto& engine = *static_cast<const pineforge::BacktestEngine*>(s);
if (pineforge::NativeExecutionConsumer::cabi_run_results_release_refused(engine))
return pineforge::run_failure_code_name(pineforge::RunFailureCode::setting_rejected);
return pineforge::run_failure_code_of(engine);
}
PF_API const char* strategy_get_last_error_args(pf_strategy_t s) {
if (!s) return nullptr;
const auto& engine = *static_cast<const pineforge::BacktestEngine*>(s);
if (pineforge::NativeExecutionConsumer::cabi_run_results_release_refused(engine)) return "{}";
return pineforge::run_failure_args_of(engine);
}
PF_API const char* strategy_get_run_warnings(pf_strategy_t s) {
if (!s) return nullptr;
const char* result = "[{\"args\":{},\"code\":\"run_warnings_unavailable\"}]";
pf_cabi_void(nullptr, [&] { // a read-only getter: records nothing on the handle
result = pineforge::native_run_warnings(
static_cast<const pineforge::BacktestEngine*>(s));
});
return result;
}
PF_API void strategy_set_trade_start_time(pf_strategy_t s, int64_t timestamp_ms) {
pf_cabi_void(s, [&] {
if (!s) return;
static_cast<pineforge::BacktestEngine*>(s)->set_trade_start_time(timestamp_ms);
});
}
/* Cooperative abort of the run in progress on ``s`` (live runtime: a settle
* supersedes an in-flight probe). Atomic; consumed by the running loop at its
* next bar. Cleared once at every public run() entry so a request made
* while idle is a no-op. The aborted run reports strategy_last_run_status()
* == 1 and leaves the handle reusable. */
PF_API void strategy_request_abort(pf_strategy_t s) {
if (!s) return;
static_cast<pineforge::BacktestEngine*>(s)->request_abort();
}
/* 1 = NOT_COMPLETED (failed/aborted run or void setter failure); -1 = NULL handle.
* A zero status alone does not prove success: also read strategy_get_last_error
* and strategy_get_last_error_code, including after a refused start. */
PF_API int strategy_last_run_status(pf_strategy_t s) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->last_run_status();
}
/* Live-runtime tail semantics (spec §3.1): the last bar of the array fed to
* the next run() is a still-forming bar, not the chart's rightmost
* historical bar. Default off (on=0): every historical run stays
* byte-identical to before this flag existed. The mode is the source
* host's (a virtual seam on the kernel): on a host that models no forming
* tail bar the call is accepted and inert, as it always was there. */
PF_API void strategy_set_realtime_tail(pf_strategy_t s, int on, int horizon_bars) {
pf_cabi_void(s, [&] {
if (!s) return;
static_cast<pineforge::BacktestEngine*>(s)->set_realtime_tail(on != 0, horizon_bars);
});
}
/* Live probe tail suppression (spec §3.2): the last script bar of the array
* fed to the next run() is matched but not calculated -- the kernel settles
* the resting book against it, and the Pine source host's scheduler
* publishes it through its suppressed-tail step instead of on_bar (source
* history and bar_index advance, no range-end row). The host's own
* bar-close policy is not the script and still runs there, so a margin call
* due against the forming bar is booked against it. Independent of
* strategy_set_realtime_tail. Honoured on every batch path (under
* aggregation, on the last completed script bar); under COOF a fill on the
* forming bar still recalculates the script there; COOF and the bar
* magnifier stay gated in live v1 -- see pineforge.h.
* Default off (on=0): every historical run stays byte-identical to before
* this flag existed. Like strategy_set_realtime_tail, the mode is the source
* host's; on a host that models no forming tail bar the call is accepted
* and inert, as it always was there. */
PF_API void strategy_set_probe_suppress_tail_logic(pf_strategy_t s, int on) {
pf_cabi_void(s, [&] {
if (!s) return;
static_cast<pineforge::BacktestEngine*>(s)->set_probe_suppress_tail_logic(on != 0);
});
}
/* ABI v4 live-runtime surface (task 4): force the intrabar path order used
* by every subsequent run() -- 0 AUTO (the unchanged TV-emulator rule), 1
* HIGH_FIRST (O -> H -> L -> C), 2 LOW_FIRST (O -> L -> H -> C); any other
* @p mode records a typed setting refusal. A live probe runs the SAME forming
* bar under both forced orders and keeps only the fills that agree between the two.
* Persistent configuration, like strategy_set_realtime_tail. The mode is
* carried by the RUN (NativeRunSpec::path_order, projected at begin), so it
* takes effect at the next begin rather than mid-run and a stream is not
* exempt: a confirmed bar pushed through strategy_stream_push_bar is sealed
* on the same forced waypoint sequence a run() walks. An observed tick
* (strategy_stream_push_tick) is one price, not a modeled path, so it has no
* legs to order. Default AUTO (mode=0): every historical run stays
* byte-identical to before this flag existed. */
PF_API void strategy_set_path_order(pf_strategy_t s, int mode) {
pf_cabi_void(s, [&] {
if (!s) return;
static_cast<pineforge::BacktestEngine*>(s)->set_path_order(mode);
});
}
/* ABI v4 live-runtime surface (task 4): the dual-entry-stop arbitration
* decided on the LAST bar the most recent run() dispatched -- a flat
* position resting one long stop-only ENTRY and one short stop-only ENTRY,
* both touched on that bar. 0 = None (no such pair was arbitrated on that
* bar), 1 = LongFirst, 2 = ShortFirst; -1 when @p s is NULL. This is a
* per-bar snapshot: it survives a later fill or a declined stop-entry
* admission on the same bar (both of which move the engine's own working
* arbitration state back to None), so it reports the real decision even for
* an ordinary process_orders_on_close run with no tail suppression. Only
* the standard (non-calc_on_order_fills) dispatch path updates this. */
PF_API int strategy_last_bar_dual_entry_path(pf_strategy_t s) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->observe_last_bar_dual_entry_path_v1();
}
/* ABI v4 live-runtime surface (task 6): toggle per-script-bar broker-state
* hash recording. Default off: pf_report_t::broker_state_hash stays
* NULL/0-length and every historical run is byte-identical to before this
* flag existed. */
PF_API void strategy_set_broker_state_hash_recording(pf_strategy_t s, int on) {
pf_cabi_void(s, [&] {
if (!s) return;
static_cast<pineforge::BacktestEngine*>(s)->set_broker_state_hash_recording(on != 0);
});
}
/* ABI v4 live-runtime surface (task 6): the broker-state hash of the FINAL
* state after the most recent run(), regardless of whether per-bar
* recording was enabled. Returns 0 when @p s is NULL, and 0 for a read the
* selected-window fence refuses (strategy_state_query_status_v1 names it):
* the C++ path throws that refusal, so it is prechecked here and never
* unwinds through C. A caller that needs a sealed selected run's terminal
* witness enables recording before the run and reads the last recorded row.
* Any other failure of the read (a spilled book that can no longer be read
* back) also answers 0, never a hash it cut short, and is noted beside the
* handle for strategy_get_last_error / _code, as the int entry points note a
* refusal: nothing unwinds through C. */
PF_API uint64_t strategy_broker_state_hash(pf_strategy_t s) {
if (!s) return 0;
if (strategy_state_query_status_v1(s) != PF_STATE_QUERY_ALLOWED_V1) return 0;
try {
return static_cast<const pineforge::BacktestEngine*>(s)->broker_state_hash();
} catch (const std::exception& error) {
note_cabi_refusal(s, &error);
return 0;
} catch (...) {
note_cabi_refusal(s, nullptr);
return 0;
}
}
/* The current eligibility of both state queries on @p s (broker-state hash
* above, stream_state_hash below): the selected-window fence, read in place.
* NULL is INVALID_HANDLE, a handle whose selected window has sealed is
* SELECTED_WINDOW_AFTER_SEAL, every other handle is ALLOWED. A pure predicate
* on the handle: no allocation, no mutation, no host dispatch, and no touch of
* the last-error slot or the run's first cause. It is also the observable
* refusal of the report-only terminal-quote writers: strategy_set_syminfo_metadata
* (below) is void and pf_cabi_void swallows the SelectedWindowQueryAfterSeal the
* Pine host throws, before any store, for the two quote keys once the selected run
* has sealed, so a caller reads this status to learn that such a write stored
* nothing. */
PF_API pf_state_query_status_v1_t strategy_state_query_status_v1(pf_strategy_t s) {
if (!s) return PF_STATE_QUERY_INVALID_HANDLE_V1;
return pineforge::native_selected_query_closed(static_cast<const pineforge::BacktestEngine*>(s))
? PF_STATE_QUERY_SELECTED_WINDOW_AFTER_SEAL_V1
: PF_STATE_QUERY_ALLOWED_V1;
}
/* ABI v4 live-runtime surface (task 7, spec 3.6): the resting-order book
* after the most recent run(), read through the generated POD mirror
* (pf_pending_order_v1_t, include/pineforge/pending_order_mirror.hpp;
* fill_pending_order_mirror / pending_order_layout live in the generated
* src/pending_order_mirror.cpp). Read-only accessors: no historical run
* changes because a caller read them. */
PF_API int strategy_pending_orders_len(pf_strategy_t s) {
if (!s) return 0;
return static_cast<const pineforge::BacktestEngine*>(s)->observe_pending_count_v1();
}
/* Copies min(size_in, sizeof(pf_pending_order_v1_t)) bytes so an older
* (smaller) or newer (larger) caller struct both work: the first two
* fields are always struct_version and size. -1 (nothing written) on a
* NULL handle/out, an out-of-range index, or a size_in too small to hold
* even that 8-byte header -- a buffer that cannot receive struct_version
* and size cannot be interpreted by any reader, so it is rejected rather
* than partially filled. */
PF_API int strategy_pending_order_get(pf_strategy_t s, int index, void* out, size_t size_in) {
if (!s || !out) return -1;
if (size_in < offsetof(pf_pending_order_v1_t, size) + sizeof(uint32_t)) return -1;
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
if (index < 0 || index >= engine->observe_pending_count_v1()) return -1;
pf_pending_order_v1_t tmp;
if (engine->observe_pending_copy_v1(index, &tmp) != 0) return -1;
std::memcpy(out, &tmp, size_in < sizeof(tmp) ? size_in : sizeof(tmp));
return 0;
}
PF_API const pf_field_desc_t* strategy_pending_order_layout(int* count) {
return pineforge::pending_order_layout(count);
}
/* ABI v4 live-runtime surface (task 8, spec 3.6): engine-computed derived
* order values and position scalars -- pure const reads of the engine's own
* sizing / admission / level-resolution predicates supplied by the native
* request core plus the source adapter projection. NULL-handle
* convention of the pf_live group: -1 for an int return, NaN for a double,
* with nothing written through the out-pointers. */
PF_API int strategy_pending_order_fill_qty(pf_strategy_t s, int index, double fill_price,
double* qty, int* close_only, int* partition) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->observe_probe_fill_qty(
index, fill_price, qty, close_only, partition);
}
PF_API int strategy_pending_order_level_resolved(pf_strategy_t s, int index) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->observe_pending_level_resolved(index);
}
PF_API int strategy_pending_order_effective_levels(pf_strategy_t s, int index, double* stop,
double* limit, double* trail_activation) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->observe_pending_effective_levels(
index, stop, limit, trail_activation);
}
/* NaN when @p s is NULL; otherwise the engine's trail extreme (itself NaN
* until a position has filled). */
PF_API double strategy_trail_best_price(pf_strategy_t s) {
if (!s) return std::numeric_limits<double>::quiet_NaN();
return static_cast<const pineforge::BacktestEngine*>(s)->observe_trail_best_price_v1();
}
/* NaN when @p s is NULL or the position is flat (the engine keeps
* position_entry_price_ at 0 there; a live reader must not mistake that for
* a price), otherwise the volume-weighted average entry price. */
PF_API double strategy_position_avg_price(pf_strategy_t s) {
if (!s) return std::numeric_limits<double>::quiet_NaN();
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
if (engine->position_cycle_seq() == 0) return std::numeric_limits<double>::quiet_NaN();
return engine->position_avg_price();
}
/* -1 when @p s is NULL; 0 when flat; otherwise the live position cycle id. */
PF_API int64_t strategy_position_cycle_seq(pf_strategy_t s) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->position_cycle_seq();
}
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) {
return pf_cabi_int(s, [&] {
if (!s) return -1;
auto* engine = static_cast<pineforge::BacktestEngine*>(s);
if (n_warmup < 0 || (n_warmup > 0 && !warmup_bars)) {
// Preserve the engine's diagnostic and lifecycle contract without
// reading malformed C input or allocating an input array.
return engine->stream_begin(nullptr, n_warmup,
input_tf ? std::string(input_tf) : std::string(),
script_tf ? std::string(script_tf) : std::string()) ? 0 : -1;
}
// pf_bar_t and Bar have identical size and field offsets (pinned
// above). Pass the warmup straight through: a Pine scheduler makes
// the one owning stream copy before returning from its begin hook.
// A temporary vector here used to keep two whole warmup arrays live.
// The caller's span is needed only for this synchronous begin call;
// realtime callbacks read the scheduler's owned warmup afterwards.
return engine->stream_begin(
reinterpret_cast<const pineforge::Bar*>(warmup_bars), n_warmup,
input_tf ? std::string(input_tf) : std::string(),
script_tf ? std::string(script_tf) : std::string()) ? 0 : -1;
});
}
PF_API int strategy_stream_api_version(void) { return 1; }
PF_API int strategy_stream_push_bar(pf_strategy_t s, const pf_bar_t* bar) {
return pf_cabi_int(s, [&] {
if (!s || !bar) return -1;
const pineforge::Bar native{bar->open, bar->high, bar->low,
bar->close, bar->volume, bar->timestamp};
return static_cast<pineforge::BacktestEngine*>(s)->stream_push_bar(native) ? 0 : -1;
});
}
PF_API int strategy_stream_order_actions_len(pf_strategy_t s) {
if (!s) return -1;
return static_cast<const pineforge::BacktestEngine*>(s)->stream_order_actions_len();
}
PF_API int strategy_stream_order_action_get(pf_strategy_t s, int index,
pf_stream_order_action_t* out) {
if (!s || !out || index < 0) return -1;
const auto* engine = static_cast<const pineforge::BacktestEngine*>(s);
if (index >= engine->stream_order_actions_len()) return -1;
const auto& a = engine->stream_order_action_at(index);
*out = pf_stream_order_action_t{a.sequence, a.timestamp_ms, a.bar_index,
a.is_entry ? 1 : 0, a.is_long ? 1 : 0, a.quantity, a.price,
a.order_id.c_str(), a.comment.c_str(), a.entry_incarnation};
return 0;
}
PF_API void strategy_stream_order_actions_clear(pf_strategy_t s) {
if (s) static_cast<pineforge::BacktestEngine*>(s)->stream_order_actions_clear();
}
/* Returns 0 for NULL and for a read the selected-window fence refuses, the
* same precheck as strategy_broker_state_hash: the refusal is a C++ exception
* and never crosses this boundary. A broker-state row is not a stream-token
* value, so a refused read of this token leaves no recorded witness. The
* token folds broker_state_hash(), so a failed read of the spilled book
* answers 0 here too, noted as strategy_broker_state_hash notes it. */
PF_API uint64_t strategy_stream_state_hash(pf_strategy_t s) {
if (!s) return 0;
if (strategy_state_query_status_v1(s) != PF_STATE_QUERY_ALLOWED_V1) return 0;
try {
return static_cast<const pineforge::BacktestEngine*>(s)->stream_state_hash();
} catch (const std::exception& error) {
note_cabi_refusal(s, &error);
return 0;
} catch (...) {
note_cabi_refusal(s, nullptr);
return 0;
}
}
PF_API int strategy_stream_push_tick(pf_strategy_t s,
const pf_trade_tick_t* tick) {
return pf_cabi_int(s, [&] {
if (!s || !tick) return -1;
const pineforge::TradeTick native{tick->timestamp, tick->sequence,
tick->price, tick->quantity};
return static_cast<pineforge::BacktestEngine*>(s)->stream_push_tick(native)
? 0
: -1;
});
}
PF_API int strategy_stream_push_ticks(pf_strategy_t s,
const pf_trade_tick_t* ticks,
int n) {
return pf_cabi_int(s, [&] {
if (!s || n < 0 || (n > 0 && !ticks)) return -1;
auto* engine = static_cast<pineforge::BacktestEngine*>(s);
std::vector<pineforge::TradeTick> native;
native.reserve(static_cast<std::size_t>(n));
for (int i = 0; i < n; ++i) {
const auto& tick = ticks[i];
native.push_back({tick.timestamp, tick.sequence, tick.price, tick.quantity});
}
return engine->stream_push_ticks(native.data(), n) ? 0 : -1;
});
}