Skip to content

Commit 650b0cb

Browse files
luisleo526claude
andcommitted
fix: report a position still open after the final bar as TradingView's range-end close
TradingView's deep-backtest report (the ws-report-v1 tape the campaign grades against) 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. The canonical row is orb-lite on NYSE:F 1D: Entry short 2026-03-16 @ 11.82, Exit 2026-04-30 @ 12.08 -- 12.08 is the last close of the range, metrics closedTrades:1. On the f-1d spark set 8/10 engine runs held the same position to the last bar (bars-in-market = TV Duration + 1) and 7/10 had a mark-to-market open_pl equal to TV's row to the cent: the row is exactly the engine's open position marked at the last close. The engine exported closed trades only (trades_ grows in emit_close_trade alone; neither run loop flattened at end of feed), so every such probe was one trade short against the tape and the verifier scored the missing row as an unmatched TV trade. The browser export writes the same row with Signal "Open", which the verifier already recognises; the ws tape gives it no marker at all. Operator decision (2026-09-02): the engine emulates TradingView's range-end accounting, in the report. After the last script bar is dispatched and its equity point recorded, record_range_end_close_trades builds the rows a close of the open position at the last bar's close would record -- one per pyramid slice through the same arithmetic as every other close (build_close_trade, split out of emit_close_trade) -- into range_end_trades_, which fill_trades_section merges behind the script's closed trades. The live position, pending orders, trades_ and the realized sums are left as the bar loop left them: a stream's realtime bars continue the warmup position, Pine accessors never see the row, and the broker-mechanics tests keep inspecting the open lot. Pricing: the row is a mark at the close, not an order the broker fills -- the raw close rounded to the nearest tick (bar_fill_price, finding-446; the tape's 12.08 is the on-tick close), no slippage ticks, commission per the strategy's rules on the exit leg like any close (the tape in hand has commission 0, so that is the operator's call, not a measurement), dated on the script bar's label. Accounting: the report's closed-trade count, net profit, win/loss tallies and commission paid include the rows. Every equity point before the last is untouched; the last point is re-marked to the flat account (open_profit 0, equity = capital + net profit including the rows) so the report identity equity == initial_capital + net_profit + open_pl that test_metrics pins still holds on the last bar -- with the tape's commission 0 and an on-tick close that point's equity VALUE is the gross mark it already was. A first cut re-marked the point and left the scalar extremes at the bar loop's gross fold; review showed that broke the compute_equity_stats walk == scalar identity on every commissioned run whose last bar was the trough or the peak (the fold had seen the gross mark, the walk the net one), so the scalars are re-folded from the curve after the re-mark (fold_equity_extreme, split out of update_equity_extremes): the walk and the scalars agree again, and every earlier bar's drawdown / run-up is unchanged. A strategy flat after the final bar is unaffected. The measurement must END where TradingView's range ends, or the row is booked on the wrong bar. The engine marks after the last bar it is FED, and the ETH chart feed (eth-corpus-15 / eth-scraped-15) runs on to 2026-05-04 15:00 UTC while every ETH tape's range ends 2026-05-01 (228 of 397 scrapper tapes with an Open row at 05-01 00:00 UTC @ 2261.44 = that bar's close); the ws-report lanes' feeds already end there. run_strategy.py now bounds the feed (ohlcv_end_ms, on both runners; the docker runner pre-trims through _trim_ohlcv_csv) to TradingView's RANGE END whenever the TV window is in use and the tape is UNMARKED (the v4 rule, below): the bars opening at or before the tape's `to` as 00:00 UTC, read from the metrics.json beside the tape (wsProvenance.requestedRange.to when the ws exporter recorded the window it sent, else the `to` date; _load_tv_range_end_ms). The rule is TradingView's own, read off the ws tapes' returnedRange.to against the requestedRange.to = 2026-05-01 00:00 UTC every campaign tape asked for: BTC/ES/NQ/XAU 15 return 05-01 00:00 (the bar OPENING at `to` is inside, 00:15 is not -- on CME's America/Chicago chart too, so `to` is UTC midnight, not the chart tz's), NYSE:F 1D returns 04-30 13:30 (the 05-01 13:30 session bar exists and is excluded), ES/NQ 1D 04-30 22:00, XAU 1D 04-30 21:00, NIFTY 15/1D 04-30 09:45/03:45, F 15 04-30 19:45 -- and every lane's open-position row sits on exactly that bar (survey of the scrapper's 17 lane directories, 1,356 tapes, 2026-09-02). Not the tape's last trade row. A first cut bounded the feed there, and the full-population gate (gate-cand-range-end-close-20260902) failed hard.regression on scrapper:data/standard/waranyutrkm-asian-box-breakout- eda-tuned (ETH 15): 110 -> 109 trades, match 100 -> 99.1. Its last trade closes 04-29 18:00 UTC, so the feed was cut mid-day, and the strategy gates entries on request.security(.., "D", close / ta.ema(close, 50), lookahead=barmerge.lookahead_on): under the historical lookahead projection (the probe's winning verifier candidate) every 04-29 chart bar reads the 04-29 daily bar's FINAL value. Cut at 18:00 the partial day gave d_close 2240.35 < d_ema 2241.85 and no long; the complete day, as TV sees it with its range running to 05-01, gives 2251.52 > 2242.29 and TV's trade 110 at 09:45 (spark, Route A: bound at the tape row 109 trades sha dc086072, bound at 04-29 23:45 / 05-01 00:00 / unbounded 110 trades sha c5ebd23f = the Cloud Run baseline; the four other near-range-end closed probes in the shard are byte-identical either way). Any probe with a lookahead_on HTF projection and a closed last trade inside the final HTF period is exposed the same way. A metrics.json without a range falls back to the tape's latest row. Trades ENTERED after TV's last entry are still dropped by _filter_trades_to_window. The auxiliary request.security feed (the ETH lane's 1m FEED_1M) is left as exported: the engine's routing ignores aux bars labelled past the last chart bar (engine_aux_security.cpp tail prefilter), so the chart's last bar keeps its full slice and no chart bar is lost; test_aux_security_feed pins that on the 15m chart / 1m aux shape. The row reaches engine_trades.csv only when the tape prints it the same way, and WHERE the measurement ends is the tape's call too. Two exporters write the campaign's tapes: ws-report-v1 (every 1D lane and most 15m; 286 of the 305 ETH tapes in the ws lanes; no marker in metrics.json beyond tapeChannel) reports the range-end position as an ordinary closed trade with an empty Signal, the shape the emulation targets; the browser export (metrics.json without tapeChannel; 227 of the 396 scraped ETH tapes) writes the same row with Signal "Open". TV nets commission on BOTH legs of an Open row exactly as on a close -- 3commas-xlm-grid-bot #615: qty 0.0912, entry 2189.13, mark 2261.44 -> 6.3511 = TV's 6.35 = the engine's 6.351137 -- so per-lot P&L is exact to the cent; the difference is what the grader does with the marker. The v4 rule (2026-09-02), keyed on the marker (_tv_tape_marks_open_rows: any row whose Signal.strip().lower() is "open"; _apply_range_end_regime applies it and main() logs one line saying which regime applied and why): UNMARKED tape -> the range-end regime (v2): bound the feed at TV's range end as above and write the range-end close rows. Every unmarked lane measured was clean under it: f-1d 10/10 engine-0 -> excellent, waranyutrkm asian-box 110/110 at 100%, and the 8 unmarked range-end ETH tapes byte-identical (spark smoke-m2v3 / smoke-m2v3b / f-1d). MARKED tape -> the BASELINE behaviour: no ohlcv_end_ms bound (the feed as exported, three days past every ETH tape's range) and no open_at_end row written -- the rows are withheld from engine_trades.csv (_withhold_open_at_end_trades; with an unbounded feed a position may still be open at the FEED's end, and that mark is withheld like any other), logging the count withheld and why and counting it on the summary line. The CSV is then the baseline's to the byte. The marked regime is the baseline's because the baseline traded past TV's range end and the canonical grader (scripts/verify_corpus.py) pairs those post-range closes with TV's Open rows on ENTRY time -- the match the campaign's scores are built on. Two bounded variants were measured on spark against it. v2 (bound + emit on every tape) paired the marks exactly but moved pnlP90 on the three 3commas grid bots by the cent-rounding of TV's Net PnL -- gate v2 4gfpn on tree ad21d0e: hard lane 5 better / 696 same / 3 worse, scrapper:data/standard/ 3commas-{3commas-xlm,btcusdt-p,nvdax}-grid-bot-long-strategy matchPct 94.3 -> 100 but pnlP90 0.55 -> 0.67, 0.53 -> 0.64, 0.18 -> 0.93 (22/22/28 open lots each, marked Open at 2026-05-01 08:00 +8) -- and the hard gate counts any metric increase as a regression. v3 (bound + withhold on marked tapes) turned every post-range close into a withheld open_at_end row and lost the pairing on ~186 marked probes (3commas-xlm 94.3 -> 93.7 strong, alexgrover 100 -> 99.8; spark smoke-m2v3 pre-check). Until verify_corpus.py pairs the marks itself (the follow-up), a marked tape is measured exactly as the baseline measured it. The verifier grades the CSV alone (run_strategy.py writes no report JSON), so the CSV is the whole of what it sees. The range-end engine mechanics are the same under both regimes. The browser export's Open row can also be priced at the export-time quote rather than a bar's print: all 12 sampled OANDA:EURUSD tapes end with Open rows @ 1.17256 while the feed's last bar is o 1.17289 h 1.17299 l 1.17282 c 1.1729 (246 of 358 EURUSD tapes end with such a row). verify_corpus.py treats a TV Open row whose engine counterpart exits on the SAME bar as count-only (counted, covered, entry compared; exit/pnl deltas left out and the pair reported as open_mark_pairs); an engine exit on a different bar keeps its deltas, since TV held to the end and the engine did not. With the harness withholding the row against a marked tape that pair no longer forms on a normal run; the rule stays for a CSV written without a tape window (--no-trim-output / --emit-window-ohlcv), where the row is still emitted. pineforge-utils/validator/validate.py tracks this rubric and needs the same rule. pf_trade_t gains open_at_end (1 on the range-end row) -- ABI v3, with the ctypes mirrors (run_strategy, docker/run_json, tutorial, benchmarks) and the docs updated; run_strategy.py carries the flag on the report dict and writes the CSV row as an ordinary exit with no marker, the way the ws tape prints it, or withholds it against a browser tape as above. run_stream_corpus compares the trades the two brokers made, without the range-end rows. tests/test_range_end_close.cpp pins the row (long, short, flat, pyramid slices, commission on both legs, rounded close without slippage, aggregated-path label, earlier curve points untouched and the last re-marked flat, walk == scalar extremes with commission and the last bar as trough and as peak, re-run reset); test_run_inputs_overrides and test_accounting_reconciliation foot the report to the blotter plus the range-end rows; scripts/test_run_strategy_range_end.py pins the range-end rule (the ws integer and the browser date, every lane's returnedRange under it), the bound on the asian-box shape (a closed last trade before the range end keeps the whole final day and every bar through TV's last bar, where the tape-row bound cut it at 18:00), the Open-row shape (the last bar the engine sees is the bar and price of TV's Open row), the NYSE:F 1D shape (the 04-30 bar kept, a 05-01 session bar dropped), the fallback to the tape's last row without a range, and the harness's EXPECTED_PF_ABI to the header's PF_ABI_VERSION (the f-1d spark pre-check of 2026-09-02 failed all 64 probes with ".so reports 3, harness expects 2" while that guard was still 2 -- the verifier runs every probe through run_strategy.py), and the v4 regime through _apply_range_end_regime and through main() with the engine stubbed: a marked tape sets no bound, withholds the open_at_end rows (the mark at the feed's end included) and leaves the closed rows -- a post-range close among them -- intact with the count logged; an unmarked tape is bounded at the range end (the ws integer, the browser date, the tape's last row as the fallback, a probe's own ohlcv_end_ms kept) and writes the rows; a header-only tape sets no bound and writes every row; and the one log line names the regime and its source; scripts/test_verify_corpus_open_mark.py pins the EURUSD Open-row pairing. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01BXAE7TVTKZYbmtenHDHVJo
1 parent bc78cc7 commit 650b0cb

