Skip to content

Commit c28c2db

Browse files
committed
Derive placement state from original admission observations
1 parent f2df706 commit c28c2db

24 files changed

Lines changed: 275 additions & 103 deletions

‎docs/pages/exit-leg-lifecycle.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,9 @@ forks receive a new instruction identity and no inherited replay receipt.
7373
All nested definition, generation, cause, obligation, window and latest-receipt
7474
facts are reflected/hashed once from canonical state. Legacy D/R/T/O/H/K/B/B0
7575
fields are read-only projections. This model removes three stored booleans.
76-
Together with admission, direct PendingOrder booleans decrease from 17 to 10.
76+
Admission, cancellation and placement-fact consolidation have reduced the
77+
direct PendingOrder boolean census from 17 to 6; this includes two ordinary
78+
direction/activation facts and does not count every engine policy option.
7779
Optional obligations, three leg generations,
7880
retirement receipts, immutable definition references and action/domain variants
7981
remain disclosed domain state. This is not a whole-engine fewer-than-five claim.

‎docs/pages/fill-model.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ admission and scheduling rules, and the ordinary bar scan and callback-driven
1111
scan are separate. The responsibilities below guide their consolidation without
1212
claiming that a single unified scheduler already exists.
1313

14+
The current pending-order representation has six direct boolean members. Two
15+
duplicate placement fields now derive from the original command observation,
16+
and cancellation has an explicit terminal receipt. This declaration count is
17+
an intermediate result: it does not prove that all remaining Pine predicates
18+
are generic, or that the whole engine has fewer than five compatibility choices.
19+
1420
## Responsibilities
1521

1622
| Submodel | Owned facts and transitions | Boundary |

‎docs/pages/market-admission.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,24 @@ An actual margin fill can revise resolved sizing without changing the original
2222
observation. Original opening qualification is also distinct from the later
2323
broker `OpeningReceipt` Check/Exempt decision, which belongs to a committed fill.
2424

25+
Two historical placement views now derive from these same original facts:
26+
27+
- `placement_has_prior_close(order)` compares the original accepted-close
28+
quantity with the existing quantity tolerance. This describes a source-time
29+
close claim, including an immediate close; it does not ask whether a position
30+
is currently flat.
31+
- `placement_at_entry_capacity(order)` compares original placement side,
32+
requested direction and held-entry count with the original configured cap.
33+
Later fills, cancellation, sizing revisions or cap changes cannot alter it.
34+
35+
These views remove two independently writable copies of already stored facts.
36+
No replacement mask, enum profile or extra state is introduced. A manual order
37+
without an original admission observation retains the historical false default.
38+
Native callers that construct orders directly must supply their real original
39+
observation when these placement facts matter; a later executable quantity or
40+
position snapshot is not a substitute. The legacy C mirror columns remain at
41+
their original offsets as derived outputs, alongside the original observation.
42+
2543
## Causal receipts
2644

2745
An event sequence is allocated once and consumed by a successful journal append.

