@@ -1081,20 +1081,18 @@ void BacktestEngine::revive_position_brackets_after_margin_call_partial(
10811081 double margin_call_event_price) {
10821082 const double mc_price = margin_call_event_price;
10831083 if (position_side_ == PositionSide::FLAT ) return ;
1084- static const std::string kClosePrefix = " __close__" ;
10851084 PendingOrder* marketable = nullptr ;
10861085 for (PendingOrder& o : pending_orders_) {
10871086 if (o.type != OrderType::EXIT ) continue ;
10881087 if (o.suppress_as_declined_reversal_close ) continue ;
10891088 if (o.id .size () >= kClosePrefix .size ()
10901089 && o.id .compare (0 , kClosePrefix .size (), kClosePrefix ) == 0 ) continue ;
10911090 if (!o.dormant_bracket ) continue ;
1092- bool bound = o.from_entry .empty ();
1093- if (!bound) {
1094- for (const auto & pe : pyramid_entries_) {
1095- if (pe.entry_id == o.from_entry ) { bound = true ; break ; }
1096- }
1097- }
1091+ // finding-347: mirror the dormancy predicate — position-cycle
1092+ // provenance, not bucket residency, so a leg orphaned by a sibling's
1093+ // FIFO drain revives with its siblings.
1094+ const bool bound = o.from_entry .empty ()
1095+ || cycle_filled_entry_ids_.count (o.from_entry ) != 0 ;
10981096 if (!bound) continue ;
10991097 o.dormant_bracket = false ;
11001098 // Marketable at the margin-call event price? (Full-percent default
@@ -4710,6 +4708,7 @@ void BacktestEngine::apply_exit_order_fill(PendingOrder& order, double fill_pric
47104708 snapshot_entry_commission (materialized);
47114709 pyramid_entries_.push_back (std::move (materialized));
47124710 id_unclosed_qty_[order.id ] += qty;
4711+ cycle_filled_entry_ids_.insert (order.id );
47134712 return ;
47144713 }
47154714
@@ -4727,6 +4726,18 @@ void BacktestEngine::apply_exit_order_fill(PendingOrder& order, double fill_pric
47274726 size_t trades_before_exit = trades_.size ();
47284727 PositionSide side_before_exit = position_side_;
47294728
4729+ // finding-348: the pyramiding slot released by this reduction depends on
4730+ // WHICH exit retired the units. strategy.close / close_all materialise as
4731+ // EXIT orders carrying the kClosePrefix id stamp; every other EXIT order
4732+ // reaching this kernel is a strategy.exit bracket leg. That prefix is the
4733+ // only structural discriminator available here, and it is exact.
4734+ const bool is_bracket_exit =
4735+ order.type == OrderType::EXIT
4736+ && !(order.id .size () >= kClosePrefix .size ()
4737+ && order.id .compare (0 , kClosePrefix .size (), kClosePrefix ) == 0 );
4738+ const auto cause = is_bracket_exit ? PositionReductionCause::BRACKET_EXIT
4739+ : PositionReductionCause::SCRIPT_ORDER ;
4740+
47304741 if (close_entries_rule_any_ && !order.from_entry .empty ()) {
47314742 // close_entries_rule="ANY": close only matching entries
47324743 if (is_partial) {
@@ -4738,28 +4749,43 @@ void BacktestEngine::apply_exit_order_fill(PendingOrder& order, double fill_pric
47384749 // their percentage at fill time.
47394750 if (has_explicit_qty_to_close) {
47404751 execute_partial_exit_by_entry_qty (
4741- fill_price, order.from_entry , order.qty );
4752+ fill_price, order.from_entry , order.qty , cause );
47424753 } else {
47434754 execute_partial_exit_by_entry_percent (
4744- fill_price, order.from_entry , qp);
4755+ fill_price, order.from_entry , qp, cause );
47454756 }
47464757 } else {
4747- execute_partial_exit_by_entry (fill_price, order.from_entry );
4758+ execute_partial_exit_by_entry (fill_price, order.from_entry , cause );
47484759 }
47494760 } else {
47504761 if (dynamic_full_live_qty) {
47514762 execute_market_exit (fill_price);
47524763 } else if (has_explicit_qty_to_close) {
4753- execute_partial_exit_qty (fill_price, order.qty );
4764+ execute_partial_exit_qty (fill_price, order.qty , cause );
47544765 } else if (is_partial) {
4755- execute_partial_exit (fill_price, qp);
4766+ execute_partial_exit (fill_price, qp, cause );
47564767 } else {
47574768 execute_market_exit (fill_price);
47584769 }
47594770 }
47604771
4772+ // The one-shot guard belongs to the exit ID, but an id can carry more than
4773+ // one bracket leg (strategy_exit's per-entry-instance leg multiplicity: one
4774+ // binding for the already-open fills, one for a pending same-id entry).
4775+ // Consuming the id on the FIRST leg's fill would make the surviving sibling
4776+ // unre-issuable while the position is still open. Mark the id consumed only
4777+ // when the last leg carrying it is gone.
47614778 if (order.requested_partial && trades_.size () > trades_before_exit) {
4762- consumed_partial_exit_ids_.insert (order.id );
4779+ bool sibling_leg_still_live = false ;
4780+ for (const PendingOrder& sibling : pending_orders_) {
4781+ if (sibling.type != OrderType::EXIT ) continue ;
4782+ if (sibling.incarnation == order.incarnation ) continue ; // self
4783+ if (sibling.id != order.id ) continue ;
4784+ if (sibling.from_entry != order.from_entry ) continue ;
4785+ sibling_leg_still_live = true ;
4786+ break ;
4787+ }
4788+ if (!sibling_leg_still_live) consumed_partial_exit_ids_.insert (order.id );
47634789 }
47644790
47654791 // KI-62: the normal close above drained only the frozen pre-add reserve
@@ -4768,7 +4794,7 @@ void BacktestEngine::apply_exit_order_fill(PendingOrder& order, double fill_pric
47684794 // covers it — scratch it dur-0 at the exit's fill price. A strict no-op
47694795 // when no such add filled (the KEEP cell: the exit fills first, so the add
47704796 // is not yet open here; and non-collision shapes flag no add slice).
4771- double scratched = cover_samebar_market_adds_on_exit (order, fill_price);
4797+ double scratched = cover_samebar_market_adds_on_exit (order, fill_price, cause );
47724798
47734799 // Full exit that closed the position: pending SAME-direction entries
47744800 // placed on a different on_bar are cancelled for the rest of this
@@ -4876,10 +4902,12 @@ void BacktestEngine::apply_raw_order_fill(PendingOrder& order, double fill_price
48764902 trail_best_price_ = fill_price;
48774903 pyramid_entries_.clear ();
48784904 id_unclosed_qty_.clear ();
4905+ cycle_filled_entry_ids_.clear ();
48794906 pyramid_entries_.push_back ({fill_price, current_bar_.timestamp , qty, order.id , bar_index_});
48804907 pyramid_entries_.back ().entry_incarnation = order.incarnation ;
48814908 snapshot_entry_commission (pyramid_entries_.back ());
48824909 id_unclosed_qty_[order.id ] += qty;
4910+ cycle_filled_entry_ids_.insert (order.id );
48834911 if (!std::isnan (order.stop_price ) || !std::isnan (order.limit_price )) {
48844912 set_entry_fill_excursion_masks (pyramid_entries_.back (), current_bar_, fill_price);
48854913 }
@@ -4936,6 +4964,7 @@ void BacktestEngine::apply_raw_order_fill(PendingOrder& order, double fill_price
49364964 // same-bar from_entry bracket exit can scratch them dur-0.
49374965 pyramid_entries_.back ().market_pyramid_add = !is_priced_entry;
49384966 id_unclosed_qty_[order.id ] += new_qty;
4967+ cycle_filled_entry_ids_.insert (order.id );
49394968 if (is_priced_entry) {
49404969 set_entry_fill_excursion_masks (pyramid_entries_.back (), current_bar_, fill_price);
49414970 }
@@ -4956,15 +4985,12 @@ void BacktestEngine::materialize_relative_exit_prices_for_live_position() {
49564985 const double dir = (position_side_ == PositionSide::LONG ) ? 1.0 : -1.0 ;
49574986 for (auto & order : pending_orders_) {
49584987 if (order.type != OrderType::EXIT ) continue ;
4959- if (!order.from_entry .empty ()) {
4960- bool has_parent_entry = false ;
4961- for (const auto & pe : pyramid_entries_) {
4962- if (pe.entry_id == order.from_entry ) {
4963- has_parent_entry = true ;
4964- break ;
4965- }
4966- }
4967- if (!has_parent_entry) continue ;
4988+ // finding-347: position-cycle provenance, mirroring the eligibility
4989+ // gate — a leg whose bucket has been FIFO-drained is still live and
4990+ // still needs its ticks resolved against the position entry price.
4991+ if (!order.from_entry .empty ()
4992+ && cycle_filled_entry_ids_.count (order.from_entry ) == 0 ) {
4993+ continue ;
49684994 }
49694995 if (std::isnan (order.limit_price ) && !std::isnan (order.profit_ticks )) {
49704996 order.limit_price = position_entry_price_ + dir * order.profit_ticks * syminfo_mintick_;
@@ -5009,7 +5035,6 @@ void BacktestEngine::materialize_relative_exit_prices_for_live_position() {
50095035// re-credit).
50105036void BacktestEngine::suppress_declined_reversal_close_legs (
50115037 const PendingOrder& declined_entry) {
5012- static const std::string kClosePrefix = " __close__" ;
50135038 for (PendingOrder& co : pending_orders_) {
50145039 if (co.suppress_as_declined_reversal_close ) continue ; // idempotent
50155040 if (co.type != OrderType::EXIT ) continue ;
@@ -5031,7 +5056,6 @@ void BacktestEngine::suppress_declined_reversal_close_legs(
50315056}
50325057
50335058void BacktestEngine::mark_position_brackets_dormant_on_declined_reversal () {
5034- static const std::string kClosePrefix = " __close__" ;
50355059 if (position_side_ == PositionSide::FLAT ) return ;
50365060 // The live position's entry ids (pyramid lots) — a bracket is "standing"
50375061 // when its from_entry names one of them, or when it is a global
@@ -5051,12 +5075,12 @@ void BacktestEngine::mark_position_brackets_dormant_on_declined_reversal() {
50515075 || !std::isnan (o.trail_points )
50525076 || !std::isnan (o.trail_price );
50535077 if (!priced) continue ;
5054- bool bound = o. from_entry . empty ();
5055- if (!bound) {
5056- for ( const auto & pe : pyramid_entries_) {
5057- if (pe. entry_id == o. from_entry ) { bound = true ; break ; }
5058- }
5059- }
5078+ // finding-347: a standing bracket is one whose from_entry filled in
5079+ // THIS position cycle (or a global from_entry-less exit) — not one
5080+ // whose bucket still holds units. A leg orphaned by a sibling's FIFO
5081+ // drain is still standing and must go dormant with its siblings.
5082+ const bool bound = o. from_entry . empty ()
5083+ || cycle_filled_entry_ids_. count (o. from_entry ) != 0 ;
50605084 if (!bound) continue ;
50615085 o.dormant_bracket = true ;
50625086 }
@@ -5324,20 +5348,30 @@ BacktestEngine::OrderEligibility BacktestEngine::classify_order_eligibility(
53245348 }
53255349 }
53265350
5327- // Skip exit orders whose from_entry doesn't match any active entry id.
5328- if (order.type == OrderType::EXIT && !order.from_entry .empty ()) {
5329- bool has_match = false ;
5330- for (const auto & pe : pyramid_entries_) {
5331- if (pe.entry_id == order.from_entry ) {
5332- has_match = true ;
5333- break ;
5334- }
5335- }
5336- if (!has_match) {
5337- // Cancel stale from_entry-bound exits so they cannot fire later
5338- // against future positions with the same id.
5339- return OrderEligibility::Remove;
5340- }
5351+ // Cancel exit orders whose from_entry never filled in THIS position cycle.
5352+ //
5353+ // finding-347: liveness is POSITION-scoped, not entry-bucket-scoped. TV
5354+ // keeps a from_entry bracket alive for as long as the position lives; once
5355+ // a sibling bracket FIFO-consumes the leg's own units, the leg still fires
5356+ // and draws from the position-level queue. The direct proof is TV's
5357+ // cross-assigned exit labels at 2025-06-17 / 2025-10-14 / 2026-01-14, where
5358+ // `Short` + `ShortAdd` fill 2u each on one bar and the T1 pair drains both
5359+ // `Short` units: TV still fires BOTH T2 legs (`T2 Exit` closes a ShortAdd
5360+ // unit, `Add T1` closed a Short unit). Testing pyramid_entries_ residency
5361+ // instead Removed the orphaned `ShortT2` permanently, so the engine fired
5362+ // only 3 of 4 units, carried a phantom unit, and was never flat — which is
5363+ // also what made the 06-18 entry look like a pyramiding-cap case when it is
5364+ // a flat-reset case. from_entry decides only whether a leg is ALLOWED TO
5365+ // EXIST (its parent entry must have filled in this position), never which
5366+ // units it may take; the fill path already draws FIFO across buckets.
5367+ //
5368+ // The Remove path's original purpose — stale exits must not fire later
5369+ // against a FUTURE position reusing the id — is preserved exactly, because
5370+ // cycle_filled_entry_ids_ is cleared the moment the position goes flat
5371+ // (reset_position_state_to_flat / open_fresh_position / the RAW_ORDER open).
5372+ if (order.type == OrderType::EXIT && !order.from_entry .empty ()
5373+ && cycle_filled_entry_ids_.count (order.from_entry ) == 0 ) {
5374+ return OrderEligibility::Remove;
53415375 }
53425376
53435377 // Same-bar exit handling: TradingView evaluates priced exits (stop/limit/
0 commit comments