24 files changed

Lines changed: 2207 additions & 62 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ int main(void) {
354354
| `pf_version_string` | Full runtime version string |
355355
356356
357-
POD types (`pf_bar_t`, `pf_trade_tick_t`, `pf_trade_t`, `pf_report_t`, `pf_security_diag_t`, `pf_trace_entry_t`, `pf_version_t`, and — since ABI v2 — `pf_trade_stats_t`, `pf_equity_stats_t`, `pf_metrics_t`, `pf_equity_point_t`) and the `pf_magnifier_distribution_t` enum complete the surface. ABI v2 (`PF_ABI_VERSION == 2`, exported as `pf_abi_version()`) appends computed trading metrics and a per-script-bar equity curve to `pf_report_t`; callers must verify the version before running since the report struct is caller-allocated.
357+
POD types (`pf_bar_t`, `pf_trade_tick_t`, `pf_trade_t`, `pf_report_t`, `pf_security_diag_t`, `pf_trace_entry_t`, `pf_version_t`, and — since ABI v2 — `pf_trade_stats_t`, `pf_equity_stats_t`, `pf_metrics_t`, `pf_equity_point_t`) and the `pf_magnifier_distribution_t` enum complete the surface. ABI v2 appends computed trading metrics and a per-script-bar equity curve to `pf_report_t`; ABI v3 (`PF_ABI_VERSION == 3`, exported as `pf_abi_version()`) appends `pf_trade_t::open_at_end`, the flag on the range-end close of a position still open after the final bar (TradingView's deep-backtest accounting). Callers must verify the version before running since the report struct is caller-allocated and the trades array stride grew.
358358
359359
**Stability guarantee:** within the same `PINEFORGE_VERSION_MAJOR`, struct layouts and `extern "C"` signatures are append-only. New fields may be appended; existing fields are never reordered, removed, or retyped. New functions may be added; existing functions are never removed or signature-changed. Compile-time `static_assert`s in `src/c_abi.cpp` pin the layouts against drift.
360360

‎benchmarks/throughput/grid_search_repro.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ class pf_trade_t(ctypes.Structure):
2929
("commission", ctypes.c_double),
3030
("entry_bar_index", ctypes.c_int32),
3131
("exit_bar_index", ctypes.c_int32),
32+
("open_at_end", ctypes.c_int32), # ABI v3: range-end close row
3233
]
3334

3435
class pf_trade_stats_t(ctypes.Structure):
@@ -127,7 +128,7 @@ class pf_report_t(ctypes.Structure):
127128

128129
# pf_report_t is caller-allocated; a layout mismatch means the runtime
129130
# writes past this script's report buffer. Verify the ABI before running.
130-
EXPECTED_PF_ABI = 2
131+
EXPECTED_PF_ABI = 3
131132

132133
def check_abi(lib):
133134
try:

‎docker/run_json.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242
"commission": float, # ABI v2
4343
"entry_bar_index": int, # ABI v2: script-bar index of entry fill
4444
"exit_bar_index": int, # ABI v2: script-bar index of exit fill
45+
"open_at_end": bool, # ABI v3: range-end close of a position still
46+
# open after the final bar (TV accounting)
4547
"entry_incarnation": int # run-scoped physical-entry provenance;
4648
# 0 when the strategy lacks the accessor
4749
},
@@ -575,6 +577,7 @@ class TradeC(ctypes.Structure):
575577
("commission", ctypes.c_double),
576578
("entry_bar_index", ctypes.c_int32),
577579
("exit_bar_index", ctypes.c_int32),
580+
("open_at_end", ctypes.c_int32), # ABI v3: range-end close row
578581
]
579582

