Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(paper-trade): match the 5m session bar by bar on the order lifecycle

shadowinlifedccb17cf4bf1
diff --git a/README.md b/README.md
index 6f273c9dc..77b7e1f4a 100644
--- a/README.md
+++ b/README.md
@@ -1490,16 +1490,17 @@ execution date, and each day receives the ledger after preceding fills. The
agent/MCP `paper_trade_step` remains a stateless research primitive.
`paper_trade_step` also takes `interval="5m"` for A-shares: one step covers one
-completed session and matches against that session's single assembled bar, built
-from the 48 continuous five-minute bars. The 09:30 label is the opening
+completed session and matches bar by bar against its 48 continuous five-minute
+bars. The 09:30 label is the opening
call-auction print, single-priced on 4 of 5 probed days, and is excluded by
policy; labels in 09:15-09:25 or from 14:57 up to but not including 15:00 are
auction-window anomalies, and 15:00 is a continuous bar. The 5m leg uses Tushare
`stk_mins`, separate from the daily chain, which serves daily bars only. It
accepts one order symbol per step: the measured provider budget is 1
call/minute, 1 call/hour and 2 calls/day, and a refused call still consumes the
-daily budget. It fills all-or-none at the `path_model` reference (`bar_median` or
-`bar_close`) and requires a non-empty `UNIVERSE` in strategy mode. `session`,
+daily budget. It fills all-or-none at each bar's `path_model` reference
+(`bar_median` or `bar_close`) and requires a non-empty `UNIVERSE` in strategy
+mode. `session`,
`path_model` and `fill_model` default to the daily behaviour, so every existing
call is unchanged; `session` is a coherence selector only (`cn_a` requires
`market="cn_a"`) and does not change the day boundary.
diff --git a/agent/src/tools/paper_trade/README.md b/agent/src/tools/paper_trade/README.md
index 7fe24f952..a11b3b6e4 100644
--- a/agent/src/tools/paper_trade/README.md
+++ b/agent/src/tools/paper_trade/README.md
@@ -86,8 +86,8 @@ strategy failure discards the whole call, including earlier uncommitted results.
## Five-minute cn_a steps
`paper_trade_step` accepts `interval="5m"` for A-shares. One step covers exactly
-one completed session and matches against that session's single assembled bar,
-built from the 48 continuous five-minute bars. The 09:30 label is the opening
+one completed session and matches bar by bar against its 48 continuous
+five-minute bars. The 09:30 label is the opening
call-auction print, single-priced on 4 of 5 probed days, and is excluded by
policy without an event. A label in 09:15-09:25 or from 14:57 up to but not
including 15:00 is an auction-window anomaly, excluded from matching and
@@ -104,9 +104,14 @@ no row at all while its daily bar exists is a provider omission and returns
| --- | --- | --- | --- |
| `interval` | `1d`, `5m` | `1d` | `5m` is cn_a-only and accepts one date per step |
| `session` | `auto`, `cn_a` | `auto` | coherence selector only: `cn_a` requires `market="cn_a"` and does not change the day boundary |
-| `path_model` | `bar_median`, `bar_close` | `bar_median` | reference price from the session bar |
+| `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.
+
The 5m leg uses Tushare `stk_mins` and is resolved separately from the daily
chain: Tencent's raw loader serves daily bars only. The measured provider limit
is one symbol per step (1 call/minute, 1 call/hour and 2 calls/day; a refused
@@ -179,5 +184,5 @@ Matching is all-or-none, with simplified fees, price limits, board lots and T+1
checks. HK lot fallback is disclosed. Invalid OHLC prevents fills; valuation
uses a finite prior close or the disclosed average-cost fallback. This is not
broker-execution simulation. Settlement, margin, options and cross-market phases
-in #1938 remain follow-up work, as does the intraday order lifecycle (partial
-fills, resting orders across bars).
+in #1938 remain follow-up work, as do partial fills and the volume-share policy
+(Phase 3).
diff --git a/agent/src/tools/paper_trade/__init__.py b/agent/src/tools/paper_trade/__init__.py
index 6f88bd28f..06d34a5bd 100644
--- a/agent/src/tools/paper_trade/__init__.py
+++ b/agent/src/tools/paper_trade/__init__.py
@@ -15,8 +15,9 @@ AM-9 federation), ``rules.py`` (three-market rule matrix + ``RULES_VERSION``),
entry), ``strategy_exec.py`` (Step 7 strategy_path execution).
pt-v1.2 additive surface (cn_a 5m post-close step, P0): ``data_5m.py`` (stk_mins
-fetch + continuous-session assembly). It is opt-in: a call that omits every
-v1.2 request field is byte-identical to pt-v1.1.
+fetch + continuous-session assembly) and ``session_5m.py`` (per-bar
+``OrderBook`` wiring). It is opt-in: a call that omits every v1.2 request field
+is byte-identical to pt-v1.1.
The persistent v1.2 runner/account/store layer (``runner.py``, ``account.py``,
``store.py``, ``storage_io.py``, ``engine_adapter.py``, ``recovery.py``,
diff --git a/agent/src/tools/paper_trade/data.py b/agent/src/tools/paper_trade/data.py
index fb04303ac..17d2e4484 100644
--- a/agent/src/tools/paper_trade/data.py
+++ b/agent/src/tools/paper_trade/data.py
@@ -46,8 +46,10 @@ bound is exclusive at midnight. Each symbol-day is split by the cn_a session
clock (:func:`calendar.classify_cn_a_session_label`): the 09:30 opening
auction print is dropped silently, an auction-window label is dropped and
reported as an ``auction_window`` event source, and the continuous bars are
-assembled into ONE session bar (D1: open = first bar's open, high/low = extremes,
-close = last bar's close, volume = sum). Zero continuous bars on a
+assembled into one day-level session bar (D1: open = first bar's open,
+high/low = extremes, close = last bar's close, volume = sum). The per-bar
+engine keeps each continuous bar as its own matching opportunity; the session
+bar is the day-level gate and summary. Zero continuous bars on a
calendar-open day is a ``halted`` candidate; zero for the whole universe is
``PAPER_DATA_NOT_READY`` (D6). A symbol with a daily bar but no 5m session
bar is a provider omission (``stk_mins`` quota or permission) ONLY when the
diff --git a/agent/src/tools/paper_trade/data_5m.py b/agent/src/tools/paper_trade/data_5m.py
index ba7eb3b44..89970d6c0 100644
--- a/agent/src/tools/paper_trade/data_5m.py
+++ b/agent/src/tools/paper_trade/data_5m.py
@@ -77,19 +77,20 @@ NOT MEASURED — blocked by that 2-calls/day cap; do not present as fact
forward-filled bars; a symbol with no 5m row at all is a provider
omission and stays ``PAPER_DATA_NOT_READY``.
-ENGINE RULE — the P0 matched bar (D1, binding for T3/T4)
- pt-v1.2 adds NO order-level bar/timestamp field, so an order cannot be
- attributed to an individual 5m bar. The engine therefore assembles ONE
- session bar per symbol-day from the 48 CONTINUOUS bars: open = the 09:35
- bar's open, high/low = the session extremes, close = the 15:00 bar's
- close, volume = their sum. The 09:30 opening-auction print is EXCLUDED
- (T4: the auction window never matches), and a label inside 09:15-09:25 or
- from 14:57 up to but not including 15:00 is excluded and reported as an
- ``auction_window`` event (the 15:00 label is a continuous bar). Every order
- is terminal in that single session bar: no partial fills, no resting orders
- across bars, no re-submission on the next bar. Per-bar order re-submission (planbook F2) needs an
- order-level bar field and is explicitly deferred — it is a P0 limitation,
- not a missing implementation.
+ENGINE RULE — the day-level session bar (D1, binding for T3/T4)
+ 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.
+ The engine still assembles ONE session bar per symbol-day from the 48
+ CONTINUOUS bars as the day-level gate and summary: open = the 09:35 bar's
+ open, high/low = the session extremes, close = the 15:00 bar's close,
+ volume = their sum. The 09:30 opening-auction print is EXCLUDED (T4: the
+ auction window never matches), and a label inside 09:15-09:25 or from 14:57
+ up to but not including 15:00 is excluded and reported as an
+ ``auction_window`` event (the 15:00 label is a continuous bar). Phase 2
+ matching walks the continuous ``bars_by_symbol`` per bar: a market order
+ fills at the first marketable bar, a limit order rests until a bar satisfies
+ its price and is canceled at session end if none does, and no partial fills
+ or volume share are modeled (Phase 3).
Reproduce (repository root, once the daily ``stk_mins`` quota has reset):
diff --git a/agent/src/tools/paper_trade/engine.py b/agent/src/tools/paper_trade/engine.py
index 61b2541d4..a81f9cfb1 100644
--- a/agent/src/tools/paper_trade/engine.py
+++ b/agent/src/tools/paper_trade/engine.py
@@ -21,12 +21,12 @@ from __future__ import annotations
import datetime as dt
from dataclasses import dataclass, field, replace
from decimal import ROUND_HALF_UP, Decimal
-from typing import Callable, Collection, Mapping
+from typing import Any, Callable, Collection, Mapping
import numpy as np
import pandas as pd
-from . import calendar, corporate_actions, data, state_hash, wire
+from . import calendar, corporate_actions, data, session_5m, state_hash, wire
from .limits_cn_a import (
PROV_LIMITS_HEURISTIC, CnALimitsClient, get_limit_status, heuristic_limit_prices)
from .rules import MarketRules, money, quantize_money
@@ -266,41 +266,36 @@ class _MatchSession:
detail=(f"no 5m session bar for {symbol} on {day.date}; "
+ ("other universe symbols traded" if traded else "no symbol traded"))))
- def match_order(self, day: DayPlan, order: Order) -> None:
- # The AM-14 ladder: first match wins, one reason per order.
+ def _day_gate(self, day: DayPlan, order: Order) -> tuple[str, str] | None:
+ # Slots 1-6 of the frozen AM-14 ladder.
symbol = order.symbol
sym_data = self.market_data.data.get(symbol)
# Slot 1 unknown_symbol: no served data at all in the fetch window.
if sym_data is None or not (sym_data.bar_dates or sym_data.session_bars):
- self._reject(day, order, "unknown_symbol", f"no market data for {symbol} in the fetch window")
- return
+ return ("unknown_symbol", f"no market data for {symbol} in the fetch window")
# Slot 2 non_trading_day: cn_a calendar truth (AM-6).
if day.skip_reason == _SKIP_NON_TRADING:
- self._reject(day, order, "non_trading_day", f"{self.market} calendar closed on {day.date}")
- return
+ return ("non_trading_day", f"{self.market} calendar closed on {day.date}")
# Slot 3 suspended: zero bar today, or an R-V3 untradable bar
# (documented mapping: suspended is the closest frozen code). In 5m
- # mode the session bar is the matched bar, so its absence is the halt.
+ # mode a missing session bar is the day-level halt gate; matching
+ # itself walks the continuous bars in bars_5m.
if self._bar_missing(day.date, sym_data):
detail = (f"no 5m session bar for {symbol} on {day.date}; session halted, position valued carry-forward"
if self._five_minute
else f"no bar for {symbol} on {day.date}; position valued carry-forward")
- self._reject(day, order, "suspended", detail)
- return
+ return ("suspended", detail)
if self._bar_untradable(day.date, sym_data):
- self._reject(day, order, "suspended", f"bar for {symbol} on {day.date} failed the price sanity gate (R-V3)")
- return
+ return ("suspended", f"bar for {symbol} on {day.date} failed the price sanity gate (R-V3)")
# Slot 4 corporate_action_unresolved: T4 detector union + injected seam.
if symbol in self.ca_by_day.get(day.date, ()):
- self._reject(day, order, "corporate_action_unresolved",
- f"unexplained price discontinuity for {symbol} on {day.date}; "
- "fail-closed rejection (no clean split ratio resolved)")
- return
+ return ("corporate_action_unresolved",
+ f"unexplained price discontinuity for {symbol} on {day.date}; "
+ "fail-closed rejection (no clean split ratio resolved)")
# Slot 5 lot_size.
if self.rules.lot_violation(symbol, order.qty):
- self._reject(day, order, "lot_size", f"qty {order.qty} violates the "
- f"{self.rules.lot_size(symbol)}-share lot rule for {symbol}")
- return
+ return ("lot_size", f"qty {order.qty} violates the "
+ f"{self.rules.lot_size(symbol)}-share lot rule for {symbol}")
close = self._close_price(day.date, sym_data)
# Slot 6 limit_up / limit_down: cn_a bands, BEFORE the AM-7 check.
# Price limits are about the official daily close, so 5m mode keeps
@@ -313,16 +308,13 @@ class _MatchSession:
up, down = self._band(symbol, day.date, sym_data)
code = self.rules.band_rejection(order.side, close, up, down)
if code == "limit_up":
- self._reject(day, order, code, f"close {close:.2f} at or above up limit {up:.2f}; buy rejected")
- return
+ return (code, f"close {close:.2f} at or above up limit {up:.2f}; buy rejected")
if code == "limit_down":
- self._reject(day, order, code, f"close {close:.2f} at or below down limit {down:.2f}; sell rejected")
- return
- # 5m: every price decision below uses the session reference price
- # (D1 path model); 1d keeps the daily close byte-identically.
- ref = self._reference_price(day.date, sym_data) if self._five_minute else close
- # Slot 7 limit_not_marketable (AM-7: buy fills only ref ≤ limit,
- # sell only ref ≥ limit; fill price = ref).
+ 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.
if self.rules.limit_order_violation(order.side, ref, order.limit):
anchor = "ref" if self._five_minute else "close"
detail = (
@@ -330,25 +322,36 @@ class _MatchSession:
if order.side == "buy"
else f"{anchor} {ref:.2f} < limit {order.limit:.2f}"
)
- self._reject(day, order, "limit_not_marketable", detail)
- return
+ return ("limit_not_marketable", detail)
+ symbol = order.symbol
# Slots 8/9 t_plus_1 → insufficient_position (disjoint conditions;
# available = total − bought_today, cn_a sells only).
total = self.positions[symbol].qty if symbol in self.positions else _ZERO
bought = self.bought_today.get(symbol, _ZERO)
code = self.rules.sell_position_rejection(order.side, order.qty, total, bought)
if code == "t_plus_1":
- self._reject(day, order, code, f"sell qty {order.qty} exceeds available position "
- f"{total - bought} (T+1: {bought} share(s) bought today are not sellable)")
- return
+ return (code, f"sell qty {order.qty} exceeds available position "
+ f"{total - bought} (T+1: {bought} share(s) bought today are not sellable)")
if code == "insufficient_position":
- self._reject(day, order, code, f"sell qty {order.qty} exceeds position {total}")
- return
+ 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)
if code == "insufficient_cash":
cost = self.rules.buy_cost(order.qty, ref)
- self._reject(day, order, code, f"buy cost {cost} exceeds cash {self.cash}")
+ return (code, f"buy cost {cost} exceeds cash {self.cash}")
+ return None
+
+ def match_order(self, day: DayPlan, order: Order) -> None:
+ # The AM-14 ladder: first match wins, one reason per order.
+ if (gate := self._day_gate(day, order)) is not None:
+ self._reject(day, order, *gate)
+ return
+ sym_data = self.market_data.data[order.symbol]
+ close = self._close_price(day.date, sym_data)
+ ref = self._reference_price(day.date, sym_data) if self._five_minute else close
+ assert ref is not None
+ if (gate := self._fill_gate(day, order, ref)) is not None:
+ self._reject(day, order, *gate)
return
self._fill(day.date, order, ref)
@@ -369,19 +372,24 @@ class _MatchSession:
return None
return float(sym_data.frame.loc[pd.Timestamp(day), "close"])
- def _reference_price(self, day: str, sym_data: data.SymbolData) -> Decimal:
- # D1: the matched bar is the assembled session bar. bar_median is the
- # median of its four prices (two middle values averaged) and bar_close
- # its close; both quantize to the 0.01 money tick so no half-cent or
- # float residue can reach the fill, the notional or the fee.
- bar = sym_data.session_bars[day]
+ def _reference_price_values(self, open_: float, high: float, low: float, close: float) -> Decimal:
+ # D1: bar_median averages the two middle prices; both models quantize
+ # to the 0.01 money tick before the fill, notional or fee arithmetic.
if self.path_model == "bar_close":
- raw = money(bar.close)
+ raw = money(close)
else:
- prices = sorted((money(bar.open), money(bar.high), money(bar.low), money(bar.close)))
+ prices = sorted((money(open_), money(high), money(low), money(close)))
raw = (prices[1] + prices[2]) / Decimal(2)
return quantize_money(raw)
+ def _reference_price(self, day: str, sym_data: data.SymbolData) -> Decimal:
+ bar = sym_data.session_bars[day]
+ return self._reference_price_values(bar.open, bar.high, bar.low, bar.close)
+
+ def _reference_price_from_bar(self, bar: Any) -> Decimal:
+ return self._reference_price_values(
+ float(bar["open"]), float(bar["high"]), float(bar["low"]), float(bar["close"]))
+
def _reject(self, day: DayPlan, order: Order, code: str, detail: str) -> None:
self.rejected.append(
RejectedOrder(trade_date=day.date, symbol=order.symbol, side=order.side,
@@ -629,8 +637,11 @@ def run_day_loop(
orders = (order_provider(entry.date, session.end_state())
if order_provider is not None and entry.skip_reason is None
else orders_by_day.get(entry.date, ()))
- for order in tuple(orders):
- session.match_order(entry, order)
+ if market_data.interval == "5m":
+ session_5m.match_orders_5m(session, entry, tuple(orders))
+ else:
+ for order in tuple(orders):
+ session.match_order(entry, order)
if entry.skip_reason is None:
session.add_nav_row(entry.date) # per-day commit: fills + one nav row
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 d691135ac..90610411e 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). P0 LIMITATION (D1): pt-v1.2 adds NO order-level bar/timestamp field, so an order cannot be attributed to an individual 5m bar; for interval='5m' the whole continuous session is ONE synthetic bar per symbol-day and every order is terminal in it (no cross-bar resting orders, no partial fills). 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, a limit order rests and is canceled at session end if never marketable, 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/session_5m.py b/agent/src/tools/paper_trade/session_5m.py
new file mode 100644
index 000000000..b52d47cbe
--- /dev/null
+++ b/agent/src/tools/paper_trade/session_5m.py
@@ -0,0 +1,113 @@
+"""Per-bar cn_a 5-minute session wiring for the paper-trading engine (#1938 phase 2).
+
+The bar-agnostic :class:`~.order_lifecycle.OrderBook` drives one completed 5m
+session: orders are submitted once for the day, every continuous bar is a
+matching opportunity, and unfilled day orders are canceled at the session
+close. Only ``interval="5m"`` reaches this module; the pt-v1.1 daily path is
+untouched.
+
+Phase-2 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;
+- an order that never fills is canceled by ``settle_day`` at session end (15:00
+ on a complete session);
+- no partial fills and no volume-share model (Phase 3);
+- the daily close still anchors price-limit bands and NAV, and T+1, board
+ lots, fees and corporate-action gates use the same frozen rules as the
+ daily path.
+
+Determinism: the bar timeline comes from the served 5m frame, order ids are
+positional (``pt-<index>``), and no clock or randomness is read.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Sequence
+
+from .order_lifecycle import STATUS_OPEN, OrderBook, OrderRequest, assign_ids
+from .rules import money
+from .schema import CANCELED_REASON_CODE, CanceledOrder, Order
+
+if TYPE_CHECKING:
+ from .engine import DayPlan, _MatchSession
+
+__all__ = ["match_orders_5m"]
+
+
+def _request(order: Order) -> OrderRequest:
+ limit = money(order.limit) if order.limit is not None else None
+ return OrderRequest(
+ symbol=order.symbol,
+ side=order.side,
+ qty=money(order.qty),
+ order_type="limit" if limit is not None else "market",
+ limit_price=limit,
+ )
+
+
+def _cancel_unfilled(
+ session: "_MatchSession", day: "DayPlan", book: OrderBook, by_id: dict[str, Order]
+) -> None:
+ for state in book.settle_day():
+ order = by_id[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",
+ ))
+
+
+def match_orders_5m(session: "_MatchSession", day: "DayPlan", orders: Sequence[Order]) -> None:
+ if not orders:
+ return
+ requests = [_request(order) for order in orders]
+ states = assign_ids(requests)
+ by_id = dict(zip(states, orders, strict=True))
+ book = OrderBook(states)
+
+ active: list[str] = []
+ for order_id, order in by_id.items():
+ gate = session._day_gate(day, order)
+ if gate is not None:
+ book.reject(order_id, gate[0])
+ session._reject(day, order, *gate)
+ continue
+ book.activate(order_id)
+ active.append(order_id)
+
+ for symbol in sorted({by_id[order_id].symbol for order_id in active}):
+ sym_data = session.market_data.data[symbol]
+ bars = sym_data.bars_5m.get(day.date)
+ order_ids = [order_id for order_id in active if by_id[order_id].symbol == symbol]
+ if bars is None or bars.empty:
+ for order_id in order_ids:
+ order = by_id[order_id]
+ book.reject(order_id, "suspended")
+ session._reject(
+ day, order, "suspended",
+ f"no 5m continuous bars for {symbol} on {day.date}")
+ continue
+ for _, bar in bars.sort_index().iterrows():
+ ref = session._reference_price_from_bar(bar)
+ for order_id in order_ids:
+ state = book.get(order_id)
+ if state is None or state.status != STATUS_OPEN:
+ continue
+ order = by_id[order_id]
+ gate = session._fill_gate(day, order, ref)
+ if gate is not None:
+ code, detail = gate
+ if code == "limit_not_marketable":
+ continue
+ book.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))
+
+ _cancel_unfilled(session, day, book, by_id)
diff --git a/agent/tests/paper_trade_5m_fixtures.py b/agent/tests/paper_trade_5m_fixtures.py
index f5464b242..3202b6068 100644
--- a/agent/tests/paper_trade_5m_fixtures.py
+++ b/agent/tests/paper_trade_5m_fixtures.py
@@ -47,12 +47,14 @@ _VOLUME_LOTS_PER_SHARE = 100.0
__all__ = [
"AUCTION_LABEL",
+ "DispersedFirstBarLoader",
"FIXTURE_ROOT",
"FixtureCalendar",
"FixtureLoader",
"continuous_bars",
"derive_daily",
"fixture_files",
+ "fixture_first_bar_reference",
"fixture_manifest",
"fixture_reference",
"fixture_days",
@@ -158,6 +160,17 @@ def fixture_reference(symbol: str, day: str, path_model: str = "bar_median") ->
return raw.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
+def fixture_first_bar_reference(symbol: str, day: str, path_model: str = "bar_median") -> Decimal:
+ """The first continuous 5m bar's reference price (per-bar Phase 2)."""
+ frame = continuous_bars(load_5m(symbol, day))
+ if frame.empty:
+ raise ValueError("no continuous 5m bars to take a first bar from")
+ bar = frame.iloc[0]
+ prices = sorted(Decimal(str(bar[key])) for key in ("open", "high", "low", "close"))
+ raw = prices[3] if path_model == "bar_close" else (prices[1] + prices[2]) / Decimal(2)
+ return raw.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
+
+
def _window(frame: pd.DataFrame, start_date: str, end_date: str, *, end_inclusive: bool):
if frame.empty:
return frame
@@ -212,6 +225,32 @@ class FixtureLoader:
return served
+class DispersedFirstBarLoader(FixtureLoader):
+ """The committed session with a dispersed first continuous bar.
+
+ The real fixtures start flat at 09:35, so ``bar_median`` and ``bar_close``
+ agree there. This loader widens that one bar to 1421.00/1422.00/1421.00/
+ 1422.00 so a test can still distinguish the two path models.
+ """
+
+ def __init__(self, symbol: str, day: str) -> None:
+ super().__init__()
+ self._symbol = symbol
+ self._day = day
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ if str(interval).lower() not in ("5m", "5min", "5"):
+ return super().fetch(codes, start_date, end_date, interval=interval, fields=fields)
+ ordered = tuple(str(code) for code in codes)
+ self.calls.append((ordered, start_date, end_date, str(interval)))
+ if self._symbol not in ordered:
+ return {}
+ frame = load_5m(self._symbol, self._day).copy()
+ first = continuous_bars(frame).index[0]
+ frame.loc[first, ["open", "high", "low", "close"]] = [1421.0, 1422.0, 1421.0, 1422.0]
+ return {self._symbol: frame}
+
+
class FixtureCalendar:
"""The structural ``TradeCalendarClient`` shape; exactly ``open_days`` are open."""
diff --git a/agent/tests/test_paper_trade_5m_engine.py b/agent/tests/test_paper_trade_5m_engine.py
index 94053a2dd..d6616d17c 100644
--- a/agent/tests/test_paper_trade_5m_engine.py
+++ b/agent/tests/test_paper_trade_5m_engine.py
@@ -1,9 +1,10 @@
-"""T3 gate — cn_a 5m reference price, all-or-none fills and emergency cancel.
+"""T3 gate — cn_a per-bar 5m reference, all-or-none fills and day settlement.
-Every order matches ONE assembled session bar (D1: the 48 continuous 5m bars
-of the day, 09:30 opening-auction print excluded). The reference price is
-``bar_median`` (median of open/high/low/close) or ``bar_close``; it drives
-limit marketability, the cash gate, the fill price, the notional and the fee.
+Every continuous 5m bar (09:30 opening-auction print excluded) is a matching
+opportunity. 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.
A failed order keeps its specific pt-v1.1 reason in ``rejected_orders`` AND
gets one ``canceled_after_failed_match`` row in ``canceled_orders`` (D2).
Offline: synthetic frames through a fake loader, never the network.
@@ -80,6 +81,14 @@ def _flat_5m(day: str, price: float) -> pd.DataFrame:
return _intraday(day, {label: price for label in _session_labels(day)}, auction=price)
+def _dispersed_5m(day: str = _DAY) -> pd.DataFrame:
+ labels = _session_labels(day)
+ frame = _intraday(day, {label: 10.20 for label in labels}, auction=10.05)
+ first = pd.Timestamp(f"{day} {labels[0]}")
+ frame.loc[first, ["open", "high", "low", "close"]] = [10.00, 10.20, 10.00, 10.20]
+ return frame
+
+
def _daily(rows: list[tuple[str, float]]) -> pd.DataFrame:
records = [
{"trade_date": day, "open": close, "high": close, "low": close, "close": close, "volume": 1000.0}
@@ -195,78 +204,80 @@ def _sell(limit=None, qty=100, symbol=_SYM):
return order
-def test_market_buy_fills_at_the_session_median() -> None:
- # Session bar o/h/l/c = 10.00/10.20/10.00/10.20 → median 10.10. The 09:30
- # auction print (10.05) is excluded; including it would move the median.
+def test_market_buy_fills_at_the_first_continuous_bar() -> None:
outcome = _outcome(orders=[_buy()])
assert outcome.error is None
- assert [(f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [("buy", 100.0, 10.10, 5.01)]
+ assert [(f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [("buy", 100.0, 10.00, 5.01)]
assert outcome.rejected_orders == ()
assert outcome.canceled_orders == ()
- assert outcome.end_state.cash == 98984.99
- assert outcome.end_state.positions[0].avg_cost == 10.10
+ assert outcome.end_state.cash == 98994.99
+ assert outcome.end_state.positions[0].avg_cost == 10.00
assert outcome.events == ()
- assert outcome.nav_series[0].nav == 100004.99
+ assert outcome.nav_series[0].nav == 100014.99
-def test_market_sell_fills_at_the_session_median() -> None:
+def test_market_sell_fills_at_the_first_continuous_bar() -> None:
outcome = _outcome(orders=[_sell()], positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}])
assert outcome.error is None
- assert [(f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [("sell", 100.0, 10.10, 5.52)]
- assert outcome.end_state.cash == 101004.48
+ assert [(f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [("sell", 100.0, 10.00, 5.51)]
+ assert outcome.end_state.cash == 100994.49
assert outcome.end_state.positions == ()
assert outcome.canceled_orders == ()
[email protected](("limit", "fills"), [(10.50, True), (10.10, True), (10.00, False)])
-def test_buy_limit_marketability_at_the_reference(limit: float, fills: bool) -> None:
[email protected](("limit", "expected"), [(10.50, 10.00), (10.10, 10.00), (10.00, 10.00), (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)])
- if fills:
- assert [(f.side, f.price) for f in outcome.fills] == [("buy", 10.10)]
+ if expected is not None:
+ assert [(f.side, f.price) for f in outcome.fills] == [("buy", expected)]
assert outcome.rejected_orders == ()
+ assert outcome.canceled_orders == ()
return
assert outcome.fills == ()
- assert [r.reason_code for r in outcome.rejected_orders] == ["limit_not_marketable"]
- assert outcome.rejected_orders[0].detail == "ref 10.10 > limit 10.00"
- assert [c.reason_code for c in outcome.canceled_orders] == [CANCELED_REASON_CODE]
+ assert outcome.rejected_orders == ()
+ assert [(c.reason_code, c.detail) for c in outcome.canceled_orders] == [
+ (CANCELED_REASON_CODE, "unfilled day order canceled at session end")
+ ]
[email protected](("limit", "fills"), [(10.00, True), (10.10, True), (10.20, False)])
-def test_sell_limit_marketability_at_the_reference(limit: float, fills: bool) -> None:
[email protected](("limit", "expected"), [(10.00, 10.00), (10.10, 10.20), (10.20, 10.20), (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}])
- if fills:
- assert [(f.side, f.price) for f in outcome.fills] == [("sell", 10.10)]
+ if expected is not None:
+ assert [(f.side, f.price) for f in outcome.fills] == [("sell", expected)]
assert outcome.rejected_orders == ()
+ assert outcome.canceled_orders == ()
return
assert outcome.fills == ()
- assert [r.reason_code for r in outcome.rejected_orders] == ["limit_not_marketable"]
- assert outcome.rejected_orders[0].detail == "ref 10.10 < limit 10.20"
- assert [c.reason_code for c in outcome.canceled_orders] == [CANCELED_REASON_CODE]
+ assert outcome.rejected_orders == ()
+ assert [(c.reason_code, c.detail) for c in outcome.canceled_orders] == [
+ (CANCELED_REASON_CODE, "unfilled day order canceled at session end")
+ ]
def test_path_model_changes_the_reference_and_the_verdict() -> None:
- market_data, _ = _cn_a_data()
+ 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 [f.price for f in median.fills] == [10.10]
assert median.rejected_orders == ()
assert close.fills == ()
- assert [r.reason_code for r in close.rejected_orders] == ["limit_not_marketable"]
- assert close.rejected_orders[0].detail == "ref 10.20 > limit 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 median.engine_fingerprint != close.engine_fingerprint
@pytest.mark.parametrize("path_model", ["bar_median", "bar_close"])
-def test_fill_price_equals_the_reference_under_both_path_models(path_model: str) -> None:
- market_data, _ = _cn_a_data()
- bar = market_data.data[_SYM].session_bar
+def test_fill_price_equals_the_first_bar_reference_under_both_path_models(path_model: str) -> None:
+ market_data, _ = _cn_a_data(five={_SYM: _dispersed_5m()})
expected = 10.20 if path_model == "bar_close" else 10.10
- assert (bar.open, bar.high, bar.low, bar.close) == (10.00, 10.20, 10.00, 10.20)
outcome = _outcome(orders=[_buy(), _buy(qty=200)], market_data=market_data, path_model=path_model, cash=1000000.0)
@@ -282,7 +293,7 @@ def test_insufficient_cash_rejects_and_cancels() -> None:
assert outcome.fills == ()
assert [r.reason_code for r in outcome.rejected_orders] == ["insufficient_cash"]
- assert "1015.01" in outcome.rejected_orders[0].detail
+ assert "1005.01" in outcome.rejected_orders[0].detail
assert len(outcome.canceled_orders) == 1
assert outcome.canceled_orders[0].detail == "rejected: insufficient_cash"
assert outcome.end_state.cash == 500.0
@@ -354,21 +365,22 @@ def test_halted_symbol_rejects_suspended_and_its_position_is_untouched() -> None
def test_every_order_is_terminal_and_every_failure_has_a_reason() -> None:
orders = [
- _buy(), # fills
- _buy(limit=10.00), # limit_not_marketable
- _buy(qty=150), # lot_size
- _buy(symbol="999999.SZ"), # unknown_symbol
- _sell(qty=200), # insufficient_position
+ _buy(),
+ _buy(limit=9.90),
+ _buy(qty=150),
+ _buy(symbol="999999.SZ"),
+ _sell(qty=200),
]
outcome = _outcome(orders=orders, positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}])
- assert len(outcome.fills) + len(outcome.rejected_orders) == len(orders)
+ assert len(outcome.fills) == 1
+ assert len(outcome.rejected_orders) == 3
assert all(r.reason_code in REASON_CODES for r in outcome.rejected_orders)
- assert len(outcome.canceled_orders) == len(outcome.rejected_orders)
+ assert len(outcome.canceled_orders) == 4
assert {c.reason_code for c in outcome.canceled_orders} == {CANCELED_REASON_CODE}
- assert [(c.symbol, c.side, c.qty) for c in outcome.canceled_orders] == [
- (r.symbol, r.side, r.qty) for r in outcome.rejected_orders
- ]
+ day_end = [c for c in outcome.canceled_orders
+ if c.detail == "unfilled day order canceled at session end"]
+ assert [(c.symbol, c.side, c.qty) for c in day_end] == [(_SYM, "buy", 100.0)]
def test_1d_mode_is_unchanged_and_never_cancels_or_events() -> None:
diff --git a/agent/tests/test_paper_trade_5m_golden.py b/agent/tests/test_paper_trade_5m_golden.py
index 674ed3063..74ac11dc8 100644
--- a/agent/tests/test_paper_trade_5m_golden.py
+++ b/agent/tests/test_paper_trade_5m_golden.py
@@ -9,7 +9,7 @@ What this suite pins, all through the stateless tool surface:
every fill fee non-negative;
* every fill price equals the reference recomputed here from the CSV;
* every rejected order carries a frozen reason code and, in 5m mode, exactly
- one emergency-cancel row;
+ one emergency-cancel row; an unfilled limit order gets one day-end cancel;
* a halted session leaves the ledger and the marks alone;
* an auction-window label is excluded from the session bar and reported;
* the fixture manifest indexes every committed file and matches its bytes.
@@ -36,8 +36,8 @@ from tests.paper_trade_5m_fixtures import (
FixtureCalendar,
FixtureLoader,
fixture_files,
+ fixture_first_bar_reference,
fixture_manifest,
- fixture_reference,
load_5m,
)
@@ -106,8 +106,8 @@ def test_two_sessions_have_different_engine_fingerprints() -> None:
_, today = _run(_payload(_DAY))
assert prior["engine_fingerprint"] != today["engine_fingerprint"]
- assert prior["fills"][0]["price"] == 1419.50
- assert today["fills"][0]["price"] == 1421.50
+ assert prior["fills"][0]["price"] == 1419.00
+ assert today["fills"][0]["price"] == 1421.00
def test_cash_and_positions_are_conserved_and_every_fee_is_non_negative() -> None:
@@ -147,7 +147,8 @@ def test_cash_and_positions_are_conserved_and_every_fee_is_non_negative() -> Non
held = {row["symbol"]: _money(row["qty"]) for row in document["end_state"]["positions"]}
assert held == {_SYM: Decimal("200") + bought - sold} == {_SYM: Decimal("400")}
assert [fill["side"] for fill in document["fills"]] == ["buy", "buy", "sell"]
- assert len(document["rejected_orders"]) == 3
+ assert len(document["rejected_orders"]) == 2
+ assert len(document["canceled_orders"]) == 3
def test_every_fill_price_is_the_reference_recomputed_from_the_csv() -> None:
@@ -161,7 +162,7 @@ def test_every_fill_price_is_the_reference_recomputed_from_the_csv() -> None:
],
)
)
- expected = float(fixture_reference(_SYM, _DAY, path_model))
+ expected = float(fixture_first_bar_reference(_SYM, _DAY, path_model))
assert [fill["price"] for fill in document["fills"]] == [expected, expected]
@@ -175,18 +176,18 @@ def test_every_rejection_is_frozen_and_emergency_canceled() -> None:
_, document = _run(_payload(orders=orders))
assert document["fills"] == []
- assert len(document["rejected_orders"]) == len(orders)
+ assert len(document["rejected_orders"]) == 3
assert {row["reason_code"] for row in document["rejected_orders"]} == {
"lot_size",
- "limit_not_marketable",
"insufficient_position",
}
for row in document["rejected_orders"]:
assert row["reason_code"] in REASON_CODES
assert row["reason_code"]
- assert [(row["symbol"], row["side"], row["qty"]) for row in document["canceled_orders"]] == [
- (row["symbol"], row["side"], row["qty"]) for row in document["rejected_orders"]
- ]
+ assert len(document["canceled_orders"]) == len(document["rejected_orders"]) + 1
+ day_end = [row for row in document["canceled_orders"]
+ if row["detail"] == "unfilled day order canceled at session end"]
+ assert [(row["symbol"], row["side"], row["qty"]) for row in day_end] == [(_SYM, "buy", 100.0)]
assert {row["reason_code"] for row in document["canceled_orders"]} == {CANCELED_REASON_CODE}
@@ -249,7 +250,7 @@ def test_auction_window_label_is_excluded_and_reported() -> None:
assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_SYM, "auction_window")]
assert "14:58" in document["events"][0]["detail"]
- assert document["fills"][0]["price"] == clean["fills"][0]["price"] == 1421.50
+ assert document["fills"][0]["price"] == clean["fills"][0]["price"] == 1421.00
def test_manifest_indexes_every_fixture_and_matches_its_bytes() -> None:
diff --git a/agent/tests/test_paper_trade_5m_scope.py b/agent/tests/test_paper_trade_5m_scope.py
index e8c8c68a8..7a8291749 100644
--- a/agent/tests/test_paper_trade_5m_scope.py
+++ b/agent/tests/test_paper_trade_5m_scope.py
@@ -161,7 +161,7 @@ def test_one_5m_order_symbol_issues_exactly_one_provider_call() -> None:
loader = _RateLimitedLoader()
document, _ = _run(_payload(), loader=loader)
- assert [(fill["symbol"], fill["price"]) for fill in document["fills"]] == [(_SYM, 1421.50)]
+ assert [(fill["symbol"], fill["price"]) for fill in document["fills"]] == [(_SYM, 1421.00)]
assert len(loader.five_minute_calls()) == 1
assert loader.five_minute_calls()[0][0] == (_SYM,)
diff --git a/agent/tests/test_paper_trade_5m_strategy.py b/agent/tests/test_paper_trade_5m_strategy.py
index 4895817e3..8a81798df 100644
--- a/agent/tests/test_paper_trade_5m_strategy.py
+++ b/agent/tests/test_paper_trade_5m_strategy.py
@@ -21,7 +21,9 @@ import json
from src.tools.paper_trade.wire import received_state_hash_from_payload
from tests.paper_trade_5m_fixtures import (
+ DispersedFirstBarLoader,
FixtureLoader,
+ _DAY,
_SYM,
_WITNESS,
_install_strategy,
@@ -75,7 +77,7 @@ def test_a_5m_strategy_with_a_universe_fills_and_leaves_an_outside_position_alon
assert "status" not in document
assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [
- (_SYM, "sell", 100.0, 1421.50)
+ (_SYM, "sell", 100.0, 1421.00)
]
assert document["events"] == []
assert document["rejected_orders"] == []
@@ -148,7 +150,7 @@ def test_a_5m_strategy_order_inside_its_universe_still_fills() -> None:
assert "status" not in document
assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [
- (_SYM, "sell", 100.0, 1421.50)
+ (_SYM, "sell", 100.0, 1421.00)
]
assert document["rejected_orders"] == []
assert document["events"] == []
@@ -184,8 +186,14 @@ def test_a_5m_strategy_honours_the_declared_path_model() -> None:
"positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],
}
- median_document, _ = _run(_strategy_payload(path, account_state=account_state, path_model="bar_median"))
- close_document, _ = _run(_strategy_payload(path, account_state=account_state, path_model="bar_close"))
+ median_document, _ = _run(
+ _strategy_payload(path, account_state=account_state, path_model="bar_median"),
+ loader=DispersedFirstBarLoader(_SYM, _DAY),
+ )
+ close_document, _ = _run(
+ _strategy_payload(path, account_state=account_state, path_model="bar_close"),
+ loader=DispersedFirstBarLoader(_SYM, _DAY),
+ )
assert median_document["fills"][0]["price"] == 1421.50
assert close_document["fills"][0]["price"] == 1422.00
diff --git a/agent/tests/test_paper_trade_5m_tool.py b/agent/tests/test_paper_trade_5m_tool.py
index be68d06a7..206216fd4 100644
--- a/agent/tests/test_paper_trade_5m_tool.py
+++ b/agent/tests/test_paper_trade_5m_tool.py
@@ -16,7 +16,7 @@ resolution) live in ``test_paper_trade_5m_scope``; the strategy-mode gates
shared from ``paper_trade_5m_fixtures``.
Every price is re-derived from the committed CSV fixtures by the test (see
-``paper_trade_5m_fixtures.fixture_reference``), so a wrong reference inside
+``paper_trade_5m_fixtures.fixture_first_bar_reference``), so a wrong reference inside
the engine cannot make an assertion agree with it. Offline: no network, no
clock, no writes.
"""
@@ -32,6 +32,7 @@ from src.tools.paper_trade import tool as tool_module
from src.tools.paper_trade.schema import CANCELED_REASON_CODE
from src.tools.paper_trade.tool import PaperTradeDocument, run_paper_trade_step
from tests.paper_trade_5m_fixtures import (
+ DispersedFirstBarLoader,
FixtureCalendar,
FixtureLoader,
_DAY,
@@ -42,7 +43,7 @@ from tests.paper_trade_5m_fixtures import (
_payload,
_run,
derive_daily,
- fixture_reference,
+ fixture_first_bar_reference,
load_5m,
load_5m_all,
session_values,
@@ -54,7 +55,7 @@ _NORMAL_BAR = {"open": 1421.0, "high": 1422.0, "low": 1421.0, "close": 1422.0}
@pytest.mark.parametrize(
("path_model", "expected"),
- [("bar_median", 1421.50), ("bar_close", 1422.00)],
+ [("bar_median", 1421.00), ("bar_close", 1421.00)],
)
def test_normal_day_fills_exactly_at_the_recomputed_reference(path_model: str, expected: float) -> None:
document, _ = _run(_payload(path_model=path_model))
@@ -64,7 +65,7 @@ def test_normal_day_fills_exactly_at_the_recomputed_reference(path_model: str, e
assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [
(_SYM, "buy", 100.0, expected)
]
- assert document["fills"][0]["price"] == float(fixture_reference(_SYM, _DAY, path_model))
+ assert document["fills"][0]["price"] == float(fixture_first_bar_reference(_SYM, _DAY, path_model))
assert document["canceled_orders"] == []
assert document["events"] == []
assert document["rejected_orders"] == []
@@ -73,24 +74,21 @@ def test_normal_day_fills_exactly_at_the_recomputed_reference(path_model: str, e
def test_the_two_path_models_produce_different_prices_and_fingerprints() -> None:
- median, _ = _run(_payload(path_model="bar_median"))
- close, _ = _run(_payload(path_model="bar_close"))
+ median, _ = _run(_payload(path_model="bar_median"), loader=DispersedFirstBarLoader(_SYM, _DAY))
+ close, _ = _run(_payload(path_model="bar_close"), loader=DispersedFirstBarLoader(_SYM, _DAY))
assert median["fills"][0]["price"] == 1421.50
assert close["fills"][0]["price"] == 1422.00
assert median["engine_fingerprint"] != close["engine_fingerprint"]
-def test_non_marketable_limit_is_rejected_and_emergency_canceled() -> None:
+def test_non_marketable_limit_rests_and_is_canceled_at_session_end() -> None:
document, _ = _run(_payload(orders=[{"symbol": _SYM, "side": "buy", "qty": 100, "limit": 1.0}]))
assert document["fills"] == []
- assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [
- (_SYM, "limit_not_marketable")
- ]
- assert document["rejected_orders"][0]["detail"] == "ref 1421.50 > limit 1.00"
- assert [(row["symbol"], row["reason_code"]) for row in document["canceled_orders"]] == [
- (_SYM, CANCELED_REASON_CODE)
+ assert document["rejected_orders"] == []
+ assert [(row["symbol"], row["reason_code"], row["detail"]) for row in document["canceled_orders"]] == [
+ (_SYM, CANCELED_REASON_CODE, "unfilled day order canceled at session end")
]
assert document["events"] == []
@@ -159,7 +157,7 @@ def test_a_v1_2_field_silently_downgraded_to_v1_1_shows_up_only_in_the_hash() ->
assert key not in v11_document
assert v11_document["received_state_hash"] != v12_document["received_state_hash"]
assert v11_document["fills"][0]["price"] == session_values(load_5m(_SYM, _DAY))["close"]
- assert v12_document["fills"][0]["price"] == fixture_reference(_SYM, _DAY, "bar_median")
+ assert v12_document["fills"][0]["price"] == fixture_first_bar_reference(_SYM, _DAY, "bar_median")
def test_fixture_loader_serves_both_legs_and_the_step_issues_one_5m_call() -> None:
diff --git a/schema/tool_contracts/paper_trade_step-v1.2.json b/schema/tool_contracts/paper_trade_step-v1.2.json
index d691135ac..90610411e 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). P0 LIMITATION (D1): pt-v1.2 adds NO order-level bar/timestamp field, so an order cannot be attributed to an individual 5m bar; for interval='5m' the whole continuous session is ONE synthetic bar per symbol-day and every order is terminal in it (no cross-bar resting orders, no partial fills). 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, a limit order rests and is canceled at session end if never marketable, 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",