"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(paper-trade): version corrected order statuses and limit matching
Haozhe Wu2e7c2ca1b646
diff --git a/agent/src/tools/paper_trade/README.md b/agent/src/tools/paper_trade/README.mdindex 19c58c2c7..3dde73971 100644--- a/agent/src/tools/paper_trade/README.md+++ b/agent/src/tools/paper_trade/README.md@@ -107,10 +107,23 @@ no row at all while its daily bar exists is a provider omission and returns| `path_model` | `bar_median`, `bar_close` | `bar_median` | reference price from each bar || `fill_model` | `all_or_none` | `all_or_none` | no partial fills |-A market order fills at the first continuous bar whose fill gates pass; a-limit order rests until a bar satisfies its price and is canceled at session end-(15:00 on a complete session) if none does. Every fill is all-or-none; partial-fills and volume share are Phase 3.+A market order fills at the first continuous bar whose fill gates pass. A+resting limit follows JoinQuant's bar matching: a buy triggers only when+`bar.low < limit` (its 委托价 above the bar's low) and a sell only when+`bar.high > limit` (its 委托价 below the bar's high), and a triggered fill+executes at the order's 委托价 rather than the bar reference. Equality does not+fill, so a bar that only touches the limit leaves the order resting, and a limit+that never triggers is canceled at session end (15:00 on a complete session). On+the first bar with volume, an already-marketable reference (`ref < limit` for a+buy, `ref > limit` for a sell) fills at that strictly better price instead,+which wins over the 委托价 even when the bar also crosses. Every fill is+all-or-none; volume share is Phase 3.++Order statuses use JoinQuant's `OrderStatus` vocabulary for both intervals:+`filled` means partially filled and still active, so the residual stays in+`open_orders()` and can be canceled, settled or matched by a later bar; `held`+means fully filled and terminal. `canceled` and `rejected` are also terminal;+`new`, `open` and `pending_cancel` are not.The 5m leg uses Tushare `stk_mins` and is resolved separately from the dailychain: Tencent's raw loader serves daily bars only. The measured provider limit@@ -134,9 +147,10 @@ branch (`paper-trade-v12-persistence`) and is not wired to any CLI, API or MCPsurface in this PR.Daily data supplies the prior close for price-limit bands and the final NAV.-The current 5m reference is checked against those bands; an order waits while-its side is blocked by a price limit. Zero-volume bars cannot fill. Corporate-actions remain fail-closed.+The band and cash gates check the price the fill would execute at, so a 5m+market order is gated at its bar reference and a resting limit at its 委托价;+an order waits while its side is blocked by a price limit. Zero-volume bars+cannot fill. Corporate actions remain fail-closed.## Known limits@@ -166,6 +180,11 @@ actions remain fail-closed.- **5m strategy UNIVERSE is strict.** An order on a position outside thedeclared `UNIVERSE` fails the whole call, so such a position cannot be reducedby a 5m strategy step; use the 1d step for that.+- **Matching changes are versioned.** `pt-rules-v2` identifies the corrected+ full/partial order statuses and 5m limit-fill rules. Its engine fingerprint+ differs from `pt-rules-v1` even with identical bars and model settings;+ archived results retain their original version.+## Data and model limitsdiff --git a/agent/src/tools/paper_trade/engine.py b/agent/src/tools/paper_trade/engine.pyindex 0772d2f94..b0d826893 100644--- a/agent/src/tools/paper_trade/engine.py+++ b/agent/src/tools/paper_trade/engine.py@@ -313,22 +313,26 @@ class _MatchSession:return (code, f"close {close:.2f} at or below down limit {down:.2f}; sell rejected")return None- def _fill_gate(self, day: DayPlan, order: Order, ref: float | Decimal) -> tuple[str, str] | None:- # Slots 7-10 of the frozen AM-14 ladder.+ def _fill_gate(self, day: DayPlan, order: Order, price: float | Decimal) -> tuple[str, str] | None:+ # Slots 7-10 of the frozen AM-14 ladder. ``price`` is the price the+ # fill would execute at: the bar reference for a market order or a+ # first-bar marketable limit, the 委托价 for a bar-low/high limit fill.+ # In 5m the band and cash checks must be anchored on that execution+ # price, never on the bar reference alone.if self._five_minute and self.rules.has_price_limits:sym_data = self.market_data.data[order.symbol]up, down = self._band(order.symbol, day.date, sym_data)- code = self.rules.band_rejection(order.side, ref, up, down)+ code = self.rules.band_rejection(order.side, price, up, down)if code == "limit_up":- return (code, f"ref {ref:.2f} at or above up limit {up:.2f}; buy deferred")+ return (code, f"price {price:.2f} at or above up limit {up:.2f}; buy deferred")if code == "limit_down":- return (code, f"ref {ref:.2f} at or below down limit {down:.2f}; sell deferred")- if self.rules.limit_order_violation(order.side, ref, order.limit):- anchor = "ref" if self._five_minute else "close"+ return (code, f"price {price:.2f} at or below down limit {down:.2f}; sell deferred")+ if self.rules.limit_order_violation(order.side, price, order.limit):+ anchor = "price" if self._five_minute else "close"detail = (- f"{anchor} {ref:.2f} > limit {order.limit:.2f}"+ f"{anchor} {price:.2f} > limit {order.limit:.2f}"if order.side == "buy"- else f"{anchor} {ref:.2f} < limit {order.limit:.2f}"+ else f"{anchor} {price:.2f} < limit {order.limit:.2f}")return ("limit_not_marketable", detail)symbol = order.symbol@@ -343,9 +347,9 @@ class _MatchSession:if code == "insufficient_position":return (code, f"sell qty {order.qty} exceeds position {total}")# Slot 10 insufficient_cash (§4: qty×price+fee ≤ cash).- code = self.rules.cash_rejection(order.side, order.qty, ref, self.cash)+ code = self.rules.cash_rejection(order.side, order.qty, price, self.cash)if code == "insufficient_cash":- cost = self.rules.buy_cost(order.qty, ref)+ cost = self.rules.buy_cost(order.qty, price)return (code, f"buy cost {cost} exceeds cash {self.cash}")return Nonediff --git a/agent/src/tools/paper_trade/order_lifecycle.py b/agent/src/tools/paper_trade/order_lifecycle.pyindex 56b3452cd..96c0a91d0 100644--- a/agent/src/tools/paper_trade/order_lifecycle.py+++ b/agent/src/tools/paper_trade/order_lifecycle.py@@ -9,8 +9,9 @@ Scope, frozen from the thread:- order id stable across replay (a replayed order list reproduces identicalids, so a retry is distinguishable from a new order);-- status set ``new / open / filled / canceled / rejected / held- (partially filled) / pending_cancel``;+- status set ``new / open / filled (partially filled) / canceled / rejected /+ held (fully filled) / pending_cancel``, matching JoinQuant's ``OrderStatus``+ names rather than the everyday sense of "filled";- cancel by order id; cancel of a terminal order is refused, cancel of analready-cancel-requested order is idempotent;- day-order semantics: every unfinished order is canceled at end of day@@ -39,10 +40,10 @@ STATUS_HELD = "held"STATUS_PENDING_CANCEL = "pending_cancel"_TERMINAL_STATUSES = frozenset(- {STATUS_FILLED, STATUS_CANCELED, STATUS_REJECTED}+ {STATUS_HELD, STATUS_CANCELED, STATUS_REJECTED})-_UNFINISHED_STATUSES = frozenset({STATUS_NEW, STATUS_OPEN, STATUS_HELD, STATUS_PENDING_CANCEL})-_ACTIVE_STATUSES = frozenset({STATUS_NEW, STATUS_OPEN, STATUS_HELD})+_UNFINISHED_STATUSES = frozenset({STATUS_NEW, STATUS_OPEN, STATUS_FILLED, STATUS_PENDING_CANCEL})+_ACTIVE_STATUSES = frozenset({STATUS_NEW, STATUS_OPEN, STATUS_FILLED})_ORDER_ID_PREFIX = "pt"@@ -138,7 +139,11 @@ class OrderBook:return self._states.get(order_id)def open_orders(self) -> list[OrderState]:- """Today's unfinished orders (JoinQuant's ``get_open_orders``)."""+ """Today's unfinished orders (JoinQuant's ``get_open_orders``).++ A partially ``filled`` order is still open — it can take further+ fills — while a fully ``held`` order is terminal and is not listed.+ """return [s for s in self._states.values() if s.status in _ACTIVE_STATUSES]# ----------------------------------------------------------------- writes@@ -174,9 +179,11 @@ class OrderBook:def request_cancel(self, order_id: str) -> OrderState:"""Ask to cancel by order id.- A terminal order (filled/canceled/rejected) cannot be canceled — the- refusal is an error, not a silent no-op. Asking twice is idempotent:- the second call returns the ``pending_cancel`` state unchanged.+ A terminal order (``held``/``canceled``/``rejected``) cannot be+ canceled — the refusal is an error, not a silent no-op. A partially+ ``filled`` order is not terminal, so its residual can still be+ canceled. Asking twice is idempotent: the second call returns the+ ``pending_cancel`` state unchanged."""state = self._require(order_id)if state.status in _TERMINAL_STATUSES:@@ -190,6 +197,11 @@ class OrderBook:def fill(self, order_id: str, qty: Decimal, price: Decimal, *, volume_cap: Decimal | None = None) -> Fill:"""Execute part or all of an unfinished order at ``price``.+ Status follows JoinQuant's names, not the everyday sense of+ "filled": a partial execution leaves the order ``filled`` (still+ active and matchable), while a complete execution leaves it ``held``+ (terminal).+Args:order_id: The order to fill.qty: Requested execution quantity; clipped to the remaining@@ -202,7 +214,8 @@ class OrderBook:The executed :class:`Fill`.Raises:- OrderLifecycleError: The order is terminal or already+ OrderLifecycleError: The order is terminal+ (``held``/``canceled``/``rejected``) or alreadycancel-requested (a pending_cancel order stops matching), orthe qty/cap is not positive."""@@ -232,15 +245,19 @@ class OrderBook:total_cost = sum((f.qty * f.price for f in state.fills), Decimal(0))state.avg_fill_price = total_cost / state.filled_qtystate.status = (- STATUS_FILLED if state.filled_qty == state.request.qty else STATUS_HELD+ STATUS_HELD if state.filled_qty == state.request.qty else STATUS_FILLED)return filldef settle_day(self) -> list[OrderState]:"""Day-order semantics: cancel every unfinished order at session end.- Returns the canceled states. A ``pending_cancel`` order settles the- same way — the cancel it asked for has arrived.+ ``new``, ``open``, partially ``filled`` and ``pending_cancel`` orders+ all settle; a fully ``held`` order is terminal and is left alone. A+ ``pending_cancel`` order settles the same way — the cancel it asked+ for has arrived.++ Returns the canceled states."""settled: list[OrderState] = []for state in self._states.values():diff --git a/agent/src/tools/paper_trade/rules.py b/agent/src/tools/paper_trade/rules.pyindex 4b3c2133b..683ade696 100644--- a/agent/src/tools/paper_trade/rules.py+++ b/agent/src/tools/paper_trade/rules.py@@ -57,10 +57,10 @@ __all__ = []#: D3 engine-fingerprint component. Bump this string whenever fee / lot /-#: price-limit / settlement semantics change, so a stored fingerprint can never+#: price-limit / settlement / order-status / matching semantics change, so a stored fingerprint can never#: claim a rule set the engine no longer implements. It is a constant only: no#: fee, lot or matching behaviour in this module depends on it.-RULES_VERSION = "pt-rules-v1"+RULES_VERSION = "pt-rules-v2"#: AM-14 frozen rejection decision order — first match wins (REQUIREMENTS §2#: hard semantics 3a). ``limit_up``/``limit_down`` share one frozen slot anddiff --git a/agent/src/tools/paper_trade/session_5m.py b/agent/src/tools/paper_trade/session_5m.pyindex d13dd515b..75fdd9f1f 100644--- a/agent/src/tools/paper_trade/session_5m.py+++ b/agent/src/tools/paper_trade/session_5m.py@@ -6,11 +6,22 @@ matching opportunity, and unfilled day orders are canceled at the sessionclose. Only ``interval="5m"`` reaches this module; the pt-v1.1 daily path isuntouched.-Phase-2 semantics:+Phase-2/3 semantics:- a market order fills in full at the first continuous bar whose fill gates- pass; a limit order rests across bars and fills in full at the first bar- whose reference price satisfies the limit;+ pass, at that bar's reference price;+- a resting limit order (JoinQuant 订单处理) fills in full at its 委托价+ (``order.limit``) once a bar trades through it: a buy needs+ ``bar.low < limit``, a sell needs ``bar.high > limit`` — both strict, so a+ bar that only touches the limit never fills. On the first continuous bar a+ strictly better reference (buy ``ref < limit``, sell ``ref > limit``) fills+ at that reference, never worse than the limit; at equality the bar rule+ alone decides. Later bars let only the bar low/high rule decide the+ verdict, so ``path_model`` cannot change a limit fill that the bar trades+ through — it only picks the first-bar marketable *price*;+- the price-limit band and cash gates are anchored on the actual fill price+ (the reference for market/first-bar fills, the 委托价 for bar-low/high+ fills);- an order that never fills is canceled by ``settle_day`` at session end (15:00on a complete session);- no partial fills and no volume-share model (Phase 3);@@ -25,10 +36,11 @@ positional (``pt-<index>``), and no clock or randomness is read.from __future__ import annotations-from typing import TYPE_CHECKING, Sequence+from decimal import Decimal+from typing import TYPE_CHECKING, Any, Sequence-from .order_lifecycle import STATUS_OPEN, OrderBook, OrderRequest, assign_ids-from .rules import money+from .order_lifecycle import _ACTIVE_STATUSES, OrderBook, OrderRequest, assign_ids+from .rules import money, quantize_moneyfrom .schema import CANCELED_REASON_CODE, CanceledOrder, Orderif TYPE_CHECKING:@@ -48,6 +60,28 @@ def _request(order: Order) -> OrderRequest:)+def _limit_fill_price(order: Order, ref: Decimal, bar: Any, *, first_bar: bool) -> Decimal | None:+ """The 委托价 execution for a resting limit, or ``None`` while it rests.++ JoinQuant's bar matching triggers on the bar's traded range: a buy needs+ ``bar.low < limit`` and a sell ``bar.high > limit`` (both strict, so a bar+ whose low/high only touches the limit never fills), and the execution is+ the 委托价. The first continuous bar adds the first-bar marketable rule:+ a strictly better reference fills at that reference, never worse than the+ limit; at equality the bar-low/high rule alone decides.+ """+ limit = money(order.limit)+ low = quantize_money(money(float(bar["low"])))+ high = quantize_money(money(float(bar["high"])))+ if order.side == "buy":+ if first_bar and ref < limit:+ return ref+ return limit if low < limit else None+ if first_bar and ref > limit:+ return ref+ return limit if high > limit else None++def _cancel_unfilled(session: "_MatchSession", day: "DayPlan", book: OrderBook, by_id: dict[str, Order]) -> None:@@ -94,30 +128,48 @@ def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[Oday, order, "suspended",f"no 5m continuous bars for {symbol} on {day.date}")continue+ live_bar = 0for _, bar in bars.sort_index().iterrows():if float(bar["volume"]) <= 0:+ # A zero-volume bar is not a matching opportunity, so it can+ # neither fill nor consume the first-bar marketable branch.continueref = session._reference_price_from_bar(bar)+ first_bar = live_bar == 0+ live_bar += 1for order_id in order_ids:state = book.get(order_id)- if state is None or state.status != STATUS_OPEN:+ if state is None or state.status not in _ACTIVE_STATUSES:continueorder = by_id[order_id]- gate = session._fill_gate(day, order, ref)+ if order.limit is None:+ price = ref+ else:+ # Trigger/price split: the bar range decides whether a+ # resting limit fills, and it fills at the 委托价; only the+ # first continuous bar can fill at a strictly better+ # reference. A limit that never triggers rests untouched.+ price = _limit_fill_price(order, ref, bar, first_bar=first_bar)+ if price is None:+ continue+ gate = session._fill_gate(day, order, price)if gate is not None:code, detail = gate- if code in {"limit_not_marketable", "limit_up", "limit_down"}:+ if code in {"limit_up", "limit_down"}:+ # The band blocks the side; the order waits for a+ # later bar (and is rejected at day end if still+ # blocked), exactly like a market order.deferred[order_id] = gatecontinuebook.reject(order_id, code)session._reject(day, order, code, detail)continue- book.fill(order_id, money(order.qty), ref)- session._fill(day.date, order, float(ref))+ book.fill(order_id, money(order.qty), price)+ session._fill(day.date, order, float(price))for order_id, gate in deferred.items():state = book.get(order_id)- if state is not None and state.status == STATUS_OPEN and gate[0] != "limit_not_marketable":+ if state is not None and state.status in _ACTIVE_STATUSES:book.reject(order_id, gate[0])session._reject(day, by_id[order_id], *gate)_cancel_unfilled(session, day, book, by_id)diff --git a/agent/tests/test_paper_order_lifecycle.py b/agent/tests/test_paper_order_lifecycle.pyindex 2ac9e8563..73a93f295 100644--- a/agent/tests/test_paper_order_lifecycle.py+++ b/agent/tests/test_paper_order_lifecycle.py@@ -74,15 +74,15 @@ class TestLifecycleFlow:fill = book.fill("pt-0", D("100"), D("1700.00"))assert fill.qty == D("100")state = book.get("pt-0")- assert state.status == STATUS_FILLED+ assert state.status == STATUS_HELDassert state.filled_qty == D("100")assert state.avg_fill_price == D("1700.00")- def test_partial_fill_marks_held(self):+ def test_partial_fill_marks_filled(self):book = OrderBook(assign_ids([_request()]))book.activate("pt-0")book.fill("pt-0", D("40"), D("1700.00"))- assert book.get("pt-0").status == STATUS_HELD+ assert book.get("pt-0").status == STATUS_FILLEDdef test_avg_price_weighted_across_fills(self):book = OrderBook(assign_ids([_request(qty=D("200"))]))@@ -98,7 +98,7 @@ class TestLifecycleFlow:book.fill("pt-0", D("60"), D("10"))fill = book.fill("pt-0", D("1000"), D("10"))assert fill.qty == D("40")- assert book.get("pt-0").status == STATUS_FILLED+ assert book.get("pt-0").status == STATUS_HELDdef test_rejected_reason_is_recorded(self):book = OrderBook(assign_ids([_request()]))@@ -159,7 +159,7 @@ class TestDayOrderSettlement:book.activate("pt-0")book.fill("pt-0", D("100"), D("1700"))assert book.settle_day() == []- assert book.get("pt-0").status == STATUS_FILLED+ assert book.get("pt-0").status == STATUS_HELDclass TestVolumeCap:@@ -168,7 +168,7 @@ class TestVolumeCap:book.activate("pt-0")fill = book.fill("pt-0", D("1000"), D("10"), volume_cap=D("250"))assert fill.qty == D("250")- assert book.get("pt-0").status == STATUS_HELD+ assert book.get("pt-0").status == STATUS_FILLEDdef test_non_positive_cap_fails_closed(self):book = OrderBook(assign_ids([_request()]))diff --git a/agent/tests/test_paper_trade_5m_engine.py b/agent/tests/test_paper_trade_5m_engine.pyindex bdcf84e07..eec538611 100644--- a/agent/tests/test_paper_trade_5m_engine.py+++ b/agent/tests/test_paper_trade_5m_engine.py@@ -2,9 +2,12 @@Every continuous 5m bar (09:30 opening-auction print excluded) is a matchingopportunity. A market order fills at the first bar whose fill gates pass; a-limit order rests until a bar satisfies its price and is canceled at session-end if none does. ``bar_median`` / ``bar_close`` drive the reference, limit-marketability, the cash gate, the fill price, the notional and the fee.+limit order rests until a bar trades through it (buy ``bar.low < limit``,+sell ``bar.high > limit``) and fills at its 委托价, or is canceled at session+end if none does. The first continuous bar may instead fill a strictly better+``ref``. ``bar_median`` / ``bar_close`` drive the reference, a market order's+fill price and the first-bar marketable price; the cash gate, notional and fee+follow the actual fill price.A failed order keeps its specific pt-v1.1 reason in ``rejected_orders`` ANDgets one ``canceled_after_failed_match`` row in ``canceled_orders`` (D2).Offline: synthetic frames through a fake loader, never the network.@@ -227,7 +230,7 @@ def test_market_sell_fills_at_the_first_continuous_bar() -> None:assert outcome.canceled_orders == ()[email protected](("limit", "expected"), [(10.50, 10.00), (10.10, 10.00), (10.00, 10.00), (9.90, None)])[email protected](("limit", "expected"), [(10.50, 10.00), (10.10, 10.00), (10.00, None), (9.90, None)])def test_buy_limit_fills_at_the_first_marketable_bar(limit: float, expected: float | None) -> None:outcome = _outcome(orders=[_buy(limit=limit)])@@ -243,7 +246,7 @@ def test_buy_limit_fills_at_the_first_marketable_bar(limit: float, expected: flo][email protected](("limit", "expected"), [(10.00, 10.00), (10.10, 10.20), (10.20, 10.20), (10.30, None)])[email protected](("limit", "expected"), [(10.00, 10.00), (10.10, 10.10), (10.20, None), (10.30, None)])def test_sell_limit_fills_at_the_first_marketable_bar(limit: float, expected: float | None) -> None:outcome = _outcome(orders=[_sell(limit=limit)], positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}])@@ -259,18 +262,16 @@ def test_sell_limit_fills_at_the_first_marketable_bar(limit: float, expected: fl]-def test_path_model_changes_the_reference_and_the_verdict() -> None:+def test_path_model_changes_only_the_first_bar_marketable_price() -> None:market_data, _ = _cn_a_data(five={_SYM: _dispersed_5m()})median = _outcome(orders=[_buy(limit=10.15)], market_data=market_data)close = _outcome(orders=[_buy(limit=10.15)], market_data=market_data, path_model="bar_close")assert [f.price for f in median.fills] == [10.10]assert median.rejected_orders == ()- assert close.fills == ()+ assert [f.price for f in close.fills] == [10.15]assert close.rejected_orders == ()- assert [(c.reason_code, c.detail) for c in close.canceled_orders] == [- (CANCELED_REASON_CODE, "unfilled day order canceled at session end")- ]+ assert close.canceled_orders == ()assert median.engine_fingerprint != close.engine_fingerprintdiff --git a/agent/tests/test_paper_trade_5m_limit_price.py b/agent/tests/test_paper_trade_5m_limit_price.pynew file mode 100644index 000000000..2f1d50b18--- /dev/null+++ b/agent/tests/test_paper_trade_5m_limit_price.py@@ -0,0 +1,486 @@+"""T4 gate — JoinQuant limit-fill trigger and price for the cn_a 5m step.++The official contract (JoinQuantAPI.pdf, 订单处理; restated by the phase-3+planbook):++* a resting **limit buy** fills at its 委托价 once a bar's ``low`` is strictly+ below that limit (``bar.low < limit``);+* a resting **limit sell** fills at its 委托价 once a bar's ``high`` is+ strictly above that limit (``bar.high > limit``);+* equality never fills — both comparisons are strict;+* a limit already marketable at the **first continuous bar** fills at that+ bar's reference price (``ref``) only when the reference is strictly better+ than the limit (buy ``ref < limit``, sell ``ref > limit``); at equality it+ rests. ``path_model`` therefore chooses the first-bar marketable *price*,+ while a bar-low/high cross decides the *verdict* and fills at the limit.++Every case runs a **two-bar** continuous day so the order is already resting+on bar 1 and the case under test is a deferred order on bar 2. The days are+synthetic ``_intraday`` frames in the style of+``test_paper_trade_5m_engine.py`` (opening-auction print omitted, so the two+continuous bars are the whole session); no committed market fixture is added.+"""++from __future__ import annotations++from decimal import ROUND_HALF_UP, Decimal++import pandas as pd+import pytest++from src.tools.paper_trade import engine+from src.tools.paper_trade.data import fetch_market_data+from src.tools.paper_trade.schema import CANCELED_REASON_CODE, parse_request++_DAY = "2026-10-20"+_PREV = "2026-10-19"+_SYM = "600519.SH"+_FEE_MODEL = {+ "commission_rate": 0.00025,+ "commission_min": 5.0,+ "stamp_tax_sell": 0.0005,+ "transfer_fee": 0.00001,+}+_LABELS = ("09:35", "09:40")++# (open, high, low, close)+Bar = tuple[float, float, float, float]+++# ── synthetic two-bar days (no committed fixture) ────────────────────────────+++def _intraday(day: str, bars: tuple[Bar, Bar]) -> pd.DataFrame:+ """Two on-grid continuous 5m bars; labels are bar ENDS."""+ records = [+ {+ "bar_time": f"{day} {label}",+ "open": bar[0],+ "high": bar[1],+ "low": bar[2],+ "close": bar[3],+ "volume": 120000.0,+ }+ for label, bar in zip(_LABELS, bars, strict=True)+ ]+ frame = pd.DataFrame(records)+ frame["bar_time"] = pd.to_datetime(frame["bar_time"])+ return frame.set_index("bar_time")+++def _reference(bar: Bar, path_model: str = "bar_median") -> Decimal:+ """Recompute a bar reference independently of the engine.++ ``money()`` is ``Decimal(str(x))`` and the frozen tick is 2dp HALF_UP;+ both are restated here rather than imported so an engine change cannot+ make this assertion agree with a wrong price.+ """+ open_, high, low, close = (Decimal(str(value)) for value in bar)+ if path_model == "bar_close":+ raw = close+ else:+ prices = sorted((open_, high, low, close))+ raw = (prices[1] + prices[2]) / Decimal(2)+ return raw.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)+++def _daily() -> pd.DataFrame:+ rows = [(_PREV, 10.00), (_DAY, 10.20)]+ frame = pd.DataFrame(+ [+ {+ "trade_date": day,+ "open": close,+ "high": close,+ "low": close,+ "close": close,+ "volume": 1000.0,+ }+ for day, close in rows+ ]+ )+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])+ return frame.set_index("trade_date")+++class _FakeChClient:+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:+ return pd.DataFrame()+++class _FakeLoader:+ name = "tencent"++ def __init__(self, five: dict[str, pd.DataFrame]) -> None:+ self._daily = {_SYM: _daily()}+ self._five = five+ self.calls: list[tuple[tuple[str, ...], str, str, str]] = []++ def is_available(self) -> bool:+ return True++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ self.calls.append((tuple(codes), start_date, end_date, interval))+ source = self._five if interval == "5m" else self._daily+ return {code: source[code] for code in codes if code in source}+++class _FakeCalendarClient:+ def __init__(self, open_days: frozenset[str]) -> None:+ self._open = open_days++ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:+ rows = [+ {+ "exchange": "SSE",+ "cal_date": day.strftime("%Y-%m-%d"),+ "is_open": int(day.strftime("%Y-%m-%d") in self._open),+ "pretrade_date": "",+ }+ for day in pd.date_range(start_date, end_date)+ ]+ return pd.DataFrame(rows, columns=["exchange", "cal_date", "is_open", "pretrade_date"])+++# ── harness ──────────────────────────────────────────────────────────────────+++def _outcome(+ *,+ orders: list[dict],+ five: dict[str, pd.DataFrame],+ cash: float = 100000.0,+ positions: tuple[dict, ...] = (),+ path_model: str = "bar_median",+):+ market_data = fetch_market_data(+ "cn_a",+ [_SYM],+ _DAY,+ _DAY,+ loader=_FakeLoader(five),+ ch_client=_FakeChClient(),+ interval="5m",+ )+ request = parse_request(+ {+ "account_id": "pa_5m_limit",+ "market": "cn_a",+ "account_state": {"cash": cash, "positions": list(positions)},+ "orders": orders,+ "from_date": _DAY,+ "to_date": _DAY,+ "fee_model": dict(_FEE_MODEL),+ "interval": "5m",+ "path_model": path_model,+ }+ )+ return engine.match_orders(+ request,+ market_data=market_data,+ calendar_client=_FakeCalendarClient(frozenset({_DAY})),+ )+++def _buy(limit: float | None = None, qty: float = 100) -> dict:+ order = {"symbol": _SYM, "side": "buy", "qty": qty}+ if limit is not None:+ order["limit"] = limit+ return order+++def _sell(limit: float | None = None, qty: float = 100) -> dict:+ order = {"symbol": _SYM, "side": "sell", "qty": qty}+ if limit is not None:+ order["limit"] = limit+ return order+++_HELD = ({"symbol": _SYM, "qty": 100, "avg_cost": 10.0},)+++def _fills(outcome) -> list[tuple[str, float, float]]:+ return [(fill.side, fill.qty, fill.price) for fill in outcome.fills]+++def _cancels(outcome) -> list[tuple[str, str, float, str, str]]:+ return [+ (cancel.symbol, cancel.side, cancel.qty, cancel.reason_code, cancel.detail)+ for cancel in outcome.canceled_orders+ ]+++def _observed(outcome) -> str:+ return (+ f"fills={_fills(outcome)!r}, "+ f"rejected={[(r.reason_code, r.detail) for r in outcome.rejected_orders]!r}, "+ f"canceled={_cancels(outcome)!r}"+ )+++def _assert_day_end_cancel(outcome, *, side: str, qty: float, case: str) -> None:+ """Exactly one day-end cancel of the whole (all-or-none) order."""+ cancels = _cancels(outcome)+ assert len(cancels) == 1, f"{case}: expected one day-end cancel; {_observed(outcome)}"+ symbol, cancel_side, cancel_qty, reason, detail = cancels[0]+ assert (symbol, cancel_side, cancel_qty) == (_SYM, side, qty), (+ f"{case}: cancel must carry the order's symbol/side/qty; got {cancels!r}"+ )+ assert reason == CANCELED_REASON_CODE, f"{case}: unexpected cancel reason; got {cancels!r}"+ assert detail.startswith("unfilled day order canceled at session end"), (+ f"{case}: expected the day-end cancel, not a rejection cancel; got {cancels!r}"+ )+++# ── case 1 ───────────────────────────────────────────────────────────────────+++def test_case1_resting_buy_fills_at_the_limit_when_the_bar_low_crosses() -> None:+ """Bar 1 ref 10.30 rests; bar 2 low 9.80 < 10.00 fills at 委托价 10.00."""+ bars = (+ (10.30, 10.30, 10.30, 10.30),+ (10.00, 10.40, 9.80, 10.40),+ )+ outcome = _outcome(orders=[_buy(limit=10.00)], five={_SYM: _intraday(_DAY, bars)})++ assert _reference(bars[0]) == Decimal("10.30")+ assert _reference(bars[1]) == Decimal("10.20")+ assert _fills(outcome) == [("buy", 100.0, 10.00)], (+ "case 1 (buy limit 10.00): a resting limit must fill at 委托价 10.00 once "+ "bar 2's low (9.80) is strictly below the limit. The current tree defers the "+ "order because bar 2's reference (10.20) is worse than the limit instead of "+ f"triggering on the bar low; {_observed(outcome)}"+ )+ assert outcome.rejected_orders == (), f"case 1: {_observed(outcome)}"+ assert outcome.canceled_orders == (), f"case 1: {_observed(outcome)}"+++# ── case 2 ───────────────────────────────────────────────────────────────────+++def test_case2_resting_buy_does_not_fill_when_the_bar_low_equals_the_limit() -> None:+ """Bar 1 ref 10.30 rests; bar 2 low == ref == 10.00 -> strict rule: no fill."""+ bars = (+ (10.30, 10.30, 10.30, 10.30),+ (10.00, 10.00, 10.00, 10.00),+ )+ outcome = _outcome(orders=[_buy(limit=10.00)], five={_SYM: _intraday(_DAY, bars)})++ assert _reference(bars[1]) == Decimal("10.00")+ assert _fills(outcome) == [], (+ "case 2 (buy limit 10.00): bar 2's low equals the limit (10.00 == 10.00), "+ "so the strict `bar.low < limit` rule must leave the order unfilled. The "+ "current tree fills at 10.00 because the reference merely equals the limit "+ f"and equality is treated as marketable; {_observed(outcome)}"+ )+ assert outcome.rejected_orders == (), f"case 2: {_observed(outcome)}"+ _assert_day_end_cancel(outcome, side="buy", qty=100.0, case="case 2")+++# ── case 3 ───────────────────────────────────────────────────────────────────+++def test_case3_resting_sell_fills_at_the_limit_when_the_bar_high_crosses() -> None:+ """Bar 1 ref 9.70 rests; bar 2 high 10.20 > 10.00 fills at 委托价 10.00."""+ bars = (+ (9.70, 9.70, 9.70, 9.70),+ (10.00, 10.20, 9.70, 9.80),+ )+ outcome = _outcome(+ orders=[_sell(limit=10.00)],+ five={_SYM: _intraday(_DAY, bars)},+ positions=_HELD,+ )++ assert _reference(bars[0]) == Decimal("9.70")+ assert _reference(bars[1]) == Decimal("9.90")+ assert _fills(outcome) == [("sell", 100.0, 10.00)], (+ "case 3 (sell limit 10.00): a resting limit must fill at 委托价 10.00 once "+ "bar 2's high (10.20) is strictly above the limit. The current tree defers "+ "the order because bar 2's reference (9.90) is worse than the limit instead "+ f"of triggering on the bar high; {_observed(outcome)}"+ )+ assert outcome.rejected_orders == (), f"case 3: {_observed(outcome)}"+ assert outcome.canceled_orders == (), f"case 3: {_observed(outcome)}"+++# ── case 4 ───────────────────────────────────────────────────────────────────+++def test_case4_resting_sell_does_not_fill_when_the_bar_high_equals_the_limit() -> None:+ """Bar 1 ref 9.70 rests; bar 2 high == ref == 10.00 -> strict rule: no fill."""+ bars = (+ (9.70, 9.70, 9.70, 9.70),+ (10.00, 10.00, 10.00, 10.00),+ )+ outcome = _outcome(+ orders=[_sell(limit=10.00)],+ five={_SYM: _intraday(_DAY, bars)},+ positions=_HELD,+ )++ assert _reference(bars[1]) == Decimal("10.00")+ assert _fills(outcome) == [], (+ "case 4 (sell limit 10.00): bar 2's high equals the limit (10.00 == 10.00), "+ "so the strict `bar.high > limit` rule must leave the order unfilled. The "+ "current tree fills at 10.00 because the reference merely equals the limit "+ f"and equality is treated as marketable; {_observed(outcome)}"+ )+ assert outcome.rejected_orders == (), f"case 4: {_observed(outcome)}"+ _assert_day_end_cancel(outcome, side="sell", qty=100.0, case="case 4")+++# ── case 5: first live bar marketability ─────────────────────────────────────+++def test_case5_buy_first_bar_is_marketable_only_below_the_limit() -> None:+ """A buy limit on a flat 10.40 first bar: fills at 10.40 under 10.50, rests at 10.40."""+ bars = (+ (10.40, 10.40, 10.40, 10.40),+ (10.40, 10.40, 10.40, 10.40),+ )+ frame = _intraday(_DAY, bars)+ assert _reference(bars[0]) == Decimal("10.40")++ marketable = _outcome(orders=[_buy(limit=10.50)], five={_SYM: frame})+ assert _fills(marketable) == [("buy", 100.0, 10.40)], (+ "case 5 (buy, ref 10.40 < limit 10.50): the first bar is marketable and must "+ f"fill at its reference, never worse than the limit; {_observed(marketable)}"+ )+ assert marketable.fills[0].price <= 10.50+ assert marketable.rejected_orders == ()+ assert marketable.canceled_orders == ()++ resting = _outcome(orders=[_buy(limit=10.40)], five={_SYM: frame})+ assert _fills(resting) == [], (+ "case 5 (buy, ref 10.40 == limit 10.40): at equality the first bar is NOT "+ "marketable and the order must rest; the current tree fills at the reference "+ f"because equality is treated as marketable; {_observed(resting)}"+ )+ assert resting.rejected_orders == (), f"case 5 (buy equality): {_observed(resting)}"+ _assert_day_end_cancel(resting, side="buy", qty=100.0, case="case 5 (buy equality)")+++def test_case5_sell_first_bar_is_marketable_only_above_the_limit() -> None:+ """A sell limit on a flat 10.60 first bar: fills at 10.60 over 10.50, rests at 10.60."""+ bars = (+ (10.60, 10.60, 10.60, 10.60),+ (10.60, 10.60, 10.60, 10.60),+ )+ frame = _intraday(_DAY, bars)+ assert _reference(bars[0]) == Decimal("10.60")++ marketable = _outcome(orders=[_sell(limit=10.50)], five={_SYM: frame}, positions=_HELD)+ assert _fills(marketable) == [("sell", 100.0, 10.60)], (+ "case 5 (sell, ref 10.60 > limit 10.50): the first bar is marketable and must "+ f"fill at its reference, never worse than the limit; {_observed(marketable)}"+ )+ assert marketable.fills[0].price >= 10.50+ assert marketable.rejected_orders == ()+ assert marketable.canceled_orders == ()++ resting = _outcome(orders=[_sell(limit=10.60)], five={_SYM: frame}, positions=_HELD)+ assert _fills(resting) == [], (+ "case 5 (sell, ref 10.60 == limit 10.60): at equality the first bar is NOT "+ "marketable and the order must rest; the current tree fills at the reference "+ f"because equality is treated as marketable; {_observed(resting)}"+ )+ assert resting.rejected_orders == (), f"case 5 (sell equality): {_observed(resting)}"+ _assert_day_end_cancel(resting, side="sell", qty=100.0, case="case 5 (sell equality)")+++# ── case 6: path_model="bar_close" ───────────────────────────────────────────+++ ("side", "bars", "expected_fill"),+ [+ ("buy", ((10.30, 10.30, 10.30, 10.30), (10.00, 10.40, 9.80, 10.40)), 10.00),+ ("buy", ((10.30, 10.30, 10.30, 10.30), (10.00, 10.00, 10.00, 10.00)), None),+ ("sell", ((9.70, 9.70, 9.70, 9.70), (10.00, 10.20, 9.70, 9.80)), 10.00),+ ("sell", ((9.70, 9.70, 9.70, 9.70), (10.00, 10.00, 10.00, 10.00)), None),+ ],+ ids=["buy-cross", "buy-equality", "sell-cross", "sell-equality"],+)+def test_case6_bar_close_keeps_the_bar_low_high_verdict(+ side: str, bars: tuple[Bar, Bar], expected_fill: float | None+) -> None:+ """bar_close moves the reference; a low/high cross still decides the verdict."""+ frame = _intraday(_DAY, bars)+ order = _buy(limit=10.00) if side == "buy" else _sell(limit=10.00)+ outcome = _outcome(+ orders=[order],+ five={_SYM: frame},+ positions=() if side == "buy" else _HELD,+ path_model="bar_close",+ )+ close_ref = _reference(bars[-1], "bar_close")+ median_ref = _reference(bars[-1])+ if len(set(bars[-1])) > 1:+ # The bar is dispersed, so the two path models really disagree here...+ assert close_ref != median_ref++ if expected_fill is not None:+ assert _fills(outcome) == [(side, 100.0, expected_fill)], (+ f"case 6 ({side}-cross, bar_close ref {close_ref} vs bar_median ref "+ f"{median_ref}): a bar-low/high cross must decide the verdict and fill at "+ f"the 委托价 {expected_fill:.2f} regardless of the reference; "+ f"{_observed(outcome)}"+ )+ assert outcome.fills[0].price == expected_fill+ assert outcome.rejected_orders == (), f"case 6 ({side}-cross): {_observed(outcome)}"+ assert outcome.canceled_orders == (), f"case 6 ({side}-cross): {_observed(outcome)}"+ return++ assert _fills(outcome) == [], (+ f"case 6 ({side}-equality, bar_close ref {close_ref}): equality must not fill "+ f"under the strict bar low/high rule; {_observed(outcome)}"+ )+ assert outcome.rejected_orders == (), f"case 6 ({side}-equality): {_observed(outcome)}"+ _assert_day_end_cancel(outcome, side=side, qty=100.0, case=f"case 6 ({side}-equality)")+++def test_case6_bar_close_changes_the_first_bar_marketable_price() -> None:+ """Only the first-bar marketable *price* follows the reference, never the limit rule."""+ buy_bar: Bar = (10.00, 10.30, 9.90, 10.30)+ buy_frame = _intraday(_DAY, (buy_bar, (10.30, 10.30, 10.30, 10.30)))+ assert _reference(buy_bar) == Decimal("10.15")+ assert _reference(buy_bar, "bar_close") == Decimal("10.30")++ buy_median = _outcome(orders=[_buy(limit=10.35)], five={_SYM: buy_frame})+ buy_close = _outcome(+ orders=[_buy(limit=10.35)], five={_SYM: buy_frame}, path_model="bar_close"+ )+ assert _fills(buy_median) == [("buy", 100.0, 10.15)], (+ "case 6 (buy first bar): bar_median reference 10.15 is strictly below the "+ f"limit 10.35, so the fill is the reference; {_observed(buy_median)}"+ )+ assert _fills(buy_close) == [("buy", 100.0, 10.30)], (+ "case 6 (buy first bar): bar_close reference 10.30 is strictly below the "+ f"limit 10.35, so the fill is the reference; {_observed(buy_close)}"+ )+ assert buy_median.fills[0].price <= 10.35 and buy_close.fills[0].price <= 10.35+ assert buy_median.canceled_orders == () and buy_close.canceled_orders == ()++ sell_bar: Bar = (10.80, 10.80, 10.50, 10.50)+ sell_frame = _intraday(_DAY, (sell_bar, (10.50, 10.50, 10.50, 10.50)))+ assert _reference(sell_bar) == Decimal("10.65")+ assert _reference(sell_bar, "bar_close") == Decimal("10.50")++ sell_median = _outcome(orders=[_sell(limit=10.40)], five={_SYM: sell_frame}, positions=_HELD)+ sell_close = _outcome(+ orders=[_sell(limit=10.40)],+ five={_SYM: sell_frame},+ positions=_HELD,+ path_model="bar_close",+ )+ assert _fills(sell_median) == [("sell", 100.0, 10.65)], (+ "case 6 (sell first bar): bar_median reference 10.65 is strictly above the "+ f"limit 10.40, so the fill is the reference; {_observed(sell_median)}"+ )+ assert _fills(sell_close) == [("sell", 100.0, 10.50)], (+ "case 6 (sell first bar): bar_close reference 10.50 is strictly above the "+ f"limit 10.40, so the fill is the reference; {_observed(sell_close)}"+ )+ assert sell_median.fills[0].price >= 10.40 and sell_close.fills[0].price >= 10.40+ assert sell_median.canceled_orders == () and sell_close.canceled_orders == ()diff --git a/agent/tests/test_paper_trade_order_status.py b/agent/tests/test_paper_trade_order_status.pynew file mode 100644index 000000000..0ec05d72e--- /dev/null+++ b/agent/tests/test_paper_trade_order_status.py@@ -0,0 +1,131 @@+"""Failing-first tests for JoinQuant order-status semantics (#1938).++JoinQuant's ``OrderStatus`` names the two degrees of completion the other way+round from the phase-1 lifecycle that shipped:++- ``filled`` -> partially filled, still active: it may receive further fills+ and it can still be canceled;+- ``held`` -> fully filled, terminal: it can neither fill nor be canceled.++These tests pin that contract through the public ``OrderBook`` API. They are+expected to fail on the pre-fix tree, where ``STATUS_FILLED`` marks a complete+fill and ``STATUS_HELD`` a partial one.+"""++from __future__ import annotations++from decimal import Decimal++import pytest++from src.tools.paper_trade.order_lifecycle import (+ STATUS_CANCELED,+ STATUS_FILLED,+ STATUS_HELD,+ STATUS_PENDING_CANCEL,+ OrderBook,+ OrderLifecycleError,+ OrderRequest,+ assign_ids,+ replay_snapshot,+)++D = Decimal+++def _request(**overrides):+ kwargs = dict(symbol="600519.SH", side="buy", qty=D("100"))+ kwargs.update(overrides)+ return OrderRequest(**kwargs)+++def _partially_filled_book(book_qty: str = "100", fill_qty: str = "40") -> OrderBook:+ """One activated order filled for less than it requested."""+ book = OrderBook(assign_ids([_request(qty=D(book_qty))]))+ book.activate("pt-0")+ book.fill("pt-0", D(fill_qty), D("1700.00"))+ return book+++def test_full_fill_ends_held_and_terminal():+ """A complete fill is ``held`` and accepts no further lifecycle event."""+ book = OrderBook(assign_ids([_request(qty=D("100"))]))+ book.activate("pt-0")+ book.fill("pt-0", D("100"), D("1700.00"))++ state = book.get("pt-0")+ assert state is not None+ assert state.filled_qty == D("100")+ assert state.status == STATUS_HELD+ # Terminal: not among today's open orders.+ assert "pt-0" not in [open_state.order_id for open_state in book.open_orders()]+ with pytest.raises(OrderLifecycleError, match="cannot fill"):+ book.fill("pt-0", D("1"), D("1700.00"))+ with pytest.raises(OrderLifecycleError, match="cannot be canceled"):+ book.request_cancel("pt-0")+++def test_partial_fill_ends_filled_stays_open_and_settles_to_canceled():+ """A partial fill is ``filled``, remains open, and its residual settles."""+ book = OrderBook(assign_ids([_request(qty=D("100"))]))+ book.activate("pt-0")+ book.fill("pt-0", D("40"), D("1700.00"))++ state = book.get("pt-0")+ assert state is not None+ assert state.filled_qty == D("40")+ assert state.status == STATUS_FILLED+ assert [open_state.order_id for open_state in book.open_orders()] == ["pt-0"]++ settled = book.settle_day()+ assert [settled_state.order_id for settled_state in settled] == ["pt-0"]+ assert state.status == STATUS_CANCELED+ assert state.filled_qty == D("40")+ assert state.request.qty - state.filled_qty == D("60")+++def test_request_cancel_accepts_filled_and_refuses_held():+ """Cancel is accepted on a partial fill and refused on a complete one."""+ partial = _partially_filled_book()+ assert partial.get("pt-0").status == STATUS_FILLED+ canceled = partial.request_cancel("pt-0")+ assert canceled.status == STATUS_PENDING_CANCEL++ full = OrderBook(assign_ids([_request(qty=D("100"))]))+ full.activate("pt-0")+ full.fill("pt-0", D("100"), D("1700.00"))+ assert full.get("pt-0").status == STATUS_HELD+ with pytest.raises(OrderLifecycleError, match="cannot be canceled"):+ full.request_cancel("pt-0")+++def test_replay_snapshot_reports_filled_for_partial_and_held_for_full():+ """The replay snapshot carries the JoinQuant names, not the inverted ones."""+ book = OrderBook(+ assign_ids([_request(qty=D("100")), _request(side="sell", qty=D("100"))])+ )+ book.activate("pt-0")+ book.activate("pt-1")+ book.fill("pt-0", D("40"), D("1700.00"))+ book.fill("pt-1", D("100"), D("1710.00"))++ snapshot = replay_snapshot(book)+ assert snapshot["pt-0"]["status"] == STATUS_FILLED+ assert snapshot["pt-0"]["filled_qty"] == "40"+ assert snapshot["pt-1"]["status"] == STATUS_HELD+ assert snapshot["pt-1"]["filled_qty"] == "100"+++def test_canceled_partial_keeps_its_filled_qty():+ """Canceling a partial fill does not erase the quantity already executed."""+ book = _partially_filled_book()+ book.request_cancel("pt-0")+ settled = book.settle_day()++ state = book.get("pt-0")+ assert [settled_state.order_id for settled_state in settled] == ["pt-0"]+ assert state is not None+ assert state.status == STATUS_CANCELED+ assert state.filled_qty == D("40")+ assert [fill.qty for fill in state.fills] == [D("40")]+ assert replay_snapshot(book)["pt-0"]["filled_qty"] == "40"diff --git a/agent/tests/test_paper_trade_v12_schema.py b/agent/tests/test_paper_trade_v12_schema.pyindex 5b2b46e60..0b2b237c2 100644--- a/agent/tests/test_paper_trade_v12_schema.py+++ b/agent/tests/test_paper_trade_v12_schema.py@@ -262,7 +262,11 @@ def test_engine_fingerprint_matches_the_frozen_formula() -> None:"bar_fingerprint": _HEX_A,})- assert rules.RULES_VERSION == "pt-rules-v1"+ assert rules.RULES_VERSION == "pt-rules-v2"+ assert actual != state_hash.engine_fingerprint(+ interval="5m", path_model="bar_close", fill_model="all_or_none",+ bar_fingerprint=_HEX_A, rules_version="pt-rules-v1",+ )assert actual == manualassert re.fullmatch(r"[0-9a-f]{64}", actual)