Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(paper-trade): add the pt-v1.2 cn_a 5-minute post-close step

shadowinlifec6acd2ca4e96
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 2d32ee549..de869da06 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -825,7 +825,7 @@ def backtest(run_dir: str) -> str:
# ---------------------------------------------------------------------------
-# Paper-trading step tool (pt-v1.1, hand-written wrapper)
+# Paper-trading step tool (pt-v1.1/pt-v1.2, VD-12 hand-written wrapper)
# ---------------------------------------------------------------------------
@@ -839,14 +839,18 @@ def paper_trade_step(
orders: _lenient_dict_list_opt = None,
strategy_path: str | None = None,
fee_model: _lenient_dict_any_opt = None,
+ interval: str | None = None,
+ session: str | None = None,
+ path_model: str | None = None,
+ fill_model: str | None = None,
) -> str:
"""Run one step of the deterministic paper-trading matching engine; never places real orders.
- Matches the injected ``orders`` (or a ``strategy_path``'s per-day orders)
- against daily bars under the market's frozen rules (T+1, price limits,
- board lots, fees) and returns ONE in-band JSON document on
- ``result.content[0].text``: the pt-v1.1 success result, or an error
- envelope (``PAPER_DATA_NOT_READY`` retryable / ``INVALID_REQUEST``
+ Matches the injected ``orders`` (or, in Step 7, a ``strategy_path``'s
+ per-day orders) against bars under the market's frozen rules (T+1, price
+ limits, board lots, fees) and returns ONE in-band JSON document on
+ ``result.content[0].text``: the pt-v1.1/pt-v1.2 success result, or an AM-5
+ error envelope (``PAPER_DATA_NOT_READY`` retryable / ``INVALID_REQUEST``
non-retryable) on the SAME channel — never a transport error. Research-only:
it reads market data and the injected ledger, matches on paper, and writes
nothing; no broker or trading-connector order path exists here.
@@ -867,7 +871,15 @@ def paper_trade_step(
per-day orders are matched. Exactly one of ``orders`` /
``strategy_path``.
fee_model: Optional per-key fee overrides merged over the market
- defaults.
+ defaults (AM-4-3: RM always injects it explicitly).
+ interval: Optional pt-v1.2 bar interval — ``1d`` (default) or ``5m``;
+ ``5m`` is cn_a-only.
+ session: Optional pt-v1.2 session selector — ``auto`` (default) or
+ ``cn_a``; ``cn_a`` requires market ``cn_a``.
+ path_model: Optional pt-v1.2 reference-price model — ``bar_median``
+ (default) or ``bar_close``; ignored for ``1d``.
+ fill_model: Optional pt-v1.2 fill model — ``all_or_none`` (default and
+ only P0 value).
"""
from src.tools.paper_trade.tool import run_paper_trade_step
@@ -884,6 +896,14 @@ def paper_trade_step(
payload["strategy_path"] = strategy_path
if fee_model is not None:
payload["fee_model"] = fee_model
+ if interval is not None:
+ payload["interval"] = interval
+ if session is not None:
+ payload["session"] = session
+ if path_model is not None:
+ payload["path_model"] = path_model
+ if fill_model is not None:
+ payload["fill_model"] = fill_model
return run_paper_trade_step(payload)
diff --git a/agent/src/tools/paper_trade/__init__.py b/agent/src/tools/paper_trade/__init__.py
index 14c194ccd..6f88bd28f 100644
--- a/agent/src/tools/paper_trade/__init__.py
+++ b/agent/src/tools/paper_trade/__init__.py
@@ -1,18 +1,28 @@
-"""paper_trade — deterministic paper-trading matching engine (pt-v1.1).
+"""paper_trade — deterministic paper-trading matching engine (pt-v1.1/pt-v1.2).
Research-only engine that matches injected orders (or a strategy's per-day
-orders) against daily bars under each market's frozen rules and returns one
-in-band JSON document. It NEVER places a real order and touches no broker /
+orders) against bars under each market's frozen rules and returns one in-band
+JSON document. It NEVER places a real order and touches no broker /
trading connector (REQUIREMENTS R1).
-Module map: ``schema.py`` (wire contract + boundary parse), ``state_hash.py``
-(JCS ``received_state_hash``), ``calendar.py`` (cn_a CH truth / hk-us zero
-calendar), ``limits_cn_a.py`` (cn_a limit/ST/suspension), ``data.py`` (market
-data supply + AM-9 federation), ``rules.py`` (three-market rule matrix),
+Module map — matching and wire (pt-v1.1 core): ``schema.py`` (wire contract +
+boundary parse), ``state_hash.py`` (JCS ``received_state_hash`` and the D3
+engine fingerprint), ``calendar.py`` (cn_a CH truth / hk-us zero calendar),
+``limits_cn_a.py`` (cn_a limit/ST/suspension), ``data.py`` (market data supply +
+AM-9 federation), ``rules.py`` (three-market rule matrix + ``RULES_VERSION``),
``engine.py`` (day-loop matching), ``corporate_actions.py`` (split detector),
``wire.py`` (success/error serialization), ``tool.py`` (the ``paper_trade_step``
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.
+
+The persistent v1.2 runner/account/store layer (``runner.py``, ``account.py``,
+``store.py``, ``storage_io.py``, ``engine_adapter.py``, ``recovery.py``,
+``trading_days.py``) is a follow-up branch (``paper-trade-v12-persistence``),
+not part of this change: it is not wired to any CLI, API or MCP surface yet.
+
The tool registry's auto-discovery (``src/tools/__init__.py``) imports this
package at agent startup and collects :class:`PaperTradeStepTool` via
``BaseTool.__subclasses__()`` (VD-12). Consumers import submodules explicitly
diff --git a/agent/src/tools/paper_trade/calendar.py b/agent/src/tools/paper_trade/calendar.py
index 70e695657..d34c07b3b 100644
--- a/agent/src/tools/paper_trade/calendar.py
+++ b/agent/src/tools/paper_trade/calendar.py
@@ -37,13 +37,26 @@ if TYPE_CHECKING:
__all__ = [
"CN_A_MARKET",
+ "CN_A_AUCTION_WINDOWS",
+ "CN_A_CONTINUOUS_WINDOWS",
+ "CN_A_SESSION_TIMEZONE",
+ "CLOSING_AUCTION",
+ "CONTINUOUS_AFTERNOON",
+ "CONTINUOUS_MORNING",
"HK_MARKET",
+ "OPENING_AUCTION",
+ "OPENING_AUCTION_PRINT",
+ "SESSION_AUCTION_WINDOW",
+ "SESSION_CONTINUOUS",
+ "SESSION_OPENING_AUCTION_PRINT",
+ "SESSION_OUTSIDE",
"US_MARKET",
"VERDICT_MARKET_CLOSED_INFERRED",
"VERDICT_NOT_READY",
"VERDICT_TRADING_DAY",
"TradeCalendarClient",
"ZeroCalendarDayVerdict",
+ "classify_cn_a_session_label",
"classify_zero_calendar_day",
"hk_us_candidate_days",
"is_trading_day",
@@ -54,6 +67,77 @@ CN_A_MARKET = "cn_a"
HK_MARKET = "hk"
US_MARKET = "us"
+# ── cn_a session clock (T4) ──
+#
+# Fixed Asia/Shanghai (UTC+08:00, no DST): mainland China observes no daylight
+# saving, so a fixed offset is exact and no tz database lookup is needed at
+# import. Labels are bar ENDS (T1, data_5m.py): the first continuous bar ends
+# at 09:35 and the last at 11:30 / 15:00.
+CN_A_SESSION_TIMEZONE = "Asia/Shanghai"
+
+#: Continuous call-auction (撮合) windows, half-open at the opening edge:
+#: a bar label t trades continuously when ``start < t <= end``.
+CONTINUOUS_MORNING = ("09:30", "11:30")
+CONTINUOUS_AFTERNOON = ("13:00", "15:00")
+
+#: Opening call auction 09:15-09:25 and closing call auction 14:57-15:00
+#: (``14:57 <= label < 15:00``; the 15:00 label is a continuous bar).
+#: Neither auction window is matched (T4 "竞价段不撮合").
+OPENING_AUCTION = ("09:15", "09:25")
+CLOSING_AUCTION = ("14:57", "15:00")
+
+CN_A_CONTINUOUS_WINDOWS = (CONTINUOUS_MORNING, CONTINUOUS_AFTERNOON)
+CN_A_AUCTION_WINDOWS = (OPENING_AUCTION, CLOSING_AUCTION)
+
+#: Continuous 5-minute bars in one cn_a session pair, measured by T1
+#: (data_5m.CONTINUOUS_BARS_PER_DAY): 09:35..11:30 and 13:05..15:00.
+CONTINUOUS_BARS_PER_DAY = 48
+
+#: The single expected opening-auction print label (T1: 49 raw rows/day; this
+#: row is single-priced and equals the daily open). It is excluded from the
+#: session bar but is NOT an anomaly, so it raises no event.
+OPENING_AUCTION_PRINT = "09:30"
+
+# ``classify_cn_a_session_label`` verdicts.
+SESSION_CONTINUOUS = "continuous"
+SESSION_OPENING_AUCTION_PRINT = "opening_auction_print"
+SESSION_AUCTION_WINDOW = "auction_window"
+SESSION_OUTSIDE = "outside"
+
+
+def classify_cn_a_session_label(label: str) -> str:
+ """Classify one ``HH:MM`` bar label against the cn_a session clock (T4).
+
+ Returns one of :data:`SESSION_CONTINUOUS`,
+ :data:`SESSION_OPENING_AUCTION_PRINT`, :data:`SESSION_AUCTION_WINDOW` or
+ :data:`SESSION_OUTSIDE`.
+
+ * ``09:30`` is the opening call-auction print, single-priced on 4 of 5
+ probed days (data_5m.py T1): expected, excluded from the session bar by
+ policy, never an event.
+ * A label inside the opening auction (09:15-09:25 inclusive, because no
+ continuous label lives there) or inside the closing auction
+ (14:57 <= t < 15:00; 15:00 itself is the real closing bar per T1) is an
+ auction-window anomaly: excluded from matching AND reported as an
+ ``auction_window`` event.
+ * Continuous windows are half-open at the start (``09:30 < t <= 11:30``,
+ ``13:00 < t <= 15:00``), so 09:35..11:30 and 13:05..15:00 are continuous
+ and 13:00 / the lunch labels are not.
+ * Anything else (lunch, pre-open, post-close) is outside: excluded with a
+ warning, never matched.
+ """
+ if not isinstance(label, str) or len(label) != 5 or label[2] != ":":
+ raise ValueError(f"bar label must be HH:MM, got {label!r}")
+ if label == OPENING_AUCTION_PRINT:
+ return SESSION_OPENING_AUCTION_PRINT
+ if OPENING_AUCTION[0] <= label <= OPENING_AUCTION[1]:
+ return SESSION_AUCTION_WINDOW
+ if CLOSING_AUCTION[0] <= label < CLOSING_AUCTION[1]:
+ return SESSION_AUCTION_WINDOW
+ if any(start < label <= end for start, end in CN_A_CONTINUOUS_WINDOWS):
+ return SESSION_CONTINUOUS
+ return SESSION_OUTSIDE
+
_CALENDAR_MARKETS = (CN_A_MARKET, HK_MARKET, US_MARKET)
# AM-6 (APPROVED, G1 open 2026-10-19): hk/us are ZERO-CALENDAR markets —
diff --git a/agent/src/tools/paper_trade/data.py b/agent/src/tools/paper_trade/data.py
index 4d9368957..fb04303ac 100644
--- a/agent/src/tools/paper_trade/data.py
+++ b/agent/src/tools/paper_trade/data.py
@@ -34,21 +34,56 @@ Determinism (R1-1): NO clock is read — every date is injected, so the CH UTC
vs host CST 8h skew cannot leak into verdicts. Zero side effects: no file
writes, network only to market-data sources; CH credentials come solely from
the existing ``CLICKHOUSE_*`` env config (zero-credential red line).
+
+pt-v1.2 ``interval="5m"`` (T3/T4): the DAILY leg above is fetched unchanged
+(K=120 lookback, valuation, price-limit bands, corporate actions) and exactly
+ONE extra ranged 5m call covers the ORDER symbols — never one call per day and
+never one call per position (T1: the provider allows 2 stk_mins calls/day, the
+Tushare loader loops per code, and a refused call still burns the budget, so a
+whole-universe request makes any two-symbol account unadvanceable). The 5m
+request end is ``to_date + 1 day`` because the provider's end
+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
+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
+provider returned no row for it at all, and is reported as
+``PAPER_DATA_NOT_READY`` naming it — a provider error must never be read as
+a halt. A symbol whose only 5m row is the 09:30 opening-auction print is a
+halt candidate instead: the provider served the symbol, the exchange simply
+had no continuous session (N3). Unsupported instruments (ETFs, funds,
+indices) are rejected by the tool before the fetch
+(``data_5m.is_supported_five_minute_symbol``).
"""
from __future__ import annotations
import datetime as dt
import logging
+import math
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Mapping, Protocol
+from typing import TYPE_CHECKING, Any, Iterable, Mapping, Protocol
import numpy as np
import pandas as pd
from backtest.loaders.registry import frame_caliber, resolve_loader
-from .schema import DataProvenance
+from . import state_hash
+from .data_5m import FiveMinuteFacts, SessionBar, fetch_five_minute
+from .data_readiness import (
+ NOT_READY_CODE, # noqa: F401 — re-exported for callers that import it here
+ ReadinessVerdict,
+ _assess_five_minute_readiness, # noqa: F401 — re-exported for existing callers
+ _normalize_day,
+ assess_readiness,
+ day_bar_availability,
+)
+from .schema import DEFAULT_INTERVAL, INTERVALS, DataProvenance
if TYPE_CHECKING:
from .schema import AccountState, Order
@@ -63,6 +98,7 @@ __all__ = [
"CnABarsClient",
"MarketDataResult",
"ReadinessVerdict",
+ "SessionBar",
"SymbolData",
"assess_readiness",
"day_bar_availability",
@@ -88,13 +124,15 @@ LOOKBACK_CALENDAR_SPAN_DAYS = 200
OHLCV_COLUMNS: tuple[str, ...] = ("open", "high", "low", "close", "volume")
_PRICE_COLUMNS: tuple[str, ...] = ("open", "high", "low", "close")
-#: Frozen in-band envelope code (schema.ERROR_CODES member) for target-day
-#: all-market zero bar (AM-5/AM-9).
-NOT_READY_CODE = "PAPER_DATA_NOT_READY"
-
_CN_A_MARKET = "cn_a"
_CLICKHOUSE_LOADER_NAME = "clickhouse"
+#: The only loader with a measured ``stk_mins`` leg. The a_share daily chain
+#: head (tencent) is wrapped as ``TencentRawLoader``, which refuses every
+#: interval but ``1D`` — sharing that instance would make every 5m step a
+#: permanent data-not-ready. The 5m leg therefore resolves its own loader.
+_FIVE_MINUTE_LOADER_NAME = "tushare"
+
# Sentinel distinguishing "not injected" from an explicit None.
_AUTO = object()
@@ -126,10 +164,6 @@ def _canonical_frame(frame: pd.DataFrame | None) -> pd.DataFrame:
return df[~df.index.duplicated(keep="last")].sort_index()
-def _normalize_day(value: str) -> str:
- return dt.date.fromisoformat(str(value).strip()).isoformat()
-
-
def _max_as_of(frames: Mapping[str, pd.DataFrame]) -> str | None:
stamps = [
pd.Timestamp(f.index.max()).strftime("%Y-%m-%d")
@@ -300,10 +334,29 @@ class SymbolData:
untradable_dates: tuple[str, ...] = () # R-V3 flagged dates, ascending
valuation_price: float | None = None # None ⇒ value at avg_cost
valuation_basis: str = "last_close"
+ #: Day -> continuous 5m bars (empty for interval="1d"); for a single-day
+ #: orders-mode step this is exactly the target day's continuous bars.
+ bars_5m: Mapping[str, pd.DataFrame] = field(default_factory=dict)
+ #: Day -> assembled session bar (the D1 matched bar), interval="5m" only.
+ session_bars: Mapping[str, SessionBar] = field(default_factory=dict)
+ #: The TARGET day's session bar (``to_date``), or None when it has none.
+ session_bar: SessionBar | None = None
+ #: Day -> auction-window labels excluded from matching (T4 events).
+ auction_labels: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
+ #: Days with at least one 5m row of ANY kind, the 09:30 opening-auction
+ #: print included. Distinguishes a halt (rows, no continuous bar) from a
+ #: provider omission (no row at all) — N3.
+ five_minute_days: frozenset[str] = frozenset()
def has_bar(self, day: str) -> bool:
return day in self.bar_dates
+ def has_session_bar(self, day: str) -> bool:
+ return day in self.session_bars
+
+ def has_five_minute_rows(self, day: str) -> bool:
+ return day in self.five_minute_days
+
@dataclass(frozen=True, eq=False)
class MarketDataResult:
@@ -317,16 +370,28 @@ class MarketDataResult:
data: Mapping[str, SymbolData] = field(default_factory=dict)
provenance: DataProvenance = field(default_factory=lambda: DataProvenance(source=""))
warnings: tuple[str, ...] = ()
-
-
-@dataclass(frozen=True, slots=True)
-class ReadinessVerdict:
- """Target-day readiness (AM-9). ``ready=False`` carries the frozen in-band
- envelope material (AM-5) — this layer never raises for data-not-ready."""
-
- ready: bool
- code: str | None = None
- message: str | None = None
+ #: "1d" (frozen pt-v1.1 path) or "5m" (pt-v1.2 cn_a session path).
+ interval: str = DEFAULT_INTERVAL
+ #: D3 bar fingerprint over the bars actually served: the continuous 5m
+ #: bars when a 5m step orders symbols, the day bars otherwise (a
+ #: pure-valuation 5m step issues no 5m request and is valued on them).
+ bar_fingerprint: str = ""
+ #: Day -> symbols whose daily bar and 5m session bar disagree on whether
+ #: the symbol traded (a provider fault, never a halt: D6 fail-closed).
+ five_minute_contradiction: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
+ #: Symbols the 5m leg covers — the ORDER symbols in orders mode (the daily
+ #: leg values positions), the declared universe in strategy mode. Empty
+ #: for a pure-valuation step, which issues no 5m request at all.
+ five_minute_symbols: tuple[str, ...] = ()
+ #: Why the 5m leg produced no data when the cause is the LOADER (none
+ #: available, or the fetch raised), never when the provider simply omitted
+ #: a halted day. Readiness surfaces this verbatim instead of blaming the
+ #: provider's quota for a source that cannot serve 5m at all.
+ five_minute_error: str = ""
+ #: Loader that served the 5m leg (empty when no 5m request was made). It
+ #: stays OFF the wire so the frozen response shape is unchanged; a future
+ #: persistent runner can record it in its step audit trail.
+ five_minute_source: str = ""
def symbols_for_request(
@@ -340,6 +405,25 @@ def symbols_for_request(
return tuple(sorted(universe))
+def _resolve_five_minute_loader(loader: Any) -> Any | None:
+ """Return the loader that serves ``interval="5m"``, or ``None`` when none can.
+
+ An injected loader is honoured verbatim — tests and embedders own their
+ source, and substituting another one would hide the failure. Only the
+ ``_AUTO`` sentinel resolves the Tushare ``stk_mins`` loader; the daily
+ chain is deliberately never consulted for 5m.
+ """
+ if loader is not _AUTO:
+ return loader
+ try:
+ from backtest.loaders.tushare import DataLoader
+
+ candidate = DataLoader()
+ return candidate if candidate.is_available() else None
+ except Exception: # noqa: BLE001 — an unavailable 5m source is data-not-ready
+ return None
+
+
def fetch_market_data(
market: str,
symbols: Any,
@@ -348,21 +432,41 @@ def fetch_market_data(
*,
loader: Any = _AUTO,
ch_client: Any = _AUTO,
+ interval: str = DEFAULT_INTERVAL,
+ five_minute_symbols: Iterable[str] | None = None,
) -> MarketDataResult:
"""Fetch the frozen window for every symbol; assemble merged provenance.
``loader`` injects the network leg (cn_a: clickhouse-named loaders are
refused — recursion guard; hk/us: the single leg); ``ch_client`` injects
- the cn_a CH leg (``None`` forces network-only). ValueError for an unknown
- market, bad dates or a clickhouse injection → in-band INVALID_REQUEST (T6).
+ the cn_a CH leg (``None`` forces network-only). ``interval="1d"`` is the
+ frozen pt-v1.1 path and never issues a 5m request; ``interval="5m"`` keeps
+ the daily leg (K=120 lookback, valuation, limits, corporate actions) and
+ adds exactly ONE ranged 5m fetch (T1 quota: the provider allows 2 calls/day,
+ so a per-day loop is forbidden, and the Tushare loader loops per symbol —
+ a whole-universe request would burn the budget on the first account with
+ two names). ``five_minute_symbols`` therefore narrows that ONE request to
+ the symbols whose session bar is actually matched (orders mode: the order
+ symbols); ``None`` keeps the legacy whole-universe request. ValueError
+ for an unknown market, bad dates, an unknown interval, a non-cn_a 5m
+ request or a clickhouse injection → in-band INVALID_REQUEST (T6).
"""
if market not in MARKET_LOADER_KEYS:
raise ValueError(f"unknown market for paper data fetch: {market!r}")
+ if interval not in INTERVALS:
+ raise ValueError(f"unknown interval for paper data fetch: {interval!r}")
+ if interval == "5m" and market != _CN_A_MARKET:
+ raise ValueError("interval '5m' is cn_a-only in pt-v1.2")
start = _normalize_day(from_date)
end = _normalize_day(to_date)
if start > end:
raise ValueError(f"from_date ({start}) > to_date ({end})")
ordered = tuple(sorted({str(symbol) for symbol in symbols}))
+ ordered_five = (
+ ordered
+ if five_minute_symbols is None
+ else tuple(dict.fromkeys(str(symbol) for symbol in five_minute_symbols))
+ )
window_start = (
dt.date.fromisoformat(start) - dt.timedelta(days=LOOKBACK_CALENDAR_SPAN_DAYS)
).isoformat()
@@ -377,6 +481,29 @@ def fetch_market_data(
market, ordered, window_start, end, loader=loader, warnings=warnings
)
+ five = FiveMinuteFacts()
+ five_minute_error = ""
+ five_minute_source = ""
+ if interval == "5m" and ordered_five:
+ five_loader = _resolve_five_minute_loader(loader)
+ if five_loader is None:
+ five_minute_error = (
+ "5m data: no available 5m loader; interval 5m requires the Tushare "
+ "stk_mins source (daily sources such as tencent serve 1D only)")
+ warnings.append(five_minute_error)
+ five = FiveMinuteFacts(
+ bar_fingerprint=state_hash.state_hash([]), fetch_failed=True,
+ missing_symbols=ordered_five)
+ else:
+ five = fetch_five_minute(
+ ordered_five, start, end, loader=five_loader, warnings=warnings)
+ five_minute_source = str(getattr(five_loader, "name", ""))
+ if five.fetch_failed:
+ five_minute_error = five.failure_reason or (
+ "5m data: the 5m fetch through "
+ f"{getattr(five_loader, 'name', 'the loader')!r} failed; "
+ "the step is data-not-ready, retry later")
+
data: dict[str, SymbolData] = {}
for symbol in ordered:
frame = _trim_window(frames.get(symbol, _empty_frame()), start, end)
@@ -389,17 +516,132 @@ def fetch_market_data(
)
if needs_warning:
warnings.append(f"valuation: {symbol} has no usable positive close in the fetch window; positions value at avg_cost")
+ bars_5m, session_bars = five.for_symbol(symbol)
data[symbol] = SymbolData(
symbol=symbol, frame=frame,
bar_dates=frozenset(day.strftime("%Y-%m-%d") for day in frame.index),
untradable_dates=untradable, valuation_price=price, valuation_basis=basis,
+ bars_5m=bars_5m, session_bars=session_bars,
+ session_bar=session_bars.get(end),
+ auction_labels=five.auction_by_symbol.get(symbol, {}),
+ five_minute_days=frozenset(five.observed_days_by_symbol.get(symbol, ())),
)
+
+ omitted_5m = tuple(
+ symbol for symbol in five.missing_symbols
+ if symbol in data and data[symbol].has_bar(end)
+ )
+ if omitted_5m:
+ warnings.append(
+ f"5m data: provider omitted the 5m leg for {', '.join(omitted_5m)} even though the "
+ "daily bar exists; stk_mins quota or permission likely; retry after the quota window")
+
+ # D3 covers the bars that actually produced this step's output. With 5m
+ # order symbols that is the continuous 5m leg; a pure-valuation 5m step
+ # issues no 5m request at all, so its NAV comes from the daily leg and the
+ # daily digest is the honest one (otherwise every such step shares the
+ # empty-tape hash and the fingerprint cannot tell two days apart).
+ bar_fingerprint = (
+ five.bar_fingerprint if interval == "5m" and ordered_five
+ else _daily_bar_fingerprint(data, ordered, start, end)
+ )
return MarketDataResult(
market=market, from_date=start, to_date=end, symbols=ordered,
data=data, provenance=provenance, warnings=tuple(warnings),
+ interval=interval, bar_fingerprint=bar_fingerprint,
+ five_minute_contradiction=_five_minute_contradictions(
+ data, ordered_five, start, end, interval, five),
+ five_minute_symbols=ordered_five,
+ five_minute_error=five_minute_error,
+ five_minute_source=five_minute_source,
+ )
+
+
+def _days_in_range(from_date: str, to_date: str) -> tuple[str, ...]:
+ start = dt.date.fromisoformat(from_date)
+ end = dt.date.fromisoformat(to_date)
+ return tuple(
+ (start + dt.timedelta(days=offset)).isoformat()
+ for offset in range((end - start).days + 1)
)
+def _finite_float(value: Any) -> float:
+ numeric = float(value)
+ return numeric if math.isfinite(numeric) else 0.0
+
+
+def _daily_bar_fingerprint(
+ data: Mapping[str, SymbolData],
+ symbols: tuple[str, ...],
+ from_date: str,
+ to_date: str,
+) -> str:
+ # D3 for interval="1d": the day bars actually served in [from, to], sorted
+ # by (symbol, date) so input order cannot change the digest. Rows are
+ # [symbol, "YYYY-MM-DD", open, high, low, close, volume] with finite
+ # floats (a non-finite cell, e.g. a missing volume, canonicalizes as 0.0
+ # instead of raising inside the JCS serializer).
+ start = pd.Timestamp(from_date)
+ end = pd.Timestamp(to_date)
+ payload: list[list[Any]] = []
+ for symbol in sorted(symbols):
+ sym_data = data.get(symbol)
+ if sym_data is None or sym_data.frame.empty:
+ continue
+ window = sym_data.frame[(sym_data.frame.index >= start) & (sym_data.frame.index <= end)]
+ for timestamp, row in window.iterrows():
+ payload.append([
+ symbol, timestamp.strftime("%Y-%m-%d"),
+ _finite_float(row["open"]), _finite_float(row["high"]),
+ _finite_float(row["low"]), _finite_float(row["close"]),
+ _finite_float(row["volume"]),
+ ])
+ return state_hash.state_hash(payload)
+
+
+def _five_minute_leg_mismatch(sym_data: SymbolData, day: str) -> bool:
+ """True when the daily and 5m legs disagree in a way a halt cannot explain.
+
+ A daily bar with no continuous 5m bar is a provider omission only when the
+ symbol produced NO 5m row that day. A symbol the provider DID serve (even
+ just the 09:30 opening-auction print) is a halt candidate: the exchange had
+ no continuous session, the provider did not fail (N3). A session bar with
+ no daily bar is a mismatch in both directions.
+ """
+ has_daily = sym_data.has_bar(day)
+ has_session = sym_data.has_session_bar(day)
+ if has_daily == has_session:
+ return False
+ return has_session or not sym_data.has_five_minute_rows(day)
+
+
+def _five_minute_contradictions(
+ data: Mapping[str, SymbolData],
+ symbols: tuple[str, ...],
+ from_date: str,
+ to_date: str,
+ interval: str,
+ five: FiveMinuteFacts,
+) -> dict[str, tuple[str, ...]]:
+ # A daily bar with no 5m session bar (or the reverse) cannot be a halt when
+ # the provider served no 5m row at all for that symbol: Tushare omits
+ # suspended days from BOTH endpoints. It is a provider / federation fault,
+ # so the day fails closed as data-not-ready rather than reading a provider
+ # error as "halted" (D6).
+ if interval != "5m" or five.fetch_failed or not symbols:
+ return {}
+ contradictions: dict[str, tuple[str, ...]] = {}
+ for day in _days_in_range(from_date, to_date):
+ mismatched = tuple(sorted(
+ symbol for symbol in symbols
+ if symbol in data and _five_minute_leg_mismatch(data[symbol], day)
+ ))
+ if mismatched:
+ contradictions[day] = mismatched
+ return contradictions
+
+
def _fetch_cn_a(
symbols: tuple[str, ...],
window_start: str,
@@ -496,32 +738,3 @@ def _fetch_single_leg(
network_as_of=as_of,
)
return frames, provenance
-
-
-def assess_readiness(result: MarketDataResult, target_day: str) -> ReadinessVerdict:
- """Target-day readiness on the merged frame (AM-9), never on a leg alone.
-
- Ready when ANY served symbol carries the target-day bar (single-symbol
- absence is a suspended fact for the engine, AM-6③); all-market zero bar →
- the frozen PAPER_DATA_NOT_READY material (message follows the R1-4 example
- shape; deterministic English, no timestamps — VD-7). An empty universe is
- vacuously ready.
- """
- day = _normalize_day(target_day)
- if result.symbols and not any(
- result.data[symbol].has_bar(day) for symbol in result.symbols
- ):
- ends = result.provenance.bars_as_of or "empty"
- message = f"target bar {day} not available from served sources ({result.provenance.source} frame ends {ends})"
- return ReadinessVerdict(ready=False, code=NOT_READY_CODE, message=message)
- return ReadinessVerdict(ready=True)
-
-
-def day_bar_availability(result: MarketDataResult, dates: Any) -> dict[str, tuple[str, ...]]:
- # Per-day sorted tuple of symbols WITH a bar — the AM-6 matrix input
- # (dates: iterable of YYYY-MM-DD, e.g. hk_us_candidate_days output).
- availability: dict[str, tuple[str, ...]] = {}
- for raw in dates:
- day = _normalize_day(raw)
- availability[day] = tuple(s for s in result.symbols if result.data[s].has_bar(day))
- return availability
diff --git a/agent/src/tools/paper_trade/data_5m.py b/agent/src/tools/paper_trade/data_5m.py
new file mode 100644
index 000000000..ba7eb3b44
--- /dev/null
+++ b/agent/src/tools/paper_trade/data_5m.py
@@ -0,0 +1,603 @@
+"""Measured semantics of Tushare ``stk_mins`` 5-minute bars for cn_a equities (T1).
+
+Frozen data proof for the 5m paper-trade engine (T2-T6). Everything under
+VERIFIED was read from the live ``stk_mins`` endpoint through the production
+loader path ``backtest.loaders.tushare.DataLoader.fetch(..., interval="5m")``.
+
+PROBE A (executed 2026-10-21 07:44 CST, one provider call)
+ ``600519.SH``, 2026-10-13..2026-10-20 -> 245 rows over 5 trading days.
+
+VERIFIED — bar count and labels
+ * 49 raw rows per trading day. First label 09:30:00, last 15:00:00 on
+ every one of the five days.
+ * The 09:30 row is the opening call-auction snapshot, not a continuous
+ bar: on 10-13/14/15/16 its OHLC is one price (1287.00 / 1270.10 /
+ 1286.00 / 1311.57) and equals that day's ``api.daily`` open.
+ * Dropping the 09:30 label leaves exactly 48 continuous bars per day.
+ The planbook's "48 five-minute bars" are the CONTINUOUS bars only.
+ * 2026-10-17/18 (weekend, ``api.trade_cal`` is_open=0) returned 0 rows.
+ * ``end_date`` is exclusive at midnight: fetching 2026-10-13..2026-10-20
+ returned 10-13..10-19 only, although ``daily()`` already had 10-20.
+ To read day D, pass an end date later than D.
+
+VERIFIED — a label is the bar's END, not its start
+ * The 15:00 row is a real 5-minute bar, not a closing-auction print: all
+ five days carry a multi-tick range (10-19: O1323.73 H1325.18 L1323.04
+ C1324.97). An SSE closing call auction clears at ONE price, so an
+ auction-snapshot row would be single-priced; the observed ranges rule
+ that reading out.
+ * The 09:30 row is single-priced on 4/5 days (the opening auction). Under
+ a bar-start convention it would be a full 5-minute continuous bar with
+ zero price movement on 20k+ shares — not credible for a 1287 CNY stock.
+ * Count arithmetic: a 5-minute grid from 09:30 to 15:00 holds 67 labels;
+ only 49 exist, so 18 slots (90 minutes) are skipped — exactly the
+ 11:30-13:00 lunch break. No bar spans the break.
+ * Therefore: 09:35 covers 09:30-09:35, 11:30 covers 11:25-11:30, 13:05
+ covers 13:00-13:05, 15:00 covers 14:55-15:00. Session code must read
+ label 11:30 as the morning close and 15:00 as the day close, and must
+ never expect a 13:00 bar.
+
+VERIFIED — adjustment caliber
+ * The 5m close equals the RAW ``api.daily`` close AND the loader's qfq
+ close on all five days (1274.89 / 1286.00 / 1312.97 / 1329.00 /
+ 1324.97); the first 5m open equals the daily open (the auction print).
+ * ``api.adj_factor`` is constant over the window (600519: 8.6463;
+ 603517: 1.5997), so qfq == raw on these days. This probe therefore
+ cannot distinguish "raw" from "qfq": what is proven is that the 5m
+ frame and the daily frame agree exactly while the factor is constant.
+ * Engine rule: never compare a 5m price with a daily qfq price across an
+ ex-date without an explicit factor. Anchor on the RAW daily series, or
+ scale one leg by ``adj_factor`` on the same day.
+
+VERIFIED — the 5m volume unit differs from the daily frame
+ * 5m ``volume`` is in SHARES; the daily loader's ``volume`` is in LOTS
+ (``TushareLoader.volume_units == {"a_share": "lots"}``).
+ * Proof: 600519 10-13 daily volume is 26,572.76 lots = 2,657,276 shares,
+ while that day's 15:00 bar alone reports 154,400. In lots that would be
+ 15.4M shares = 581% of the whole day; only shares fit.
+ * Engine rule: divide 5m volume by 100 (or multiply the daily volume by
+ 100) before any comparison.
+
+VERIFIED — provider limits observed on this token
+ * ``stk_mins`` is capped at 1 call/minute, 1 call/hour AND 2 calls/day.
+ A refused request still consumes the daily budget (the cap was hit
+ after a single successful call plus two refusals).
+ * The daily budget resets at 00:00 Asia/Shanghai.
+
+NOT MEASURED — blocked by that 2-calls/day cap; do not present as fact
+ * The explicit 11:30 / 13:05 rows. The bar-end conclusion above is
+ derived from the row count, the 09:30 and 15:00 rows, and session
+ arithmetic — not from printing those two labels.
+ * A suspended symbol-day's 5m response. A real sample is prepared:
+ 603517.SH is suspended on 2026-10-19 (``api.suspend_d`` type S, and no
+ ``daily()`` bar that day) while 10-16 and 10-20 traded. Running the
+ command below on a fresh quota probes exactly that window; expect 0
+ rows on 10-19. Until then, 5m rows with no continuous session (or a
+ zero-volume session) are reported as ``halted``, never as fabricated or
+ 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.
+
+Reproduce (repository root, once the daily ``stk_mins`` quota has reset):
+
+ PYTHONPATH=agent conda run -n legonanobot python -m src.tools.paper_trade.data_5m
+
+It prints the per-day label lists, the lunch boundary, the auction row, and
+the 48 continuous rows of the first probed day as CSV. Pass
+``<code> <start> <end>`` to probe another window.
+
+Run it as a module, not as a file: this directory contains ``calendar.py``,
+which would shadow the stdlib ``calendar`` module that pandas imports when
+the script's own directory is first on ``sys.path``.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+import math
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Mapping
+
+import pandas as pd
+
+from . import calendar, state_hash
+
+#: ``agent/`` — the import root the loader package expects (``backtest.*``).
+AGENT_DIR = Path(__file__).resolve().parents[3]
+
+#: Label of the opening call-auction row. It is NOT a continuous 5-minute bar.
+AUCTION_LABEL = "09:30"
+
+#: Continuous 5-minute bars in one cn_a session pair (09:30-11:30, 13:00-15:00).
+#: Hard cap on the symbols ONE 5m step may request. ``stk_mins`` is measured
+#: at 1 call/minute and 1/hour, 2/day; the loader is per-code, so a second
+#: symbol in the SAME step is rate-limited immediately — and the refused call
+#: still burns the 2/day budget, so a 2-symbol step can never complete (not
+#: even on a retry). P0 constant, re-measure before raising.
+MAX_FIVE_MINUTE_SYMBOLS = 1
+
+#: Default probe: a normal day (10-16), a suspended day (10-19) and a resumed
+#: day (10-20) in one ranged call, so one unit of the daily quota answers both
+#: the session-shape and the suspended-day questions.
+DEFAULT_CODE = "603517.SH"
+DEFAULT_START = "2026-10-16"
+DEFAULT_END = "2026-10-21"
+
+_LUNCH_START = "11:20"
+_LUNCH_END = "13:15"
+
+_OHLCV_COLUMNS: tuple[str, ...] = ("open", "high", "low", "close", "volume")
+_PRICE_COLUMNS: tuple[str, ...] = ("open", "high", "low", "close")
+
+#: cn_a exchange suffixes whose 5-minute (``stk_mins``) leg serves ordinary
+#: stocks. ETFs/LOFs, indices and every other instrument class have no 5m
+#: endpoint (the Tushare loader skips funds explicitly), so admitting one would
+#: turn a structural limitation into a permanent data-not-ready account (F2).
+_FIVE_MINUTE_STOCK_PREFIXES: dict[str, tuple[str, ...]] = {
+ "SH": ("600", "601", "603", "605", "688", "689"),
+ "SZ": ("000", "001", "002", "003", "300", "301"),
+}
+
+
+def is_supported_five_minute_symbol(symbol: str) -> bool:
+ """True when ``stk_mins`` serves 5m bars for this cn_a symbol.
+
+ Only ordinary Shanghai/Shenzhen stocks have a MEASURED 5m leg (T1 probed
+ SH; the SZ prefixes share the same ``stk_mins`` endpoint). ``.SH``
+ 000/5/88/99/11/12 (indices, bonds, funds), ``.SZ`` 15/16/18/399 (funds,
+ indices), every ``.BJ`` listing and every other suffix are rejected: their
+ daily bars exist but no 5m endpoint is proven, so admitting them would
+ make the step fail closed forever on a provider omission it can never
+ observe.
+ """
+ if not isinstance(symbol, str):
+ return False
+ code, separator, suffix = symbol.partition(".")
+ if separator != "." or len(code) != 6 or not code.isdigit():
+ return False
+ if suffix == "BJ":
+ # BJ 5m not measured in T1; fail fast rather than a permanent
+ # provider-omission loop.
+ return False
+ prefixes = _FIVE_MINUTE_STOCK_PREFIXES.get(suffix)
+ return prefixes is not None and code.startswith(prefixes)
+
+
+def fetch_5m_frame(
+ code: str = DEFAULT_CODE,
+ start_date: str = DEFAULT_START,
+ end_date: str = DEFAULT_END,
+) -> tuple[Any | None, Any]:
+ """Fetch one cn_a symbol's 5m frame through the production loader path.
+
+ Loads ``agent/.env`` explicitly (the ambient shell is not assumed to carry
+ ``TUSHARE_TOKEN``) and calls exactly the method the engine will call:
+ ``backtest.loaders.tushare.DataLoader.fetch(..., interval="5m")``.
+
+ Args:
+ code: cn_a symbol with exchange suffix, e.g. ``"600519.SH"``.
+ start_date: Inclusive first calendar day, ``YYYY-MM-DD``.
+ end_date: Last calendar day to request. The provider's end bound is
+ exclusive at midnight, so this must be later than the last day
+ whose bars are wanted (see the module docstring).
+
+ Returns:
+ ``(frame, loader)``: the bar frame indexed by its bar label (a bar
+ end, not a bar start), or ``None`` when the provider returns no rows
+ for the window; plus the loader instance so the probe can read the
+ daily frame without constructing a second ``TushareLoader``.
+ """
+ if str(AGENT_DIR) not in sys.path:
+ sys.path.insert(0, str(AGENT_DIR))
+
+ from dotenv import load_dotenv
+
+ load_dotenv(AGENT_DIR / ".env", override=True)
+
+ from backtest.loaders.tushare import DataLoader
+
+ loader = DataLoader()
+ frames = loader.fetch([code], start_date, end_date, interval="5m")
+ return frames.get(code), loader
+
+
+def _labels(frame: Any) -> list[str]:
+ return [timestamp.strftime("%H:%M") for timestamp in frame.index]
+
+
+def _continuous(day_frame: Any) -> Any:
+ """Drop the opening call-auction row, leaving the continuous bars.
+
+ G3 policy: the 09:30 row is the opening call-auction print, not a
+ continuous 5-minute bar, so it never participates in matching (T1/T4).
+ """
+ return day_frame[day_frame.index.strftime("%H:%M") != AUCTION_LABEL]
+
+
+def _empty_intraday_frame() -> pd.DataFrame:
+ columns = {column: pd.Series(dtype="float64") for column in _OHLCV_COLUMNS}
+ return pd.DataFrame(columns, index=pd.DatetimeIndex([], name="bar_time"))
+
+
+def _canonical_intraday_frame(frame: pd.DataFrame | None) -> pd.DataFrame:
+ """Canonical 5m shape WITHOUT day normalization (bar labels are kept).
+
+ ``_canonical_frame`` collapses every label to midnight, which is correct
+ for day bars and destroys an intraday series — so the 5m leg has its own
+ canonicalizer: tz-naive ``DatetimeIndex`` on the provider's Asia/Shanghai
+ wall clock (bar ENDS, T1), exactly _OHLCV_COLUMNS, ascending, de-duplicated
+ keep-last. No ``.normalize()``, no resampling, no forwarding.
+ """
+ if frame is None or len(frame) == 0:
+ return _empty_intraday_frame()
+ df = frame.copy()
+ if "trade_time" in df.columns:
+ df = df.set_index(pd.to_datetime(df["trade_time"]))
+ elif "trade_date" in df.columns:
+ df = df.set_index(pd.to_datetime(df["trade_date"]))
+ index = pd.DatetimeIndex(df.index)
+ if index.tz is not None:
+ index = index.tz_convert(calendar.CN_A_SESSION_TIMEZONE).tz_localize(None)
+ df.index = index
+ df.index.name = "bar_time"
+ if "vol" in df.columns and "volume" not in df.columns:
+ df = df.rename(columns={"vol": "volume"})
+ for column in _OHLCV_COLUMNS:
+ if column not in df.columns:
+ df[column] = float("nan")
+ df[column] = pd.to_numeric(df[column], errors="coerce")
+ df = df[list(_OHLCV_COLUMNS)]
+ return df[~df.index.duplicated(keep="last")].sort_index()
+
+
+@dataclass(frozen=True, slots=True)
+class SessionBar:
+ """One symbol-day's assembled session bar from the continuous 5m bars (D1).
+
+ ``volume`` is the provider's raw 5m unit — SHARES, not the daily frame's
+ lots (T1) — so it is never compared with a daily volume without a scale.
+ """
+
+ open: float
+ high: float
+ low: float
+ close: float
+ volume: float
+ bar_count: int
+
+
+@dataclass(frozen=True)
+class FiveMinuteFacts:
+ bars_by_symbol: Mapping[str, Mapping[str, pd.DataFrame]] = field(default_factory=dict)
+ session_by_symbol: Mapping[str, Mapping[str, SessionBar]] = field(default_factory=dict)
+ auction_by_symbol: Mapping[str, Mapping[str, tuple[str, ...]]] = field(default_factory=dict)
+ #: Symbol -> days that produced AT LEAST ONE 5m row of any kind (the 09:30
+ #: opening-auction print counts). A symbol with rows but no continuous bar
+ #: is a halt candidate; only a symbol with no row at all is a provider
+ #: omission (N3).
+ observed_days_by_symbol: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
+ bar_fingerprint: str = ""
+ fetch_failed: bool = False
+ #: Deterministic reason for ``fetch_failed`` — surfaced verbatim as the
+ #: in-band message so a payload fault is never reported as a generic fetch
+ #: failure (or, worse, as a caller-contract violation).
+ failure_reason: str = ""
+ #: Requested symbols for which the provider yielded no 5m row at all.
+ missing_symbols: tuple[str, ...] = ()
+
+ def for_symbol(self, symbol: str) -> tuple[Mapping[str, pd.DataFrame], Mapping[str, SessionBar]]:
+ return self.bars_by_symbol.get(symbol, {}), self.session_by_symbol.get(symbol, {})
+
+
+def _finite(value: Any, default: float = 0.0) -> float:
+ numeric = float(value)
+ return numeric if math.isfinite(numeric) else default
+
+
+def _assemble_session_bar(continuous: pd.DataFrame) -> SessionBar:
+ first = continuous.iloc[0]
+ last = continuous.iloc[-1]
+ return SessionBar(
+ open=float(first["open"]),
+ high=float(continuous["high"].max()),
+ low=float(continuous["low"].min()),
+ close=float(last["close"]),
+ volume=float(continuous["volume"].sum()),
+ bar_count=int(len(continuous)),
+ )
+
+
+def _split_session_days(
+ symbol: str, frame: pd.DataFrame, warnings: list[str]
+) -> tuple[dict[str, pd.DataFrame], dict[str, SessionBar], dict[str, tuple[str, ...]]]:
+ """Split one symbol's continuous 5m frame into per-day session facts (T4).
+
+ Continuous windows only: the 09:30 opening-auction print is dropped
+ silently (it is expected, G3), an auction-window label is dropped AND
+ recorded for the ``auction_window`` event, and an out-of-session label is
+ dropped with a warning. A day with zero continuous bars has no session bar
+ (the ``halted`` candidate); 1..47 bars are legitimate for an illiquid stock
+ and produce one deterministic ``<n>/48`` warning naming the count.
+
+ Payload integrity (G4) is enforced here rather than trusted downstream:
+
+ * a continuous label off the 5-minute grid (a finer interval served as
+ 5m) raises ``ValueError``;
+ * a continuous day whose every row fails the price sanity gate raises
+ ``ValueError`` (an all-NaN payload is a provider fault, not a halt);
+ * a non-finite session volume raises ``ValueError``;
+ * a zero-volume session is a genuine halt: the day is dropped (warned
+ about) so the engine's existing halted/suspended path handles it.
+
+ ``fetch_five_minute`` catches these ``ValueError``\\ s and routes them to
+ ``failure_reason``, so they surface as ``PAPER_DATA_NOT_READY`` — never as
+ a transport error and never as a tradable session.
+ """
+ bars_by_day: dict[str, pd.DataFrame] = {}
+ session_by_day: dict[str, SessionBar] = {}
+ auction_by_day: dict[str, tuple[str, ...]] = {}
+ if frame.empty:
+ return bars_by_day, session_by_day, auction_by_day
+
+ labels = frame.index.strftime("%H:%M")
+ days = frame.index.strftime("%Y-%m-%d")
+ kinds = [calendar.classify_cn_a_session_label(label) for label in labels]
+ framed = frame.copy()
+ framed["_day"] = days
+ framed["_label"] = labels
+ framed["_kind"] = kinds
+
+ for day, chunk in framed.groupby("_day", sort=True):
+ # G3: only SESSION_CONTINUOUS rows build the session bar. The 09:30
+ # opening call-auction print is classified separately and excluded.
+ continuous = chunk[chunk["_kind"] == calendar.SESSION_CONTINUOUS]
+ auction_labels = tuple(sorted(set(chunk.loc[chunk["_kind"] == calendar.SESSION_AUCTION_WINDOW, "_label"])))
+ outside_labels = tuple(sorted(set(chunk.loc[chunk["_kind"] == calendar.SESSION_OUTSIDE, "_label"])))
+ if auction_labels:
+ auction_by_day[day] = auction_labels
+ warnings.append(
+ f"5m data: {symbol} on {day} has auction-window label(s) "
+ f"{', '.join(auction_labels)}; excluded from matching"
+ )
+ if outside_labels:
+ warnings.append(
+ f"5m data: {symbol} on {day} has {len(outside_labels)} bar label(s) "
+ f"outside the cn_a session windows (first: {outside_labels[0]}); excluded"
+ )
+ # A 1m payload served as 5m produces labels off the 5-minute grid;
+ # accepting them would assemble a ~240-row "session" the matching
+ # contract never priced. Legitimate partial sessions (09:35, 09:40,
+ # ..., 11:30, 13:05, ..., 15:00) are all on the grid.
+ off_grid = sorted({label for label in continuous["_label"] if int(label[3:5]) % 5 != 0})
+ if off_grid:
+ raise ValueError(
+ f"5m data: {symbol} on {day} has off-grid continuous label(s) "
+ f"{', '.join(off_grid[:3])}; labels must sit on the 5-minute grid"
+ )
+ price_columns = list(_PRICE_COLUMNS)
+ had_continuous = not continuous.empty
+ bad = continuous[price_columns].isna().any(axis=1) | (continuous[price_columns] <= 0).any(axis=1)
+ if bad.any():
+ warnings.append(
+ f"5m data: {symbol} on {day} dropped {int(bad.sum())} bar(s) failing the " "price sanity gate (R-V3)"
+ )
+ continuous = continuous[~bad]
+ if had_continuous and continuous.empty:
+ # Every served continuous row was unusable: a provider fault,
+ # not a halt. Fail the payload closed instead of inventing a
+ # suspended session from prices that were never valid.
+ raise ValueError("all continuous 5m bars failed the price sanity gate")
+ if continuous.empty:
+ continue
+ day_bars = continuous[list(_OHLCV_COLUMNS)].copy()
+ session = _assemble_session_bar(day_bars)
+ if not math.isfinite(session.volume):
+ raise ValueError("5m data has a non-finite session volume")
+ if session.volume <= 0:
+ # No shares traded across the whole continuous session: a halt.
+ # Dropping the day lets the engine's halted/suspended path value
+ # positions carry-forward and reject orders `suspended`.
+ warnings.append(f"5m data: {symbol} on {day} has a zero-volume session; treated as halted")
+ continue
+ bars_by_day[day] = day_bars
+ session_by_day[day] = session
+ if len(day_bars) < calendar.CONTINUOUS_BARS_PER_DAY:
+ warnings.append(
+ f"5m data: {symbol} on {day} has {len(day_bars)}/48 continuous "
+ "bars; session bar assembled from what exists"
+ )
+ return bars_by_day, session_by_day, auction_by_day
+
+
+def _bar_fingerprint(facts: FiveMinuteFacts) -> str:
+ """D3 bar fingerprint over the continuous 5m bars actually used.
+
+ Payload is a list sorted by (symbol, day, label) so symbol input order and
+ dict iteration order cannot change the digest; each row is
+ ``[symbol, day, "HH:MM", open, high, low, close, volume]``. The symbol and
+ day are part of the tuple because a bare ``HH:MM`` label repeats across
+ symbols and days. No clock, no paths, no floats beyond the served values.
+ """
+ payload: list[list[Any]] = []
+ for symbol in sorted(facts.bars_by_symbol):
+ for day in sorted(facts.bars_by_symbol[symbol]):
+ frame = facts.bars_by_symbol[symbol][day]
+ for timestamp, row in frame.iterrows():
+ payload.append(
+ [
+ symbol,
+ day,
+ timestamp.strftime("%H:%M"),
+ float(row["open"]),
+ float(row["high"]),
+ float(row["low"]),
+ float(row["close"]),
+ _finite(row["volume"]),
+ ]
+ )
+ return state_hash.state_hash(payload)
+
+
+def fetch_five_minute(
+ symbols: tuple[str, ...],
+ from_date: str,
+ to_date: str,
+ *,
+ loader: Any,
+ warnings: list[str],
+) -> FiveMinuteFacts:
+ """ONE ranged 5m fetch for the whole universe (never one call per day).
+
+ T1: the provider's ``end_date`` is exclusive at midnight, so the request
+ end is ``to_date + 1 day``. The production Tushare loader swallows a
+ provider error into an empty mapping, so a failed call and a genuinely
+ empty day are indistinguishable at this seam — the caller's whole-universe
+ zero-bar rule maps both to ``PAPER_DATA_NOT_READY`` (D6), never to
+ ``halted``. An exception that does surface is caught here, warned about,
+ and treated the same way.
+ """
+ empty = FiveMinuteFacts(bar_fingerprint=state_hash.state_hash([]))
+ if not symbols or loader is None:
+ return empty
+ end_exclusive = (dt.date.fromisoformat(to_date) + dt.timedelta(days=1)).isoformat()
+ try:
+ served = loader.fetch(list(symbols), from_date, end_exclusive, interval="5m")
+ except Exception as exc: # noqa: BLE001 — a provider fault is data-not-ready, never a halt
+ reason = (
+ f"5m fetch ({getattr(loader, 'name', 'network')}) failed: "
+ f"{type(exc).__name__}; the step is data-not-ready"
+ )
+ warnings.append(reason)
+ return FiveMinuteFacts(
+ bar_fingerprint=state_hash.state_hash([]),
+ fetch_failed=True,
+ failure_reason=reason,
+ missing_symbols=tuple(symbols),
+ )
+ if not served:
+ return FiveMinuteFacts(bar_fingerprint=state_hash.state_hash([]), missing_symbols=tuple(symbols))
+
+ start_ts = pd.Timestamp(from_date)
+ end_ts = pd.Timestamp(end_exclusive)
+ bars_by_symbol: dict[str, Mapping[str, pd.DataFrame]] = {}
+ session_by_symbol: dict[str, Mapping[str, SessionBar]] = {}
+ auction_by_symbol: dict[str, Mapping[str, tuple[str, ...]]] = {}
+ observed_days_by_symbol: dict[str, tuple[str, ...]] = {}
+ payload_error = ""
+ for symbol in symbols:
+ try:
+ frame = _canonical_intraday_frame(served.get(symbol))
+ if not frame.empty:
+ frame = frame[(frame.index >= start_ts) & (frame.index < end_ts)]
+ if not frame.empty:
+ observed_days_by_symbol[symbol] = tuple(sorted(set(frame.index.strftime("%Y-%m-%d"))))
+ bars, sessions, auctions = _split_session_days(symbol, frame, warnings)
+ except Exception as exc: # noqa: BLE001 — a malformed payload is a provider fault
+ payload_error = (
+ f"5m payload ({getattr(loader, 'name', 'network')}) for {symbol} "
+ f"could not be parsed ({type(exc).__name__}); the step is data-not-ready"
+ )
+ warnings.append(payload_error)
+ break
+ if bars:
+ bars_by_symbol[symbol] = bars
+ session_by_symbol[symbol] = sessions
+ if auctions:
+ auction_by_symbol[symbol] = auctions
+ if payload_error:
+ return FiveMinuteFacts(
+ bar_fingerprint=state_hash.state_hash([]),
+ fetch_failed=True,
+ failure_reason=payload_error,
+ missing_symbols=tuple(symbols),
+ )
+ facts = FiveMinuteFacts(
+ bars_by_symbol=bars_by_symbol,
+ session_by_symbol=session_by_symbol,
+ auction_by_symbol=auction_by_symbol,
+ observed_days_by_symbol=observed_days_by_symbol,
+ missing_symbols=tuple(
+ symbol for symbol in symbols if symbol not in bars_by_symbol and symbol not in observed_days_by_symbol
+ ),
+ )
+ return _with_fingerprint(facts)
+
+
+def _with_fingerprint(facts: FiveMinuteFacts) -> FiveMinuteFacts:
+ return FiveMinuteFacts(
+ bars_by_symbol=facts.bars_by_symbol,
+ session_by_symbol=facts.session_by_symbol,
+ auction_by_symbol=facts.auction_by_symbol,
+ observed_days_by_symbol=facts.observed_days_by_symbol,
+ bar_fingerprint=_bar_fingerprint(facts),
+ fetch_failed=facts.fetch_failed,
+ missing_symbols=facts.missing_symbols,
+ )
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Print the probe evidence; exit 2 when the provider yields no 5m rows."""
+ args = list(sys.argv[1:] if argv is None else argv)
+ code = args[0] if args else DEFAULT_CODE
+ start = args[1] if len(args) > 1 else DEFAULT_START
+ end = args[2] if len(args) > 2 else DEFAULT_END
+
+ print(f"code={code} start={start} end={end}")
+ frame, loader = fetch_5m_frame(code, start, end)
+ if frame is None or frame.empty:
+ print("NO 5m DATA for this window")
+ return 2
+
+ print(f"rows={len(frame)} first={frame.index[0]} last={frame.index[-1]}")
+ print(f"columns={list(frame.columns)}")
+
+ daily = loader.fetch([code], start, end, interval="1D").get(code)
+ print("\nper-day: count, labels, volume and OHLC vs the daily qfq frame")
+ for day, chunk in frame.groupby(frame.index.normalize()):
+ labels = _labels(chunk)
+ row = daily.loc[day] if daily is not None and day in daily.index else None
+ print(f"{day.date()} n={len(chunk)} first={labels[0]} last={labels[-1]} " f"labels={' '.join(labels)}")
+ if row is not None:
+ print(
+ f" vol5m_sum={chunk['volume'].sum():.2f} daily_vol={row['volume']:.2f} "
+ f"ratio={chunk['volume'].sum() / row['volume']:.6f} "
+ f"open5m={chunk['open'].iloc[0]:.2f} daily_open={row['open']:.2f} "
+ f"close5m={chunk['close'].iloc[-1]:.2f} daily_close={row['close']:.2f} "
+ f"high5m={chunk['high'].max():.2f} daily_high={row['high']:.2f} "
+ f"low5m={chunk['low'].min():.2f} daily_low={row['low']:.2f}"
+ )
+
+ print("\ncalendar days returned:", [str(day.date()) for day in frame.index.normalize().unique()])
+
+ demo_day = frame.index.normalize().unique()[0]
+ day_frame = frame[frame.index.normalize() == demo_day]
+ print(f"\nauction row vs first continuous bar ({demo_day.date()})")
+ print(day_frame.head(2).to_string())
+ print("\nlunch boundary rows")
+ print(day_frame.loc[f"{demo_day.date()} {_LUNCH_START}" :f"{demo_day.date()} {_LUNCH_END}"].to_string())
+
+ continuous = _continuous(day_frame)
+ print(f"\nCSV: full frame ({len(frame)} rows)")
+ print(frame.to_csv())
+ print(f"CSV: continuous {demo_day.date()} ({len(continuous)} rows)")
+ print(continuous.to_csv())
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/agent/src/tools/paper_trade/data_readiness.py b/agent/src/tools/paper_trade/data_readiness.py
new file mode 100644
index 000000000..d5a42bfae
--- /dev/null
+++ b/agent/src/tools/paper_trade/data_readiness.py
@@ -0,0 +1,163 @@
+"""Target-day readiness verdicts for ``paper_trade_step`` (AM-5 / AM-6 / AM-9).
+
+Extracted from :mod:`data` (T5): the fetch layer re-exports these names, so
+existing ``data.assess_readiness`` / ``data.ReadinessVerdict`` imports keep
+working. This module is a LEAF — it imports nothing from :mod:`data` at module
+scope (only the result types under ``TYPE_CHECKING``), which is what lets
+:mod:`data` import it back without an import cycle.
+
+``assess_readiness`` judges the FEDERATED MERGED frame, never a leg alone (CH
+is T-1 caliber — judging on it would false-alarm ``PAPER_DATA_NOT_READY`` every
+trading day). ``ready=False`` carries the frozen in-band envelope material
+(AM-5); this layer never raises for data-not-ready.
+
+Determinism (R1-1): NO clock is read — every date is injected, so the CH UTC
+vs host CST 8h skew cannot leak into verdicts.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from .data import MarketDataResult
+
+__all__ = [
+ "NOT_READY_CODE",
+ "ReadinessVerdict",
+ "assess_readiness",
+ "day_bar_availability",
+]
+
+#: Frozen in-band envelope code (schema.ERROR_CODES member) for target-day
+#: all-market zero bar (AM-5/AM-9).
+NOT_READY_CODE = "PAPER_DATA_NOT_READY"
+
+
+@dataclass(frozen=True, slots=True)
+class ReadinessVerdict:
+ """Target-day readiness (AM-9). ``ready=False`` carries the frozen in-band
+ envelope material (AM-5) — this layer never raises for data-not-ready."""
+
+ ready: bool
+ code: str | None = None
+ message: str | None = None
+
+
+# Date normalization shared with the fetch layer (``data`` imports it back); it
+# lives here so this module keeps no runtime dependency on ``data``.
+def _normalize_day(value: str) -> str:
+ return dt.date.fromisoformat(str(value).strip()).isoformat()
+
+
+def assess_readiness(result: MarketDataResult, target_day: str) -> ReadinessVerdict:
+ """Target-day readiness on the merged frame (AM-9), never on a leg alone.
+
+ Ready when ANY served symbol carries the target-day bar (a zero-bar symbol
+ is a suspended fact for the engine, AM-6③); all-market zero bar → the
+ frozen PAPER_DATA_NOT_READY material (message follows the R1-4 example
+ shape; deterministic English, no timestamps — VD-7). An empty universe is
+ vacuously ready.
+
+ ``interval="5m"`` judges the order symbols on the 5m leg instead: a
+ provider omission (daily bar present, no 5m row at all) and a day with no
+ session bar anywhere are PAPER_DATA_NOT_READY, while a served symbol with
+ no continuous session stays a halt for the engine. A zero-order 5m step
+ issues no 5m request, so it falls back to the 1d contract above and must
+ carry the target daily bar.
+ """
+ day = _normalize_day(target_day)
+ if not result.symbols:
+ return ReadinessVerdict(ready=True)
+ if result.interval == "5m":
+ return _assess_five_minute_readiness(result, day)
+ if not any(result.data[symbol].has_bar(day) for symbol in result.symbols):
+ ends = result.provenance.bars_as_of or "empty"
+ message = f"target bar {day} not available from served sources ({result.provenance.source} frame ends {ends})"
+ return ReadinessVerdict(ready=False, code=NOT_READY_CODE, message=message)
+ return ReadinessVerdict(ready=True)
+
+
+def _assess_five_minute_readiness(result: MarketDataResult, day: str) -> ReadinessVerdict:
+ # D6 fail-closed: a leg mismatch is a provider/federation fault, and an
+ # all-symbol zero-bar day cannot be told apart from a market-wide outage;
+ # both are PAPER_DATA_NOT_READY (retryable), never a silent halted day.
+ if result.five_minute_error:
+ return ReadinessVerdict(ready=False, code=NOT_READY_CODE, message=result.five_minute_error)
+ five = result.five_minute_symbols
+ if not five:
+ # An explicitly empty 5m universe (pure-valuation step) issues no 5m
+ # request, so its NAV comes from the daily leg and that leg must carry
+ # the target day — exactly the interval="1d" contract. A result built
+ # before the field existed carries session evidence instead; fall back
+ # to the whole universe only in that legacy shape.
+ if not any(result.data[s].session_bars for s in result.symbols):
+ if not any(result.data[s].has_bar(day) for s in result.symbols):
+ ends = result.provenance.bars_as_of or "empty"
+ message = (
+ f"target bar {day} not available from served sources "
+ f"({result.provenance.source} frame ends {ends})"
+ )
+ return ReadinessVerdict(ready=False, code=NOT_READY_CODE, message=message)
+ return ReadinessVerdict(ready=True)
+ five = result.symbols
+ traded = [symbol for symbol in five if result.data[symbol].has_session_bar(day)]
+ # Provider omission = the daily leg proves the symbol traded and the 5m
+ # response carried NO row for it at all. A symbol served only an auction
+ # print has 5m evidence, so its empty continuous session is a halt (N3).
+ provider_missing = [
+ symbol
+ for symbol in five
+ if symbol not in traded
+ and result.data[symbol].has_bar(day)
+ and not result.data[symbol].has_five_minute_rows(day)
+ ]
+ if provider_missing:
+ return ReadinessVerdict(
+ ready=False,
+ code=NOT_READY_CODE,
+ message=(
+ f"5m data: provider omitted the 5m leg on {day} for "
+ f"{', '.join(provider_missing)} although the daily bar exists; "
+ "stk_mins quota or permission likely; retry after the quota window"
+ ),
+ )
+ if not traded:
+ # No order symbol carries a 5m session bar. A universe symbol with a
+ # daily bar proves the exchange traded that day, so the zero-bar order
+ # symbols are genuine halts; with no bar anywhere it is an outage.
+ if not any(result.data[symbol].has_bar(day) for symbol in result.symbols):
+ ends = result.provenance.bars_as_of or "empty"
+ return ReadinessVerdict(
+ ready=False,
+ code=NOT_READY_CODE,
+ message=(
+ f"no 5m session bar for {day} from served sources "
+ f"({result.provenance.source}; daily frame ends {ends})"
+ ),
+ )
+ return ReadinessVerdict(ready=True)
+ mismatched = tuple(symbol for symbol in result.five_minute_contradiction.get(day, ()) if symbol in five)
+ if mismatched:
+ return ReadinessVerdict(
+ ready=False,
+ code=NOT_READY_CODE,
+ message=(
+ f"5m data is inconsistent on {day}: {', '.join(mismatched)} has a daily bar "
+ "and a 5m session bar is missing (or the reverse); refusing to read a "
+ "provider fault as a halt"
+ ),
+ )
+ return ReadinessVerdict(ready=True)
+
+
+def day_bar_availability(result: MarketDataResult, dates: Any) -> dict[str, tuple[str, ...]]:
+ # Per-day sorted tuple of symbols WITH a bar — the AM-6 matrix input
+ # (dates: iterable of YYYY-MM-DD, e.g. hk_us_candidate_days output).
+ availability: dict[str, tuple[str, ...]] = {}
+ for raw in dates:
+ day = _normalize_day(raw)
+ availability[day] = tuple(s for s in result.symbols if result.data[s].has_bar(day))
+ return availability
diff --git a/agent/src/tools/paper_trade/engine.py b/agent/src/tools/paper_trade/engine.py
index 7620c6089..61b2541d4 100644
--- a/agent/src/tools/paper_trade/engine.py
+++ b/agent/src/tools/paper_trade/engine.py
@@ -31,8 +31,9 @@ from .limits_cn_a import (
PROV_LIMITS_HEURISTIC, CnALimitsClient, get_limit_status, heuristic_limit_prices)
from .rules import MarketRules, money, quantize_money
from .schema import (
- AccountState, DataProvenance, Fill, NavPoint, Order, PaperTradeStepRequest,
- Position, RejectedOrder, SkippedDay,
+ CANCELED_REASON_CODE, DEFAULT_FILL_MODEL, DEFAULT_PATH_MODEL, AccountState,
+ CanceledOrder, DataProvenance, Fill, NavPoint, Order, PaperTradeStepRequest,
+ Position, RejectedOrder, SessionEvent, SkippedDay,
)
__all__ = ["DayPlan", "EngineError", "MatchOutcome", "build_day_plan",
@@ -67,6 +68,11 @@ class MatchOutcome:
effective_fee_model: dict[str, float] = field(default_factory=dict)
limit_provenance: tuple[str, ...] = ()
error: EngineError | None = None
+ # pt-v1.2 additive out-params (D2/D3). All three stay at their empty
+ # defaults for an interval="1d" call, so the pt-v1.1 outcome is unchanged.
+ engine_fingerprint: str = ""
+ canceled_orders: tuple[CanceledOrder, ...] = ()
+ events: tuple[SessionEvent, ...] = ()
@dataclass(frozen=True, slots=True)
@@ -164,10 +170,16 @@ class _MatchSession:
limits_client: CnALimitsClient | None,
corporate_action_unresolved_by_day: Mapping[str, Collection[str]],
ca_plan: corporate_actions.CorporateActionPlan,
+ *,
+ path_model: str = DEFAULT_PATH_MODEL,
+ fill_model: str = DEFAULT_FILL_MODEL,
) -> None:
self.market = market
self.rules = rules
self.market_data = market_data
+ self.interval = market_data.interval
+ self.path_model = path_model
+ self.fill_model = fill_model
self.limits_client = limits_client
self.ca_by_day = corporate_action_unresolved_by_day
self.cash = quantize_money(money(account_state.cash))
@@ -181,6 +193,8 @@ class _MatchSession:
self.skipped: list[SkippedDay] = []
self.warnings: list[str] = list(market_data.warnings) + list(ca_plan.warnings)
self.limit_provenance: list[str] = []
+ self.canceled: list[CanceledOrder] = []
+ self.events: list[SessionEvent] = []
self._band_cache: dict[tuple[str, str], tuple[float | None, float | None]] = {}
def _merge_input_position(self, symbol: str, qty: Decimal, avg_cost: Decimal) -> None:
@@ -196,12 +210,68 @@ class _MatchSession:
self.positions[symbol] = _LedgerPosition(
new_qty, basis.quantize(_Q4, rounding=ROUND_HALF_UP))
+ @property
+ def _five_minute(self) -> bool:
+ return self.interval == "5m"
+
+ @property
+ def _five_minute_symbols(self) -> tuple[str, ...]:
+ # The session-fact universe is the 5m leg's universe (the order symbols
+ # in orders mode): a position with no order was only fetched on the
+ # daily leg and must never be reported as halted. An empty 5m universe
+ # issues no 5m request, so it has no session facts at all; only a
+ # legacy result that records no universe but did serve session bars
+ # falls back to the whole symbol list.
+ symbols = self.market_data.five_minute_symbols
+ if symbols:
+ return symbols
+ if any(sym_data.session_bars for sym_data in self.market_data.data.values()):
+ return self.market_data.symbols
+ return ()
+
+ def begin_day(self, day: DayPlan) -> None:
+ # T4 session facts, emitted once per day before its orders: a closed
+ # calendar day is a day-level non_trading_day; on a matching day a
+ # symbol with zero session bars is halted (D6 guarantees at least one
+ # other symbol traded for the target day), and auction-window labels
+ # that were excluded from the session bar are reported. interval="1d"
+ # emits nothing.
+ if not self._five_minute:
+ return
+ if day.skip_reason == _SKIP_NON_TRADING:
+ self.events.append(SessionEvent(
+ trade_date=day.date, symbol="", event_type="non_trading_day",
+ detail=f"{self.market} calendar closed on {day.date}"))
+ return
+ if day.skip_reason is not None:
+ return
+ five_symbols = self._five_minute_symbols
+ traded = any(
+ (sym_data := self.market_data.data.get(symbol)) is not None
+ and sym_data.has_session_bar(day.date)
+ for symbol in five_symbols)
+ for symbol in five_symbols:
+ sym_data = self.market_data.data.get(symbol)
+ if sym_data is None:
+ continue
+ labels = sym_data.auction_labels.get(day.date, ())
+ if labels:
+ self.events.append(SessionEvent(
+ trade_date=day.date, symbol=symbol, event_type="auction_window",
+ detail=f"auction-window label(s) {', '.join(labels)} excluded from matching"))
+ if sym_data.has_session_bar(day.date):
+ continue
+ self.events.append(SessionEvent(
+ trade_date=day.date, symbol=symbol, event_type="halted",
+ 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.
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:
+ 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
# Slot 2 non_trading_day: cn_a calendar truth (AM-6).
@@ -209,11 +279,15 @@ class _MatchSession:
self._reject(day, order, "non_trading_day", f"{self.market} calendar closed on {day.date}")
return
# Slot 3 suspended: zero bar today, or an R-V3 untradable bar
- # (documented mapping: suspended is the closest frozen code).
- if not sym_data.has_bar(day.date):
- self._reject(day, order, "suspended", f"no bar for {symbol} on {day.date}; position valued carry-forward")
+ # (documented mapping: suspended is the closest frozen code). In 5m
+ # mode the session bar is the matched bar, so its absence is the halt.
+ 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
- if day.date in sym_data.untradable_dates:
+ 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
# Slot 4 corporate_action_unresolved: T4 detector union + injected seam.
@@ -227,24 +301,34 @@ class _MatchSession:
self._reject(day, order, "lot_size", f"qty {order.qty} violates the "
f"{self.rules.lot_size(symbol)}-share lot rule for {symbol}")
return
- close = float(sym_data.frame.loc[pd.Timestamp(day.date), "close"])
+ 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
+ # this anchor; an absent daily close skips the band (never fabricated).
if self.rules.has_price_limits:
- 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
- if code == "limit_down":
- self._reject(day, order, code, f"close {close:.2f} at or below down limit {down:.2f}; sell rejected")
- return
- # Slot 7 limit_not_marketable (AM-7: buy fills only close ≤ limit,
- # sell only close ≥ limit; fill price = close).
- if self.rules.limit_order_violation(order.side, close, order.limit):
+ if close is None:
+ self.warnings.append(
+ f"limit band check skipped for {symbol} on {day.date}: no daily close to anchor the band")
+ else:
+ 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
+ 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).
+ if self.rules.limit_order_violation(order.side, ref, order.limit):
+ anchor = "ref" if self._five_minute else "close"
detail = (
- f"close {close:.2f} > limit {order.limit:.2f}"
+ f"{anchor} {ref:.2f} > limit {order.limit:.2f}"
if order.side == "buy"
- else f"close {close:.2f} < limit {order.limit:.2f}"
+ else f"{anchor} {ref:.2f} < limit {order.limit:.2f}"
)
self._reject(day, order, "limit_not_marketable", detail)
return
@@ -261,26 +345,67 @@ class _MatchSession:
self._reject(day, order, code, f"sell qty {order.qty} exceeds position {total}")
return
# Slot 10 insufficient_cash (§4: qty×price+fee ≤ cash).
- code = self.rules.cash_rejection(order.side, order.qty, close, self.cash)
+ code = self.rules.cash_rejection(order.side, order.qty, ref, self.cash)
if code == "insufficient_cash":
- cost = self.rules.buy_cost(order.qty, close)
+ cost = self.rules.buy_cost(order.qty, ref)
self._reject(day, order, code, f"buy cost {cost} exceeds cash {self.cash}")
return
- self._fill(day.date, order, close)
+ self._fill(day.date, order, ref)
+
+ def _bar_missing(self, day: str, sym_data: data.SymbolData) -> bool:
+ if self._five_minute:
+ return not sym_data.has_session_bar(day)
+ return not sym_data.has_bar(day)
+
+ def _bar_untradable(self, day: str, sym_data: data.SymbolData) -> bool:
+ if day in sym_data.untradable_dates:
+ return True
+ bar = sym_data.session_bars.get(day) if self._five_minute else None
+ return bar is not None and min(bar.open, bar.high, bar.low, bar.close) <= 0
+
+ def _close_price(self, day: str, sym_data: data.SymbolData) -> float | None:
+ # The daily close stays the band / valuation anchor in both modes.
+ if sym_data.frame.empty or not sym_data.has_bar(day):
+ 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]
+ if self.path_model == "bar_close":
+ raw = money(bar.close)
+ else:
+ prices = sorted((money(bar.open), money(bar.high), money(bar.low), money(bar.close)))
+ raw = (prices[1] + prices[2]) / Decimal(2)
+ return quantize_money(raw)
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,
qty=order.qty, reason_code=code, detail=detail)
)
+ if not self._five_minute:
+ return
+ # T3/D2 emergency cancel: one row per failed order IN ADDITION to its
+ # specific pt-v1.1 reason (the frozen REASON_CODES table is untouched).
+ self.canceled.append(CanceledOrder(
+ trade_date=day.date, symbol=order.symbol, side=order.side, qty=order.qty,
+ reason_code=CANCELED_REASON_CODE, detail=f"rejected: {code}"))
+ if code in ("limit_up", "limit_down"):
+ self.events.append(SessionEvent(
+ trade_date=day.date, symbol=order.symbol, event_type="price_limit", detail=detail))
def _fill(self, day: str, order: Order, close: float) -> None:
# Decimal settlement (VD-9): 2dp notional ± 2dp fee; avg_cost is the
# fee-exclusive weighted average fill price, quantized 4dp HALF_UP at
# every mutation so internal chaining equals the RM round-trip.
+ price_value = float(close) # 5m hands a 2dp Decimal; the wire wants a float
qty = money(order.qty)
- price = money(close)
- fee = self.rules.fee(order.side, order.qty, close)
+ price = money(price_value)
+ fee = self.rules.fee(order.side, order.qty, price_value)
notional = quantize_money(qty * price)
if order.side == "buy":
self.cash -= notional + fee
@@ -298,7 +423,7 @@ class _MatchSession:
self.positions[order.symbol].qty -= qty
# VD-15/B2 dual mode at the fill boundary: plain Orders → ""; StrategyOrders → ≤200 chars.
self.fills.append(Fill(trade_date=day, symbol=order.symbol, side=order.side,
- qty=order.qty, price=close, fee=float(fee),
+ qty=order.qty, price=price_value, fee=float(fee),
reason=wire.strategy_fill_reason(getattr(order, "reason", None))))
def _band(self, symbol: str, day: str, sym_data: data.SymbolData) -> tuple[float | None, float | None]:
@@ -420,6 +545,12 @@ def match_orders(
raise ValueError(
f"market_data was fetched for {market_data.market!r}, request says {request.market!r}"
)
+ if request.interval != market_data.interval:
+ # Cross-field gate: a 5m request served a 1d frame (or the reverse)
+ # must not silently match the daily close under 5m semantics.
+ error = EngineError("INVALID_REQUEST", f"market_data was fetched at interval "
+ f"{market_data.interval!r}, request says {request.interval!r}")
+ return error_outcome(error, request.account_state, market_data, request.market, request.fee_model)
if request.from_date != request.to_date:
error = EngineError("INVALID_REQUEST", "orders mode requires from_date == to_date "
f"(AM-3 single-day); got from_date={request.from_date} to_date={request.to_date}")
@@ -433,7 +564,8 @@ def match_orders(
from_date=request.from_date, to_date=request.to_date, market_data=market_data,
orders_by_day={request.from_date: request.orders}, fee_model=request.fee_model,
calendar_client=calendar_client, limits_client=limits_client, hk_lot_sizes=hk_lot_sizes,
- corporate_action_unresolved_by_day=corporate_action_unresolved_by_day)
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day,
+ path_model=request.path_model, fill_model=request.fill_model)
def run_day_loop(
@@ -450,6 +582,8 @@ def run_day_loop(
limits_client: CnALimitsClient | None = None,
corporate_action_unresolved_by_day: Mapping[str, Collection[str]] | None = None,
hk_lot_sizes: Mapping[str, int] | None = None,
+ path_model: str = DEFAULT_PATH_MODEL,
+ fill_model: str = DEFAULT_FILL_MODEL,
) -> MatchOutcome:
# Day-loop core: enumerate [from, to], gate readiness (AM-9), match
# serially (VD-10). Multi-day ranges are only reachable through this
@@ -481,8 +615,9 @@ def run_day_loop(
market, rules, market_data, account_state, limits_client,
corporate_actions.merge_unresolved(
corporate_action_unresolved_by_day, ca_plan.unresolved_by_day),
- ca_plan)
+ ca_plan, path_model=path_model, fill_model=fill_model)
for entry in plan:
+ session.begin_day(entry) # T4 session facts (no-op for interval="1d")
session.bought_today = {} # T+1 availability resets each day
if entry.skip_reason is not None:
session.skipped.append(SkippedDay(date=entry.date, reason=entry.skip_reason))
@@ -513,4 +648,9 @@ def run_day_loop(
tuple(market_data.provenance.corporate_actions) + ca_plan.provenance)),
effective_fee_model=rules.effective_fee_model,
limit_provenance=tuple(dict.fromkeys(session.limit_provenance)),
+ engine_fingerprint=state_hash.engine_fingerprint(
+ interval=market_data.interval, path_model=path_model, fill_model=fill_model,
+ bar_fingerprint=market_data.bar_fingerprint),
+ canceled_orders=tuple(session.canceled),
+ events=tuple(session.events),
)
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
new file mode 100644
index 000000000..d691135ac
--- /dev/null
+++ b/agent/src/tools/paper_trade/paper_trade_step-v1.2.json
@@ -0,0 +1,319 @@
+{
+ "$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.",
+ "contract": "paper_trade_step",
+ "version": "pt-v1.2",
+ "status": "final",
+ "schemas": {
+ "result": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.2/result.json",
+ "title": "paper_trade_step success result (pt-v1.2)",
+ "type": "object",
+ "required": [
+ "schema_version",
+ "tool",
+ "account_id",
+ "market",
+ "range",
+ "received_state_hash",
+ "effective_fee_model",
+ "fills",
+ "rejected_orders",
+ "end_state",
+ "nav_series",
+ "skipped_days",
+ "warnings",
+ "data_provenance"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "schema_version": {
+ "type": "string",
+ "enum": ["pt-v1.1", "pt-v1.2"],
+ "$comment": "Which version a response emits: 'pt-v1.1' when every new request field is at its default (byte-identical to the frozen v1.1 document, no v1.2 keys at all); 'pt-v1.2' when at least one new request field is non-default (D8). A 'pt-v1.1' document remains governed by paper_trade_step-v1.1.json."
+ },
+ "tool": { "type": "string", "const": "paper_trade_step" },
+ "account_id": {
+ "type": "string",
+ "minLength": 1,
+ "$comment": "verbatim echo of the input (R4)"
+ },
+ "market": {
+ "type": "string",
+ "enum": ["cn_a", "hk", "us"]
+ },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "sha256(JCS(non-order inputs)) — AM-4/R7; 64 lowercase hex. The four new request fields enter the coverage object ONLY when non-default (D4), so a v1.1 call hashes exactly as before."
+ },
+ "effective_fee_model": {
+ "type": "object",
+ "$comment": "Full echo of the fee parameters in effect (R7-3). Default key names FROZEN per APPROVAL note 5 / REQUIREMENTS §4 (state_hash.py _DEFAULT_FEE_MODELS, delivery note #7): cn_a = commission_rate 0.00025, commission_min 5.0, stamp_tax_sell 0.0005, transfer_fee 0.00001; hk = commission_rate 0.0003, commission_min 3.0, stamp_tax_rate 0.001, regulatory_levy_rate 0.00003; us = commission_per_share 0.0049, commission_min 0.99, sec_fee_rate 0.0. Per-key merge: RM always injects fee_model explicitly (AM-4-3) and injected keys pass through, so the object stays open by design."
+ },
+ "fills": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "price", "fee", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": {
+ "type": "string",
+ "enum": ["buy", "sell"]
+ },
+ "qty": { "type": "number" },
+ "price": { "type": "number" },
+ "fee": { "type": "number" },
+ "reason": {
+ "type": "string",
+ "$comment": "VD-15: orders mode = empty string; strategy_path mode = strategy reason text truncated to <=200 chars (UTF-8 safe)"
+ }
+ }
+ }
+ },
+ "rejected_orders": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "reason_code", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": {
+ "type": "string",
+ "enum": ["buy", "sell"]
+ },
+ "qty": { "type": "number" },
+ "reason_code": {
+ "type": "string",
+ "enum": [
+ "insufficient_cash",
+ "insufficient_position",
+ "t_plus_1",
+ "limit_up",
+ "limit_down",
+ "suspended",
+ "lot_size",
+ "non_trading_day",
+ "unknown_symbol",
+ "corporate_action_unresolved",
+ "limit_not_marketable"
+ ],
+ "$comment": "AM-14 closed vocabulary (11) — FROZEN, unchanged by pt-v1.2 (D2): the emergency-cancel event lives in canceled_orders, never here"
+ },
+ "detail": { "type": "string" }
+ }
+ }
+ },
+ "canceled_orders": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "reason_code", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": {
+ "type": "string",
+ "enum": ["buy", "sell"]
+ },
+ "qty": { "type": "number" },
+ "reason_code": {
+ "type": "string",
+ "const": "canceled_after_failed_match",
+ "$comment": "T3 emergency cancel: one row per failed order in 5m mode (D2). Never added to the frozen rejected_orders vocabulary."
+ },
+ "detail": { "type": "string" }
+ }
+ },
+ "$comment": "pt-v1.2 only. Emitted (possibly empty) for a v1.2 call; omitted entirely for a pt-v1.1 call, which stays byte-identical (D2/D8)."
+ },
+ "events": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "event_type", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "event_type": {
+ "type": "string",
+ "enum": ["non_trading_day", "halted", "price_limit", "auction_window"],
+ "$comment": "Session facts (T4, D2). halted = calendar says open, the 5m fetch succeeded, another symbol has bars that day, and this symbol has zero bars for the session (D6)."
+ },
+ "detail": { "type": "string" }
+ }
+ },
+ "$comment": "pt-v1.2 only. Emitted (possibly empty) for a v1.2 call; omitted entirely for a pt-v1.1 call (D2/D8)."
+ },
+ "end_state": {
+ "type": "object",
+ "required": ["cash", "positions"],
+ "additionalProperties": false,
+ "properties": {
+ "cash": { "type": "number" },
+ "positions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "qty", "avg_cost"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "qty": { "type": "number" },
+ "avg_cost": { "type": "number" }
+ }
+ }
+ }
+ }
+ },
+ "nav_series": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "nav", "cash", "position_value"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "nav": { "type": "number" },
+ "cash": { "type": "number" },
+ "position_value": { "type": "number" }
+ }
+ }
+ },
+ "skipped_days": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "reason": {
+ "type": "string",
+ "enum": ["non_trading_day", "market_closed_inferred"],
+ "$comment": "AM-14 closed vocabulary (2): non_trading_day = cn_a only (CH calendar truth); market_closed_inferred = hk/us only, always accompanied by a warning (AM-6)"
+ }
+ }
+ }
+ },
+ "warnings": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "deterministic English strings, never contain timestamps (VD-7 / R1 hard semantics 1)"
+ },
+ "data_provenance": {
+ "type": "object",
+ "required": ["source"],
+ "additionalProperties": false,
+ "properties": {
+ "source": {
+ "type": "string",
+ "$comment": "AM-9 merged-frame form for cn_a, e.g. 'clickhouse+tencent(merged)'"
+ },
+ "ch_as_of": { "type": "string" },
+ "network_as_of": { "type": "string" },
+ "bars_as_of": { "type": "string" },
+ "corporate_actions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "date", "ratio", "detected"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "date": { "type": "string" },
+ "ratio": {
+ "type": "string",
+ "$comment": "clean hit = ratio label (e.g. '4:1'); unresolved = the observed close-to-close ratio as a decimal string (fail-closed fact, never a guess)"
+ },
+ "detected": {
+ "type": "boolean",
+ "$comment": "true = clean split applied; false = unresolved fail-closed rejection (corporate_action_unresolved). Typed to match the T4 emitter (corporate_actions.py); reconciled from the draft's string typing at G1 finalization as its module docstring assigned to T5"
+ }
+ }
+ }
+ },
+ "limit_provenance": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "VD-11 cn_a limit/ST/suspension path tokens, '<symbol>@<date>:<token>' — token set frozen (limits_cn_a.py): limits:stk_limit / limits:heuristic / limits:unavailable / st:stk_st_daily / st:stk_st_daily-no-row / suspend:stk_suspend / suspend:stk_suspend-no-row / limit_list:stk_limit_list_d. Present only for cn_a runs that consulted the band seam"
+ }
+ },
+ "$comment": "Extension set FINALIZED at G1 (was draft-open): AM-9 merge-state fields (ch_as_of/network_as_of/bars_as_of), T4 corporate_actions, VD-11 limit_provenance. Optional fields are omitted when unset, never null. Unchanged by pt-v1.2."
+ },
+ "engine_fingerprint": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{64}$",
+ "$comment": "Required in a pt-v1.2 document (D3/D8): sha256(JCS({interval, path_model, fill_model, rules_version, bar_fingerprint})) as lowercase hex. No paths, no clock, no dict iteration order. Out field only — it never changes matching. bar_fingerprint is supplied by the engine (T3/T4); '' means no bar fingerprint was supplied (e.g. a cash-only account)."
+ }
+ },
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "schema_version": { "const": "pt-v1.2" }
+ },
+ "required": ["schema_version"]
+ },
+ "then": {
+ "required": ["engine_fingerprint", "canceled_orders", "events"]
+ },
+ "$comment": "Version-gated requirement: engine_fingerprint/canceled_orders/events are mandatory ONLY for a pt-v1.2 document, so a pt-v1.1-labelled document stays valid under this additive file (it is governed by paper_trade_step-v1.1.json). The dependency-free validator in agent/src/tools/paper_trade/schema.py deliberately ignores if/then/allOf (it implements a keyword subset); wire.build_success_payload enforces the same rule in Python — it raises unless a pt-v1.2 fingerprint is 64 lowercase hex and always emits canceled_orders/events for a v1.2 result."
+ }
+ ]
+ },
+ "error_envelope": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.2/error_envelope.json",
+ "title": "paper_trade_step in-band error envelope (pt-v1.2, AM-5)",
+ "type": "object",
+ "required": ["status", "code", "account_id", "market", "range", "message"],
+ "additionalProperties": false,
+ "properties": {
+ "status": { "type": "string", "const": "error" },
+ "code": {
+ "type": "string",
+ "enum": ["PAPER_DATA_NOT_READY", "INVALID_REQUEST"],
+ "$comment": "AM-14 closed vocabulary (2 + transport reserved): PAPER_DATA_NOT_READY = retryable (RM 30min x 3); INVALID_REQUEST = non-retryable. Transport-level MCP errors are reserved for engine-internal faults. Unchanged by pt-v1.2."
+ },
+ "account_id": { "type": "string", "$comment": "verbatim echo even on the error path (AM-4-4/AM-5)" },
+ "market": {
+ "type": "string",
+ "enum": ["cn_a", "hk", "us"]
+ },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "present only when the received account_state was parseable (AM-4-4); omitted otherwise, never null — RM reads the absence as 'state unparseable' and must not burn its retry chain"
+ },
+ "message": {
+ "type": "string",
+ "$comment": "deterministic English, no timestamps (VD-7). Frozen formats include strategy_execution_timeout:{YYYY-MM-DD} and strategy_execution_error:{YYYY-MM-DD}:{exception class} (VD-8/B1, Step 7). pt-v1.2 adds 'interval 5m is cn_a-only in pt-v1.2' and the cn_a session gate."
+ }
+ }
+ }
+ }
+}
diff --git a/agent/src/tools/paper_trade/rules.py b/agent/src/tools/paper_trade/rules.py
index 45e4fde0d..4b3c2133b 100644
--- a/agent/src/tools/paper_trade/rules.py
+++ b/agent/src/tools/paper_trade/rules.py
@@ -49,12 +49,19 @@ from . import state_hash
__all__ = [
"CN_A_LOT_SHARES",
"REJECTION_ORDER",
+ "RULES_VERSION",
"US_LOT_SHARES",
"MarketRules",
"money",
"quantize_money",
]
+#: D3 engine-fingerprint component. Bump this string whenever fee / lot /
+#: price-limit / settlement 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"
+
#: AM-14 frozen rejection decision order — first match wins (REQUIREMENTS §2
#: hard semantics 3a). ``limit_up``/``limit_down`` share one frozen slot and
#: sit adjacent: a buy can only hit the upper band, a sell only the lower one,
diff --git a/agent/src/tools/paper_trade/schema.py b/agent/src/tools/paper_trade/schema.py
index 818d469cb..e84de4ff7 100644
--- a/agent/src/tools/paper_trade/schema.py
+++ b/agent/src/tools/paper_trade/schema.py
@@ -1,4 +1,4 @@
-"""pt-v1.1 wire contract for ``paper_trade_step`` (dataclasses + vocabularies).
+"""pt-v1.1 / pt-v1.2 wire contract for ``paper_trade_step`` (shapes + vocabularies).
Declares the in-param, out-param and error-envelope shapes frozen by
``PAPER_TRADING_ENGINE_AMENDMENT_PT_V1.1.md`` §2 (the FROZEN summary), plus
@@ -8,11 +8,25 @@ Every contract-sensitive value here is FROZEN per the approval §5
declaration: vocabulary or field-set changes are a major schema bump with
RM written confirmation; additive fields are a minor bump (REQUIREMENTS §9).
+pt-v1.2 is the ADDITIVE bump for the cn_a 5m post-close step (P0 plan T2,
+decision record D1-D8). It adds four OPTIONAL request fields — ``interval``,
+``session``, ``path_model``, ``fill_model`` — whose defaults reproduce the
+pt-v1.1 semantics exactly, and three out-param additions —
+``engine_fingerprint``, ``canceled_orders``, ``events`` — emitted ONLY for a
+v1.2 call. "v1.2 call" means at least one new request field is non-default
+(D8): every call that omits them stays byte-identical to pt-v1.1, including
+``received_state_hash`` (D4). The pt-v1.1 vocabularies (``REASON_CODES``,
+``SKIPPED_DAY_REASONS``, ``ERROR_CODES``) are NOT extended; the emergency
+cancel token lives only inside ``canceled_orders`` (D2).
+
Companion artifacts:
-* ``schema/tool_contracts/paper_trade_step-v1.1.json`` — finalized out-param
+* ``schema/tool_contracts/paper_trade_step-v1.1.json`` — frozen v1.1 out-param
+ error-envelope jsonschema (VD-13), loaded by :func:`load_contract_schema`.
-* ``state_hash.py`` — ``received_state_hash`` / ``effective_fee_model``.
+* ``schema/tool_contracts/paper_trade_step-v1.2.json`` — the additive v1.2
+ copy (same loader, ``version="pt-v1.2"``).
+* ``state_hash.py`` — ``received_state_hash`` / ``effective_fee_model`` /
+ ``engine_fingerprint``.
* ``wire.py`` — success/error payload builders + deterministic JSON
serialization (Step 5 split: this module stays shapes + boundary parsing).
@@ -38,14 +52,27 @@ from pathlib import Path
from typing import Any
__all__ = [
+ "CANCELED_REASON_CODE",
+ "DEFAULT_FILL_MODEL",
+ "DEFAULT_INTERVAL",
+ "DEFAULT_PATH_MODEL",
+ "DEFAULT_SESSION",
"ERROR_CODES",
+ "FILL_MODELS",
+ "INTERVALS",
"MARKETS",
+ "PATH_MODELS",
"REASON_CODES",
+ "SCHEMA_VERSIONS",
+ "SCHEMA_VERSION",
+ "SCHEMA_VERSION_V1_2",
+ "SESSION_EVENT_TYPES",
+ "SESSIONS",
"SIDES",
"SKIPPED_DAY_REASONS",
- "SCHEMA_VERSION",
"TOOL_NAME",
"AccountState",
+ "CanceledOrder",
"ErrorEnvelope",
"Fill",
"NavPoint",
@@ -55,6 +82,7 @@ __all__ = [
"PaperTradeStepResult",
"Position",
"RejectedOrder",
+ "SessionEvent",
"SkippedDay",
"load_contract_schema",
"parse_account_state",
@@ -64,9 +92,53 @@ __all__ = [
#: Wire contract version — FROZEN: pt-v1.1 is the first frozen implementation
#: version (G1 approved 2026-10-19; AMENDMENT header version-semantics ruling).
+#: It stays the DEFAULT version emitted: a call that uses no pt-v1.2 field is
+#: a pt-v1.1 document, byte-identical to the frozen output (D8).
#: Constant convention: backtest_summary.py:31, market_data_tool.py:71.
SCHEMA_VERSION = "pt-v1.1"
+#: Additive bump version (P0 5m plan T2): emitted when at least one new
+#: request field is non-default.
+SCHEMA_VERSION_V1_2 = "pt-v1.2"
+
+#: Every version this loader can resolve, oldest first.
+SCHEMA_VERSIONS: tuple[str, ...] = (SCHEMA_VERSION, SCHEMA_VERSION_V1_2)
+
+# ── pt-v1.2 additive request vocabularies (D1/D5/D8) ──
+#
+# Defaults are the pt-v1.1 semantics: omitting all four fields selects the
+# frozen daily close-price path and leaves the wire document untouched.
+#: ``interval`` — 1d keeps the frozen pt-v1.1 path; 5m is cn_a-only (D5).
+INTERVALS: tuple[str, ...] = ("1d", "5m")
+DEFAULT_INTERVAL = "1d"
+
+#: ``session`` — ``auto`` resolves to cn_a for market=cn_a and is inert for
+#: hk/us; ``cn_a`` with a non-cn_a market is an INVALID_REQUEST gate (D5).
+SESSIONS: tuple[str, ...] = ("auto", "cn_a")
+DEFAULT_SESSION = "auto"
+
+#: ``path_model`` — how the reference price is derived from the matched bar
+#: (D1). Ignored for interval=1d (which keeps the pt-v1.1 close path).
+PATH_MODELS: tuple[str, ...] = ("bar_median", "bar_close")
+DEFAULT_PATH_MODEL = "bar_median"
+
+#: ``fill_model`` — the only P0 value: all-or-nothing, no partial fills.
+FILL_MODELS: tuple[str, ...] = ("all_or_none",)
+DEFAULT_FILL_MODEL = "all_or_none"
+
+#: ``events[].event_type`` — pt-v1.2 session facts (T4, D2). Not an AM-14
+#: vocabulary and not part of any frozen pt-v1.1 table.
+SESSION_EVENT_TYPES: tuple[str, ...] = (
+ "non_trading_day",
+ "halted",
+ "price_limit",
+ "auction_window",
+)
+
+#: ``canceled_orders[].reason_code`` — the single T3 emergency-cancel token
+#: (D2). Deliberately NOT a member of ``REASON_CODES``, which stays frozen.
+CANCELED_REASON_CODE = "canceled_after_failed_match"
+
#: Bare MCP tool name (RM observer whitelists bare + ``vibe-trading_`` prefix).
TOOL_NAME = "paper_trade_step"
@@ -109,8 +181,15 @@ SIDES: tuple[str, ...] = ("buy", "sell")
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
-#: Repo-root-relative location of the wire-contract jsonschema (VD-13).
-_CONTRACT_SCHEMA_PATH = Path(__file__).with_name("paper_trade_step-v1.1.json")
+#: Contract jsonschemas ship INSIDE the package (``tools/paper_trade/*.json`` is
+#: declared package-data) so an installed wheel or sdist resolves them without
+#: the repository root. ``schema/tool_contracts/`` keeps the published mirror;
+#: a test pins the two copies byte-identical.
+_CONTRACT_SCHEMA_DIR = Path(__file__).resolve().parent
+_CONTRACT_SCHEMA_PATHS: dict[str, Path] = {
+ SCHEMA_VERSION: _CONTRACT_SCHEMA_DIR / "paper_trade_step-v1.1.json",
+ SCHEMA_VERSION_V1_2: _CONTRACT_SCHEMA_DIR / "paper_trade_step-v1.2.json",
+}
class PaperTradeSchemaError(ValueError):
@@ -171,6 +250,31 @@ class PaperTradeStepRequest:
# explicitly (required-at-dispatch) while the field stays schema-optional
# for backward compatibility (AMENDMENT §2.3).
fee_model: dict[str, float] = field(default_factory=dict)
+ # pt-v1.2 additive fields (D8): defaults ARE the pt-v1.1 semantics, so an
+ # absent field is indistinguishable from the default value everywhere.
+ interval: str = DEFAULT_INTERVAL
+ session: str = DEFAULT_SESSION
+ path_model: str = DEFAULT_PATH_MODEL
+ fill_model: str = DEFAULT_FILL_MODEL
+
+ @property
+ def uses_v1_2(self) -> bool:
+ """Whether this call selects the additive pt-v1.2 surface (D8).
+
+ True iff at least one new request field is non-default. A False
+ request must keep the pt-v1.1 byte-identical output and hash (D4).
+ """
+ return (
+ self.interval != DEFAULT_INTERVAL
+ or self.session != DEFAULT_SESSION
+ or self.path_model != DEFAULT_PATH_MODEL
+ or self.fill_model != DEFAULT_FILL_MODEL
+ )
+
+ @property
+ def schema_version(self) -> str:
+ """The wire ``schema_version`` this request's result must carry."""
+ return SCHEMA_VERSION_V1_2 if self.uses_v1_2 else SCHEMA_VERSION
def _require_number(value: Any, path: str) -> float:
@@ -201,6 +305,21 @@ def _parse_date(value: Any, path: str) -> str:
return text
+def _parse_choice(value: Any, path: str, allowed: tuple[str, ...], default: str) -> str:
+ """Parse one pt-v1.2 optional enum: absent/null → default, else closed check.
+
+ ``None`` is the "field not supplied" spelling (JSON null and a missing key
+ are the same intent for an optional field); a PRESENT non-string or an
+ out-of-vocabulary string is a contract violation, never silently defaulted.
+ """
+ if value is None:
+ return default
+ text = _require_str(value, path)
+ if text not in allowed:
+ raise PaperTradeSchemaError(f"{path} must be one of {allowed}, got {text!r}")
+ return text
+
+
def _parse_position(raw: Any, path: str) -> Position:
if not isinstance(raw, dict):
raise PaperTradeSchemaError(f"{path} must be an object, got {type(raw).__name__}")
@@ -291,6 +410,14 @@ def parse_request(payload: dict[str, Any]) -> PaperTradeStepRequest:
orders=orders,
strategy_path=strategy_path,
fee_model=fee_model,
+ interval=_parse_choice(payload.get("interval"), "interval", INTERVALS, DEFAULT_INTERVAL),
+ session=_parse_choice(payload.get("session"), "session", SESSIONS, DEFAULT_SESSION),
+ path_model=_parse_choice(
+ payload.get("path_model"), "path_model", PATH_MODELS, DEFAULT_PATH_MODEL
+ ),
+ fill_model=_parse_choice(
+ payload.get("fill_model"), "fill_model", FILL_MODELS, DEFAULT_FILL_MODEL
+ ),
)
@@ -332,6 +459,33 @@ class RejectedOrder:
detail: str = ""
+@dataclass(frozen=True, slots=True)
+class CanceledOrder:
+ """One pt-v1.2 emergency-cancel row (T3, D2).
+
+ ``reason_code`` is fixed at :data:`CANCELED_REASON_CODE`; it is NOT a
+ member of the frozen ``REASON_CODES`` vocabulary.
+ """
+
+ trade_date: str
+ symbol: str
+ side: str
+ qty: float
+ reason_code: str = CANCELED_REASON_CODE
+ detail: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class SessionEvent:
+ """One pt-v1.2 session fact (T4, D2); ``event_type`` from
+ :data:`SESSION_EVENT_TYPES`."""
+
+ trade_date: str
+ symbol: str
+ event_type: str
+ detail: str = ""
+
+
@dataclass(frozen=True, slots=True)
class NavPoint:
"""One ``nav_series`` row (skipped days produce NO row — R3)."""
@@ -367,7 +521,12 @@ class DataProvenance:
@dataclass(frozen=True, slots=True)
class PaperTradeStepResult:
- """Full success out-param document (AMENDMENT §2.2, pt-v1.1)."""
+ """Full success out-param document (AMENDMENT §2.2; pt-v1.2 additive fields).
+
+ The three pt-v1.2 fields stay at their empty defaults for a v1.1 document
+ and are serialized only when ``schema_version == SCHEMA_VERSION_V1_2``
+ (D8). ``engine_fingerprint`` is required in a v1.2 document (D3).
+ """
account_id: str
market: str
@@ -385,6 +544,9 @@ class PaperTradeStepResult:
)
schema_version: str = SCHEMA_VERSION
tool: str = TOOL_NAME
+ engine_fingerprint: str = ""
+ canceled_orders: tuple[CanceledOrder, ...] = ()
+ events: tuple[SessionEvent, ...] = ()
@dataclass(frozen=True, slots=True)
@@ -406,14 +568,25 @@ class ErrorEnvelope:
# ── Contract schema loading + dependency-free subset validation ──
-def load_contract_schema(name: str = "result") -> dict[str, Any]:
- """Load one named jsonschema from the VD-13 contract file.
+def load_contract_schema(
+ name: str = "result", *, version: str = SCHEMA_VERSION
+) -> dict[str, Any]:
+ """Load one named jsonschema from a VD-13 contract file.
- ``name`` is ``"result"`` (success out-param) or ``"error_envelope"``.
- Read-only; the file is the finalized pt-v1.1 contract (G1 approved
- 2026-10-19).
+ ``name`` is ``"result"`` (success out-param) or ``"error_envelope"``;
+ ``version`` is one of :data:`SCHEMA_VERSIONS` and defaults to the frozen
+ pt-v1.1 file, so every existing caller keeps reading the same document.
+ A v1.1 result validates ONLY against ``version="pt-v1.1"``; a v1.2 result
+ (``engine_fingerprint`` present) validates against ``version="pt-v1.2"``.
+ Read-only.
"""
- document = json.loads(_CONTRACT_SCHEMA_PATH.read_text(encoding="utf-8"))
+ try:
+ path = _CONTRACT_SCHEMA_PATHS[version]
+ except KeyError:
+ raise KeyError(
+ f"unknown contract version {version!r}; available: {list(SCHEMA_VERSIONS)}"
+ ) from None
+ document = json.loads(path.read_text(encoding="utf-8"))
schemas = document.get("schemas", {})
if name not in schemas:
raise KeyError(f"unknown contract schema {name!r}; available: {sorted(schemas)}")
diff --git a/agent/src/tools/paper_trade/state_hash.py b/agent/src/tools/paper_trade/state_hash.py
index 22c68f7ef..3bf8de518 100644
--- a/agent/src/tools/paper_trade/state_hash.py
+++ b/agent/src/tools/paper_trade/state_hash.py
@@ -28,6 +28,12 @@ Canonicalization rules (RFC 8785 JCS as frozen by VD-4):
Determinism: this module reads no clock, no environment, no network and
writes nothing — the same input always produces the same bytes.
+
+pt-v1.2 (D3/D4): :func:`compute_received_state_hash` accepts the four new
+request fields and adds each to the coverage object ONLY when it is
+non-default, so every pt-v1.1 call hashes byte-identically; and
+:func:`engine_fingerprint` hashes the engine-parameter tuple with the same
+JCS helper. Neither function changes matching.
"""
from __future__ import annotations
@@ -38,10 +44,18 @@ import math
from decimal import Decimal
from typing import Any
+from .schema import (
+ DEFAULT_FILL_MODEL,
+ DEFAULT_INTERVAL,
+ DEFAULT_PATH_MODEL,
+ DEFAULT_SESSION,
+)
+
__all__ = [
"canonicalize",
"compute_received_state_hash",
"effective_fee_model",
+ "engine_fingerprint",
"state_hash",
]
@@ -161,14 +175,23 @@ def compute_received_state_hash(
fee_model: Any,
from_date: str,
to_date: str,
+ interval: str = DEFAULT_INTERVAL,
+ session: str = DEFAULT_SESSION,
+ path_model: str = DEFAULT_PATH_MODEL,
+ fill_model: str = DEFAULT_FILL_MODEL,
) -> str:
- """Hash the frozen AM-4-1 coverage object (non-order tool inputs).
+ """Hash the AM-4-1 coverage object plus any non-default pt-v1.2 field.
``fee_model`` must be the EFFECTIVE value (see :func:`effective_fee_model`)
— AM-4-3: the RM dispatch always injects fee_model explicitly, so the hash
covers every non-order parameter.
+
+ D4: the four pt-v1.2 fields enter the coverage object ONLY when explicitly
+ non-default, so a call that omits them (or passes the default value) hashes
+ exactly as pt-v1.1 did. A v1.2 call can never hide a non-default field
+ from the hash.
"""
- coverage = {
+ coverage: dict[str, Any] = {
"account_id": account_id,
"market": market,
"account_state": account_state,
@@ -176,9 +199,51 @@ def compute_received_state_hash(
"from_date": from_date,
"to_date": to_date,
}
+ for key, value, default in (
+ ("interval", interval, DEFAULT_INTERVAL),
+ ("session", session, DEFAULT_SESSION),
+ ("path_model", path_model, DEFAULT_PATH_MODEL),
+ ("fill_model", fill_model, DEFAULT_FILL_MODEL),
+ ):
+ if value != default:
+ coverage[key] = value
return state_hash(coverage)
+def engine_fingerprint(
+ *,
+ interval: str = DEFAULT_INTERVAL,
+ path_model: str = DEFAULT_PATH_MODEL,
+ fill_model: str = DEFAULT_FILL_MODEL,
+ bar_fingerprint: str = "",
+ rules_version: str | None = None,
+) -> str:
+ """D3: ``sha256(JCS({interval, path_model, fill_model, rules_version,
+ bar_fingerprint}))`` as lowercase hex.
+
+ ``bar_fingerprint`` is supplied by the engine (T3/T4) as a hex digest of
+ the bars actually used; ``""`` means no bar fingerprint was supplied (e.g.
+ a cash-only account with no matched bar). ``rules_version`` defaults to
+ :data:`rules.RULES_VERSION` — imported lazily because ``rules`` imports
+ this module — and is injectable so the fingerprint can be audited against
+ a past rule set. No clock, no paths, no environment: the same arguments
+ always produce the same hex string.
+ """
+ if rules_version is None:
+ from .rules import RULES_VERSION
+
+ rules_version = RULES_VERSION
+ return state_hash(
+ {
+ "interval": interval,
+ "path_model": path_model,
+ "fill_model": fill_model,
+ "rules_version": rules_version,
+ "bar_fingerprint": bar_fingerprint,
+ }
+ )
+
+
def effective_fee_model(market: str, fee_model: dict[str, Any] | None = None) -> dict[str, Any]:
"""Return the fee parameters actually in effect for this run (R7-3 echo).
diff --git a/agent/src/tools/paper_trade/strategy_exec.py b/agent/src/tools/paper_trade/strategy_exec.py
index ee7f852ca..2a00552cf 100644
--- a/agent/src/tools/paper_trade/strategy_exec.py
+++ b/agent/src/tools/paper_trade/strategy_exec.py
@@ -408,6 +408,17 @@ class _StrategyDayFailure(RuntimeError):
self.class_name = class_name
+class _UniverseViolation(RuntimeError):
+ # Internal carrier from _execute_days to run_strategy_path; a strategy
+ # order outside the declared 5m UNIVERSE is an authoring error, not a
+ # suspended symbol. The whole call fails in-band before any fill.
+ def __init__(self, day: str, symbols: tuple[str, ...], allowed: Collection[str]) -> None:
+ super().__init__(f"strategy order outside the 5m universe on {day}")
+ self.day = day
+ self.symbols = tuple(symbols)
+ self.allowed = tuple(sorted(allowed))
+
+
def _execute_days(
request: PaperTradeStepRequest,
market_data: data.MarketDataResult,
@@ -417,6 +428,7 @@ def _execute_days(
day_timeout: float,
ctx_symbols: tuple[str, ...],
run_loop: Any,
+ allowed_five: frozenset[str] | None = None,
) -> MatchOutcome:
payload = {
"source": source,
@@ -455,7 +467,12 @@ def _execute_days(
raise _StrategyDayFailure(msg[1], msg[2])
if msg[0] != "day" or msg[1] != day:
raise _StrategyDayFailure(day, StrategyProcessError.__name__)
- return tuple(StrategyOrder(**item) for item in msg[2])
+ orders = tuple(StrategyOrder(**item) for item in msg[2])
+ if allowed_five is not None:
+ outside = sorted({order.symbol for order in orders} - allowed_five)
+ if outside:
+ raise _UniverseViolation(day, tuple(outside), allowed_five)
+ return orders
return run_loop(order_provider=provide_orders)
finally:
if proc.poll() is None:
@@ -532,7 +549,11 @@ def run_strategy_path(
orders_by_day={}, fee_model=request.fee_model,
calendar_client=calendar_client, limits_client=limits_client,
corporate_action_unresolved_by_day=corporate_action_unresolved_by_day,
- hk_lot_sizes=hk_lot_sizes, **kwargs)
+ hk_lot_sizes=hk_lot_sizes,
+ path_model=request.path_model, fill_model=request.fill_model, **kwargs)
+ allowed_five = (
+ frozenset(market_data.five_minute_symbols)
+ if request.interval == "5m" else None)
if days:
# The declared UNIVERSE joins the child's ctx.symbols (sorted union
# with the served universe), extracted from THE SAME single source
@@ -541,7 +562,16 @@ def run_strategy_path(
ctx_symbols = tuple(sorted(set(market_data.symbols) | set(_declared_universe(source))))
try:
return _execute_days(
- request, market_data, days, path, source, day_timeout, ctx_symbols, run_loop)
+ request, market_data, days, path, source, day_timeout, ctx_symbols, run_loop,
+ allowed_five=allowed_five)
+ except _UniverseViolation as violation:
+ message = (
+ f"strategy orders on {', '.join(violation.symbols)} are outside the 5m UNIVERSE "
+ f"({', '.join(violation.allowed) or 'empty'}); declare them in UNIVERSE "
+ "or use interval=1d")
+ logger.warning("paper_trade strategy 5m universe violation on %s: %s",
+ violation.day, message)
+ return _strategy_error(request, market_data, message)
except _StrategyDayFailure as failure:
message = (f"strategy_execution_timeout:{failure.day}"
if failure.class_name is None
diff --git a/agent/src/tools/paper_trade/tool.py b/agent/src/tools/paper_trade/tool.py
index 4e514ac47..88e27bf79 100644
--- a/agent/src/tools/paper_trade/tool.py
+++ b/agent/src/tools/paper_trade/tool.py
@@ -33,7 +33,7 @@ from typing import Any
from src.agent.tools import BaseTool
-from . import data, engine, wire
+from . import data, data_5m, engine, wire
from .calendar import CN_A_MARKET, CalendarUnavailableError, snapshot_calendar
from .data import ClickHouseBarsClient
from .limits_cn_a import ClickHouseLimitsClient
@@ -46,7 +46,30 @@ from .schema import (
logger = logging.getLogger(__name__)
-__all__ = ["PaperTradeStepTool", "run_paper_trade_step"]
+__all__ = ["PaperTradeDocument", "PaperTradeStepTool", "run_paper_trade_step"]
+
+
+class PaperTradeDocument(str):
+ """The in-band result document text, carrying the fetch evidence when any.
+
+ The wire contract is a JSON *string*, and this subclass IS one: ``json.loads``,
+ string equality, indexing and every ``str`` operation see exactly the bytes a
+ plain ``str`` would carry. On the success path it additionally carries the
+ :class:`data.MarketDataResult` that produced it. The runner's default step
+ adapter needs that evidence to write ``steps/<date>/bars/<symbol>.csv``
+ (T5 gap): the wire contract deliberately does not echo bars, and re-fetching
+ them would double the provider cost (``stk_mins`` is capped at 2 calls/day and
+ a refused call still burns the budget — T1). Attaching the already-fetched
+ frame is the only single-fetch path to them.
+
+ A caller that only wants the wire bytes treats this as ``str``; the attribute
+ is additive and never serialized.
+ """
+
+ def __new__(cls, text: str, market_data: Any = None) -> "PaperTradeDocument":
+ document = super().__new__(cls, text)
+ document.market_data = market_data
+ return document
# Sentinel distinguishing "not injected" (resolve for production) from an
# explicit None. It MUST be data._AUTO by identity: run_paper_trade_step
@@ -60,10 +83,12 @@ _DESCRIPTION = (
"Run one deterministic paper-trading step for a single account: a "
"deterministic paper-trading matching engine; never places real orders. "
"Matches the injected orders (or a strategy_path's per-day orders, Step 7) "
- "against daily bars under the market's frozen rules (T+1, price limits, "
+ "against bars under the market's frozen rules (T+1, price limits, "
"board lots, fees), and returns one in-band JSON document — the success "
"result or an AM-5 error envelope (PAPER_DATA_NOT_READY / INVALID_REQUEST) "
- "on the same channel, never a transport error. Research-only."
+ "on the same channel, never a transport error. Optional pt-v1.2 selectors "
+ "(interval/session/path_model/fill_model) default to the pt-v1.1 daily "
+ "behaviour; interval='5m' is cn_a-only. Research-only."
)
@@ -182,7 +207,38 @@ def run_paper_trade_step(
``PAPER_DATA_NOT_READY``). Injection seams (``loader``/``ch_client``/
``calendar_client``/``limits_client``/…) default to ``_AUTO`` production
resolution; tests pass fakes so nothing touches the network.
+
+ The returned :class:`PaperTradeDocument` is the wire string plus the
+ fetched :class:`data.MarketDataResult` (``None`` on every error envelope),
+ so an in-process caller can record the day's bars without a second fetch.
"""
+ document, market_data = _execute_step(
+ payload,
+ loader=loader,
+ ch_client=ch_client,
+ calendar_client=calendar_client,
+ limits_client=limits_client,
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day,
+ hk_lot_sizes=hk_lot_sizes,
+ timeout_seconds=timeout_seconds,
+ orders_at_end=_orders_at_end,
+ )
+ return PaperTradeDocument(document, market_data)
+
+
+def _execute_step(
+ payload: Any,
+ *,
+ loader: Any,
+ ch_client: Any,
+ calendar_client: Any,
+ limits_client: Any,
+ corporate_action_unresolved_by_day: Any,
+ hk_lot_sizes: Any,
+ timeout_seconds: float | None,
+ orders_at_end: bool,
+) -> tuple[str, Any | None]:
+ """The step pipeline: ``(wire document text, fetched market data or None)``."""
raw_payload = payload if isinstance(payload, dict) else {}
# 1. Boundary parse (shape contract). A violation is non-retryable input.
@@ -197,7 +253,7 @@ def run_paper_trade_step(
_as_str(raw_payload.get("to_date")),
str(exc),
raw_payload,
- )
+ ), None
# 2. Semantic gate owned by the tool (schema.py defers it): exactly one of
# orders / strategy_path. ``orders=()`` (empty array) is the valid
@@ -213,7 +269,30 @@ def run_paper_trade_step(
return _error_document(
"INVALID_REQUEST", request.account_id, request.market,
request.from_date, request.to_date, message, raw_payload,
- )
+ ), None
+
+ # 2b. pt-v1.2 cross-field gates (D5). Shape/vocabulary checks already ran
+ # in parse_request; these are the market-combination rules the shape
+ # parser cannot own. Both stay in-band and non-retryable.
+ if request.interval == "5m" and request.market != CN_A_MARKET:
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date,
+ "interval 5m is cn_a-only in pt-v1.2", raw_payload,
+ ), None
+ if request.session == "cn_a" and request.market != CN_A_MARKET:
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date,
+ "session cn_a requires market cn_a in pt-v1.2", raw_payload,
+ ), None
+ if request.interval == "5m" and request.from_date != request.to_date:
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date,
+ "interval 5m supports one trading day per step; the runner advances one day at a time",
+ raw_payload,
+ ), None
# 3. Market data over the frozen window (universe = positions ∪ orders;
# strategy_path mode ALSO unions the strategy file's declared UNIVERSE
@@ -222,32 +301,85 @@ def run_paper_trade_step(
# empty. strategy_universe is a pure AST read (never an execution) and
# degrades to (); the empty-declaration fallback keeps the existing
# behavior and T7's B1 path still owns a genuinely unusable universe.
- # Orders mode never consults it.)
+ # Orders mode never consults it. Every 5m gate below runs BEFORE the
+ # fetch, so a refusal never spends provider budget.)
cal, lim, ch = _resolve_clients(request.market, calendar_client, limits_client, ch_client)
if request.market == CN_A_MARKET and cal is None:
return _error_document(
"PAPER_DATA_NOT_READY", request.account_id, request.market,
request.from_date, request.to_date,
"A-share trading calendar unavailable; configure a reachable ClickHouse trade_calendar and retry",
- raw_payload)
+ raw_payload), None
if request.market == CN_A_MARKET:
try:
cal = snapshot_calendar(cal, request.from_date, request.to_date)
except CalendarUnavailableError as exc:
return _error_document(
"PAPER_DATA_NOT_READY", request.account_id, request.market,
- request.from_date, request.to_date, str(exc), raw_payload)
+ request.from_date, request.to_date, str(exc), raw_payload), None
symbols = data.symbols_for_request(request.account_state, request.orders)
+ declared: tuple[str, ...] = ()
if has_strategy:
from .strategy_exec import strategy_universe
declared = strategy_universe(request.strategy_path or "")
if declared:
symbols = tuple(sorted(set(symbols) | set(declared)))
+ five_minute_symbols = declared
+ else:
+ five_minute_symbols = tuple(
+ dict.fromkeys(order.symbol for order in request.orders or ()))
+ if request.interval == "5m":
+ # 3a. Strategy mode needs an explicit 5m universe. Falling back to the
+ # positions would hide every order the strategy places on a symbol
+ # it does not hold, and a silent empty universe rejects EVERY order
+ # as `suspended` while the step still succeeds (N1). This is the
+ # one place the empty-declaration fallback must not apply.
+ if has_strategy and not declared:
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date,
+ "interval 5m strategy mode requires an explicit non-empty UNIVERSE "
+ "in the strategy source",
+ raw_payload,
+ ), None
+ # 3b. The provider budget, not a nicety: stk_mins is measured at
+ # 1 call/minute, 1/hour and 2 calls/day, and the loader issues one
+ # call per code. A second symbol in the SAME step is rate-limited
+ # immediately (and the refused call still burns the 2/day budget),
+ # so it could never complete on a retry either (N2/F2R3-1).
+ limit = data_5m.MAX_FIVE_MINUTE_SYMBOLS
+ if len(five_minute_symbols) > limit:
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date,
+ f"interval 5m supports at most {limit} "
+ f"symbol{'s' if limit != 1 else ''} per step (measured stk_mins "
+ "budget: 1 call/minute, 1/hour, 2/day); split the orders across "
+ f"steps or use 1d (received {len(five_minute_symbols)}: "
+ f"{', '.join(five_minute_symbols)})",
+ raw_payload,
+ ), None
+ unsupported = [
+ symbol for symbol in five_minute_symbols
+ if not data_5m.is_supported_five_minute_symbol(symbol)
+ ]
+ if unsupported:
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date,
+ f"interval 5m does not support {', '.join(unsupported)}: stk_mins serves cn_a "
+ "stocks only (SH 600/601/603/605/688/689, SZ 000/001/002/003/300/301); "
+ "ETFs, funds and indices have no 5m leg",
+ raw_payload,
+ ), None
try:
market_data = data.fetch_market_data(
request.market, symbols, request.from_date, request.to_date,
loader=loader, ch_client=ch,
+ interval=request.interval,
+ five_minute_symbols=(
+ five_minute_symbols if request.interval == "5m" else None),
)
except ValueError as exc:
# Data-layer input guards (from_date > to_date, unknown market, a
@@ -255,7 +387,20 @@ def run_paper_trade_step(
return _error_document(
"INVALID_REQUEST", request.account_id, request.market,
request.from_date, request.to_date, str(exc), raw_payload,
- )
+ ), None
+ except Exception as exc: # noqa: BLE001 — provider fault (network/quota/permission)
+ # U6: a fetch fault that is NOT an input-contract violation is late
+ # data, never a transport crash and never a halt. The message carries
+ # the exception CLASS only — provider text can embed hosts, quotes and
+ # timings, and the envelope must stay deterministic (VD-7).
+ logger.warning("paper_trade market data fetch failed: %s", type(exc).__name__)
+ return _error_document(
+ "PAPER_DATA_NOT_READY", request.account_id, request.market,
+ request.from_date, request.to_date,
+ f"market data fetch failed ({type(exc).__name__}); the step is data-not-ready, "
+ "retry later",
+ raw_payload,
+ ), None
# 4. Mode dispatch. strategy_exec is T7 and imported lazily so this module
# stays importable (and the agent registry stays buildable) while T7 is
@@ -272,7 +417,7 @@ def run_paper_trade_step(
hk_lot_sizes=hk_lot_sizes,
timeout_seconds=timeout_seconds,
)
- elif _orders_at_end:
+ elif orders_at_end:
# Saved accounts must scan every intervening day, including actions,
# while applying explicit orders only at the chosen execution close.
outcome = engine.run_day_loop(
@@ -280,7 +425,8 @@ def run_paper_trade_step(
from_date=request.from_date, to_date=request.to_date, market_data=market_data,
orders_by_day={request.to_date: request.orders or ()}, fee_model=request.fee_model,
calendar_client=cal, limits_client=lim, hk_lot_sizes=hk_lot_sizes,
- corporate_action_unresolved_by_day=corporate_action_unresolved_by_day)
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day,
+ path_model=request.path_model, fill_model=request.fill_model)
else:
outcome = engine.match_orders(
request,
@@ -297,11 +443,11 @@ def run_paper_trade_step(
return _error_document(
outcome.error.code, request.account_id, request.market,
request.from_date, request.to_date, outcome.error.message, raw_payload,
- )
+ ), None
result = wire.assemble_result(
request, outcome, raw_account_state=raw_payload.get("account_state")
)
- return wire.dumps_payload(wire.build_success_payload(result))
+ return wire.dumps_payload(wire.build_success_payload(result)), market_data
class PaperTradeStepTool(BaseTool):
@@ -369,6 +515,43 @@ class PaperTradeStepTool(BaseTool):
"(AM-4-3: RM always injects it explicitly)."
),
},
+ "interval": {
+ "type": "string",
+ "enum": ["1d", "5m"],
+ "default": "1d",
+ "description": (
+ "Optional pt-v1.2 bar interval. '1d' (default) keeps the pt-v1.1 "
+ "daily close-price path; '5m' is cn_a-only and matches the whole "
+ "continuous session as one bar (D1)."
+ ),
+ },
+ "session": {
+ "type": "string",
+ "enum": ["auto", "cn_a"],
+ "default": "auto",
+ "description": (
+ "Optional pt-v1.2 session selector. 'auto' resolves to cn_a for "
+ "market=cn_a and is inert for hk/us; 'cn_a' requires market=cn_a (D5)."
+ ),
+ },
+ "path_model": {
+ "type": "string",
+ "enum": ["bar_median", "bar_close"],
+ "default": "bar_median",
+ "description": (
+ "Optional pt-v1.2 reference-price model for interval='5m': "
+ "median(open, high, low, close) or the bar close (D1). Ignored for '1d'."
+ ),
+ },
+ "fill_model": {
+ "type": "string",
+ "enum": ["all_or_none"],
+ "default": "all_or_none",
+ "description": (
+ "Optional pt-v1.2 fill model: 'all_or_none' is the only P0 value — "
+ "no partial fills, every order terminal in its bar."
+ ),
+ },
},
"required": ["account_id", "market", "account_state", "from_date", "to_date"],
}
diff --git a/agent/src/tools/paper_trade/wire.py b/agent/src/tools/paper_trade/wire.py
index f520cd2c9..31102cb87 100644
--- a/agent/src/tools/paper_trade/wire.py
+++ b/agent/src/tools/paper_trade/wire.py
@@ -25,6 +25,13 @@ Frozen surfaces implemented here:
=False`` + ``allow_nan=False``: byte-deterministic strict JSON, no
timestamps anywhere (VD-7), NaN/Infinity refused.
+pt-v1.2 (D8) is additive and version-gated: a request whose four new fields
+are all at their defaults produces the pt-v1.1 document with the v1.2 keys
+ABSENT (not empty), while a request with at least one non-default field emits
+``schema_version="pt-v1.2"`` plus ``engine_fingerprint``, ``canceled_orders``
+and ``events``. AM-4-4's error-path hash follows the same rule: the new
+fields join the coverage object only when non-default (D4).
+
Determinism (R1-1): no clock, no randomness, no I/O — every input injected.
"""
@@ -32,12 +39,26 @@ from __future__ import annotations
import json
import math
+import re
from dataclasses import replace
from typing import TYPE_CHECKING, Any
+from . import state_hash
from .schema import (
+ CANCELED_REASON_CODE,
+ DEFAULT_FILL_MODEL,
+ DEFAULT_INTERVAL,
+ DEFAULT_PATH_MODEL,
+ DEFAULT_SESSION,
ERROR_CODES,
+ FILL_MODELS,
+ INTERVALS,
MARKETS,
+ PATH_MODELS,
+ SCHEMA_VERSIONS,
+ SCHEMA_VERSION_V1_2,
+ SESSION_EVENT_TYPES,
+ SESSIONS,
DateRange,
ErrorEnvelope,
PaperTradeSchemaError,
@@ -82,16 +103,41 @@ def strategy_fill_reason(reason: str | None) -> str:
return reason[:FILL_REASON_MAX_CHARS]
+def _payload_choices(payload: dict[str, Any]) -> dict[str, str] | None:
+ """Read the four pt-v1.2 request enums from a raw payload, or ``None``.
+
+ Absent/null is the default (D8). A present non-string or out-of-vocabulary
+ value makes the AM-4-4 coverage object not computable, exactly like a
+ malformed fee_model.
+ """
+ choices: dict[str, str] = {}
+ for key, allowed, default in (
+ ("interval", INTERVALS, DEFAULT_INTERVAL),
+ ("session", SESSIONS, DEFAULT_SESSION),
+ ("path_model", PATH_MODELS, DEFAULT_PATH_MODEL),
+ ("fill_model", FILL_MODELS, DEFAULT_FILL_MODEL),
+ ):
+ value = payload.get(key)
+ if value is None:
+ value = default
+ elif not isinstance(value, str) or value not in allowed:
+ return None
+ choices[key] = value
+ return choices
+
+
def received_state_hash_from_payload(payload: Any) -> str | None:
"""AM-4-4: hash the raw coverage fields, or ``None`` when not computable.
Not computable = the received ``account_state`` fails the shape parse, or
the coverage object cannot be extracted (account_id/from_date/to_date not
- strings, market outside the frozen enum, malformed fee_model). The error
- envelope then OMITS ``received_state_hash`` — RM reads the absence as
- "state unparseable" and must not burn its retry chain on a corrupt
- snapshot. The hash covers the RAW ``account_state`` value (see the module
- docstring) with the effective fee model merged over the market defaults.
+ strings, market outside the frozen enum, malformed fee_model, or a pt-v1.2
+ field that is present but outside its vocabulary). The error envelope then
+ OMITS ``received_state_hash`` — RM reads the absence as "state unparseable"
+ and must not burn its retry chain on a corrupt snapshot. The hash covers
+ the RAW ``account_state`` value (see the module docstring) with the
+ effective fee model merged over the market defaults; non-default pt-v1.2
+ fields join the coverage object (D4).
"""
if not isinstance(payload, dict):
return None
@@ -116,6 +162,9 @@ def received_state_hash_from_payload(payload: Any) -> str | None:
fee_model_raw = {}
if not isinstance(fee_model_raw, dict):
return None
+ choices = _payload_choices(payload)
+ if choices is None:
+ return None
fee_model: dict[str, float] = {}
for key, value in fee_model_raw.items():
if not isinstance(key, str):
@@ -137,6 +186,7 @@ def received_state_hash_from_payload(payload: Any) -> str | None:
fee_model=effective_fee_model(market, fee_model),
from_date=from_date,
to_date=to_date,
+ **choices,
)
except (TypeError, ValueError):
# The raw state passed the shape parse but is not JCS-canonicalizable
@@ -159,6 +209,12 @@ def assemble_result(
would launder LLM-introduced keys past the RM verification (AM-4-1).
The hash and the echo share ``outcome.effective_fee_model`` so the
covered fee model and the disclosed fee model cannot diverge.
+
+ The pt-v1.2 out-params are read with ``getattr`` defaults so this builder
+ works before T3/T4 populate ``MatchOutcome``. A v1.2 request whose
+ outcome carries no ``engine_fingerprint`` gets the D3 fingerprint of the
+ declared engine parameters with an empty bar fingerprint (no bar evidence
+ claimed); a v1.1 request never carries any of the three fields (D8).
"""
if outcome.error is not None:
raise ValueError(
@@ -172,7 +228,24 @@ def assemble_result(
fee_model=outcome.effective_fee_model,
from_date=request.from_date,
to_date=request.to_date,
+ interval=request.interval,
+ session=request.session,
+ path_model=request.path_model,
+ fill_model=request.fill_model,
)
+ version = request.schema_version
+ if request.uses_v1_2:
+ fingerprint = getattr(outcome, "engine_fingerprint", "")
+ if not fingerprint:
+ fingerprint = state_hash.engine_fingerprint(
+ interval=request.interval,
+ path_model=request.path_model,
+ fill_model=request.fill_model,
+ )
+ canceled_orders = tuple(getattr(outcome, "canceled_orders", ()))
+ events = tuple(getattr(outcome, "events", ()))
+ else:
+ fingerprint, canceled_orders, events = "", (), ()
return PaperTradeStepResult(
account_id=request.account_id,
market=request.market,
@@ -188,6 +261,10 @@ def assemble_result(
data_provenance=replace(
outcome.data_provenance, limit_provenance=tuple(outcome.limit_provenance)
),
+ schema_version=version,
+ engine_fingerprint=fingerprint,
+ canceled_orders=canceled_orders,
+ events=events,
)
@@ -207,14 +284,71 @@ def _provenance_payload(result: PaperTradeStepResult) -> dict[str, Any]:
return payload
+#: D3: the fingerprint is sha256 hex, always 64 lowercase characters.
+_FINGERPRINT_RE = re.compile(r"^[0-9a-f]{64}$")
+
+
+def _canceled_payload(orders: tuple[Any, ...]) -> list[dict[str, Any]]:
+ """Serialize ``canceled_orders``, failing closed on the frozen token."""
+ rows: list[dict[str, Any]] = []
+ for row in orders:
+ if row.reason_code != CANCELED_REASON_CODE:
+ raise ValueError(
+ f"canceled reason_code must be {CANCELED_REASON_CODE!r}, "
+ f"got {row.reason_code!r}"
+ )
+ rows.append(
+ {
+ "trade_date": row.trade_date,
+ "symbol": row.symbol,
+ "side": row.side,
+ "qty": row.qty,
+ "reason_code": row.reason_code,
+ "detail": row.detail,
+ }
+ )
+ return rows
+
+
+def _events_payload(events: tuple[Any, ...]) -> list[dict[str, Any]]:
+ """Serialize ``events``, failing closed on an unknown ``event_type``."""
+ rows: list[dict[str, Any]] = []
+ for event in events:
+ if event.event_type not in SESSION_EVENT_TYPES:
+ raise ValueError(
+ f"event_type {event.event_type!r} is outside the pt-v1.2 "
+ f"vocabulary {SESSION_EVENT_TYPES}"
+ )
+ rows.append(
+ {
+ "trade_date": event.trade_date,
+ "symbol": event.symbol,
+ "event_type": event.event_type,
+ "detail": event.detail,
+ }
+ )
+ return rows
+
+
def build_success_payload(result: PaperTradeStepResult) -> dict[str, Any]:
"""Serialize the success document (AMENDMENT §2.2 wire shape).
``range.from_`` maps to the wire key ``"from"``; optional provenance
fields are omitted (never null) when unset; arrays keep the engine's
frozen order (VD-10: day-ascending, then input index).
+
+ The three pt-v1.2 keys are emitted ONLY when ``schema_version`` is
+ ``pt-v1.2`` (D8), so the pt-v1.1 byte stream is untouched. A v1.2
+ document without a 64-hex fingerprint, with a cancel token other than the
+ frozen one, or with an unknown event type raises (engine bug / transport
+ class), never shipping a document RM cannot verify.
"""
- return {
+ if result.schema_version not in SCHEMA_VERSIONS:
+ raise ValueError(
+ f"unknown schema_version {result.schema_version!r}; "
+ f"expected one of {SCHEMA_VERSIONS}"
+ )
+ payload: dict[str, Any] = {
"schema_version": result.schema_version,
"tool": result.tool,
"account_id": result.account_id,
@@ -267,6 +401,16 @@ def build_success_payload(result: PaperTradeStepResult) -> dict[str, Any]:
"warnings": list(result.warnings),
"data_provenance": _provenance_payload(result),
}
+ if result.schema_version == SCHEMA_VERSION_V1_2:
+ if not _FINGERPRINT_RE.match(result.engine_fingerprint):
+ raise ValueError(
+ "a pt-v1.2 result requires a 64-character lowercase hex "
+ f"engine_fingerprint (D3), got {result.engine_fingerprint!r}"
+ )
+ payload["engine_fingerprint"] = result.engine_fingerprint
+ payload["canceled_orders"] = _canceled_payload(result.canceled_orders)
+ payload["events"] = _events_payload(result.events)
+ return payload
def build_error_payload(envelope: ErrorEnvelope) -> dict[str, Any]:
diff --git a/schema/tool_contracts/paper_trade_step-v1.2.json b/schema/tool_contracts/paper_trade_step-v1.2.json
new file mode 100644
index 000000000..d691135ac
--- /dev/null
+++ b/schema/tool_contracts/paper_trade_step-v1.2.json
@@ -0,0 +1,319 @@
+{
+ "$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.",
+ "contract": "paper_trade_step",
+ "version": "pt-v1.2",
+ "status": "final",
+ "schemas": {
+ "result": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.2/result.json",
+ "title": "paper_trade_step success result (pt-v1.2)",
+ "type": "object",
+ "required": [
+ "schema_version",
+ "tool",
+ "account_id",
+ "market",
+ "range",
+ "received_state_hash",
+ "effective_fee_model",
+ "fills",
+ "rejected_orders",
+ "end_state",
+ "nav_series",
+ "skipped_days",
+ "warnings",
+ "data_provenance"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "schema_version": {
+ "type": "string",
+ "enum": ["pt-v1.1", "pt-v1.2"],
+ "$comment": "Which version a response emits: 'pt-v1.1' when every new request field is at its default (byte-identical to the frozen v1.1 document, no v1.2 keys at all); 'pt-v1.2' when at least one new request field is non-default (D8). A 'pt-v1.1' document remains governed by paper_trade_step-v1.1.json."
+ },
+ "tool": { "type": "string", "const": "paper_trade_step" },
+ "account_id": {
+ "type": "string",
+ "minLength": 1,
+ "$comment": "verbatim echo of the input (R4)"
+ },
+ "market": {
+ "type": "string",
+ "enum": ["cn_a", "hk", "us"]
+ },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "sha256(JCS(non-order inputs)) — AM-4/R7; 64 lowercase hex. The four new request fields enter the coverage object ONLY when non-default (D4), so a v1.1 call hashes exactly as before."
+ },
+ "effective_fee_model": {
+ "type": "object",
+ "$comment": "Full echo of the fee parameters in effect (R7-3). Default key names FROZEN per APPROVAL note 5 / REQUIREMENTS §4 (state_hash.py _DEFAULT_FEE_MODELS, delivery note #7): cn_a = commission_rate 0.00025, commission_min 5.0, stamp_tax_sell 0.0005, transfer_fee 0.00001; hk = commission_rate 0.0003, commission_min 3.0, stamp_tax_rate 0.001, regulatory_levy_rate 0.00003; us = commission_per_share 0.0049, commission_min 0.99, sec_fee_rate 0.0. Per-key merge: RM always injects fee_model explicitly (AM-4-3) and injected keys pass through, so the object stays open by design."
+ },
+ "fills": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "price", "fee", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": {
+ "type": "string",
+ "enum": ["buy", "sell"]
+ },
+ "qty": { "type": "number" },
+ "price": { "type": "number" },
+ "fee": { "type": "number" },
+ "reason": {
+ "type": "string",
+ "$comment": "VD-15: orders mode = empty string; strategy_path mode = strategy reason text truncated to <=200 chars (UTF-8 safe)"
+ }
+ }
+ }
+ },
+ "rejected_orders": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "reason_code", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": {
+ "type": "string",
+ "enum": ["buy", "sell"]
+ },
+ "qty": { "type": "number" },
+ "reason_code": {
+ "type": "string",
+ "enum": [
+ "insufficient_cash",
+ "insufficient_position",
+ "t_plus_1",
+ "limit_up",
+ "limit_down",
+ "suspended",
+ "lot_size",
+ "non_trading_day",
+ "unknown_symbol",
+ "corporate_action_unresolved",
+ "limit_not_marketable"
+ ],
+ "$comment": "AM-14 closed vocabulary (11) — FROZEN, unchanged by pt-v1.2 (D2): the emergency-cancel event lives in canceled_orders, never here"
+ },
+ "detail": { "type": "string" }
+ }
+ }
+ },
+ "canceled_orders": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "reason_code", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": {
+ "type": "string",
+ "enum": ["buy", "sell"]
+ },
+ "qty": { "type": "number" },
+ "reason_code": {
+ "type": "string",
+ "const": "canceled_after_failed_match",
+ "$comment": "T3 emergency cancel: one row per failed order in 5m mode (D2). Never added to the frozen rejected_orders vocabulary."
+ },
+ "detail": { "type": "string" }
+ }
+ },
+ "$comment": "pt-v1.2 only. Emitted (possibly empty) for a v1.2 call; omitted entirely for a pt-v1.1 call, which stays byte-identical (D2/D8)."
+ },
+ "events": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "event_type", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "event_type": {
+ "type": "string",
+ "enum": ["non_trading_day", "halted", "price_limit", "auction_window"],
+ "$comment": "Session facts (T4, D2). halted = calendar says open, the 5m fetch succeeded, another symbol has bars that day, and this symbol has zero bars for the session (D6)."
+ },
+ "detail": { "type": "string" }
+ }
+ },
+ "$comment": "pt-v1.2 only. Emitted (possibly empty) for a v1.2 call; omitted entirely for a pt-v1.1 call (D2/D8)."
+ },
+ "end_state": {
+ "type": "object",
+ "required": ["cash", "positions"],
+ "additionalProperties": false,
+ "properties": {
+ "cash": { "type": "number" },
+ "positions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "qty", "avg_cost"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "qty": { "type": "number" },
+ "avg_cost": { "type": "number" }
+ }
+ }
+ }
+ }
+ },
+ "nav_series": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "nav", "cash", "position_value"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "nav": { "type": "number" },
+ "cash": { "type": "number" },
+ "position_value": { "type": "number" }
+ }
+ }
+ },
+ "skipped_days": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "reason": {
+ "type": "string",
+ "enum": ["non_trading_day", "market_closed_inferred"],
+ "$comment": "AM-14 closed vocabulary (2): non_trading_day = cn_a only (CH calendar truth); market_closed_inferred = hk/us only, always accompanied by a warning (AM-6)"
+ }
+ }
+ }
+ },
+ "warnings": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "deterministic English strings, never contain timestamps (VD-7 / R1 hard semantics 1)"
+ },
+ "data_provenance": {
+ "type": "object",
+ "required": ["source"],
+ "additionalProperties": false,
+ "properties": {
+ "source": {
+ "type": "string",
+ "$comment": "AM-9 merged-frame form for cn_a, e.g. 'clickhouse+tencent(merged)'"
+ },
+ "ch_as_of": { "type": "string" },
+ "network_as_of": { "type": "string" },
+ "bars_as_of": { "type": "string" },
+ "corporate_actions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "date", "ratio", "detected"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "date": { "type": "string" },
+ "ratio": {
+ "type": "string",
+ "$comment": "clean hit = ratio label (e.g. '4:1'); unresolved = the observed close-to-close ratio as a decimal string (fail-closed fact, never a guess)"
+ },
+ "detected": {
+ "type": "boolean",
+ "$comment": "true = clean split applied; false = unresolved fail-closed rejection (corporate_action_unresolved). Typed to match the T4 emitter (corporate_actions.py); reconciled from the draft's string typing at G1 finalization as its module docstring assigned to T5"
+ }
+ }
+ }
+ },
+ "limit_provenance": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "VD-11 cn_a limit/ST/suspension path tokens, '<symbol>@<date>:<token>' — token set frozen (limits_cn_a.py): limits:stk_limit / limits:heuristic / limits:unavailable / st:stk_st_daily / st:stk_st_daily-no-row / suspend:stk_suspend / suspend:stk_suspend-no-row / limit_list:stk_limit_list_d. Present only for cn_a runs that consulted the band seam"
+ }
+ },
+ "$comment": "Extension set FINALIZED at G1 (was draft-open): AM-9 merge-state fields (ch_as_of/network_as_of/bars_as_of), T4 corporate_actions, VD-11 limit_provenance. Optional fields are omitted when unset, never null. Unchanged by pt-v1.2."
+ },
+ "engine_fingerprint": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{64}$",
+ "$comment": "Required in a pt-v1.2 document (D3/D8): sha256(JCS({interval, path_model, fill_model, rules_version, bar_fingerprint})) as lowercase hex. No paths, no clock, no dict iteration order. Out field only — it never changes matching. bar_fingerprint is supplied by the engine (T3/T4); '' means no bar fingerprint was supplied (e.g. a cash-only account)."
+ }
+ },
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "schema_version": { "const": "pt-v1.2" }
+ },
+ "required": ["schema_version"]
+ },
+ "then": {
+ "required": ["engine_fingerprint", "canceled_orders", "events"]
+ },
+ "$comment": "Version-gated requirement: engine_fingerprint/canceled_orders/events are mandatory ONLY for a pt-v1.2 document, so a pt-v1.1-labelled document stays valid under this additive file (it is governed by paper_trade_step-v1.1.json). The dependency-free validator in agent/src/tools/paper_trade/schema.py deliberately ignores if/then/allOf (it implements a keyword subset); wire.build_success_payload enforces the same rule in Python — it raises unless a pt-v1.2 fingerprint is 64 lowercase hex and always emits canceled_orders/events for a v1.2 result."
+ }
+ ]
+ },
+ "error_envelope": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.2/error_envelope.json",
+ "title": "paper_trade_step in-band error envelope (pt-v1.2, AM-5)",
+ "type": "object",
+ "required": ["status", "code", "account_id", "market", "range", "message"],
+ "additionalProperties": false,
+ "properties": {
+ "status": { "type": "string", "const": "error" },
+ "code": {
+ "type": "string",
+ "enum": ["PAPER_DATA_NOT_READY", "INVALID_REQUEST"],
+ "$comment": "AM-14 closed vocabulary (2 + transport reserved): PAPER_DATA_NOT_READY = retryable (RM 30min x 3); INVALID_REQUEST = non-retryable. Transport-level MCP errors are reserved for engine-internal faults. Unchanged by pt-v1.2."
+ },
+ "account_id": { "type": "string", "$comment": "verbatim echo even on the error path (AM-4-4/AM-5)" },
+ "market": {
+ "type": "string",
+ "enum": ["cn_a", "hk", "us"]
+ },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "present only when the received account_state was parseable (AM-4-4); omitted otherwise, never null — RM reads the absence as 'state unparseable' and must not burn its retry chain"
+ },
+ "message": {
+ "type": "string",
+ "$comment": "deterministic English, no timestamps (VD-7). Frozen formats include strategy_execution_timeout:{YYYY-MM-DD} and strategy_execution_error:{YYYY-MM-DD}:{exception class} (VD-8/B1, Step 7). pt-v1.2 adds 'interval 5m is cn_a-only in pt-v1.2' and the cn_a session gate."
+ }
+ }
+ }
+ }
+}