"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
test(paper-trade): cover the pt-v1.2 5m step, its fixtures and contract
shadowinlife528eb183fe0b
diff --git a/agent/tests/fixtures/paper_trade/5m/000001.SZ/2026-10-19.csv b/agent/tests/fixtures/paper_trade/5m/000001.SZ/2026-10-19.csvnew file mode 100644index 000000000..3b58e9fa6--- /dev/null+++ b/agent/tests/fixtures/paper_trade/5m/000001.SZ/2026-10-19.csv@@ -0,0 +1,50 @@+bar_time,open,high,low,close,volume+2026-10-19 09:30:00,10.00,10.00,10.00,10.00,250000+2026-10-19 09:35:00,10.00,10.00,10.00,10.00,500000+2026-10-19 09:40:00,10.00,10.00,10.00,10.00,500000+2026-10-19 09:45:00,10.00,10.00,10.00,10.00,500000+2026-10-19 09:50:00,10.00,10.00,10.00,10.00,500000+2026-10-19 09:55:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:00:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:05:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:10:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:15:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:20:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:25:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:30:00,10.00,10.05,10.00,10.00,500000+2026-10-19 10:35:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:40:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:45:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:50:00,10.00,10.00,10.00,10.00,500000+2026-10-19 10:55:00,10.00,10.00,10.00,10.00,500000+2026-10-19 11:00:00,10.00,10.00,10.00,10.00,500000+2026-10-19 11:05:00,10.00,10.00,10.00,10.00,500000+2026-10-19 11:10:00,10.00,10.00,10.00,10.00,500000+2026-10-19 11:15:00,10.00,10.00,10.00,10.00,500000+2026-10-19 11:20:00,10.00,10.00,10.00,10.00,500000+2026-10-19 11:25:00,10.00,10.00,10.00,10.00,500000+2026-10-19 11:30:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:05:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:10:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:15:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:20:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:25:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:30:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:35:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:40:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:45:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:50:00,10.00,10.00,10.00,10.00,500000+2026-10-19 13:55:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:00:00,10.00,10.00,9.98,10.00,500000+2026-10-19 14:05:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:10:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:15:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:20:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:25:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:30:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:35:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:40:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:45:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:50:00,10.00,10.00,10.00,10.00,500000+2026-10-19 14:55:00,10.00,10.00,10.00,10.00,500000+2026-10-19 15:00:00,10.00,10.02,10.00,10.02,500000diff --git a/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-16.csv b/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-16.csvnew file mode 100644index 000000000..f1531b167--- /dev/null+++ b/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-16.csv@@ -0,0 +1,50 @@+bar_time,open,high,low,close,volume+2026-10-16 09:30:00,1418.00,1418.00,1418.00,1418.00,60000+2026-10-16 09:35:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 09:40:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 09:45:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 09:50:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 09:55:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:00:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:05:00,1419.00,1421.00,1419.00,1419.00,120000+2026-10-16 10:10:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:15:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:20:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:25:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:30:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:35:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:40:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:45:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:50:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 10:55:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 11:00:00,1419.00,1419.00,1417.00,1419.00,120000+2026-10-16 11:05:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 11:10:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 11:15:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 11:20:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 11:25:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 11:30:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:05:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:10:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:15:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:20:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:25:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:30:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:35:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:40:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:45:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:50:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 13:55:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:00:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:05:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:10:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:15:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:20:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:25:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:30:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:35:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:40:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:45:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:50:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 14:55:00,1419.00,1419.00,1419.00,1419.00,120000+2026-10-16 15:00:00,1419.00,1420.00,1419.00,1420.00,120000diff --git a/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-19.csv b/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-19.csvnew file mode 100644index 000000000..604bf11d6--- /dev/null+++ b/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-19.csv@@ -0,0 +1 @@+bar_time,open,high,low,close,volumediff --git a/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-20.csv b/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-20.csvnew file mode 100644index 000000000..4a92a8dc7--- /dev/null+++ b/agent/tests/fixtures/paper_trade/5m/600519.SH/2026-10-20.csv@@ -0,0 +1,50 @@+bar_time,open,high,low,close,volume+2026-10-20 09:30:00,1423.00,1423.00,1423.00,1423.00,48000+2026-10-20 09:35:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 09:40:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 09:45:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 09:50:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 09:55:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:00:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:05:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:10:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:15:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:20:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:25:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:30:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:35:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:40:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:45:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:50:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 10:55:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 11:00:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 11:05:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 11:10:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 11:15:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 11:20:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 11:25:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 11:30:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:05:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:10:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:15:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:20:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:25:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:30:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:35:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:40:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:45:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:50:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 13:55:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:00:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:05:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:10:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:15:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:20:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:25:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:30:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:35:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:40:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:45:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:50:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 14:55:00,1421.00,1421.00,1421.00,1421.00,120000+2026-10-20 15:00:00,1422.00,1422.00,1422.00,1422.00,120000diff --git a/agent/tests/fixtures/paper_trade/5m/MANIFEST.json b/agent/tests/fixtures/paper_trade/5m/MANIFEST.jsonnew file mode 100644index 000000000..89ae8f08c--- /dev/null+++ b/agent/tests/fixtures/paper_trade/5m/MANIFEST.json@@ -0,0 +1,87 @@+{+ "schema": "paper_trade.five_minute_fixture_manifest/v1",+ "description": "Synthetic cn_a 5-minute bar fixtures for the pt-v1.2 paper-trade tests. Every file here is AUTHORED, not recorded from a provider: the live stk_mins probe (T1) supplied the SHAPE (49 raw rows per session = 09:30 opening-auction print + 48 continuous bars, labels are bar ENDS, volume in shares), and the prices are synthetic. Tests must never present these numbers as market data. sha256 is of the exact on-disk bytes; test_paper_trade_5m_golden.py re-verifies them and fails when a fixture changes without this manifest.",+ "conventions": {+ "columns": [+ "bar_time",+ "open",+ "high",+ "low",+ "close",+ "volume"+ ],+ "label_semantics": "bar END in Asia/Shanghai wall clock (09:35 covers 09:30-09:35)",+ "auction_row": "the 09:30 row is the opening call-auction print and is excluded from the matched session bar",+ "continuous_bars_per_day": 48,+ "volume_unit": "shares (5m caliber, T1) - the derived daily frame divides by 100 to reach lots",+ "empty_day_sentinel": "a header-only CSV is a zero-bar session, not a missing fixture"+ },+ "fixtures": [+ {+ "file": "600519.SH/2026-10-16.csv",+ "symbol": "600519.SH",+ "trade_date": "2026-10-16",+ "kind": "normal",+ "rows": 49,+ "continuous_rows": 48,+ "session_bar": {+ "open": 1419.0,+ "high": 1421.0,+ "low": 1417.0,+ "close": 1420.0,+ "volume": 5760000.0+ },+ "sha256": "856310b990402645d3a317183fddc96015690b35b076160eb2f8020214c382da",+ "bytes": 2926,+ "construction": "09:30 opening-auction print at 1418.00 (single price, matches the daily open); 48 continuous bars at 1419.00 with a 1421.00 high at 10:05, a 1417.00 low at 11:00 and a 1420.00 close at 15:00; volume 120000 shares per continuous bar. Provides the previous close for the 2026-10-20 price-limit band and the carry-forward mark for the 2026-10-19 halt."+ },+ {+ "file": "600519.SH/2026-10-19.csv",+ "symbol": "600519.SH",+ "trade_date": "2026-10-19",+ "kind": "halted",+ "rows": 0,+ "continuous_rows": 0,+ "session_bar": null,+ "sha256": "450689727ec7fa6c04ba4309b4dcbf094e96e04a34e4bb10432baa9bb9f22be9",+ "bytes": 36,+ "construction": "Header-only file: the documented zero-bar sentinel for a suspended session (T1: a suspended day is absent from BOTH the daily and the 5m endpoint). Readers must treat it as zero bars, never as a missing fixture."+ },+ {+ "file": "600519.SH/2026-10-20.csv",+ "symbol": "600519.SH",+ "trade_date": "2026-10-20",+ "kind": "normal",+ "rows": 49,+ "continuous_rows": 48,+ "session_bar": {+ "open": 1421.0,+ "high": 1422.0,+ "low": 1421.0,+ "close": 1422.0,+ "volume": 5760000.0+ },+ "sha256": "f453ab6fadd19a7d9f2cc5894374d99b85d240dbccf900a77492158f157d164a",+ "bytes": 2926,+ "construction": "09:30 opening-auction print at 1423.00 (single price, equals the daily open); 48 continuous bars at 1421.00 with a 1422.00 close at 15:00; volume 120000 shares per continuous bar."+ },+ {+ "file": "000001.SZ/2026-10-19.csv",+ "symbol": "000001.SZ",+ "trade_date": "2026-10-19",+ "kind": "normal",+ "rows": 49,+ "continuous_rows": 48,+ "session_bar": {+ "open": 10.0,+ "high": 10.05,+ "low": 9.98,+ "close": 10.02,+ "volume": 24000000.0+ },+ "sha256": "38bbc01c64a1c70513160aca54b96104b91cc31d777a9303d9d9bdb6fca0a10d",+ "bytes": 2534,+ "construction": "Witness session for the halted-day case: 09:30 auction print at 10.00 plus 48 continuous bars around 10.00 (high 10.05 at 10:30, low 9.98 at 14:00, close 10.02 at 15:00), volume 500000 shares per continuous bar. Its presence keeps the 2026-10-19 whole-universe check from collapsing a one-symbol halt into PAPER_DATA_NOT_READY (D6)."+ }+ ]+}diff --git a/agent/tests/paper_trade_5m_fixtures.py b/agent/tests/paper_trade_5m_fixtures.pynew file mode 100644index 000000000..f5464b242--- /dev/null+++ b/agent/tests/paper_trade_5m_fixtures.py@@ -0,0 +1,329 @@+"""Offline dual-leg market data for the cn_a 5m paper-trade tests (T6).++ONE loader serves both legs the engine needs, from the committed CSV fixtures+under ``agent/tests/fixtures/paper_trade/5m/<symbol>/<date>.csv``:++* ``interval="5m"`` returns the raw day files (49 rows: the 09:30 opening+ call-auction print plus 48 continuous bars, labels are bar ENDS).+* every other interval returns a DAILY frame DERIVED from the same session+ bars (open = first continuous open, high/low = session extremes, close =+ last continuous close, volume = the 5m share volume / 100 to reach the+ daily frame's lot unit, T1).++Deriving the daily leg instead of authoring a second fixture keeps the two+legs mutually consistent by construction, which matters because the engine+treats "daily bar present XOR 5m session bar present" as a provider fault+(D6). A header-only CSV is the zero-bar sentinel for a suspended session, so+a halted symbol has neither leg - exactly what Tushare serves (T1: suspended+days are absent from BOTH endpoints).++The fixtures are SYNTHETIC (see ``MANIFEST.json``); no test may present their+prices as market data. No network, no clock, no writes.++The module also hosts the shared step harness for the three 5m tool suites+(``test_paper_trade_5m_tool``, ``test_paper_trade_5m_scope``,+``test_paper_trade_5m_strategy``): the seed constants, the payload builders,+and the strategy-file helpers, so a split suite cannot drift apart.+"""++from __future__ import annotations++import json+import re+from decimal import ROUND_HALF_UP, Decimal+from pathlib import Path+from typing import Any, Iterable, Mapping, Sequence++import pandas as pd++from src.config.paths import get_runtime_root+from src.tools.paper_trade.tool import run_paper_trade_step++FIXTURE_ROOT = Path(__file__).parent / "fixtures" / "paper_trade" / "5m"++OHLCV: tuple[str, ...] = ("open", "high", "low", "close", "volume")+AUCTION_LABEL = "09:30"+_VOLUME_LOTS_PER_SHARE = 100.0++__all__ = [+ "AUCTION_LABEL",+ "FIXTURE_ROOT",+ "FixtureCalendar",+ "FixtureLoader",+ "continuous_bars",+ "derive_daily",+ "fixture_files",+ "fixture_manifest",+ "fixture_reference",+ "fixture_days",+ "load_5m",+ "load_5m_all",+ "session_values",+]+++def fixture_manifest() -> dict[str, Any]:+ """The fixture index (synthetic provenance, conventions, per-file digests)."""+ return json.loads((FIXTURE_ROOT / "MANIFEST.json").read_text(encoding="utf-8"))+++def fixture_files() -> tuple[Path, ...]:+ """Every committed 5m fixture, symbol-major then day-ascending."""+ return tuple(sorted(FIXTURE_ROOT.glob("*/*.csv")))+++def fixture_days(symbol: str) -> tuple[str, ...]:+ return tuple(sorted(path.stem for path in (FIXTURE_ROOT / symbol).glob("*.csv")))+++def _empty_intraday() -> pd.DataFrame:+ columns = {column: pd.Series(dtype="float64") for column in OHLCV}+ return pd.DataFrame(columns, index=pd.DatetimeIndex([], name="bar_time"))+++def load_5m(symbol: str, day: str) -> pd.DataFrame:+ """One symbol-day's raw bars; a header-only file is zero bars, not an error."""+ path = FIXTURE_ROOT / symbol / f"{day}.csv"+ if not path.is_file():+ raise FileNotFoundError(f"no 5m fixture for {symbol} on {day}: {path}")+ frame = pd.read_csv(path, parse_dates=["bar_time"])+ if frame.empty:+ return _empty_intraday()+ return frame.set_index("bar_time")[list(OHLCV)].sort_index()+++def load_5m_all(symbol: str) -> pd.DataFrame:+ """All of one symbol's fixture bars in ascending label order."""+ frames = [load_5m(symbol, day) for day in fixture_days(symbol)]+ frames = [frame for frame in frames if not frame.empty]+ if not frames:+ return _empty_intraday()+ return pd.concat(frames).sort_index()+++def continuous_bars(frame: pd.DataFrame) -> pd.DataFrame:+ """Drop the 09:30 opening-auction print, leaving the continuous bars."""+ if frame.empty:+ return frame+ return frame[frame.index.strftime("%H:%M") != AUCTION_LABEL]+++def session_values(frame: pd.DataFrame) -> dict[str, float]:+ """The D1 session bar (open/high/low/close/volume) from a raw day frame."""+ continuous = continuous_bars(frame)+ if continuous.empty:+ raise ValueError("no continuous 5m bars to assemble a session bar from")+ return {+ "open": float(continuous["open"].iloc[0]),+ "high": float(continuous["high"].max()),+ "low": float(continuous["low"].min()),+ "close": float(continuous["close"].iloc[-1]),+ "volume": float(continuous["volume"].sum()),+ }+++def derive_daily(symbol: str) -> pd.DataFrame:+ """A daily frame assembled from the fixture's session bars (lots, T1 units)."""+ records: list[dict[str, Any]] = []+ for day in fixture_days(symbol):+ frame = load_5m(symbol, day)+ if continuous_bars(frame).empty:+ continue+ bar = session_values(frame)+ records.append(+ {+ "trade_date": pd.Timestamp(day),+ "open": bar["open"],+ "high": bar["high"],+ "low": bar["low"],+ "close": bar["close"],+ "volume": bar["volume"] / _VOLUME_LOTS_PER_SHARE,+ }+ )+ frame = pd.DataFrame(records, columns=["trade_date", *OHLCV])+ return frame.set_index("trade_date").sort_index()+++def fixture_reference(symbol: str, day: str, path_model: str = "bar_median") -> Decimal:+ """The reference price recomputed from the CSV with Decimal arithmetic.++ Deliberately independent of the engine: ``money()`` is ``Decimal(str(x))``+ and the frozen tick is 2dp HALF_UP, both restated here rather than imported,+ so a change in the engine's helper cannot make this assertion agree with a+ wrong price.+ """+ bar = session_values(load_5m(symbol, day))+ prices = sorted(Decimal(str(bar[key])) for key in ("open", "high", "low", "close"))+ raw = prices[3] if path_model == "bar_close" else (prices[1] + prices[2]) / Decimal(2)+ return raw.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)+++def _window(frame: pd.DataFrame, start_date: str, end_date: str, *, end_inclusive: bool):+ if frame.empty:+ return frame+ start = pd.Timestamp(start_date)+ end = pd.Timestamp(end_date)+ mask = (frame.index >= start) & ((frame.index <= end) if end_inclusive else (frame.index < end))+ return frame[mask]+++class FixtureLoader:+ """The network leg's structural shape, served entirely from CSV fixtures.++ ``calls`` records every request so a test can prove a step issued exactly+ ONE ranged 5m call (the provider allows 2/day, T1).+ """++ name = "fixture"++ def __init__(self) -> None:+ self.calls: list[tuple[tuple[str, ...], str, str, str]] = []+ self._daily: dict[str, pd.DataFrame] = {}++ def is_available(self) -> bool:+ return True++ def five_minute_calls(self) -> list[tuple[tuple[str, ...], str, str, str]]:+ return [call for call in self.calls if call[3] in ("5m", "5min", "5")]++ def fetch(+ self,+ codes: Iterable[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Sequence[str] | None = None,+ ) -> Mapping[str, pd.DataFrame]:+ ordered = tuple(str(code) for code in codes)+ kind = str(interval)+ self.calls.append((ordered, start_date, end_date, kind))+ five_minute = kind.lower() in ("5m", "5min", "5")+ served: dict[str, pd.DataFrame] = {}+ for code in ordered:+ if five_minute:+ frame = _window(load_5m_all(code), start_date, end_date, end_inclusive=False)+ else:+ if code not in self._daily:+ self._daily[code] = derive_daily(code)+ frame = _window(self._daily[code], start_date, end_date, end_inclusive=True)+ if not frame.empty:+ served[code] = frame+ return served+++class FixtureCalendar:+ """The structural ``TradeCalendarClient`` shape; exactly ``open_days`` are open."""++ def __init__(self, open_days: Iterable[str]) -> None:+ self.open_days = frozenset(open_days)++ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:+ rows = [+ {+ "exchange": "SSE",+ "cal_date": day.strftime("%Y-%m-%d"),+ "is_open": int(day.strftime("%Y-%m-%d") in self.open_days),+ "pretrade_date": "",+ }+ for day in pd.date_range(start_date, end_date)+ ]+ return pd.DataFrame(rows, columns=["exchange", "cal_date", "is_open", "pretrade_date"])+++# ── Shared step harness: one seed payload, the strategy sources, the helpers ──++_DAY = "2026-10-20"+_HALTED = "2026-10-19"+_SYM = "600519.SH"+_WITNESS = "000001.SZ"+_THIRD = "600000.SH"+_SHA_RE = re.compile(r"^[0-9a-f]{64}$")+_FEES = {+ "commission_rate": 0.00025,+ "commission_min": 5.0,+ "stamp_tax_sell": 0.0005,+ "transfer_fee": 0.00001,+}+++def _payload(**overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "account_id": "pa_5m_tool",+ "market": "cn_a",+ "account_state": {"cash": 1_000_000.0, "positions": []},+ "orders": [{"symbol": _SYM, "side": "buy", "qty": 100}],+ "from_date": _DAY,+ "to_date": _DAY,+ "fee_model": dict(_FEES),+ "interval": "5m",+ }+ base.update(overrides)+ return base+++def _run(payload: dict[str, Any], *, loader: Any = None, calendar: Any = None):+ loader = FixtureLoader() if loader is None else loader+ calendar = FixtureCalendar((payload["to_date"],)) if calendar is None else calendar+ document = run_paper_trade_step(+ payload,+ loader=loader,+ ch_client=None,+ calendar_client=calendar,+ limits_client=None,+ )+ return json.loads(document), loader+++def _strategy_payload(path: str, **overrides: Any) -> dict[str, Any]:+ payload = _payload(**overrides)+ payload.pop("orders")+ payload["strategy_path"] = path+ return payload+++def _install_strategy(name: str, source: str) -> str:+ # The path policy only admits <runtime_root>/strategies; the conftest HOME+ # sandbox makes that a per-session temp dir.+ root = get_runtime_root() / "strategies"+ root.mkdir(parents=True, exist_ok=True)+ path = root / name+ path.write_text(source, encoding="utf-8")+ return str(path)+++def _strategy_source(*universe: str) -> str:+ """A minimal SignalEngine selling each target symbol held at call start.++ With ``universe`` it declares UNIVERSE and orders exactly those symbols;+ without it, orders ``ctx.symbols`` (the served universe fallback).+ """+ declaration = f"UNIVERSE = {universe!r}\n\n" if universe else ""+ target = repr(universe) if universe else "ctx.symbols"+ return (+ declaration+ + "class SignalEngine:\n"+ + "\n"+ + " def generate_signals(self, ctx, trade_date):\n"+ + " held = {position.symbol: position.qty\n"+ + " for position in ctx.account_state.positions}\n"+ + " return [\n"+ + ' {"symbol": symbol, "side": "sell", "qty": held[symbol]}\n'+ + f" for symbol in {target} if symbol in held\n"+ + " ]\n"+ )+++def _outside_universe_source(declared: tuple[str, ...], target: str) -> str:+ """Declare one 5m UNIVERSE but order a held symbol, possibly outside it."""+ return (+ f"UNIVERSE = {declared!r}\n\n"+ "class SignalEngine:\n"+ "\n"+ " def generate_signals(self, ctx, trade_date):\n"+ " held = {position.symbol: position.qty\n"+ " for position in ctx.account_state.positions}\n"+ f" if {target!r} not in held:\n"+ " return []\n"+ f" return [{{'symbol': {target!r}, 'side': 'sell', 'qty': held[{target!r}]}}]\n"+ )diff --git a/agent/tests/test_paper_accounts.py b/agent/tests/test_paper_accounts.pyindex 3b2038d06..cb48913bf 100644--- a/agent/tests/test_paper_accounts.py+++ b/agent/tests/test_paper_accounts.py@@ -1,5 +1,6 @@"""Forward account clocks, real matching, persistence and concurrent writes."""+import inspectimport jsonfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timezone@@ -124,6 +125,44 @@ def test_failure_does_not_save_or_consume_revision(service):assert service.history(account["id"]) == []+def test_advance_stays_v1_1_and_cannot_ask_for_an_interval(service):+ account = create(service)+ seen: list[dict] = []++ def step(payload: dict) -> str:+ seen.append(payload)+ return matching(payload)++ service.step = step+ signature = inspect.signature(PaperAccounts.advance).parameters+ assert "interval" not in signature+ assert not any(param.kind is inspect.Parameter.VAR_KEYWORD for param in signature.values())++ with pytest.raises(TypeError):+ service.advance(+ account["id"],+ expected_revision=0,+ to_date="2026-10-20",+ orders=[],+ interval="5m",+ )+ assert seen == []++ reply = service.advance(+ account["id"],+ expected_revision=0,+ to_date="2026-10-20",+ orders=[],+ )+ assert seen and set(seen[0]).isdisjoint({"interval", "session", "path_model", "fill_model"})+ assert reply["committed"] is True+ assert reply["account"]["revision"] == 1+ assert reply["result"]["schema_version"] == "pt-v1.1"+ assert [row["date"] for row in reply["result"]["nav_series"]] == ["2026-10-20"]+ assert "engine_fingerprint" not in reply["result"]+ assert "interval" not in reply["result"]++def test_concurrent_match_commits_only_once(service):account = create(service)barrier = Barrier(2)diff --git a/agent/tests/test_paper_trade_1d_fingerprint.py b/agent/tests/test_paper_trade_1d_fingerprint.pynew file mode 100644index 000000000..2ad560de8--- /dev/null+++ b/agent/tests/test_paper_trade_1d_fingerprint.py@@ -0,0 +1,103 @@+"""D3 gate — the 1d ``bar_fingerprint`` covers the served day bars.++Before this change ``data.fetch_market_data`` hard-coded ``bar_fingerprint=""``+for ``interval="1d"``, so two different days (or two different price tapes)+shared one ``engine_fingerprint``. The fingerprint is an audit field only: it+never changes matching, and the pt-v1.1 wire document still does not carry it.++Offline: no network, no clock, no writes.+"""++from __future__ import annotations++import json+from typing import Any, Iterable, Mapping, Sequence++import pandas as pd++from src.tools.paper_trade.data import fetch_market_data+from src.tools.paper_trade.tool import run_paper_trade_step++_DAY_A = "2026-10-19"+_DAY_B = "2026-10-20"+_SYM = "AAPL.US"+++def _frame(rows: Iterable[tuple[str, float]]) -> pd.DataFrame:+ records = [+ {+ "trade_date": pd.Timestamp(day),+ "open": close - 0.5,+ "high": close + 0.5,+ "low": close - 1.0,+ "close": close,+ "volume": 1_000.0,+ }+ for day, close in rows+ ]+ return pd.DataFrame(records).set_index("trade_date")+++class _Loader:+ name = "fixture"++ def __init__(self, frames: Mapping[str, pd.DataFrame]) -> None:+ self.frames = dict(frames)+ self.calls: list[tuple[tuple[str, ...], str, str, str]] = []++ def is_available(self) -> bool:+ return True++ def fetch(+ self,+ codes: Iterable[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Sequence[str] | None = None,+ ) -> Mapping[str, pd.DataFrame]:+ self.calls.append((tuple(str(code) for code in codes), start_date, end_date, str(interval)))+ return {code: self.frames[code] for code in codes if code in self.frames}+++def _fetch(day: str, close: float):+ loader = _Loader({_SYM: _frame([("2026-10-16", 100.0), (day, close)])})+ return fetch_market_data("us", [_SYM], day, day, loader=loader)+++def test_different_days_and_prices_produce_different_fingerprints() -> None:+ first = _fetch(_DAY_A, 101.0)+ second = _fetch(_DAY_B, 101.0)+ repriced = _fetch(_DAY_A, 102.0)++ assert len(first.bar_fingerprint) == 64+ assert first.bar_fingerprint != second.bar_fingerprint+ assert first.bar_fingerprint != repriced.bar_fingerprint+++def test_the_same_served_tape_hashes_identically_twice() -> None:+ first = _fetch(_DAY_A, 101.0)+ second = _fetch(_DAY_A, 101.0)++ assert first.bar_fingerprint == second.bar_fingerprint+++def test_a_v1_1_document_still_has_no_engine_fingerprint() -> None:+ loader = _Loader({_SYM: _frame([("2026-10-16", 100.0), (_DAY_B, 101.0)])})+ payload: dict[str, Any] = {+ "account_id": "pa_1d_fingerprint",+ "market": "us",+ "account_state": {"cash": 100_000.0, "positions": []},+ "orders": [{"symbol": _SYM, "side": "buy", "qty": 10}],+ "from_date": _DAY_B,+ "to_date": _DAY_B,+ }++ document = json.loads(+ run_paper_trade_step(payload, loader=loader, ch_client=None, calendar_client=None, limits_client=None)+ )++ assert document["schema_version"] == "pt-v1.1"+ assert "engine_fingerprint" not in document+ assert [fill["symbol"] for fill in document["fills"]] == [_SYM]diff --git a/agent/tests/test_paper_trade_5m_engine.py b/agent/tests/test_paper_trade_5m_engine.pynew file mode 100644index 000000000..94053a2dd--- /dev/null+++ b/agent/tests/test_paper_trade_5m_engine.py@@ -0,0 +1,422 @@+"""T3 gate — cn_a 5m reference price, all-or-none fills and emergency cancel.++Every order matches ONE assembled session bar (D1: the 48 continuous 5m bars+of the day, 09:30 opening-auction print excluded). The reference price is+``bar_median`` (median of open/high/low/close) or ``bar_close``; it drives+limit marketability, the cash gate, the fill price, the notional and the fee.+A failed order keeps its specific pt-v1.1 reason in ``rejected_orders`` AND+gets one ``canceled_after_failed_match`` row in ``canceled_orders`` (D2).+Offline: synthetic frames through a fake loader, never the network.+"""++from __future__ import annotations++import datetime as dt++import pandas as pd+import pytest++from src.tools.paper_trade import engine, state_hash+from src.tools.paper_trade.data import fetch_market_data+from src.tools.paper_trade.schema import CANCELED_REASON_CODE, REASON_CODES, parse_request++_DAY = "2026-10-20"+_PREV = "2026-10-19"+_SYM = "600519.SH"+_OTHER = "000001.SZ"+_FEE_MODEL = {+ "commission_rate": 0.00025,+ "commission_min": 5.0,+ "stamp_tax_sell": 0.0005,+ "transfer_fee": 0.00001,+}+++def _session_labels(day: str = _DAY) -> list[str]:+ stamps: list[str] = []+ for hour, minute in ((9, 30), (13, 0)):+ start = dt.datetime.fromisoformat(f"{day}T{hour:02d}:{minute:02d}:00")+ stamps.extend((start + dt.timedelta(minutes=5 * step)).strftime("%H:%M") for step in range(1, 25))+ return stamps+++def _intraday(day: str, prices: dict[str, float], auction: float | None = None) -> pd.DataFrame:+ records = []+ if auction is not None:+ records.append(+ {+ "bar_time": f"{day} 09:30",+ "open": auction,+ "high": auction,+ "low": auction,+ "close": auction,+ "volume": 48000.0,+ }+ )+ for label, price in prices.items():+ records.append(+ {+ "bar_time": f"{day} {label}",+ "open": price,+ "high": price,+ "low": price,+ "close": price,+ "volume": 120000.0,+ }+ )+ frame = pd.DataFrame(records)+ frame["bar_time"] = pd.to_datetime(frame["bar_time"])+ return frame.set_index("bar_time")+++def _normal_5m(day: str = _DAY, *, close: float = 10.20) -> pd.DataFrame:+ labels = _session_labels(day)+ prices = {label: 10.00 for label in labels[:-1]}+ prices[labels[-1]] = close+ return _intraday(day, prices, auction=10.05)+++def _flat_5m(day: str, price: float) -> pd.DataFrame:+ return _intraday(day, {label: price for label in _session_labels(day)}, auction=price)+++def _daily(rows: list[tuple[str, float]]) -> pd.DataFrame:+ records = [+ {"trade_date": day, "open": close, "high": close, "low": close, "close": close, "volume": 1000.0}+ for day, close in rows+ ]+ frame = pd.DataFrame(records)+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])+ return frame.set_index("trade_date")+++class FakeChClient:+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:+ return pd.DataFrame()+++class FakeLoader:+ def __init__(self, daily: dict[str, pd.DataFrame], five: dict[str, pd.DataFrame] | None = None) -> None:+ self.name = "tencent"+ self._daily = daily+ self._five = five or {}+ self.calls: list[tuple[tuple[str, ...], str, str, str]] = []++ def is_available(self) -> bool:+ return True++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ self.calls.append((tuple(codes), start_date, end_date, interval))+ source = self._five if interval == "5m" else self._daily+ return {code: source[code] for code in codes if code in source}+++class FakeCalendarClient:+ def __init__(self, open_days: frozenset[str]) -> None:+ self._open = open_days++ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:+ rows = [+ {+ "exchange": "SSE",+ "cal_date": day.strftime("%Y-%m-%d"),+ "is_open": int(day.strftime("%Y-%m-%d") in self._open),+ "pretrade_date": "",+ }+ for day in pd.date_range(start_date, end_date)+ ]+ return pd.DataFrame(rows, columns=["exchange", "cal_date", "is_open", "pretrade_date"])+++def _market_data(daily: dict[str, pd.DataFrame], five: dict[str, pd.DataFrame], *, symbols: tuple[str, ...] = (_SYM,)):+ return fetch_market_data(+ "cn_a",+ list(symbols),+ _DAY,+ _DAY,+ loader=FakeLoader(daily, five),+ ch_client=FakeChClient(),+ interval="5m",+ )+++def _cn_a_data(**overrides) -> tuple[object, FakeLoader]:+ five_overrides = overrides.pop("five", None)+ daily_overrides = overrides.pop("daily", None)+ symbols = tuple(overrides.pop("symbols", (_SYM,)))+ daily = {_SYM: _daily([(_PREV, 10.00), (_DAY, 10.20)])}+ if daily_overrides:+ daily.update(daily_overrides)+ five = {_SYM: _normal_5m()}+ if five_overrides is not None:+ five = five_overrides+ return _market_data(daily, five, symbols=symbols), FakeLoader(daily, five)+++def _outcome(+ *,+ orders,+ cash=100000.0,+ positions=(),+ path_model="bar_median",+ market_data=None,+ open_days=frozenset({_DAY}),+ **frames,+):+ if market_data is None:+ market_data, _ = _cn_a_data(**frames)+ request = parse_request(+ {+ "account_id": "pa_5m",+ "market": "cn_a",+ "account_state": {"cash": cash, "positions": list(positions)},+ "orders": list(orders),+ "from_date": _DAY,+ "to_date": _DAY,+ "fee_model": dict(_FEE_MODEL),+ "interval": "5m",+ "path_model": path_model,+ }+ )+ return engine.match_orders(request, market_data=market_data, calendar_client=FakeCalendarClient(open_days))+++def _buy(limit=None, qty=100, symbol=_SYM):+ order = {"symbol": symbol, "side": "buy", "qty": qty}+ if limit is not None:+ order["limit"] = limit+ return order+++def _sell(limit=None, qty=100, symbol=_SYM):+ order = {"symbol": symbol, "side": "sell", "qty": qty}+ if limit is not None:+ order["limit"] = limit+ return order+++def test_market_buy_fills_at_the_session_median() -> None:+ # Session bar o/h/l/c = 10.00/10.20/10.00/10.20 → median 10.10. The 09:30+ # auction print (10.05) is excluded; including it would move the median.+ outcome = _outcome(orders=[_buy()])++ assert outcome.error is None+ assert [(f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [("buy", 100.0, 10.10, 5.01)]+ assert outcome.rejected_orders == ()+ assert outcome.canceled_orders == ()+ assert outcome.end_state.cash == 98984.99+ assert outcome.end_state.positions[0].avg_cost == 10.10+ assert outcome.events == ()+ assert outcome.nav_series[0].nav == 100004.99+++def test_market_sell_fills_at_the_session_median() -> None:+ outcome = _outcome(orders=[_sell()], positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}])++ assert outcome.error is None+ assert [(f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [("sell", 100.0, 10.10, 5.52)]+ assert outcome.end_state.cash == 101004.48+ assert outcome.end_state.positions == ()+ assert outcome.canceled_orders == ()++[email protected](("limit", "fills"), [(10.50, True), (10.10, True), (10.00, False)])+def test_buy_limit_marketability_at_the_reference(limit: float, fills: bool) -> None:+ outcome = _outcome(orders=[_buy(limit=limit)])++ if fills:+ assert [(f.side, f.price) for f in outcome.fills] == [("buy", 10.10)]+ assert outcome.rejected_orders == ()+ return+ assert outcome.fills == ()+ assert [r.reason_code for r in outcome.rejected_orders] == ["limit_not_marketable"]+ assert outcome.rejected_orders[0].detail == "ref 10.10 > limit 10.00"+ assert [c.reason_code for c in outcome.canceled_orders] == [CANCELED_REASON_CODE]++[email protected](("limit", "fills"), [(10.00, True), (10.10, True), (10.20, False)])+def test_sell_limit_marketability_at_the_reference(limit: float, fills: bool) -> None:+ outcome = _outcome(orders=[_sell(limit=limit)], positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}])++ if fills:+ assert [(f.side, f.price) for f in outcome.fills] == [("sell", 10.10)]+ assert outcome.rejected_orders == ()+ return+ assert outcome.fills == ()+ assert [r.reason_code for r in outcome.rejected_orders] == ["limit_not_marketable"]+ assert outcome.rejected_orders[0].detail == "ref 10.10 < limit 10.20"+ assert [c.reason_code for c in outcome.canceled_orders] == [CANCELED_REASON_CODE]+++def test_path_model_changes_the_reference_and_the_verdict() -> None:+ market_data, _ = _cn_a_data()+ median = _outcome(orders=[_buy(limit=10.15)], market_data=market_data)+ close = _outcome(orders=[_buy(limit=10.15)], market_data=market_data, path_model="bar_close")++ assert [(f.price) for f in median.fills] == [10.10]+ assert median.rejected_orders == ()+ assert close.fills == ()+ assert [r.reason_code for r in close.rejected_orders] == ["limit_not_marketable"]+ assert close.rejected_orders[0].detail == "ref 10.20 > limit 10.15"+ assert median.engine_fingerprint != close.engine_fingerprint++[email protected]("path_model", ["bar_median", "bar_close"])+def test_fill_price_equals_the_reference_under_both_path_models(path_model: str) -> None:+ market_data, _ = _cn_a_data()+ bar = market_data.data[_SYM].session_bar+ expected = 10.20 if path_model == "bar_close" else 10.10+ assert (bar.open, bar.high, bar.low, bar.close) == (10.00, 10.20, 10.00, 10.20)++ outcome = _outcome(orders=[_buy(), _buy(qty=200)], market_data=market_data, path_model=path_model, cash=1000000.0)++ assert [f.price for f in outcome.fills] == [expected, expected]+ assert outcome.canceled_orders == ()+ assert outcome.engine_fingerprint == state_hash.engine_fingerprint(+ interval="5m", path_model=path_model, fill_model="all_or_none", bar_fingerprint=market_data.bar_fingerprint+ )+++def test_insufficient_cash_rejects_and_cancels() -> None:+ outcome = _outcome(orders=[_buy()], cash=500.0)++ assert outcome.fills == ()+ assert [r.reason_code for r in outcome.rejected_orders] == ["insufficient_cash"]+ assert "1015.01" in outcome.rejected_orders[0].detail+ assert len(outcome.canceled_orders) == 1+ assert outcome.canceled_orders[0].detail == "rejected: insufficient_cash"+ assert outcome.end_state.cash == 500.0+++def test_insufficient_position_rejects_and_cancels() -> None:+ outcome = _outcome(orders=[_sell(qty=200)], positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}])++ assert outcome.fills == ()+ assert [r.reason_code for r in outcome.rejected_orders] == ["insufficient_position"]+ assert [c.reason_code for c in outcome.canceled_orders] == [CANCELED_REASON_CODE]+ assert outcome.end_state.positions[0].qty == 100+++def test_lot_size_rejects_and_cancels() -> None:+ outcome = _outcome(orders=[_buy(qty=150)])++ assert outcome.fills == ()+ assert [r.reason_code for r in outcome.rejected_orders] == ["lot_size"]+ assert len(outcome.canceled_orders) == 1+++def test_limit_up_buy_rejects_with_a_price_limit_event() -> None:+ daily = {_SYM: _daily([(_PREV, 10.00), (_DAY, 11.00)])}+ five = {_SYM: _flat_5m(_DAY, 11.00)}+ outcome = _outcome(orders=[_buy()], daily=daily, five=five)++ assert outcome.fills == ()+ assert [r.reason_code for r in outcome.rejected_orders] == ["limit_up"]+ assert [(e.symbol, e.event_type) for e in outcome.events] == [(_SYM, "price_limit")]+ assert "up limit 11.00" in outcome.events[0].detail+ assert len(outcome.canceled_orders) == 1+++def test_limit_down_sell_rejects_with_a_price_limit_event() -> None:+ daily = {_SYM: _daily([(_PREV, 10.00), (_DAY, 9.00)])}+ five = {_SYM: _flat_5m(_DAY, 9.00)}+ outcome = _outcome(+ orders=[_sell()], daily=daily, five=five, positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}]+ )++ assert outcome.fills == ()+ assert [r.reason_code for r in outcome.rejected_orders] == ["limit_down"]+ assert [(e.symbol, e.event_type) for e in outcome.events] == [(_SYM, "price_limit")]+ assert len(outcome.canceled_orders) == 1+++def test_halted_symbol_rejects_suspended_and_its_position_is_untouched() -> None:+ daily = {+ _SYM: _daily([(_PREV, 10.00), (_DAY, 10.20)]),+ _OTHER: _daily([(_PREV, 20.00)]),+ }+ five = {_SYM: _normal_5m()}+ market_data, _ = _cn_a_data(daily=daily, five=five, symbols=(_SYM, _OTHER))+ outcome = _outcome(+ orders=[_buy(symbol=_OTHER)],+ market_data=market_data,+ positions=[{"symbol": _OTHER, "qty": 100, "avg_cost": 20.0}],+ )++ assert outcome.fills == ()+ assert [(r.symbol, r.reason_code) for r in outcome.rejected_orders] == [(_OTHER, "suspended")]+ assert [(e.symbol, e.event_type) for e in outcome.events] == [(_OTHER, "halted")]+ assert [(p.symbol, p.qty, p.avg_cost) for p in outcome.end_state.positions] == [(_OTHER, 100.0, 20.0)]+ assert outcome.end_state.cash == 100000.0+ assert outcome.nav_series[0].position_value == 2000.0+ assert len(outcome.canceled_orders) == 1+++def test_every_order_is_terminal_and_every_failure_has_a_reason() -> None:+ orders = [+ _buy(), # fills+ _buy(limit=10.00), # limit_not_marketable+ _buy(qty=150), # lot_size+ _buy(symbol="999999.SZ"), # unknown_symbol+ _sell(qty=200), # insufficient_position+ ]+ outcome = _outcome(orders=orders, positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}])++ assert len(outcome.fills) + len(outcome.rejected_orders) == len(orders)+ assert all(r.reason_code in REASON_CODES for r in outcome.rejected_orders)+ assert len(outcome.canceled_orders) == len(outcome.rejected_orders)+ assert {c.reason_code for c in outcome.canceled_orders} == {CANCELED_REASON_CODE}+ assert [(c.symbol, c.side, c.qty) for c in outcome.canceled_orders] == [+ (r.symbol, r.side, r.qty) for r in outcome.rejected_orders+ ]+++def test_1d_mode_is_unchanged_and_never_cancels_or_events() -> None:+ daily = {_SYM: _daily([(_PREV, 10.00), (_DAY, 10.20)])}+ market_data = fetch_market_data("cn_a", [_SYM], _DAY, _DAY, loader=FakeLoader(daily), ch_client=FakeChClient())+ request = parse_request(+ {+ "account_id": "pa_5m_1d",+ "market": "cn_a",+ "account_state": {"cash": 100000.0, "positions": []},+ "orders": [_buy(limit=10.00)],+ "from_date": _DAY,+ "to_date": _DAY,+ "fee_model": dict(_FEE_MODEL),+ }+ )+ outcome = engine.match_orders(+ request, market_data=market_data, calendar_client=FakeCalendarClient(frozenset({_DAY}))+ )++ assert outcome.fills == ()+ assert outcome.rejected_orders[0].detail == "close 10.20 > limit 10.00"+ assert outcome.canceled_orders == ()+ assert outcome.events == ()+ assert market_data.interval == "1d"+ assert len(market_data.bar_fingerprint) == 64+++def test_5m_request_refuses_a_daily_frame() -> None:+ daily = {_SYM: _daily([(_PREV, 10.00), (_DAY, 10.20)])}+ market_data = fetch_market_data("cn_a", [_SYM], _DAY, _DAY, loader=FakeLoader(daily), ch_client=FakeChClient())+ request = parse_request(+ {+ "account_id": "pa_5m_gate",+ "market": "cn_a",+ "account_state": {"cash": 100000.0, "positions": []},+ "orders": [_buy()],+ "from_date": _DAY,+ "to_date": _DAY,+ "fee_model": dict(_FEE_MODEL),+ "interval": "5m",+ }+ )+ outcome = engine.match_orders(+ request, market_data=market_data, calendar_client=FakeCalendarClient(frozenset({_DAY}))+ )++ assert outcome.error is not None+ assert outcome.error.code == "INVALID_REQUEST"+ assert "interval" in outcome.error.message+ assert outcome.fills == () and outcome.canceled_orders == ()diff --git a/agent/tests/test_paper_trade_5m_golden.py b/agent/tests/test_paper_trade_5m_golden.pynew file mode 100644index 000000000..674ed3063--- /dev/null+++ b/agent/tests/test_paper_trade_5m_golden.py@@ -0,0 +1,267 @@+"""T6 gate — determinism, ledger invariants and fixture integrity for 5m.++What this suite pins, all through the stateless tool surface:++* the same input produces BYTE-identical JSON on two independent runs, and+ two different sessions produce different ``engine_fingerprint`` values+ (the fingerprint folds in bar evidence, D3);+* cash and position conservation under the engine's exact 2dp arithmetic,+ every fill fee non-negative;+* every fill price equals the reference recomputed here from the CSV;+* every rejected order carries a frozen reason code and, in 5m mode, exactly+ one emergency-cancel row;+* a halted session leaves the ledger and the marks alone;+* an auction-window label is excluded from the session bar and reported;+* the fixture manifest indexes every committed file and matches its bytes.++The persistent runner/adapter suite lives with the persistence layer on the+follow-up ``paper-trade-v12-persistence`` branch.++Offline: fixtures via ``paper_trade_5m_fixtures``, no network.+"""++from __future__ import annotations++import hashlib+import json+from decimal import ROUND_HALF_UP, Decimal+from typing import Any++import pandas as pd++from src.tools.paper_trade.schema import CANCELED_REASON_CODE, REASON_CODES+from src.tools.paper_trade.tool import run_paper_trade_step+from tests.paper_trade_5m_fixtures import (+ FIXTURE_ROOT,+ FixtureCalendar,+ FixtureLoader,+ fixture_files,+ fixture_manifest,+ fixture_reference,+ load_5m,+)++_DAY = "2026-10-20"+_PRIOR = "2026-10-16"+_HALTED = "2026-10-19"+_SYM = "600519.SH"+_WITNESS = "000001.SZ"+_CENT = Decimal("0.01")+_FEES = {+ "commission_rate": 0.00025,+ "commission_min": 5.0,+ "stamp_tax_sell": 0.0005,+ "transfer_fee": 0.00001,+}+++def _payload(day: str = _DAY, **overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "account_id": "pa_5m_golden",+ "market": "cn_a",+ "account_state": {"cash": 1_000_000.0, "positions": []},+ "orders": [{"symbol": _SYM, "side": "buy", "qty": 100}],+ "from_date": day,+ "to_date": day,+ "fee_model": dict(_FEES),+ "interval": "5m",+ }+ base.update(overrides)+ return base+++def _run(payload: dict[str, Any], *, loader: Any = None) -> tuple[str, dict[str, Any]]:+ loader = FixtureLoader() if loader is None else loader+ raw = run_paper_trade_step(+ payload,+ loader=loader,+ ch_client=None,+ calendar_client=FixtureCalendar((payload["to_date"],)),+ limits_client=None,+ )+ return raw, json.loads(raw)+++def _money(value: Any) -> Decimal:+ return Decimal(str(value))+++def _notional(fill: dict[str, Any]) -> Decimal:+ return (_money(fill["qty"]) * _money(fill["price"])).quantize(_CENT, rounding=ROUND_HALF_UP)+++def test_the_same_input_yields_byte_identical_documents() -> None:+ first, document = _run(_payload())+ second, _ = _run(_payload())++ assert isinstance(first, str)+ assert first == second+ assert hashlib.sha256(first.encode("utf-8")).hexdigest() == hashlib.sha256(second.encode("utf-8")).hexdigest()+ assert document["engine_fingerprint"] == json.loads(second)["engine_fingerprint"]+ assert len(document["fills"]) == 1+++def test_two_sessions_have_different_engine_fingerprints() -> None:+ _, prior = _run(_payload(_PRIOR))+ _, today = _run(_payload(_DAY))++ assert prior["engine_fingerprint"] != today["engine_fingerprint"]+ assert prior["fills"][0]["price"] == 1419.50+ assert today["fills"][0]["price"] == 1421.50+++def test_cash_and_positions_are_conserved_and_every_fee_is_non_negative() -> None:+ orders = [+ {"symbol": _SYM, "side": "buy", "qty": 100},+ {"symbol": _SYM, "side": "buy", "qty": 200},+ {"symbol": _SYM, "side": "sell", "qty": 100},+ {"symbol": _SYM, "side": "buy", "qty": 150},+ {"symbol": _SYM, "side": "buy", "qty": 100, "limit": 1.0},+ {"symbol": _SYM, "side": "sell", "qty": 10_000},+ ]+ start_cash = Decimal("1000000.00")+ _, document = _run(+ _payload(+ orders=orders,+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 200, "avg_cost": 1420.0}],+ },+ )+ )++ cash = start_cash+ bought = Decimal("0")+ sold = Decimal("0")+ for fill in document["fills"]:+ fee = _money(fill["fee"])+ assert fee >= 0+ if fill["side"] == "buy":+ cash -= _notional(fill) + fee+ bought += _money(fill["qty"])+ else:+ cash += _notional(fill) - fee+ sold += _money(fill["qty"])++ assert _money(document["end_state"]["cash"]) == cash+ held = {row["symbol"]: _money(row["qty"]) for row in document["end_state"]["positions"]}+ assert held == {_SYM: Decimal("200") + bought - sold} == {_SYM: Decimal("400")}+ assert [fill["side"] for fill in document["fills"]] == ["buy", "buy", "sell"]+ assert len(document["rejected_orders"]) == 3+++def test_every_fill_price_is_the_reference_recomputed_from_the_csv() -> None:+ for path_model in ("bar_median", "bar_close"):+ _, document = _run(+ _payload(+ path_model=path_model,+ orders=[+ {"symbol": _SYM, "side": "buy", "qty": 100},+ {"symbol": _SYM, "side": "buy", "qty": 200},+ ],+ )+ )+ expected = float(fixture_reference(_SYM, _DAY, path_model))+ assert [fill["price"] for fill in document["fills"]] == [expected, expected]+++def test_every_rejection_is_frozen_and_emergency_canceled() -> None:+ orders = [+ {"symbol": _SYM, "side": "buy", "qty": 150},+ {"symbol": _SYM, "side": "buy", "qty": 100, "limit": 1.0},+ {"symbol": _SYM, "side": "sell", "qty": 100},+ {"symbol": _SYM, "side": "sell", "qty": 10_000},+ ]+ _, document = _run(_payload(orders=orders))++ assert document["fills"] == []+ assert len(document["rejected_orders"]) == len(orders)+ assert {row["reason_code"] for row in document["rejected_orders"]} == {+ "lot_size",+ "limit_not_marketable",+ "insufficient_position",+ }+ for row in document["rejected_orders"]:+ assert row["reason_code"] in REASON_CODES+ assert row["reason_code"]+ assert [(row["symbol"], row["side"], row["qty"]) for row in document["canceled_orders"]] == [+ (row["symbol"], row["side"], row["qty"]) for row in document["rejected_orders"]+ ]+ assert {row["reason_code"] for row in document["canceled_orders"]} == {CANCELED_REASON_CODE}+++def test_halted_session_carries_the_marks_forward_untouched() -> None:+ _, document = _run(+ _payload(+ _HALTED,+ orders=[{"symbol": _SYM, "side": "buy", "qty": 100}],+ account_state={+ "cash": 1_000_000.0,+ "positions": [+ {"symbol": _SYM, "qty": 100, "avg_cost": 1421.0},+ {"symbol": _WITNESS, "qty": 1000, "avg_cost": 10.0},+ ],+ },+ )+ )++ assert document["fills"] == []+ assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_SYM, "halted")]+ assert document["nav_series"] == [+ {+ "date": _HALTED,+ "nav": 1_152_020.0,+ "cash": 1_000_000.0,+ "position_value": 152_020.0,+ }+ ]+ assert document["end_state"]["cash"] == 1_000_000.0+ assert {row["symbol"]: (row["qty"], row["avg_cost"]) for row in document["end_state"]["positions"]} == {+ _SYM: (100.0, 1421.0),+ _WITNESS: (1000.0, 10.0),+ }+++class _AuctionLoader(FixtureLoader):+ """Serves the committed day plus one synthetic 14:58 auction-window label."""++ def __init__(self, symbol: str, frame: pd.DataFrame) -> None:+ super().__init__()+ self._symbol = symbol+ self._frame = frame++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ if str(interval).lower() in ("5m", "5min", "5"):+ ordered = tuple(str(code) for code in codes)+ self.calls.append((ordered, start_date, end_date, str(interval)))+ return {self._symbol: self._frame} if self._symbol in ordered else {}+ return super().fetch(codes, start_date, end_date, interval=interval, fields=fields)+++def test_auction_window_label_is_excluded_and_reported() -> None:+ extra = pd.DataFrame(+ [{"open": 99.0, "high": 99.0, "low": 99.0, "close": 99.0, "volume": 1.0}],+ index=pd.DatetimeIndex([pd.Timestamp(f"{_DAY} 14:58:00")], name="bar_time"),+ )+ tainted = pd.concat([load_5m(_SYM, _DAY), extra]).sort_index()+ _, clean = _run(_payload())+ _, document = _run(_payload(), loader=_AuctionLoader(_SYM, tainted))++ assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_SYM, "auction_window")]+ assert "14:58" in document["events"][0]["detail"]+ assert document["fills"][0]["price"] == clean["fills"][0]["price"] == 1421.50+++def test_manifest_indexes_every_fixture_and_matches_its_bytes() -> None:+ manifest = fixture_manifest()+ listed = {entry["file"]: entry for entry in manifest["fixtures"]}+ on_disk = {path.relative_to(FIXTURE_ROOT).as_posix() for path in fixture_files()}++ assert set(listed) == on_disk+ assert manifest["schema"] == "paper_trade.five_minute_fixture_manifest/v1"+ for relative, entry in listed.items():+ data = (FIXTURE_ROOT / relative).read_bytes()+ assert hashlib.sha256(data).hexdigest() == entry["sha256"], relative+ assert data.count(b"\n") == entry["rows"] + 1+ assert entry["continuous_rows"] in (0, 48)+ assert listed[f"{_SYM}/{_HALTED}.csv"]["continuous_rows"] == 0diff --git a/agent/tests/test_paper_trade_5m_payload.py b/agent/tests/test_paper_trade_5m_payload.pynew file mode 100644index 000000000..88fb77f20--- /dev/null+++ b/agent/tests/test_paper_trade_5m_payload.py@@ -0,0 +1,201 @@+"""T2 gate — malformed and zero-volume 5m payloads fail closed.++A payload that cannot be trusted must never become a tradable session. Three+provider faults are refused as ``PAPER_DATA_NOT_READY``: a finer interval+(1m) served as 5m, an all-NaN continuous day, and a non-finite session. A+zero-volume session is different: nothing traded, so the day is dropped and+the engine's existing halted path rejects orders ``suspended``. A partial+5m session keeps the existing ``<48`` warning and still fills, and the+auction-only halt (no continuous bar, daily bar present) stays a halt.++Every case drives the public ``run_paper_trade_step`` surface with a fake+loader and calendar: one symbol, one cn_a day, no network.+"""++from __future__ import annotations++import datetime as dt+import json+from typing import Any++import pandas as pd++from src.tools.paper_trade.tool import run_paper_trade_step++_DAY = "2026-10-20"+_PREV = "2026-10-19"+_SYM = "600519.SH"+_FEES = {+ "commission_rate": 0.00025,+ "commission_min": 5.0,+ "stamp_tax_sell": 0.0005,+ "transfer_fee": 0.00001,+}+++def _grid(start: str, step_minutes: int, count: int) -> list[str]:+ first = dt.datetime.fromisoformat(f"{_DAY}T{start}:00")+ return [(first + dt.timedelta(minutes=step_minutes * index)).strftime("%Y-%m-%d %H:%M") for index in range(count)]+++def _session_labels() -> list[str]:+ """The 48 legitimate continuous labels: 09:35..11:30, 13:05..15:00."""+ return _grid("09:35", 5, 24) + _grid("13:05", 5, 24)+++def _minute_labels() -> list[str]:+ """240 one-minute labels served as if they were 5m bars."""+ return _grid("09:31", 1, 120) + _grid("13:01", 1, 120)+++def _intraday(+ labels: list[str], *, price: float = 10.0, volume: float = 120_000.0, all_nan: bool = False+) -> pd.DataFrame:+ records = [+ {+ "bar_time": label,+ "open": float("nan") if all_nan else price,+ "high": float("nan") if all_nan else price,+ "low": float("nan") if all_nan else price,+ "close": float("nan") if all_nan else price,+ "volume": volume,+ }+ for label in labels+ ]+ frame = pd.DataFrame(records)+ frame["bar_time"] = pd.to_datetime(frame["bar_time"])+ return frame.set_index("bar_time")+++def _daily(close: float = 10.0) -> pd.DataFrame:+ frame = pd.DataFrame(+ [+ {"trade_date": _PREV, "open": close, "high": close, "low": close, "close": close, "volume": 1_000.0},+ {"trade_date": _DAY, "open": close, "high": close, "low": close, "close": close, "volume": 1_000.0},+ ]+ )+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])+ return frame.set_index("trade_date")+++class _Loader:+ name = "fixture"++ def __init__(self, five_minute: pd.DataFrame, daily: pd.DataFrame | None = None) -> None:+ self._five_minute = five_minute+ self._daily = _daily() if daily is None else daily++ def is_available(self) -> bool:+ return True++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ five_minute = str(interval).lower() in ("5m", "5min", "5")+ frame = self._five_minute if five_minute else self._daily+ return {code: frame.copy() for code in codes if not frame.empty}+++class _Calendar:+ def __init__(self, open_days: tuple[str, ...]) -> None:+ self._open = frozenset(open_days)++ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:+ rows = [+ {+ "exchange": "SSE",+ "cal_date": day.strftime("%Y-%m-%d"),+ "is_open": int(day.strftime("%Y-%m-%d") in self._open),+ "pretrade_date": "",+ }+ for day in pd.date_range(start_date, end_date)+ ]+ return pd.DataFrame(rows, columns=["exchange", "cal_date", "is_open", "pretrade_date"])+++def _payload(orders: list[dict[str, Any]] | None = None) -> dict[str, Any]:+ return {+ "account_id": "pa_5m_payload",+ "market": "cn_a",+ "account_state": {"cash": 1_000_000.0, "positions": []},+ "orders": [{"symbol": _SYM, "side": "buy", "qty": 100}] if orders is None else orders,+ "from_date": _DAY,+ "to_date": _DAY,+ "fee_model": dict(_FEES),+ "interval": "5m",+ }+++def _run(loader: _Loader, orders: list[dict[str, Any]] | None = None) -> dict[str, Any]:+ document = run_paper_trade_step(+ _payload(orders),+ loader=loader,+ ch_client=None,+ calendar_client=_Calendar((_DAY,)),+ limits_client=None,+ )+ return json.loads(document)+++def test_zero_volume_48_bar_session_is_halted_not_filled() -> None:+ loader = _Loader(_intraday(_session_labels(), volume=0.0))++ document = _run(loader)++ assert "status" not in document, document+ assert document["fills"] == []+ assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [(_SYM, "suspended")]+ assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_SYM, "halted")]+ assert len(document["canceled_orders"]) == 1+ assert document["end_state"]["cash"] == 1_000_000.0+ assert any("zero-volume session; treated as halted" in warning for warning in document["warnings"])+++def test_one_minute_payload_is_data_not_ready_not_a_session() -> None:+ loader = _Loader(_intraday(_minute_labels()))++ document = _run(loader)++ assert document["status"] == "error", document+ assert document["code"] == "PAPER_DATA_NOT_READY"+ assert "fills" not in document+ assert "could not be parsed" in document["message"]+ assert "halted" not in document["message"]+++def test_all_nan_continuous_payload_is_data_not_ready() -> None:+ loader = _Loader(_intraday(_session_labels(), all_nan=True))++ document = _run(loader)++ assert document["status"] == "error", document+ assert document["code"] == "PAPER_DATA_NOT_READY"+ assert "fills" not in document+ assert "suspended" not in document["message"]+ assert "halted" not in document["message"]+++def test_partial_5m_session_still_fills_with_coverage_warning() -> None:+ loader = _Loader(_intraday(_session_labels()[:30]))++ document = _run(loader)++ assert "status" not in document, document+ assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [+ (_SYM, "buy", 100.0, 10.0)+ ]+ assert document["rejected_orders"] == []+ assert document["events"] == []+ assert any("30/48 continuous bars" in warning for warning in document["warnings"])+++def test_auction_only_symbol_with_a_daily_bar_is_still_halted() -> None:+ auction_only = _intraday(["2026-10-20 09:30"], price=10.0, volume=48_000.0)+ loader = _Loader(auction_only)++ document = _run(loader)++ assert "status" not in document, document+ assert document["fills"] == []+ assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [(_SYM, "suspended")]+ assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_SYM, "halted")]+ assert not any("zero-volume" in warning for warning in document["warnings"])+ assert not any("continuous bars;" in warning for warning in document["warnings"])diff --git a/agent/tests/test_paper_trade_5m_readiness.py b/agent/tests/test_paper_trade_5m_readiness.pynew file mode 100644index 000000000..c842c6fe3--- /dev/null+++ b/agent/tests/test_paper_trade_5m_readiness.py@@ -0,0 +1,112 @@+"""B2 gate: a 5m pure-valuation step fails closed on a missing target bar.++A step with no orders issues no 5m request, so its NAV comes from the daily+leg and its readiness is the interval="1d" contract: at least one served+symbol must carry the target daily bar. Without it the step returns the same+``PAPER_DATA_NOT_READY`` material instead of advancing NAV on a stale frame.+Offline: fake loader / calendar only, never the network.+"""++from __future__ import annotations++import pandas as pd++from src.tools.paper_trade import engine+from src.tools.paper_trade.data import fetch_market_data+from src.tools.paper_trade.schema import parse_request++_DAY = "2026-10-20"+_PREV = "2026-10-19"+_SYM = "600519.SH"+++class FakeChClient:+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:+ return pd.DataFrame()+++class FakeLoader:+ def __init__(self, frames: dict[str, pd.DataFrame]) -> None:+ self.name = "tencent"+ self._frames = frames++ def is_available(self) -> bool:+ return True++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ return {code: self._frames[code] for code in codes if code in self._frames}+++class FakeCalendarClient:+ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:+ rows = [+ {"exchange": "SSE", "cal_date": day.strftime("%Y-%m-%d"), "is_open": 1, "pretrade_date": ""}+ for day in pd.date_range(start_date, end_date)+ ]+ return pd.DataFrame(rows, columns=["exchange", "cal_date", "is_open", "pretrade_date"])+++def _frame(rows: list[tuple[str, float]]) -> pd.DataFrame:+ records = [+ {"trade_date": day, "open": close, "high": close, "low": close, "close": close, "volume": 1000.0}+ for day, close in rows+ ]+ frame = pd.DataFrame(records)+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])+ return frame.set_index("trade_date")+++def _valuation(interval: str, rows: list[tuple[str, float]]):+ market_data = fetch_market_data(+ "cn_a",+ [_SYM],+ _DAY,+ _DAY,+ loader=FakeLoader({_SYM: _frame(rows)}),+ ch_client=FakeChClient(),+ interval=interval,+ five_minute_symbols=() if interval == "5m" else None,+ )+ request = parse_request(+ {+ "account_id": "pa_5m_readiness",+ "market": "cn_a",+ "account_state": {+ "cash": 1000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}],+ },+ "orders": [],+ "from_date": _DAY,+ "to_date": _DAY,+ "fee_model": {},+ "interval": interval,+ }+ )+ return engine.match_orders(request, market_data=market_data, calendar_client=FakeCalendarClient())+++def test_5m_valuation_without_target_daily_bar_is_not_ready() -> None:+ outcome = _valuation("5m", [(_PREV, 10.0)])++ assert outcome.error is not None+ assert outcome.error.code == "PAPER_DATA_NOT_READY"+ assert f"target bar {_DAY}" in outcome.error.message+ assert outcome.fills == () and outcome.nav_series == ()+ assert outcome.end_state.cash == 1000.0+++def test_5m_valuation_with_target_daily_bar_is_ready() -> None:+ outcome = _valuation("5m", [(_PREV, 10.0), (_DAY, 10.5)])++ assert outcome.error is None+ assert outcome.fills == ()+ assert [(point.date, point.nav) for point in outcome.nav_series] == [(_DAY, 2050.0)]+++def test_5m_and_1d_agree_on_a_missing_target_bar() -> None:+ five = _valuation("5m", [(_PREV, 10.0)])+ daily = _valuation("1d", [(_PREV, 10.0)])++ assert five.error is not None and daily.error is not None+ assert five.error.code == daily.error.code == "PAPER_DATA_NOT_READY"+ assert five.error.message == daily.error.messagediff --git a/agent/tests/test_paper_trade_5m_scope.py b/agent/tests/test_paper_trade_5m_scope.pynew file mode 100644index 000000000..e8c8c68a8--- /dev/null+++ b/agent/tests/test_paper_trade_5m_scope.py@@ -0,0 +1,336 @@+"""T6 gate — the 5m input-scope gates of the public ``paper_trade_step``.++Everything here is refused (or resolved) BEFORE any provider work, so each+test asserts the in-band error shape and that the loader saw no call at all:+which cn_a symbols the 5m leg supports, one trading day per 5m step, the+measured ``stk_mins`` budget of one order symbol per step, the unmeasured BJ+leg, the 5m loader resolution (a daily-only chain cannot serve 5m), the+calendar snapshot, and a malformed provider payload.++Document shape, fills, halts and provider faults live in+``test_paper_trade_5m_tool``; UNIVERSE and order-scope gates live in+``test_paper_trade_5m_strategy``. Seed constants and payload builders are+shared from ``paper_trade_5m_fixtures``. Offline: no network, no clock, no+writes.+"""++from __future__ import annotations++import json+from typing import Any, Iterable, Mapping, Sequence++import pandas as pd+import pytest++from src.tools.paper_trade import data as data_module+from src.tools.paper_trade import data_5m+from src.tools.paper_trade import tool as tool_module+from src.tools.paper_trade.tool import run_paper_trade_step+from tests.paper_trade_5m_fixtures import (+ FixtureCalendar,+ FixtureLoader,+ _DAY,+ _HALTED,+ _SYM,+ _THIRD,+ _WITNESS,+ _install_strategy,+ _payload,+ _run,+ _strategy_payload,+ _strategy_source,+)++# ── F2/b: unsupported 5m instruments are refused before any fetch ──++[email protected]("symbol", ["600519.SH", "000001.SZ", "300750.SZ", "688981.SH"])+def test_supported_five_minute_symbols(symbol: str) -> None:+ assert data_5m.is_supported_five_minute_symbol(symbol) is True++[email protected]("symbol", ["510300.SH", "159915.SZ", "000001.SH", "399001.SZ", "00700.HK", "830799.BJ"])+def test_unsupported_five_minute_symbols(symbol: str) -> None:+ assert data_5m.is_supported_five_minute_symbol(symbol) is False++[email protected]("symbol", ["510300.SH", "159915.SZ", "000001.SH", "399001.SZ", "00700.HK", "830799.BJ"])+def test_an_unsupported_5m_instrument_is_an_in_band_refusal_before_fetch(symbol: str) -> None:+ loader = FixtureLoader()+ document, _ = _run(+ _payload(orders=[{"symbol": symbol, "side": "buy", "qty": 100}]),+ loader=loader,+ )++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert symbol in document["message"]+ assert loader.calls == []+++# ── F3: one trading day per 5m step ──+++def test_5m_multi_day_is_an_in_band_refusal_before_fetch() -> None:+ loader = FixtureLoader()+ document, _ = _run(_payload(from_date=_HALTED, to_date=_DAY), loader=loader)++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "interval 5m supports one trading day per step" in document["message"]+ assert loader.calls == []+++def test_daily_multi_day_keeps_the_existing_orders_mode_gate() -> None:+ payload = _payload(from_date=_HALTED, to_date=_DAY)+ payload.pop("interval")++ document, _ = _run(payload)++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "orders mode requires from_date == to_date" in document["message"]+++# ── N2: the measured stk_mins budget caps one 5m step at one symbol ──+++class _RateLimitedLoader(FixtureLoader):+ """The measured provider: a second 5m call in one step is refused."""++ def fetch(+ self,+ codes: Iterable[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Sequence[str] | None = None,+ ) -> Mapping[str, Any]:+ if str(interval).lower() in ("5m", "5min", "5") and self.five_minute_calls():+ self.calls.append((tuple(str(code) for code in codes), start_date, end_date, str(interval)))+ raise RuntimeError("stk_mins: 1 call/minute budget exhausted")+ return super().fetch(codes, start_date, end_date, interval=interval, fields=fields)+++def test_three_5m_order_symbols_are_refused_before_any_fetch() -> None:+ loader = FixtureLoader()+ document, _ = _run(+ _payload(+ orders=[+ {"symbol": _SYM, "side": "buy", "qty": 100},+ {"symbol": _WITNESS, "side": "buy", "qty": 1000},+ {"symbol": _THIRD, "side": "buy", "qty": 100},+ ]+ ),+ loader=loader,+ )++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "at most 1 symbol per step" in document["message"]+ assert "received 3" in document["message"]+ for symbol in (_SYM, _WITNESS, _THIRD):+ assert symbol in document["message"]+ assert loader.calls == []+++def test_two_5m_order_symbols_are_refused_before_any_fetch() -> None:+ loader = FixtureLoader()+ document, _ = _run(+ _payload(+ orders=[+ {"symbol": _SYM, "side": "buy", "qty": 100},+ {"symbol": _THIRD, "side": "buy", "qty": 100},+ ]+ ),+ loader=loader,+ )++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "at most 1 symbol per step" in document["message"]+ assert "1 call/minute, 1/hour, 2/day" in document["message"]+ assert "received 2" in document["message"]+ for symbol in (_SYM, _THIRD):+ assert symbol in document["message"]+ assert loader.calls == []+++def test_one_5m_order_symbol_issues_exactly_one_provider_call() -> None:+ loader = _RateLimitedLoader()+ document, _ = _run(_payload(), loader=loader)++ assert [(fill["symbol"], fill["price"]) for fill in document["fills"]] == [(_SYM, 1421.50)]+ assert len(loader.five_minute_calls()) == 1+ assert loader.five_minute_calls()[0][0] == (_SYM,)+++def test_a_5m_strategy_universe_over_the_budget_is_refused_before_any_fetch() -> None:+ path = _install_strategy("wide_universe_5m.py", _strategy_source(_SYM, _WITNESS, _THIRD))+ loader = FixtureLoader()+ document, _ = _run(_strategy_payload(path), loader=loader)++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "at most 1 symbol per step" in document["message"]+ assert "received 3" in document["message"]+ assert loader.calls == []+++# ── N7: BJ 5m is unmeasured and refused for P0 ──+++def test_bj_5m_is_refused_until_the_leg_is_measured() -> None:+ loader = FixtureLoader()+ document, _ = _run(+ _payload(orders=[{"symbol": "830799.BJ", "side": "buy", "qty": 100}]),+ loader=loader,+ )++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "830799.BJ" in document["message"]+ assert "BJ 4xx" not in document["message"]+ assert loader.calls == []+++# ── The 5m leg resolves its own loader; the daily chain cannot serve it ──+++class _DailyOnlyLoader:+ """The shape of the a_share daily chain head (``TencentRawLoader``)."""++ name = "tencent_raw"++ def is_available(self) -> bool:+ return True++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ if interval != "1D":+ raise ValueError("Paper execution requires daily bars")+ return {}+++def test_a_daily_only_loader_is_reported_as_a_5m_fetch_failure() -> None:+ document, _ = _run(_payload(), loader=_DailyOnlyLoader())++ assert document["status"] == "error"+ assert document["code"] == "PAPER_DATA_NOT_READY"+ assert "5m fetch" in document["message"]+ assert "tencent_raw" in document["message"]+ assert "provider omitted" not in document["message"]+++def test_a_missing_5m_loader_names_the_loader_not_the_provider(monkeypatch) -> None:+ monkeypatch.setattr(data_module, "_resolve_five_minute_loader", lambda loader: None)++ result = data_module.fetch_market_data(+ "cn_a",+ (_SYM,),+ _DAY,+ _DAY,+ loader=FixtureLoader(),+ ch_client=None,+ interval="5m",+ five_minute_symbols=(_SYM,),+ )+ verdict = data_module.assess_readiness(result, _DAY)++ assert verdict.ready is False+ assert verdict.code == "PAPER_DATA_NOT_READY"+ assert "no available 5m loader" in (verdict.message or "")+ assert "provider omitted" not in (verdict.message or "")+++def test_auto_resolution_uses_the_stk_mins_loader_not_the_daily_chain(monkeypatch) -> None:+ import backtest.loaders.tushare as tushare_loader++ class _FakeTushare:+ name = "tushare"++ def is_available(self) -> bool:+ return True++ monkeypatch.setattr(tushare_loader, "DataLoader", _FakeTushare)++ assert isinstance(data_module._resolve_five_minute_loader(data_module._AUTO), _FakeTushare)+++def test_auto_resolution_refuses_when_no_5m_loader_is_configured(monkeypatch) -> None:+ import backtest.loaders.tushare as tushare_loader++ def _unavailable():+ raise RuntimeError("TUSHARE_TOKEN is not configured")++ monkeypatch.setattr(tushare_loader, "DataLoader", _unavailable)++ assert data_module._resolve_five_minute_loader(data_module._AUTO) is None+++# ── The calendar is snapshotted once and that snapshot reaches the engine ──+++def test_the_calendar_is_snapshotted_once_and_passed_to_the_engine(monkeypatch) -> None:+ class _CountingConnector:+ def __init__(self) -> None:+ self.calendar_reads = 0++ def query(self, sql, *args, **kwargs):+ return pd.DataFrame()++ def get_trade_calendar(self, start_date, end_date):+ self.calendar_reads += 1+ return FixtureCalendar((end_date,)).get_trade_calendar(start_date, end_date)++ connector = _CountingConnector()+ builds: list[int] = []++ def _build():+ builds.append(1)+ return connector++ monkeypatch.setattr(tool_module, "_default_cn_a_connector", _build)++ document = json.loads(+ run_paper_trade_step(+ _payload(),+ loader=FixtureLoader(),+ ch_client=None,+ calendar_client=tool_module._AUTO,+ limits_client=None,+ )+ )++ assert "status" not in document, document+ assert len(builds) == 1+ assert connector.calendar_reads == 1+++# ── A malformed provider payload is data-not-ready, not a caller error ──+++class _MalformedPayloadLoader(FixtureLoader):+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ if interval == "5m":+ return {+ codes[0]: pd.DataFrame(+ {+ "trade_time": ["not-a-timestamp"],+ "open": [1.0],+ "high": [1.0],+ "low": [1.0],+ "close": [1.0],+ "vol": [1.0],+ }+ )+ }+ return super().fetch(codes, start_date, end_date, interval=interval, fields=fields)+++def test_a_malformed_5m_payload_is_data_not_ready_not_invalid_request() -> None:+ document, _ = _run(_payload(), loader=_MalformedPayloadLoader())++ assert document["status"] == "error"+ assert document["code"] == "PAPER_DATA_NOT_READY", document+ assert "could not be parsed" in document["message"]diff --git a/agent/tests/test_paper_trade_5m_session.py b/agent/tests/test_paper_trade_5m_session.pynew file mode 100644index 000000000..c0fc0e1f7--- /dev/null+++ b/agent/tests/test_paper_trade_5m_session.py@@ -0,0 +1,357 @@+"""T4 gate — cn_a session shape, 5m bar assembly and session events.++The normal-day fixture is a real 5m shape: 49 raw rows (the 09:30 opening+call-auction print plus 48 continuous bars). The session bar must be built+from the 48 continuous bars only, a normal day must emit NO events, a halted+symbol-day must emit only ``halted``, an auction-window label must be+excluded and reported, and a whole-universe zero-bar day must fail closed as+``PAPER_DATA_NOT_READY`` instead of inventing a halt (D6).+Offline: committed fixtures and in-test frames, never the network.+"""++from __future__ import annotations++import datetime as dt+from pathlib import Path++import pandas as pd+import pytest++from src.tools.paper_trade import calendar, engine+from src.tools.paper_trade.data import NOT_READY_CODE, fetch_market_data+from src.tools.paper_trade.schema import parse_request++_DAY = "2026-10-20"+_PREV = "2026-10-19"+_SYM = "600519.SH"+_OTHER = "000001.SZ"+_FIXTURE_DIR = Path(__file__).parent / "fixtures" / "paper_trade" / "5m" / _SYM+++def _fixture_5m(day: str = _DAY) -> pd.DataFrame:+ frame = pd.read_csv(_FIXTURE_DIR / f"{day}.csv", parse_dates=["bar_time"])+ return frame.set_index("bar_time")+++def _labels(day: str = _DAY) -> list[str]:+ stamps: list[str] = []+ for hour, minute in ((9, 30), (13, 0)):+ start = dt.datetime.fromisoformat(f"{day}T{hour:02d}:{minute:02d}:00")+ stamps.extend((start + dt.timedelta(minutes=5 * step)).strftime("%H:%M") for step in range(1, 25))+ return stamps+++def _intraday(day: str, prices: dict[str, float], auction: float | None = None) -> pd.DataFrame:+ records = []+ if auction is not None:+ records.append(+ {+ "bar_time": f"{day} 09:30",+ "open": auction,+ "high": auction,+ "low": auction,+ "close": auction,+ "volume": 48000.0,+ }+ )+ for label, price in prices.items():+ records.append(+ {+ "bar_time": f"{day} {label}",+ "open": price,+ "high": price,+ "low": price,+ "close": price,+ "volume": 120000.0,+ }+ )+ frame = pd.DataFrame(records)+ frame["bar_time"] = pd.to_datetime(frame["bar_time"])+ return frame.set_index("bar_time")+++def _daily(rows: list[tuple[str, float]]) -> pd.DataFrame:+ records = [+ {"trade_date": day, "open": close, "high": close, "low": close, "close": close, "volume": 1000.0}+ for day, close in rows+ ]+ frame = pd.DataFrame(records)+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])+ return frame.set_index("trade_date")+++class FakeChClient:+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:+ return pd.DataFrame()+++class FakeLoader:+ def __init__(self, daily: dict[str, pd.DataFrame], five: dict[str, pd.DataFrame] | None = None) -> None:+ self.name = "tencent"+ self._daily = daily+ self._five = five or {}+ self.calls: list[tuple[tuple[str, ...], str, str, str]] = []++ def is_available(self) -> bool:+ return True++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ self.calls.append((tuple(codes), start_date, end_date, interval))+ source = self._five if interval == "5m" else self._daily+ return {code: source[code] for code in codes if code in source}+++class FakeCalendarClient:+ def __init__(self, open_days: frozenset[str]) -> None:+ self._open = open_days++ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:+ rows = [+ {+ "exchange": "SSE",+ "cal_date": day.strftime("%Y-%m-%d"),+ "is_open": int(day.strftime("%Y-%m-%d") in self._open),+ "pretrade_date": "",+ }+ for day in pd.date_range(start_date, end_date)+ ]+ return pd.DataFrame(rows, columns=["exchange", "cal_date", "is_open", "pretrade_date"])+++def _fetch(daily, five, *, symbols=(_SYM,), interval="5m", from_date=_DAY, to_date=_DAY):+ loader = FakeLoader(daily, five)+ return (+ fetch_market_data(+ "cn_a", list(symbols), from_date, to_date, loader=loader, ch_client=FakeChClient(), interval=interval+ ),+ loader,+ )+++def _daily_tape(*symbols: str, day_close: float = 1422.0) -> dict[str, pd.DataFrame]:+ return {symbol: _daily([(_PREV, 1421.0), (_DAY, day_close)]) for symbol in symbols}+++def _run(market_data, orders=(), *, cash=1000000.0, positions=(), open_days=frozenset({_DAY}), path_model="bar_median"):+ request = parse_request(+ {+ "account_id": "pa_5m_session",+ "market": "cn_a",+ "account_state": {"cash": cash, "positions": list(positions)},+ "orders": list(orders),+ "from_date": _DAY,+ "to_date": _DAY,+ "interval": "5m",+ "path_model": path_model,+ }+ )+ return engine.match_orders(request, market_data=market_data, calendar_client=FakeCalendarClient(open_days))+++def test_normal_day_has_48_continuous_bars_and_no_events() -> None:+ market_data, _ = _fetch(_daily_tape(_SYM), {_SYM: _fixture_5m()})+ symbol_data = market_data.data[_SYM]++ continuous = symbol_data.bars_5m[_DAY]+ assert len(continuous) == calendar.CONTINUOUS_BARS_PER_DAY == 48+ assert continuous.index.strftime("%H:%M").tolist() == _labels()+ assert symbol_data.session_bar is not None+ bar = symbol_data.session_bar+ assert (bar.open, bar.high, bar.low, bar.close, bar.bar_count) == (1421.0, 1422.0, 1421.0, 1422.0, 48)+ assert bar.volume == 47 * 120000.0 + 120000.0++ outcome = _run(market_data)+ assert outcome.events == ()+ assert outcome.canceled_orders == ()+ assert outcome.fills == outcome.rejected_orders == ()+ assert outcome.warnings == ()+++def test_auction_print_is_excluded_from_the_session_bar() -> None:+ market_data, _ = _fetch(_daily_tape(_SYM), {_SYM: _fixture_5m()})+ labels = market_data.data[_SYM].bars_5m[_DAY].index.strftime("%H:%M").tolist()++ assert "09:30" not in labels+ # Including the 09:30 print (1423.00) would raise the session open to+ # 1423.00 and the close/median would move; the assembled bar proves the+ # exclusion changed a real number.+ assert market_data.data[_SYM].session_bar.open == 1421.0+ assert market_data.data[_SYM].auction_labels == {}+++def test_closing_auction_window_label_is_excluded_and_reported() -> None:+ prices = {label: 1421.0 for label in _labels()}+ prices["14:58"] = 99.0+ frame = _intraday(_DAY, prices, auction=1423.0)+ market_data, _ = _fetch(_daily_tape(_SYM), {_SYM: frame})++ symbol_data = market_data.data[_SYM]+ assert "14:58" not in symbol_data.bars_5m[_DAY].index.strftime("%H:%M")+ assert symbol_data.session_bar.high == 1421.0 # 99.0 never pollutes the bar+ assert symbol_data.auction_labels[_DAY] == ("14:58",)+ assert any("auction-window label(s) 14:58" in warning for warning in market_data.warnings)++ outcome = _run(market_data)+ assert [(e.trade_date, e.symbol, e.event_type) for e in outcome.events] == [(_DAY, _SYM, "auction_window")]+ assert "14:58" in outcome.events[0].detail+++def test_partial_gap_warns_with_the_bar_count_and_still_matches() -> None:+ partial = {label: 10.0 for label in _labels()[:30]}+ market_data, _ = _fetch({_SYM: _daily([(_PREV, 10.0), (_DAY, 10.0)])}, {_SYM: _intraday(_DAY, partial)})++ symbol_data = market_data.data[_SYM]+ assert len(symbol_data.bars_5m[_DAY]) == 30+ assert symbol_data.session_bar.bar_count == 30+ assert any("30/48 continuous bars" in warning for warning in market_data.warnings)++ outcome = _run(market_data, orders=[{"symbol": _SYM, "side": "buy", "qty": 100}])+ assert [(f.side, f.price) for f in outcome.fills] == [("buy", 10.0)]+ assert outcome.rejected_orders == ()+++def test_halted_symbol_emits_only_halted_and_leaves_the_ledger_alone() -> None:+ # The halted symbol has NO daily bar for the day either (Tushare omits a+ # suspended day from both endpoints); the other symbol traded, so the day+ # is ready and the halt is a per-symbol fact.+ daily = {_SYM: _daily([(_PREV, 10.0), (_DAY, 10.2)]), _OTHER: _daily([(_PREV, 20.0)])}+ market_data, _ = _fetch(+ daily, {_SYM: _intraday(_DAY, {label: 10.0 for label in _labels()})}, symbols=(_SYM, _OTHER)+ )+ outcome = _run(+ market_data,+ orders=[{"symbol": _OTHER, "side": "buy", "qty": 100}],+ positions=[{"symbol": _OTHER, "qty": 100, "avg_cost": 20.0}],+ )++ assert [(e.symbol, e.event_type) for e in outcome.events] == [(_OTHER, "halted")]+ assert [(r.symbol, r.reason_code) for r in outcome.rejected_orders] == [(_OTHER, "suspended")]+ assert outcome.fills == ()+ assert [(p.symbol, p.qty, p.avg_cost) for p in outcome.end_state.positions] == [(_OTHER, 100.0, 20.0)]+ assert outcome.nav_series[0].position_value == 2000.0+++def test_whole_universe_zero_bars_is_data_not_ready() -> None:+ daily = {_SYM: _daily([(_PREV, 10.0)]), _OTHER: _daily([(_PREV, 20.0)])}+ market_data, _ = _fetch(daily, {}, symbols=(_SYM, _OTHER))++ outcome = _run(market_data, orders=[{"symbol": _SYM, "side": "buy", "qty": 100}])++ assert outcome.error is not None+ assert outcome.error.code == NOT_READY_CODE+ assert outcome.fills == outcome.canceled_orders == outcome.events == ()+ assert market_data.five_minute_contradiction == {}+++def test_daily_bar_without_a_5m_bar_is_a_provider_fault_not_a_halt() -> None:+ # The daily bar proves the symbol traded; a provider error that returns+ # no 5m bars must fail closed as data-not-ready, never as "halted" (D6).+ daily = {_SYM: _daily([(_PREV, 10.0), (_DAY, 10.2)]), _OTHER: _daily([(_PREV, 20.0), (_DAY, 20.0)])}+ five = {_OTHER: _intraday(_DAY, {label: 20.0 for label in _labels()})}+ market_data, _ = _fetch(daily, five, symbols=(_SYM, _OTHER))++ assert market_data.five_minute_contradiction == {_DAY: (_SYM,)}+ outcome = _run(market_data, orders=[{"symbol": _SYM, "side": "buy", "qty": 100}])++ assert outcome.error is not None+ assert outcome.error.code == NOT_READY_CODE+ assert "provider omitted the 5m leg" in outcome.error.message+ assert _SYM in outcome.error.message+ assert "halted" not in outcome.error.message+ assert outcome.events == () and outcome.fills == ()+++def test_calendar_closed_day_emits_non_trading_day_and_never_fills() -> None:+ market_data, _ = _fetch(_daily_tape(_SYM), {_SYM: _fixture_5m()})+ outcome = _run(market_data, orders=[{"symbol": _SYM, "side": "buy", "qty": 100}], open_days=frozenset())++ assert [(e.trade_date, e.symbol, e.event_type) for e in outcome.events] == [(_DAY, "", "non_trading_day")]+ assert [(s.date, s.reason) for s in outcome.skipped_days] == [(_DAY, "non_trading_day")]+ assert [r.reason_code for r in outcome.rejected_orders] == ["non_trading_day"]+ assert [c.reason_code for c in outcome.canceled_orders] == ["canceled_after_failed_match"]+ assert outcome.fills == ()+++def test_one_ranged_5m_call_with_an_exclusive_end_bound() -> None:+ market_data, loader = _fetch(_daily_tape(_SYM), {_SYM: _fixture_5m()})+ five_calls = [call for call in loader.calls if call[3] == "5m"]++ assert len(five_calls) == 1+ codes, start, end, _ = five_calls[0]+ assert codes == (_SYM,)+ assert start == _DAY+ assert end == "2026-10-21" # provider end bound is exclusive at midnight+ assert market_data.interval == "5m"+++def test_1d_fetch_never_issues_a_5m_request() -> None:+ daily = _daily_tape(_SYM)+ market_data, loader = _fetch(daily, {_SYM: _fixture_5m()}, interval="1d")++ assert [call[3] for call in loader.calls] == ["1D"]+ assert market_data.interval == "1d"+ assert len(market_data.bar_fingerprint) == 64+ assert market_data.data[_SYM].bars_5m == {}+ assert market_data.data[_SYM].session_bar is None+++def test_bar_fingerprint_is_symbol_order_independent_and_deterministic() -> None:+ daily = _daily_tape(_SYM, _OTHER)+ five = {_SYM: _fixture_5m(), _OTHER: _intraday(_DAY, {label: 20.0 for label in _labels()})}+ first, _ = _fetch(daily, five, symbols=(_SYM, _OTHER))+ second, _ = _fetch(daily, five, symbols=(_OTHER, _SYM))++ assert len(first.bar_fingerprint) == 64+ assert first.bar_fingerprint == second.bar_fingerprint++ changed = dict(five)+ changed[_OTHER] = _intraday(_DAY, {label: 20.5 for label in _labels()})+ third, _ = _fetch(daily, changed, symbols=(_SYM, _OTHER))+ assert third.bar_fingerprint != first.bar_fingerprint+++def test_duplicate_label_keeps_the_last_row() -> None:+ first = _intraday(_DAY, {label: 10.0 for label in _labels()})+ duplicate = _intraday(_DAY, {"10:00": 10.9})+ frame = pd.concat([first, duplicate]).sort_index(kind="stable")+ market_data, _ = _fetch({_SYM: _daily([(_PREV, 10.0), (_DAY, 10.0)])}, {_SYM: frame})++ labels = market_data.data[_SYM].bars_5m[_DAY].index.strftime("%H:%M").tolist()+ assert labels.count("10:00") == 1+ assert market_data.data[_SYM].bars_5m[_DAY].loc[pd.Timestamp(f"{_DAY} 10:00"), "close"] == 10.9+++def test_5m_is_refused_outside_cn_a_and_unknown_intervals_are_refused() -> None:+ with pytest.raises(ValueError, match="cn_a-only"):+ fetch_market_data("us", ["AAPL.US"], _DAY, _DAY, loader=FakeLoader({}), interval="5m")+ with pytest.raises(ValueError, match="unknown interval"):+ fetch_market_data("cn_a", [_SYM], _DAY, _DAY, loader=FakeLoader({}), interval="1m")+++ ("label", "kind"),+ [+ ("09:30", calendar.SESSION_OPENING_AUCTION_PRINT),+ ("09:15", calendar.SESSION_AUCTION_WINDOW),+ ("09:25", calendar.SESSION_AUCTION_WINDOW),+ ("09:35", calendar.SESSION_CONTINUOUS),+ ("11:30", calendar.SESSION_CONTINUOUS),+ ("11:35", calendar.SESSION_OUTSIDE),+ ("13:00", calendar.SESSION_OUTSIDE),+ ("13:05", calendar.SESSION_CONTINUOUS),+ ("14:57", calendar.SESSION_AUCTION_WINDOW),+ ("14:59", calendar.SESSION_AUCTION_WINDOW),+ ("15:00", calendar.SESSION_CONTINUOUS),+ ("15:05", calendar.SESSION_OUTSIDE),+ ],+)+def test_session_label_classification_matrix(label: str, kind: str) -> None:+ assert calendar.classify_cn_a_session_label(label) == kind+++def test_session_constants_are_the_frozen_cn_a_windows() -> None:+ assert calendar.CN_A_SESSION_TIMEZONE == "Asia/Shanghai"+ assert calendar.CONTINUOUS_MORNING == ("09:30", "11:30")+ assert calendar.CONTINUOUS_AFTERNOON == ("13:00", "15:00")+ assert calendar.OPENING_AUCTION == ("09:15", "09:25")+ assert calendar.CLOSING_AUCTION == ("14:57", "15:00")diff --git a/agent/tests/test_paper_trade_5m_strategy.py b/agent/tests/test_paper_trade_5m_strategy.pynew file mode 100644index 000000000..4895817e3--- /dev/null+++ b/agent/tests/test_paper_trade_5m_strategy.py@@ -0,0 +1,192 @@+"""T6 gate — the 5m strategy-mode gates of the public ``paper_trade_step``.++A 5m strategy step is driven by the strategy file the caller points at, so the+declared UNIVERSE is the only thing that can bound the order set. These tests+pin that contract: a 5m strategy must declare an explicit non-empty UNIVERSE+before any fetch; it may not order outside that declaration (a refusal, not a+per-symbol suspension); an inside order still fills; 1d keeps its old,+ungated behaviour; and the strategy path honours the declared reference-price+model.++Input-scope gates (symbol support, multi-day, symbol budget, BJ, loader+resolution, calendar) live in ``test_paper_trade_5m_scope``; document shape,+fills and provider faults live in ``test_paper_trade_5m_tool``. Seed+constants, payload builders and the strategy sources are shared from+``paper_trade_5m_fixtures``. Offline: no network, no clock, no writes.+"""++from __future__ import annotations++import json++from src.tools.paper_trade.wire import received_state_hash_from_payload+from tests.paper_trade_5m_fixtures import (+ FixtureLoader,+ _SYM,+ _WITNESS,+ _install_strategy,+ _outside_universe_source,+ _run,+ _strategy_payload,+ _strategy_source,+)++# ── N1: 5m strategy mode requires an explicit UNIVERSE ──+++def test_a_5m_strategy_without_a_universe_is_refused_before_any_fetch() -> None:+ path = _install_strategy("no_universe_5m.py", _strategy_source())+ loader = FixtureLoader()+ document, _ = _run(+ _strategy_payload(+ path,+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],+ },+ ),+ loader=loader,+ )++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "explicit non-empty UNIVERSE" in document["message"]+ assert "rejected_orders" not in document+ assert "suspended" not in json.dumps(document)+ assert loader.calls == []+++def test_a_5m_strategy_with_a_universe_fills_and_leaves_an_outside_position_alone() -> None:+ path = _install_strategy("universe_5m.py", _strategy_source(_SYM))+ loader = FixtureLoader()+ document, _ = _run(+ _strategy_payload(+ path,+ account_state={+ "cash": 1_000_000.0,+ "positions": [+ {"symbol": _SYM, "qty": 100, "avg_cost": 1421.0},+ {"symbol": _WITNESS, "qty": 1000, "avg_cost": 10.0},+ ],+ },+ ),+ loader=loader,+ )++ assert "status" not in document+ assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [+ (_SYM, "sell", 100.0, 1421.50)+ ]+ assert document["events"] == []+ assert document["rejected_orders"] == []+ assert loader.five_minute_calls()[0][0] == (_SYM,)+ witness = next(position for position in document["end_state"]["positions"] if position["symbol"] == _WITNESS)+ assert (witness["qty"], witness["avg_cost"]) == (1000.0, 10.0)+++def test_a_1d_strategy_without_a_universe_keeps_running() -> None:+ path = _install_strategy("no_universe_1d.py", _strategy_source())+ payload = _strategy_payload(+ path,+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],+ },+ )+ payload.pop("interval")++ document, _ = _run(payload)++ assert document["schema_version"] == "pt-v1.1"+ assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [+ (_SYM, "sell", 100.0, 1422.0)+ ]+++# ── N1-B: a 5m strategy may not order outside its declared UNIVERSE ──+++def test_a_5m_strategy_order_outside_its_universe_is_refused_not_suspended() -> None:+ path = _install_strategy("outside_order_5m.py", _outside_universe_source((_SYM,), _WITNESS))+ payload = _strategy_payload(+ path,+ account_state={+ "cash": 1_000_000.0,+ "positions": [+ {"symbol": _SYM, "qty": 100, "avg_cost": 1421.0},+ {"symbol": _WITNESS, "qty": 1000, "avg_cost": 10.0},+ ],+ },+ )+ loader = FixtureLoader()+ document, _ = _run(payload, loader=loader)++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert _WITNESS in document["message"]+ assert "outside the 5m UNIVERSE" in document["message"]+ assert _SYM in document["message"]+ assert document.get("fills", []) == []+ assert document.get("rejected_orders", []) == []+ assert "suspended" not in json.dumps(document)+ assert "end_state" not in document+ assert document["received_state_hash"] == received_state_hash_from_payload(payload)+ assert loader.five_minute_calls()[0][0] == (_SYM,)+++def test_a_5m_strategy_order_inside_its_universe_still_fills() -> None:+ path = _install_strategy("inside_order_5m.py", _outside_universe_source((_SYM,), _SYM))+ document, _ = _run(+ _strategy_payload(+ path,+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],+ },+ )+ )++ assert "status" not in document+ assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [+ (_SYM, "sell", 100.0, 1421.50)+ ]+ assert document["rejected_orders"] == []+ assert document["events"] == []+++def test_a_1d_strategy_order_outside_its_universe_is_not_gated() -> None:+ path = _install_strategy("outside_order_1d.py", _outside_universe_source((_SYM,), _WITNESS))+ payload = _strategy_payload(+ path,+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _WITNESS, "qty": 1000, "avg_cost": 10.0}],+ },+ )+ payload.pop("interval")+ loader = FixtureLoader()+ document, _ = _run(payload, loader=loader)++ assert document["schema_version"] == "pt-v1.1"+ assert "status" not in document+ assert document["fills"] == []+ assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [(_WITNESS, "suspended")]+ assert loader.five_minute_calls() == []+++# ── The strategy path honours the declared reference-price model ──+++def test_a_5m_strategy_honours_the_declared_path_model() -> None:+ path = _install_strategy("path_model_5m.py", _strategy_source(_SYM))+ account_state = {+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],+ }++ median_document, _ = _run(_strategy_payload(path, account_state=account_state, path_model="bar_median"))+ close_document, _ = _run(_strategy_payload(path, account_state=account_state, path_model="bar_close"))++ assert median_document["fills"][0]["price"] == 1421.50+ assert close_document["fills"][0]["price"] == 1422.00+ assert median_document["engine_fingerprint"] != close_document["engine_fingerprint"]diff --git a/agent/tests/test_paper_trade_5m_tool.py b/agent/tests/test_paper_trade_5m_tool.pynew file mode 100644index 000000000..be68d06a7--- /dev/null+++ b/agent/tests/test_paper_trade_5m_tool.py@@ -0,0 +1,383 @@+"""T6 gate — the public ``paper_trade_step`` surface for cn_a 5m (document leg).++The engine-only suites (T3/T4) prove matching against in-test frames. This+suite drives the SAME public entry point the runner consumes, with the loader+injected: the document shape, the normal fill and its path-model reference,+the halted session, the frozen v1.1 document when no new field is used, the+fetch evidence carried by the returned string, the order-symbol-only 5m leg,+a provider omission, and the U6 rule that a provider fault (anything that is+not a ``ValueError`` input guard) is retryable ``PAPER_DATA_NOT_READY`` —+never a transport crash and never a halt.++The input-scope gates (symbol support, multi-day, symbol budget, BJ, loader+resolution) live in ``test_paper_trade_5m_scope``; the strategy-mode gates+(UNIVERSE declaration, order scope, 1d non-gating, path model) live in+``test_paper_trade_5m_strategy``. The seed constants and payload builders are+shared from ``paper_trade_5m_fixtures``.++Every price is re-derived from the committed CSV fixtures by the test (see+``paper_trade_5m_fixtures.fixture_reference``), so a wrong reference inside+the engine cannot make an assertion agree with it. Offline: no network, no+clock, no writes.+"""++from __future__ import annotations++import json+from typing import Any, Iterable, Mapping, Sequence++import pytest++from src.tools.paper_trade import tool as tool_module+from src.tools.paper_trade.schema import CANCELED_REASON_CODE+from src.tools.paper_trade.tool import PaperTradeDocument, run_paper_trade_step+from tests.paper_trade_5m_fixtures import (+ FixtureCalendar,+ FixtureLoader,+ _DAY,+ _HALTED,+ _SHA_RE,+ _SYM,+ _WITNESS,+ _payload,+ _run,+ derive_daily,+ fixture_reference,+ load_5m,+ load_5m_all,+ session_values,+)++#: The session bar the fixture actually encodes (T1 shape: 09:30 excluded).+_NORMAL_BAR = {"open": 1421.0, "high": 1422.0, "low": 1421.0, "close": 1422.0}+++ ("path_model", "expected"),+ [("bar_median", 1421.50), ("bar_close", 1422.00)],+)+def test_normal_day_fills_exactly_at_the_recomputed_reference(path_model: str, expected: float) -> None:+ document, _ = _run(_payload(path_model=path_model))++ assert document["schema_version"] == "pt-v1.2"+ assert _SHA_RE.match(document["engine_fingerprint"])+ assert [(fill["symbol"], fill["side"], fill["qty"], fill["price"]) for fill in document["fills"]] == [+ (_SYM, "buy", 100.0, expected)+ ]+ assert document["fills"][0]["price"] == float(fixture_reference(_SYM, _DAY, path_model))+ assert document["canceled_orders"] == []+ assert document["events"] == []+ assert document["rejected_orders"] == []+ assert document["warnings"] == []+ assert document["data_provenance"]["source"] == "fixture"+++def test_the_two_path_models_produce_different_prices_and_fingerprints() -> None:+ median, _ = _run(_payload(path_model="bar_median"))+ close, _ = _run(_payload(path_model="bar_close"))++ assert median["fills"][0]["price"] == 1421.50+ assert close["fills"][0]["price"] == 1422.00+ assert median["engine_fingerprint"] != close["engine_fingerprint"]+++def test_non_marketable_limit_is_rejected_and_emergency_canceled() -> None:+ document, _ = _run(_payload(orders=[{"symbol": _SYM, "side": "buy", "qty": 100, "limit": 1.0}]))++ assert document["fills"] == []+ assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [+ (_SYM, "limit_not_marketable")+ ]+ assert document["rejected_orders"][0]["detail"] == "ref 1421.50 > limit 1.00"+ assert [(row["symbol"], row["reason_code"]) for row in document["canceled_orders"]] == [+ (_SYM, CANCELED_REASON_CODE)+ ]+ assert document["events"] == []+++def test_halted_session_fills_nothing_and_reports_only_halted() -> None:+ document, _ = _run(+ _payload(+ from_date=_HALTED,+ to_date=_HALTED,+ account_state={+ "cash": 1_000_000.0,+ "positions": [+ {"symbol": _SYM, "qty": 100, "avg_cost": 1421.0},+ {"symbol": _WITNESS, "qty": 1000, "avg_cost": 10.0},+ ],+ },+ )+ )++ assert document["fills"] == []+ assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [(_SYM, "suspended")]+ assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_SYM, "halted")]+ assert len(document["canceled_orders"]) == 1+ assert document["end_state"]["cash"] == 1_000_000.0+ assert {row["symbol"]: row["qty"] for row in document["end_state"]["positions"]} == {+ _SYM: 100.0,+ _WITNESS: 1000.0,+ }+++def test_a_v1_1_call_keeps_the_frozen_document() -> None:+ payload = _payload()+ for key in ("interval", "path_model", "fill_model", "session"):+ payload.pop(key, None)++ document, _ = _run(payload)++ assert document["schema_version"] == "pt-v1.1"+ assert "engine_fingerprint" not in document+ assert "canceled_orders" not in document+ assert "events" not in document+ assert document["fills"][0]["price"] == session_values(load_5m(_SYM, _DAY))["close"]+++def test_a_v1_2_field_silently_downgraded_to_v1_1_shows_up_only_in_the_hash() -> None:+ """A v1.2 payload sent to a v1.1 parser runs the daily path, but the hash differs.++ The v1.1 parser has no fields for the four selectors, so it ignores them. The+ successful document is the frozen v1.1 shape; the non-default interval changes+ ``received_state_hash``, which is the client-side downgrade signal.+ """++ v12_document, _ = _run(_payload())+ v11_payload = _payload()+ for key in ("interval", "path_model", "fill_model", "session"):+ v11_payload.pop(key, None)+ v11_document, _ = _run(v11_payload)++ assert v12_document["schema_version"] == "pt-v1.2"+ assert v11_document["schema_version"] == "pt-v1.1"+ assert isinstance(v12_document["received_state_hash"], str)+ assert isinstance(v11_document["received_state_hash"], str)+ assert len(v12_document["received_state_hash"]) == 64+ assert len(v11_document["received_state_hash"]) == 64+ for key in ("engine_fingerprint", "canceled_orders", "events"):+ assert key not in v11_document+ assert v11_document["received_state_hash"] != v12_document["received_state_hash"]+ assert v11_document["fills"][0]["price"] == session_values(load_5m(_SYM, _DAY))["close"]+ assert v12_document["fills"][0]["price"] == fixture_reference(_SYM, _DAY, "bar_median")+++def test_fixture_loader_serves_both_legs_and_the_step_issues_one_5m_call() -> None:+ loader = FixtureLoader()+ document, same = _run(_payload(), loader=loader)++ assert document["fills"], document+ assert len(same.five_minute_calls()) == 1+ assert same.five_minute_calls()[0] == ((_SYM,), _DAY, "2026-10-21", "5m")+ assert [call for call in same.calls if call[3] == "1D"]++ raw = load_5m(_SYM, _DAY)+ assert len(raw) == 49+ daily = derive_daily(_SYM)+ assert list(daily["close"]) == [1420.0, 1422.0]+ assert _NORMAL_BAR == {key: session_values(raw)[key] for key in _NORMAL_BAR}++[email protected]("fault", [RuntimeError("permission denied"), OSError("network down")])+def test_a_provider_fault_is_in_band_data_not_ready(fault: Exception, monkeypatch) -> None:+ def boom(*args: Any, **kwargs: Any) -> Any:+ raise fault++ monkeypatch.setattr(tool_module.data, "fetch_market_data", boom)++ document, _ = _run(_payload())++ assert document["status"] == "error"+ assert document["code"] == "PAPER_DATA_NOT_READY"+ assert type(fault).__name__ in document["message"]+ assert "halted" not in document["message"]+++def test_a_value_error_stays_a_non_retryable_invalid_request(monkeypatch) -> None:+ def boom(*args: Any, **kwargs: Any) -> Any:+ raise ValueError("unknown market for paper data fetch: 'xx'")++ monkeypatch.setattr(tool_module.data, "fetch_market_data", boom)++ document, _ = _run(_payload())++ assert document["status"] == "error"+ assert document["code"] == "INVALID_REQUEST"+ assert "unknown market" in document["message"]+++def test_the_document_is_a_str_that_carries_the_fetch_evidence() -> None:+ loader = FixtureLoader()+ raw = run_paper_trade_step(+ _payload(),+ loader=loader,+ ch_client=None,+ calendar_client=FixtureCalendar((_DAY,)),+ limits_client=None,+ )++ assert isinstance(raw, str)+ assert isinstance(raw, PaperTradeDocument)+ assert raw.market_data is not None+ assert raw.market_data.interval == "5m"+ assert raw.market_data.data[_SYM].session_bar is not None+ assert json.loads(raw)["schema_version"] == "pt-v1.2"+ assert str(raw) == raw+++class _NoFiveMinuteLoader(FixtureLoader):+ """Daily leg works; the provider yields no 5m rows (quota/permission)."""++ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):+ if str(interval).lower() in ("5m", "5min", "5"):+ self.calls.append((tuple(str(code) for code in codes), start_date, end_date, str(interval)))+ return {}+ return super().fetch(codes, start_date, end_date, interval=interval, fields=fields)+++# ── F2/a: the 5m leg covers the ORDER symbols only ──+++def test_positions_only_5m_step_issues_no_5m_fetch_and_advances_nav() -> None:+ loader = FixtureLoader()+ document, _ = _run(+ _payload(+ orders=[],+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],+ },+ ),+ loader=loader,+ )++ assert document["schema_version"] == "pt-v1.2"+ assert document["fills"] == []+ assert document["events"] == []+ assert document["canceled_orders"] == []+ assert loader.five_minute_calls() == []+ assert document["nav_series"][-1]["nav"] == 1_142_200.0+++def test_only_the_order_symbol_is_requested_from_the_5m_leg() -> None:+ loader = FixtureLoader()+ document, _ = _run(+ _payload(+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _WITNESS, "qty": 1000, "avg_cost": 10.0}],+ },+ ),+ loader=loader,+ )++ assert [fill["symbol"] for fill in document["fills"]] == [_SYM]+ assert len(loader.five_minute_calls()) == 1+ assert loader.five_minute_calls()[0][0] == (_SYM,)+ daily_codes = next(call[0] for call in loader.calls if call[3] == "1D")+ assert set(daily_codes) == {_SYM, _WITNESS}+++def test_a_provider_omitted_5m_leg_names_the_symbol_and_stays_retryable() -> None:+ loader = _NoFiveMinuteLoader()+ document, _ = _run(_payload(), loader=loader)++ assert document["status"] == "error"+ assert document["code"] == "PAPER_DATA_NOT_READY"+ assert _SYM in document["message"]+ assert "provider omitted the 5m leg" in document["message"]+ assert "retry after the quota window" in document["message"]+ assert "halted" not in document["message"]+ assert "inconsistent" not in document["message"]+ assert len(loader.five_minute_calls()) == 1+++def test_an_order_symbol_with_no_bar_at_all_is_halted_not_data_not_ready() -> None:+ document, _ = _run(+ _payload(+ orders=[{"symbol": _WITNESS, "side": "buy", "qty": 1000}],+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],+ },+ )+ )++ assert "status" not in document+ assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_WITNESS, "halted")]+ assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [(_WITNESS, "suspended")]+ assert document["fills"] == []+++# ── D3: a pure-valuation 5m step hashes the daily bars that produced it ──+++def test_a_5m_valuation_step_without_orders_hashes_the_daily_bars() -> None:+ def valuation(day: str) -> dict[str, Any]:+ document, _ = _run(+ _payload(+ orders=[],+ from_date=day,+ to_date=day,+ account_state={+ "cash": 1_000_000.0,+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 1421.0}],+ },+ )+ )+ return document++ earlier = valuation("2026-10-16")+ later = valuation(_DAY)+ repeated = valuation(_DAY)++ assert _SHA_RE.match(earlier["engine_fingerprint"])+ assert _SHA_RE.match(later["engine_fingerprint"])+ assert earlier["engine_fingerprint"] != later["engine_fingerprint"]+ assert repeated["engine_fingerprint"] == later["engine_fingerprint"]+++# ── N3: an auction-only day is a halt, not a provider omission ──+++class _AuctionOnlyLoader(FixtureLoader):+ """Witness has a daily bar and, on the 5m leg, only the 09:30 print."""++ def fetch(+ self,+ codes: Iterable[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Sequence[str] | None = None,+ ) -> Mapping[str, Any]:+ ordered = tuple(str(code) for code in codes)+ kind = str(interval)+ self.calls.append((ordered, start_date, end_date, kind))+ five_minute = kind.lower() in ("5m", "5min", "5")+ served: dict[str, Any] = {}+ for code in ordered:+ source = _SYM if code == _WITNESS else code+ if five_minute:+ frame = load_5m_all(source)+ frame = frame[frame.index.strftime("%H:%M") == "09:30"]+ else:+ frame = derive_daily(source)+ if not frame.empty:+ served[code] = frame.copy()+ return served+++def test_an_auction_only_symbol_with_a_daily_bar_is_halted_not_data_not_ready() -> None:+ loader = _AuctionOnlyLoader()+ document, _ = _run(+ _payload(orders=[{"symbol": _WITNESS, "side": "buy", "qty": 100}]),+ loader=loader,+ )++ assert "status" not in document, document+ assert [(row["symbol"], row["event_type"]) for row in document["events"]] == [(_WITNESS, "halted")]+ assert [(row["symbol"], row["reason_code"]) for row in document["rejected_orders"]] == [(_WITNESS, "suspended")]+ assert document["fills"] == []+ assert not any("provider omitted" in warning for warning in document["warnings"])diff --git a/agent/tests/test_paper_trade_v12_schema.py b/agent/tests/test_paper_trade_v12_schema.pynew file mode 100644index 000000000..5b2b46e60--- /dev/null+++ b/agent/tests/test_paper_trade_v12_schema.py@@ -0,0 +1,539 @@+"""T2 gate — pt-v1.2 additive contract (schema + hash + wire + tool surface).++Pins the binding decisions of the P0 5m plan: the four optional request fields+and their defaults (D8), the closed vocabularies and market-combination gates+(D5), the D3 engine fingerprint, the D4 byte-compatible state hash, and the+D8 rule that a v1.1 call emits NO v1.2 key while a v1.2 call emits exactly+three. Offline: no network, no clock, no data fetch (the 5m/hk gate returns+before the data layer is reached).+"""++from __future__ import annotations++import json+import re+import types+from dataclasses import replace+from pathlib import Path++import pytest++from src.tools.paper_trade import rules, schema as schema_module, state_hash, wire+from src.tools.paper_trade.engine import MatchOutcome+from src.tools.paper_trade.schema import (+ CANCELED_REASON_CODE,+ DEFAULT_FILL_MODEL,+ DEFAULT_INTERVAL,+ DEFAULT_PATH_MODEL,+ DEFAULT_SESSION,+ FILL_MODELS,+ INTERVALS,+ PATH_MODELS,+ SCHEMA_VERSION,+ SCHEMA_VERSION_V1_2,+ SCHEMA_VERSIONS,+ SESSION_EVENT_TYPES,+ SESSIONS,+ AccountState,+ CanceledOrder,+ DataProvenance,+ DateRange,+ Fill,+ NavPoint,+ PaperTradeSchemaError,+ PaperTradeStepResult,+ RejectedOrder,+ SessionEvent,+ SkippedDay,+ load_contract_schema,+ parse_request,+ validate_payload,+)+from src.tools.paper_trade.tool import PaperTradeStepTool, run_paper_trade_step++_CONTRACT_DIR = Path(__file__).resolve().parents[1] / "src" / "tools" / "paper_trade"+_PUBLISHED_CONTRACT_DIR = Path(__file__).resolve().parents[2] / "schema" / "tool_contracts"+_V12_KEYS = {"engine_fingerprint", "canceled_orders", "events"}+_V11_KEYS = {+ "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",+}+_DAY = "2026-10-20"+_HEX_A = "a" * 64+++def _payload(**overrides) -> dict:+ payload = {+ "account_id": "pa_v12_01",+ "market": "cn_a",+ "account_state": {"cash": 100000.0, "positions": []},+ "orders": [{"symbol": "600519.SH", "side": "buy", "qty": 100}],+ "from_date": _DAY,+ "to_date": _DAY,+ }+ payload.update(overrides)+ return payload+++def _outcome() -> MatchOutcome:+ return MatchOutcome(+ end_state=AccountState(cash=100000.0),+ effective_fee_model=state_hash.effective_fee_model("cn_a"),+ )+++def _v11_result(**overrides) -> PaperTradeStepResult:+ fields: dict = dict(+ account_id="pa_v12_01",+ market="cn_a",+ range=DateRange(from_=_DAY, to=_DAY),+ received_state_hash="0" * 64,+ effective_fee_model=state_hash.effective_fee_model("cn_a"),+ fills=(Fill(trade_date=_DAY, symbol="600519.SH", side="buy", qty=100.0, price=1421.0, fee=36.95, reason=""),),+ rejected_orders=(+ RejectedOrder(+ trade_date=_DAY, symbol="000001.SZ", side="sell", qty=200.0, reason_code="insufficient_position"+ ),+ ),+ end_state=AccountState(cash=100000.0),+ nav_series=(NavPoint(date=_DAY, nav=100000.0, cash=100000.0, position_value=0.0),),+ skipped_days=(SkippedDay(date="2026-10-18", reason="non_trading_day"),),+ warnings=("valuation: 000001.SZ has no usable close",),+ data_provenance=DataProvenance(source="clickhouse+tencent(merged)"),+ )+ fields.update(overrides)+ return PaperTradeStepResult(**fields)+++def _v12_result(**overrides) -> PaperTradeStepResult:+ fields: dict = dict(+ schema_version=SCHEMA_VERSION_V1_2,+ engine_fingerprint="d" * 64,+ canceled_orders=(+ CanceledOrder(+ trade_date=_DAY, symbol="600519.SH", side="buy", qty=100.0, detail="limit 1000.0 not marketable"+ ),+ ),+ events=(+ SessionEvent(+ trade_date=_DAY,+ symbol="600519.SH",+ event_type="auction_window",+ detail="09:30 opening auction excluded",+ ),+ ),+ )+ fields.update(overrides)+ return replace(_v11_result(), **fields)+++# ── Defaults: absent/null new fields ARE the pt-v1.1 semantics (D8) ──+++def test_absent_new_fields_take_the_v11_defaults() -> None:+ request = parse_request(_payload())+ assert (request.interval, request.session, request.path_model, request.fill_model) == (+ DEFAULT_INTERVAL,+ DEFAULT_SESSION,+ DEFAULT_PATH_MODEL,+ DEFAULT_FILL_MODEL,+ )+ assert (request.interval, request.session, request.path_model, request.fill_model) == (+ "1d",+ "auto",+ "bar_median",+ "all_or_none",+ )+ assert request.uses_v1_2 is False+ assert request.schema_version == SCHEMA_VERSION == "pt-v1.1"++[email protected]("field", ["interval", "session", "path_model", "fill_model"])+def test_explicit_null_is_the_same_as_absent(field: str) -> None:+ request = parse_request(_payload(**{field: None}))+ assert request.uses_v1_2 is False+++def test_any_non_default_field_selects_v12() -> None:+ for field, value in (+ ("interval", "5m"),+ ("session", "cn_a"),+ ("path_model", "bar_close"),+ ("fill_model", "all_or_none"),+ ):+ request = parse_request(_payload(**{field: value}))+ assert request.uses_v1_2 is (field != "fill_model"), field+++# ── Closed vocabularies: every member accepted, everything else rejected ──++[email protected]("value", INTERVALS)+def test_every_interval_is_accepted(value: str) -> None:+ assert parse_request(_payload(interval=value)).interval == value++[email protected]("value", SESSIONS)+def test_every_session_is_accepted(value: str) -> None:+ assert parse_request(_payload(session=value)).session == value++[email protected]("value", PATH_MODELS)+def test_every_path_model_is_accepted(value: str) -> None:+ assert parse_request(_payload(path_model=value)).path_model == value++[email protected]("value", FILL_MODELS)+def test_every_fill_model_is_accepted(value: str) -> None:+ assert parse_request(_payload(fill_model=value)).fill_model == value+++ ("field", "value"),+ [+ ("interval", "15m"),+ ("interval", "5M"),+ ("session", "hk"),+ ("path_model", "vwap"),+ ("fill_model", "partial"),+ ("interval", 5),+ ("session", True),+ ("path_model", ["bar_close"]),+ ],+)+def test_out_of_vocabulary_or_non_string_values_are_rejected(field: str, value) -> None:+ with pytest.raises(PaperTradeSchemaError, match=field):+ parse_request(_payload(**{field: value}))+++# ── D5 market-combination gates: in-band INVALID_REQUEST, never a traceback ──++[email protected]("market", ["hk", "us"])+def test_5m_outside_cn_a_is_in_band_invalid_request(market: str) -> None:+ doc = json.loads(run_paper_trade_step(_payload(market=market, interval="5m")))+ assert doc["status"] == "error"+ assert doc["code"] == "INVALID_REQUEST"+ assert "interval 5m is cn_a-only in pt-v1.2" in doc["message"]+ assert "received_state_hash" in doc++[email protected]("market", ["hk", "us"])+def test_cn_a_session_outside_cn_a_is_in_band_invalid_request(market: str) -> None:+ doc = json.loads(run_paper_trade_step(_payload(market=market, session="cn_a")))+ assert doc["code"] == "INVALID_REQUEST"+ assert "session cn_a requires market cn_a" in doc["message"]+++def test_session_is_inert_for_interval_1d_and_cn_a() -> None:+ request = parse_request(_payload(market="cn_a", session="cn_a", interval="1d"))+ assert request.uses_v1_2 is True+ assert request.schema_version == SCHEMA_VERSION_V1_2+++# ── D3 engine fingerprint ──+++def test_engine_fingerprint_matches_the_frozen_formula() -> None:+ actual = state_hash.engine_fingerprint(+ interval="5m",+ path_model="bar_close",+ fill_model="all_or_none",+ bar_fingerprint=_HEX_A,+ )+ manual = state_hash.state_hash(+ {+ "interval": "5m",+ "path_model": "bar_close",+ "fill_model": "all_or_none",+ "rules_version": rules.RULES_VERSION,+ "bar_fingerprint": _HEX_A,+ }+ )+ assert rules.RULES_VERSION == "pt-rules-v1"+ assert actual == manual+ assert re.fullmatch(r"[0-9a-f]{64}", actual)+++def test_engine_fingerprint_is_deterministic_and_input_sensitive() -> None:+ base_kwargs = dict(interval="5m", path_model="bar_median", fill_model="all_or_none", bar_fingerprint=_HEX_A)+ base = state_hash.engine_fingerprint(**base_kwargs)+ assert state_hash.engine_fingerprint(**base_kwargs) == base+ assert state_hash.engine_fingerprint(**{**base_kwargs, "interval": "1d"}) != base+ assert state_hash.engine_fingerprint(**{**base_kwargs, "path_model": "bar_close"}) != base+ assert state_hash.engine_fingerprint(**{**base_kwargs, "fill_model": "x"}) != base+ assert state_hash.engine_fingerprint(**{**base_kwargs, "bar_fingerprint": "b" * 64}) != base+ assert state_hash.engine_fingerprint(**{**base_kwargs, "rules_version": "pt-rules-v0"}) != base+++def test_engine_fingerprint_defaults_are_the_pt_v11_parameters() -> None:+ assert state_hash.engine_fingerprint() == state_hash.engine_fingerprint(+ interval="1d",+ path_model="bar_median",+ fill_model="all_or_none",+ bar_fingerprint="",+ rules_version=rules.RULES_VERSION,+ )+++# ── D4 received_state_hash: v1.1 byte-compatible, v1.2 covered ──+++def test_v11_hash_is_the_frozen_coverage_object() -> None:+ request = parse_request(_payload())+ result = wire.assemble_result(request, _outcome(), raw_account_state=_payload()["account_state"])+ manual = state_hash.state_hash(+ {+ "account_id": "pa_v12_01",+ "market": "cn_a",+ "account_state": _payload()["account_state"],+ "fee_model": state_hash.effective_fee_model("cn_a"),+ "from_date": _DAY,+ "to_date": _DAY,+ }+ )+ assert result.received_state_hash == manual+++def test_explicit_defaults_do_not_change_the_hash() -> None:+ base = wire.received_state_hash_from_payload(_payload())+ respelled = wire.received_state_hash_from_payload(+ _payload(+ interval="1d",+ session="auto",+ path_model="bar_median",+ fill_model="all_or_none",+ )+ )+ assert base is not None and base == respelled+++def test_non_default_fields_join_the_hash() -> None:+ baseline = wire.received_state_hash_from_payload(_payload())+ v12 = wire.received_state_hash_from_payload(_payload(interval="5m", path_model="bar_close"))+ assert v12 is not None and v12 != baseline+ manual = state_hash.state_hash(+ {+ "account_id": "pa_v12_01",+ "market": "cn_a",+ "account_state": _payload()["account_state"],+ "fee_model": state_hash.effective_fee_model("cn_a"),+ "from_date": _DAY,+ "to_date": _DAY,+ "interval": "5m",+ "path_model": "bar_close",+ }+ )+ assert v12 == manual+++ ("field", "value"),+ [("interval", "15m"), ("session", 5), ("path_model", "vwap"), ("fill_model", [])],+)+def test_error_path_hash_is_omitted_for_malformed_v12_fields(field: str, value) -> None:+ assert wire.received_state_hash_from_payload(_payload(**{field: value})) is None+++# ── D8 wire shape: v1.1 untouched, v1.2 adds exactly three keys ──+++def test_v11_payload_key_set_is_the_frozen_set() -> None:+ payload = wire.build_success_payload(_v11_result())+ assert set(payload) == _V11_KEYS+ assert payload["schema_version"] == "pt-v1.1"+ assert validate_payload(payload, load_contract_schema("result")) == []+++def test_v12_payload_adds_exactly_the_three_documented_keys() -> None:+ payload = wire.build_success_payload(_v12_result())+ assert set(payload) - set(_v11_result_payload()) == _V12_KEYS+ assert payload["schema_version"] == "pt-v1.2"+ assert payload["engine_fingerprint"] == "d" * 64+ assert payload["canceled_orders"][0]["reason_code"] == CANCELED_REASON_CODE+ assert payload["events"][0]["event_type"] == "auction_window"+ assert validate_payload(payload, load_contract_schema("result", version="pt-v1.2")) == []+++def _v11_result_payload() -> dict:+ return wire.build_success_payload(_v11_result())+++def test_v11_result_stays_valid_under_the_additive_v12_document() -> None:+ payload = _v11_result_payload()+ assert set(payload).isdisjoint(_V12_KEYS)+ assert validate_payload(payload, load_contract_schema("result", version="pt-v1.2")) == []+++def test_the_subset_validator_defers_the_v12_version_gate_to_the_wire_builder() -> None:+ unversioned = _v11_result_payload() | {"schema_version": "pt-v1.2"}+ assert validate_payload(unversioned, load_contract_schema("result", version="pt-v1.2")) == []+ with pytest.raises(ValueError, match="engine_fingerprint"):+ wire.build_success_payload(_v12_result(engine_fingerprint=""))+++def test_v12_result_does_not_validate_as_a_v11_document() -> None:+ payload = wire.build_success_payload(_v12_result())+ errors = validate_payload(payload, load_contract_schema("result"))+ assert any("schema_version" in error for error in errors)+++def test_v12_assembly_reads_the_engine_populated_outcome_fields() -> None:+ base = _outcome()+ outcome = types.SimpleNamespace(+ error=None,+ effective_fee_model=base.effective_fee_model,+ fills=base.fills,+ rejected_orders=base.rejected_orders,+ end_state=base.end_state,+ nav_series=base.nav_series,+ skipped_days=base.skipped_days,+ warnings=base.warnings,+ data_provenance=base.data_provenance,+ limit_provenance=base.limit_provenance,+ engine_fingerprint="e" * 64,+ canceled_orders=(CanceledOrder(trade_date=_DAY, symbol="600519.SH", side="buy", qty=100.0),),+ events=(SessionEvent(trade_date=_DAY, symbol="600519.SH", event_type="halted"),),+ )+ request = parse_request(_payload(interval="5m"))+ result = wire.assemble_result(request, outcome, raw_account_state=_payload()["account_state"])+ assert result.engine_fingerprint == "e" * 64+ assert result.canceled_orders[0].reason_code == CANCELED_REASON_CODE+ assert result.events[0].event_type == "halted"+++def test_v12_assembly_computes_a_fingerprint_before_the_engine_populates_it() -> None:+ request = parse_request(_payload(interval="5m", path_model="bar_close"))+ result = wire.assemble_result(request, _outcome(), raw_account_state=_payload()["account_state"])+ assert result.schema_version == SCHEMA_VERSION_V1_2+ assert result.engine_fingerprint == state_hash.engine_fingerprint(+ interval="5m", path_model="bar_close", fill_model="all_or_none"+ )+++def test_v11_assembly_never_carries_v12_fields() -> None:+ request = parse_request(_payload())+ result = wire.assemble_result(request, _outcome(), raw_account_state=_payload()["account_state"])+ assert result.schema_version == SCHEMA_VERSION+ assert (result.engine_fingerprint, result.canceled_orders, result.events) == ("", (), ())+++# ── Fail-closed serialization on engine bugs ──+++def test_v12_without_a_fingerprint_fails_closed() -> None:+ with pytest.raises(ValueError, match="engine_fingerprint"):+ wire.build_success_payload(_v12_result(engine_fingerprint=""))+++def test_wrong_cancel_token_fails_closed() -> None:+ bad = CanceledOrder(trade_date=_DAY, symbol="600519.SH", side="buy", qty=100.0, reason_code="insufficient_cash")+ with pytest.raises(ValueError, match="canceled reason_code"):+ wire.build_success_payload(_v12_result(canceled_orders=(bad,)))+++def test_unknown_event_type_fails_closed() -> None:+ bad = SessionEvent(trade_date=_DAY, symbol="600519.SH", event_type="closing_auction")+ with pytest.raises(ValueError, match="event_type"):+ wire.build_success_payload(_v12_result(events=(bad,)))+++def test_unknown_schema_version_fails_closed() -> None:+ with pytest.raises(ValueError, match="unknown schema_version"):+ wire.build_success_payload(_v11_result(schema_version="pt-v1.0"))+++# ── Contract files: v1.2 additive copy, v1.1 frozen ──+++def test_v12_contract_file_declares_the_additive_surface() -> None:+ document = json.loads((_CONTRACT_DIR / "paper_trade_step-v1.2.json").read_text("utf-8"))+ assert document["version"] == "pt-v1.2"+ assert "additive" in document["$comment"].lower()+ result = document["schemas"]["result"]+ assert result["properties"]["schema_version"]["enum"] == ["pt-v1.1", "pt-v1.2"]+ assert result["properties"]["engine_fingerprint"]["pattern"] == "^[0-9a-f]{64}$"+ cancel_reason = result["properties"]["canceled_orders"]["items"]["properties"]["reason_code"]+ assert cancel_reason["const"] == CANCELED_REASON_CODE+ event_types = result["properties"]["events"]["items"]["properties"]["event_type"]["enum"]+ assert tuple(event_types) == SESSION_EVENT_TYPES+++def test_v12_contract_requires_the_additive_fields_only_for_a_v12_document() -> None:+ document = json.loads((_CONTRACT_DIR / "paper_trade_step-v1.2.json").read_text("utf-8"))+ result = document["schemas"]["result"]+ assert "engine_fingerprint" not in result["required"]+ conditional = next(node for node in result["allOf"] if "if" in node)+ assert conditional["if"]["properties"]["schema_version"]["const"] == "pt-v1.2"+ assert set(conditional["then"]["required"]) == _V12_KEYS+ assert "wire.build_success_payload" in conditional["$comment"]+++def test_v11_contract_file_is_not_edited() -> None:+ document = json.loads((_CONTRACT_DIR / "paper_trade_step-v1.1.json").read_text("utf-8"))+ assert document["version"] == "pt-v1.1"+ result = document["schemas"]["result"]+ assert result["properties"]["schema_version"]["const"] == "pt-v1.1"+ assert not (_V12_KEYS & set(result["properties"]))+++def test_packaged_contracts_mirror_the_published_copies() -> None:+ for name in ("paper_trade_step-v1.1.json", "paper_trade_step-v1.2.json"):+ packaged = (_CONTRACT_DIR / name).read_bytes()+ published = (_PUBLISHED_CONTRACT_DIR / name).read_bytes()+ assert packaged == published, name+++def test_loader_resolves_contracts_from_inside_the_package() -> None:+ # The wheel/sdist ships ``tools/paper_trade/*.json`` as package-data; a+ # loader that reached the repository root would work in CI and break in an+ # installed copy.+ package_dir = Path(schema_module.__file__).resolve().parent+ for version in SCHEMA_VERSIONS:+ path = schema_module._CONTRACT_SCHEMA_PATHS[version]+ assert path.parent == package_dir+ assert path.is_file()+ schema = schema_module.load_contract_schema("result", version=version)+ assert schema["properties"]["schema_version"]+++def test_loader_defaults_to_v11_and_rejects_an_unknown_version() -> None:+ assert load_contract_schema("result")["properties"]["schema_version"]["const"] == "pt-v1.1"+ with pytest.raises(KeyError, match="unknown contract version"):+ load_contract_schema("result", version="pt-v1.3")+++# ── Tool registration surface ──+++def test_tool_parameters_expose_the_four_optional_fields() -> None:+ parameters = PaperTradeStepTool.parameters+ properties = parameters["properties"]+ assert properties["interval"]["enum"] == ["1d", "5m"]+ assert properties["interval"]["default"] == "1d"+ assert properties["session"]["enum"] == ["auto", "cn_a"]+ assert properties["session"]["default"] == "auto"+ assert properties["path_model"]["enum"] == ["bar_median", "bar_close"]+ assert properties["path_model"]["default"] == "bar_median"+ assert properties["fill_model"]["enum"] == ["all_or_none"]+ assert properties["fill_model"]["default"] == "all_or_none"+ assert parameters["required"] == [+ "account_id",+ "market",+ "account_state",+ "from_date",+ "to_date",+ ]+ assert "deterministic paper-trading matching engine; never places real orders" in (PaperTradeStepTool.description)