Skip to content

Commit 8df08f2

Browse files
authored
fix(engine): make dead strategy.close semantically inert (#143)
Remove the source-text AST gate from deferred-flip carry while retaining the legacy field as a generated-code compatibility no-op. Add metamorphic coverage for unreachable strategy.close and update characterization tests and runtime documentation.
1 parent d9e3510 commit 8df08f2

6 files changed

Lines changed: 112 additions & 40 deletions

File tree

‎docs/cheatsheet-runtime-and-execution.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ Sentinels for "not overridden": `NaN` (doubles), `-1` (ints).
6161
| `close_entries_rule` | FIFO | `ANY`/`any`/`1` = ANY, else FIFO |
6262

6363
**Compile-time only (no override path):** `margin_long` / `margin_short`
64-
(default 100 = 1x), `script_has_strategy_close_` (gates the deferred-flip rule).
64+
(default 100 = 1x). `script_has_strategy_close_` is retained only as a legacy
65+
generated-code compatibility bit and does not affect runtime behavior.
6566

6667
## 1.3 `strategy.risk.*` — compile-time only
6768

@@ -210,8 +211,9 @@ mintick directionally (buys ceil, sells floor).
210211

211212
**Deferred-flip carry (`tv_carry_qty`, `|old|+qty`):** a **priced** entry firing
212213
**from flat** opposite to its `created_position_side` opens at `carry + base_qty`
213-
**iff** all hold: `script_has_strategy_close_`, priced entry, `carry > 0`,
214-
opposite direction. Carry snapshot taken **at `strategy.entry` call time** =
214+
**iff** all hold: priced entry, `carry > 0`, opposite direction. This also
215+
applies when a `strategy.exit` bracket closed the source position. Carry
216+
snapshot taken **at `strategy.entry` call time** =
215217
`max(0, position_qty_ − pending_close_qty_in_bar_)`. Same-id replacement
216218
re-snaps carry; siblings in the same cycle get carry zeroed on fire.
217219

‎include/pineforge/engine.hpp‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -902,11 +902,12 @@ class BacktestEngine {
902902
// callers that want the legacy hold-to-infinity behaviour.
903903
bool margin_call_enabled_ = true;
904904

905-
// True iff the user's strategy.pine contains at least one
906-
// ``strategy.close`` or ``strategy.close_all`` call (compile-time
907-
// determined by the codegen, set in the generated class's
908-
// constructor). Gates the TradingView deferred-flip growth rule
909-
// applied in ``execute_market_entry``'s FLAT branch.
905+
// Legacy codegen compatibility bit. Older and current generated classes
906+
// set this when the Pine source contains ``strategy.close`` or
907+
// ``strategy.close_all``. Runtime behavior must not depend on it: a
908+
// bracket exit can also close a carry source, and unreachable source code
909+
// cannot be allowed to change fills. Keep the member until generated
910+
// classes no longer write it.
910911
bool script_has_strategy_close_ = false;
911912
int64_t trade_start_time_ = std::numeric_limits<int64_t>::min();
912913

‎src/engine_orders.cpp‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -745,17 +745,17 @@ void BacktestEngine::consume_tv_carry_from_siblings(const std::string& id,
745745
// transient state.
746746
//
747747
// Conditions:
748-
// (a) script_has_strategy_close_ -- compile-time AST scan (gates the
749-
// rule to strategies that can
750-
// actually trigger the deferred-flip
751-
// pattern)
752-
// (b) is_priced_entry -- stop/limit, not market
753-
// (c) tv_carry_qty > 0 -- order was placed while a position
748+
// (a) is_priced_entry -- stop/limit, not market
749+
// (b) tv_carry_qty > 0 -- order was placed while a position
754750
// was open
755-
// (d) requested != created direction
751+
// (c) requested != created direction
756752
// -- new entry is opposite to the carry
757753
// position
758754
//
755+
// Do not gate this on the compile-time ``script_has_strategy_close_`` AST
756+
// scan. A bracket from ``strategy.exit`` can close the source position too,
757+
// and adding an unreachable ``strategy.close`` must be semantically inert.
758+
//
759759
// After applying the carry, ``consume_tv_carry_from_siblings`` zeroes the
760760
// same-source-cycle siblings so probe 93 doesn't double-grow.
761761
//
@@ -776,10 +776,10 @@ void BacktestEngine::enter_market_from_flat(const std::string& id, bool is_long,
776776
int created_bar,
777777
bool explicit_qty_prequantized,
778778
uint64_t entry_incarnation) {
779-
bool carry_was_long = (created_position_side == PositionSide::LONG);
780-
bool tv_deferred_flip =
781-
script_has_strategy_close_
782-
&& is_priced_entry
779+
const bool carry_was_long =
780+
created_position_side == PositionSide::LONG;
781+
const bool tv_deferred_flip =
782+
is_priced_entry
783783
&& tv_carry_qty > 0.0
784784
&& (carry_was_long ? !is_long : is_long);
785785
double base_qty = explicit_qty_prequantized

‎tests/test_close_all_coqueued_entry.cpp‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -409,22 +409,28 @@ static void test_G_carry_priorbar_still_cancelled() {
409409
// G-opposite (KI-64 untouched — characterization). An opposite-direction entry
410410
// co-queued with close_all is never a target of the same-direction wipe
411411
// (is_long != exit_closed_was_long); its behavior is IDENTICAL before and after
412-
// this fix. Pins the current engine behavior: the opposite short stop survives
413-
// and fills when touched.
412+
// this fix. Pins the generated-script behavior: the opposite short stop
413+
// survives and fills with its placement-time reversal transaction. Because
414+
// this source contains close_all, legacy codegen set
415+
// script_has_strategy_close_=true even before issue #141 removed that AST bit
416+
// from the runtime predicate.
414417
//
415418
// bar0: entry("L0", mkt)
416419
// bar1: L0 fills @100 → LONG 1. arm OPPOSITE short stop "SOPP"@90 + close_all()
417420
// bar2: close_all fills @100 → FLAT (1 trade). SOPP opposite dir → untouched;
418421
// low 99 > 90 stays pending.
419-
// bar3: low 88 ≤ 90 → SOPP fires → SHORT 1.
422+
// bar3: low 88 ≤ 90 → SOPP fires from flat with carry 1 + own 1 → SHORT 2.
420423
//
421-
// EXPECTED (pre- and post-fix, characterization): position ends SHORT 1.
424+
// EXPECTED (pre- and post-fix, generated-source characterization): SHORT 2.
422425
// ─────────────────────────────────────────────────────────────────────
423426
static void test_G_opposite_unchanged_ki64() {
424427
std::printf("G-opposite (KI-64 opposite-direction unchanged)\n");
425428
class Probe : public ProbeBase {
426429
public:
427-
Probe() : ProbeBase(2) {}
430+
Probe() : ProbeBase(2) {
431+
// Match what codegen emits for the reachable close_all below.
432+
script_has_strategy_close_ = true;
433+
}
428434
void on_bar(const Bar&) override {
429435
if (bar_index_ == 0) strategy_entry("L0", true);
430436
if (bar_index_ == 1) {
@@ -443,7 +449,7 @@ static void test_G_opposite_unchanged_ki64() {
443449
};
444450
p.run(bars, 5);
445451
CHECK(p.trade_count() == 1);
446-
CHECK(near(p.pos_size(), -1.0)); // opposite entry survives (unchanged pre/post)
452+
CHECK(near(p.pos_size(), -2.0)); // carry + own qty (unchanged pre/post)
447453
}
448454

449455
// ─────────────────────────────────────────────────────────────────────

‎tests/test_same_id_stop_replace.cpp‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,6 @@ class StopReplaceProbe : public BacktestEngine {
8181
slippage_ = 0;
8282
commission_value_ = 0;
8383
pyramiding_ = 1;
84-
// The deferred-flip carry rule is gated on the script having a
85-
// ``strategy.close`` call — set it true so the carry-leak
86-
// regression (default position_qty_ before any fill) would
87-
// surface as qty=2 rather than being silently masked.
88-
script_has_strategy_close_ = true;
8984
}
9085

9186
void snapshot() {
@@ -307,9 +302,9 @@ static void test_new_entry_after_same_bar_fill_defers_to_next_bar() {
307302
// strategy.entry placed BEFORE the first fill of any session must
308303
// capture tv_carry_qty=0, not the engine's default
309304
// ``position_qty_=1.0`` value. Pre-fix, the LE order's tv_carry_qty
310-
// was 1, which combined with ``script_has_strategy_close_=true`` and
311-
// the order firing from FLAT in the LONG direction produced
312-
// tv_deferred_flip = (true && true && carry=1>0 && (false?:true=true))
305+
// was 1, which combined with the priced order firing from FLAT in the
306+
// LONG direction produced
307+
// tv_deferred_flip = (priced && carry=1>0 && (false?:true=true))
313308
// → qty = 1 + 1 = 2 instead of 1. Probe 62's first in-window trade
314309
// fired qty=2 with double the expected PnL (-18.22 vs TV's -9.11),
315310
// breaking parity even before the warmup-gate buffer fix exposed the

‎tests/test_strategy_pyramiding.cpp‎

Lines changed: 75 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,6 @@ class DeferredFlipProbe : public BacktestEngine {
7676
slippage_ = 0;
7777
commission_value_ = 0;
7878
pyramiding_ = 1;
79-
// The deferred-flip rule is gated on the script having a
80-
// ``strategy.close`` call at compile time. The codegen would
81-
// set this flag from an AST scan; here we set it directly.
82-
script_has_strategy_close_ = true;
8379
}
8480

8581
void on_bar(const Bar& bar) override {
@@ -126,6 +122,50 @@ class DeferredFlipProbe : public BacktestEngine {
126122
int last_bar_index_seen = -1;
127123
};
128124

125+
// Metamorphic probe for issue #141. Both instances execute exactly the same
126+
// broker commands: a bracket closes the source long, then a pre-armed priced
127+
// short entry fires from flat. The only difference is the legacy codegen AST
128+
// bit that says whether the Pine source contains any strategy.close call.
129+
// An unreachable call can change that bit but cannot change runtime behavior.
130+
class BracketExitDeferredFlipProbe : public BacktestEngine {
131+
public:
132+
explicit BracketExitDeferredFlipProbe(bool ast_has_strategy_close) {
133+
initial_capital_ = 1'000'000;
134+
default_qty_type_ = QtyType::FIXED;
135+
default_qty_value_ = 1.0;
136+
slippage_ = 0;
137+
commission_value_ = 0;
138+
pyramiding_ = 1;
139+
syminfo_mintick_ = 0.01;
140+
script_has_strategy_close_ = ast_has_strategy_close;
141+
}
142+
143+
void on_bar(const Bar&) override {
144+
if (bar_index_ == 0) {
145+
strategy_entry("L", true,
146+
std::numeric_limits<double>::quiet_NaN(),
147+
std::numeric_limits<double>::quiet_NaN(), 1.0);
148+
}
149+
if (bar_index_ == 1 && position_side_ == PositionSide::LONG) {
150+
strategy_entry("S", false,
151+
/*limit=*/105.0,
152+
std::numeric_limits<double>::quiet_NaN(), 1.0);
153+
strategy_exit("XL", "L",
154+
std::numeric_limits<double>::quiet_NaN(),
155+
/*stop=*/95.0);
156+
}
157+
if (bar_index_ == 3) {
158+
final_side = position_side_;
159+
final_qty = position_qty_;
160+
closed_trade_count = trade_count();
161+
}
162+
}
163+
164+
PositionSide final_side = PositionSide::FLAT;
165+
double final_qty = 0.0;
166+
int closed_trade_count = -1;
167+
};
168+
129169
} // namespace
130170

131171
// Scenario 1: deferred-flip oracle (probe 95-style). Cycle qty grows
@@ -170,6 +210,36 @@ static void test_deferred_flip_chain_grows() {
170210
CHECK(max_qty >= 2);
171211
}
172212

213+
// Scenario 1b: a strategy.exit bracket is itself sufficient to close the
214+
// source position before a priced opposite entry fires. The global AST scan
215+
// for strategy.close must not decide whether the captured carry applies.
216+
static void test_unreachable_strategy_close_is_semantically_inert() {
217+
std::printf("test_unreachable_strategy_close_is_semantically_inert\n");
218+
Bar bars[4] = {
219+
{100, 101, 99, 100, 1000, 60'000},
220+
{100, 101, 99, 100, 1000, 120'000}, // L fills; arm S + XL
221+
{100, 101, 94, 95, 1000, 180'000}, // XL closes L; S untouched
222+
{100, 106, 99, 105, 1000, 240'000}, // S limit fires from flat
223+
};
224+
225+
BracketExitDeferredFlipProbe without_dead_close(false);
226+
BracketExitDeferredFlipProbe with_dead_close(true);
227+
without_dead_close.run(bars, 4);
228+
with_dead_close.run(bars, 4);
229+
230+
CHECK(without_dead_close.last_error().empty());
231+
CHECK(with_dead_close.last_error().empty());
232+
CHECK(without_dead_close.final_side == PositionSide::SHORT);
233+
CHECK(with_dead_close.final_side == PositionSide::SHORT);
234+
CHECK(near(without_dead_close.final_qty, 2.0));
235+
CHECK(near(with_dead_close.final_qty, 2.0));
236+
CHECK(near(without_dead_close.final_qty, with_dead_close.final_qty));
237+
CHECK(without_dead_close.closed_trade_count == 1);
238+
CHECK(with_dead_close.closed_trade_count == 1);
239+
CHECK(without_dead_close.closed_trade_count ==
240+
with_dead_close.closed_trade_count);
241+
}
242+
173243
// Scenario 2: deferred-flip is gated on opposite direction. A
174244
// pre-armed SAME-direction priced entry (long stop placed during a
175245
// long, position closes, long stop later fires from flat) should NOT
@@ -191,7 +261,6 @@ static void test_same_direction_no_carry() {
191261
slippage_ = 0;
192262
commission_value_ = 0;
193263
pyramiding_ = 1;
194-
script_has_strategy_close_ = true;
195264
}
196265
void on_bar(const Bar& bar) override {
197266
if (bar_index_ == 0) {
@@ -323,7 +392,6 @@ static void test_two_cycle_siblings_independent_carry() {
323392
slippage_ = 0;
324393
commission_value_ = 0;
325394
pyramiding_ = 5;
326-
script_has_strategy_close_ = true;
327395
}
328396
void on_bar(const Bar& bar) override {
329397
(void)bar;
@@ -487,7 +555,6 @@ static void test_per_leg_fifo_pnl_three_legs() {
487555
slippage_ = 0;
488556
commission_value_ = 0;
489557
pyramiding_ = 3;
490-
script_has_strategy_close_ = true;
491558
}
492559
void on_bar(const Bar& bar) override {
493560
(void)bar;
@@ -689,6 +756,7 @@ static void test_overcap_same_id_reissue_removes_old_pending_order() {
689756

690757
int main() {
691758
test_deferred_flip_chain_grows();
759+
test_unreachable_strategy_close_is_semantically_inert();
692760
test_same_direction_no_carry();
693761
test_two_cycle_siblings_independent_carry();
694762
test_per_bar_pending_close_resets_in_script_tf_run();

0 commit comments

Comments
 (0)