Coverage for execution/order_gate.py: 100%
159 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Pure, Lean-free order gating for Phase V2-15 (Observation Mode).
3No imports from AlgorithmImports/QCAlgorithm live here on purpose: this
4module owns the mode -> real-vs-simulated order decision table and must be
5unit-testable without a Lean runtime on sys.path.
6"""
8from __future__ import annotations
10import math
11from typing import TYPE_CHECKING, Any
13if TYPE_CHECKING:
14 from collections.abc import Iterable
15 from datetime import datetime
17VALID_MODES = ("backtest", "observation", "paper", "live")
18DEFAULT_FALLBACK_MODE = "observation"
20# Default ceiling on the per-fill slippage resolve_fill_slippage() will
21# ever apply, regardless of what liquidity/market_liquidity.py's
22# estimated_round_trip_cost computes. 500bps (5%) is far above anything the
23# estimator produces under normal participation (build_liquidity_decision()
24# already blocks orders at 5% participation, long before slippage_factor's
25# default 0.1 multiplier could get anywhere near this), so this only ever
26# binds as a guard against a degenerate estimate (e.g. a volatility spike on
27# a razor-thin bar) corrupting a fill price - never a normal-path limiter.
28# Overridable via phase_v2.liquidity.fill_slippage.max_bps (main.py reads
29# it in _ensure_ready() and passes it into every call below) - this
30# constant is only the fallback when that key is absent from config.json.
31MAX_LIQUIDITY_SLIPPAGE_BPS = 500.0
33# phase_v2.liquidity.fill_slippage.source: which LiquidityDecision field
34# main.py converts into fill-slippage bps. "round_trip" (default, see
35# execution/README.md's "Real fill slippage" section for the rationale) =
36# estimated_round_trip_cost (price impact + bid-ask spread combined).
37# "impact_only" = estimated_slippage alone, for isolating/excluding the
38# spread-crossing component.
39# "per_side" (V5.5.0) = HALF of estimated_round_trip_cost: a single fill only
40# crosses half the spread, but "round_trip" charged the full round trip on
41# every fill, double-counting the spread over a position's entry + exit.
42VALID_FILL_SLIPPAGE_SOURCES = ("round_trip", "impact_only", "per_side")
43DEFAULT_FILL_SLIPPAGE_SOURCE = "round_trip"
46def resolve_runtime_mode(raw_mode: str | None) -> str:
47 """Normalize a config-supplied mode value, failing safe to observation."""
48 if isinstance(raw_mode, str) and raw_mode in VALID_MODES:
49 return raw_mode
50 return DEFAULT_FALLBACK_MODE
53def resolve_order_permission(
54 mode: str,
55 allow_live_orders: bool,
56 broker_config_present: bool,
57 risk_locks_healthy: bool,
58) -> tuple[bool, str]:
59 """Decide whether a real broker order may be placed in the given mode.
61 observation always returns False regardless of the other flags - this is
62 the single safety invariant the whole phase depends on.
63 """
64 if mode == "backtest":
65 return True, "backtest_unrestricted"
67 if mode == "observation":
68 return False, "observation_mode_no_real_orders"
70 if mode == "paper":
71 if allow_live_orders and broker_config_present and risk_locks_healthy:
72 return True, "paper_orders_enabled"
73 if allow_live_orders and broker_config_present:
74 # V5.4.5 (development/Problems.md #116): paper previously
75 # ignored risk_locks_healthy entirely - a tripped kill switch /
76 # drawdown lock / manual lock could not stop real broker orders
77 # in the one mode that actually reaches a brokerage besides
78 # live. Same enforcement point as live below.
79 return False, "paper_orders_blocked_risk_lock"
80 return False, "paper_orders_blocked_missing_flag_or_broker_config"
82 if mode == "live":
83 if allow_live_orders and broker_config_present and risk_locks_healthy:
84 return True, "live_orders_enabled"
85 return False, "live_orders_blocked_missing_flag_or_broker_config_or_risk_lock"
87 return False, "unknown_mode_defaults_to_no_orders"
90def resolve_risk_exit_permission(
91 mode: str,
92 allow_live_orders: bool,
93 broker_config_present: bool,
94) -> tuple[bool, str]:
95 """May a real order close risk while a lock is active? `resolve_order_permission` with the lock taken as healthy: a lock
96 stops new risk, and must not also stop the orders that take risk off, or a tripped book freezes open in paper and live
97 while a backtest liquidates it. Observation still places nothing."""
98 allowed, reason = resolve_order_permission(mode, allow_live_orders, broker_config_present, True)
99 return allowed, f"risk_exit:{reason}"
102def resolve_cash_sweep_order_permission(mode: str, allow_live_orders: bool, broker_config_present: bool) -> tuple[bool, str]:
103 """V6.2.0: whether the T-bill cash sweep may trade. The strategy's risk locks (kill switch, drawdown lock, manual
104 lock) stop the strategy, not cash management, so they are not consulted; every other gate of
105 resolve_order_permission (observation never trades, paper / live need the flag and the broker config) applies."""
106 return resolve_order_permission(mode, allow_live_orders, broker_config_present, risk_locks_healthy=True)
109def slippage_amount(reference_price: float, slippage_bps: float) -> float:
110 """Absolute per-unit price slippage for a given bps estimate.
112 Shared by main.py's Lean SlippageModel (real backtest/live fills, wired
113 via security.SetSlippageModel()) and simulate_fill() below
114 (observation-mode simulated fills), so both paths apply the exact same
115 bps -> price-impact math instead of two independently-drifting
116 formulas. Returns 0.0 for a non-positive or non-finite price/bps -
117 slippage is never negative (never improves the fill price), and a NaN
118 estimate must never reach a fill price (V5.4.5, Problems.md #117:
119 `nan <= 0` is False, so the old guard let NaN straight into
120 `price * nan`).
121 """
122 if (
123 not math.isfinite(reference_price)
124 or not math.isfinite(slippage_bps)
125 or reference_price <= 0
126 or slippage_bps <= 0
127 ):
128 return 0.0
129 return float(reference_price) * (float(slippage_bps) / 10_000.0)
132def resolve_fill_slippage_source(raw_source: str | None) -> str:
133 """Normalize a phase_v2.liquidity.fill_slippage.source config value,
134 failing safe to DEFAULT_FILL_SLIPPAGE_SOURCE for anything unset/unknown
135 - same fail-safe-normalize convention as resolve_runtime_mode() above.
136 """
137 if isinstance(raw_source, str) and raw_source in VALID_FILL_SLIPPAGE_SOURCES:
138 return raw_source
139 return DEFAULT_FILL_SLIPPAGE_SOURCE
142def liquidity_cost_fraction(liquidity_payload: dict[str, Any], source: str) -> float:
143 """Pick which liquidity/market_liquidity.py::LiquidityDecision field
144 (already a fraction, e.g. 0.001 = 10bps) feeds the fill-slippage
145 estimate, per resolve_fill_slippage_source()'s normalized source.
146 Missing/malformed field -> 0.0, never raises.
147 """
148 key = "estimated_slippage" if source == "impact_only" else "estimated_round_trip_cost"
149 try:
150 fraction = float(liquidity_payload.get(key, 0.0) or 0.0)
151 except (TypeError, ValueError):
152 return 0.0
153 if not math.isfinite(fraction):
154 return 0.0
155 return fraction * 0.5 if source == "per_side" else fraction
158def resolve_slippage_bps(
159 symbol_key: str,
160 slippage_bps_by_symbol: dict[str, Any],
161 max_bps: float = MAX_LIQUIDITY_SLIPPAGE_BPS,
162) -> float:
163 """Pure lookup + clamp: how many bps of slippage to charge symbol_key,
164 given the per-symbol bps dict main.py refreshes every bar in
165 on_data()'s Pass 2 (liquidity_cost_fraction()'s selected field,
166 converted to bps). Shared by resolve_fill_slippage() below (real Lean
167 fills) and main.py's observation-mode
168 SimulatedPortfolioState.enter_long() call sites, so both paths apply
169 the identical clamp.
171 Missing symbol -> 0.0 bps (no liquidity estimate computed yet, e.g. an
172 order placed before Pass 2 has run for it once). Clamped to max_bps
173 (phase_v2.liquidity.fill_slippage.max_bps, defaulting to
174 MAX_LIQUIDITY_SLIPPAGE_BPS) as a guard against a degenerate estimate
175 corrupting a fill price. Non-finite estimates degrade to 0.0 (V5.4.5,
176 Problems.md #117) - max/min pass NaN through untouched, so the clamp
177 alone would not.
178 """
179 raw = slippage_bps_by_symbol.get(symbol_key, 0.0) or 0.0
180 try:
181 bps = float(raw)
182 except (TypeError, ValueError):
183 return 0.0
184 if not math.isfinite(bps):
185 return 0.0
186 return min(max(bps, 0.0), float(max_bps))
189def resolve_fill_slippage(
190 symbol_key: str,
191 reference_price: float,
192 slippage_bps_by_symbol: dict[str, Any],
193 max_bps: float = MAX_LIQUIDITY_SLIPPAGE_BPS,
194) -> float:
195 """Pure lookup + clamp + apply, used by main.py's real Lean
196 SlippageModel (_LiquidityAwareSlippageModel.GetSlippageApproximation)
197 to turn the per-symbol bps dict into an absolute fill-price delta."""
198 return slippage_amount(reference_price, resolve_slippage_bps(symbol_key, slippage_bps_by_symbol, max_bps))
201def simulate_fill(
202 close_price: float,
203 target_weight: float,
204 equity: float,
205 slippage_bps: float = 0.0,
206) -> dict[str, Any]:
207 """Pure hypothetical fill-price/quantity/notional math.
209 Quantity/notional are purely a function of the target portfolio weight,
210 current equity, and fill price - the same math applies whether the
211 caller is entering, exiting (target_weight=0.0), or liquidating.
212 """
213 if close_price <= 0:
214 return {"fill_price": 0.0, "notional": 0.0, "quantity": 0.0}
216 fill_price = close_price + slippage_amount(close_price, slippage_bps)
217 notional = target_weight * equity
218 quantity = notional / fill_price
220 return {
221 "fill_price": fill_price,
222 "notional": notional,
223 "quantity": quantity,
224 }
227# Exits that may rest as a limit order (V6.0.0): the model's own sell, the book's rotation exit and the age exit.
228# The rest are risk exits and always go to the market: a trailing stop, the sleeve loss guard, the kill switch and
229# the disabled-class / venue sweeps (a resting order would let the loss run).
230LIMIT_EXIT_REASONS = frozenset({"model_sell", "rotation", "max_holding_age_exceeded"})
233def resolve_limit_setting_by_class(asset_class: str | None, by_class: dict[str, Any] | None, default: float) -> float:
234 """A limit-order setting (`offset_multiplier`, `unfilled_timeout_bars`) for one asset class (V6.0.0): the class's entry in
235 `phase_v2.limit_orders.<setting>_by_class` when present, else the global value. Classes absent from the dict (every
236 class by default, the dict being empty) behave exactly as before."""
237 if asset_class and by_class and asset_class in by_class:
238 return type(default)(by_class[asset_class])
239 return default
242def resolve_exit_order_route(asset_class: str | None, exit_reason: str | None, exit_asset_classes: Iterable[str] | None) -> str:
243 """"limit" or "market" for a full exit (V6.0.0, todo lead 3: crypto exits were all market orders at 80 bps against
244 ~60 bps for the maker entries). A limit exit needs the class listed in `phase_v2.limit_orders.exit_asset_classes`
245 (default empty = every exit stays a market order, as before) and a reason from LIMIT_EXIT_REASONS; the timeout
246 fallback to a market order is the entry path's own (`fallback_to_market_on_timeout`)."""
247 if asset_class and asset_class in set(exit_asset_classes or ()) and exit_reason in LIMIT_EXIT_REASONS:
248 return "limit"
249 return "market"
252def resolve_combo_limit_price(net_mid: float, spread_fraction: float, is_buy: bool, offset_multiplier: float = 1.0) -> float:
253 """Limit for a whole option combo at its net price per unit, which can be a credit (below zero). The same half-spread offset as
254 `resolve_limit_price`, on the net's size: a buyer pays up, a seller gives up, whichever side of zero the net is. Rounded to cents, as a combo is quoted."""
255 offset = abs(float(net_mid)) * max(float(spread_fraction), 0.0) * 0.5 * max(float(offset_multiplier), 0.0)
256 return round(float(net_mid) + offset if is_buy else float(net_mid) - offset, 2)
259def resolve_limit_price(
260 reference_price: float,
261 spread_fraction: float,
262 is_buy: bool,
263 offset_multiplier: float = 1.0,
264) -> float:
265 """Pure limit-price placement for main.py's real limit orders
266 (execution/risk realism pass, part 2).
268 Offsets reference_price by half of spread_fraction (already a
269 fraction, e.g. 0.001 = 10bps - the same unit family
270 liquidity_cost_fraction() above consumes) times offset_multiplier
271 (phase_v2.limit_orders.offset_multiplier). Halving matches the
272 standard "bid = mid - spread/2, ask = mid + spread/2" convention -
273 spread_fraction is a round-trip/full-spread estimate
274 (liquidity/market_liquidity.py's spread_proxy), a single-sided limit
275 order should only cross half of it.
277 A buy limit sits BELOW reference_price (never overpay above the last
278 close); a sell/short limit sits ABOVE it (never undersell below the
279 last close). offset_multiplier > 1.0 places a more passive (further
280 from reference, lower fill probability, more price improvement if
281 filled) limit; < 1.0 places a more aggressive one (closer to/crossing
282 reference, higher fill probability, less improvement).
284 Returns reference_price unchanged whenever reference_price or
285 spread_fraction is non-positive - never returns a non-positive or
286 crossed-through price, matching slippage_amount()'s fail-safe-to-
287 neutral convention above.
288 """
289 if reference_price <= 0 or spread_fraction <= 0:
290 return float(reference_price)
291 offset = float(reference_price) * (float(spread_fraction) / 2.0) * float(offset_multiplier)
292 return reference_price - offset if is_buy else reference_price + offset
295# Pure classification of a Lean OrderStatus enum member's name (or
296# str(status)) into "pending" / "filled" / "canceled" / "unknown" -
297# isolates the one place this pass has to guess at Lean's real OrderStatus
298# spelling (see execution/README.md's "Real limit orders" section for the
299# full casing-risk writeup) into a single small function, so a casing fix
300# is a one-line change here rather than a hunt through main.py's
301# on_order_event()/_process_pending_limit_order_timeouts().
302#
303# V5.2.8 (development/Problems.md #34) - "CancelPending" added after
304# scanning 33 real order-events.json files across backtests/2026-07-*/
305# and backtests/2026-08-*/: Lean's real OrderStatus.CancelPending appears
306# 23 times (e.g. backtests/2026-08-11_09-56-24, paired 1:1 with 23
307# "canceled" records - a genuine unfilled-timeout cancel lifecycle,
308# directly confirmed on individual records, e.g. HYG qty 15 @
309# limitPrice=54.30, fillQuantity=0.0). Previously fell through to
310# "unknown", which every caller already treats identically to "pending" -
311# so this is a precision/self-documentation fix, not a behavior change.
312# PartiallyFilled has never once appeared across those 33 files - a real,
313# permanent, still-unexercised-in-practice caveat, not a gap to close here.
314PENDING_ORDER_STATUS_NAMES = ("New", "Submitted", "PartiallyFilled", "UpdateSubmitted", "CancelPending")
315TERMINAL_FILLED_STATUS_NAMES = ("Filled",)
316TERMINAL_CANCELED_STATUS_NAMES = ("Canceled", "Invalid")
319def classify_order_status(status_name: str) -> str:
320 """Pure string classification, never raises on an unrecognized value -
321 returns "unknown" instead, which callers treat as still-pending
322 (conservative: never mistakes an unrecognized status for a fill)."""
323 if status_name in TERMINAL_FILLED_STATUS_NAMES:
324 return "filled"
325 if status_name in TERMINAL_CANCELED_STATUS_NAMES:
326 return "canceled"
327 if status_name in PENDING_ORDER_STATUS_NAMES:
328 return "pending"
329 return "unknown"
332# V5.3.1 (development/Problems.md #34/#96) - main.py's on_order_event()/
333# _process_pending_limit_order_timeouts() cannot themselves be unit-tested
334# (main.py imports QCAlgorithm from AlgorithmImports, which only resolves
335# inside a real Lean process - confirmed: `python -c "import main"` raises
336# NameError outside one). These two functions are a pure restatement of
337# those methods' decision logic, extracted so classify_order_status("Partially
338# Filled") == "pending" (already tested above) has a testable path all the
339# way through to "does the pending-order record correctly stay open, and
340# does a subsequent timeout fall back for only the REMAINING quantity" -
341# not just proven at the classification step. main.py calls these two
342# functions instead of inlining the equivalent branches.
345def should_clear_pending_limit_order(status: str, all_legs_filled: bool) -> bool:
346 """Mirrors on_order_event()'s clearing decision: a tracked pending-
347 limit-order record should be POPPED (stop tracking it) only when it's
348 genuinely resolved - "filled" (and only once every leg of a multi-leg
349 combo has filled, not on the first leg alone) or "canceled". Every
350 other status - "pending", "unknown", and critically "PartiallyFilled"
351 (which classify_order_status() maps to "pending") - returns False, so
352 a partial fill leaves the record tracked for
353 resolve_limit_order_timeout_action() to eventually resolve, exactly as
354 main.py's own on_order_event() docstring already documents.
356 `all_legs_filled` is irrelevant (never even inspected) unless
357 status == "filled" - a "canceled" leg always clears regardless of the
358 other legs' state, matching main.py's existing elif branch."""
359 if status == "filled":
360 return all_legs_filled
361 return status == "canceled"
364def resolve_limit_order_timeout_action(
365 status: str,
366 quantity_remaining: float,
367 fallback_enabled: bool,
368) -> dict[str, Any]:
369 """Mirrors _process_pending_limit_order_timeouts()'s per-leg branch
370 once a tracked order has sat unfilled for
371 phase_v2.limit_orders.unfilled_timeout_bars bars: an already-resolved
372 leg ("filled"/"canceled" - main.py's own comment: resolved by
373 on_order_event() this bar or an earlier one) needs no action here.
374 Any other status - "pending", "unknown", or "PartiallyFilled" (which
375 classify_order_status() maps to "pending") - gets canceled, with a
376 market-order fallback for exactly `quantity_remaining` (never the
377 order's original size, which this function deliberately never
378 receives - a partial fill's leftover quantity is structurally the
379 only number that can ever be returned here) when fallback_enabled and
380 there IS a nonzero remainder.
382 Returns {"should_cancel": bool, "fallback_market_quantity": float | None}.
383 """
384 if status in ("filled", "canceled"):
385 return {"should_cancel": False, "fallback_market_quantity": None}
386 fallback_market_quantity = quantity_remaining if (fallback_enabled and quantity_remaining != 0) else None
387 return {"should_cancel": True, "fallback_market_quantity": fallback_market_quantity}
390def resolve_pending_order_action(
391 existing_pending: dict[str, Any] | None,
392 is_buy: bool,
393 bar_index: int,
394 timeout_bars: int,
395) -> str:
396 """V5.5.0 (Problems.md #128) - what _try_submit_limit_order() should do
397 when asked to place a limit order for a symbol that may already have one
398 in flight. Before this, every bar a still-unfilled entry re-fired a NEW
399 order and overwrote the pending record, orphaning the earlier ticket
400 (never cancelled, never timed out - the record's submitted_bar kept
401 resetting) so several orders could all fill (AMZN: 3x its target).
403 - "submit": nothing in flight, place a fresh order.
404 - "keep": an order in the SAME direction is still within its timeout -
405 do nothing, let it work (and let the timeout sweep resolve it).
406 - "cancel_replace": the in-flight order points the other way, or has
407 outlived timeout_bars - cancel its tickets, then submit fresh.
408 """
409 if not existing_pending:
410 return "submit"
411 existing_direction = existing_pending.get("direction")
412 wanted_direction = "buy" if is_buy else "sell"
413 if existing_direction != wanted_direction:
414 return "cancel_replace"
415 try:
416 age = int(bar_index) - int(existing_pending.get("submitted_bar", bar_index))
417 except (TypeError, ValueError):
418 return "cancel_replace"
419 if age >= max(1, int(timeout_bars)):
420 return "cancel_replace"
421 return "keep"
424def should_skip_for_open_order(open_order_quantity: float, has_tracked_pending_limit: bool) -> bool:
425 """V5.5.0 (Problems.md #133) - an UNTRACKED order is already working for
426 this symbol (e.g. the market fallback _process_pending_limit_order_timeouts()
427 just sent after cancelling a limit order, which also pops the pending
428 record), so entering again would stack a second one. In the 2026-10-07
429 backtest the same bar then also submitted a fresh limit order: 26 times a
430 market-on-open and a limit order were created together, and in several
431 (TLT -26/-27, -44/-45 shares) BOTH filled, doubling the position.
432 A TRACKED pending limit order is left to resolve_pending_order_action()
433 (keep / cancel-replace). Non-finite quantities count as 'nothing open'."""
434 try:
435 quantity = float(open_order_quantity)
436 except (TypeError, ValueError):
437 return False
438 if not math.isfinite(quantity):
439 return False
440 return quantity != 0.0 and not has_tracked_pending_limit
443def compute_fill_slippage_divergence_bps(
444 fill_price: float,
445 reference_price: float,
446 expected_cost_bps: float,
447 direction: float | None = None,
448) -> float | None:
449 """V5.7.0 (Problems.md #148): with `direction` (the fill quantity's sign: > 0 buy, < 0 sell) only ADVERSE slippage
450 counts - a buy filled below the open (or a sell above it) is price improvement, a limit order doing its job, and used
451 to be added to the kill-switch average as if it were a cost (BT5: crypto limit fills 1-4% under the open locked 24 book
452 decisions). Without `direction` the absolute gap is used, as before.
454 V5.5.0 (Problems.md #88/#96) - realized-minus-expected slippage in bps
455 for evaluate_kill_switch(). `reference_price` must be the FILL BAR's
456 open (what a daily market order actually targets), NOT the prior bar's
457 close - against the prior close this measured the overnight gap, which
458 is why the trigger had to be disabled with a 1e12 sentinel. Returns None
459 on any non-finite/non-positive input so the caller records nothing
460 rather than a fabricated 0."""
461 try:
462 fill = float(fill_price)
463 reference = float(reference_price)
464 expected = float(expected_cost_bps)
465 except (TypeError, ValueError):
466 return None
467 if not (math.isfinite(fill) and math.isfinite(reference) and math.isfinite(expected)):
468 return None
469 if fill <= 0.0 or reference <= 0.0:
470 return None
471 gap_bps = (fill - reference) / reference * 10_000.0
472 if direction is not None and math.isfinite(float(direction)) and float(direction) != 0.0:
473 return (gap_bps if float(direction) > 0.0 else -gap_bps) - expected
474 return abs(gap_bps) - expected
477IMMEDIATE_FILL_SECONDS = 3600.0
480def slippage_reference_price(
481 submit_price: float | None,
482 fill_bar_open: float | None,
483 submitted_at: datetime | None=None,
484 filled_at: datetime | None=None,
485 immediate_fill_seconds: float = IMMEDIATE_FILL_SECONDS,
486) -> tuple[float | None, str]:
487 """V5.8.0 (todo lead 3): which price a fill's slippage is measured from. An order that fills within
488 `immediate_fill_seconds` of its submission (crypto/forex, an open exchange) fills at the price it saw: its reference
489 is the submission price. An order queued past the close fills at the next session's open: its reference is that fill
490 bar's open (#88/#96 - against the submission price it would measure the overnight gap). Without timestamps or a
491 submission price the fill bar's open is used, the pre-V5.8.0 rule. Returns (price, "submit" | "fill_bar_open")."""
492 try:
493 elapsed = (filled_at - submitted_at).total_seconds() if submitted_at is not None and filled_at is not None else None
494 except (TypeError, AttributeError):
495 elapsed = None
496 if (
497 elapsed is not None
498 and 0.0 <= elapsed <= immediate_fill_seconds
499 and submit_price is not None
500 and math.isfinite(float(submit_price))
501 and float(submit_price) > 0.0
502 ):
503 return float(submit_price), "submit"
504 return (float(fill_bar_open) if fill_bar_open is not None else None), "fill_bar_open"
507# Pure classification of main.py::_apply_signal()/_apply_option_order()'s
508# execution_note return strings into "was a REAL order actually placed" -
509# used by the audit-log hook (development/Problems.md #42) at its single
510# call site in on_data()'s Pass 2 loop, rather than scattering a push call
511# across every one of _apply_signal()'s many branches/asset-class routings
512# (equity/futures/option x buy/sell/short, each with its own f-string
513# execution_note). An explicit denylist, not a broader heuristic, so a new
514# no-op reason added to main.py in the future fails safe (gets audited as
515# "real" and is easy to notice/fix) rather than silently never being
516# audited if it happened to match a loose pattern.
517_NO_OP_EXECUTION_NOTES = frozenset(
518 {
519 "kept_long",
520 "kept_short",
521 "already_flat",
522 "cooldown_active",
523 "no_action",
524 "max_active_positions_reached",
525 "futures_zero_contract_count",
526 "options_no_usable_contract",
527 "options_multi_leg_no_usable_legs",
528 # V4.3.0 - allow adding to an existing position (development/
529 # Changelog.md). Plain constants only, never f-strings - this
530 # denylist is exact-string matching, and an f-string note would
531 # silently misclassify as a REAL placement, the wrong-direction
532 # failure mode this module's own docstring warns about.
533 "kept_long_futures",
534 "kept_short_futures",
535 "futures_zero_delta_kept",
536 # V5.5.0 (Problems.md #128) - forex siblings of the futures no-ops above (they were
537 # missing, so every held-forex tick was audited as a REAL order placement), plus the
538 # new deadband and the "an order for this symbol is already working" note.
539 "kept_long_forex",
540 "kept_short_forex",
541 "forex_zero_delta_kept",
542 "forex_zero_order_units",
543 "forex_resize_deadband_kept",
544 "limit_order_already_pending",
545 "order_already_open",
546 "options_kept",
547 "options_contract_drifted_kept",
548 "options_multi_leg_kept",
549 "options_multi_leg_mismatch_kept",
550 # V4.4 - architecturally-sound options (development/Problems.md):
551 # single-leg/spread scale-down replaced "options_zero_or_negative_
552 # delta_kept"/"options_spread_shrink_unsupported" (both retired -
553 # a negative delta is now a REAL reduce order, never a no-op) with
554 # a delta==0-only no-op; the multi-position book adds two more.
555 "options_zero_delta_kept",
556 "options_at_position_cap_kept",
557 "options_held_contract_not_in_chain_kept",
558 # V4.5 (full OptionStrategies coverage, §9.1): the at-cap re-price
559 # search is scoped to records sharing this bar's strategy_name -
560 # when no held record is a comparable shape, there's nothing
561 # sensible to re-price, a distinct no-op from every "kept" reason
562 # above (renamed from V4.4's "spread"-suffixed strings - "spread"
563 # retired as a record kind, folded into "multi_leg", see main.py).
564 "options_no_comparable_position_to_reprice_kept",
565 }
566)
567_NO_OP_EXECUTION_NOTE_SUFFIXES = ("_exposure_cap_reached",)
570def is_real_order_placement(execution_note: str, orders_allowed: bool) -> bool:
571 """True only for a genuinely-placed real order - never a simulated/
572 observation-mode fill (execution_note prefixed "simulated_") and never
573 one of the known no-op/blocked outcomes above."""
574 if not orders_allowed or execution_note.startswith("simulated_"):
575 return False
576 if execution_note in _NO_OP_EXECUTION_NOTES:
577 return False
578 return not execution_note.endswith(_NO_OP_EXECUTION_NOTE_SUFFIXES)