diff --git a/tests/unit/test_trading_execution.py b/tests/unit/test_trading_execution.py index 01e08b6..dee46fb 100644 --- a/tests/unit/test_trading_execution.py +++ b/tests/unit/test_trading_execution.py @@ -460,6 +460,29 @@ def test_unfilled_entry_is_armed_then_times_out(store): assert service._armed == {} +def test_backed_out_unfilled_entry_frees_its_cap_slot(store): + # Behavior fix: the daily cap counts FILLS, not submissions. Two resting entries consume + # the cap, but when they back out UNFILLED their slots are freed (the 2026-07-01/02 bug + # where phantom unfilled limits capped the day after only a few real trades). + for sym, e, s in [("AAA", 14.0, 13.45), ("BBB", 8.0, 7.60), ("CCC", 5.0, 4.70)]: + emit_signal(store, symbol=sym, entry=e, stop=s) + executor = FakeExecutor(status="accepted") # resting limits, never fill + clock = Clock() + service = make_service(store, executor, auto_approve=True, now_fn=clock, + max_fresh_entries_per_day=2, max_concurrent_positions=10, + max_orders_per_tick=10, entry_timeout_bars=2, entry_invalidate_pct=-1.0) + service.request_approvals_for_ready_signals() + ids = [q["order_id"] for q in query_approval_queue(store)] + results = [service.approve_order(oid, approved_by="auto") for oid in ids] + assert service._fresh_entries["n"] == 2 # 2 armed+counted, cap hit + assert sum(1 for r in results if r.get("rejected")) == 1 # 3rd was cap-rejected + assert len(service._armed) == 2 + clock.advance(3) # both time out unfilled + service.expire_stale_entries() + assert service._armed == {} + assert service._fresh_entries["n"] == 0 # <-- the fix: slots freed + + def test_fast_guard_does_not_shorten_timeout(store): """Checking many times a second must not trip the wall-clock timeout early.""" emit_signal(store) diff --git a/trading_execution.py b/trading_execution.py index a6ab358..5df5c75 100644 --- a/trading_execution.py +++ b/trading_execution.py @@ -900,6 +900,8 @@ class TradingExecutionService: and isinstance(self._fresh_entries.get("n"), int) ): self._fresh_entries["n"] += 1 # count toward the per-day cap + if order_id in self._armed: # a resting limit -> free the slot if it backs out + self._armed[order_id]["counted"] = True return { "ok": result.ok, "order_id": order_id, @@ -1105,6 +1107,8 @@ class TradingExecutionService: if result.ok and self.settings.max_fresh_entries_per_day > 0: if isinstance(self._fresh_entries.get("n"), int): self._fresh_entries["n"] += 1 # count toward the per-day cap + if request.order_id in self._armed: + self._armed[request.order_id]["counted"] = True logger.info( "live ORB break %s qty=%s -> ok=%s status=%s rank=%s", symbol, request.quantity, result.ok, result.status, rank, @@ -1380,6 +1384,16 @@ class TradingExecutionService: )) self._prev_held = held + def _release_cap_slot(self, armed: dict | None) -> None: + """Free a per-day cap slot for an entry that consumed one but backed out UNFILLED. + This makes the cap count FILLS, not submissions: an unfilled/canceled limit no longer + permanently burns a slot (the 2026-07-01/07-02 bug where 2 phantom entries capped the + day). Fills keep their slot (their armed dict is popped without calling this).""" + if (armed and armed.get("counted") + and isinstance(self._fresh_entries.get("n"), int) + and self._fresh_entries["n"] > 0): + self._fresh_entries["n"] -= 1 + def expire_stale_entries(self) -> list[dict]: """Back out of unfilled entries that timed out or broke their trigger. @@ -1423,7 +1437,7 @@ class TradingExecutionService: self._armed.pop(order_id, None) continue if order_id in cancelled: - self._armed.pop(order_id, None) + self._release_cap_slot(self._armed.pop(order_id, None)) # unfilled -> free slot self._requested_symbols.discard(symbol) continue # FILLED at the broker (position open) -> stop tracking, NEVER cancel @@ -1484,6 +1498,7 @@ class TradingExecutionService: action_taken="cancelled_unfilled_entry", ) ) + self._release_cap_slot(armed) # backed out unfilled -> free the cap slot self._armed.pop(order_id, None) self._requested_symbols.discard(symbol) actions.append({"order_id": order_id, "symbol": symbol,