Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(paper-trade): cancel price-limit market orders (#2176)

Haozhe Wu3afeabaf5bf4
diff --git a/agent/src/tools/paper_trade/README.md b/agent/src/tools/paper_trade/README.md
index 2fc0e2747..25d27846a 100644
--- a/agent/src/tools/paper_trade/README.md
+++ b/agent/src/tools/paper_trade/README.md
@@ -107,8 +107,18 @@ 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
-resting limit follows JoinQuant's bar matching: a buy triggers only when
+A market order fills at the first continuous bar whose fill gates pass. If a
+buy is blocked at the upper price limit or a sell at the lower limit, it is
+canceled immediately and cannot fill on a later bar even if the price reopens.
+The result contains one `canceled_orders` entry with the existing
+`canceled_after_failed_match` reason and a detail naming `limit_up` or
+`limit_down`, plus a `price_limit` event; it is not a rejected order. A limit
+order blocked by the price band instead stays open until it fills or expires at
+the end of the session ([JoinQuant API guide, order processing](https://cdn.joinquant.com/help/img/JoinQuantAPI.pdf)).
+The default daily pt-v1.1 contract is unchanged and
+continues to report its established rejection reasons.
+
+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
@@ -182,9 +192,10 @@ cannot fill. Corporate actions remain fail-closed.
- **5m strategy UNIVERSE is strict.** An order on a position outside the
declared `UNIVERSE` fails the whole call, so such a position cannot be reduced
by 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;
+- **Matching changes are versioned.** `pt-rules-v3` identifies the immediate
+ price-limit market cancellation; `pt-rules-v2` identified the corrected
+ full/partial order statuses and 5m limit-fill rules. Each rule version has a
+ different engine fingerprint even with identical bars and model settings;
archived results retain their original version.
diff --git a/agent/src/tools/paper_trade/engine.py b/agent/src/tools/paper_trade/engine.py
index b0d826893..fda78f64b 100644
--- a/agent/src/tools/paper_trade/engine.py
+++ b/agent/src/tools/paper_trade/engine.py
@@ -324,9 +324,9 @@ class _MatchSession:
up, down = self._band(order.symbol, day.date, sym_data)
code = self.rules.band_rejection(order.side, price, up, down)
if code == "limit_up":
- return (code, f"price {price:.2f} at or above up limit {up:.2f}; buy deferred")
+ return (code, f"price {price:.2f} at or above up limit {up:.2f}; buy blocked")
if code == "limit_down":
- return (code, f"price {price:.2f} at or below down limit {down:.2f}; sell deferred")
+ return (code, f"price {price:.2f} at or below down limit {down:.2f}; sell blocked")
if self.rules.limit_order_violation(order.side, price, order.limit):
anchor = "price" if self._five_minute else "close"
detail = (
diff --git a/agent/src/tools/paper_trade/paper_trade_step-v1.2.json b/agent/src/tools/paper_trade/paper_trade_step-v1.2.json
index ba08d2bca..8c7a058b7 100644
--- a/agent/src/tools/paper_trade/paper_trade_step-v1.2.json
+++ b/agent/src/tools/paper_trade/paper_trade_step-v1.2.json
@@ -1,5 +1,5 @@
{
- "$comment": "FINALIZED pt-v1.2 — ADDITIVE bump of the frozen pt-v1.1 contract (schema/tool_contracts/paper_trade_step-v1.1.json, which is NOT edited). Scope: the cn_a 5m post-close step (P0 execution plan T2), decisions D1-D8 of the paper-trade-p0-5m-execution decision record. Additions only (REQUIREMENTS §9: additive = minor bump): request-side interval/session/path_model/fill_model are all optional and default to the pt-v1.1 semantics (1d/auto/bar_median/all_or_none); result-side engine_fingerprint/canceled_orders/events are emitted ONLY for a v1.2 call, where v1.2 means at least one new request field is non-default. A call that omits every new field is a pt-v1.1 call: identical bytes, identical received_state_hash, schema_version 'pt-v1.1' (D4/D8). PHASE-2 SEMANTICS: pt-v1.2 adds NO order-level bar/timestamp field, so a fill is attributed to the bar whose reference price produced it, not to a client order timestamp. For interval='5m' the engine matches bar by bar over the 48 continuous bars; a market order fills at the first marketable bar, a resting limit order fills at its limit price once a bar trades strictly through it (pt-rules-v2; on the first continuous bar a strictly better reference price fills at that price) and is canceled at session end if never triggered, and no partial fills or volume share are modeled (Phase 3). HK/US 5m is out of scope. The dependency-free validator in agent/src/tools/paper_trade/schema.py implements a keyword subset (type/const/enum/required/properties/items/additionalProperties) and ignores the version-gated allOf/if/then block in the result schema; pattern/minLength are documentation for the real jsonschema library, which can consume this standard draft-2020-12 document.",
+ "$comment": "FINALIZED pt-v1.2 — ADDITIVE bump of the frozen pt-v1.1 contract (schema/tool_contracts/paper_trade_step-v1.1.json, which is NOT edited). Scope: the cn_a 5m post-close step (P0 execution plan T2), decisions D1-D8 of the paper-trade-p0-5m-execution decision record. Additions only (REQUIREMENTS §9: additive = minor bump): request-side interval/session/path_model/fill_model are all optional and default to the pt-v1.1 semantics (1d/auto/bar_median/all_or_none); result-side engine_fingerprint/canceled_orders/events are emitted ONLY for a v1.2 call, where v1.2 means at least one new request field is non-default. A call that omits every new field is a pt-v1.1 call: identical bytes, identical received_state_hash, schema_version 'pt-v1.1' (D4/D8). PHASE-2 SEMANTICS: pt-v1.2 adds NO order-level bar/timestamp field, so a fill is attributed to the bar whose reference price produced it, not to a client order timestamp. For interval='5m' the engine matches bar by bar over the 48 continuous bars; a market order fills at the first marketable bar or is canceled immediately if the price band blocks its side (pt-rules-v3), a resting limit order fills at its limit price once a bar trades strictly through it (pt-rules-v2; on the first continuous bar a strictly better reference price fills at that price) and is canceled at session end if never triggered, and no partial fills or volume share are modeled (Phase 3). HK/US 5m is out of scope. The dependency-free validator in agent/src/tools/paper_trade/schema.py implements a keyword subset (type/const/enum/required/properties/items/additionalProperties) and ignores the version-gated allOf/if/then block in the result schema; pattern/minLength are documentation for the real jsonschema library, which can consume this standard draft-2020-12 document.",
"contract": "paper_trade_step",
"version": "pt-v1.2",
"status": "final",
diff --git a/agent/src/tools/paper_trade/rules.py b/agent/src/tools/paper_trade/rules.py
index 683ade696..26c3f60cc 100644
--- a/agent/src/tools/paper_trade/rules.py
+++ b/agent/src/tools/paper_trade/rules.py
@@ -60,7 +60,7 @@ __all__ = [
#: 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-v2"
+RULES_VERSION = "pt-rules-v3"
#: AM-14 frozen rejection decision order — first match wins (REQUIREMENTS §2
#: hard semantics 3a). ``limit_up``/``limit_down`` share one frozen slot and
diff --git a/agent/src/tools/paper_trade/session_5m.py b/agent/src/tools/paper_trade/session_5m.py
index 75fdd9f1f..0d9798bab 100644
--- a/agent/src/tools/paper_trade/session_5m.py
+++ b/agent/src/tools/paper_trade/session_5m.py
@@ -9,7 +9,8 @@ untouched.
Phase-2/3 semantics:
- a market order fills in full at the first continuous bar whose fill gates
- pass, at that bar's reference price;
+ pass, at that bar's reference price; a market order blocked by the daily
+ price limit is canceled immediately, rather than waiting for another bar;
- 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
@@ -41,7 +42,7 @@ from typing import TYPE_CHECKING, Any, Sequence
from .order_lifecycle import _ACTIVE_STATUSES, OrderBook, OrderRequest, assign_ids
from .rules import money, quantize_money
-from .schema import CANCELED_REASON_CODE, CanceledOrder, Order
+from .schema import CANCELED_REASON_CODE, CanceledOrder, Order, SessionEvent
if TYPE_CHECKING:
from .engine import DayPlan, _MatchSession
@@ -83,17 +84,20 @@ def _limit_fill_price(order: Order, ref: Decimal, bar: Any, *, first_bar: bool)
def _cancel_unfilled(
- session: "_MatchSession", day: "DayPlan", book: OrderBook, by_id: dict[str, Order]
+ session: "_MatchSession", day: "DayPlan", book: OrderBook, by_id: dict[str, Order],
+ price_limit_cancels: dict[str, tuple[str, str]],
) -> None:
for state in book.settle_day():
order = by_id[state.order_id]
+ gate = price_limit_cancels.get(state.order_id)
session.canceled.append(CanceledOrder(
trade_date=day.date,
symbol=order.symbol,
side=order.side,
qty=order.qty,
reason_code=CANCELED_REASON_CODE,
- detail="unfilled day order canceled at session end",
+ detail=(f"market order canceled: {gate[0]}; {gate[1]}" if gate
+ else "unfilled day order canceled at session end"),
))
@@ -105,7 +109,7 @@ def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[O
by_id = dict(zip(states, orders, strict=True))
book = OrderBook(states)
- deferred: dict[str, tuple[str, str]] = {}
+ price_limit_cancels: dict[str, tuple[str, str]] = {}
active: list[str] = []
for order_id, order in by_id.items():
gate = session._day_gate(day, order)
@@ -156,10 +160,17 @@ def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[O
if gate is not None:
code, detail = gate
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] = gate
+ if order.limit is None:
+ # No later bar may revive a canceled market order.
+ # Pending-cancel is excluded from matching and is
+ # settled to canceled exactly once at day end.
+ book.request_cancel(order_id)
+ price_limit_cancels[order_id] = gate
+ session.events.append(SessionEvent(
+ trade_date=day.date, symbol=order.symbol,
+ event_type="price_limit", detail=detail))
+ # A blocked limit order remains open until another
+ # bar can match it, or it expires at session end.
continue
book.reject(order_id, code)
session._reject(day, order, code, detail)
@@ -167,9 +178,4 @@ def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[O
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 in _ACTIVE_STATUSES:
- book.reject(order_id, gate[0])
- session._reject(day, by_id[order_id], *gate)
- _cancel_unfilled(session, day, book, by_id)
+ _cancel_unfilled(session, day, book, by_id, price_limit_cancels)
diff --git a/agent/tests/test_paper_trade_5m_engine.py b/agent/tests/test_paper_trade_5m_engine.py
index eec538611..7e320d8a8 100644
--- a/agent/tests/test_paper_trade_5m_engine.py
+++ b/agent/tests/test_paper_trade_5m_engine.py
@@ -16,13 +16,17 @@ Offline: synthetic frames through a fake loader, never the network.
from __future__ import annotations
import datetime as dt
+import json
import pandas as pd
import pytest
from src.tools.paper_trade import engine, state_hash
from src.tools.paper_trade.data import fetch_market_data
-from src.tools.paper_trade.schema import CANCELED_REASON_CODE, REASON_CODES, parse_request
+from src.tools.paper_trade.schema import (
+ CANCELED_REASON_CODE, REASON_CODES, load_contract_schema, parse_request, validate_payload,
+)
+from src.tools.paper_trade.tool import run_paper_trade_step
_DAY = "2026-10-20"
_PREV = "2026-10-19"
@@ -317,19 +321,20 @@ def test_lot_size_rejects_and_cancels() -> None:
assert len(outcome.canceled_orders) == 1
-def test_limit_up_buy_rejects_with_a_price_limit_event() -> None:
+def test_limit_up_buy_cancels_with_a_price_limit_event() -> None:
daily = {_SYM: _daily([(_PREV, 10.00), (_DAY, 11.00)])}
five = {_SYM: _flat_5m(_DAY, 11.00)}
outcome = _outcome(orders=[_buy()], daily=daily, five=five)
assert outcome.fills == ()
- assert [r.reason_code for r in outcome.rejected_orders] == ["limit_up"]
+ assert outcome.rejected_orders == ()
assert [(e.symbol, e.event_type) for e in outcome.events] == [(_SYM, "price_limit")]
assert "up limit 11.00" in outcome.events[0].detail
assert len(outcome.canceled_orders) == 1
+ assert "limit_up" in outcome.canceled_orders[0].detail
-def test_limit_down_sell_rejects_with_a_price_limit_event() -> None:
+def test_limit_down_sell_cancels_with_a_price_limit_event() -> None:
daily = {_SYM: _daily([(_PREV, 10.00), (_DAY, 9.00)])}
five = {_SYM: _flat_5m(_DAY, 9.00)}
outcome = _outcome(
@@ -337,9 +342,87 @@ def test_limit_down_sell_rejects_with_a_price_limit_event() -> None:
)
assert outcome.fills == ()
- assert [r.reason_code for r in outcome.rejected_orders] == ["limit_down"]
+ assert outcome.rejected_orders == ()
assert [(e.symbol, e.event_type) for e in outcome.events] == [(_SYM, "price_limit")]
assert len(outcome.canceled_orders) == 1
+ assert "limit_down" in outcome.canceled_orders[0].detail
+
+
[email protected]("side,blocked,later", [("buy", 11.0, 10.2), ("sell", 9.0, 9.8)])
+def test_price_limit_canceled_market_order_never_revives(side, blocked, later) -> None:
+ labels = _session_labels()
+ prices = {label: later for label in labels}
+ prices[labels[0]] = blocked
+ daily = {_SYM: _daily([(_PREV, 10.0), (_DAY, later)])}
+ five = {_SYM: _intraday(_DAY, prices)}
+ positions = [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}] if side == "sell" else []
+ outcome = _outcome(orders=[{"symbol": _SYM, "side": side, "qty": 100}],
+ positions=positions, daily=daily, five=five)
+ assert outcome.fills == ()
+ assert outcome.rejected_orders == ()
+ assert len(outcome.canceled_orders) == 1
+ expected_reason = "limit_up" if side == "buy" else "limit_down"
+ assert expected_reason in outcome.canceled_orders[0].detail
+ assert [event.event_type for event in outcome.events] == ["price_limit"]
+ assert outcome.end_state.cash == 100000.0
+ assert len(outcome.end_state.positions) == len(positions)
+ if positions:
+ assert outcome.end_state.positions[0].qty == 100
+
+
[email protected]("side,price", [("buy", 9.0), ("sell", 11.0)])
+def test_opposite_side_of_price_limit_can_fill(side, price):
+ daily = {_SYM: _daily([(_PREV, 10.0), (_DAY, price)])}
+ positions = [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}] if side == "sell" else []
+ outcome = _outcome(orders=[{"symbol": _SYM, "side": side, "qty": 100}],
+ positions=positions, daily=daily, five={_SYM: _flat_5m(_DAY, price)})
+ assert len(outcome.fills) == 1
+ assert outcome.fills[0].price == price
+ assert outcome.rejected_orders == ()
+ assert outcome.canceled_orders == ()
+
+
+def test_price_limit_blocked_limit_order_expires_without_rejection() -> None:
+ daily = {_SYM: _daily([(_PREV, 10.0), (_DAY, 11.0)])}
+ five = {_SYM: _flat_5m(_DAY, 11.0)}
+ # The first bar reference is better than this limit but is itself at the
+ # exchange ceiling, so the limit cannot fill and must remain resting.
+ outcome = _outcome(orders=[_buy(limit=11.1)], daily=daily, five=five)
+ assert outcome.fills == ()
+ assert outcome.rejected_orders == ()
+ assert len(outcome.canceled_orders) == 1
+ assert outcome.canceled_orders[0].detail == "unfilled day order canceled at session end"
+
+
+def test_price_limit_cancellation_reaches_the_wire_and_replays_identically():
+ labels = _session_labels()
+ prices = {label: 10.2 for label in labels}
+ prices[labels[0]] = 11.0
+ daily = {_SYM: _daily([(_PREV, 10.0), (_DAY, 10.2)])}
+ five = {_SYM: _intraday(_DAY, prices)}
+ loader = FakeLoader(daily, five)
+ payload = {
+ "account_id": "pa_cancel", "market": "cn_a",
+ "account_state": {"cash": 100000.0, "positions": []},
+ "orders": [_buy()], "from_date": _DAY, "to_date": _DAY,
+ "fee_model": dict(_FEE_MODEL), "interval": "5m",
+ }
+ kwargs = {"loader": loader, "ch_client": FakeChClient(),
+ "calendar_client": FakeCalendarClient(frozenset({_DAY})), "limits_client": None}
+ first = run_paper_trade_step(payload, **kwargs)
+ assert first == run_paper_trade_step(payload, **kwargs)
+ result = json.loads(first)
+ assert validate_payload(result, load_contract_schema(version="pt-v1.2")) == []
+ assert result["schema_version"] == "pt-v1.2"
+ assert result["fills"] == result["rejected_orders"] == []
+ assert len(result["canceled_orders"]) == 1
+ assert result["canceled_orders"][0]["reason_code"] == CANCELED_REASON_CODE
+ assert "limit_up" in result["canceled_orders"][0]["detail"]
+ assert [event["event_type"] for event in result["events"]] == ["price_limit"]
+ assert result["end_state"] == payload["account_state"]
+ assert result["engine_fingerprint"] != state_hash.engine_fingerprint(
+ interval="5m", bar_fingerprint=_market_data(daily, five).bar_fingerprint,
+ rules_version="pt-rules-v2")
def test_halted_symbol_rejects_suspended_and_its_position_is_untouched() -> None:
@@ -443,12 +526,14 @@ def test_late_limit_up_does_not_reject_an_earlier_fill():
assert outcome.fills[0].price == 10.0
-def test_order_waits_for_limit_to_reopen():
+def test_market_order_does_not_wait_for_limit_to_reopen():
bars = _flat_5m(_DAY, 10.0)
bars.loc[pd.Timestamp(f"{_DAY} 09:35"), ["open", "high", "low", "close"]] = 11.0
outcome = _outcome(orders=[_buy()], five={_SYM: bars})
- assert len(outcome.fills) == 1
- assert outcome.fills[0].price == 10.0
+ assert outcome.fills == ()
+ assert outcome.rejected_orders == ()
+ assert len(outcome.canceled_orders) == 1
+ assert "limit_up" in outcome.canceled_orders[0].detail
def test_zero_volume_bar_cannot_fill():
diff --git a/agent/tests/test_paper_trade_v12_schema.py b/agent/tests/test_paper_trade_v12_schema.py
index 0b2b237c2..c04f22c06 100644
--- a/agent/tests/test_paper_trade_v12_schema.py
+++ b/agent/tests/test_paper_trade_v12_schema.py
@@ -262,7 +262,7 @@ def test_engine_fingerprint_matches_the_frozen_formula() -> None:
"bar_fingerprint": _HEX_A,
}
)
- assert rules.RULES_VERSION == "pt-rules-v2"
+ assert rules.RULES_VERSION == "pt-rules-v3"
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",
diff --git a/schema/tool_contracts/paper_trade_step-v1.2.json b/schema/tool_contracts/paper_trade_step-v1.2.json
index ba08d2bca..8c7a058b7 100644
--- a/schema/tool_contracts/paper_trade_step-v1.2.json
+++ b/schema/tool_contracts/paper_trade_step-v1.2.json
@@ -1,5 +1,5 @@
{
- "$comment": "FINALIZED pt-v1.2 — ADDITIVE bump of the frozen pt-v1.1 contract (schema/tool_contracts/paper_trade_step-v1.1.json, which is NOT edited). Scope: the cn_a 5m post-close step (P0 execution plan T2), decisions D1-D8 of the paper-trade-p0-5m-execution decision record. Additions only (REQUIREMENTS §9: additive = minor bump): request-side interval/session/path_model/fill_model are all optional and default to the pt-v1.1 semantics (1d/auto/bar_median/all_or_none); result-side engine_fingerprint/canceled_orders/events are emitted ONLY for a v1.2 call, where v1.2 means at least one new request field is non-default. A call that omits every new field is a pt-v1.1 call: identical bytes, identical received_state_hash, schema_version 'pt-v1.1' (D4/D8). PHASE-2 SEMANTICS: pt-v1.2 adds NO order-level bar/timestamp field, so a fill is attributed to the bar whose reference price produced it, not to a client order timestamp. For interval='5m' the engine matches bar by bar over the 48 continuous bars; a market order fills at the first marketable bar, a resting limit order fills at its limit price once a bar trades strictly through it (pt-rules-v2; on the first continuous bar a strictly better reference price fills at that price) and is canceled at session end if never triggered, and no partial fills or volume share are modeled (Phase 3). HK/US 5m is out of scope. The dependency-free validator in agent/src/tools/paper_trade/schema.py implements a keyword subset (type/const/enum/required/properties/items/additionalProperties) and ignores the version-gated allOf/if/then block in the result schema; pattern/minLength are documentation for the real jsonschema library, which can consume this standard draft-2020-12 document.",
+ "$comment": "FINALIZED pt-v1.2 — ADDITIVE bump of the frozen pt-v1.1 contract (schema/tool_contracts/paper_trade_step-v1.1.json, which is NOT edited). Scope: the cn_a 5m post-close step (P0 execution plan T2), decisions D1-D8 of the paper-trade-p0-5m-execution decision record. Additions only (REQUIREMENTS §9: additive = minor bump): request-side interval/session/path_model/fill_model are all optional and default to the pt-v1.1 semantics (1d/auto/bar_median/all_or_none); result-side engine_fingerprint/canceled_orders/events are emitted ONLY for a v1.2 call, where v1.2 means at least one new request field is non-default. A call that omits every new field is a pt-v1.1 call: identical bytes, identical received_state_hash, schema_version 'pt-v1.1' (D4/D8). PHASE-2 SEMANTICS: pt-v1.2 adds NO order-level bar/timestamp field, so a fill is attributed to the bar whose reference price produced it, not to a client order timestamp. For interval='5m' the engine matches bar by bar over the 48 continuous bars; a market order fills at the first marketable bar or is canceled immediately if the price band blocks its side (pt-rules-v3), a resting limit order fills at its limit price once a bar trades strictly through it (pt-rules-v2; on the first continuous bar a strictly better reference price fills at that price) and is canceled at session end if never triggered, and no partial fills or volume share are modeled (Phase 3). HK/US 5m is out of scope. The dependency-free validator in agent/src/tools/paper_trade/schema.py implements a keyword subset (type/const/enum/required/properties/items/additionalProperties) and ignores the version-gated allOf/if/then block in the result schema; pattern/minLength are documentation for the real jsonschema library, which can consume this standard draft-2020-12 document.",
"contract": "paper_trade_step",
"version": "pt-v1.2",
"status": "final",