Repository navigation
Expand file tree
/
Copy pathrun_strategy.py
More file actions
4679 lines (4326 loc) · 235 KB
/
Copy pathrun_strategy.py
File metadata and controls
4679 lines (4326 loc) · 235 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
#!/usr/bin/env python3
"""Run a compiled PineForge strategy `.so` against an OHLCV bar feed and
emit `engine_trades.csv` in TradingView-compatible format.
This script is the user-facing piece of the reproducibility kit: given
the open-source runtime and the codegen-emitted `generated.cpp`, anyone
can compile a `strategy.so` (see `corpus/CMakeLists.txt`) and drive it
through this harness to regenerate the exact same `engine_trades.csv`
file shipped in the corpus.
It binds *only* the C ABI declared in `<pineforge/pineforge.h>` via
ctypes. There is no transpiler dependency. The struct layouts here are
mirrors of the C declarations and pinned by static_asserts in the
runtime library — if either side drifts, the runtime fails to link
rather than corrupting reads.
Usage examples
--------------
# Single strategy (auto-finds strategy.so next to generated.cpp)
python scripts/run_strategy.py corpus/basic/greedy
# Custom OHLCV input
python scripts/run_strategy.py corpus/basic/greedy \\
--ohlcv corpus/data/derived/ohlcv_ETH-USDT-USDT_15m_window.csv
# Don't overwrite engine_trades.csv if it already exists
python scripts/run_strategy.py corpus/basic/greedy --no-overwrite
# All strategies (matches `bash scripts/run_corpus.sh`)
for d in corpus/*/*/; do python scripts/run_strategy.py "$d"; done
# Warm indicators on pre-window bars but suppress order execution
# until the comparison window opens (prevents warmup-period trades
# from polluting engine_trades.csv in strategies with early signals):
python scripts/run_strategy.py corpus/basic/greedy \\
--disable-trading-before-window
With a TradingView tape (inputs.json::tv_trades_csv, default
strategy_dir/tv_trades.csv) the emit window is TradingView's own: order
commands are ignored before the chart bar that precedes TV's first entry
bar (the bar the first entry was placed on) -- or, on a run whose feed
starts on TradingView's first computed bar, before that bar -- and the
trades written are those entered inside the tape's span —
_tv_entry_emit_window states the exact rule.
"""
from __future__ import annotations
import argparse
import base64
import csv
import ctypes
import hashlib
import io
import json
import math
import os
import re
import struct
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import NamedTuple
REPO_ROOT = Path(__file__).resolve().parent.parent
# The corpus ships a single committed feed (full-history 1m, Git LFS);
# the 15m chart feeds are derived from it locally. main() calls
# ensure_derived() only for a run that reads a derived feed
# (_reads_derived_feed): importing this module stays side-effect free for
# consumers that only want the ABI mirrors, and a run on its own feed
# (every benchmark slot) needs no corpus checkout.
from derive_corpus_feeds import ( # noqa: E402
DERIVED_15M, DERIVED_15M_WINDOW, DERIVED_DIR, ensure_derived)
REFERENCE_OHLCV = DERIVED_15M_WINDOW
WARMUP_OHLCV = DERIVED_15M
DEFAULT_OHLCV = WARMUP_OHLCV
# Keys in inputs.json that are validator/harness metadata, not Pine input()
# values. Mirrors the canonical validator's VALIDATION_INPUT_META_KEYS so
# they are not forwarded to ``strategy_set_input`` (which would either
# silently no-op or pollute the strategy's input table).
_VALIDATION_META_KEYS = frozenset({
"tv_trades_csv_tz",
"tv_trades_csv",
"runtime_overrides",
"strategy_overrides",
"validation_overrides",
"ohlcv_csv",
"aux_security_ohlcv_csv",
"aux_security_input_tf",
"native_security_feeds",
"ohlcv_start_ms",
"script_tf",
"input_tf",
"chart_timezone",
})
# >>> fingerprint helpers (DUPLICATED verbatim in scripts/run_strategy.py;
# scripts/ is .dockerignore'd so this cannot be a shared module.
# scripts/fingerprint_self_test.py asserts both copies stay identical.)
try:
from importlib import metadata as _ilmd
except ImportError: # pragma: no cover
_ilmd = None
# Canonical strategy() defaults: the member defaults of
# source::PineStrategyConfig (include/pineforge/source/pine_adapter.hpp),
# which a generated constructor fills and hands to configure_pine_strategy.
# The constructor declares only what the script (or, for Pine v6, TradingView's
# default) sets -- a script that omits process_orders_on_close or
# close_entries_rule leaves them to the struct -- so this seed supplies the
# rest. KEEP IN SYNC with PineStrategyConfig.
STRATEGY_SEED = {
"initial_capital": 1000000.0,
"process_orders_on_close": False,
"default_qty_type": "fixed",
"default_qty_value": 1.0,
"pyramiding": 1,
"commission_type": "percent",
"commission_value": 0.0,
"slippage": 0,
"close_entries_rule": "FIFO",
}
_QTY_TYPE = {"FIXED": "fixed", "PERCENT_OF_EQUITY": "percent_of_equity", "CASH": "cash"}
_COMM_TYPE = {"PERCENT": "percent", "CASH_PER_ORDER": "cash_per_order",
"CASH_PER_CONTRACT": "cash_per_contract"}
# PineStrategyConfig member -> provenance key: the generated constructor's
# `cfg.<member> = <value>;` lines (pineforge-codegen since R4-C).
_CFG_FIELD_KEY = {
"initial_capital": "initial_capital",
"process_orders_on_close": "process_orders_on_close",
"default_qty_type": "default_qty_type",
"default_qty_value": "default_qty_value",
"pyramiding": "pyramiding",
"commission_type": "commission_type",
"commission_value": "commission_value",
"slippage": "slippage",
"close_entries_rule_any": "close_entries_rule",
}
_QTY_TYPE_INDEX = {0: "fixed", 1: "percent_of_equity", 2: "cash"}
_COMM_TYPE_INDEX = {0: "percent", 1: "cash_per_order", 2: "cash_per_contract"}
_CFG_DECL_RE = re.compile(r"\bPineStrategyConfig\s+(\w+)\s*(?:\{\s*\}|\(\s*\))?\s*;")
# Pre-R4-C generated.cpp ctor member write -> provenance key.
_STRAT_FIELD_KEY = {
"initial_capital_": "initial_capital",
"process" + "_orders_on_close_": "process_orders_on_close",
"default_qty_type_": "default_qty_type",
"default_qty_value_": "default_qty_value",
"pyramiding_": "pyramiding",
"commission_type_": "commission_type",
"commission_value_": "commission_value",
"slippage_": "slippage",
"close_entries_rule_any_": "close_entries_rule",
}
_INPUT_RE = re.compile(
r'get_input_(\w+)\(\s*"((?:[^"\\]|\\.)*)"\s*,\s*((?:[^();]|\([^()]*\))*?)\s*\)')
# Canonical primary-feed identity. Hash the numeric BarC values in source-row
# order, before any validation-only start/end slicing. The domain prefix makes
# the byte contract versioned and prevents cross-domain hash reuse.
SOURCE_FEED_CANONICALIZATION = "pf-ohlcv-barc-le-v1"
_SOURCE_FEED_HASH_PREFIX = b"pineforge:ohlcv:barc-le:v1\0"
_SOURCE_FEED_RECORD = struct.Struct("<5dq")
def _new_source_feed_hasher():
h = hashlib.sha256()
h.update(_SOURCE_FEED_HASH_PREFIX)
return h
def _update_source_feed_hash(h, row) -> None:
h.update(_SOURCE_FEED_RECORD.pack(*row))
def _ctor_body(cpp_text: str) -> str:
"""Return the GeneratedStrategy constructor body, or '' if not found.
Scoping to the ctor is load-bearing: set_strategy_override() also contains
`initial_capital_ = std::stod(value);` lines that must NOT be parsed as
defaults. The member-init list (`_ta_ema_1(5)`) has no `=` so it cannot
false-match the field regex."""
m = re.search(r"GeneratedStrategy\s*\([^)]*\)\s*(?::[^{]*)?\{", cpp_text)
if not m:
return ""
i = m.end() - 1 # index of the opening '{'
depth = 0
for j in range(i, len(cpp_text)):
c = cpp_text[j]
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
return cpp_text[i + 1:j]
return ""
def _coerce_scalar(rhs: str):
rhs = rhs.strip()
if rhs in ("true", "false"):
return rhs == "true"
if re.fullmatch(r"[+-]?\d+", rhs):
return int(rhs)
try:
f = float(rhs)
return f if (f == f and f not in (float("inf"), float("-inf"))) else rhs
except ValueError:
return rhs
def _unwrap_std_string(expr: str) -> str:
"""Codegen wraps string input defaults as std::string("..."); unwrap to the
inner literal so the recorded default is the value, not the C++ expression."""
m = re.fullmatch(r'std::string\((.*)\)', expr.strip(), re.DOTALL)
return m.group(1).strip() if m else expr
def _strategy_value(key: str, rhs: str):
"""One declared strategy() value as the provenance spells it. The generated
constructor stores PineStrategyConfig's enum members as int
(`static_cast<int>(QtyType::FIXED)`); a pre-R4-C one assigned the enum."""
rhs = rhs.strip()
cast = re.fullmatch(r"static_cast<\s*\w+\s*>\((.*)\)", rhs, re.DOTALL)
if cast:
rhs = cast.group(1).strip()
if key in ("default_qty_type", "commission_type"):
names, index = ((_QTY_TYPE, _QTY_TYPE_INDEX) if key == "default_qty_type"
else (_COMM_TYPE, _COMM_TYPE_INDEX))
value = _coerce_scalar(rhs)
if isinstance(value, int) and not isinstance(value, bool):
return index.get(value, rhs)
return names.get(rhs.split("::")[-1], rhs)
if key == "close_entries_rule":
return "ANY" if _coerce_scalar(rhs) is True else "FIFO"
return _coerce_scalar(rhs)
def parse_strategy_params(cpp_text: str) -> dict:
"""Parse strategy() header defaults from the constructor body only: the
PineStrategyConfig the generated constructor fills (`cfg.<member> = ...;`),
or a pre-R4-C constructor's member writes (`<member>_ = ...;`)."""
out: dict = {}
body = _ctor_body(cpp_text)
decl = _CFG_DECL_RE.search(body)
if decl:
field = re.compile(r"\b" + re.escape(decl.group(1)) + r"\.(\w+)\s*=\s*([^;]+);")
for fld, rhs in field.findall(body):
key = _CFG_FIELD_KEY.get(fld)
if key:
out[key] = _strategy_value(key, rhs)
for fld, rhs in re.findall(r"(\w+_)\s*=\s*([^;]+);", body):
key = _STRAT_FIELD_KEY.get(fld)
if key:
out[key] = _strategy_value(key, rhs)
return out
def effective_strategy(cpp_text: str, overrides: dict | None) -> dict:
"""Canonical seed -> ctor-parsed defaults -> user overrides (string wins)."""
s = dict(STRATEGY_SEED)
s.update(parse_strategy_params(cpp_text))
for k, v in (overrides or {}).items():
s[k] = v
return s
def parse_inputs(cpp_text: str) -> dict:
"""Parse every get_input_*("title", default) call; dedup by title (first wins)."""
out: dict = {}
for typ, title, dflt in _INPUT_RE.findall(cpp_text):
if title in out:
continue
d = _unwrap_std_string(dflt.strip())
if d.startswith('"') and d.endswith('"') and len(d) >= 2:
val = d[1:-1]
elif typ == "source":
val = d
else:
val = _coerce_scalar(d)
out[title] = {"type": typ, "default": val}
return out
def effective_inputs(cpp_text: str, inputs_applied: dict | None) -> dict:
"""All declared inputs with {type, default, value}; value = override or default.
Applied inputs with no matching declaration are appended best-effort."""
applied = inputs_applied or {}
out: dict = {}
for title, meta in parse_inputs(cpp_text).items():
out[title] = {
"type": meta["type"],
"default": meta["default"],
"value": applied.get(title, meta["default"]),
}
for title, v in applied.items():
if title not in out:
out[title] = {"type": "unknown", "default": None, "value": v}
return out
def _sha256_file(path) -> str | None:
try:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
except OSError:
return None
def _codegen_version() -> str:
if _ilmd is None:
return "unknown"
try:
return _ilmd.version("pineforge-codegen")
except Exception:
return "unknown"
def build_provenance(engine: dict, cpp_path, transpiled: bool,
inputs_applied: dict, overrides_applied: dict,
runtime: dict | None, *, source_feed_sha256: str) -> dict:
if not isinstance(source_feed_sha256, str) or not re.fullmatch(
r"[0-9a-f]{64}", source_feed_sha256):
raise ValueError("source_feed_sha256 must be a lowercase SHA-256 hex digest")
cpp_text = ""
cpp_sha = None
if cpp_path:
cpp_sha = _sha256_file(cpp_path)
try:
with open(cpp_path, "r", encoding="utf-8", errors="replace") as f:
cpp_text = f.read()
except OSError:
cpp_text = ""
return {
"engine": engine,
"feed": {
"canonicalization": SOURCE_FEED_CANONICALIZATION,
"source_values_sha256": source_feed_sha256,
},
"codegen": {
"version": _codegen_version(),
"generated_cpp_sha256": cpp_sha,
"transpiled_from_pine": bool(transpiled),
},
"strategy": effective_strategy(cpp_text, overrides_applied),
"inputs": effective_inputs(cpp_text, inputs_applied),
"applied": {
"inputs": dict(inputs_applied or {}),
"overrides": dict(overrides_applied or {}),
},
"runtime": runtime or {},
}
# Product accepted-type domain for exact Python integers: JavaScript
# Number.MAX/MIN_SAFE_INTEGER (= ±(2**53 - 1)). Rejecting larger exact ints
# guarantees unique lossless integer identity across generic ECMAScript
# consumers. This is not a claim that every such magnitude must round as
# binary64 — e.g. float(2**53) is exactly representable and remains legal
# on the float path, while exact int(2**53) is deliberately outside the
# product integer domain. Out-of-domain provenance yields no fingerprint
# under existing callers (exception → fingerprint None / skipped).
# Booleans are handled separately (bool subclasses int).
_JS_MAX_SAFE_INTEGER = 9007199254740991
_JS_MIN_SAFE_INTEGER = -9007199254740991
def _canonical_json_number(num: float) -> str:
"""Serialize a finite IEEE-754 float via ECMAScript NumberToString.
Matches ECMAScript NumberToString (RFC 8785 / JCS numeric form):
integral values have no trailing ``.0``, ``±0`` is ``0``, and
scientific notation uses ES exponent thresholds (``e`` when the
exponent is < -6 or >= 21). Non-finite values raise ValueError.
Float subclasses are normalized via base ``float.__float__`` first so
hooks such as ``__float__``/``__abs__``/comparisons/``__repr__`` cannot
alter the underlying binary64 value used for math and emission.
"""
# Plain built-in float: ignore subclass __float__/__abs__/__lt__/...
num = float.__float__(num)
if not math.isfinite(num):
raise ValueError(
"non-finite numbers are not permitted in fingerprint JSON")
if num == 0.0:
return "0"
negative = num < 0
r = repr(abs(num))
if "e" in r or "E" in r:
mant, exp_s = r.lower().split("e")
exp = int(exp_s)
if "." in mant:
whole, frac = mant.split(".")
digits_raw = whole + frac
n = exp + len(whole)
else:
digits_raw = mant
n = exp + len(digits_raw)
else:
if "." in r:
whole, frac = r.split(".")
digits_raw = whole + frac
n = len(whole)
else:
digits_raw = r
n = len(digits_raw)
# Leading-zero strip adjusts n so value = int(digits)*10^(n-k) holds.
lead = len(digits_raw) - len(digits_raw.lstrip("0"))
digits = digits_raw.lstrip("0") or "0"
if digits != "0":
n -= lead
while len(digits) > 1 and digits[-1] == "0":
digits = digits[:-1]
k = len(digits)
sign = "-" if negative else ""
if 0 < n <= 21:
if k <= n:
return sign + digits + ("0" * (n - k))
return sign + digits[:n] + "." + digits[n:]
if -6 < n <= 0:
return sign + "0." + ("0" * (-n)) + digits
exp = n - 1
exp_s = f"+{exp}" if exp >= 0 else str(exp)
if k == 1:
return sign + digits + "e" + exp_s
return sign + digits[0] + "." + digits[1:] + "e" + exp_s
def _reject_unpaired_surrogates(s: str, *, what: str) -> None:
"""Fail closed on unpaired UTF-16 surrogates (invalid I-JSON / UTF-8)."""
for ch in s:
cp = ord(ch)
if 0xD800 <= cp <= 0xDFFF:
raise ValueError(
f"unpaired UTF-16 surrogate in fingerprint JSON {what}")
def _canonical_json_string(s: str) -> str:
"""Serialize a string in RFC 8785 / JCS string form.
JSON control characters, quotes, and backslashes are escaped; valid
Unicode (including non-ASCII, emoji, and U+2028/U+2029) is emitted as
raw code points (not ``ensure_ascii`` ``\\uXXXX`` escapes). Unpaired
surrogates raise ValueError rather than producing invalid I-JSON.
Str subclasses are normalized via base ``str.__str__`` first so
``__str__``/``__iter__`` hooks cannot redirect iteration or emission.
"""
# Plain built-in str: ignore subclass __str__/__iter__/...
s = str.__str__(s)
_reject_unpaired_surrogates(s, what="string")
return json.dumps(s, ensure_ascii=False)
def _utf16_code_unit_key(s: str) -> bytes:
"""Object-key sort key matching JCS / ECMAScript UTF-16 code unit order.
Str subclasses are normalized via base ``str.__str__`` first so
``__str__``/``__iter__``/``encode`` hooks cannot corrupt key order or
hide unpaired surrogates.
"""
# Plain built-in str: ignore subclass __str__/__iter__/encode hooks.
s = str.__str__(s)
_reject_unpaired_surrogates(s, what="object key")
return s.encode("utf-16-be")
def _canonical_fingerprint_json(value) -> str:
"""Canonical JSON text for fingerprint token/digest bytes.
Direct RFC 8785 / JCS-style canonical writer over the accepted Python
value tree. The resulting UTF-8 token bytes are authoritative for
``digest``; verifiers should hash those bytes rather than assuming plain
``JSON.stringify`` is itself JCS (it does not sort keys or implement
full JCS). Over values parsed under a JavaScript / IEEE-754 binary64
number model, this matches a JCS direct encoder for the accepted types:
- objects: each key is normalized once via base ``str.__str__`` to a
plain built-in str; keys sorted by UTF-16 code unit order on those
normalized names; no whitespace. Duplicate normalized names raise
ValueError (fail closed — distinct str-subclass keys can override
``__eq__``/``__hash__`` so both coexist in a Python dict while
``str.__str__`` yields the same text; emitting both would produce
duplicate JSON names that JS silently drops). Non-str keys raise
TypeError. The retained original key is used only for value lookup.
- arrays: element order preserved; no whitespace
- numbers (float): ECMAScript NumberToString for every finite IEEE-754
value after base ``float.__float__`` normalization (subclass hooks
ignored); non-finite numbers raise ValueError
- numbers (int): decimal digits only for exact integers inside the
product safe-integer domain [-(2**53-1), 2**53-1]. This is a strict
accepted-type policy guaranteeing unique lossless integer identity
across generic ECMAScript consumers — not a claim that every larger
individual value is unrepresentable as binary64. Exact integers
outside the domain raise ValueError (e.g. int 2**53); isolated
binary64 floats such as float(2**53) remain legal via the float path.
Int subclasses (e.g. IntEnum) are normalized via base ``int.__index__``
to a plain built-in int before domain checks and digit emission, so
``__index__``/``__int__``/comparison/``__str__``/``__repr__``/
``__format__`` hooks cannot change the value or bypass rejection.
Booleans are not integers.
- strings: JCS form — control/quote/backslash escapes, raw valid
Unicode; unpaired surrogates raise ValueError. Str subclasses are
normalized via base ``str.__str__`` so ``__str__``/``__iter__``/
``encode`` hooks cannot change emission, key order, or bypass
surrogate rejection.
- bools/null: ``true`` / ``false`` / ``null``
"""
if value is None:
return "null"
if value is True:
return "true"
if value is False:
return "false"
if isinstance(value, str):
return _canonical_json_string(value)
if isinstance(value, int) and not isinstance(value, bool):
# Plain built-in int via base slot: subclass __index__/__int__/
# comparison hooks must not bypass domain checks or alter digits
# (Python 3.9 IntEnum str was "Enum.NAME").
value = int.__index__(value)
if value < _JS_MIN_SAFE_INTEGER or value > _JS_MAX_SAFE_INTEGER:
raise ValueError(
"integers outside the JavaScript safe-integer range "
f"[{_JS_MIN_SAFE_INTEGER}, {_JS_MAX_SAFE_INTEGER}] "
"are not permitted in fingerprint JSON")
return int.__repr__(value)
if isinstance(value, float):
return _canonical_json_number(value)
if isinstance(value, list):
return "[" + ",".join(
_canonical_fingerprint_json(v) for v in value) + "]"
if isinstance(value, dict):
# Normalize each original key exactly once to a plain built-in str.
# Distinct str subclasses can override __eq__/__hash__ so two keys
# coexist while str.__str__ yields the same text; emit the
# normalized name, look up values via the retained original key,
# and fail closed on duplicate normalized names.
items = [] # (normalized_key, original_key)
seen_normalized = set()
for k in value.keys():
if not isinstance(k, str):
raise TypeError(
"fingerprint JSON object keys must be str, "
f"got {type(k).__name__}")
nk = str.__str__(k)
if nk in seen_normalized:
raise ValueError(
"duplicate fingerprint JSON object key after "
f"str normalization: {nk!r}")
seen_normalized.add(nk)
items.append((nk, k))
parts = []
for nk, orig in sorted(items, key=lambda ik: _utf16_code_unit_key(ik[0])):
parts.append(
_canonical_json_string(nk) + ":"
+ _canonical_fingerprint_json(value[orig]))
return "{" + ",".join(parts) + "}"
raise TypeError(
f"fingerprint JSON cannot encode {type(value).__name__}")
def build_fingerprint(provenance: dict) -> dict:
"""Build ``{token, digest, provenance}`` for a provenance dict.
``token`` is base64 of the canonical UTF-8 JSON bytes; ``digest`` is
``sha256:`` + hex of those same bytes. Verifiers should treat the decoded
token bytes as authoritative and hash them directly. Re-canonicalizing a
decoded value tree requires an RFC 8785/JCS direct encoder with an
IEEE-754 binary64 number model — default Python ``json.loads`` may yield
ints outside the product integer domain for tokens such as ``1e20``
(``100000000000000000000``). Project tests that rebuild from token text
use ``json.loads(text, parse_int=float)``. Out-of-domain inputs raise
here; existing callers yield no fingerprint (``None`` / skip).
"""
canonical = _canonical_fingerprint_json(provenance)
raw = canonical.encode("utf-8")
return {
"token": base64.b64encode(raw).decode("ascii"),
"digest": "sha256:" + hashlib.sha256(raw).hexdigest(),
"provenance": provenance,
}
# <<< fingerprint helpers
# Timestamped quote->account FX is fingerprinted from the exact values passed
# through the C ABI, not merely from provider-file metadata. The raw file hash
# remains useful provenance, while this canonical digest proves the effective
# broker input independently of JSON key order or whitespace.
ACCOUNT_CURRENCY_FX_CANONICALIZATION = "pf-account-currency-fx-i64-f64-le-v1"
_ACCOUNT_CURRENCY_FX_HASH_PREFIX = \
b"pineforge:account-currency-fx:i64-f64-le:v1\0"
_ACCOUNT_CURRENCY_FX_RECORD = struct.Struct("<qd")
def _account_currency_fx_values_sha256(timestamps, rates) -> str:
if len(timestamps) != len(rates) or not timestamps:
raise ValueError(
"account_currency_fx_series requires equal non-empty timestamp/rate arrays")
h = hashlib.sha256()
h.update(_ACCOUNT_CURRENCY_FX_HASH_PREFIX)
previous_timestamp = None
for raw_timestamp, raw_rate in zip(timestamps, rates):
timestamp = int(raw_timestamp)
rate = float(raw_rate)
if previous_timestamp is not None and timestamp <= previous_timestamp:
raise ValueError(
"account_currency_fx_series timestamps must be strictly increasing")
if not math.isfinite(rate) or rate <= 0.0:
raise ValueError(
"account_currency_fx_series rates must be positive and finite")
h.update(_ACCOUNT_CURRENCY_FX_RECORD.pack(timestamp, rate))
previous_timestamp = timestamp
return h.hexdigest()
def _effective_account_currency_fx_scalar(run_kwargs: dict) -> float:
metadata = run_kwargs.get("syminfo_metadata")
raw_value = metadata.get("account_currency_fx", 1.0) \
if isinstance(metadata, dict) else 1.0
try:
value = float(raw_value)
except (TypeError, ValueError):
return 1.0
return value if math.isfinite(value) and value > 0.0 else 1.0
def build_runtime_provenance(run_kwargs: dict, trade_start_ms: int | None) -> dict:
"""Return the effective runtime settings that participate in a fingerprint."""
fx_scalar = _effective_account_currency_fx_scalar(run_kwargs)
fx_series = run_kwargs.get("account_currency_fx_series")
fx_summary = None
if fx_series:
timestamps, rates = fx_series
fx_summary = {
"canonicalization": ACCOUNT_CURRENCY_FX_CANONICALIZATION,
"effective_values_sha256":
_account_currency_fx_values_sha256(timestamps, rates),
"source_file_sha256": run_kwargs.get(
"account_currency_fx_source_sha256") or "",
"fallback_account_per_quote": fx_scalar,
"points": len(timestamps),
"first_effective_ms": int(timestamps[0]),
"last_effective_ms": int(timestamps[-1]),
}
runtime = {
"input_tf": run_kwargs.get("input_tf") or "",
"script_tf": run_kwargs.get("script_tf") or "",
"bar_magnifier": bool(run_kwargs.get("bar_magnifier")),
"magnifier_samples": int(run_kwargs.get("magnifier_samples") or 4),
"magnifier_distribution": run_kwargs.get("magnifier_distribution") or "ENDPOINTS",
"chart_timezone": run_kwargs.get("chart_timezone") or "",
"trade_start_ms": None if trade_start_ms is None else int(trade_start_ms),
"account_currency_fx_scalar": fx_scalar,
"account_currency_fx_series": fx_summary,
}
aux_path = run_kwargs.get("aux_security_ohlcv_csv")
if aux_path is not None:
runtime["aux_security_feed"] = {
"input_tf": run_kwargs.get("aux_security_input_tf") or "",
"source_path": str(Path(aux_path).resolve()),
"source_file_sha256": run_kwargs.get(
"aux_security_source_file_sha256") or "",
"source_values_sha256": run_kwargs.get(
"aux_security_source_feed_sha256") or "",
}
native_feeds = run_kwargs.get("native_security_feeds")
if native_feeds:
# One entry per requested timeframe served by the exchange's own bars
# (strategy_set_native_security_feed): the file identity resolved at
# inputs time and, when the run supplied it, the parsed-values digest.
runtime["native_security_feeds"] = {
str(tf): {
"source_path": str(Path(entry["path"]).resolve()),
"source_file_sha256": entry.get("source_file_sha256") or "",
"source_values_sha256": entry.get("source_values_sha256") or "",
}
for tf, entry in sorted(native_feeds.items())
}
tail = run_kwargs.get("ohlcv_tail_bar")
if tail is not None:
# The input bar that completes a daily chart's cut last bar on the
# declared-magnifier route (_daily_bars_rebuilt).
runtime["ohlcv_tail_bar"] = [int(tail[0])] + [float(x) for x in tail[1:]]
calendar = _session_calendar_provenance(run_kwargs.get("syminfo_metadata"))
if calendar is not None:
runtime["session_calendar"] = calendar
quote = run_kwargs.get("report_terminal_quote")
if quote is not None:
runtime["report_terminal_quote"] = {
"time_ms": int(quote[0]),
"close": float(quote[1]),
"source_file_sha256": run_kwargs.get("report_terminal_quote_source_sha256") or "",
}
return runtime
def _session_calendar_provenance(metadata) -> dict | None:
"""The session calendar a run hands the Pine host (the "symbol_calendar_*"
syminfo metadata _session_calendar_metadata writes): its day count and
the sha256 of its days, one "open,close" line each; None without one."""
if not isinstance(metadata, dict) or "symbol_calendar_days" not in metadata:
return None
days = int(metadata["symbol_calendar_days"])
digest = hashlib.sha256()
for index in range(days):
open_ms = int(metadata[f"symbol_calendar_open:{index}"])
close_ms = int(metadata[f"symbol_calendar_close:{index}"])
digest.update(f"{open_ms},{close_ms}\n".encode("ascii"))
return {"days": days, "sessions_sha256": digest.hexdigest()}
# --- ctypes mirror of <pineforge/pineforge.h> -------------------------
#
# Field order, types, and widths must match the C struct exactly. The
# runtime library has corresponding static_assert(sizeof(...) == ...) and
# offsetof checks in src/c_abi.cpp; if any of these structs drift, the
# library fails to compile.
class BarC(ctypes.Structure):
_fields_ = [
("open", ctypes.c_double),
("high", ctypes.c_double),
("low", ctypes.c_double),
("close", ctypes.c_double),
("volume", ctypes.c_double),
("timestamp", ctypes.c_int64),
]
class TradeTickC(ctypes.Structure):
"""Mirror of pf_trade_tick_t for historical -> realtime handoff."""
_fields_ = [
("timestamp", ctypes.c_int64),
("sequence", ctypes.c_uint64),
("price", ctypes.c_double),
("quantity", ctypes.c_double),
]
class TradeC(ctypes.Structure):
_fields_ = [
("entry_time", ctypes.c_int64),
("exit_time", ctypes.c_int64),
("entry_price", ctypes.c_double),
("exit_price", ctypes.c_double),
("pnl", ctypes.c_double),
("pnl_pct", ctypes.c_double),
("is_long", ctypes.c_int),
("max_runup", ctypes.c_double),
("max_drawdown", ctypes.c_double),
("qty", ctypes.c_double),
("commission", ctypes.c_double),
("entry_bar_index", ctypes.c_int32),
("exit_bar_index", ctypes.c_int32),
# ABI v3: 1 on the range-end close of a position still open after the
# final bar (TradingView's deep-backtest accounting; pineforge.h).
("open_at_end", ctypes.c_int32),
]
class TradeStatsC(ctypes.Structure):
"""Mirror of pf_trade_stats_t (ABI v2)."""
_fields_ = [
("num_trades", ctypes.c_int32), ("num_wins", ctypes.c_int32),
("num_losses", ctypes.c_int32), ("num_even", ctypes.c_int32),
("percent_profitable", ctypes.c_double),
("net_profit", ctypes.c_double), ("net_profit_pct", ctypes.c_double),
("gross_profit", ctypes.c_double), ("gross_profit_pct", ctypes.c_double),
("gross_loss", ctypes.c_double), ("gross_loss_pct", ctypes.c_double),
("profit_factor", ctypes.c_double),
("avg_trade", ctypes.c_double), ("avg_trade_pct", ctypes.c_double),
("avg_win", ctypes.c_double), ("avg_win_pct", ctypes.c_double),
("avg_loss", ctypes.c_double), ("avg_loss_pct", ctypes.c_double),
("ratio_avg_win_avg_loss", ctypes.c_double),
("largest_win", ctypes.c_double), ("largest_win_pct", ctypes.c_double),
("largest_loss", ctypes.c_double), ("largest_loss_pct", ctypes.c_double),
("commission_paid", ctypes.c_double),
("expectancy", ctypes.c_double),
("max_consecutive_wins", ctypes.c_int32), ("max_consecutive_losses", ctypes.c_int32),
("avg_bars_in_trade", ctypes.c_double), ("avg_bars_in_wins", ctypes.c_double),
("avg_bars_in_losses", ctypes.c_double),
]
class EquityStatsC(ctypes.Structure):
"""Mirror of pf_equity_stats_t (ABI v2)."""
_fields_ = [
("max_equity_drawdown", ctypes.c_double), ("max_equity_drawdown_pct", ctypes.c_double),
("max_equity_runup", ctypes.c_double), ("max_equity_runup_pct", ctypes.c_double),
("buy_hold_return", ctypes.c_double), ("buy_hold_return_pct", ctypes.c_double),
# The C field names. The JSON report keys of these two stay
# sharpe_tv / sortino_tv (ADR-0001, "Deprecated public spellings").
("sharpe_monthly", ctypes.c_double), ("sortino_monthly", ctypes.c_double),
("sharpe_bar", ctypes.c_double), ("sortino_bar", ctypes.c_double),
("cagr", ctypes.c_double), ("calmar", ctypes.c_double),
("recovery_factor", ctypes.c_double), ("time_in_market_pct", ctypes.c_double),
("open_pl", ctypes.c_double),
]
class MetricsC(ctypes.Structure):
"""Mirror of pf_metrics_t (ABI v2)."""
_fields_ = [("all", TradeStatsC), ("longs", TradeStatsC),
("shorts", TradeStatsC), ("equity", EquityStatsC)]
class EquityPointC(ctypes.Structure):
"""Mirror of pf_equity_point_t (ABI v2)."""
_fields_ = [("time_ms", ctypes.c_int64), ("equity", ctypes.c_double),
("open_profit", ctypes.c_double)]
class SecurityDiagC(ctypes.Structure):
_fields_ = [
("sec_id", ctypes.c_int),
("feed_count", ctypes.c_int64),
("eval_complete_count", ctypes.c_int64),
("eval_partial_count", ctypes.c_int64),
]
class TraceEntryC(ctypes.Structure):
_fields_ = [
("timestamp", ctypes.c_int64),
("bar_index", ctypes.c_int32),
("name_id", ctypes.c_int32),
("value", ctypes.c_double),
]
class ReportC(ctypes.Structure):
_fields_ = [
("total_trades", ctypes.c_int),
("trades", ctypes.POINTER(TradeC)),
("trades_len", ctypes.c_int),
("net_profit", ctypes.c_double),
("input_bars_processed", ctypes.c_int64),
("script_bars_processed", ctypes.c_int64),
("security_feeds_total", ctypes.c_int64),
("security_eval_complete_total", ctypes.c_int64),
("security_eval_partial_total", ctypes.c_int64),
("magnifier_sub_bars_total", ctypes.c_int64),
("magnifier_sample_ticks_total", ctypes.c_int64),
("input_tf_seconds", ctypes.c_int),
("script_tf_seconds", ctypes.c_int),
("script_tf_ratio", ctypes.c_int),
("needs_aggregation", ctypes.c_int),
("bar_magnifier_enabled", ctypes.c_int),
("security_diag", ctypes.POINTER(SecurityDiagC)),
("security_diag_len", ctypes.c_int),
("trace", ctypes.POINTER(TraceEntryC)),
("trace_len", ctypes.c_int),
("trace_names", ctypes.POINTER(ctypes.c_char_p)),
("trace_names_len", ctypes.c_int),
("metrics", MetricsC),
("equity_curve", ctypes.POINTER(EquityPointC)),
("equity_curve_len", ctypes.c_int64), # int64 in the C header, NOT c_int
("broker_state_hash", ctypes.POINTER(ctypes.c_uint64)),
("broker_state_hash_len", ctypes.c_int64),
]
# ABI version this harness mirrors (PF_ABI_VERSION in pineforge.h).
# pf_report_t is CALLER-allocated: running an old .so against the v3
# ReportC mirror (or vice versa) silently corrupts memory, so the .so's
# pf_abi_version() export is asserted before any run. v3 appended
# pf_trade_t::open_at_end (TradeC above); v4 appended the live-runtime
# accessors and grew pf_report_t with the broker_state_hash array after
# equity_curve_len (ReportC above already carries both fields).
# test_run_strategy_range_end.py pins this constant to the header's
# macro, because the campaign's verifier runs every probe through THIS
# harness and a stale guard here is a run-error on every slug (the
# f-1d spark pre-check of 2026-09-02 found exactly that: ".so reports
# 3, harness expects 2" x64).
EXPECTED_PF_ABI = 4
def _check_abi(lib: ctypes.CDLL) -> None:
try:
lib.pf_abi_version.restype = ctypes.c_int
abi = lib.pf_abi_version()
except AttributeError:
raise RuntimeError(
"strategy .so predates pf_abi_version (ABI v1); rebuild it against "
"the current pineforge runtime (pf_report_t grew).")
if abi != EXPECTED_PF_ABI:
raise RuntimeError(
f"pineforge ABI mismatch: .so reports {abi}, harness expects "
f"{EXPECTED_PF_ABI}; rebuild.")
class PfVersionC(ctypes.Structure):
"""Mirror of pf_version_t (returned by value from pf_version_get)."""
_fields_ = [("major", ctypes.c_int), ("minor", ctypes.c_int),
("patch", ctypes.c_int), ("commit_sha", ctypes.c_char_p)]
class PfFieldDescC(ctypes.Structure):
"""Mirror of pf_field_desc_t (<pineforge/pending_order_mirror.hpp>): one
row of the self-describing pf_pending_order_v1_t field table returned by
strategy_pending_order_layout (ABI v4 live-runtime surface, task 7)."""
_fields_ = [("name", ctypes.c_char_p), ("type", ctypes.c_char_p),
("offset", ctypes.c_uint32), ("size", ctypes.c_uint32)]
# C type spelling in a pf_field_desc_t row -> ctypes scalar. `char[N]` is
# handled separately (an N-byte c_char array).
_PF_FIELD_CTYPES = {
"uint8_t": ctypes.c_uint8,
"uint32_t": ctypes.c_uint32,
"int32_t": ctypes.c_int32,
"int64_t": ctypes.c_int64,
"uint64_t": ctypes.c_uint64,
"double": ctypes.c_double,
}
_PF_CHAR_ARRAY_RE = re.compile(r"^char\[(\d+)\]$")
PENDING_ORDER_STRUCT_VERSION = 1
# strategy_pending_order_fill_qty partition codes (pineforge.h, ABI v4 task 8).
FILL_QTY_PARTITIONS = {
0: "EXPLICIT", 1: "FROZEN_PLACEMENT", 2: "DEFAULT_STOP_PLACEMENT", 3: "AT_FILL"}
def _nan_to_none(x: float) -> float | None:
"""NaN / inf sentinels -> None (JSON null); finite doubles unchanged."""
x = float(x)
return x if math.isfinite(x) else None
def _pending_order_layout(lib: ctypes.CDLL) -> list[tuple[str, str, int, int]]:
"""Read strategy_pending_order_layout() into [(name, type, offset, size)]."""
count = ctypes.c_int(0)
descs = lib.strategy_pending_order_layout(ctypes.byref(count))
return [(descs[i].name.decode("ascii"), descs[i].type.decode("ascii"),
int(descs[i].offset), int(descs[i].size)) for i in range(count.value)]
def build_pending_order_struct(layout: list[tuple[str, str, int, int]]) -> type:
"""Build the ctypes.Structure mirroring pf_pending_order_v1_t FROM THE
RUNTIME'S OWN FIELD TABLE (strategy_pending_order_layout), never from a
hand-typed field list: the mirror is append-only and generated from
engine.hpp (scripts/gen_pending_order_mirror.py), so a reader typed by
hand would silently desynchronise the first time intent row grows.
Every ctypes offset/size is cross-checked against the table and a
mismatch raises rather than mis-reading the book."""
if not layout:
raise RuntimeError("strategy_pending_order_layout returned no fields")
fields = []
for name, ctype, offset, size in layout:
m = _PF_CHAR_ARRAY_RE.match(ctype)
if m:
ct = ctypes.c_char * int(m.group(1))
elif ctype in _PF_FIELD_CTYPES:
ct = _PF_FIELD_CTYPES[ctype]
else:
raise RuntimeError(
f"strategy_pending_order_layout: field {name!r} has unknown C type "
f"{ctype!r}; extend _PF_FIELD_CTYPES in run_strategy.py")
if ctypes.sizeof(ct) != size:
raise RuntimeError(
f"strategy_pending_order_layout: field {name!r} ({ctype}) is {size} "
f"bytes in the runtime but {ctypes.sizeof(ct)} in ctypes")
fields.append((name, ct))
if fields[0][0] != "struct_version" or fields[1][0] != "size":
raise RuntimeError(
"strategy_pending_order_layout: table must start with struct_version, size; "
f"got {[f[0] for f in fields[:2]]}")
cls = type("IntentRowV1", (ctypes.Structure,), {"_fields_": fields})
for name, _ctype, offset, _size in layout:
got = getattr(cls, name).offset
if got != offset:
raise RuntimeError(
f"strategy_pending_order_layout: field {name!r} is at byte {offset} in the "
f"runtime but ctypes placed it at {got} (natural alignment differs?)")
last_name, _, last_off, last_size = layout[-1]
if ctypes.sizeof(cls) < last_off + last_size:
raise RuntimeError(
f"strategy_pending_order_layout: sizeof(IntentRowV1) {ctypes.sizeof(cls)} < "
f"end of {last_name!r} ({last_off + last_size})")
return cls
def pending_order_to_dict(rec, layout: list[tuple[str, str, int, int]]) -> dict:
"""One pf_pending_order_v1_t record -> JSON-ready dict, in field order.
char[N] -> str (up to the NUL); NaN/inf doubles -> None (JSON has no
NaN; the engine's "not set" sentinel); EVERY uint64_t field (the
*_hash64 digests, incarnation / *_incarnation, signal_close_mc_fill_seq,
...) -> 16-hex-digit string, because a uint64 is not a JS-safe number
and a consumer must not silently round one; everything else (uint8_t /
int32_t / int64_t / uint32_t / double) -> int/float."""
out = {}
for name, ctype, _offset, _size in layout:
v = getattr(rec, name)
if ctype.startswith("char["):
out[name] = bytes(v).decode("utf-8", "replace")