‎include/pineforge/engine.hpp‎

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -492,25 +492,6 @@ struct PendingOrder {
492492
// LONG and must not be mistaken for an order born in the later LONG
493493
// cycle. Zero means the order was created while broker-flat.
494494
int64_t created_position_cycle_seq = 0;
495-
// True when a successful strategy.close/close_all call earlier in this
496-
// same on_bar already targeted live quantity. This remains distinct from
497-
// created_position_side: an immediate full close makes the engine truly
498-
// FLAT before a paired reentry is placed, but that reentry is not an
499-
// independent true-flat opening for KI-61 affordability purposes.
500-
bool created_after_position_close_in_bar = false;
501-
// True when this SAME-direction MARKET/ENTRY order was OVER the pyramiding
502-
// cap at PLACEMENT — i.e. the position was already held in this order's
503-
// direction with position_entry_count_ >= pyramiding_ at the moment it was
504-
// placed. Snapshotted at every entry placement site so it mirrors the
505-
// fill-time pyramiding gate (add_to_pyramid_market / the strategy.order add
506-
// gate) exactly. The post-full-close same-direction wipe reads this to
507-
// distinguish a TV-admissible (within-cap) co-queue — which survives a
508-
// deferred full close that flattens on the fill bar — from one TradingView
509-
// rejects at placement (over cap), which must still be cancelled even though
510-
// the co-queued close zeroed position_entry_count_ before the add's fill-time
511-
// gate ran. See classify_order_eligibility / compact_filled_pending_orders
512-
// and test_close_all_coqueued_entry.cpp.
513-
bool over_pyramiding_cap_at_placement = false;
514495
// Call-bar provenance for the one deferred close_all whose post-fill
515496
// cleanup may preserve this order. Set only on a PRIOR-bar, pure-STOP
516497
// strategy.entry that was under the pyramiding cap and reused the id of a
@@ -907,6 +888,27 @@ struct PendingOrder {
907888
ShortSeedCollisionRole::NONE;
908889
};
909890

891+
// These views derive historical placement facts from the original command.
892+
// No current position, current configuration or mutable sizing participates.
893+
// The close fact describes previously accepted close claims, not physical
894+
// flatness; even an immediate close can leave that source-time fact positive.
895+
// The capacity view uses the original direction/count/cap (including cap0),
896+
// which remains meaningful after fills or a later configuration change.
897+
// Missing observations retain the historical default false for manual orders.
898+
// The comparison matches the broker's existing quantity tolerance exactly.
899+
inline bool placement_has_prior_close(const PendingOrder& order) {
900+
const auto& observation = order.market_admission.observation();
901+
return observation && observation->prior_close_quantity > 1e-10;
902+
}
903+
inline bool placement_at_entry_capacity(const PendingOrder& order) {
904+
const auto& observation = order.market_admission.observation();
905+
if (!observation) return false;
906+
const auto requested_side = observation->buy ? PositionSide::LONG : PositionSide::SHORT;
907+
return observation->placement_side != static_cast<int>(PositionSide::FLAT)
908+
&& observation->placement_side == static_cast<int>(requested_side)
909+
&& observation->held_entries >= observation->configuration.pyramiding;
910+
}
911+
910912
} // inline namespace engine_script_run_v9 (PendingOrder)
911913

912914
// default_qty_type constants (matches TradingView)
@@ -1956,7 +1958,7 @@ class BacktestEngine {
19561958
|| order.type != OrderType::MARKET || order.incarnation == 0
19571959
|| order.created_bar != bar_index_
19581960
|| order.created_position_side != PositionSide::FLAT
1959-
|| order.created_after_position_close_in_bar
1961+
|| placement_has_prior_close(order)
19601962
|| (order.replaced_order_incarnation != 0)
19611963
|| order.oca_type != 0 || !order.oca_name.empty()
19621964
|| position_side_ != PositionSide::FLAT
@@ -2000,7 +2002,7 @@ class BacktestEngine {
20002002
|| !order.is_long || order.incarnation == 0
20012003
|| order.created_bar != bar_index_
20022004
|| order.created_position_side != PositionSide::FLAT
2003-
|| order.created_after_position_close_in_bar
2005+
|| placement_has_prior_close(order)
20042006
|| order.birth.from_fill() || (order.replaced_order_incarnation != 0)
20052007
|| !order.oca_name.empty() || order.oca_type != 0
20062008
|| position_side_ != PositionSide::FLAT || position_entry_count_ != 0
@@ -2039,7 +2041,7 @@ class BacktestEngine {
20392041
|| (order.pine_frozen_market_instruction.transaction()
20402042
&& order.pine_frozen_market_instruction.transaction()->transaction_units
20412043
== order.pine_frozen_market_instruction.transaction()->own_units
2042-
&& !order.over_pyramiding_cap_at_placement));
2044+
&& !placement_at_entry_capacity(order)));
20432045
if (!default_all_in && !explicit_fixed) return false;
20442046
const double mark = default_all_in ? order.sizing_mark
20452047
: order.affordability_signal_price;

‎include/pineforge/pending_order_mirror.hpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// GENERATED by scripts/gen_pending_order_mirror.py from include/pineforge/engine.hpp -- do not edit.
2-
// 68 PendingOrder members mirrored (406 POD fields incl. struct_version/size).
2+
// 66 PendingOrder members mirrored (406 POD fields incl. struct_version/size).
33
#pragma once
44
#include <stdint.h>
55