580583

@@ -701,7 +704,7 @@ def engine_version(lib: ctypes.CDLL) -> dict:
701704

702705
# pf_report_t is CALLER-allocated: a .so built against a different ABI
703706
# writes past (or short of) our ReportC buffer. Assert version up front.
704-
EXPECTED_PF_ABI = 2
707+
EXPECTED_PF_ABI = 3
705708

706709

707710
def check_abi(lib: ctypes.CDLL) -> None:
@@ -869,6 +872,7 @@ def build_report_dict(report: ReportC, ohlcv_path: Path,
869872
"commission": float(t.commission),
870873
"entry_bar_index": int(t.entry_bar_index),
871874
"exit_bar_index": int(t.exit_bar_index),
875+
"open_at_end": bool(t.open_at_end),
872876
"entry_incarnation": (
873877
int(trade_entry_incarnations[i])
874878
if trade_entry_incarnations is not None

‎docs/pages/examples-rust.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ struct PfTrade {
6060
commission: f64,
6161
entry_bar_index: i32,
6262
exit_bar_index: i32,
63+
// ABI v3: 1 on the range-end close of a position still open after the
64+
// final bar (TradingView's deep-backtest accounting)
65+
open_at_end: i32,
6366
}
6467

6568
// ── ABI v2 metrics PODs ──────────────────────────────────────────────
@@ -165,7 +168,7 @@ struct PfReport {
165168
const PF_MAGNIFIER_ENDPOINTS: c_int = 3;
166169

167170
// PfReport is CALLER-allocated: before any run, resolve `pf_abi_version`
168-
// via libloading and assert it returns 2 (PF_ABI_VERSION) — an old .so
171+
// via libloading and assert it returns 3 (PF_ABI_VERSION) — an old .so
169172
// writing into this larger struct (or vice versa) corrupts memory silently.
170173

171174
// ── Safe wrapper ──────────────────────────────────────────────────────

‎docs/pages/ffi-python.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ class pf_trade_t(ctypes.Structure):
4848
("commission", ctypes.c_double), # ABI v2
4949
("entry_bar_index", ctypes.c_int32), # ABI v2
5050
("exit_bar_index", ctypes.c_int32), # ABI v2
51+
("open_at_end", ctypes.c_int32), # ABI v3: range-end close row
5152
]
5253

5354
class pf_trade_stats_t(ctypes.Structure):
@@ -177,7 +178,7 @@ lib = ctypes.CDLL("./my_strategy.so")
177178
# ABI guard — pf_report_t is CALLER-allocated, so running an old .so
178179
# against the v2 mirror above (or vice versa) silently corrupts memory.
179180
# Verify the .so's layout version before any run:
180-
EXPECTED_PF_ABI = 2 # PF_ABI_VERSION in <pineforge/pineforge.h>
181+
EXPECTED_PF_ABI = 3 # PF_ABI_VERSION in <pineforge/pineforge.h>
181182
try:
182183
lib.pf_abi_version.restype = ctypes.c_int
183184
abi = lib.pf_abi_version()

‎docs/pages/report-schema.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,10 @@ typedef struct pf_report_s {
5858

5959
@note The `metrics` / `equity_curve` fields were appended in **ABI
6060
version 2** (`PF_ABI_VERSION`). `pf_report_t` is caller-allocated, so
61-
consumers must check `pf_abi_version() == 2` before running — a `.so`
61+
consumers must check `pf_abi_version() == 3` before running — a `.so`
6262
with no `pf_abi_version` symbol is ABI v1 and predates these fields.
63+
**ABI version 3** appends `pf_trade_t::open_at_end`, the range-end close
64+
flag; a v2 reader would misindex the trades array.
6365

6466
## Trade fields
6567

@@ -88,6 +90,9 @@ typedef struct pf_trade_s {
8890
double commission; /* ABI v2: entry+exit commission deducted from pnl */
8991
int32_t entry_bar_index;/* ABI v2: script-bar index of entry fill (0-based) */
9092
int32_t exit_bar_index; /* ABI v2: script-bar index of exit fill (0-based) */
93+
int32_t open_at_end; /* ABI v3: 1 on the range-end close of a position still
94+
open after the final bar (TradingView's deep-backtest
95+
accounting: exit = last bar at its close, no Signal) */
9196
} pf_trade_t;
9297
```
9398

‎include/pineforge/engine.hpp‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,10 @@ struct Trade {
105105
// Physical-entry provenance copied from PyramidEntry. This is deliberately
106106
// separate from entry_id: Pine permits user-visible IDs to be reused.
107107
uint64_t entry_incarnation = 0;
108+
// True for the range-end close of a position still open after the final
109+
// bar (record_range_end_close_trades); false for every script-driven
110+
// or bracket exit. Mirrors pf_trade_t::open_at_end.
111+
bool open_at_end = false;
108112
};
109113

110114
struct TradeC {
@@ -124,6 +128,7 @@ struct TradeC {
124128
double commission; // mirrors pf_trade_t tail; semantics documented in pineforge.h
125129
int32_t entry_bar_index;
126130
int32_t exit_bar_index;
131+
int32_t open_at_end; // ABI v3: 1 on the range-end close row (pineforge.h)
127132
};
128133

129134
struct SecurityDiagC {
@@ -1125,6 +1130,12 @@ class BacktestEngine {
11251130
bool current_fill_is_limit_ = false;
11261131

11271132
std::vector<Trade> trades_;
1133+
// TradingView's range-end accounting (record_range_end_close_trades,
1134+
// engine_orders.cpp): the rows that close a position still open after
1135+
// the final script bar, at that bar's close. Report-only — they are
1136+
// merged behind trades_ by fill_trades_section and never enter trades_,
1137+
// the realized sums, or the live position (a stream continues it).
1138+
std::vector<Trade> range_end_trades_;
11281139
std::vector<PendingOrder> pending_orders_;
11291140
// A rejected strategy.entry call leaves no PendingOrder behind. The exact
11301141
// collision gate can consume only the immediately preceding source bar, so
@@ -2388,9 +2399,13 @@ class BacktestEngine {
23882399

23892400
// --- Equity extremes update (called after each on_bar) ---
23902401
// NOTE: the dd/runup walk in src/engine_metrics.cpp (compute_equity_stats)
2391-
// MUST mirror this trough-reset logic; keep in lockstep.
2392-
void update_equity_extremes() {
2393-
double eq = initial_capital_ + net_profit_sum_ + open_profit(current_bar_.close);
2402+
// MUST mirror this trough-reset logic; keep in lockstep. The fold is
2403+
// exactly one per script bar and always paired with record_equity_point,
2404+
// so the curve holds the very values folded here and a re-walk of the
2405+
// curve through fold_equity_extreme reproduces the scalars bit for bit
2406+
// — record_range_end_close_trades (engine_orders.cpp) relies on that
2407+
// when it re-marks the last point.
2408+
void fold_equity_extreme(double eq) {
23942409
if (eq > max_equity_) {
23952410
max_equity_ = eq;
23962411
min_equity_ = eq; // reset trough on new peak
@@ -2402,6 +2417,9 @@ class BacktestEngine {
24022417
if (dd > max_drawdown_) max_drawdown_ = dd;
24032418
double ru = eq - min_equity_;
24042419
if (ru > max_runup_) max_runup_ = ru;
2420+
}
2421+
void update_equity_extremes() {
2422+
fold_equity_extreme(initial_capital_ + net_profit_sum_ + open_profit(current_bar_.close));
24052423

24062424
// --- Update max_contracts_held_* running peaks ---
24072425
double abs_qty = std::abs(position_qty_);
@@ -2578,6 +2596,14 @@ class BacktestEngine {
25782596
bool explicit_qty_prequantized,
25792597
uint64_t entry_incarnation);
25802598
void execute_market_exit(double fill_price);
2599+
// Range-end accounting: record the rows that close a position still
2600+
// open after the final script bar at that bar's close, the way
2601+
// TradingView's deep-backtest report does (engine_orders.cpp). Called by
2602+
// every run() overload after its bar loop; a no-op when flat or during
2603+
// a stream warmup replay. Reporting only: the live position is kept; the
2604+
// last equity point is re-marked to the flat account and the scalar
2605+
// drawdown / run-up extremes re-folded from the curve to match.
2606+
void record_range_end_close_trades();
25812607
void execute_partial_exit_qty(
25822608
double fill_price, double qty_to_close,
25832609
PositionReductionCause cause = PositionReductionCause::SCRIPT_ORDER);
@@ -2818,6 +2844,13 @@ class BacktestEngine {
28182844
// engine_orders.cpp).
28192845
void emit_close_trade(const PyramidEntry& pe, double close_qty,
28202846
double fill_price, bool was_long);
2847+
// The arithmetic of emit_close_trade without its bookkeeping: the Trade
2848+
// row a close of ``close_qty`` of ``pe`` at ``fill_price`` on the
2849+
// current bar would record (pnl, pnl_pct, commission, excursions, bar
2850+
// indexes). emit_close_trade builds and commits; the range-end close
2851+
// builds only.
2852+
Trade build_close_trade(const PyramidEntry& pe, double close_qty,
2853+
double fill_price, bool was_long) const;
28212854
// FIFO-drain up to qty_limit from pyramid_entries_, in order, splitting the
28222855
// boundary entry as needed. When from_entry is non-null only entries whose
28232856
// entry_id == *from_entry are eligible (others are kept untouched); null

‎include/pineforge/pineforge.h‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,10 @@
7474
* iterate the trades array with the stale sizeof. Value 2 = first
7575
* versioned layout (metrics + equity curve); .so files predating this
7676
* macro have no pf_abi_version symbol — treat dlsym failure as
77-
* version 1. */
78-
#define PF_ABI_VERSION 2
77+
* version 1. Value 3 appends pf_trade_t::open_at_end (the range-end
78+
* close flag); a v2 reader iterating trades with the v2 stride would
79+
* misindex every row after the first. */
80+
#define PF_ABI_VERSION 3
7981

8082
/** Feature probe for the opt-in split chart/request.security feed boundary.
8183
* When defined, #strategy_set_aux_security_feed is available. */
@@ -156,6 +158,21 @@ typedef struct pf_trade_s {
156158
* (account currency). pnl is already net of this. */
157159
int32_t entry_bar_index;/**< Script-bar index of the entry fill (0-based). */
158160
int32_t exit_bar_index; /**< Script-bar index of the exit fill (0-based). */
161+
int32_t open_at_end; /**< 1 when this row is the RANGE-END close of a position
162+
* that was still open after the final bar; 0 for an
163+
* exit the script or a bracket produced. TradingView's
164+
* deep-backtest report does not leave the last position
165+
* open: it reports it as a closed trade whose exit leg is
166+
* the range's last bar at that bar's CLOSE, with an
167+
* empty exit Signal, and counts it in closedTrades
168+
* (orb-lite on NYSE:F 1D: Entry short 2026-03-16 @ 11.82,
169+
* Exit 2026-04-30 @ 12.08 = the last close,
170+
* closedTrades:1). The engine emulates that row
171+
* (operator decision 2026-09-02): exit_time is the last
172+
* script bar's label, exit_price its mintick-rounded
173+
* close with no slippage, commission per the strategy's
174+
* rules, pnl/pnl_pct/excursions as for any close.
175+
* Appended in ABI v3. */
159176
} pf_trade_t;
160177

161178
/** Trade-level statistics block — computed once each for all / long / short.
@@ -314,8 +331,11 @@ typedef struct pf_trace_entry_s {
314331

315332
typedef struct pf_report_s {
316333
/* Trades */
317-
int total_trades; /**< Closed-trade count (== trades_len). */
318-
pf_trade_t* trades; /**< Heap array of closed trades. */
334+
int total_trades; /**< Closed-trade count (== trades_len), including
335+
* the range-end close of a position still open
336+
* after the final bar (pf_trade_t::open_at_end). */
337+
pf_trade_t* trades; /**< Heap array of closed trades; script-driven exits
338+
* first, then the range-end rows (open_at_end=1). */
319339
int trades_len; /**< Length of #trades. */
320340
double net_profit; /**< Sum of all closed-trade PnL. */
321341

‎scripts/pf_release_run.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ def report_trades_to_runstrategy_shape(report: dict) -> list[dict]:
155155
"commission": float(t.get("commission", 0.0)),
156156
"entry_bar_index": int(t.get("entry_bar_index", -1)),
157157
"exit_bar_index": int(t.get("exit_bar_index", -1)),
158+
"open_at_end": bool(t.get("open_at_end", False)),
158159
"entry_incarnation": int(t.get("entry_incarnation", 0) or 0),
159160
})
160161
return out

0 commit comments

Comments
 (0)