Skip to content

Commit 337729f

Browse files
author
PineForge Factorial
committed
factorial: pyramiding-count-occupancy+exit-bracket-pending-entry-leg+bracket-leg-position-cycle-lifetime [engine]
1 parent 76d4dc9 commit 337729f

10 files changed

Lines changed: 1338 additions & 79 deletions

‎include/pineforge/engine.hpp‎

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <cmath>
77
#include <ctime>
88
#include <limits>
9+
#include <set>
910
#include <unordered_map>
1011
#include <unordered_set>
1112
#include "na.hpp"
@@ -699,6 +700,12 @@ class BacktestEngine {
699700
int64_t position_cycle_seq_ = 0;
700701
int64_t next_position_cycle_seq_ = 1;
701702
std::vector<PyramidEntry> pyramid_entries_; // individual entries for trade reporting
703+
// Entry ids that have filled at least once in the CURRENT position cycle.
704+
// TV keeps a from_entry bracket live for the life of the POSITION, not the
705+
// life of its own entry leg: once the leg's units are FIFO-consumed by a
706+
// sibling bracket, the leg still fires against the remaining position
707+
// (thulashimohanr 06-17/10-14/01-14: Short's T2 closes a ShortAdd unit).
708+
std::set<std::string> cycle_filled_entry_ids_;
702709
// Per-entry-id UNCLOSED quantity ledger, used ONLY by strategy.close(id)
703710
// under the default FIFO close-entries rule to decide how much to close.
704711
//
@@ -2355,7 +2362,8 @@ class BacktestEngine {
23552362

23562363
private:
23572364
enum class PositionReductionCause {
2358-
SCRIPT_ORDER,
2365+
SCRIPT_ORDER, // strategy.close / close_all / market exit / reversal
2366+
BRACKET_EXIT, // a strategy.exit bracket leg fill
23592367
MARGIN_CALL,
23602368
};
23612369

@@ -2375,18 +2383,28 @@ class BacktestEngine {
23752383
void execute_partial_exit_qty(
23762384
double fill_price, double qty_to_close,
23772385
PositionReductionCause cause = PositionReductionCause::SCRIPT_ORDER);
2378-
void execute_partial_exit(double fill_price, double qty_percent);
2379-
void execute_partial_exit_by_entry(double fill_price, const std::string& from_entry);
2380-
void execute_partial_exit_by_entry_qty(double fill_price,
2381-
const std::string& from_entry,
2382-
double qty_to_close);
2383-
void execute_partial_exit_by_entry_percent(double fill_price, const std::string& from_entry, double qty_percent);
2386+
void execute_partial_exit(
2387+
double fill_price, double qty_percent,
2388+
PositionReductionCause cause = PositionReductionCause::SCRIPT_ORDER);
2389+
void execute_partial_exit_by_entry(
2390+
double fill_price, const std::string& from_entry,
2391+
PositionReductionCause cause = PositionReductionCause::SCRIPT_ORDER);
2392+
void execute_partial_exit_by_entry_qty(
2393+
double fill_price,
2394+
const std::string& from_entry,
2395+
double qty_to_close,
2396+
PositionReductionCause cause = PositionReductionCause::SCRIPT_ORDER);
2397+
void execute_partial_exit_by_entry_percent(
2398+
double fill_price, const std::string& from_entry, double qty_percent,
2399+
PositionReductionCause cause = PositionReductionCause::SCRIPT_ORDER);
23842400
// KI-62: scratch (close dur-0) any same-bar same-id MARKET pyramid-add
23852401
// slices still open after a from_entry priced bracket exit fills — TV's
23862402
// open-tick fill sequence covered them. Targets only flagged same-bar add
23872403
// slices (never the frozen pre-add lot, never a prior-bar slice). Returns
23882404
// the qty scratched (0 = no collision → strict no-op).
2389-
double cover_samebar_market_adds_on_exit(const PendingOrder& order, double fill_price);
2405+
double cover_samebar_market_adds_on_exit(
2406+
const PendingOrder& order, double fill_price,
2407+
PositionReductionCause cause = PositionReductionCause::SCRIPT_ORDER);
23902408
void cancel_oca_group(const std::string& oca_name, const std::string& exclude_id);
23912409
// Pine v6 oca.reduce: when one sibling fills qty Q, reduce remaining
23922410
// siblings' qty by Q. Siblings whose qty becomes <= 0 are cancelled.
@@ -2574,12 +2592,17 @@ class BacktestEngine {
25742592
bool closes_any_qty,
25752593
double consumed_ledger_qty =
25762594
std::numeric_limits<double>::quiet_NaN());
2595+
// cleared_leg_count_out: how many live EXIT legs carried this
2596+
// (id, from_entry) before the erase. TV re-issues MODIFY every live leg
2597+
// (each keeping its own entry binding) rather than collapsing them into
2598+
// one, so strategy_exit needs the census to re-arm the same multiplicity.
25772599
void clear_existing_exit_order(const std::string& id,
25782600
const std::string& from_entry,
25792601
bool has_trail_request,
25802602
int64_t& preserved_seq_out,
25812603
uint64_t& replaced_incarnation_out,
2582-
double& preserved_reserved_qty_out);
2604+
double& preserved_reserved_qty_out,
2605+
int& cleared_leg_count_out);
25832606
bool compute_exit_reserved_qty(const std::string& from_entry,
25842607
double preserved_reserved_qty,
25852608
double live_pos_qty,

‎src/engine_fills.cpp‎

Lines changed: 79 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -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).
50105036
void 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

50335058
void 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/

‎src/engine_internal.hpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@ inline constexpr double kPathPosEps = 1e-12;
5656
inline constexpr double kSegmentDenomEps = 1e-15;
5757
inline constexpr double kPathTimeEps = 1e-12;
5858

59+
// The id prefix the engine stamps on every EXIT order materialised from a
60+
// strategy.close / strategy.close_all instruction ("__close__" + target id,
61+
// bare "__close__" for close_all). It is the ONLY structural marker that
62+
// separates a close-path reduction from a strategy.exit bracket leg fill at
63+
// the exit-fill site, and three call sites previously each carried their own
64+
// function-local copy. One definition, so the predicate cannot drift.
65+
inline const std::string kClosePrefix = "__close__";
66+
5967
struct RetainedChildFreshParentOrderContext {
6068
bool enabled = false;
6169
bool broker_flat = false;

0 commit comments

Comments
 (0)