@@ -55,8 +55,8 @@ typedef struct pf_pending_order_v1_s {
5555
uint8_t coof_cascade_inflight_fires;
5656
int32_t created_position_side;
5757
int64_t created_position_cycle_seq;
58-
uint8_t created_after_position_close_in_bar;
59-
uint8_t over_pyramiding_cap_at_placement;
58+
uint8_t created_after_position_close_in_bar; // deprecated, derived output only
59+
uint8_t over_pyramiding_cap_at_placement; // deprecated, derived output only
6060
int32_t same_id_stop_deferred_close_all_bar;
6161
uint64_t same_id_stop_deferred_close_all_incarnation;
6262
uint8_t reverses_same_bar_market_from_flat;

‎scripts/gen_pending_order_mirror.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@
6262
# Public v1 is append-only. Removed native fields survive only as one-way
6363
# deprecated output projections at their original offsets.
6464
LEGACY_OUTPUTS = {
65+
"created_after_position_close_in_bar": "placement_has_prior_close(src) ? 1 : 0",
66+
"over_pyramiding_cap_at_placement": "placement_at_entry_capacity(src) ? 1 : 0",
6567
"limit_price": "src.legs.prices().limit_price",
6668
"stop_price": "src.legs.prices().stop_price",
6769
"trail_points": "src.legs.prices().trail_points",
@@ -98,7 +100,7 @@
98100
"sbmt_member": "src.pine_frozen_market_instruction.active() ? 1 : 0",
99101
"sbmt_own_qty": "src.pine_frozen_market_instruction.transaction() ? src.pine_frozen_market_instruction.transaction()->own_units : std::numeric_limits<double>::quiet_NaN()",
100102
"sbmt_tx_qty": "src.pine_frozen_market_instruction.transaction() ? src.pine_frozen_market_instruction.transaction()->transaction_units : std::numeric_limits<double>::quiet_NaN()",
101-
"sbmt_kept_over_cap": "src.pine_frozen_market_instruction.transaction() && src.over_pyramiding_cap_at_placement ? 1 : 0",
103+
"sbmt_kept_over_cap": "src.pine_frozen_market_instruction.transaction() && placement_at_entry_capacity(src) ? 1 : 0",
102104
"sbmt_close_qty": "src.pine_frozen_market_instruction.targeted_close() ? src.quantity_request.intent()->units() : std::numeric_limits<double>::quiet_NaN()",
103105
"sbmt_close_buy": "src.pine_frozen_market_instruction.targeted_close() && src.created_position_side == PositionSide::SHORT ? 1 : 0",
104106
"declined_by_replaced_short_market": "src.cancellation.cause() == CancellationCause::Replacement ? 1 : 0",

‎scripts/test_broker_state_hash_coverage.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def test_capture_nested_storage_cannot_hide(self):
102102

103103
def test_capture_folds_cannot_be_conditional_rebound_or_duplicated(self):
104104
start = SOURCE.index(" f.b(o.reservation_expansion.capture().has_value());")
105-
end = SOURCE.index(" // Suppressed-close", start)
105+
end = SOURCE.index("\n }\n market_admission_journal_", start)
106106
block = SOURCE[start:end]
107107
for mutated in ["if (false) {" + block + "}", block + block,
108108
block.replace("capture = o.reservation_expansion.capture()", "capture = foreign.capture()"),

‎src/compat/pine/order_priority.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ std::optional<broker::OrderPriorityDecision> OrderPriority::select(
3939
&& parent->created_bar == ctx.bar_index - 1
4040
&& std::isnan(parent->qty)
4141
&& !parent->birth.from_fill()
42-
&& !parent->created_after_position_close_in_bar
43-
&& !parent->over_pyramiding_cap_at_placement
42+
&& !placement_has_prior_close(*parent)
43+
&& !placement_at_entry_capacity(*parent)
4444
&& !parent->stop_limit_activated
4545
&& std::isfinite(parent->legs.prices().stop_price)
4646
&& std::isnan(parent->legs.prices().limit_price)
@@ -60,7 +60,7 @@ std::optional<broker::OrderPriorityDecision> OrderPriority::select(
6060
&& child->created_position_side == PositionSide::FLAT
6161
&& child->created_bar == ctx.bar_index - 1
6262
&& !child->birth.from_fill()
63-
&& !child->created_after_position_close_in_bar
63+
&& !placement_has_prior_close(*child)
6464
&& !child->quantity_request.is_partial(1e-9, 1e-9)
6565
&& std::isnan(child->qty)
6666
&& child_qp >= 100.0 - 1e-9

‎src/compat/pine/reservation_expansion.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ std::vector<uint64_t> select_reservation_growth_sources(const std::vector<Pendin
1414
&& source.type != OrderType::RAW_ORDER) continue;
1515
const auto requested = source.is_long ? PositionSide::LONG : PositionSide::SHORT;
1616
if (source.created_bar != bar || source.type != OrderType::MARKET
17-
|| source.birth.from_fill() || source.over_pyramiding_cap_at_placement
17+
|| source.birth.from_fill() || placement_at_entry_capacity(source)
1818
|| requested != side || source.created_position_side != side) return {};
1919
selected.push_back(source.incarnation);
2020
}

0 commit comments

Comments
 (0)