Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(paper-trade): causal daily matching and CLI/API/Web paper accounts (#1939)

shadowinlife3868c7ad6380
diff --git a/.gitignore b/.gitignore
index 7db12f5f0..f0722c677 100644
--- a/.gitignore
+++ b/.gitignore
@@ -180,3 +180,6 @@ agent/tests/artifacts/
/pixel-office.sqlite3
/pixel-office.sqlite3-*
+
+# Local simulated account ledgers
+/paper-trading/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d00cf034..de1d865c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,18 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Daily paper trading — 2026-10-21
+
+- Add the deterministic `paper_trade_step` agent/MCP tool plus local paper
+ accounts through CLI, authenticated REST and the Web sidebar (all UI locales).
+ Accounts start today or next session with configurable cash and positions;
+ atomic revisions protect saved ledgers from duplicate or concurrent steps.
+- Strategies receive only prior bars and the ledger after preceding fills.
+ Failures discard the whole call. Raw execution feeds reject adjusted and
+ non-finite prices; incomplete A-share calendars and unverified split-like
+ events fail visibly. Corporate-action reconciliation and dividends remain
+ outside this daily-close model (#1939).
+
### Maintenance — 2026-10-20
- Warn about unrecognized backtest configuration keys and include the warning
diff --git a/README.md b/README.md
index 373324390..fedd87f26 100644
--- a/README.md
+++ b/README.md
@@ -1391,6 +1391,20 @@ Saves write the `channels.<name>` section of `~/.vibe-trading/agent.json` atomic
### Strategy & Backtesting
+**Daily paper trading** is available in the Web sidebar (`/paper-trading`),
+`vibe-trading paper`, and the authenticated `/api/paper-accounts` API. Start today
+or next session with configurable cash/positions; settle completed daily bars
+and inspect fills, rejections and NAV history. Strategy history stops before the
+execution date, and each day receives the ledger after preceding fills. The
+agent/MCP `paper_trade_step` remains a stateless research primitive.
+
+Execution uses raw prices (Tencent raw for A-shares/HK, raw-capable US providers).
+A-shares require a complete ClickHouse calendar. Unavailable data/calendar and
+unverified split-like events fail visibly without committing a saved ledger;
+price/volume ratios never authorize multiplying a position. Cash dividends and
+automatic corporate-action reconciliation are not implemented. See the
+[paper-trading guide](agent/src/tools/paper_trade/README.md) for CLI/API examples and model limits.
+
Daily-engine backtests report engine-specific unused settings in the run-card
warnings. For example, crypto reads `maker_rate` and `taker_rate`, so supplying
the A-share `commission_rate` setting warns instead of silently implying that
@@ -1722,7 +1736,7 @@ Posting `{}` schedules a template on its own suggested cadence with its declared
## 🔌 MCP Plugin
-Vibe-Trading exposes 81 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.
+Vibe-Trading exposes 82 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.
**Environment variables:** the client spawns the server itself, so a shell `export` never reaches it — set them in the client's `env` block. Generated backtest code is sandboxed to the allowed run roots, so writing results into a workspace of your own needs `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1791,7 +1805,7 @@ with `--host` / `--port`.
</details>
-**MCP tools exposed (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**MCP tools exposed (82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.
`quantlib_call` attribution requires finite sector weights and returns, finite Carino return inputs, and a finite non-negative weight-sum tolerance. Invalid data is rejected explicitly rather than returned as an attribution result containing `NaN`. Missing returns for a zero-weight sector may still be inferred from the other side.
@@ -2216,7 +2230,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 82 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -2231,7 +2245,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 112 auto-discovered agent tools
+│ │ ├── tools/ # 113 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_ar.md b/README_ar.md
index d61b25be1..25bd78413 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -1308,7 +1308,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-يعرض Vibe-Trading 81 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.
+يعرض Vibe-Trading 82 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.
**متغيرات البيئة:** العميل هو من يشغّل الخادم بنفسه، لذا لا يصل إليه `export` من الـ shell أبداً —— اضبطها في كتلة `env` الخاصة بالعميل. كود الاختبار الخلفي المولَّد محصور ضمن جذور التشغيل المسموح بها، لذا تحتاج إلى `VIBE_TRADING_ALLOWED_RUN_ROOTS` لكتابة النتائج في دليل عمل خاص بك:
@@ -1364,7 +1364,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**أدوات MCP المعروضة (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**أدوات MCP المعروضة (82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.
### أدوات MCP الخارجية في SWARM
@@ -1724,7 +1724,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 82 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -1739,7 +1739,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 112 auto-discovered agent tools
+│ │ ├── tools/ # 113 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_es.md b/README_es.md
index 9a9fe2c93..ff37dd3e0 100644
--- a/README_es.md
+++ b/README_es.md
@@ -1368,7 +1368,7 @@ Enviar `{}` programa una plantilla con su propia cadencia sugerida y sus valores
## 🔌 MCP Plugin
-Vibe-Trading expone 81 MCP tools para cualquier cliente compatible con MCP. Se ejecuta como un subproceso stdio — no requiere configuración de servidor. Las herramientas de investigación principales funcionan sin ninguna API key para HK/US/crypto; las herramientas del conector de trading usan el perfil de conector seleccionado, y `run_swarm` necesita una LLM key.
+Vibe-Trading expone 82 MCP tools para cualquier cliente compatible con MCP. Se ejecuta como un subproceso stdio — no requiere configuración de servidor. Las herramientas de investigación principales funcionan sin ninguna API key para HK/US/crypto; las herramientas del conector de trading usan el perfil de conector seleccionado, y `run_swarm` necesita una LLM key.
**Variables de entorno:** el cliente lanza el servidor él mismo, así que un `export` de shell nunca le llega — configúralas en el bloque `env` del cliente. El código de backtest generado está confinado a los run roots permitidos, así que para escribir resultados en un workspace propio necesitas `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1439,7 +1439,7 @@ dirección de bind con `--host` / `--port`.
</details>
-**MCP tools expuestas (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**MCP tools expuestas (82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.
### SWARM external MCP tools
@@ -1812,7 +1812,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # Paquete CLI — TUI interactiva + subcomandos
│ ├── api_server.py # Servidor FastAPI — runs, sesiones, carga, swarm, SSE
-│ ├── mcp_server.py # Servidor MCP — 81 herramientas para OpenClaw / Claude Desktop
+│ ├── mcp_server.py # Servidor MCP — 82 herramientas para OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # Núcleo del agente ReAct
@@ -1827,7 +1827,7 @@ Vibe-Trading/
│ │ ├── memory/ # Memoria persistente entre sesiones
│ │ │ └── persistent.py # memoria basada en archivos (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 112 herramientas de agente autodescubiertas
+│ │ ├── tools/ # 113 herramientas de agente autodescubiertas
│ │ │ ├── backtest_tool.py # ejecuta backtests
│ │ │ ├── remember_tool.py # memoria entre sesiones (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # CRUD de skills (save/patch/delete/file)
diff --git a/README_id.md b/README_id.md
index 49202c1d5..92565e10a 100644
--- a/README_id.md
+++ b/README_id.md
@@ -1614,7 +1614,7 @@ Mengirim `{}` akan menjadwalkan template memakai cadence yang disarankan beserta
<a id="-mcp-plugin"></a>
## 🔌 Plugin MCP
-Vibe-Trading mengekspos 81 tool MCP untuk client yang kompatibel MCP. Berjalan sebagai subprocess stdio — tidak perlu setup server. Tool riset inti bekerja tanpa API key untuk HK/AS/crypto; tool connector trading menggunakan profil connector terpilih, dan `run_swarm` memerlukan LLM key.
+Vibe-Trading mengekspos 82 tool MCP untuk client yang kompatibel MCP. Berjalan sebagai subprocess stdio — tidak perlu setup server. Tool riset inti bekerja tanpa API key untuk HK/AS/crypto; tool connector trading menggunakan profil connector terpilih, dan `run_swarm` memerlukan LLM key.
**Environment variable:** client menjalankan server sendiri, sehingga `export` dari shell tidak pernah sampai ke proses tersebut — atur di block `env` client. Kode backtest yang dihasilkan dibatasi ke root run yang diizinkan, jadi menulis hasil ke workspace Anda sendiri memerlukan `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1683,7 +1683,7 @@ dengan `--host` / `--port`.
</details>
-**Tool MCP yang diekspos (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**Tool MCP yang diekspos (82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.
### Tool MCP eksternal untuk SWARM
@@ -2057,7 +2057,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 82 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -2072,7 +2072,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 112 auto-discovered agent tools
+│ │ ├── tools/ # 113 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_ja.md b/README_ja.md
index e01753ca8..131eb8748 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -1310,7 +1310,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-Vibe-Trading は MCP-compatible client 向けに 81 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。
+Vibe-Trading は MCP-compatible client 向けに 82 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。
**環境変数:** server は client 自身が spawn するため、shell の `export` は届きません —— client の `env` block に設定してください。生成された backtest code は allowed run roots 内に制限されるので、結果を自分の作業 directory に書き出すには `VIBE_TRADING_ALLOWED_RUN_ROOTS` が必要です:
@@ -1366,7 +1366,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**公開される MCP tools(81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**公開される MCP tools(82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.
### SWARM の外部 MCP tools
@@ -1732,7 +1732,7 @@ Vibe-Trading/
├── agent/ # バックエンド (Python)
│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド
│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 81 tools
+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 82 tools
│ │
│ ├── src/
│ │ ├── agent/ # ReAct エージェントコア
@@ -1747,7 +1747,7 @@ Vibe-Trading/
│ │ ├── memory/ # クロスセッション永続メモリ
│ │ │ └── persistent.py # ファイルベースメモリ (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 112 個の自動検出エージェントツール
+│ │ ├── tools/ # 113 個の自動検出エージェントツール
│ │ │ ├── backtest_tool.py # バックテスト実行
│ │ │ ├── remember_tool.py # クロスセッションメモリ (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_ko.md b/README_ko.md
index a1210fcab..292cc4746 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -1311,7 +1311,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-Vibe-Trading은 모든 MCP-compatible client를 위해 81개 MCP tools를 제공합니다. stdio subprocess로 실행되므로 server setup이 필요 없습니다. 핵심 research tools는 HK/US/crypto에서 API key 없이 작동하고, trading connector tools는 선택된 connector profile을 사용하며, `run_swarm`만 LLM key가 필요합니다.
+Vibe-Trading은 모든 MCP-compatible client를 위해 82개 MCP tools를 제공합니다. stdio subprocess로 실행되므로 server setup이 필요 없습니다. 핵심 research tools는 HK/US/crypto에서 API key 없이 작동하고, trading connector tools는 선택된 connector profile을 사용하며, `run_swarm`만 LLM key가 필요합니다.
**환경 변수:** server는 client가 직접 spawn하므로 shell의 `export`는 전달되지 않습니다 —— client의 `env` block에 설정하세요. 생성된 backtest code는 allowed run roots 안으로 제한되므로, 결과를 자신의 작업 directory에 쓰려면 `VIBE_TRADING_ALLOWED_RUN_ROOTS`가 필요합니다:
@@ -1367,7 +1367,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**노출되는 MCP tools(81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**노출되는 MCP tools(82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.
### SWARM 외부 MCP tools
@@ -1729,7 +1729,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 82 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -1744,7 +1744,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 112 auto-discovered agent tools
+│ │ ├── tools/ # 113 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_zh.md b/README_zh.md
index 3cfd8efb8..791a2ab80 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -1315,7 +1315,7 @@ POST `{}` 即按模板自身的建议节奏和默认变量排程。渲染后的
## 🔌 MCP Plugin
-Vibe-Trading 为任何 MCP-compatible client 暴露 81 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。
+Vibe-Trading 为任何 MCP-compatible client 暴露 82 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。
**环境变量:** server 由 client 自己 spawn,因此在 shell 里 `export` 永远传不进去 —— 请写在 client 的 `env` 块里。生成的回测代码被限制在 allowed run roots 内,所以要把结果写进你自己的工作目录,需要 `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1371,7 +1371,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**暴露的 MCP tools(81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**暴露的 MCP tools(82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.
### SWARM 的外部 MCP tools
@@ -1727,7 +1727,7 @@ Vibe-Trading/
├── agent/ # 后端(Python)
│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令
│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP server —— 81 个工具,面向 OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server —— 82 个工具,面向 OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent 内核
@@ -1742,7 +1742,7 @@ Vibe-Trading/
│ │ ├── memory/ # 跨 session 持久记忆
│ │ │ └── persistent.py # 基于文件的记忆(~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 112 个自动发现的 agent 工具
+│ │ ├── tools/ # 113 个自动发现的 agent 工具
│ │ │ ├── backtest_tool.py # 运行回测
│ │ │ ├── remember_tool.py # 跨 session 记忆(save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD(save/patch/delete/file)
diff --git a/agent/SKILL.md b/agent/SKILL.md
index a647d5d60..8d0ea6e05 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -133,7 +133,7 @@ Comprehensive knowledge base covering:
Use `load_skill(name)` to access full methodology docs with code templates.
-## Available MCP Tools (81)
+## Available MCP Tools (82)
| Tool | Description | API Key |
|------|-------------|---------|
@@ -144,6 +144,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.
| `add_goal_evidence` | Attach evidence to a research goal | None |
| `update_research_goal_status` | Update goal lifecycle status | None |
| `backtest` | Run vectorized backtest engine | None* |
+| `paper_trade_step` | Deterministic paper-trading matching engine; never places real orders | None* |
| `factor_analysis` | IC/IR analysis + layered backtest | None* |
| `alpha_zoo` | Browse bundled alpha metadata and registry health | None |
| `alpha_bench` | Benchmark one alpha or a complete zoo | None* |
diff --git a/agent/api_server.py b/agent/api_server.py
index 171d9998d..8fddc250f 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -261,6 +261,8 @@ register_live_routes(app)
# --- Read-only portfolio dashboard ---
from src.api.portfolio_routes import register_portfolio_routes # noqa: E402
register_portfolio_routes(app)
+from src.api.paper_trade_routes import register_paper_trade_routes # noqa: E402
+register_paper_trade_routes(app)
from src.api.connection_routes import register_connection_routes # noqa: E402
register_connection_routes(app)
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 9af4c9018..c671d4d68 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -5833,6 +5833,8 @@ def _build_parser() -> argparse.ArgumentParser:
from cli.commands.strategy_evidence import add_subparser as _add_strategy_evidence_subparser
_add_strategy_evidence_subparser(subparsers)
+ from cli.commands.paper_trade import add_parser as add_paper_parser
+ add_paper_parser(subparsers)
return parser
@@ -6745,6 +6747,9 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "strategy-evidence":
from cli.commands.strategy_evidence import dispatch as _strategy_evidence_dispatch
return _coerce_exit_code(_strategy_evidence_dispatch(args))
+ if args.command == "paper":
+ from cli.commands.paper_trade import dispatch as dispatch_paper
+ return dispatch_paper(args)
if args.command == "portfolio":
return _coerce_exit_code(_dispatch_portfolio(args))
if args.command == "connector":
diff --git a/agent/cli/commands/paper_trade.py b/agent/cli/commands/paper_trade.py
new file mode 100644
index 000000000..3aa2de550
--- /dev/null
+++ b/agent/cli/commands/paper_trade.py
@@ -0,0 +1,81 @@
+"""CLI for local paper accounts and caller-owned step payloads."""
+
+import json
+from pathlib import Path
+
+from src.tools.paper_trade.accounts import PaperAccounts
+
+
+def add_parser(subparsers):
+ parser = subparsers.add_parser(
+ "paper", help="Forward paper accounts; never places real orders"
+ )
+ commands = parser.add_subparsers(dest="paper_command", required=True)
+ create = commands.add_parser("create", help="Start today or next trading session")
+ create.add_argument("--label", required=True)
+ create.add_argument("--market", required=True, choices=["cn_a", "hk", "us"])
+ create.add_argument(
+ "--state", required=True, help="JSON file with cash and positions"
+ )
+ create.add_argument("--start", default="today", choices=["today", "next_session"])
+ commands.add_parser("list")
+ for name in ("show", "history", "advance"):
+ cmd = commands.add_parser(name)
+ cmd.add_argument("account_id")
+ if name == "advance":
+ cmd.add_argument("--revision", required=True, type=int)
+ cmd.add_argument("--to-date", required=True)
+ mode = cmd.add_mutually_exclusive_group(required=True)
+ mode.add_argument(
+ "--orders", help="JSON file containing an order array (or [])"
+ )
+ mode.add_argument("--strategy-path")
+ step = commands.add_parser(
+ "step", help="Run a pure step from a caller-owned JSON payload"
+ )
+ step.add_argument("payload")
+
+
+def dispatch(args):
+ try:
+ if args.paper_command == "step":
+ from src.tools.paper_trade.tool import run_paper_trade_step
+
+ result = json.loads(
+ run_paper_trade_step(json.loads(Path(args.payload).read_text()))
+ )
+ else:
+ service = PaperAccounts()
+ if args.paper_command == "create":
+ result = service.create(
+ label=args.label,
+ market=args.market,
+ start=args.start,
+ account_state=json.loads(Path(args.state).read_text()),
+ )
+ elif args.paper_command == "advance":
+ result = service.advance(
+ args.account_id,
+ expected_revision=args.revision,
+ to_date=args.to_date,
+ orders=(
+ json.loads(Path(args.orders).read_text())
+ if args.orders
+ else None
+ ),
+ strategy_path=args.strategy_path,
+ )
+ elif args.paper_command == "list":
+ result = service.list()
+ elif args.paper_command == "history":
+ result = service.history(args.account_id)
+ else:
+ result = service.get(args.account_id)
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return int(
+ isinstance(result, dict)
+ and ("code" in result or result.get("committed") is False)
+ )
+ except (ValueError, KeyError, OSError) as exc:
+ print(json.dumps({"error": str(exc)}, ensure_ascii=False))
+ return 1
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index bb6344bbc..d0268583b 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -6,9 +6,9 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,
AKShare are free). Trading connector tools are profile-scoped and require the
selected connector's own local app or OAuth setup.
-Surfaces 81 tools: skills, research goals, strategy discovery,
+Surfaces 82 tools: skills, research goals, strategy discovery,
backtest/factor/options/pattern
-analysis, market data, fundamentals & capital-flow & news & discovery
+analysis, deterministic paper-trading matching (paper_trade_step), market data, fundamentals & capital-flow & news & discovery
(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_southbound_flow /
get_margin_trading /
get_block_trades / get_shareholder_count / get_lockup_expiry / get_sector_info /
@@ -468,6 +468,7 @@ _lenient_str_list_opt = Annotated[list[str] | None, _lenient]
_lenient_float_list_opt = Annotated[list[float] | None, _lenient]
_lenient_dict_list = Annotated[list[dict[str, Any]], _lenient]
_lenient_dict_list_opt = Annotated[list[dict[str, Any]] | None, _lenient]
+_lenient_dict_any = Annotated[dict[str, Any], _lenient]
_lenient_dict_any_opt = Annotated[dict[str, Any] | None, _lenient]
_lenient_dict_str_str = Annotated[dict[str, str], _lenient]
@@ -822,6 +823,69 @@ def backtest(run_dir: str) -> str:
return run_backtest(run_dir)
+# ---------------------------------------------------------------------------
+# Paper-trading step tool (pt-v1.1, hand-written wrapper)
+# ---------------------------------------------------------------------------
+
+
+def paper_trade_step(
+ account_id: str,
+ market: str,
+ account_state: _lenient_dict_any,
+ from_date: str,
+ to_date: str,
+ orders: _lenient_dict_list_opt = None,
+ strategy_path: str | None = None,
+ fee_model: _lenient_dict_any_opt = None,
+) -> str:
+ """Run one step of the deterministic paper-trading matching engine; never places real orders.
+
+ Matches the injected ``orders`` (or a ``strategy_path``'s per-day orders)
+ against daily bars under the market's frozen rules (T+1, price limits,
+ board lots, fees) and returns ONE in-band JSON document on
+ ``result.content[0].text``: the pt-v1.1 success result, or an error
+ envelope (``PAPER_DATA_NOT_READY`` retryable / ``INVALID_REQUEST``
+ non-retryable) on the SAME channel — never a transport error. Research-only:
+ it reads market data and the injected ledger, matches on paper, and writes
+ nothing; no broker or trading-connector order path exists here.
+
+ Args:
+ account_id: Account identifier, echoed verbatim in the result.
+ market: One of ``cn_a`` / ``hk`` / ``us`` — selects the frozen rule set.
+ account_state: RM-injected ledger snapshot ``{cash, positions:[{symbol,
+ qty, avg_cost}]}``. Hashed raw for ``received_state_hash``.
+ from_date: Inclusive range start ``YYYY-MM-DD``. Orders mode requires
+ ``from_date == to_date`` (single day); multi-day ranges are
+ strategy_path mode only.
+ to_date: Inclusive range end ``YYYY-MM-DD`` (the target trading day).
+ orders: Orders mode — array of ``{symbol, side, qty, limit?}``. Exactly
+ one of ``orders`` / ``strategy_path`` must be given; an empty array
+ is the zero-order pure-valuation path.
+ strategy_path: Strategy mode — path to an AST-hardened strategy whose
+ per-day orders are matched. Exactly one of ``orders`` /
+ ``strategy_path``.
+ fee_model: Optional per-key fee overrides merged over the market
+ defaults.
+ """
+ from src.tools.paper_trade.tool import run_paper_trade_step
+
+ payload: dict[str, Any] = {
+ "account_id": account_id,
+ "market": market,
+ "account_state": account_state,
+ "from_date": from_date,
+ "to_date": to_date,
+ }
+ if orders is not None:
+ payload["orders"] = orders
+ if strategy_path is not None:
+ payload["strategy_path"] = strategy_path
+ if fee_model is not None:
+ payload["fee_model"] = fee_model
+ return run_paper_trade_step(payload)
+
+
# ---------------------------------------------------------------------------
# Factor analysis tool
# ---------------------------------------------------------------------------
diff --git a/agent/src/api/paper_trade_routes.py b/agent/src/api/paper_trade_routes.py
new file mode 100644
index 000000000..87e77eee1
--- /dev/null
+++ b/agent/src/api/paper_trade_routes.py
@@ -0,0 +1,73 @@
+"""Authenticated paper-account API; all mutations use the settings write gate."""
+
+from fastapi import Depends, FastAPI, HTTPException
+from pydantic import BaseModel, ConfigDict, Field
+
+from src.api.security import require_auth, require_settings_write_auth
+from src.tools.paper_trade.accounts import AccountConflict, PaperAccounts
+
+
+class CreateAccount(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ label: str = Field(min_length=1, max_length=80)
+ market: str
+ account_state: dict
+ start: str = "today"
+ fee_model: dict = Field(default_factory=dict)
+
+
+class AdvanceAccount(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ expected_revision: int = Field(strict=True, ge=0)
+ to_date: str
+ orders: list[dict] | None = Field(default=None, max_length=1000)
+ strategy_path: str | None = None
+
+
+def _call(fn, *args, **kwargs):
+ try:
+ return fn(*args, **kwargs)
+ except KeyError as exc:
+ raise HTTPException(404, "Paper account not found") from exc
+ except AccountConflict as exc:
+ raise HTTPException(409, str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(422, str(exc)) from exc
+
+
+def register_paper_trade_routes(app: FastAPI):
+ @app.get("/api/paper-accounts", dependencies=[Depends(require_auth)])
+ def list_accounts():
+ return PaperAccounts().list()
+
+ @app.post(
+ "/api/paper-accounts", dependencies=[Depends(require_settings_write_auth)]
+ )
+ def create_account(body: CreateAccount):
+ return _call(PaperAccounts().create, **body.model_dump())
+
+ @app.get("/api/paper-accounts/{account_id}", dependencies=[Depends(require_auth)])
+ def get_account(account_id: str):
+ return _call(PaperAccounts().get, account_id)
+
+ @app.get(
+ "/api/paper-accounts/{account_id}/history", dependencies=[Depends(require_auth)]
+ )
+ def account_history(account_id: str):
+ return _call(PaperAccounts().history, account_id)
+
+ @app.post(
+ "/api/paper-accounts/{account_id}/advance",
+ dependencies=[Depends(require_settings_write_auth)],
+ )
+ def advance_account(account_id: str, body: AdvanceAccount):
+ return _call(PaperAccounts().advance, account_id, **body.model_dump())
+
+ @app.post(
+ "/api/paper-trade/step", dependencies=[Depends(require_settings_write_auth)]
+ )
+ def pure_step(body: dict):
+ import json
+ from src.tools.paper_trade.tool import run_paper_trade_step
+
+ return json.loads(run_paper_trade_step(body))
diff --git a/agent/src/tools/paper_trade/README.md b/agent/src/tools/paper_trade/README.md
new file mode 100644
index 000000000..f79741c15
--- /dev/null
+++ b/agent/src/tools/paper_trade/README.md
@@ -0,0 +1,105 @@
+# Daily paper trading
+
+Open **Paper trading** in the Web sidebar (`/paper-trading`). Create an account
+with initial cash and positions, choose today or the next session, then settle
+completed daily bars with explicit orders or a strategy file. The page displays
+cash, positions, fills, rejections, data provenance, warnings and NAV history.
+It supports every registered UI language. No broker order is sent.
+
+Saved accounts start no earlier than creation in the market's time zone.
+“Next session” sets the earliest eligible date after today; weekends are skipped
+and holidays wait for available session data. Settlement waits until 30 minutes
+after the regular local close (conservative on early-close days). There is no
+background scheduler. Failure leaves the ledger unchanged. Revision checks
+prevent concurrent requests from committing the same step. Ledger and history
+live in `<runtime_root>/paper-trading/accounts.db`.
+
+## CLI
+
+Create `initial-state.json` with your simulated ledger:
+
+```json
+{"cash": 100000, "positions": [{"symbol": "AAPL.US", "qty": 10, "avg_cost": 330}]}
+```
+
+```bash
+vibe-trading paper create --label 'US research' --market us --state initial-state.json --start today
+vibe-trading paper list
+vibe-trading paper show ACCOUNT_ID
+vibe-trading paper advance ACCOUNT_ID --revision 0 --to-date YYYY-MM-DD --orders orders.json
+vibe-trading paper history ACCOUNT_ID
+```
+
+`orders.json` is an array, e.g. `[{"symbol":"AAPL.US","side":"buy","qty":10}]`.
+Use `[]` for valuation only. Replace `--orders` with `--strategy-path PATH` to run
+a strategy. Explicit orders execute on `--to-date`; all intervening dates are
+checked and valued. The revision is returned by `show` and changes on commit.
+A nonzero CLI exit indicates an error or a step that did not commit.
+
+## API
+
+All routes require the existing API authentication policy. POST routes also use
+the browser-origin and local/authenticated write gate.
+
+| Method and path | Purpose |
+| --- | --- |
+| `GET /api/paper-accounts` | List accounts |
+| `POST /api/paper-accounts` | Create: `label`, `market`, `account_state`, optional `start` (`today` / `next_session`) and `fee_model` |
+| `GET /api/paper-accounts/{id}` | Read ledger and revision |
+| `GET /api/paper-accounts/{id}/history` | Read committed results |
+| `POST /api/paper-accounts/{id}/advance` | `expected_revision`, `to_date`, and exactly one of `orders` / `strategy_path` |
+| `POST /api/paper-trade/step` | Pure caller-owned payload; no saved account |
+
+Advance returns `{account, result, committed}`. Data/strategy errors return
+`committed: false`; HTTP 409 means the account changed and must be reloaded.
+After a network timeout, read the account before retrying: the server may have
+committed. The Web client reloads it automatically on a request error.
+
+The pure `paper_trade_step` agent/MCP tool and `vibe-trading paper step payload.json`
+remain stateless and accept historical dates for reproducible research. Their
+orders mode requires a single date. Saved accounts enforce forward-only dates.
+
+## Strategy contract
+
+Place a Python file under `<runtime_root>/strategies/`. The `SignalEngine` class
+is required; `UNIVERSE` supplies symbols for cash-only accounts.
+
+```python
+UNIVERSE = ("AAPL.US",)
+
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ history = ctx.history("AAPL.US")
+ if len(history) < 20 or ctx.account_state.positions:
+ return []
+ if history["close"].iloc[-1] > history["close"].iloc[-20:].mean():
+ return [{"symbol": "AAPL.US", "side": "buy", "qty": 1}]
+ return []
+```
+
+History contains **only dates strictly before execution**. Orders fill at that
+day's close. The strategy receives the private ledger after previous days'
+fills. The spawned child receives no current/future bars and retains its instance
+across dates in one call. Source validation and process timeouts apply. Any
+strategy failure discards the whole call, including earlier uncommitted results.
+
+## Data and model limits
+
+Execution requires raw prices. Tencent's unadjusted endpoint serves A-shares/HK;
+raw-capable providers such as Sina serve US stocks. These paths are separate
+from adjusted backtest feeds. Adjusted/unknown price calibers are rejected.
+A-shares also require an available, complete ClickHouse trading calendar;
+missing dates return `PAPER_DATA_NOT_READY`, not guessed holidays. ClickHouse
+historical bars retain priority on overlapping dates.
+
+Price/volume ratios cannot establish a split. Split-like discontinuities return
+`PAPER_DATA_NOT_READY` without multiplying holdings. Other unresolved
+discontinuities reject affected orders and disclose the issue. Automatic action
+reconciliation and cash dividends are not implemented. NAV is not total return.
+A-shares are included in the raw-price discontinuity checks.
+
+Matching is daily close, all-or-none, with simplified fees, price limits, board
+lots and T+1 checks. HK lot fallback is disclosed. Invalid OHLC prevents fills;
+valuation uses a finite prior close or the disclosed average-cost fallback.
+This is not intraday or broker-execution simulation. The 5-minute, settlement,
+margin, options and cross-market phases in #1938 remain follow-up work.
diff --git a/agent/src/tools/paper_trade/__init__.py b/agent/src/tools/paper_trade/__init__.py
new file mode 100644
index 000000000..14c194ccd
--- /dev/null
+++ b/agent/src/tools/paper_trade/__init__.py
@@ -0,0 +1,27 @@
+"""paper_trade — deterministic paper-trading matching engine (pt-v1.1).
+
+Research-only engine that matches injected orders (or a strategy's per-day
+orders) against daily bars under each market's frozen rules and returns one
+in-band JSON document. It NEVER places a real order and touches no broker /
+trading connector (REQUIREMENTS R1).
+
+Module map: ``schema.py`` (wire contract + boundary parse), ``state_hash.py``
+(JCS ``received_state_hash``), ``calendar.py`` (cn_a CH truth / hk-us zero
+calendar), ``limits_cn_a.py`` (cn_a limit/ST/suspension), ``data.py`` (market
+data supply + AM-9 federation), ``rules.py`` (three-market rule matrix),
+``engine.py`` (day-loop matching), ``corporate_actions.py`` (split detector),
+``wire.py`` (success/error serialization), ``tool.py`` (the ``paper_trade_step``
+entry), ``strategy_exec.py`` (Step 7 strategy_path execution).
+
+The tool registry's auto-discovery (``src/tools/__init__.py``) imports this
+package at agent startup and collects :class:`PaperTradeStepTool` via
+``BaseTool.__subclasses__()`` (VD-12). Consumers import submodules explicitly
+(``from src.tools.paper_trade import engine``); this ``__init__`` re-exports
+only the tool class the registry discovers.
+"""
+
+from __future__ import annotations
+
+from .tool import PaperTradeStepTool
+
+__all__ = ["PaperTradeStepTool"]
diff --git a/agent/src/tools/paper_trade/accounts.py b/agent/src/tools/paper_trade/accounts.py
new file mode 100644
index 000000000..dd963ee01
--- /dev/null
+++ b/agent/src/tools/paper_trade/accounts.py
@@ -0,0 +1,258 @@
+"""Local forward paper accounts shared by CLI and Web API; no broker writes.
+
+The pure step tool remains available for caller-owned ledgers/replays. This
+service owns wall-clock eligibility and commits each successful step atomically.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+import uuid
+from contextlib import contextmanager
+from functools import partial
+from dataclasses import asdict
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Callable
+from zoneinfo import ZoneInfo
+
+from src.config.paths import get_runtime_root
+from .schema import MARKETS, parse_account_state, parse_request
+
+# Daily bars may remain provisional shortly after the regular market close.
+_MARKET_TIME = {
+ "cn_a": ("Asia/Shanghai", 15, 30),
+ "hk": ("Asia/Hong_Kong", 16, 30),
+ "us": ("America/New_York", 16, 30),
+}
+
+
+class AccountConflict(ValueError):
+ """Another request has already advanced this account."""
+
+
+class PaperAccounts:
+ """SQLite ledger with optimistic concurrency across processes and surfaces."""
+
+ def __init__(
+ self,
+ path: Path | None = None,
+ *,
+ clock: Callable | None = None,
+ step: Callable | None = None,
+ ):
+ self.path = path or get_runtime_root() / "paper-trading" / "accounts.db"
+ self.clock = clock or (lambda: datetime.now(timezone.utc))
+ if step is None:
+ from .tool import run_paper_trade_step
+
+ step = partial(run_paper_trade_step, _orders_at_end=True)
+ self.step = step
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ with self._connect() as db:
+ db.execute(
+ "CREATE TABLE IF NOT EXISTS accounts (id TEXT PRIMARY KEY, document TEXT NOT NULL)"
+ )
+ db.execute(
+ "CREATE TABLE IF NOT EXISTS steps (account_id TEXT, revision INTEGER, document TEXT NOT NULL, "
+ "PRIMARY KEY(account_id, revision))"
+ )
+
+ @contextmanager
+ def _connect(self):
+ db = sqlite3.connect(self.path, timeout=10)
+ try:
+ with db:
+ yield db
+ finally:
+ db.close()
+
+ def _now(self, market):
+ return self.clock().astimezone(ZoneInfo(_MARKET_TIME[market][0]))
+
+ def create(
+ self,
+ *,
+ label: str,
+ market: str,
+ account_state: dict,
+ start: str = "today",
+ fee_model: dict | None = None,
+ ) -> dict:
+ """Create a ledger eligible today or at the next observed trading session.
+
+ Args:
+ label: Human-readable account name.
+ market: cn_a, hk, or us.
+ account_state: Initial cash and positions, in the market's currency.
+ start: today or next_session; holidays are resolved by actual bars.
+ fee_model: Optional overrides supported by the selected market.
+ """
+ if not isinstance(label, str) or not label.strip() or len(label) > 80:
+ raise ValueError("label must contain 1–80 characters")
+ if market not in MARKETS or start not in ("today", "next_session"):
+ raise ValueError("invalid market or start mode")
+ state = parse_account_state(account_state)
+ if state.cash < 0 or any(
+ p.qty <= 0 or p.avg_cost <= 0 or not p.symbol.strip()
+ for p in state.positions
+ ):
+ raise ValueError(
+ "Initial cash must be non-negative; positions require positive quantity and average cost"
+ )
+ if len({p.symbol for p in state.positions}) != len(state.positions):
+ raise ValueError("Initial positions must have unique symbols")
+ today = self._now(market).date()
+ earliest = today + timedelta(days=int(start == "next_session"))
+ while earliest.weekday() >= 5:
+ earliest += timedelta(days=1)
+ document = {
+ "id": uuid.uuid4().hex,
+ "label": label.strip(),
+ "market": market,
+ "currency": {"cn_a": "CNY", "hk": "HKD", "us": "USD"}[market],
+ "created_at": self.clock().isoformat(),
+ "start": start,
+ "start_on": earliest.isoformat(),
+ "last_date": None,
+ "revision": 0,
+ "initial_state": asdict(state),
+ "account_state": asdict(state),
+ "fee_model": fee_model if fee_model is not None else {},
+ "last_result": None,
+ }
+ # Reuse the tool's strict numeric/fee validation at every entrance.
+ parse_request(
+ {
+ "account_id": document["id"],
+ "market": market,
+ "account_state": account_state,
+ "from_date": document["start_on"],
+ "to_date": document["start_on"],
+ "orders": [],
+ "fee_model": document["fee_model"],
+ }
+ )
+ if any(value < 0 for value in document["fee_model"].values()):
+ raise ValueError("Fees must be non-negative")
+ document = json.loads(json.dumps(document))
+ with self._connect() as db:
+ db.execute(
+ "INSERT INTO accounts VALUES (?, ?)",
+ (document["id"], json.dumps(document)),
+ )
+ return document
+
+ def list(self) -> list[dict]:
+ with self._connect() as db:
+ return [
+ json.loads(row[0])
+ for row in db.execute(
+ "SELECT document FROM accounts ORDER BY rowid DESC"
+ )
+ ]
+
+ def get(self, account_id: str) -> dict:
+ with self._connect() as db:
+ row = db.execute(
+ "SELECT document FROM accounts WHERE id = ?", (account_id,)
+ ).fetchone()
+ if row is None:
+ raise KeyError("paper account not found")
+ return json.loads(row[0])
+
+ def history(self, account_id: str) -> list[dict]:
+ self.get(account_id)
+ with self._connect() as db:
+ return [
+ json.loads(row[0])
+ for row in db.execute(
+ "SELECT document FROM steps WHERE account_id = ? ORDER BY revision",
+ (account_id,),
+ )
+ ]
+
+ def advance(
+ self,
+ account_id: str,
+ *,
+ expected_revision: int,
+ to_date: str,
+ orders: list | None = None,
+ strategy_path: str | None = None,
+ ) -> dict:
+ """Match completed daily bars and atomically commit, refusing stale callers.
+
+ Args:
+ account_id: Saved account identifier.
+ expected_revision: Revision last read by the caller.
+ to_date: Last completed execution day (YYYY-MM-DD).
+ orders: Explicit orders for a single day, including [] for valuation.
+ strategy_path: Strategy under the configured runtime strategies folder.
+ """
+ account = self.get(account_id)
+ if (
+ not isinstance(expected_revision, int)
+ or isinstance(expected_revision, bool)
+ or expected_revision != account["revision"]
+ ):
+ raise AccountConflict("Account changed; reload before advancing")
+ now = self._now(account["market"])
+ _, hour, minute = _MARKET_TIME[account["market"]]
+ latest = now.date() - timedelta(
+ days=int((now.hour, now.minute) < (hour, minute))
+ )
+ earliest = account["start_on"]
+ if account["last_date"]:
+ earliest = (
+ datetime.fromisoformat(account["last_date"]).date() + timedelta(days=1)
+ ).isoformat()
+ if (
+ not isinstance(to_date, str)
+ or not earliest <= to_date <= latest.isoformat()
+ ):
+ raise ValueError(
+ f"Execution date must be between {earliest} and {latest.isoformat()}; "
+ "wait for a completed session after account creation"
+ )
+ payload = {
+ "account_id": account_id,
+ "market": account["market"],
+ "account_state": account["account_state"],
+ "fee_model": account["fee_model"],
+ "from_date": earliest,
+ "to_date": to_date,
+ }
+ if orders is not None:
+ payload["orders"] = orders
+ if strategy_path is not None:
+ payload["strategy_path"] = strategy_path
+ parse_request(payload)
+ result = json.loads(self.step(payload))
+ if "code" in result:
+ return {"account": account, "result": result, "committed": False}
+ # Closed dates must not consume the account's first eligible session.
+ if not result.get("nav_series"):
+ return {"account": account, "result": result, "committed": False}
+ previous = json.dumps(account)
+ account.update(
+ account_state=result["end_state"],
+ last_date=to_date,
+ revision=expected_revision + 1,
+ last_result=result,
+ )
+ with self._connect() as db:
+ updated = db.execute(
+ "UPDATE accounts SET document = ? WHERE id = ? AND document = ?",
+ (json.dumps(account), account_id, previous),
+ ).rowcount
+ if updated != 1:
+ raise AccountConflict(
+ "Account advanced concurrently; result discarded, reload"
+ )
+ db.execute(
+ "INSERT INTO steps VALUES (?, ?, ?)",
+ (account_id, account["revision"], json.dumps(result)),
+ )
+ return {"account": account, "result": result, "committed": True}
diff --git a/agent/src/tools/paper_trade/calendar.py b/agent/src/tools/paper_trade/calendar.py
new file mode 100644
index 000000000..70e695657
--- /dev/null
+++ b/agent/src/tools/paper_trade/calendar.py
@@ -0,0 +1,283 @@
+"""Trading-calendar seam for ``paper_trade_step`` (pt-v1.1 R3 / AM-6, VD-5).
+
+Market strategy matrix (AM-6):
+
+* **cn_a** — ClickHouse ``ashare.trade_calendar`` is the truth
+ (exchange / cal_date / is_open / pretrade_date). The client is
+ INJECTABLE: this module never constructs a connector, never touches the
+ network, and is offline-testable with a fake client.
+ ``ClickHouseConnector.get_trade_calendar`` (agent/src/clickhouse_connector.py:501)
+ satisfies :class:`TradeCalendarClient` structurally — no wrapper needed.
+* **hk / us** — APPROVED AM-6 zero-calendar fail-closed strategy (G1 open,
+ 2026-10-19): the engine holds NO exchange calendar for these markets and
+ introduces no new dependency (``exchange_calendars``-class packages stay an
+ RM-side escalation path). Day verdicts are inferred from bar availability
+ via :func:`classify_zero_calendar_day` — the three-state matrix:
+ target-day all-market zero bar → ``PAPER_DATA_NOT_READY`` (retryable
+ envelope); mid-range all-market zero bar → skipped reason
+ ``market_closed_inferred`` + mandatory warning (never silently a
+ ``non_trading_day``); single-symbol zero bar → ``suspended`` rejections +
+ carry-forward valuation. The calendar-lookup functions below stay cn_a-only
+ and raise ``NotImplementedError`` for hk/us by design. Day enumeration for
+ hk/us is :func:`hk_us_candidate_days` (weekdays; weekends are non-trading by
+ Gregorian fact, holidays surface as zero-bar weekdays).
+
+Determinism: no clock, no environment, no network reads here; the same
+client rows and bar-availability facts always produce the same verdicts.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Protocol
+
+if TYPE_CHECKING:
+ import pandas as pd
+
+__all__ = [
+ "CN_A_MARKET",
+ "HK_MARKET",
+ "US_MARKET",
+ "VERDICT_MARKET_CLOSED_INFERRED",
+ "VERDICT_NOT_READY",
+ "VERDICT_TRADING_DAY",
+ "TradeCalendarClient",
+ "ZeroCalendarDayVerdict",
+ "classify_zero_calendar_day",
+ "hk_us_candidate_days",
+ "is_trading_day",
+ "trading_days_in_range",
+]
+
+CN_A_MARKET = "cn_a"
+HK_MARKET = "hk"
+US_MARKET = "us"
+
+_CALENDAR_MARKETS = (CN_A_MARKET, HK_MARKET, US_MARKET)
+
+# AM-6 (APPROVED, G1 open 2026-10-19): hk/us are ZERO-CALENDAR markets —
+# fail-closed day classification from bar availability
+# (:func:`classify_zero_calendar_day`). No exchange-calendar dependency is
+# ever introduced here (REQUIREMENTS §9 red line); the escalation path
+# (exchange_calendars-class) is registered RM-side.
+_ZERO_CALENDAR_MARKETS = (HK_MARKET, US_MARKET)
+
+_HK_US_NOT_IMPLEMENTED = (
+ "paper_trade calendar: market {market!r} has no in-engine calendar by design "
+ "(AM-6 zero-calendar fail-closed, approved): day verdicts come from bar "
+ "availability via classify_zero_calendar_day — target-day all-market zero bar "
+ "=> PAPER_DATA_NOT_READY, mid-range all-market zero bar => "
+ "market_closed_inferred + warning, single-symbol zero bar => suspended"
+)
+
+#: AM-6 verdict kinds (frozen three-state matrix). ``market_closed_inferred``
+#: is a member of the closed ``schema.SKIPPED_DAY_REASONS`` vocabulary (pinned
+#: by test); ``not_ready`` maps to the frozen ``PAPER_DATA_NOT_READY`` envelope
+#: code at the tool layer (AM-5).
+VERDICT_TRADING_DAY = "trading_day"
+VERDICT_NOT_READY = "not_ready"
+VERDICT_MARKET_CLOSED_INFERRED = "market_closed_inferred"
+
+_MARKET_CLOSED_WARNING = (
+ "no bars for any symbol on {date}: hk/us have no in-engine calendar "
+ "(AM-6 zero-calendar fail-closed), so the day is inferred closed from bar "
+ "availability and must be cross-checked against the RM static holiday file"
+)
+
+
+@dataclass(frozen=True, slots=True)
+class ZeroCalendarDayVerdict:
+ """One AM-6 matrix verdict for a hk/us candidate day.
+
+ ``suspended_symbols`` is only populated on ``trading_day`` verdicts:
+ symbols with zero bar that day (the engine rejects their orders with
+ reason_code ``suspended`` and values their positions carry-forward).
+ ``warning`` is mandatory on ``market_closed_inferred`` (never silent).
+ """
+
+ date: str
+ kind: str
+ suspended_symbols: tuple[str, ...] = ()
+ warning: str | None = None
+
+
+class TradeCalendarClient(Protocol):
+ """Structural interface for calendar lookups.
+
+ ``ClickHouseConnector`` satisfies it as-is: ``get_trade_calendar``
+ returns a DataFrame with columns ``exchange, cal_date, is_open,
+ pretrade_date`` for the inclusive ``YYYY-MM-DD`` range. Tests inject
+ a fake returning recorded rows — never the network.
+ """
+
+ def get_trade_calendar(self, start_date: str, end_date: str) -> "pd.DataFrame":
+ ...
+
+
+def _normalize_date(value: str) -> str:
+ """Normalize a calendar date to ``YYYY-MM-DD``.
+
+ The connector documents ``YYYY-MM-DD`` parameters, but the stored
+ ``cal_date`` spelling is unverified while ClickHouse is unreachable
+ (Step 0 DD-5 live column recheck pending); tushare-lineage exports
+ commonly use ``YYYYMMDD``. Both spellings normalize; anything else
+ fails closed with a deterministic message.
+ """
+ text = str(value).strip()
+ if len(text) == 10 and text[4] == "-" and text[7] == "-":
+ return text
+ if len(text) == 8 and text.isdigit():
+ return f"{text[:4]}-{text[4:6]}-{text[6:]}"
+ raise ValueError(f"unrecognized calendar date format: {value!r}")
+
+
+def _cn_a_open_map(client: TradeCalendarClient, start_date: str, end_date: str) -> dict[str, bool]:
+ """Query the CH calendar once and reduce rows to {date: is_open}.
+
+ The table carries one row per exchange per date; SSE and SZSE share the
+ cn_a holiday calendar, so a date aggregates as open when ANY row says
+ open — robust to single-exchange exports and deterministic either way.
+ A date with no row at all is NOT a confirmed trading day (the table is
+ the truth source and expected complete; fail closed).
+ """
+ frame = client.get_trade_calendar(start_date, end_date)
+ open_map: dict[str, bool] = {}
+ for record in frame.to_dict("records"):
+ date = _normalize_date(record["cal_date"])
+ is_open = int(record["is_open"]) == 1
+ open_map[date] = open_map.get(date, False) or is_open
+ return open_map
+
+
+def _ensure_calendar_market(market: str) -> None:
+ if market not in _CALENDAR_MARKETS:
+ raise ValueError(f"unknown market for calendar lookup: {market!r}")
+ if market in _ZERO_CALENDAR_MARKETS:
+ raise NotImplementedError(_HK_US_NOT_IMPLEMENTED.format(market=market))
+
+
+def is_trading_day(client: TradeCalendarClient, market: str, date: str) -> bool:
+ """Whether ``date`` (YYYY-MM-DD) is a trading day of ``market``.
+
+ cn_a: CH ``trade_calendar`` truth. hk/us: raises NotImplementedError
+ (AM-6 zero-calendar — use :func:`classify_zero_calendar_day`). Unknown
+ market: ValueError.
+ """
+ _ensure_calendar_market(market)
+ day = _normalize_date(date)
+ return _cn_a_open_map(client, day, day).get(day, False)
+
+
+def trading_days_in_range(
+ client: TradeCalendarClient, market: str, from_date: str, to_date: str
+) -> tuple[str, ...]:
+ """Open trading days within the inclusive range, ascending (R3 driver).
+
+ The engine's day loop (Step 3) consumes this to emit ``skipped_days``
+ rows with reason ``non_trading_day`` for the closed dates in between.
+ """
+ _ensure_calendar_market(market)
+ start = _normalize_date(from_date)
+ end = _normalize_date(to_date)
+ open_map = _cn_a_open_map(client, start, end)
+ # Clamp to the requested range: the real connector filters in SQL, but
+ # the contract this function guarantees is "open days within [start, end]"
+ # regardless of what the client hands back.
+ return tuple(sorted(date for date, is_open in open_map.items() if is_open and start <= date <= end))
+
+
+def hk_us_candidate_days(from_date: str, to_date: str) -> tuple[str, ...]:
+ """Weekdays (Mon-Fri) within the inclusive range, ascending.
+
+ Zero-calendar day enumeration for hk/us: weekends are non-trading by
+ Gregorian fact (no exchange-calendar dependency); holiday closures surface
+ as zero-bar weekdays and are classified by
+ :func:`classify_zero_calendar_day`. Pure date arithmetic on injected
+ strings — deterministic, no clock.
+ """
+ start = dt.date.fromisoformat(_normalize_date(from_date))
+ end = dt.date.fromisoformat(_normalize_date(to_date))
+ if start > end:
+ raise ValueError(f"from_date ({start}) > to_date ({end})")
+ days: list[str] = []
+ day = start
+ while day <= end:
+ if day.weekday() < 5:
+ days.append(day.isoformat())
+ day += dt.timedelta(days=1)
+ return tuple(days)
+
+
+def classify_zero_calendar_day(
+ market: str,
+ date: str,
+ *,
+ is_target_day: bool,
+ symbols: "object",
+ symbols_with_bars: "object",
+) -> ZeroCalendarDayVerdict:
+ """AM-6 fail-closed three-state matrix for one hk/us candidate day.
+
+ ① target day, all-market zero bar → ``VERDICT_NOT_READY`` (the tool layer
+ emits the retryable ``PAPER_DATA_NOT_READY`` envelope; data delays are
+ absorbed by the RM retry chain). ② mid-range day, all-market zero bar →
+ ``VERDICT_MARKET_CLOSED_INFERRED`` + mandatory warning — never silently a
+ ``non_trading_day`` (that reason is cn_a-only, CH calendar truth). ③ any
+ symbol has a bar → ``VERDICT_TRADING_DAY``; zero-bar symbols come back as
+ ``suspended_symbols`` (engine rejects their orders ``suspended`` and
+ values their positions carry-forward).
+
+ ``symbols`` is the account universe (positions ∪ orders);
+ ``symbols_with_bars`` comes from :func:`data.day_bar_availability`.
+ cn_a is refused (ValueError) — ``market_closed_inferred`` is hk/us-only
+ vocabulary. An empty universe classifies as all-market zero bar (the
+ matrix is literal; degenerate calls are the tool layer's concern).
+ """
+ if market not in _ZERO_CALENDAR_MARKETS:
+ raise ValueError(f"zero-calendar classification is hk/us only, got market {market!r}")
+ day = _normalize_date(date)
+ universe = tuple(sorted({str(symbol) for symbol in symbols}))
+ with_bars = frozenset(universe) & {str(symbol) for symbol in symbols_with_bars}
+ if not with_bars:
+ if is_target_day:
+ return ZeroCalendarDayVerdict(day, VERDICT_NOT_READY)
+ return ZeroCalendarDayVerdict(
+ day, VERDICT_MARKET_CLOSED_INFERRED, warning=_MARKET_CLOSED_WARNING.format(date=day)
+ )
+ suspended = tuple(symbol for symbol in universe if symbol not in with_bars)
+ return ZeroCalendarDayVerdict(day, VERDICT_TRADING_DAY, suspended_symbols=suspended)
+
+
+class CalendarUnavailableError(RuntimeError):
+ """A calendar query failed or did not establish every requested date."""
+
+
+@dataclass(frozen=True)
+class CalendarSnapshot:
+ frame: "pd.DataFrame"
+
+ def get_trade_calendar(self, start_date: str, end_date: str) -> "pd.DataFrame":
+ return self.frame.copy()
+
+
+def snapshot_calendar(client: TradeCalendarClient, start_date: str, end_date: str) -> CalendarSnapshot:
+ """Read once; a missing row is unknown, never a confirmed market closure."""
+ import pandas as pd
+
+ try:
+ frame = client.get_trade_calendar(start_date, end_date)
+ observed = {}
+ for row in frame.to_dict("records"):
+ day = _normalize_date(row["cal_date"])
+ if str(row["is_open"]) not in ("0", "1", "False", "True"):
+ raise ValueError("invalid open flag")
+ observed[day] = True
+ required = {day.strftime("%Y-%m-%d") for day in pd.date_range(start_date, end_date)}
+ if not required.issubset(observed):
+ raise ValueError("incomplete date coverage")
+ frame = frame.copy()
+ frame["is_open"] = frame["is_open"].map(lambda value: int(str(value) in ("1", "True")))
+ return CalendarSnapshot(frame)
+ except Exception as exc:
+ raise CalendarUnavailableError("Trading calendar query failed or has incomplete date coverage") from exc
diff --git a/agent/src/tools/paper_trade/corporate_actions.py b/agent/src/tools/paper_trade/corporate_actions.py
new file mode 100644
index 000000000..e93e9a146
--- /dev/null
+++ b/agent/src/tools/paper_trade/corporate_actions.py
@@ -0,0 +1,333 @@
+"""Market-agnostic split detector for ``paper_trade_step`` (Step 4 / T4).
+
+R6 / AM-2 / VD-6 (frozen, G1-approved): hk/us serve RAW (unadjusted) prices,
+so a split ex-date can break the ledger. All three markets now use raw
+execution bars. This module identifies candidate discontinuities only;
+OHLC/volume is not authoritative corporate-action evidence. The engine
+refuses a split-like candidate without changing holdings.
+
+Triple gate for a CLEAN hit (all three must hold; exact rational arithmetic
+via ``Fraction``/``Decimal`` — never the built-in rounding function, VD-9):
+
+1. **Price gate** — the close-to-close ratio ``close_after / close_before``
+ matches ``1 / mult`` for some frozen clean qty multiplier
+ ``mult ∈ {2,3,4,5,10,3/2} ∪ {1/2,1/3,1/4,1/5,1/10,2/3}`` within
+ :data:`PRICE_RATIO_REL_TOL` (1e-3 relative).
+2. **Volume gate** — the volume ratio ``volume_after / volume_before`` equals
+ the SAME multiple ``mult`` (price 1/4 ⇒ volume 4x — the same-direction
+ confirmation VD-6 requires) within :data:`VOLUME_RATIO_REL_TOL`.
+3. **NAV gate** — post-adjustment NAV continuity against the prior close
+ holds within ±0.01% (:data:`NAV_CONTINUITY_REL_TOL` = 1e-4 relative, the
+ R6-1 frozen bound): ``|qty·mult·close_after − qty·close_before| ≤
+ 1e-4 · qty·close_before``. For qty > 0 the qty cancels, so this is the
+ price gate restated on position value; qty = 0 passes trivially (no
+ position to preserve). The gate is computed with the injected qty to
+ honor the contract signature (input = bar series + current position qty).
+
+A boundary is a CANDIDATE discontinuity only when the price ratio falls
+outside the neutral band bounded by the smallest frozen split magnitudes
+(``ratio ≤ 2/3`` or ``ratio ≥ 3/2``; ``ratio == 1`` is inside the band). A
+candidate that is NOT a clean hit is UNRESOLVED — the ratio is never guessed
+and the boundary is never silently passed (fail-closed, R6-3): the engine
+rejects that symbol's orders for the day ``corporate_action_unresolved``.
+
+Note 2 (APPROVAL §3, VT obligation): only boundaries whose AFTER-date is a
+SIMULATED day in ``[from_date, to_date]`` are scanned; the BEFORE bar may sit
+in the K=120 lookback (required when ``from_date`` itself is the ex-date). A
+historical discontinuity wholly before ``from_date`` never triggers an event
+or a rejection — otherwise a stale non-clean action would keep mis-rejecting
+the symbol for the whole window.
+
+Cash dividends are NEVER detected heuristically (R6-5: a raw series has no
+clean ratio to anchor; fabricating a dividend cash adjustment is worse than
+disclosing the price-return caliber, AM-12). Determinism (R1-1): no clock,
+no randomness, no I/O; every input is injected. Provenance form note: the
+internal ``corporate_actions[]`` entries carry ``detected`` as a bool and
+``ratio`` as a string; the DRAFT wire skeleton types both as strings — T5
+owns the wire surface and reconciles the skeleton at finalization (the
+skeleton file is not touched here).
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from decimal import Decimal
+from fractions import Fraction
+from typing import TYPE_CHECKING, Any, Collection, Mapping, Sequence
+
+if TYPE_CHECKING:
+ from .data import MarketDataResult, SymbolData
+ from .schema import Position
+
+__all__ = [
+ "CLEAN_QTY_MULTIPLIERS",
+ "NAV_CONTINUITY_REL_TOL",
+ "PRICE_RATIO_REL_TOL",
+ "VOLUME_RATIO_REL_TOL",
+ "CorporateActionPlan",
+ "EMPTY_PLAN",
+ "SplitEvent",
+ "build_plan",
+ "classify_boundary",
+ "detect_symbol",
+ "merge_unresolved",
+ "ratio_label",
+]
+
+#: Frozen clean qty-multiplier set (R6-1 / VD-6): {2,3,4,5,10,3/2} ∪ their
+#: reciprocals. A 4:1 split has qty multiplier 4 (price ratio 1/4, volume
+#: ratio 4); a 1:4 reverse split has qty multiplier 1/4. The set is closed
+#: under reciprocation, so the clean price ratios are the same 12 values.
+CLEAN_QTY_MULTIPLIERS: tuple[Fraction, ...] = (
+ Fraction(2), Fraction(3), Fraction(4), Fraction(5), Fraction(10), Fraction(3, 2),
+ Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5), Fraction(1, 10), Fraction(2, 3),
+)
+
+# Neutral band bounds = the smallest frozen split magnitudes expressed as
+# price ratios (qty 3/2 ⇒ price 2/3; qty 2/3 ⇒ price 3/2). A candidate
+# discontinuity is a price ratio at or beyond either bound.
+_BAND_LOW = Fraction(2, 3)
+_BAND_HIGH = Fraction(3, 2)
+
+#: Documented relative tolerances (exact rationals; the built-in rounding
+#: function is never used on any path, VD-9). The price gate (1e-3) absorbs
+#: cent-quote quantization of the ex-date reference price (0.005/P ≤ 1e-3 for
+#: post-split prices P ≥ 5.00; cheaper lines fail closed); the NAV gate is the
+#: contract-frozen ±0.01% (R6-1) and is the binding confirmation for held
+#: positions; volume is looser (1e-2) because share counts are noisier than
+#: prices — it only confirms the same-direction multiple.
+PRICE_RATIO_REL_TOL = Fraction(1, 1000)
+VOLUME_RATIO_REL_TOL = Fraction(1, 100)
+NAV_CONTINUITY_REL_TOL = Fraction(1, 10000)
+
+_ZERO_DEC = Decimal(0)
+
+KIND_CLEAN = "clean"
+KIND_UNRESOLVED = "unresolved"
+KIND_NONE = "none"
+
+
+@dataclass(frozen=True, slots=True)
+class BoundaryVerdict:
+ """One boundary classification (pure detector output)."""
+
+ kind: str # KIND_CLEAN | KIND_UNRESOLVED | KIND_NONE
+ qty_multiplier: Fraction | None = None # clean ratio; None unless clean
+ observed_ratio: Decimal | None = None # close_after/close_before (a fact)
+
+
+@dataclass(frozen=True, slots=True)
+class SplitEvent:
+ """A detected event on one simulated day (clean or unresolved)."""
+
+ symbol: str
+ date: str # ex-date = the AFTER bar's date (a simulated day, note 2)
+ detected: bool # True = ratio candidate, not authority to adjust a ledger
+ qty_multiplier: Fraction | None # clean ratio; None when unresolved
+ observed_ratio: Decimal # observed close_after/close_before (provenance fact)
+
+
+@dataclass(frozen=True, slots=True)
+class CorporateActionPlan:
+ """Assembled plan the engine threads into the day loop (T4)."""
+
+ clean_by_day: Mapping[str, tuple[SplitEvent, ...]]
+ unresolved_by_day: Mapping[str, tuple[str, ...]]
+ warnings: tuple[str, ...]
+ provenance: tuple[dict[str, Any], ...]
+
+
+#: cn_a / no-event plan (the engine uses it verbatim for the exempt market).
+EMPTY_PLAN = CorporateActionPlan(clean_by_day={}, unresolved_by_day={}, warnings=(), provenance=())
+
+
+def _positive_finite(value: float) -> bool:
+ return math.isfinite(value) and value > 0.0
+
+
+def _fraction(value: float) -> Fraction:
+ # Decimal(str(x)) is the VD-9 money-path entry conversion; Fraction of it
+ # is the exact rational of the shortest round-trip decimal (no binary
+ # float error, no built-in rounding function).
+ return Fraction(Decimal(str(value)))
+
+
+def ratio_label(mult: Fraction) -> str:
+ """Human/wire label for a qty multiplier: ``Fraction(4)`` → ``"4:1"``,
+ ``Fraction(1, 4)`` → ``"1:4"``, ``Fraction(3, 2)`` → ``"3:2"``."""
+ return f"{mult.numerator}:{mult.denominator}"
+
+
+def classify_boundary(
+ *,
+ close_before: float,
+ close_after: float,
+ volume_before: float,
+ volume_after: float,
+ qty: Decimal,
+) -> BoundaryVerdict:
+ """Classify one before→after boundary (pure, market-agnostic).
+
+ Returns KIND_NONE when the boundary is not a candidate discontinuity (or
+ the evidence is insufficient — missing/non-positive prior close, no prior
+ bar); KIND_CLEAN when the triple gate confirms a frozen split ratio;
+ KIND_UNRESOLVED when a candidate cannot be explained by a clean ratio
+ (fail-closed — never guess, never silently pass).
+ """
+ # Insufficient evidence: a usable boundary needs two positive finite closes.
+ if not (_positive_finite(close_before) and _positive_finite(close_after)):
+ return BoundaryVerdict(KIND_NONE)
+ dec_before = Decimal(str(close_before))
+ dec_after = Decimal(str(close_after))
+ observed = dec_after / dec_before # Decimal division (28-digit context)
+ price_ratio = Fraction(dec_after) / Fraction(dec_before) # exact, for gates
+
+ # Candidate band: outside (2/3, 3/2). ratio == 1 is inside → no event.
+ if _BAND_LOW < price_ratio < _BAND_HIGH:
+ return BoundaryVerdict(KIND_NONE, observed_ratio=observed)
+
+ # Price gate: does the ratio match 1/mult for a frozen clean multiplier?
+ matched: Fraction | None = None
+ for mult in CLEAN_QTY_MULTIPLIERS:
+ clean_price = 1 / mult
+ if abs(price_ratio - clean_price) <= PRICE_RATIO_REL_TOL * clean_price:
+ matched = mult
+ break
+ if matched is None:
+ # Candidate but no clean ratio explains it → fail-closed unresolved.
+ return BoundaryVerdict(KIND_UNRESOLVED, observed_ratio=observed)
+
+ # Volume gate: same-direction multiple confirmation (price 1/4 ⇒ vol 4x).
+ if not (_positive_finite(volume_before) and _positive_finite(volume_after)):
+ return BoundaryVerdict(KIND_UNRESOLVED, qty_multiplier=None, observed_ratio=observed)
+ volume_ratio = _fraction(volume_after) / _fraction(volume_before)
+ if abs(volume_ratio - matched) > VOLUME_RATIO_REL_TOL * matched:
+ return BoundaryVerdict(KIND_UNRESOLVED, observed_ratio=observed)
+
+ # NAV gate: post-adjustment continuity vs the prior close (±0.01%, R6-1).
+ qty_frac = Fraction(qty)
+ prior_value = qty_frac * Fraction(dec_before)
+ if prior_value > 0:
+ adjusted_value = qty_frac * matched * Fraction(dec_after)
+ if abs(adjusted_value - prior_value) > NAV_CONTINUITY_REL_TOL * prior_value:
+ return BoundaryVerdict(KIND_UNRESOLVED, observed_ratio=observed)
+ return BoundaryVerdict(KIND_CLEAN, qty_multiplier=matched, observed_ratio=observed)
+
+
+def detect_symbol(
+ symbol: str,
+ sym_data: "SymbolData",
+ matching_days: Collection[str],
+ qty: Decimal,
+) -> tuple[SplitEvent, ...]:
+ """Pure per-symbol detector over the served frame (lookback included).
+
+ Scans only boundaries whose AFTER-date is a simulated day (note 2); the
+ BEFORE bar may be a lookback row (required when ``from_date`` is the
+ ex-date). Boundaries wholly inside the lookback are never scanned.
+ """
+ frame = sym_data.frame
+ if frame.empty or len(frame) < 2 or not matching_days:
+ return ()
+ days = frozenset(matching_days)
+ untradable = frozenset(sym_data.untradable_dates)
+ dates = [stamp.strftime("%Y-%m-%d") for stamp in frame.index]
+ closes = frame["close"]
+ volumes = frame["volume"]
+ events: list[SplitEvent] = []
+ for i in range(1, len(frame)):
+ # Note 2: only simulated-day boundaries are candidates. R-V3 flagged
+ # bars are unusable for any consumption (slot 3 rejects that day).
+ if dates[i] not in days or dates[i] in untradable or dates[i - 1] in untradable:
+ continue
+ verdict = classify_boundary(
+ close_before=float(closes.iloc[i - 1]), close_after=float(closes.iloc[i]),
+ volume_before=float(volumes.iloc[i - 1]), volume_after=float(volumes.iloc[i]),
+ qty=qty,
+ )
+ if verdict.kind == KIND_NONE:
+ continue
+ events.append(SplitEvent(
+ symbol=symbol, date=dates[i], detected=(verdict.kind == KIND_CLEAN),
+ qty_multiplier=verdict.qty_multiplier,
+ observed_ratio=verdict.observed_ratio if verdict.observed_ratio is not None else _ZERO_DEC,
+ ))
+ return tuple(events)
+
+
+def _qty_by_symbol(positions: Sequence["Position"]) -> dict[str, Decimal]:
+ qty: dict[str, Decimal] = {}
+ for position in positions:
+ qty[position.symbol] = qty.get(position.symbol, _ZERO_DEC) + Decimal(str(position.qty))
+ return qty
+
+
+def build_plan(
+ market_data: "MarketDataResult",
+ matching_days: Collection[str],
+ positions: Sequence["Position"],
+) -> CorporateActionPlan:
+ """Assemble the per-day plan across all served symbols (sorted, VD-10).
+
+ ``matching_days`` are the simulated days (skip_reason is None) from the
+ engine's day plan; ``positions`` is the input account_state.positions
+ (the detector's NAV gate consumes the current qty per symbol). Warnings
+ are deterministic English with no timestamps (VD-7); provenance entries
+ are ordered by symbol then date.
+ """
+ if not matching_days:
+ return EMPTY_PLAN
+ qty_map = _qty_by_symbol(positions)
+ clean_by_day: dict[str, list[SplitEvent]] = {}
+ unresolved_by_day: dict[str, list[str]] = {}
+ warnings: list[str] = []
+ provenance: list[dict[str, Any]] = []
+ for symbol in market_data.symbols: # served order = sorted (VD-10)
+ sym_data = market_data.data.get(symbol)
+ if sym_data is None:
+ continue
+ for event in detect_symbol(symbol, sym_data, matching_days, qty_map.get(symbol, _ZERO_DEC)):
+ observed = str(event.observed_ratio)
+ if event.detected and event.qty_multiplier is not None:
+ label = ratio_label(event.qty_multiplier)
+ clean_by_day.setdefault(event.date, []).append(event)
+ warnings.append(
+ f"corporate action: {symbol} split {label} on {event.date}; position qty "
+ f"x{event.qty_multiplier}, avg_cost /{event.qty_multiplier}; nav continuous "
+ "within 0.01%")
+ provenance.append(
+ {"symbol": symbol, "date": event.date, "ratio": label, "detected": True})
+ else:
+ unresolved_by_day.setdefault(event.date, []).append(symbol)
+ warnings.append(
+ f"corporate action unresolved: {symbol} on {event.date}; close-to-close "
+ f"ratio {observed} matches no clean split ratio with volume confirmation; "
+ f"orders for {symbol} on {event.date} are rejected fail-closed "
+ "(corporate_action_unresolved)")
+ provenance.append(
+ {"symbol": symbol, "date": event.date, "ratio": observed, "detected": False})
+ return CorporateActionPlan(
+ clean_by_day={day: tuple(events) for day, events in sorted(clean_by_day.items())},
+ unresolved_by_day={
+ day: tuple(sorted(set(symbols))) for day, symbols in sorted(unresolved_by_day.items())},
+ warnings=tuple(warnings),
+ provenance=tuple(provenance),
+ )
+
+
+def merge_unresolved(
+ injected: Mapping[str, Collection[str]] | None,
+ detected: Mapping[str, Collection[str]],
+) -> dict[str, tuple[str, ...]]:
+ """Union the injectable T3 seam with the detector output (never replace).
+
+ The existing ``corporate_action_unresolved_by_day`` override keeps working
+ (T3 tests rely on it); detector findings are added, so a symbol rejected
+ by either source is rejected. Deterministic: days sorted, symbols sorted.
+ """
+ merged: dict[str, set[str]] = {}
+ for source in (injected or {}, detected):
+ for day, symbols in source.items():
+ merged.setdefault(day, set()).update(str(symbol) for symbol in symbols)
+ return {day: tuple(sorted(symbols)) for day, symbols in sorted(merged.items())}
diff --git a/agent/src/tools/paper_trade/data.py b/agent/src/tools/paper_trade/data.py
new file mode 100644
index 000000000..4d9368957
--- /dev/null
+++ b/agent/src/tools/paper_trade/data.py
@@ -0,0 +1,527 @@
+"""Market-data supply layer for ``paper_trade_step`` (pt-v1.1 Step 2 / T2).
+
+Public surface (the Step 3 engine consumes exactly these names):
+:data:`MARKET_LOADER_KEYS` (resolve_loader wiring cn_a→a_share / hk→hk_equity
+/ us→us_equity; the R5 ``MARKET_DATA_ORDER_US_EQUITY`` knob applies),
+:data:`LOOKBACK_TRADING_DAYS` (K=120 FROZEN terminal value, VD-6/B3 —
+delivery-note item; the window ``[from_date − K trading days, to_date]`` is
+part of the data-snapshot definition), :func:`symbols_for_request` (universe =
+positions ∪ orders, sorted — VD-10), :func:`fetch_market_data` (one batch
+fetch per leg over the sorted list; served order = sorted order),
+:func:`assess_readiness` (target-day readiness on the FEDERATED MERGED frame
+— AM-9), :func:`day_bar_availability` (per-day facts for the AM-6 matrix in
+calendar.py).
+
+AM-9 (cn_a federation): the ClickHouse leg supplies T-1 history, the network
+leg (first available non-clickhouse loader of the a_share chain, tencent in
+production) supplies the current day; frames merge CH-priority. Readiness is
+judged on the MERGED frame, never the CH frame alone (CH is T-1 caliber —
+judging on it would false-alarm NOT_READY every trading day). The CH leg
+bypasses ``clickhouse.DataLoader.fetch``: its internal federation calls
+``resolve_loader("a_share")`` (clickhouse.py:296), which resolves back to
+itself whenever CH is healthy and recurses until RecursionError degrades the
+fetch to a CH-only frame (measured: ~490 wasted health checks, no current-day
+bar). The loader registry is never modified (import-only, VD-2).
+
+Production prices must be raw: the existing registry's frame/source caliber
+is checked before matching or merging. Adjusted and unknown network frames
+are refused, including A-share qfq fallback frames; a matching timestamp does
+not make them compatible with a raw-price cash ledger. Explicit injected
+clients/loaders are trusted test or embedding inputs and must supply raw bars.
+The ClickHouse adapter selects the raw OHLC columns explicitly.
+
+Determinism (R1-1): NO clock is read — every date is injected, so the CH UTC
+vs host CST 8h skew cannot leak into verdicts. Zero side effects: no file
+writes, network only to market-data sources; CH credentials come solely from
+the existing ``CLICKHOUSE_*`` env config (zero-credential red line).
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+import logging
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Mapping, Protocol
+
+import numpy as np
+import pandas as pd
+
+from backtest.loaders.registry import frame_caliber, resolve_loader
+
+from .schema import DataProvenance
+
+if TYPE_CHECKING:
+ from .schema import AccountState, Order
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+ "LOOKBACK_CALENDAR_SPAN_DAYS",
+ "LOOKBACK_TRADING_DAYS",
+ "MARKET_LOADER_KEYS",
+ "ClickHouseBarsClient",
+ "CnABarsClient",
+ "MarketDataResult",
+ "ReadinessVerdict",
+ "SymbolData",
+ "assess_readiness",
+ "day_bar_availability",
+ "default_ch_client",
+ "fetch_market_data",
+ "symbols_for_request",
+]
+
+MARKET_LOADER_KEYS: dict[str, str] = {
+ "cn_a": "a_share",
+ "hk": "hk_equity",
+ "us": "us_equity",
+}
+
+#: K — frozen lookback in TRADING days (VD-6/B3 Step 2 terminal value).
+LOOKBACK_TRADING_DAYS = 120
+
+# Calendar span fetched to guarantee K trading bars before from_date even
+# across holiday clusters: ceil(120×7/5)=168 + 32 slack. _trim_window cuts
+# back to exactly K, so the span never leaks into the served snapshot.
+LOOKBACK_CALENDAR_SPAN_DAYS = 200
+
+OHLCV_COLUMNS: tuple[str, ...] = ("open", "high", "low", "close", "volume")
+_PRICE_COLUMNS: tuple[str, ...] = ("open", "high", "low", "close")
+
+#: Frozen in-band envelope code (schema.ERROR_CODES member) for target-day
+#: all-market zero bar (AM-5/AM-9).
+NOT_READY_CODE = "PAPER_DATA_NOT_READY"
+
+_CN_A_MARKET = "cn_a"
+_CLICKHOUSE_LOADER_NAME = "clickhouse"
+
+# Sentinel distinguishing "not injected" from an explicit None.
+_AUTO = object()
+
+
+def _empty_frame() -> pd.DataFrame:
+ columns = {column: pd.Series(dtype="float64") for column in OHLCV_COLUMNS}
+ return pd.DataFrame(columns, index=pd.DatetimeIndex([], name="trade_date"))
+
+
+def _canonical_frame(frame: pd.DataFrame | None) -> pd.DataFrame:
+ # Canonical shape: tz-naive date DatetimeIndex (day-bar semantics: trading
+ # day D stamped midnight), exactly OHLCV_COLUMNS (vol→volume, missing
+ # NaN-filled), ascending, de-duplicated (keep last).
+ if frame is None or len(frame) == 0:
+ return _empty_frame()
+ df = frame.copy()
+ if "trade_date" in df.columns:
+ df = df.set_index(pd.to_datetime(df["trade_date"]))
+ index = pd.DatetimeIndex(df.index)
+ df.index = (index.tz_localize(None) if index.tz is not None else index).normalize()
+ df.index.name = "trade_date"
+ if "vol" in df.columns and "volume" not in df.columns:
+ df = df.rename(columns={"vol": "volume"})
+ for column in OHLCV_COLUMNS:
+ if column not in df.columns:
+ df[column] = float("nan")
+ df[column] = pd.to_numeric(df[column], errors="coerce")
+ df = df[list(OHLCV_COLUMNS)]
+ return df[~df.index.duplicated(keep="last")].sort_index()
+
+
+def _normalize_day(value: str) -> str:
+ return dt.date.fromisoformat(str(value).strip()).isoformat()
+
+
+def _max_as_of(frames: Mapping[str, pd.DataFrame]) -> str | None:
+ stamps = [
+ pd.Timestamp(f.index.max()).strftime("%Y-%m-%d")
+ for f in frames.values() if f is not None and not f.empty
+ ]
+ return max(stamps) if stamps else None
+
+
+def _trim_window(frame: pd.DataFrame, from_date: str, to_date: str) -> pd.DataFrame:
+ # Freeze the served window: the last K trading bars before from_date
+ # (VD-6/B3) plus [from_date, to_date]; later bars never enter the snapshot.
+ if frame.empty:
+ return frame
+ start = pd.Timestamp(from_date)
+ end = pd.Timestamp(to_date)
+ before = frame[frame.index < start]
+ if len(before) > LOOKBACK_TRADING_DAYS:
+ before = before.iloc[-LOOKBACK_TRADING_DAYS:]
+ in_range = frame[(frame.index >= start) & (frame.index <= end)]
+ if before.empty:
+ return in_range
+ if in_range.empty:
+ return before
+ return pd.concat([before, in_range]).sort_index()
+
+
+def _untradable_dates(frame: pd.DataFrame) -> tuple[str, ...]:
+ # R-V3 price sanity gate: non-positive/NaN OHLC bars must never reach
+ # matching (cn_a additive-qfq old levels can go negative). The Step 3
+ # engine rejects that symbol's orders on these dates (frozen-vocabulary
+ # mapping is the engine's call; this layer only flags, never crashes).
+ if frame.empty:
+ return ()
+ prices = frame[list(_PRICE_COLUMNS)]
+ bad = (~np.isfinite(prices)).any(axis=1) | (prices <= 0).any(axis=1)
+ return tuple(day.strftime("%Y-%m-%d") for day in frame.index[bad])
+
+
+def _valuation(frame: pd.DataFrame) -> tuple[float | None, str, bool]:
+ # Carry-forward valuation = last usable positive close in the window (B3);
+ # zero bars — or no positive close — falls back to avg_cost + warning.
+ closes = frame["close"].dropna() if not frame.empty else pd.Series(dtype="float64")
+ positives = closes[np.isfinite(closes) & (closes > 0)]
+ if positives.empty:
+ return None, "avg_cost", True
+ return float(positives.iloc[-1]), "last_close", False
+
+
+class CnABarsClient(Protocol):
+ """Narrow injectable interface for the cn_a CH history leg."""
+
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ """Rows ``trade_date, open, high, low, close, vol`` (empty = no data)."""
+ ...
+
+
+class ClickHouseBarsClient:
+ """CH bar-leg adapter over an INJECTED connector (limits_cn_a.py precedent).
+
+ Narrow explicit SELECT (no ``SELECT *``); raw ``close`` (NOT ``close_hfq``)
+ per the module-docstring caliber facts.
+ """
+
+ def __init__(self, connector: Any) -> None:
+ self._connector = connector
+
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ sql = (
+ "SELECT trade_date, open, high, low, close, vol FROM stk_factor_pro "
+ "WHERE ts_code = {ts_code:String} AND trade_date >= {start_date:String} "
+ "AND trade_date <= {end_date:String} ORDER BY trade_date"
+ )
+ params = {"param_ts_code": ts_code, "param_start_date": start_date, "param_end_date": end_date}
+ return self._connector.query(sql, params=params)
+
+
+def default_ch_client() -> CnABarsClient | None:
+ """CH bar client from the existing ``CLICKHOUSE_*`` env config, or None
+ when unreachable — the cn_a path then degrades to the network leg alone."""
+ try:
+ from src.clickhouse_connector import ClickHouseConnector
+ from src.config.accessor import get_env_config
+
+ cfg = get_env_config().data
+ connector = ClickHouseConnector(
+ host=cfg.clickhouse_host or None, port=cfg.clickhouse_port or None,
+ user=cfg.clickhouse_user or None, password=cfg.clickhouse_password or None,
+ database=cfg.clickhouse_database or None,
+ )
+ # Probe with an AUTHENTICATED SELECT 1, not connector.health_check():
+ # health_check sends its probe with no credentials, so it 403s against
+ # a password-protected server even when the configured credentials are
+ # valid (observed live on the dev CH via SSH tunnel, 2026-10-19).
+ connector.query("SELECT 1")
+ return ClickHouseBarsClient(connector)
+ except Exception as exc: # noqa: BLE001 — unreachable CH degrades, never crashes
+ logger.debug("paper_trade CH bar client unavailable: %s", exc)
+ return None
+
+
+def _resolve_network_loader(chain_key: str, exclude: frozenset[str] = frozenset()) -> Any | None:
+ # First raw-capable loader of the chain, skipping excluded names. The
+ # registry's resolve_loader cannot exclude the chain head, and cn_a must
+ # exclude clickhouse (recursion — module docstring).
+ from backtest.loaders.base import NoAvailableSourceError
+ from backtest.loaders.registry import FALLBACK_CHAINS, LOADER_REGISTRY, price_caliber
+
+ try:
+ head = resolve_loader(chain_key)
+ except NoAvailableSourceError:
+ return None
+ if head.name == "tencent":
+ from .raw_loader import TencentRawLoader
+ return TencentRawLoader()
+ if head.name not in exclude and price_caliber(head.name, chain_key) == "raw":
+ return head
+ for name in FALLBACK_CHAINS.get(chain_key, []):
+ if name in exclude or name not in LOADER_REGISTRY:
+ continue
+ try:
+ loader = LOADER_REGISTRY[name]()
+ if (loader.name == "tencent" or price_caliber(loader.name, chain_key) == "raw") and loader.is_available():
+ if loader.name == "tencent":
+ from .raw_loader import TencentRawLoader
+ return TencentRawLoader()
+ return loader
+ except Exception: # noqa: BLE001 — unavailable candidates keep the walk going
+ continue
+ return None
+
+
+def _fetch_leg(
+ loader: Any, symbols: tuple[str, ...], start_date: str, end_date: str, warnings: list[str],
+ *, production_market: str | None = None,
+) -> dict[str, pd.DataFrame]:
+ # One batch fetch over the sorted symbol list (VD-10); failures degrade
+ # to an empty leg with a structured warning, never a crash.
+ if not symbols:
+ return {}
+ try:
+ served = loader.fetch(list(symbols), start_date, end_date, interval="1D")
+ except Exception as exc: # noqa: BLE001
+ warnings.append(f"network fetch ({loader.name}) failed: {type(exc).__name__}")
+ return {}
+ frames = {}
+ for symbol in symbols:
+ if production_market is not None:
+ caliber = frame_caliber(served.get(symbol), loader.name, production_market, symbol)
+ if caliber != "raw":
+ warnings.append(
+ f"paper matching requires raw prices for {symbol}; "
+ f"{loader.name} supplied {caliber}; frame rejected"
+ )
+ continue
+ frame = _canonical_frame(served.get(symbol))
+ if not frame.empty:
+ frames[symbol] = frame
+ return frames
+
+
+@dataclass(frozen=True, eq=False)
+class SymbolData:
+ """One symbol's served window (eq=False: DataFrame fields are not ==-safe)."""
+
+ symbol: str
+ frame: pd.DataFrame
+ bar_dates: frozenset[str] = frozenset()
+ untradable_dates: tuple[str, ...] = () # R-V3 flagged dates, ascending
+ valuation_price: float | None = None # None ⇒ value at avg_cost
+ valuation_basis: str = "last_close"
+
+ def has_bar(self, day: str) -> bool:
+ return day in self.bar_dates
+
+
+@dataclass(frozen=True, eq=False)
+class MarketDataResult:
+ """Frozen-order fetch result (VD-10): ``symbols`` sorted, ``data`` keyed in
+ the same order; ``provenance`` is the AM-9 merged-frame record."""
+
+ market: str
+ from_date: str
+ to_date: str
+ symbols: tuple[str, ...]
+ data: Mapping[str, SymbolData] = field(default_factory=dict)
+ provenance: DataProvenance = field(default_factory=lambda: DataProvenance(source=""))
+ warnings: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class ReadinessVerdict:
+ """Target-day readiness (AM-9). ``ready=False`` carries the frozen in-band
+ envelope material (AM-5) — this layer never raises for data-not-ready."""
+
+ ready: bool
+ code: str | None = None
+ message: str | None = None
+
+
+def symbols_for_request(
+ account_state: "AccountState", orders: "tuple[Order, ...] | None"
+) -> tuple[str, ...]:
+ """Fetch universe = positions ∪ orders, sorted (VD-10); the zero-order
+ pure-valuation path yields the position symbols alone."""
+ universe = {position.symbol for position in account_state.positions}
+ for order in orders or ():
+ universe.add(order.symbol)
+ return tuple(sorted(universe))
+
+
+def fetch_market_data(
+ market: str,
+ symbols: Any,
+ from_date: str,
+ to_date: str,
+ *,
+ loader: Any = _AUTO,
+ ch_client: Any = _AUTO,
+) -> MarketDataResult:
+ """Fetch the frozen window for every symbol; assemble merged provenance.
+
+ ``loader`` injects the network leg (cn_a: clickhouse-named loaders are
+ refused — recursion guard; hk/us: the single leg); ``ch_client`` injects
+ the cn_a CH leg (``None`` forces network-only). ValueError for an unknown
+ market, bad dates or a clickhouse injection → in-band INVALID_REQUEST (T6).
+ """
+ if market not in MARKET_LOADER_KEYS:
+ raise ValueError(f"unknown market for paper data fetch: {market!r}")
+ start = _normalize_day(from_date)
+ end = _normalize_day(to_date)
+ if start > end:
+ raise ValueError(f"from_date ({start}) > to_date ({end})")
+ ordered = tuple(sorted({str(symbol) for symbol in symbols}))
+ window_start = (
+ dt.date.fromisoformat(start) - dt.timedelta(days=LOOKBACK_CALENDAR_SPAN_DAYS)
+ ).isoformat()
+
+ warnings: list[str] = []
+ if market == _CN_A_MARKET:
+ frames, provenance = _fetch_cn_a(
+ ordered, window_start, end, loader=loader, ch_client=ch_client, warnings=warnings
+ )
+ else:
+ frames, provenance = _fetch_single_leg(
+ market, ordered, window_start, end, loader=loader, warnings=warnings
+ )
+
+ data: dict[str, SymbolData] = {}
+ for symbol in ordered:
+ frame = _trim_window(frames.get(symbol, _empty_frame()), start, end)
+ untradable = _untradable_dates(frame)
+ price, basis, needs_warning = _valuation(frame)
+ if untradable:
+ warnings.append(
+ f"price sanity: {symbol} has {len(untradable)} invalid price bar(s) in the fetch "
+ f"window ({untradable[0]}..{untradable[-1]}); orders on those days are rejected"
+ )
+ if needs_warning:
+ warnings.append(f"valuation: {symbol} has no usable positive close in the fetch window; positions value at avg_cost")
+ data[symbol] = SymbolData(
+ symbol=symbol, frame=frame,
+ bar_dates=frozenset(day.strftime("%Y-%m-%d") for day in frame.index),
+ untradable_dates=untradable, valuation_price=price, valuation_basis=basis,
+ )
+ return MarketDataResult(
+ market=market, from_date=start, to_date=end, symbols=ordered,
+ data=data, provenance=provenance, warnings=tuple(warnings),
+ )
+
+
+def _fetch_cn_a(
+ symbols: tuple[str, ...],
+ window_start: str,
+ to_date: str,
+ *,
+ loader: Any,
+ ch_client: Any,
+ warnings: list[str],
+) -> tuple[dict[str, pd.DataFrame], DataProvenance]:
+ # Explicit two-leg federation (AM-9): CH history + network current day,
+ # merged CH-priority. Legs are fetched sequentially over sorted symbols
+ # (deterministic; no ordering hazard to freeze).
+ if loader is not _AUTO and getattr(loader, "name", "") == _CLICKHOUSE_LOADER_NAME:
+ raise ValueError(
+ "paper data fetch refuses a clickhouse-named loader injection: its internal federation "
+ "leg recurses into resolve_loader (clickhouse.py:296); federate via ch_client instead"
+ )
+ client: CnABarsClient | None = default_ch_client() if ch_client is _AUTO else ch_client
+ ch_frames: dict[str, pd.DataFrame] = {}
+ if client is not None:
+ for symbol in symbols:
+ try:
+ frame = _canonical_frame(client.get_bars(symbol, window_start, to_date))
+ except Exception as exc: # noqa: BLE001 — leg failure degrades, never crashes
+ warnings.append(f"clickhouse leg failed for {symbol}: {type(exc).__name__}")
+ continue
+ if not frame.empty:
+ ch_frames[symbol] = frame
+
+ net_loader = (
+ loader
+ if loader is not _AUTO
+ else _resolve_network_loader(
+ MARKET_LOADER_KEYS[_CN_A_MARKET], exclude=frozenset({_CLICKHOUSE_LOADER_NAME})
+ )
+ )
+ net_frames = (
+ _fetch_leg(net_loader, symbols, window_start, to_date, warnings,
+ production_market=MARKET_LOADER_KEYS[_CN_A_MARKET] if loader is _AUTO else None)
+ if net_loader is not None
+ else {}
+ )
+ if client is None and net_loader is None:
+ warnings.append("no available data source for market 'cn_a'; frames are empty")
+
+ merged: dict[str, pd.DataFrame] = {}
+ for symbol in symbols:
+ ch_frame = ch_frames.get(symbol)
+ net_frame = net_frames.get(symbol)
+ if ch_frame is not None and net_frame is not None:
+ merged[symbol] = ch_frame.combine_first(net_frame) # CH priority (AM-9)
+ elif ch_frame is not None:
+ merged[symbol] = ch_frame
+ elif net_frame is not None:
+ merged[symbol] = net_frame
+
+ ch_as_of = _max_as_of(ch_frames)
+ network_as_of = _max_as_of(net_frames)
+ net_name = str(getattr(net_loader, "name", "network"))
+ if ch_as_of is not None and network_as_of is not None:
+ source = f"clickhouse+{net_name}(merged)"
+ elif ch_as_of is not None:
+ source = "clickhouse"
+ else:
+ source = net_name if network_as_of is not None else "unavailable"
+ provenance = DataProvenance(
+ source=source, bars_as_of=_max_as_of(merged), ch_as_of=ch_as_of, network_as_of=network_as_of
+ )
+ return merged, provenance
+
+
+def _fetch_single_leg(
+ market: str,
+ symbols: tuple[str, ...],
+ window_start: str,
+ to_date: str,
+ *,
+ loader: Any,
+ warnings: list[str],
+) -> tuple[dict[str, pd.DataFrame], DataProvenance]:
+ # hk/us single leg through the registry chain (resolve_loader wiring).
+ net_loader = (
+ loader if loader is not _AUTO else _resolve_network_loader(MARKET_LOADER_KEYS[market])
+ )
+ if net_loader is None:
+ warnings.append(f"no available data source for market {market!r}; frames are empty")
+ return {}, DataProvenance(source="unavailable")
+ frames = _fetch_leg(net_loader, symbols, window_start, to_date, warnings,
+ production_market=MARKET_LOADER_KEYS[market] if loader is _AUTO else None)
+ as_of = _max_as_of(frames)
+ provenance = DataProvenance(
+ source=str(getattr(net_loader, "name", "network")) if frames else "unavailable",
+ bars_as_of=as_of,
+ network_as_of=as_of,
+ )
+ return frames, provenance
+
+
+def assess_readiness(result: MarketDataResult, target_day: str) -> ReadinessVerdict:
+ """Target-day readiness on the merged frame (AM-9), never on a leg alone.
+
+ Ready when ANY served symbol carries the target-day bar (single-symbol
+ absence is a suspended fact for the engine, AM-6③); all-market zero bar →
+ the frozen PAPER_DATA_NOT_READY material (message follows the R1-4 example
+ shape; deterministic English, no timestamps — VD-7). An empty universe is
+ vacuously ready.
+ """
+ day = _normalize_day(target_day)
+ if result.symbols and not any(
+ result.data[symbol].has_bar(day) for symbol in result.symbols
+ ):
+ ends = result.provenance.bars_as_of or "empty"
+ message = f"target bar {day} not available from served sources ({result.provenance.source} frame ends {ends})"
+ return ReadinessVerdict(ready=False, code=NOT_READY_CODE, message=message)
+ return ReadinessVerdict(ready=True)
+
+
+def day_bar_availability(result: MarketDataResult, dates: Any) -> dict[str, tuple[str, ...]]:
+ # Per-day sorted tuple of symbols WITH a bar — the AM-6 matrix input
+ # (dates: iterable of YYYY-MM-DD, e.g. hk_us_candidate_days output).
+ availability: dict[str, tuple[str, ...]] = {}
+ for raw in dates:
+ day = _normalize_day(raw)
+ availability[day] = tuple(s for s in result.symbols if result.data[s].has_bar(day))
+ return availability
diff --git a/agent/src/tools/paper_trade/engine.py b/agent/src/tools/paper_trade/engine.py
new file mode 100644
index 000000000..7620c6089
--- /dev/null
+++ b/agent/src/tools/paper_trade/engine.py
@@ -0,0 +1,516 @@
+"""Deterministic day-loop matching engine for ``paper_trade_step`` (Step 3 / T3).
+
+Frozen surfaces: per-day atomicity (R1-2), AM-14 rejection order
+(:data:`rules.REJECTION_ORDER`, first match wins), VD-10 ordering (input
+order = matching order; fills/rejected day-ascending then input index;
+nav_series day-ascending), AM-3 orders-mode single-day gate, AM-9 readiness
+on the merged frame, AM-6 calendar matrix (cn_a = injected calendar truth,
+hk/us = zero-calendar fail-closed). ``strategy_path`` (T7, :mod:`strategy_exec`) generates orders from prior bars and the current private ledger, then drives :func:`run_day_loop` via the public plan/readiness/error seams.
+Step 4 (T4) threads :mod:`corporate_actions`: simulated-day boundaries only
+(note 2), unverified split-like discontinuities stop the call; unresolved moves reject orders.
+Step-3 interpretations (R-V3 → ``suspended``; empty-universe short-circuit;
+unknown band skips the check + warns; rejected qty echoed; avg_cost
+fee-exclusive 4dp; positions symbol-sorted) live in the STEP3 receipt and
+the comments below. Determinism: no clock, no randomness, dates injected;
+unexpected exceptions propagate (transport = engine-internal fault, AM-5) so
+a half-day is never observable — the call aborts with no partial result.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+from dataclasses import dataclass, field, replace
+from decimal import ROUND_HALF_UP, Decimal
+from typing import Callable, Collection, Mapping
+
+import numpy as np
+import pandas as pd
+
+from . import calendar, corporate_actions, data, state_hash, wire
+from .limits_cn_a import (
+ PROV_LIMITS_HEURISTIC, CnALimitsClient, get_limit_status, heuristic_limit_prices)
+from .rules import MarketRules, money, quantize_money
+from .schema import (
+ AccountState, DataProvenance, Fill, NavPoint, Order, PaperTradeStepRequest,
+ Position, RejectedOrder, SkippedDay,
+)
+
+__all__ = ["DayPlan", "EngineError", "MatchOutcome", "build_day_plan",
+ "error_outcome", "match_orders", "readiness_error", "run_day_loop"]
+
+_Q4 = Decimal("0.0001")
+_ZERO = Decimal("0")
+_SKIP_NON_TRADING = "non_trading_day"
+_SKIP_MARKET_CLOSED = "market_closed_inferred"
+
+
+@dataclass(frozen=True, slots=True)
+class EngineError:
+ # In-band error material (AM-5); T6 maps it to the wire ErrorEnvelope.
+ code: str
+ message: str
+
+
+@dataclass(frozen=True)
+class MatchOutcome:
+ # Engine result, consumable by T5 (hash/fee echo closure) and T6 (wire).
+ # ``error`` set ⇒ in-band error material; arrays empty, ``end_state`` the
+ # untouched input state. ``limit_provenance`` carries the VD-11
+ # table/heuristic tokens (wire mapping is T5's schema-closure call).
+ end_state: AccountState
+ fills: tuple[Fill, ...] = ()
+ rejected_orders: tuple[RejectedOrder, ...] = ()
+ nav_series: tuple[NavPoint, ...] = ()
+ skipped_days: tuple[SkippedDay, ...] = ()
+ warnings: tuple[str, ...] = ()
+ data_provenance: DataProvenance = field(default_factory=lambda: DataProvenance(source=""))
+ effective_fee_model: dict[str, float] = field(default_factory=dict)
+ limit_provenance: tuple[str, ...] = ()
+ error: EngineError | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class DayPlan:
+ date: str
+ skip_reason: str | None # None ⇒ matching day
+ warning: str | None
+
+
+@dataclass
+class _LedgerPosition:
+ qty: Decimal
+ avg_cost: Decimal
+
+
+def _calendar_days(from_date: str, to_date: str) -> list[str]:
+ # Every Gregorian day of the inclusive range (injected dates, no clock).
+ start = dt.date.fromisoformat(from_date)
+ end = dt.date.fromisoformat(to_date)
+ if start > end:
+ raise ValueError(f"from_date ({from_date}) > to_date ({to_date})")
+ days: list[str] = []
+ day = start
+ while day <= end:
+ days.append(day.isoformat())
+ day += dt.timedelta(days=1)
+ return days
+
+
+def build_day_plan(
+ market: str,
+ from_date: str,
+ to_date: str,
+ market_data: data.MarketDataResult,
+ calendar_client: calendar.TradeCalendarClient | None,
+) -> list[DayPlan]:
+ # Day enumeration per the AM-6 matrix. cn_a: the injected CH calendar is
+ # the truth — a missing client RAISES (weekdays are never silently treated
+ # as cn_a trading days); closed dates become non_trading_day skips.
+ if market == calendar.CN_A_MARKET:
+ if calendar_client is None:
+ raise ValueError(
+ "cn_a day enumeration requires an injected TradeCalendarClient "
+ "(ClickHouse trade_calendar is the AM-6 truth source); refusing "
+ "to treat weekdays as cn_a trading days"
+ )
+ trading = set(calendar.trading_days_in_range(calendar_client, market, from_date, to_date))
+ return [
+ DayPlan(day, None if day in trading else _SKIP_NON_TRADING, None)
+ for day in _calendar_days(from_date, to_date)
+ ]
+
+ candidates = calendar.hk_us_candidate_days(from_date, to_date)
+ if not market_data.symbols:
+ # Empty-universe short-circuit (T2 handoff): classify_zero_calendar_day
+ # reads an empty universe literally as all-market zero bar, which would
+ # break a cash-only account; with nothing to classify, every candidate
+ # weekday is a cash-only matching day.
+ return [DayPlan(day, None, None) for day in candidates]
+
+ # hk/us zero-calendar fail-closed: mid-range all-market zero bar →
+ # market_closed_inferred + mandatory warning (never non_trading_day —
+ # that reason is cn_a-only vocabulary); any bar → matching day, and the
+ # zero-bar symbols reject `suspended` per-order via ladder slot 3.
+ availability = data.day_bar_availability(market_data, candidates)
+ plan: list[DayPlan] = []
+ for day in candidates:
+ verdict = calendar.classify_zero_calendar_day(
+ market, day, is_target_day=(day == to_date),
+ symbols=market_data.symbols, symbols_with_bars=availability[day])
+ if verdict.kind == calendar.VERDICT_NOT_READY:
+ # Target-day all-market zero bar (AM-6①). The AM-9 readiness
+ # gate in run_day_loop runs BEFORE the loop over the same bar
+ # facts (assess_readiness ⇔ this verdict) and returns the in-band
+ # PAPER_DATA_NOT_READY material; this entry is a placeholder the
+ # loop never reaches. Never a transport-class raise — a not-ready
+ # target day is a retryable data fact, not an engine fault (AM-5).
+ plan.append(DayPlan(day, None, None))
+ elif verdict.kind == calendar.VERDICT_MARKET_CLOSED_INFERRED:
+ plan.append(DayPlan(day, _SKIP_MARKET_CLOSED, verdict.warning))
+ else:
+ plan.append(DayPlan(day, None, None))
+ return plan
+
+
+class _MatchSession:
+ # Mutable ledger + caches for one run_day_loop call (single-threaded).
+
+ def __init__(
+ self,
+ market: str,
+ rules: MarketRules,
+ market_data: data.MarketDataResult,
+ account_state: AccountState,
+ limits_client: CnALimitsClient | None,
+ corporate_action_unresolved_by_day: Mapping[str, Collection[str]],
+ ca_plan: corporate_actions.CorporateActionPlan,
+ ) -> None:
+ self.market = market
+ self.rules = rules
+ self.market_data = market_data
+ self.limits_client = limits_client
+ self.ca_by_day = corporate_action_unresolved_by_day
+ self.cash = quantize_money(money(account_state.cash))
+ self.positions: dict[str, _LedgerPosition] = {}
+ for position in account_state.positions:
+ self._merge_input_position(position.symbol, money(position.qty), money(position.avg_cost))
+ self.bought_today: dict[str, Decimal] = {}
+ self.fills: list[Fill] = []
+ self.rejected: list[RejectedOrder] = []
+ self.nav_series: list[NavPoint] = []
+ self.skipped: list[SkippedDay] = []
+ self.warnings: list[str] = list(market_data.warnings) + list(ca_plan.warnings)
+ self.limit_provenance: list[str] = []
+ self._band_cache: dict[tuple[str, str], tuple[float | None, float | None]] = {}
+
+ def _merge_input_position(self, symbol: str, qty: Decimal, avg_cost: Decimal) -> None:
+ # Duplicate input symbols merge additively (trusted RM ledger; the
+ # merge keeps the invariant deterministic instead of crashing).
+ existing = self.positions.get(symbol)
+ if existing is None:
+ self.positions[symbol] = _LedgerPosition(qty, avg_cost.quantize(_Q4, rounding=ROUND_HALF_UP))
+ return
+ new_qty = existing.qty + qty
+ merged = existing.qty * existing.avg_cost + qty * avg_cost
+ basis = merged / new_qty if new_qty > _ZERO else avg_cost
+ self.positions[symbol] = _LedgerPosition(
+ new_qty, basis.quantize(_Q4, rounding=ROUND_HALF_UP))
+
+ def match_order(self, day: DayPlan, order: Order) -> None:
+ # The AM-14 ladder: first match wins, one reason per order.
+ symbol = order.symbol
+ sym_data = self.market_data.data.get(symbol)
+ # Slot 1 unknown_symbol: no served data at all in the fetch window.
+ if sym_data is None or not sym_data.bar_dates:
+ self._reject(day, order, "unknown_symbol", f"no market data for {symbol} in the fetch window")
+ return
+ # Slot 2 non_trading_day: cn_a calendar truth (AM-6).
+ if day.skip_reason == _SKIP_NON_TRADING:
+ self._reject(day, order, "non_trading_day", f"{self.market} calendar closed on {day.date}")
+ return
+ # Slot 3 suspended: zero bar today, or an R-V3 untradable bar
+ # (documented mapping: suspended is the closest frozen code).
+ if not sym_data.has_bar(day.date):
+ self._reject(day, order, "suspended", f"no bar for {symbol} on {day.date}; position valued carry-forward")
+ return
+ if day.date in sym_data.untradable_dates:
+ self._reject(day, order, "suspended", f"bar for {symbol} on {day.date} failed the price sanity gate (R-V3)")
+ return
+ # Slot 4 corporate_action_unresolved: T4 detector union + injected seam.
+ if symbol in self.ca_by_day.get(day.date, ()):
+ self._reject(day, order, "corporate_action_unresolved",
+ f"unexplained price discontinuity for {symbol} on {day.date}; "
+ "fail-closed rejection (no clean split ratio resolved)")
+ return
+ # Slot 5 lot_size.
+ if self.rules.lot_violation(symbol, order.qty):
+ self._reject(day, order, "lot_size", f"qty {order.qty} violates the "
+ f"{self.rules.lot_size(symbol)}-share lot rule for {symbol}")
+ return
+ close = float(sym_data.frame.loc[pd.Timestamp(day.date), "close"])
+ # Slot 6 limit_up / limit_down: cn_a bands, BEFORE the AM-7 check.
+ if self.rules.has_price_limits:
+ up, down = self._band(symbol, day.date, sym_data)
+ code = self.rules.band_rejection(order.side, close, up, down)
+ if code == "limit_up":
+ self._reject(day, order, code, f"close {close:.2f} at or above up limit {up:.2f}; buy rejected")
+ return
+ if code == "limit_down":
+ self._reject(day, order, code, f"close {close:.2f} at or below down limit {down:.2f}; sell rejected")
+ return
+ # Slot 7 limit_not_marketable (AM-7: buy fills only close ≤ limit,
+ # sell only close ≥ limit; fill price = close).
+ if self.rules.limit_order_violation(order.side, close, order.limit):
+ detail = (
+ f"close {close:.2f} > limit {order.limit:.2f}"
+ if order.side == "buy"
+ else f"close {close:.2f} < limit {order.limit:.2f}"
+ )
+ self._reject(day, order, "limit_not_marketable", detail)
+ return
+ # Slots 8/9 t_plus_1 → insufficient_position (disjoint conditions;
+ # available = total − bought_today, cn_a sells only).
+ total = self.positions[symbol].qty if symbol in self.positions else _ZERO
+ bought = self.bought_today.get(symbol, _ZERO)
+ code = self.rules.sell_position_rejection(order.side, order.qty, total, bought)
+ if code == "t_plus_1":
+ self._reject(day, order, code, f"sell qty {order.qty} exceeds available position "
+ f"{total - bought} (T+1: {bought} share(s) bought today are not sellable)")
+ return
+ if code == "insufficient_position":
+ self._reject(day, order, code, f"sell qty {order.qty} exceeds position {total}")
+ return
+ # Slot 10 insufficient_cash (§4: qty×price+fee ≤ cash).
+ code = self.rules.cash_rejection(order.side, order.qty, close, self.cash)
+ if code == "insufficient_cash":
+ cost = self.rules.buy_cost(order.qty, close)
+ self._reject(day, order, code, f"buy cost {cost} exceeds cash {self.cash}")
+ return
+ self._fill(day.date, order, close)
+
+ def _reject(self, day: DayPlan, order: Order, code: str, detail: str) -> None:
+ self.rejected.append(
+ RejectedOrder(trade_date=day.date, symbol=order.symbol, side=order.side,
+ qty=order.qty, reason_code=code, detail=detail)
+ )
+
+ def _fill(self, day: str, order: Order, close: float) -> None:
+ # Decimal settlement (VD-9): 2dp notional ± 2dp fee; avg_cost is the
+ # fee-exclusive weighted average fill price, quantized 4dp HALF_UP at
+ # every mutation so internal chaining equals the RM round-trip.
+ qty = money(order.qty)
+ price = money(close)
+ fee = self.rules.fee(order.side, order.qty, close)
+ notional = quantize_money(qty * price)
+ if order.side == "buy":
+ self.cash -= notional + fee
+ existing = self.positions.get(order.symbol)
+ if existing is None or existing.qty == _ZERO:
+ basis = price
+ else:
+ basis = (existing.qty * existing.avg_cost + qty * price) / (existing.qty + qty)
+ self.positions[order.symbol] = _LedgerPosition(
+ qty if existing is None or existing.qty == _ZERO else existing.qty + qty,
+ basis.quantize(_Q4, rounding=ROUND_HALF_UP))
+ self.bought_today[order.symbol] = self.bought_today.get(order.symbol, _ZERO) + qty
+ else:
+ self.cash += notional - fee
+ self.positions[order.symbol].qty -= qty
+ # VD-15/B2 dual mode at the fill boundary: plain Orders → ""; StrategyOrders → ≤200 chars.
+ self.fills.append(Fill(trade_date=day, symbol=order.symbol, side=order.side,
+ qty=order.qty, price=close, fee=float(fee),
+ reason=wire.strategy_fill_reason(getattr(order, "reason", None))))
+
+ def _band(self, symbol: str, day: str, sym_data: data.SymbolData) -> tuple[float | None, float | None]:
+ # VD-11: CH table first (injected client), heuristic board-ratio
+ # fallback (china_a._price_limit via limits_cn_a), provenance tokens
+ # recorded per symbol-day. A band is never fabricated: with no table
+ # row and no previous close the check is SKIPPED with a warning —
+ # the reused _blocked_by_limit primitive's unknown-band semantics.
+ key = (symbol, day)
+ if key in self._band_cache:
+ return self._band_cache[key]
+ prev_close = _prev_close(sym_data, day)
+ up: float | None
+ down: float | None
+ if self.limits_client is not None:
+ status = get_limit_status(self.limits_client, symbol, day, prev_close)
+ up, down = status.up_limit, status.down_limit
+ self.limit_provenance.extend(f"{symbol}@{day}:{token}" for token in status.provenance)
+ elif prev_close is not None:
+ up, down = heuristic_limit_prices(symbol, prev_close, is_st=False)
+ self.limit_provenance.append(f"{symbol}@{day}:{PROV_LIMITS_HEURISTIC}")
+ else:
+ up, down = None, None
+ if up is None and down is None:
+ self.warnings.append(f"limit band unavailable for {symbol} on {day}: no table row "
+ "and no previous close in the fetch window; price-limit check skipped")
+ self._band_cache[key] = (up, down)
+ return up, down
+
+ def add_nav_row(self, day: str) -> None:
+ # §4 NAV row: close × positions + cash. Per-position values quantize
+ # 2dp; suspended symbols value carry-forward (last positive close on
+ # or before the day), falling back to avg_cost with a warning (B3).
+ position_value = _ZERO
+ for symbol in sorted(self.positions):
+ position = self.positions[symbol]
+ if position.qty == _ZERO:
+ continue
+ price = self._valuation_price(symbol, day, position.avg_cost)
+ position_value += quantize_money(position.qty * price)
+ position_value = quantize_money(position_value)
+ self.nav_series.append(NavPoint(date=day, nav=float(self.cash + position_value),
+ cash=float(self.cash), position_value=float(position_value)))
+
+ def _valuation_price(self, symbol: str, day: str, avg_cost: Decimal) -> Decimal:
+ sym_data = self.market_data.data.get(symbol)
+ if sym_data is not None:
+ if sym_data.has_bar(day) and day not in sym_data.untradable_dates:
+ return money(float(sym_data.frame.loc[pd.Timestamp(day), "close"]))
+ if not sym_data.frame.empty:
+ prior = sym_data.frame.loc[: pd.Timestamp(day), "close"].dropna()
+ prior = prior[np.isfinite(prior) & (prior > 0)]
+ if not prior.empty:
+ return money(float(prior.iloc[-1]))
+ self.warnings.append(f"valuation: {symbol} has no usable close on or before {day}; "
+ "position valued at avg_cost")
+ return avg_cost
+
+ def end_state(self) -> AccountState:
+ # Symbol-sorted (deterministic), zero-qty rows dropped.
+ return AccountState(
+ cash=float(self.cash),
+ positions=tuple(
+ Position(symbol=symbol, qty=float(position.qty), avg_cost=float(position.avg_cost))
+ for symbol, position in sorted(self.positions.items()) if position.qty != _ZERO))
+
+
+def _prev_close(sym_data: data.SymbolData, day: str) -> float | None:
+ # Last positive close strictly before the day (heuristic band base).
+ if sym_data.frame.empty:
+ return None
+ prior = sym_data.frame.loc[: pd.Timestamp(day), "close"]
+ prior = prior.iloc[:-1] if sym_data.has_bar(day) else prior
+ prior = prior.dropna()
+ prior = prior[np.isfinite(prior) & (prior > 0)]
+ return float(prior.iloc[-1]) if not prior.empty else None
+
+
+def error_outcome(
+ error: EngineError,
+ account_state: AccountState,
+ market_data: data.MarketDataResult,
+ market: str,
+ fee_model: Mapping[str, float] | None,
+) -> MatchOutcome:
+ return MatchOutcome(
+ end_state=account_state,
+ data_provenance=market_data.provenance,
+ effective_fee_model=state_hash.effective_fee_model(market, dict(fee_model or {})),
+ error=error,
+ )
+
+
+def readiness_error(to_date: str, market_data: data.MarketDataResult, plan: Collection[DayPlan]) -> EngineError | None:
+ # AM-9 gate unless the cn_a calendar truth says to_date is closed; an empty
+ # universe is vacuously ready (T2). T7 runs this BEFORE any strategy day so
+ # a retryable data fact is never masked by a non-retryable strategy failure.
+ target = next((entry for entry in plan if entry.date == to_date), None)
+ if target is None or target.skip_reason != _SKIP_NON_TRADING:
+ verdict = data.assess_readiness(market_data, to_date)
+ if not verdict.ready:
+ return EngineError(verdict.code or data.NOT_READY_CODE, verdict.message or "")
+ return None
+
+
+def match_orders(
+ request: PaperTradeStepRequest,
+ *,
+ market_data: data.MarketDataResult,
+ calendar_client: calendar.TradeCalendarClient | None = None,
+ limits_client: CnALimitsClient | None = None,
+ corporate_action_unresolved_by_day: Mapping[str, Collection[str]] | None = None,
+ hk_lot_sizes: Mapping[str, int] | None = None,
+) -> MatchOutcome:
+ # Orders-mode entry (AM-3 single-day); strategy_path mode bypasses this and
+ # drives run_day_loop through strategy_exec (T7). Contract violations
+ # return stable INVALID_REQUEST material — no matching, no half-day.
+ if market_data.market != request.market:
+ raise ValueError(
+ f"market_data was fetched for {market_data.market!r}, request says {request.market!r}"
+ )
+ if request.from_date != request.to_date:
+ error = EngineError("INVALID_REQUEST", "orders mode requires from_date == to_date "
+ f"(AM-3 single-day); got from_date={request.from_date} to_date={request.to_date}")
+ return error_outcome(error, request.account_state, market_data, request.market, request.fee_model)
+ if request.orders is None:
+ error = EngineError("INVALID_REQUEST", "orders mode requires the orders array; "
+ "strategy_path execution lands in Step 7")
+ return error_outcome(error, request.account_state, market_data, request.market, request.fee_model)
+ return run_day_loop(
+ market=request.market, account_state=request.account_state,
+ from_date=request.from_date, to_date=request.to_date, market_data=market_data,
+ orders_by_day={request.from_date: request.orders}, fee_model=request.fee_model,
+ calendar_client=calendar_client, limits_client=limits_client, hk_lot_sizes=hk_lot_sizes,
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day)
+
+
+def run_day_loop(
+ *,
+ market: str,
+ account_state: AccountState,
+ from_date: str,
+ to_date: str,
+ orders_by_day: Mapping[str, Collection[Order]],
+ order_provider: Callable[[str, AccountState], Collection[Order]] | None = None,
+ market_data: data.MarketDataResult,
+ fee_model: Mapping[str, float] | None = None,
+ calendar_client: calendar.TradeCalendarClient | None = None,
+ limits_client: CnALimitsClient | None = None,
+ corporate_action_unresolved_by_day: Mapping[str, Collection[str]] | None = None,
+ hk_lot_sizes: Mapping[str, int] | None = None,
+) -> MatchOutcome:
+ # Day-loop core: enumerate [from, to], gate readiness (AM-9), match
+ # serially (VD-10). Multi-day ranges are only reachable through this
+ # seam (orders mode is single-day, AM-3). Day k's ledger state carries
+ # into day k+1 (R1-2: previous end_state = next day's input).
+ if market_data.market != market:
+ raise ValueError(f"market_data was fetched for {market_data.market!r}, market says {market!r}")
+ rules = MarketRules(market, fee_model, hk_lot_sizes)
+ plan = build_day_plan(market, from_date, to_date, market_data, calendar_client)
+
+ # Readiness gate (AM-9) — shared with the T7 strategy seam.
+ if (error := readiness_error(to_date, market_data, plan)) is not None:
+ return error_outcome(error, account_state, market_data, market, fee_model)
+
+ # OHLC/volume ratios identify discontinuities, not authoritative actions.
+ # All production execution series are raw, including A-shares. Never
+ # multiply a holding based only on a price crash that resembles a split.
+ ca_plan = corporate_actions.build_plan(
+ market_data, [e.date for e in plan if e.skip_reason is None], account_state.positions)
+ if ca_plan.clean_by_day:
+ day = min(ca_plan.clean_by_day)
+ symbols = ", ".join(event.symbol for event in ca_plan.clean_by_day[day])
+ return error_outcome(EngineError(
+ "PAPER_DATA_NOT_READY",
+ f"Unverified corporate action on {day} for {symbols}; "
+ "price/volume ratios cannot establish a split. Reconcile against an authoritative action record."),
+ account_state, market_data, market, fee_model)
+ session = _MatchSession(
+ market, rules, market_data, account_state, limits_client,
+ corporate_actions.merge_unresolved(
+ corporate_action_unresolved_by_day, ca_plan.unresolved_by_day),
+ ca_plan)
+ for entry in plan:
+ session.bought_today = {} # T+1 availability resets each day
+ if entry.skip_reason is not None:
+ session.skipped.append(SkippedDay(date=entry.date, reason=entry.skip_reason))
+ if entry.warning:
+ session.warnings.append(entry.warning)
+ # Orders run the ladder on EVERY day: a cn_a non-trading day rejects
+ # at slot 2; an inferred-closed hk/us day rejects at slot 3
+ # (suspended — never non_trading_day, which is cn_a-only vocabulary).
+ orders = (order_provider(entry.date, session.end_state())
+ if order_provider is not None and entry.skip_reason is None
+ else orders_by_day.get(entry.date, ()))
+ for order in tuple(orders):
+ session.match_order(entry, order)
+ if entry.skip_reason is None:
+ session.add_nav_row(entry.date) # per-day commit: fills + one nav row
+
+ for symbol, lot in sorted(rules.lot_assumptions.items()):
+ session.warnings.append(f"lot assumption: {symbol} sized on the default {lot}-share "
+ "board lot (no lot table entry)")
+ return MatchOutcome(
+ end_state=session.end_state(),
+ fills=tuple(session.fills),
+ rejected_orders=tuple(session.rejected),
+ nav_series=tuple(session.nav_series),
+ skipped_days=tuple(session.skipped),
+ warnings=tuple(dict.fromkeys(session.warnings)),
+ data_provenance=replace(market_data.provenance, corporate_actions=(
+ tuple(market_data.provenance.corporate_actions) + ca_plan.provenance)),
+ effective_fee_model=rules.effective_fee_model,
+ limit_provenance=tuple(dict.fromkeys(session.limit_provenance)),
+ )
diff --git a/agent/src/tools/paper_trade/limits_cn_a.py b/agent/src/tools/paper_trade/limits_cn_a.py
new file mode 100644
index 000000000..a2111b1af
--- /dev/null
+++ b/agent/src/tools/paper_trade/limits_cn_a.py
@@ -0,0 +1,242 @@
+"""cn_a price-limit / ST / suspension lookups (pt-v1.1 §4, VD-11).
+
+Table-first, heuristic-fallback, provenance-recorded:
+
+* **Tables (truth)** — ClickHouse ``ashare`` DDL snapshots:
+ ``stk_limit`` (up_limit/down_limit prices per trade_date+ts_code),
+ ``stk_st_daily`` (ST flag rows), ``stk_suspend`` (suspension rows),
+ ``stk_limit_list_d`` (auxiliary: which side the symbol locked, ``limit``
+ column ``U``/``D``/``Z``; the engine — Step 3 — decides consumption).
+* **Heuristic (fallback)** — when ``stk_limit`` lacks the day, the band is
+ derived from the board ratio via ``backtest.engines.china_a._price_limit``
+ (REUSED BY IMPORT, never modified — VD-2) applied to the previous close,
+ with the ST ±5% ratio taken from ``stk_st_daily`` (the engine heuristic
+ has a known ST detection gap; the paper path closes it with the table).
+* **Provenance** — every lookup records which path served each facet, so
+ the tool output can state table vs heuristic per symbol-day inside
+ ``data_provenance`` (VD-11). An unknown band is never fabricated: with
+ no table row and no previous close, limits stay ``None`` and the engine
+ fails closed (Step 3 decision).
+
+Money discipline (VD-9): heuristic bands quantize to 0.01 with Decimal
+ROUND_HALF_UP — Python's builtin rounding function is banned on money paths
+(banker's rounding: 2.675 to 2dp yields 2.67, not 2.68).
+
+Determinism: table rows are part of the input snapshot; no clock, no
+environment, no network in this module. Clients are injectable — tests
+use fakes, never live ClickHouse.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from decimal import ROUND_HALF_UP, Decimal
+from typing import TYPE_CHECKING, Protocol
+
+# VD-2: reuse the engine primitive by import; agent/backtest/ is never modified.
+from backtest.engines.china_a import _price_limit
+
+if TYPE_CHECKING:
+ import pandas as pd
+
+__all__ = [
+ "CnALimitStatus",
+ "CnALimitsClient",
+ "ClickHouseLimitsClient",
+ "get_limit_status",
+ "heuristic_limit_prices",
+]
+
+# FROZEN provenance tokens (G1: RM written approval 2026-10-19, pt-v1.1) —
+# they flow into the wire ``data_provenance`` object (AM-9/VD-11 extension
+# surface, FINALIZED at G1 per the contract JSON ``limit_provenance``
+# $comment). Any token change = major schema bump with RM written
+# confirmation (REQUIREMENTS §9).
+PROV_LIMITS_TABLE = "limits:stk_limit"
+PROV_LIMITS_HEURISTIC = "limits:heuristic"
+PROV_LIMITS_UNAVAILABLE = "limits:unavailable"
+PROV_ST_ROW = "st:stk_st_daily"
+PROV_ST_NO_ROW = "st:stk_st_daily-no-row"
+PROV_SUSPEND_ROW = "suspend:stk_suspend"
+PROV_SUSPEND_NO_ROW = "suspend:stk_suspend-no-row"
+PROV_LIMIT_LIST_ROW = "limit_list:stk_limit_list_d"
+
+#: ST price-limit ratio (REQUIREMENTS §4: ST ±5%). The board heuristic in
+#: china_a.py cannot detect ST from the code alone; the table can.
+_ST_LIMIT_RATIO = Decimal("0.05")
+
+_TICK = Decimal("0.01")
+
+
+class CnALimitsClient(Protocol):
+ """Narrow injectable lookup surface (one method per CH table).
+
+ :class:`ClickHouseLimitsClient` adapts a ``ClickHouseConnector``; tests
+ inject fakes returning recorded DataFrames. All ``trade_date``
+ parameters are ``YYYY-MM-DD`` strings.
+ """
+
+ def get_stk_limit(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ """Rows with columns ``up_limit``, ``down_limit`` (empty = no data)."""
+ ...
+
+ def get_stk_st_daily(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ """Rows with columns ``type``, ``type_name`` (any row = ST that day)."""
+ ...
+
+ def get_stk_suspend(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ """Rows with columns ``suspend_type``, ``suspend_timing``."""
+ ...
+
+ def get_stk_limit_list(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ """Rows with the ``limit`` column (``U``/``D``/``Z``), auxiliary."""
+ ...
+
+
+@dataclass(frozen=True, slots=True)
+class CnALimitStatus:
+ """Per symbol-day limit/ST/suspension status with path provenance."""
+
+ ts_code: str
+ trade_date: str
+ up_limit: float | None
+ down_limit: float | None
+ is_st: bool
+ is_suspended: bool
+ limit_list_flag: str | None
+ provenance: tuple[str, ...]
+
+
+def heuristic_limit_prices(ts_code: str, prev_close: float, is_st: bool) -> tuple[float, float]:
+ """Derive (up_limit, down_limit) from the board ratio and previous close.
+
+ Ratio source: ``china_a._price_limit`` (main board 10%, ChiNext/STAR
+ 20%, BSE 30%), overridden to 5% when the ST table says the symbol is
+ ST that day. Quantized to the 0.01 tick with ROUND_HALF_UP (VD-9).
+ ``prev_close`` must be positive — non-positive prices are a data-layer
+ sanity gate (plan R-V3), not something to derive bands from.
+ """
+ if prev_close <= 0:
+ raise ValueError(f"prev_close must be positive to derive a heuristic band, got {prev_close!r}")
+ ratio = _ST_LIMIT_RATIO if is_st else Decimal(str(_price_limit(ts_code)))
+ base = Decimal(str(prev_close))
+ up = (base * (Decimal(1) + ratio)).quantize(_TICK, rounding=ROUND_HALF_UP)
+ down = (base * (Decimal(1) - ratio)).quantize(_TICK, rounding=ROUND_HALF_UP)
+ return float(up), float(down)
+
+
+def _records(frame: "pd.DataFrame") -> list[dict]:
+ return list(frame.to_dict("records"))
+
+
+def _is_suspended(records: list[dict]) -> bool:
+ """Suspension verdict from ``stk_suspend`` rows.
+
+ tushare-lineage semantics: ``suspend_type`` ``S`` = suspended,
+ ``R`` = resumed. A resumption row means the symbol trades again, so
+ only non-``R`` rows count as suspended. (Live column recheck is a
+ Step 0 DD-5 item — ClickHouse is currently unreachable; the fake-client
+ tests pin this interpretation.)
+ """
+ return any(str(record.get("suspend_type", "")).strip().upper() != "R" for record in records)
+
+
+def get_limit_status(
+ client: CnALimitsClient,
+ ts_code: str,
+ trade_date: str,
+ prev_close: float | None = None,
+) -> CnALimitStatus:
+ """Look up one symbol-day: table-first, heuristic fallback, provenance.
+
+ ``prev_close`` is only needed on the heuristic path (the ``stk_limit``
+ table carries absolute prices). When neither the table nor a previous
+ close is available, ``up_limit``/``down_limit`` are ``None`` and the
+ provenance says ``limits:unavailable`` — the caller must fail closed,
+ never fabricate a band.
+ """
+ provenance: list[str] = []
+
+ st_records = _records(client.get_stk_st_daily(trade_date, ts_code))
+ is_st = bool(st_records)
+ provenance.append(PROV_ST_ROW if is_st else PROV_ST_NO_ROW)
+
+ suspend_records = _records(client.get_stk_suspend(trade_date, ts_code))
+ is_suspended = _is_suspended(suspend_records)
+ provenance.append(PROV_SUSPEND_ROW if suspend_records else PROV_SUSPEND_NO_ROW)
+
+ limit_records = _records(client.get_stk_limit(trade_date, ts_code))
+ up_limit: float | None
+ down_limit: float | None
+ if limit_records:
+ up_limit = float(limit_records[0]["up_limit"])
+ down_limit = float(limit_records[0]["down_limit"])
+ provenance.append(PROV_LIMITS_TABLE)
+ elif prev_close is not None:
+ up_limit, down_limit = heuristic_limit_prices(ts_code, prev_close, is_st)
+ provenance.append(PROV_LIMITS_HEURISTIC)
+ else:
+ up_limit = None
+ down_limit = None
+ provenance.append(PROV_LIMITS_UNAVAILABLE)
+
+ limit_list_flag: str | None = None
+ list_records = _records(client.get_stk_limit_list(trade_date, ts_code))
+ if list_records:
+ raw_flag = str(list_records[0].get("limit") or "").strip()
+ limit_list_flag = raw_flag or None
+ provenance.append(PROV_LIMIT_LIST_ROW)
+
+ return CnALimitStatus(
+ ts_code=ts_code,
+ trade_date=trade_date,
+ up_limit=up_limit,
+ down_limit=down_limit,
+ is_st=is_st,
+ is_suspended=is_suspended,
+ limit_list_flag=limit_list_flag,
+ provenance=tuple(provenance),
+ )
+
+
+class _QueryConnector(Protocol):
+ """The one ``ClickHouseConnector`` method the adapter needs."""
+
+ def query(self, sql: str, params: dict[str, str] | None = None) -> "pd.DataFrame":
+ ...
+
+
+class ClickHouseLimitsClient:
+ """Thin adapter over an INJECTED connector (VD-2: adapters live here).
+
+ Never constructs ``ClickHouseConnector`` itself — credentials and
+ connection stay the caller's decision (zero side effects at import and
+ construction). SQL follows the connector's established parameter style
+ (``{name:Type}`` placeholders bound via ``param_<name>``) and names
+ columns explicitly (no ``SELECT *`` — clickhouse_columns.py contract).
+ """
+
+ def __init__(self, connector: _QueryConnector) -> None:
+ self._connector = connector
+
+ def _lookup(self, table: str, columns: str, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ sql = (
+ f"SELECT {columns} FROM {table} "
+ "WHERE trade_date = {trade_date:String} AND ts_code = {ts_code:String}"
+ )
+ return self._connector.query(
+ sql, params={"param_trade_date": trade_date, "param_ts_code": ts_code}
+ )
+
+ def get_stk_limit(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ return self._lookup("stk_limit", "up_limit, down_limit", trade_date, ts_code)
+
+ def get_stk_st_daily(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ return self._lookup("stk_st_daily", "type, type_name", trade_date, ts_code)
+
+ def get_stk_suspend(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ return self._lookup("stk_suspend", "suspend_type, suspend_timing", trade_date, ts_code)
+
+ def get_stk_limit_list(self, trade_date: str, ts_code: str) -> "pd.DataFrame":
+ # `limit` is a SQL keyword — backtick-quoted in ClickHouse.
+ return self._lookup("stk_limit_list_d", "`limit`", trade_date, ts_code)
diff --git a/agent/src/tools/paper_trade/paper_trade_step-v1.1.json b/agent/src/tools/paper_trade/paper_trade_step-v1.1.json
new file mode 100644
index 000000000..78b83b9c3
--- /dev/null
+++ b/agent/src/tools/paper_trade/paper_trade_step-v1.1.json
@@ -0,0 +1,248 @@
+{
+ "$comment": "FINALIZED pt-v1.1 — G1 opened by the RM written approval of 2026-10-19 (PAPER_TRADING_ENGINE_APPROVAL_GRANTED_PT_V1.1.md). First tool-contract schema in this repo (VD-13 landing spot; the root schema/ tree otherwise holds ClickHouse DDL only). Field set per AMENDMENT §2.2/§2.3 and AM-14 vocabularies; frozen per the approval §5 declaration: vocabulary or field-set changes = major schema bump with RM written confirmation, additive fields = minor (REQUIREMENTS §9). Two named schemas live under 'schemas': 'result' (success out-param document) and 'error_envelope' (in-band error, AM-5). Both stay within the keyword subset the dependency-free validator in agent/src/tools/paper_trade/schema.py implements (type/const/enum/required/properties/items/additionalProperties), so the file is a standard draft-2020-12 document that the real jsonschema library can also consume.",
+ "contract": "paper_trade_step",
+ "version": "pt-v1.1",
+ "status": "final",
+ "schemas": {
+ "result": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.1/result.json",
+ "title": "paper_trade_step success result (pt-v1.1)",
+ "type": "object",
+ "required": [
+ "schema_version",
+ "tool",
+ "account_id",
+ "market",
+ "range",
+ "received_state_hash",
+ "effective_fee_model",
+ "fills",
+ "rejected_orders",
+ "end_state",
+ "nav_series",
+ "skipped_days",
+ "warnings",
+ "data_provenance"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "schema_version": {
+ "type": "string",
+ "const": "pt-v1.1",
+ "$comment": "FROZEN const — pt-v1.1 is the first frozen implementation version (G1 approved 2026-10-19; AMENDMENT header version-semantics ruling); any change = major schema bump"
+ },
+ "tool": { "type": "string", "const": "paper_trade_step" },
+ "account_id": {
+ "type": "string",
+ "minLength": 1,
+ "$comment": "verbatim echo of the input (R4)"
+ },
+ "market": { "type": "string", "enum": ["cn_a", "hk", "us"] },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "sha256(JCS(non-order inputs)) — AM-4/R7; 64 lowercase hex"
+ },
+ "effective_fee_model": {
+ "type": "object",
+ "$comment": "Full echo of the fee parameters in effect (R7-3). Default key names FROZEN per APPROVAL note 5 / REQUIREMENTS §4 (state_hash.py _DEFAULT_FEE_MODELS, delivery note #7): cn_a = commission_rate 0.00025, commission_min 5.0, stamp_tax_sell 0.0005, transfer_fee 0.00001; hk = commission_rate 0.0003, commission_min 3.0, stamp_tax_rate 0.001, regulatory_levy_rate 0.00003; us = commission_per_share 0.0049, commission_min 0.99, sec_fee_rate 0.0. Per-key merge: RM always injects fee_model explicitly (AM-4-3) and injected keys pass through, so the object stays open by design."
+ },
+ "fills": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "price", "fee", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": { "type": "string", "enum": ["buy", "sell"] },
+ "qty": { "type": "number" },
+ "price": { "type": "number" },
+ "fee": { "type": "number" },
+ "reason": {
+ "type": "string",
+ "$comment": "VD-15: orders mode = empty string; strategy_path mode = strategy reason text truncated to <=200 chars (UTF-8 safe)"
+ }
+ }
+ }
+ },
+ "rejected_orders": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "reason_code", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": { "type": "string", "enum": ["buy", "sell"] },
+ "qty": { "type": "number" },
+ "reason_code": {
+ "type": "string",
+ "enum": [
+ "insufficient_cash",
+ "insufficient_position",
+ "t_plus_1",
+ "limit_up",
+ "limit_down",
+ "suspended",
+ "lot_size",
+ "non_trading_day",
+ "unknown_symbol",
+ "corporate_action_unresolved",
+ "limit_not_marketable"
+ ],
+ "$comment": "AM-14 closed vocabulary (11) — any change = major schema bump"
+ },
+ "detail": { "type": "string" }
+ }
+ }
+ },
+ "end_state": {
+ "type": "object",
+ "required": ["cash", "positions"],
+ "additionalProperties": false,
+ "properties": {
+ "cash": { "type": "number" },
+ "positions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "qty", "avg_cost"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "qty": { "type": "number" },
+ "avg_cost": { "type": "number" }
+ }
+ }
+ }
+ }
+ },
+ "nav_series": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "nav", "cash", "position_value"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "nav": { "type": "number" },
+ "cash": { "type": "number" },
+ "position_value": { "type": "number" }
+ }
+ }
+ },
+ "skipped_days": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "reason": {
+ "type": "string",
+ "enum": ["non_trading_day", "market_closed_inferred"],
+ "$comment": "AM-14 closed vocabulary (2): non_trading_day = cn_a only (CH calendar truth); market_closed_inferred = hk/us only, always accompanied by a warning (AM-6)"
+ }
+ }
+ }
+ },
+ "warnings": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "deterministic English strings, never contain timestamps (VD-7 / R1 hard semantics 1)"
+ },
+ "data_provenance": {
+ "type": "object",
+ "required": ["source"],
+ "additionalProperties": false,
+ "properties": {
+ "source": {
+ "type": "string",
+ "$comment": "AM-9 merged-frame form for cn_a, e.g. 'clickhouse+tencent(merged)'"
+ },
+ "ch_as_of": { "type": "string" },
+ "network_as_of": { "type": "string" },
+ "bars_as_of": { "type": "string" },
+ "corporate_actions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "date", "ratio", "detected"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "date": { "type": "string" },
+ "ratio": {
+ "type": "string",
+ "$comment": "clean hit = ratio label (e.g. '4:1'); unresolved = the observed close-to-close ratio as a decimal string (fail-closed fact, never a guess)"
+ },
+ "detected": {
+ "type": "boolean",
+ "$comment": "true = clean split applied; false = unresolved fail-closed rejection (corporate_action_unresolved). Typed to match the T4 emitter (corporate_actions.py); reconciled from the draft's string typing at G1 finalization as its module docstring assigned to T5"
+ }
+ }
+ }
+ },
+ "limit_provenance": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "VD-11 cn_a limit/ST/suspension path tokens, '<symbol>@<date>:<token>' — token set frozen (limits_cn_a.py): limits:stk_limit / limits:heuristic / limits:unavailable / st:stk_st_daily / st:stk_st_daily-no-row / suspend:stk_suspend / suspend:stk_suspend-no-row / limit_list:stk_limit_list_d. Present only for cn_a runs that consulted the band seam"
+ }
+ },
+ "$comment": "Extension set FINALIZED at G1 (was draft-open): AM-9 merge-state fields (ch_as_of/network_as_of/bars_as_of), T4 corporate_actions, VD-11 limit_provenance. Optional fields are omitted when unset, never null. Further additions = minor schema bump (APPROVAL §5)"
+ }
+ }
+ },
+ "error_envelope": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.1/error_envelope.json",
+ "title": "paper_trade_step in-band error envelope (pt-v1.1, AM-5)",
+ "type": "object",
+ "required": ["status", "code", "account_id", "market", "range", "message"],
+ "additionalProperties": false,
+ "properties": {
+ "status": { "type": "string", "const": "error" },
+ "code": {
+ "type": "string",
+ "enum": ["PAPER_DATA_NOT_READY", "INVALID_REQUEST"],
+ "$comment": "AM-14 closed vocabulary (2 + transport reserved): PAPER_DATA_NOT_READY = retryable (RM 30min x 3); INVALID_REQUEST = non-retryable. Transport-level MCP errors are reserved for engine-internal faults."
+ },
+ "account_id": {
+ "type": "string",
+ "$comment": "verbatim echo even on the error path (AM-4-4/AM-5)"
+ },
+ "market": { "type": "string", "enum": ["cn_a", "hk", "us"] },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "present only when the received account_state was parseable (AM-4-4); omitted otherwise, never null — RM reads the absence as 'state unparseable' and must not burn its retry chain"
+ },
+ "message": {
+ "type": "string",
+ "$comment": "deterministic English, no timestamps (VD-7). Frozen formats include strategy_execution_timeout:{YYYY-MM-DD} and strategy_execution_error:{YYYY-MM-DD}:{exception class} (VD-8/B1, Step 7)"
+ }
+ }
+ }
+ }
+}
diff --git a/agent/src/tools/paper_trade/raw_loader.py b/agent/src/tools/paper_trade/raw_loader.py
new file mode 100644
index 000000000..0d973a465
--- /dev/null
+++ b/agent/src/tools/paper_trade/raw_loader.py
@@ -0,0 +1,23 @@
+"""Unadjusted execution bars, separate from research return-series loaders."""
+
+from backtest.loaders.tencent_loader import DataLoader as TencentLoader
+
+
+class TencentRawLoader:
+ """Read Tencent's raw endpoint without polluting the adjusted-price cache."""
+
+ name = "tencent_raw"
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D"):
+ if interval != "1D":
+ raise ValueError("Paper execution requires daily bars")
+ loader = TencentLoader()
+ result = {}
+ for code in codes:
+ frame = loader._fetch_one(
+ code, start_date, end_date, forward_adjusted=False
+ )
+ if frame is not None and not frame.empty:
+ frame.attrs["adjustment"] = "raw"
+ result[code] = frame
+ return result
diff --git a/agent/src/tools/paper_trade/rules.py b/agent/src/tools/paper_trade/rules.py
new file mode 100644
index 000000000..45e4fde0d
--- /dev/null
+++ b/agent/src/tools/paper_trade/rules.py
@@ -0,0 +1,245 @@
+"""Three-market rule matrix for ``paper_trade_step`` (pt-v1.1 Step 3 / T3).
+
+REQUIREMENTS §4 frozen semantics (values are the registered defaults; any
+micro-adjustment is a delivery-note item, VD-9):
+
+* **Fees (Decimal, ROUND_HALF_UP, quantized 2dp — never the builtin rounding
+ function, never float arithmetic on money)** — cn_a: commission 0.025% min
+ ¥5 + stamp tax sell-only 0.05% + transfer fee 0.001%; hk: commission 0.03%
+ min HK$3 + stamp duty 0.1% per order per side quantized to WHOLE HKD
+ ROUND_HALF_UP (HALF_UP vs HKEX ceil is the registered VD-9 delivery-note
+ choice) + regulatory levy 0.003%; us: $0.0049/share min $0.99, SEC fee
+ simplified to 0. Effective values come from
+ :func:`state_hash.effective_fee_model` (RM always injects fee_model, AM-4-3).
+* **Lots** — cn_a 100 shares (reuses ``ChinaAEngine.round_size`` by import,
+ VD-2); hk per-symbol board lot via ``GlobalEquityEngine._hk_board_lot``
+ (lot table + fallback 100 + ``lot_assumptions`` diagnostic, DD-4); us whole
+ shares (§4 lot = 1 share). A violating qty is REJECTED ``lot_size`` — the
+ paper engine never silently rounds a user-stated qty.
+* **Settlement** — cn_a T+1 on SELLS only (available = total − bought_today);
+ hk/us T+0 (same-day buy→sell passes).
+* **AM-7 limit orders** — buy fills only when close ≤ limit, sell only when
+ close ≥ limit; fill price = close; violation → ``limit_not_marketable``.
+ cn_a price-limit bands (limit_up/limit_down) are checked BEFORE the limit
+ order check (AM-14 order).
+
+:data:`REJECTION_ORDER` is the AM-14 frozen decision sequence (first match
+wins); the engine walks it, this module supplies the per-slot rule checks.
+
+VD-2: engine primitives are reused BY IMPORT (``ChinaAEngine.round_size``,
+``GlobalEquityEngine._hk_board_lot``); ``agent/backtest/`` is never modified.
+``china_a_can_execute`` is deliberately NOT consumed: it tests bands against
+the bar OPEN plus slippage (backtest fill semantics), while the paper contract
+fills at the CLOSE with zero slippage (§4) — the band derivation primitive
+(``_price_limit`` via limits_cn_a) is the reused half. Determinism: no clock,
+no randomness, no I/O; every input is injected.
+"""
+
+from __future__ import annotations
+
+from decimal import ROUND_HALF_UP, Decimal
+from typing import Mapping
+
+# VD-2: reuse engine primitives by import; agent/backtest/ is never modified.
+from backtest.engines.china_a import ChinaAEngine
+from backtest.engines.global_equity import GlobalEquityEngine
+
+from . import state_hash
+
+__all__ = [
+ "CN_A_LOT_SHARES",
+ "REJECTION_ORDER",
+ "US_LOT_SHARES",
+ "MarketRules",
+ "money",
+ "quantize_money",
+]
+
+#: AM-14 frozen rejection decision order — first match wins (REQUIREMENTS §2
+#: hard semantics 3a). ``limit_up``/``limit_down`` share one frozen slot and
+#: sit adjacent: a buy can only hit the upper band, a sell only the lower one,
+#: so adjacency preserves the frozen semantics exactly.
+REJECTION_ORDER: tuple[str, ...] = (
+ "unknown_symbol",
+ "non_trading_day",
+ "suspended",
+ "corporate_action_unresolved",
+ "lot_size",
+ "limit_up",
+ "limit_down",
+ "limit_not_marketable",
+ "t_plus_1", # cn_a sells only
+ "insufficient_position",
+ "insufficient_cash",
+)
+
+#: §4 lot rules: cn_a 100 shares/lot; us 1 share (whole-share orders).
+CN_A_LOT_SHARES = 100
+US_LOT_SHARES = 1
+
+_CENT = Decimal("0.01")
+_ONE = Decimal("1")
+_ZERO = Decimal("0")
+
+
+def money(value: object) -> Decimal:
+ """Money-path entry conversion: ``Decimal(str(x))`` (VD-9)."""
+ return Decimal(str(value))
+
+
+def quantize_money(value: Decimal) -> Decimal:
+ """Quantize to 2dp ROUND_HALF_UP — the frozen money discipline (VD-9)."""
+ return value.quantize(_CENT, rounding=ROUND_HALF_UP)
+
+
+class MarketRules:
+ """Per-market fee / lot / band / gate rules for one matching run.
+
+ Constructed per run (cheap, side-effect free); ``hk_lot_sizes`` injects
+ the board-lot table consumed by the reused ``_hk_board_lot`` mechanism
+ (live per-symbol lots are a T9b concern; the fallback chain — table, then
+ 100, then ``lot_assumptions`` diagnostic — is mandatory either way).
+ """
+
+ def __init__(
+ self,
+ market: str,
+ fee_model: Mapping[str, float] | None = None,
+ hk_lot_sizes: Mapping[str, int] | None = None,
+ ) -> None:
+ if market not in state_hash.FEE_MODEL_MARKETS:
+ raise ValueError(f"unknown market for paper rules: {market!r}")
+ self.market = market
+ #: Effective fee values (R7-3 echo source; T5 finalizes the wire field).
+ self.effective_fee_model: dict[str, float] = state_hash.effective_fee_model(
+ market, dict(fee_model or {})
+ )
+ self._fm = {key: money(value) for key, value in self.effective_fee_model.items()}
+ #: §4 settlement row: T+1 applies to cn_a sells only.
+ self.t_plus_1 = market == "cn_a"
+ #: §4 price-limit row: bands exist for cn_a only (hk/us: none).
+ self.has_price_limits = market == "cn_a"
+ self._cn_a = ChinaAEngine({}) if market == "cn_a" else None
+ self._hk = (
+ GlobalEquityEngine({"hk_lot_sizes": dict(hk_lot_sizes or {})}, market="hk")
+ if market == "hk"
+ else None
+ )
+
+ # ── Lots (§4 手数 row) ──
+
+ def lot_size(self, symbol: str) -> int:
+ """Board lot for one symbol: cn_a 100 / hk per-symbol / us 1."""
+ if self.market == "hk":
+ return int(self._hk._hk_board_lot(symbol))
+ return CN_A_LOT_SHARES if self.market == "cn_a" else US_LOT_SHARES
+
+ @property
+ def lot_assumptions(self) -> dict[str, int]:
+ """HK symbols sized on the fallback lot (DD-4 diagnostic surface)."""
+ return dict(self._hk.lot_assumptions) if self._hk is not None else {}
+
+ def lot_violation(self, symbol: str, qty: float) -> bool:
+ """Whether ``qty`` violates the market lot rule (→ ``lot_size``).
+
+ Non-positive qty is always a violation (the frozen vocabulary has no
+ dedicated code; ``lot_size`` is the closest frozen slot). cn_a reuses
+ ``ChinaAEngine.round_size`` (VD-2): a qty that does not survive the
+ 100-share floor is not a valid lot.
+ """
+ q = money(qty)
+ if q <= _ZERO:
+ return True
+ if self.market == "cn_a":
+ return money(self._cn_a.round_size(float(q), 0.0)) != q
+ if self.market == "hk":
+ return q % Decimal(self.lot_size(symbol)) != _ZERO
+ return q != q.to_integral_value() # us: whole shares
+
+ # ── Fees (§4 费用默认 row; Decimal end-to-end, VD-9) ──
+
+ def fee(self, side: str, qty: float, price: float) -> Decimal:
+ """Total fee for one fill, quantized to 2dp ROUND_HALF_UP."""
+ q = money(qty)
+ notional = q * money(price)
+ if self.market == "cn_a":
+ commission = max(notional * self._fm["commission_rate"], self._fm["commission_min"])
+ total = commission + notional * self._fm["transfer_fee"]
+ if side == "sell":
+ total += notional * self._fm["stamp_tax_sell"]
+ elif self.market == "hk":
+ commission = max(notional * self._fm["commission_rate"], self._fm["commission_min"])
+ # Per order per side, whole HKD, ROUND_HALF_UP (VD-9 registered
+ # choice; HKEX itself ceils — delivery-note item #7).
+ stamp = (notional * self._fm["stamp_tax_rate"]).quantize(_ONE, rounding=ROUND_HALF_UP)
+ total = commission + stamp + notional * self._fm["regulatory_levy_rate"]
+ else:
+ commission = max(q * self._fm["commission_per_share"], self._fm["commission_min"])
+ total = commission + notional * self._fm["sec_fee_rate"] # SEC fee: 0 (§4)
+ return quantize_money(total)
+
+ def buy_cost(self, qty: float, price: float) -> Decimal:
+ """Settled buy cost = 2dp notional + fee (§4 cash gate: qty×price+fee ≤ cash)."""
+ return quantize_money(money(qty) * money(price)) + self.fee("buy", qty, price)
+
+ # ── Price bands + limit orders (§4 成交价/涨跌停 rows) ──
+
+ def band_rejection(
+ self, side: str, close: float, up_limit: float | None, down_limit: float | None
+ ) -> str | None:
+ """``limit_up``/``limit_down`` at the close-fill price, else None.
+
+ cn_a only (§4: hk/us have no bands; us circuit breakers are NOT
+ simulated). Both sides of the comparison quantize to the 0.01 tick
+ (cn_a prices are 2dp; heuristic bands already quantize there) so the
+ verdict is exact Decimal equality-or-beyond, deterministic across
+ platforms. A ``None`` band never fabricates a rejection — mirroring
+ the reused ``_blocked_by_limit`` primitive's unknown-band semantics.
+ """
+ if not self.has_price_limits:
+ return None
+ close_q = money(close).quantize(_CENT, rounding=ROUND_HALF_UP)
+ if side == "buy" and up_limit is not None:
+ if close_q >= money(up_limit).quantize(_CENT, rounding=ROUND_HALF_UP):
+ return "limit_up"
+ if side == "sell" and down_limit is not None:
+ if close_q <= money(down_limit).quantize(_CENT, rounding=ROUND_HALF_UP):
+ return "limit_down"
+ return None
+
+ def limit_order_violation(self, side: str, close: float, limit: float | None) -> bool:
+ """AM-7 frozen semantics: buy fills only when close ≤ limit; sell only
+ when close ≥ limit (fill price = close either way)."""
+ if limit is None:
+ return False
+ close_d, limit_d = money(close), money(limit)
+ return close_d > limit_d if side == "buy" else close_d < limit_d
+
+ # ── Financial gates (§4 资金/持仓 row; AM-14 slots 8-10) ──
+
+ def sell_position_rejection(
+ self, side: str, qty: float, total: Decimal, bought_today: Decimal
+ ) -> str | None:
+ """AM-14 slots ``t_plus_1`` → ``insufficient_position``.
+
+ Discrimination note (frozen): available = total − bought_today;
+ qty > total → ``insufficient_position``; total ≥ qty > available →
+ ``t_plus_1`` (cn_a sells only). The two conditions are disjoint, so
+ the frozen slot order is preserved literally: the ``t_plus_1`` test
+ requires ``total >= qty`` and can never steal an
+ ``insufficient_position`` case.
+ """
+ if side != "sell":
+ return None
+ q = money(qty)
+ if self.t_plus_1 and total >= q > total - bought_today:
+ return "t_plus_1"
+ if q > total:
+ return "insufficient_position"
+ return None
+
+ def cash_rejection(self, side: str, qty: float, price: float, cash: Decimal) -> str | None:
+ """AM-14 slot ``insufficient_cash`` (buys only; §4: qty×price+fee ≤ cash)."""
+ if side != "buy":
+ return None
+ return "insufficient_cash" if self.buy_cost(qty, price) > cash else None
diff --git a/agent/src/tools/paper_trade/schema.py b/agent/src/tools/paper_trade/schema.py
new file mode 100644
index 000000000..818d469cb
--- /dev/null
+++ b/agent/src/tools/paper_trade/schema.py
@@ -0,0 +1,487 @@
+"""pt-v1.1 wire contract for ``paper_trade_step`` (dataclasses + vocabularies).
+
+Declares the in-param, out-param and error-envelope shapes frozen by
+``PAPER_TRADING_ENGINE_AMENDMENT_PT_V1.1.md`` §2 (the FROZEN summary), plus
+the AM-14 closed vocabularies. pt-v1.1 is APPROVED — G1 opened by the RM
+written approval of 2026-10-19 (``PAPER_TRADING_ENGINE_APPROVAL_GRANTED_PT_V1.1.md``).
+Every contract-sensitive value here is FROZEN per the approval §5
+declaration: vocabulary or field-set changes are a major schema bump with
+RM written confirmation; additive fields are a minor bump (REQUIREMENTS §9).
+
+Companion artifacts:
+
+* ``schema/tool_contracts/paper_trade_step-v1.1.json`` — finalized out-param
+ + error-envelope jsonschema (VD-13), loaded by :func:`load_contract_schema`.
+* ``state_hash.py`` — ``received_state_hash`` / ``effective_fee_model``.
+* ``wire.py`` — success/error payload builders + deterministic JSON
+ serialization (Step 5 split: this module stays shapes + boundary parsing).
+
+``jsonschema`` is deliberately NOT imported: it is not a declared runtime
+dependency (zero-new-dependency red line, REQUIREMENTS §9), so
+:func:`validate_payload` implements the small keyword subset the skeleton
+uses. The JSON file stays a standard draft-2020-12 document, so RM (or a
+future declared dependency) can validate it with the real library.
+
+Out-param dataclasses are declarative wire shapes: the engine (Steps 3-5)
+assembles them and owns Decimal→JSON serialization (VD-9). In-params are
+parsed at the boundary by :func:`parse_request` (parse, don't validate —
+downstream code receives typed values).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+__all__ = [
+ "ERROR_CODES",
+ "MARKETS",
+ "REASON_CODES",
+ "SIDES",
+ "SKIPPED_DAY_REASONS",
+ "SCHEMA_VERSION",
+ "TOOL_NAME",
+ "AccountState",
+ "ErrorEnvelope",
+ "Fill",
+ "NavPoint",
+ "Order",
+ "PaperTradeSchemaError",
+ "PaperTradeStepRequest",
+ "PaperTradeStepResult",
+ "Position",
+ "RejectedOrder",
+ "SkippedDay",
+ "load_contract_schema",
+ "parse_account_state",
+ "parse_request",
+ "validate_payload",
+]
+
+#: Wire contract version — FROZEN: pt-v1.1 is the first frozen implementation
+#: version (G1 approved 2026-10-19; AMENDMENT header version-semantics ruling).
+#: Constant convention: backtest_summary.py:31, market_data_tool.py:71.
+SCHEMA_VERSION = "pt-v1.1"
+
+#: Bare MCP tool name (RM observer whitelists bare + ``vibe-trading_`` prefix).
+TOOL_NAME = "paper_trade_step"
+
+# FROZEN (G1 approved 2026-10-19): the three vocabularies below are the AM-14
+# closed tables (11 reason_code + 2 skipped reason + 2 error code). Any
+# add/remove/change = major schema bump with RM written confirmation
+# (REQUIREMENTS §9 / APPROVAL §5 frozen-surface declaration).
+#: ``rejected_orders[].reason_code`` — closed vocabulary, 11 values (AM-14).
+REASON_CODES: tuple[str, ...] = (
+ "insufficient_cash",
+ "insufficient_position",
+ "t_plus_1",
+ "limit_up",
+ "limit_down",
+ "suspended",
+ "lot_size",
+ "non_trading_day",
+ "unknown_symbol",
+ "corporate_action_unresolved", # AM-2
+ "limit_not_marketable", # AM-7
+)
+
+#: ``skipped_days[].reason`` — closed vocabulary, 2 values (AM-14).
+SKIPPED_DAY_REASONS: tuple[str, ...] = (
+ "non_trading_day", # cn_a only — CH trade_calendar truth (AM-6)
+ "market_closed_inferred", # hk/us only — bar-inferred, always + warning (AM-6)
+)
+
+#: In-band error envelope ``code`` — closed vocabulary, 2 values (AM-5/AM-14).
+#: Transport-level MCP errors are reserved for engine-internal faults only.
+ERROR_CODES: tuple[str, ...] = (
+ "PAPER_DATA_NOT_READY", # retryable — RM 30min × 3
+ "INVALID_REQUEST", # non-retryable — input contract violation
+)
+
+# FROZEN (G1 approved 2026-10-19): market/side enums per REQUIREMENTS §2.1
+# (pt-v1.0 dispatched values, carried into pt-v1.1 unchanged).
+MARKETS: tuple[str, ...] = ("cn_a", "hk", "us")
+SIDES: tuple[str, ...] = ("buy", "sell")
+
+_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
+
+#: Repo-root-relative location of the wire-contract jsonschema (VD-13).
+_CONTRACT_SCHEMA_PATH = Path(__file__).with_name("paper_trade_step-v1.1.json")
+
+
+class PaperTradeSchemaError(ValueError):
+ """Raised when a tool input violates the pt-v1.1 in-param contract.
+
+ Step 6 (tool.py) maps this to the in-band ``INVALID_REQUEST`` envelope
+ (AM-5); messages are deterministic English (VD-7).
+ """
+
+
+# ── In-params (REQUIREMENTS §2.1 + AM-3/AM-4 revisions) ──
+
+
+@dataclass(frozen=True, slots=True)
+class Position:
+ """One holding inside ``account_state`` / ``end_state``."""
+
+ symbol: str
+ qty: float
+ avg_cost: float
+
+
+@dataclass(frozen=True, slots=True)
+class AccountState:
+ """RM-injected ledger snapshot. The engine trusts but echoes its hash (R7)."""
+
+ cash: float
+ positions: tuple[Position, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class Order:
+ """One order of the ``orders`` array (single-day mode only, AM-3)."""
+
+ symbol: str
+ side: str
+ qty: float
+ limit: float | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class PaperTradeStepRequest:
+ """Parsed ``paper_trade_step`` in-params.
+
+ ``orders`` XOR ``strategy_path`` and the orders-mode single-day rule
+ (AM-3) are SEMANTIC gates owned by tool.py (Step 6, INVALID_REQUEST);
+ this shape parser does not pre-empt them.
+ """
+
+ account_id: str
+ market: str
+ account_state: AccountState
+ from_date: str
+ to_date: str
+ orders: tuple[Order, ...] | None = None
+ strategy_path: str | None = None
+ # FROZEN (AM-4-3, G1 approved): RM dispatch always injects fee_model
+ # explicitly (required-at-dispatch) while the field stays schema-optional
+ # for backward compatibility (AMENDMENT §2.3).
+ fee_model: dict[str, float] = field(default_factory=dict)
+
+
+def _require_number(value: Any, path: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise PaperTradeSchemaError(f"{path} must be a JSON number, got {type(value).__name__}")
+ try:
+ numeric = float(value)
+ except OverflowError:
+ # An integer literal beyond the double range is not a finite JSON
+ # number for wire purposes (JCS interpretation stays within ±2^53
+ # across implementations, state_hash.py module docstring).
+ numeric = math.inf if value > 0 else -math.inf
+ if not math.isfinite(numeric):
+ raise PaperTradeSchemaError(f"{path} must be a finite JSON number, got {value!r}")
+ return numeric
+
+
+def _require_str(value: Any, path: str) -> str:
+ if not isinstance(value, str):
+ raise PaperTradeSchemaError(f"{path} must be a string, got {type(value).__name__}")
+ return value
+
+
+def _parse_date(value: Any, path: str) -> str:
+ text = _require_str(value, path)
+ if not _DATE_RE.match(text):
+ raise PaperTradeSchemaError(f"{path} must be YYYY-MM-DD, got {text!r}")
+ return text
+
+
+def _parse_position(raw: Any, path: str) -> Position:
+ if not isinstance(raw, dict):
+ raise PaperTradeSchemaError(f"{path} must be an object, got {type(raw).__name__}")
+ return Position(
+ symbol=_require_str(raw.get("symbol"), f"{path}.symbol"),
+ qty=_require_number(raw.get("qty"), f"{path}.qty"),
+ avg_cost=_require_number(raw.get("avg_cost"), f"{path}.avg_cost"),
+ )
+
+
+def parse_account_state(raw: Any, path: str = "account_state") -> AccountState:
+ """Parse ``account_state`` alone (public: the AM-4-4 error-path hash in
+ ``wire.py`` gates on state parseability without a full request parse)."""
+ if not isinstance(raw, dict):
+ raise PaperTradeSchemaError(f"{path} must be an object, got {type(raw).__name__}")
+ positions_raw = raw.get("positions", [])
+ if not isinstance(positions_raw, list):
+ raise PaperTradeSchemaError(f"{path}.positions must be an array")
+ return AccountState(
+ cash=_require_number(raw.get("cash"), f"{path}.cash"),
+ positions=tuple(
+ _parse_position(item, f"{path}.positions[{i}]") for i, item in enumerate(positions_raw)
+ ),
+ )
+
+
+def _parse_order(raw: Any, path: str) -> Order:
+ if not isinstance(raw, dict):
+ raise PaperTradeSchemaError(f"{path} must be an object, got {type(raw).__name__}")
+ side = _require_str(raw.get("side"), f"{path}.side")
+ if side not in SIDES:
+ raise PaperTradeSchemaError(f"{path}.side must be one of {SIDES}, got {side!r}")
+ limit_raw = raw.get("limit")
+ limit = None if limit_raw is None else _require_number(limit_raw, f"{path}.limit")
+ return Order(
+ symbol=_require_str(raw.get("symbol"), f"{path}.symbol"),
+ side=side,
+ qty=_require_number(raw.get("qty"), f"{path}.qty"),
+ limit=limit,
+ )
+
+
+def parse_request(payload: dict[str, Any]) -> PaperTradeStepRequest:
+ """Parse JSON-parsed tool input into the typed request contract.
+
+ Shape-level boundary parse only: types, enums, date format. Raises
+ :class:`PaperTradeSchemaError` with a deterministic message naming the
+ offending path.
+ """
+ if not isinstance(payload, dict):
+ raise PaperTradeSchemaError(f"request must be an object, got {type(payload).__name__}")
+ market = _require_str(payload.get("market"), "market")
+ if market not in MARKETS:
+ raise PaperTradeSchemaError(f"market must be one of {MARKETS}, got {market!r}")
+
+ orders_raw = payload.get("orders")
+ orders: tuple[Order, ...] | None = None
+ if orders_raw is not None:
+ if not isinstance(orders_raw, list):
+ raise PaperTradeSchemaError("orders must be an array")
+ orders = tuple(_parse_order(item, f"orders[{i}]") for i, item in enumerate(orders_raw))
+
+ strategy_path = payload.get("strategy_path")
+ if strategy_path is not None:
+ strategy_path = _require_str(strategy_path, "strategy_path")
+
+ # Only a missing or explicit null fee_model defaults to {} (AM-4-3 keeps
+ # the field schema-optional); a PRESENT falsy non-dict ([] / "" / false /
+ # 0) is a contract violation, not an absence — `or {}` would launder it.
+ fee_model_raw = payload.get("fee_model")
+ if fee_model_raw is None:
+ fee_model_raw = {}
+ if not isinstance(fee_model_raw, dict):
+ raise PaperTradeSchemaError(
+ f"fee_model must be an object, got {type(fee_model_raw).__name__}"
+ )
+ fee_model = {
+ _require_str(key, "fee_model key"): _require_number(value, f"fee_model.{key}")
+ for key, value in fee_model_raw.items()
+ }
+
+ return PaperTradeStepRequest(
+ account_id=_require_str(payload.get("account_id"), "account_id"),
+ market=market,
+ account_state=parse_account_state(payload.get("account_state"), "account_state"),
+ from_date=_parse_date(payload.get("from_date"), "from_date"),
+ to_date=_parse_date(payload.get("to_date"), "to_date"),
+ orders=orders,
+ strategy_path=strategy_path,
+ fee_model=fee_model,
+ )
+
+
+# ── Out-params (AMENDMENT §2.2) — declarative wire shapes ──
+
+
+@dataclass(frozen=True, slots=True)
+class DateRange:
+ """``range`` — the closed [from, to] interval actually processed."""
+
+ from_: str
+ to: str
+
+
+@dataclass(frozen=True, slots=True)
+class Fill:
+ """One executed fill. ``reason`` dual-mode semantics FROZEN (VD-15/B2):
+ orders mode = ``""``; strategy_path mode = strategy reason truncated to
+ <=200 characters, UTF-8 safe (``wire.strategy_fill_reason``)."""
+
+ trade_date: str
+ symbol: str
+ side: str
+ qty: float
+ price: float
+ fee: float
+ reason: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class RejectedOrder:
+ """One rejected order; ``reason_code`` from the closed 11-value table."""
+
+ trade_date: str
+ symbol: str
+ side: str
+ qty: float
+ reason_code: str
+ detail: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class NavPoint:
+ """One ``nav_series`` row (skipped days produce NO row — R3)."""
+
+ date: str
+ nav: float
+ cash: float
+ position_value: float
+
+
+@dataclass(frozen=True, slots=True)
+class SkippedDay:
+ """One ``skipped_days`` row; ``reason`` from the closed 2-value table."""
+
+ date: str
+ reason: str
+
+
+@dataclass(frozen=True, slots=True)
+class DataProvenance:
+ """``data_provenance`` — extension set FINALIZED at G1: AM-9 merged-frame
+ fields (cn_a), AM-2 ``corporate_actions`` events, VD-11 cn_a limit/ST/
+ suspension path tokens (``limit_provenance``, ``<symbol>@<date>:<token>``).
+ Further additions = minor schema bump (APPROVAL §5)."""
+
+ source: str
+ bars_as_of: str | None = None
+ ch_as_of: str | None = None
+ network_as_of: str | None = None
+ corporate_actions: tuple[dict[str, Any], ...] = ()
+ limit_provenance: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class PaperTradeStepResult:
+ """Full success out-param document (AMENDMENT §2.2, pt-v1.1)."""
+
+ account_id: str
+ market: str
+ range: DateRange
+ received_state_hash: str
+ effective_fee_model: dict[str, float]
+ fills: tuple[Fill, ...] = ()
+ rejected_orders: tuple[RejectedOrder, ...] = ()
+ end_state: AccountState = field(default_factory=AccountState)
+ nav_series: tuple[NavPoint, ...] = ()
+ skipped_days: tuple[SkippedDay, ...] = ()
+ warnings: tuple[str, ...] = () # deterministic English, no timestamps (VD-7)
+ data_provenance: DataProvenance = field(
+ default_factory=lambda: DataProvenance(source="")
+ )
+ schema_version: str = SCHEMA_VERSION
+ tool: str = TOOL_NAME
+
+
+@dataclass(frozen=True, slots=True)
+class ErrorEnvelope:
+ """In-band error envelope (AM-5, FROZEN field set) — same
+ ``result.content[0].text`` channel as the success document, never a
+ transport error; ``received_state_hash`` present only when the state was
+ parseable (AM-4-4). Serialized by ``wire.build_error_payload``."""
+
+ code: str
+ account_id: str
+ market: str
+ range: DateRange
+ message: str
+ received_state_hash: str | None = None
+ status: str = "error"
+
+
+# ── Contract schema loading + dependency-free subset validation ──
+
+
+def load_contract_schema(name: str = "result") -> dict[str, Any]:
+ """Load one named jsonschema from the VD-13 contract file.
+
+ ``name`` is ``"result"`` (success out-param) or ``"error_envelope"``.
+ Read-only; the file is the finalized pt-v1.1 contract (G1 approved
+ 2026-10-19).
+ """
+ document = json.loads(_CONTRACT_SCHEMA_PATH.read_text(encoding="utf-8"))
+ schemas = document.get("schemas", {})
+ if name not in schemas:
+ raise KeyError(f"unknown contract schema {name!r}; available: {sorted(schemas)}")
+ return schemas[name]
+
+
+_TYPE_CHECKS: dict[str, tuple[type, ...]] = {
+ "object": (dict,),
+ "array": (list, tuple),
+ "string": (str,),
+ "boolean": (bool,),
+}
+
+
+def _type_matches(instance: Any, json_type: str) -> bool:
+ if json_type == "null":
+ return instance is None
+ if json_type == "integer":
+ return isinstance(instance, int) and not isinstance(instance, bool)
+ if json_type == "number":
+ return isinstance(instance, (int, float)) and not isinstance(instance, bool)
+ if json_type == "boolean":
+ return isinstance(instance, bool)
+ expected = _TYPE_CHECKS.get(json_type)
+ if expected is None or (json_type == "object" and isinstance(instance, bool)):
+ return True # unknown keyword value — not this validator's call
+ return isinstance(instance, expected)
+
+
+def _validate_node(instance: Any, schema: dict[str, Any], path: str, errors: list[str]) -> None:
+ """Recursive subset validator: type/const/enum/required/properties/items/
+ additionalProperties(bool). Unknown keywords are ignored — the skeleton
+ stays inside this subset so the hand-rolled pass is faithful."""
+ if not isinstance(schema, dict):
+ return
+ json_type = schema.get("type")
+ if isinstance(json_type, str) and not _type_matches(instance, json_type):
+ errors.append(f"{path}: expected type {json_type!r}, got {type(instance).__name__}")
+ return
+ if "const" in schema and instance != schema["const"]:
+ errors.append(f"{path}: expected const {schema['const']!r}, got {instance!r}")
+ if "enum" in schema and instance not in schema["enum"]:
+ errors.append(f"{path}: value {instance!r} not in enum {schema['enum']}")
+ if isinstance(instance, dict):
+ for key in schema.get("required", ()):
+ if key not in instance:
+ errors.append(f"{path}: missing required property {key!r}")
+ properties = schema.get("properties", {})
+ for key, sub_schema in properties.items():
+ if key in instance:
+ _validate_node(instance[key], sub_schema, f"{path}.{key}", errors)
+ if schema.get("additionalProperties") is False and properties:
+ unknown = sorted(set(instance) - set(properties))
+ for key in unknown:
+ errors.append(f"{path}: additional property {key!r} is not allowed")
+ if isinstance(instance, (list, tuple)):
+ items_schema = schema.get("items")
+ if isinstance(items_schema, dict):
+ for i, item in enumerate(instance):
+ _validate_node(item, items_schema, f"{path}[{i}]", errors)
+
+
+def validate_payload(payload: Any, schema: dict[str, Any]) -> list[str]:
+ """Validate ``payload`` against a contract schema; return error strings.
+
+ Empty list = valid. Deterministic order: schema-declared order for
+ required/properties, index order for arrays.
+ """
+ errors: list[str] = []
+ _validate_node(payload, schema, "$", errors)
+ return errors
diff --git a/agent/src/tools/paper_trade/state_hash.py b/agent/src/tools/paper_trade/state_hash.py
new file mode 100644
index 000000000..22c68f7ef
--- /dev/null
+++ b/agent/src/tools/paper_trade/state_hash.py
@@ -0,0 +1,192 @@
+"""JCS canonicalization + state-integrity hashing for ``paper_trade_step``.
+
+Implements R7 / AM-4 of the pt-v1.1 contract (``received_state_hash`` and the
+``effective_fee_model`` echo). Per VD-4 the canonical form is hand-rolled —
+zero new runtime dependencies — and the frozen test vectors in
+``agent/tests/fixtures/paper_trade/jcs_vectors.json`` are the SOLE
+interpretation authority (AM-4-2): both the VT engine and the RM observer
+assert their own implementations against the same vectors.
+
+Canonicalization rules (RFC 8785 JCS as frozen by VD-4):
+
+* Object keys are sorted by Unicode code point — the semantics of
+ ``json.dumps(sort_keys=True)``. RFC 8785 itself sorts by UTF-16 code
+ unit; the two orders agree for BMP-only keys, which is all the frozen
+ vectors and the wire contract use.
+* Numbers use the ECMAScript shortest round-trip representation, so
+ ``100000.0`` and ``100000`` canonicalize identically (``100000``),
+ ``-0.0`` canonicalizes as ``0``, and the exponential thresholds match
+ ``JSON.stringify`` (``1e21`` -> ``1e+21`` but ``1e16`` ->
+ ``10000000000000000``). Integers are serialized exactly (Python
+ semantics); the frozen vectors stay within +/-2^53 where every
+ double-based implementation agrees.
+* Strings are escaped by ``json.dumps(..., ensure_ascii=False)`` — raw
+ UTF-8 for non-ASCII, ``\\uXXXX`` (lowercase hex) for control characters,
+ matching ``JSON.stringify`` for BMP text.
+* Arrays keep their order: element order is semantic (positions ordered by
+ the RM ledger) and is never sorted or shuffled.
+
+Determinism: this module reads no clock, no environment, no network and
+writes nothing — the same input always produces the same bytes.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from decimal import Decimal
+from typing import Any
+
+__all__ = [
+ "canonicalize",
+ "compute_received_state_hash",
+ "effective_fee_model",
+ "state_hash",
+]
+
+# FROZEN terminal defaults (G1: RM written approval 2026-10-19; APPROVAL note 5
+# + REQUIREMENTS §4 fee matrix). Key names are the pt-v1.1 final set — cn_a
+# verbatim from the AMENDMENT §2.2 out-param example, hk/us mapped item-by-item
+# to the §4 matrix; they are registered in the delivery note (#7) so the RM
+# dispatch injection (AM-4-3: fee_model is always injected explicitly) aligns.
+# Any key/value change = major schema bump with RM written confirmation
+# (REQUIREMENTS §9). VD-9 numeric choices registered in the delivery note:
+# hk stamp duty quantizes to whole HKD ROUND_HALF_UP (HKEX itself ceils) and
+# the us SEC fee is simplified to 0.
+_DEFAULT_FEE_MODELS: dict[str, dict[str, float]] = {
+ "cn_a": {
+ "commission_rate": 0.00025, # 万2.5 bilateral
+ "commission_min": 5.0, # ¥5 minimum per order
+ "stamp_tax_sell": 0.0005, # 万5 sell-side only
+ "transfer_fee": 0.00001, # 万0.1 bilateral
+ },
+ "hk": {
+ "commission_rate": 0.0003, # 0.03%
+ "commission_min": 3.0, # HK$3 minimum
+ "stamp_tax_rate": 0.001, # 0.1% per side, whole HKD ROUND_HALF_UP (VD-9)
+ "regulatory_levy_rate": 0.00003, # ≈0.003% combined levies
+ },
+ "us": {
+ "commission_per_share": 0.0049, # $0.0049/share
+ "commission_min": 0.99, # $0.99 minimum
+ "sec_fee_rate": 0.0, # simplified to zero (§4, VD-9 registered)
+ },
+}
+
+#: Markets whose fee defaults are known. Mirrors the pt-v1.1 ``market`` enum.
+FEE_MODEL_MARKETS: tuple[str, ...] = ("cn_a", "hk", "us")
+
+
+def _ecmascript_number(value: Decimal) -> str:
+ """Serialize a finite Decimal per ECMAScript ``Number::toString``.
+
+ This is the number form RFC 8785 mandates: the shortest digit string that
+ round-trips, rendered by the ECMA-262 §7.1.12.1 branch rules (plain
+ integer/decimal forms inside their thresholds, ``e±X`` outside).
+ """
+ if value == 0:
+ # Covers -0.0 too: JCS/ECMAScript render negative zero as "0".
+ return "0"
+ sign, digits, exponent = value.normalize().as_tuple()
+ # normalize() strips trailing zeros; guard the "0E+2" style residue.
+ digits = tuple(int(d) for d in digits)
+ k = len(digits)
+ n = exponent + k # value = m * 10^(n-k), m has k digits
+ prefix = "-" if sign else ""
+ body = "".join(str(d) for d in digits)
+ if k <= n <= 21:
+ return prefix + body + "0" * (n - k)
+ if 0 < n <= 21:
+ return prefix + body[:n] + "." + body[n:]
+ if -6 < n <= 0:
+ return prefix + "0." + "0" * (-n) + body
+ exp = n - 1
+ exp_part = f"e{'+' if exp >= 0 else '-'}{abs(exp)}"
+ if k == 1:
+ return prefix + body + exp_part
+ return prefix + body[0] + "." + body[1:] + exp_part
+
+
+def _serialize_number(value: int | float) -> str:
+ """Canonical number token for an int or float (bools never reach here)."""
+ if isinstance(value, float):
+ if not math.isfinite(value):
+ raise ValueError(f"non-finite float is not JSON-serializable: {value!r}")
+ # repr() is the shortest round-trip decimal for IEEE-754 doubles.
+ return _ecmascript_number(Decimal(repr(value)))
+ return _ecmascript_number(Decimal(value))
+
+
+def canonicalize(value: Any) -> str:
+ """Return the JCS canonical form of a JSON-native value.
+
+ Accepts exactly the JSON type lattice: ``None``, ``bool``, ``int``,
+ ``float``, ``str``, ``list``, ``dict`` (str keys only). Anything else —
+ ``Decimal``, ``datetime``, custom objects — raises ``TypeError``: the
+ hashed surface is the JSON-parsed tool input, and a silently coerced
+ non-JSON type would make the hash implementation-defined.
+ """
+ # bool before int: bool is an int subclass and must serialize as a token.
+ if value is None:
+ return "null"
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, (int, float)):
+ return _serialize_number(value)
+ if isinstance(value, str):
+ return json.dumps(value, ensure_ascii=False)
+ if isinstance(value, (list, tuple)):
+ return "[" + ",".join(canonicalize(item) for item in value) + "]"
+ if isinstance(value, dict):
+ items = []
+ for key in sorted(value):
+ if not isinstance(key, str):
+ raise TypeError(f"JCS object keys must be str, got {type(key).__name__}")
+ items.append(f"{json.dumps(key, ensure_ascii=False)}:{canonicalize(value[key])}")
+ return "{" + ",".join(items) + "}"
+ raise TypeError(f"value of type {type(value).__name__} is not JSON-native")
+
+
+def state_hash(value: Any) -> str:
+ """Return ``sha256(JCS(value))`` as lowercase hex (AM-4-1)."""
+ return hashlib.sha256(canonicalize(value).encode("utf-8")).hexdigest()
+
+
+def compute_received_state_hash(
+ *,
+ account_id: str,
+ market: str,
+ account_state: Any,
+ fee_model: Any,
+ from_date: str,
+ to_date: str,
+) -> str:
+ """Hash the frozen AM-4-1 coverage object (non-order tool inputs).
+
+ ``fee_model`` must be the EFFECTIVE value (see :func:`effective_fee_model`)
+ — AM-4-3: the RM dispatch always injects fee_model explicitly, so the hash
+ covers every non-order parameter.
+ """
+ coverage = {
+ "account_id": account_id,
+ "market": market,
+ "account_state": account_state,
+ "fee_model": fee_model,
+ "from_date": from_date,
+ "to_date": to_date,
+ }
+ return state_hash(coverage)
+
+
+def effective_fee_model(market: str, fee_model: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Return the fee parameters actually in effect for this run (R7-3 echo).
+
+ Per-key merge of the caller-provided overrides over the market defaults:
+ REQUIREMENTS §2.1 defines ``fee_model`` as "key = fee item name, value =
+ rate/minimum" overrides. Unknown markets fail closed — there is no
+ silent default fee schedule.
+ """
+ if market not in _DEFAULT_FEE_MODELS:
+ raise ValueError(f"unknown market for fee model: {market!r}")
+ return {**_DEFAULT_FEE_MODELS[market], **(fee_model or {})}
diff --git a/agent/src/tools/paper_trade/strategy_exec.py b/agent/src/tools/paper_trade/strategy_exec.py
new file mode 100644
index 000000000..3403d96ed
--- /dev/null
+++ b/agent/src/tools/paper_trade/strategy_exec.py
@@ -0,0 +1,558 @@
+"""pt-v1.1 ``strategy_path`` execution for ``paper_trade_step`` (Step 7 / T7).
+
+Deterministic strategy replay (REQUIREMENTS R2 / AM-8): the strategy file is
+resolved once, AST-validated by the EXISTING backtest sandbox
+(``backtest.runner._validate_signal_engine_source`` — import whitelist +
+runtime-reachable scrubber, E10), then loaded and executed **in a spawned
+child process**, never in the MCP server process. No raw import: the child
+``compile``/``exec``s the single source read the parent validated (no second
+I/O ⇒ no TOCTOU between validation and execution); a rejected source never
+runs. The child is killed with SIGKILL on a per-day timeout, so a hung day
+is really interrupted (busy loops and blocked sleeps alike), not abandoned.
+
+Strategy contract (R2 "concrete shape is VT's call", VD-8 minimal ctx)::
+
+ class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ return [{"symbol": ..., "side": "buy" | "sell", "qty": ...,
+ "limit": ... | None, "reason": ... | None}, ...]
+
+The class MUST be named ``SignalEngine``: that is the entry the runner's
+runtime-reachable scrubber scans (its methods + transitively called module
+helpers), so reusing the name reuses the hardened deep pass verbatim — no
+second, weaker scanner. ``ctx`` (:class:`StrategyContext`) exposes exactly
+the read-only ledger after preceding days' fills, ``symbols``, and
+``history(symbol)`` containing only bars strictly before the execution date.
+Orders fill at the execution day's close. The parent advances a private
+ledger between calls; failure discards the entire result.
+
+Optional universe declaration: a strategy file MAY declare a module-level
+literal ``UNIVERSE = ("SYM-A", "SYM-B")`` (a list/tuple of non-empty
+strings). :func:`strategy_universe` extracts it under the SAME path policy
+via a pure AST literal read — the file is never executed or imported on that
+path, so no top-level side effect can fire — and the T6 tool unions the
+declared symbols into the market-data fetch universe (a cash-only account
+carries no position symbols and strategy_path mode has no orders, so without
+the declaration the served universe would be empty). Any convention
+violation — absent, non-literal, non-list/tuple, a non-string or empty-string
+entry, an unreadable or syntactically invalid source, a path-policy rejection
+— degrades to an empty declaration: the served universe (positions ∪ fetched
+symbols) is the fallback, and a genuinely unusable universe stays owned by
+the B1 whole-call failure semantics below.
+
+B1 frozen failure semantics (VD-8): every strategy-side failure — path
+policy, source syntax, validator rejection, load/discovery, a malformed
+order list, a per-day exception, a per-day timeout, a child crash — returns
+the WHOLE call as in-band ``INVALID_REQUEST`` material with the frozen
+message ``strategy_execution_timeout:{YYYY-MM-DD}`` or
+``strategy_execution_error:{YYYY-MM-DD}:{ExceptionClassName}`` and empty
+fills/rejected/nav/skipped; a day-k failure never returns days 1..k-1.
+Pre-execution failures anchor the date at the first matching day (the
+range's ``from_date`` when the range holds none); the AM-9 readiness gate
+runs BEFORE validation/execution so a retryable data fact is never masked
+by a non-retryable strategy failure. Rejection details go to the module
+logger — the wire message is the frozen string, verbatim.
+
+Determinism (R2): same strategy file + same ledger state + same trading day
+= same orders. No clock, no randomness, no network in the ctx; every input
+is injected; each call spawns a fresh child (no cross-call state).
+
+Path policy: the file must resolve (symlinks followed) INSIDE
+``<runtime_root>/strategies`` (``VIBE_TRADING_HOME`` or ``~/.vibe-trading``),
+end in ``.py``, be an existing regular file under the 1 MB cap, and read as
+UTF-8 — rejections happen before any read/execute where possible, and syntax
+errors never echo source text (the target may be a non-strategy file).
+"""
+
+from __future__ import annotations
+
+import ast
+import logging
+import math
+import multiprocessing
+import sys
+import types
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Collection, Mapping
+
+import pandas as pd
+
+from . import calendar, data, schema, wire
+from .engine import (
+ EngineError, MatchOutcome, build_day_plan, error_outcome, readiness_error, run_day_loop)
+from .limits_cn_a import CnALimitsClient
+from .schema import AccountState, Order, PaperTradeStepRequest
+
+__all__ = [
+ "DEFAULT_DAY_TIMEOUT_SECONDS", "StrategyContext", "StrategyContractError", "StrategyOrder",
+ "StrategyOrderError", "StrategyPathError", "StrategyProcessError", "run_strategy_path",
+ "strategy_universe",
+]
+
+logger = logging.getLogger(__name__)
+
+#: Per-day execution budget when the caller passes no ``timeout_seconds``.
+DEFAULT_DAY_TIMEOUT_SECONDS = 30.0
+# Child startup (spawn + package imports + strategy load + entry discovery)
+# gets its own grace so a slow environment never reads as a day-1 timeout.
+_STARTUP_TIMEOUT_SECONDS = 120.0
+_JOIN_TIMEOUT_SECONDS = 10.0
+_MAX_STRATEGY_BYTES = 1_000_000
+_STRATEGIES_DIRNAME = "strategies"
+_STRATEGY_MODULE_NAME = "paper_trade_strategy"
+_OHLCV_COLUMNS = ("open", "high", "low", "close", "volume")
+_UNIVERSE_NAME = "UNIVERSE"
+
+
+class StrategyPathError(ValueError):
+ """strategy_path violated the path policy, or the source is not valid Python."""
+
+
+class StrategyContractError(ValueError):
+ """The loaded module does not expose the paper-trade strategy contract."""
+
+
+class StrategyOrderError(ValueError):
+ """generate_signals returned a malformed order list."""
+
+
+class StrategyProcessError(RuntimeError):
+ """The execution child died or broke the protocol (a crash, not a strategy exception)."""
+
+
+@dataclass(frozen=True, slots=True)
+class StrategyOrder(Order):
+ # Order + the strategy's reason text (VD-15/B2). The engine truncates via
+ # wire.strategy_fill_reason at the fill boundary; plain orders-mode Orders
+ # lack the attribute and keep "".
+ reason: str = ""
+
+
+@dataclass(frozen=True, eq=False)
+class StrategyContext:
+ """Read-only current ledger and prior completed bars for close execution.
+
+ History is copied and excludes the execution day. The child receives no
+ current or future bars, including through the private frame mapping.
+ """
+
+ account_state: AccountState
+ trade_date: str
+ symbols: tuple[str, ...]
+ _frames: Mapping[str, pd.DataFrame] = field(repr=False)
+
+ def history(self, symbol: str) -> pd.DataFrame:
+ frame = self._frames.get(symbol)
+ if frame is None or frame.empty:
+ return _empty_history()
+ return frame.loc[frame.index < pd.Timestamp(self.trade_date)].copy()
+
+ def sma(self, close: pd.Series, period: int) -> float | None:
+ from src.tools.technical_indicator_tool import _compute_sma
+ return _compute_sma(close, period)
+
+ def ema(self, close: pd.Series, period: int) -> float | None:
+ from src.tools.technical_indicator_tool import _compute_ema
+ return _compute_ema(close, period)
+
+ def rsi(self, close: pd.Series, period: int | None = None) -> float | None:
+ from src.tools.technical_indicator_tool import _compute_rsi
+ return _compute_rsi(close) if period is None else _compute_rsi(close, period)
+
+ def macd(self, close: pd.Series) -> dict[str, float | None] | None:
+ from src.tools.technical_indicator_tool import _compute_macd
+ return _compute_macd(close)
+
+ def bollinger(self, close: pd.Series) -> dict[str, float | None] | None:
+ from src.tools.technical_indicator_tool import _compute_bollinger
+ return _compute_bollinger(close)
+
+
+def _empty_history() -> pd.DataFrame:
+ # Fresh frame per call (never a shared mutable constant), canonical shape
+ # mirroring data._empty_frame.
+ columns = {column: pd.Series(dtype="float64") for column in _OHLCV_COLUMNS}
+ return pd.DataFrame(columns, index=pd.DatetimeIndex([], name="trade_date"))
+
+
+class _SourceView:
+ # Duck-typed Path view handing the runner validator THE SINGLE READ the
+ # parent performed: no second I/O ⇒ no TOCTOU between validation and the
+ # source the child executes. _validate_signal_engine_source only calls
+ # .read_text(encoding=...) and str(); a future validator using more Path
+ # surface fails loud (AttributeError), never open.
+ def __init__(self, path: Path, source: str) -> None:
+ self._path = path
+ self._source = source
+
+ def read_text(self, encoding: str = "utf-8") -> str:
+ return self._source
+
+ def __str__(self) -> str:
+ return str(self._path)
+
+ def __fspath__(self) -> str:
+ return str(self._path)
+
+
+def _resolve_strategy_source(strategy_path: str) -> tuple[Path, str]:
+ # Path policy BEFORE any read (lazy imports: parent-only path, keeps the
+ # spawned child's module import off the config/tool chain until needed).
+ from src.config.paths import get_runtime_root
+ from src.tools.path_utils import safe_path
+
+ if not strategy_path.strip():
+ raise StrategyPathError("strategy_path must be a non-empty path")
+ root = get_runtime_root() / _STRATEGIES_DIRNAME
+ try:
+ resolved = safe_path(strategy_path, root)
+ except ValueError as exc:
+ raise StrategyPathError(
+ f"strategy_path {strategy_path!r} is outside the strategies root {root}: {exc}"
+ ) from exc
+ if resolved.suffix != ".py":
+ raise StrategyPathError(f"strategy_path must be a .py file, got {resolved.name!r}")
+ if not resolved.is_file():
+ raise StrategyPathError(f"strategy_path {strategy_path!r} is not an existing regular file")
+ size = resolved.stat().st_size
+ if size > _MAX_STRATEGY_BYTES:
+ raise StrategyPathError(
+ f"strategy file exceeds the {_MAX_STRATEGY_BYTES}-byte cap ({size} bytes)")
+ try:
+ source = resolved.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError) as exc:
+ raise StrategyPathError(
+ f"strategy file is not readable UTF-8 text ({type(exc).__name__})") from exc
+ return resolved, source
+
+
+def _declared_universe(source: str) -> tuple[str, ...]:
+ # The optional module-level ``UNIVERSE`` literal, sorted and deduped.
+ # PURE AST read (ast.parse + ast.literal_eval): the source is never
+ # executed or imported here, so a top-level side effect cannot fire on
+ # this path. Only a literal list/tuple of non-empty strings is a
+ # declaration; every other shape (absent, computed/non-literal, bare
+ # string, dict/set, a non-string or empty-string entry, invalid syntax)
+ # degrades to () — the served universe is the fallback (module docstring).
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
+ return ()
+ value_node: ast.expr | None = None
+ for statement in tree.body: # module level only; last binding wins (Python semantics)
+ if isinstance(statement, ast.Assign) and any(
+ isinstance(target, ast.Name) and target.id == _UNIVERSE_NAME
+ for target in statement.targets
+ ):
+ value_node = statement.value
+ elif (
+ isinstance(statement, ast.AnnAssign)
+ and statement.value is not None
+ and isinstance(statement.target, ast.Name)
+ and statement.target.id == _UNIVERSE_NAME
+ ):
+ value_node = statement.value
+ if value_node is None:
+ return ()
+ try:
+ value = ast.literal_eval(value_node)
+ except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
+ return () # non-literal declaration (a call, an expression, a name)
+ if not isinstance(value, (list, tuple)):
+ return ()
+ if not all(isinstance(item, str) and item for item in value):
+ return ()
+ return tuple(sorted(set(value)))
+
+
+def strategy_universe(strategy_path: str) -> tuple[str, ...]:
+ """The strategy file's declared ``UNIVERSE`` literal, sorted and deduped.
+
+ Reads the source under the SAME path policy as execution
+ (:func:`_resolve_strategy_source` — strategies-root containment, ``.py``
+ suffix, regular file, size cap, UTF-8) and extracts ONLY the module-level
+ literal via :func:`_declared_universe`; the strategy is never executed or
+ imported here. Every rejection — path policy, unreadable file, invalid
+ syntax, a convention-violating declaration — degrades to ``()`` so the
+ caller falls back to the served universe; this helper never raises for a
+ bad strategy and never weakens the execution-time validation (which runs
+ unchanged in :func:`run_strategy_path`).
+ """
+ try:
+ _path, source = _resolve_strategy_source(strategy_path)
+ except (StrategyPathError, OSError):
+ return ()
+ return _declared_universe(source)
+
+
+def _validate_source(path: Path, source: str) -> None:
+ # Reuse the existing hardened validator verbatim (AM-8 / E10 anchor:
+ # backtest/runner.py _validate_signal_engine_source — structural
+ # import-time pass + runtime-reachable scrubber keyed on SignalEngine).
+ from backtest.runner import _validate_signal_engine_source
+
+ try:
+ ast.parse(source, filename=str(path))
+ except SyntaxError as exc:
+ # Sanitized: never echo source text into the wire message — the target
+ # may be a non-strategy file whose contents must not leak.
+ raise StrategyPathError(
+ f"strategy source is not valid Python (line {exc.lineno}, column {exc.offset})"
+ ) from None
+ _validate_signal_engine_source(_SourceView(path, source))
+
+
+def _load_validated_source(source: str, filename: str) -> types.ModuleType:
+ # Child-side load of the ALREADY-VALIDATED source text: compile+exec into
+ # a fresh module — no raw import machinery on an untrusted path (AM-8).
+ module = types.ModuleType(_STRATEGY_MODULE_NAME)
+ module.__file__ = filename
+ sys.modules[_STRATEGY_MODULE_NAME] = module
+ try:
+ exec(compile(source, filename, "exec"), module.__dict__)
+ except BaseException:
+ sys.modules.pop(_STRATEGY_MODULE_NAME, None)
+ raise
+ return module
+
+
+def _discover_entry(module: types.ModuleType):
+ engine_cls = getattr(module, "SignalEngine", None)
+ if not isinstance(engine_cls, type):
+ raise StrategyContractError(
+ "strategy module must define a SignalEngine class "
+ "(contract: generate_signals(self, ctx, trade_date))")
+ generate = getattr(engine_cls, "generate_signals", None)
+ if not callable(generate):
+ raise StrategyContractError(
+ "SignalEngine must define a callable generate_signals(self, ctx, trade_date)")
+ return engine_cls().generate_signals
+
+
+def _convert_order(item: Any, day: str, index: int) -> dict[str, Any]:
+ if not isinstance(item, dict):
+ raise StrategyOrderError(
+ f"orders[{index}] on {day} must be an object, got {type(item).__name__}")
+ try:
+ # Same boundary parser as the tool input (schema.parse_request) — one
+ # order-shape enforcement, not a second weaker one.
+ order = schema._parse_order(item, f"strategy orders[{index}] ({day})")
+ except schema.PaperTradeSchemaError as exc:
+ raise StrategyOrderError(str(exc)) from exc
+ reason = item.get("reason")
+ if reason is not None and not isinstance(reason, str):
+ raise StrategyOrderError(
+ f"orders[{index}].reason on {day} must be a string or null, "
+ f"got {type(reason).__name__}")
+ # Truncate in the child (bounded pipe payloads) AND at the engine's fill
+ # boundary (single Fill.reason enforcement); strategy_fill_reason is
+ # idempotent, so the double pass is safe.
+ return {"symbol": order.symbol, "side": order.side, "qty": order.qty,
+ "limit": order.limit, "reason": wire.strategy_fill_reason(reason)}
+
+
+def _child_main(conn: Any, payload: dict[str, Any]) -> None:
+ # Runs in the spawned child: the strategy's top-level code and every
+ # generate_signals call execute HERE, never in the MCP server process
+ # (AM-8). Protocol: ("ready",) → ("day", day, orders)* → ("done",);
+ # any Exception → ("error", day, class name) and exit. KeyboardInterrupt
+ # /SystemExit deliberately propagate (operator signals, not strategy
+ # errors) — the parent reads the dead pipe as StrategyProcessError.
+ days = payload["days"]
+ try:
+ module = _load_validated_source(payload["source"], payload["filename"])
+ generate = _discover_entry(module)
+ except Exception as exc:
+ conn.send(("error", days[0], type(exc).__name__))
+ return
+ conn.send(("ready",))
+ for day in days:
+ try:
+ state, frames = conn.recv()
+ ctx = StrategyContext(account_state=state, trade_date=day,
+ symbols=payload["symbols"], _frames=frames)
+ raw = generate(ctx, day)
+ if not isinstance(raw, (list, tuple)):
+ raise StrategyOrderError(
+ f"generate_signals must return a list of order objects on {day}, "
+ f"got {type(raw).__name__}")
+ orders = [_convert_order(item, day, index) for index, item in enumerate(raw)]
+ except Exception as exc:
+ conn.send(("error", day, type(exc).__name__))
+ return
+ conn.send(("day", day, orders))
+ conn.send(("done",))
+
+
+_TIMEOUT = object()
+_EOF = object()
+
+
+def _recv(conn: Any, budget: float) -> Any:
+ if not conn.poll(budget):
+ return _TIMEOUT
+ try:
+ return conn.recv()
+ except Exception:
+ # EOFError/OSError/unpickling: a dead or corrupt child is a crash.
+ return _EOF
+
+
+class _StrategyDayFailure(RuntimeError):
+ # Internal carrier from _execute_days to run_strategy_path;
+ # class_name None ⇒ the per-day budget expired (timeout).
+ def __init__(self, day: str, class_name: str | None) -> None:
+ super().__init__(f"strategy execution failed on {day}")
+ self.day = day
+ self.class_name = class_name
+
+
+def _execute_days(
+ request: PaperTradeStepRequest,
+ market_data: data.MarketDataResult,
+ days: tuple[str, ...],
+ path: Path,
+ source: str,
+ day_timeout: float,
+ ctx_symbols: tuple[str, ...],
+ run_loop: Any,
+) -> MatchOutcome:
+ payload = {
+ "source": source,
+ "filename": str(path),
+ "days": days,
+ "symbols": ctx_symbols,
+ }
+ # spawn (never fork): forking a threaded MCP server is POSIX-undefined
+ # behavior (#1355 lesson); spawn is the only start method on Windows and
+ # the default on macOS, pinned here so Linux behaves identically.
+ context = multiprocessing.get_context("spawn")
+ parent_conn, child_conn = context.Pipe(duplex=True)
+ proc = context.Process(target=_child_main, args=(child_conn, payload), daemon=True)
+ started = False
+ try:
+ proc.start()
+ started = True
+ # Close the parent's duplicate child endpoint so child death reads as EOF.
+ child_conn.close()
+ msg = _recv(parent_conn, max(_STARTUP_TIMEOUT_SECONDS, day_timeout))
+ if msg is _TIMEOUT:
+ raise _StrategyDayFailure(days[0], None)
+ if msg is not _EOF and msg[0] == "error":
+ raise _StrategyDayFailure(msg[1], msg[2])
+ if msg is _EOF or msg[0] != "ready":
+ raise _StrategyDayFailure(days[0], StrategyProcessError.__name__)
+ def provide_orders(day: str, state: AccountState) -> tuple[StrategyOrder, ...]:
+ frames = {symbol: item.frame.loc[item.frame.index < pd.Timestamp(day)].copy()
+ for symbol, item in market_data.data.items()}
+ try:
+ parent_conn.send((state, frames))
+ except (BrokenPipeError, EOFError, OSError) as exc:
+ raise _StrategyDayFailure(day, StrategyProcessError.__name__) from exc
+ msg = _recv(parent_conn, day_timeout)
+ if msg is _TIMEOUT:
+ raise _StrategyDayFailure(day, None)
+ if msg is _EOF:
+ raise _StrategyDayFailure(day, StrategyProcessError.__name__)
+ if msg[0] == "error":
+ raise _StrategyDayFailure(msg[1], msg[2])
+ if msg[0] != "day" or msg[1] != day:
+ raise _StrategyDayFailure(day, StrategyProcessError.__name__)
+ return tuple(StrategyOrder(**item) for item in msg[2])
+ return run_loop(order_provider=provide_orders)
+ finally:
+ if started:
+ if proc.is_alive():
+ proc.kill() # SIGKILL: really interrupts a hung day (no cooperative unwind)
+ proc.join(_JOIN_TIMEOUT_SECONDS)
+ proc.close()
+ parent_conn.close()
+ child_conn.close()
+
+
+def _resolve_timeout(timeout_seconds: float | None) -> float:
+ if timeout_seconds is None:
+ return DEFAULT_DAY_TIMEOUT_SECONDS
+ if isinstance(timeout_seconds, bool) or not isinstance(timeout_seconds, (int, float)):
+ raise ValueError(
+ f"timeout_seconds must be a finite positive number, got {timeout_seconds!r}")
+ value = float(timeout_seconds)
+ if not math.isfinite(value) or value <= 0:
+ raise ValueError(
+ f"timeout_seconds must be a finite positive number, got {timeout_seconds!r}")
+ return value
+
+
+def _strategy_error(request: PaperTradeStepRequest,
+ market_data: data.MarketDataResult, message: str) -> MatchOutcome:
+ # B1: the WHOLE call fails in-band — untouched input state, empty arrays.
+ return error_outcome(EngineError("INVALID_REQUEST", message),
+ request.account_state, market_data, request.market, request.fee_model)
+
+
+def run_strategy_path(
+ *,
+ request: PaperTradeStepRequest,
+ market_data: data.MarketDataResult,
+ calendar_client: calendar.TradeCalendarClient | None = None,
+ limits_client: CnALimitsClient | None = None,
+ corporate_action_unresolved_by_day: Mapping[str, Collection[str]] | None = None,
+ hk_lot_sizes: Mapping[str, int] | None = None,
+ timeout_seconds: float | None = None,
+) -> MatchOutcome:
+ """Generate and match each day against a private ledger; publish only success."""
+ if request.strategy_path is None:
+ raise ValueError(
+ "run_strategy_path requires request.strategy_path "
+ "(the orders XOR strategy_path gate is the tool's, Step 6)")
+ if request.orders is not None:
+ raise ValueError(
+ "run_strategy_path is the strategy_path seam; orders must be absent")
+ if market_data.market != request.market:
+ raise ValueError(
+ f"market_data was fetched for {market_data.market!r}, "
+ f"request says {request.market!r}")
+ day_timeout = _resolve_timeout(timeout_seconds)
+ plan = build_day_plan(request.market, request.from_date, request.to_date,
+ market_data, calendar_client)
+ # AM-9 first: a retryable data fact outranks any strategy-side failure.
+ if (error := readiness_error(request.to_date, market_data, plan)) is not None:
+ return error_outcome(error, request.account_state, market_data,
+ request.market, request.fee_model)
+ days = tuple(entry.date for entry in plan if entry.skip_reason is None)
+ anchor = days[0] if days else request.from_date
+ try:
+ path, source = _resolve_strategy_source(request.strategy_path)
+ _validate_source(path, source)
+ except Exception as exc:
+ # StrategyPathError / the validator's ValueError / any parse-adjacent
+ # fault: rejected BEFORE execution — the source never runs.
+ logger.warning("paper_trade strategy rejected before execution (%s): %s",
+ type(exc).__name__, exc)
+ return _strategy_error(request, market_data,
+ f"strategy_execution_error:{anchor}:{type(exc).__name__}")
+ def run_loop(**kwargs: Any) -> MatchOutcome:
+ return run_day_loop(
+ market=request.market, account_state=request.account_state,
+ from_date=request.from_date, to_date=request.to_date, market_data=market_data,
+ orders_by_day={}, fee_model=request.fee_model,
+ calendar_client=calendar_client, limits_client=limits_client,
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day,
+ hk_lot_sizes=hk_lot_sizes, **kwargs)
+ if days:
+ # The declared UNIVERSE joins the child's ctx.symbols (sorted union
+ # with the served universe), extracted from THE SAME single source
+ # read — no second I/O, no TOCTOU. A declared symbol with no served
+ # data reads an empty history: the child never fetches per symbol.
+ ctx_symbols = tuple(sorted(set(market_data.symbols) | set(_declared_universe(source))))
+ try:
+ return _execute_days(
+ request, market_data, days, path, source, day_timeout, ctx_symbols, run_loop)
+ except _StrategyDayFailure as failure:
+ message = (f"strategy_execution_timeout:{failure.day}"
+ if failure.class_name is None
+ else f"strategy_execution_error:{failure.day}:{failure.class_name}")
+ logger.warning("paper_trade strategy failed on %s (%s)", failure.day, message)
+ return _strategy_error(request, market_data, message)
+ return run_loop()
diff --git a/agent/src/tools/paper_trade/tool.py b/agent/src/tools/paper_trade/tool.py
new file mode 100644
index 000000000..4e514ac47
--- /dev/null
+++ b/agent/src/tools/paper_trade/tool.py
@@ -0,0 +1,383 @@
+"""``paper_trade_step`` tool entry (pt-v1.1 Step 6 / T6, VD-12 registration).
+
+The thin orchestration seam between the frozen wire contract and the engine:
+parse the request, supply market data, run one deterministic step, and return
+the single in-band JSON document. It owns the SEMANTIC gates the shape parser
+deliberately does not pre-empt (schema.py): the ``orders`` XOR ``strategy_path``
+mode rule maps a violation to the in-band ``INVALID_REQUEST`` envelope.
+
+Error discipline (AM-5 / VD-7): every input-contract violation and every
+data-not-ready condition returns an in-band envelope on the SAME
+``result.content[0].text`` channel as the success document — never a transport
+error. Transport-level faults stay reserved for engine-internal bugs (not external calendar unavailability, which returns PAPER_DATA_NOT_READY). Messages are deterministic English with no timestamps.
+
+Two registration surfaces share :func:`run_paper_trade_step` as the single
+source of truth (VD-12, the backtest two-layer pattern): the auto-discovered
+:class:`PaperTradeStepTool` (agent registry) and the hand-written
+``@mcp.tool paper_trade_step`` wrapper in ``agent/mcp_server.py``.
+
+Research-only red line (REQUIREMENTS R1): this tool NEVER places a real order
+and never touches a broker / trading connector — it reads market data and the
+injected ledger, matches on paper, and returns the result document.
+
+Determinism (R1-1): no clock, no randomness; every date and every client is
+injected or resolved from env config. ``strategy_path`` execution is T7
+(:mod:`strategy_exec`), imported lazily so this module stays importable while
+T7 is in flight.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from src.agent.tools import BaseTool
+
+from . import data, engine, wire
+from .calendar import CN_A_MARKET, CalendarUnavailableError, snapshot_calendar
+from .data import ClickHouseBarsClient
+from .limits_cn_a import ClickHouseLimitsClient
+from .schema import (
+ DateRange,
+ ErrorEnvelope,
+ PaperTradeSchemaError,
+ parse_request,
+)
+
+logger = logging.getLogger(__name__)
+
+__all__ = ["PaperTradeStepTool", "run_paper_trade_step"]
+
+# Sentinel distinguishing "not injected" (resolve for production) from an
+# explicit None. It MUST be data._AUTO by identity: run_paper_trade_step
+# forwards ``loader``/``ch_client`` straight into data.fetch_market_data, which
+# recognises its own sentinel to trigger production resolution.
+_AUTO = data._AUTO
+
+#: REQUIREMENTS R1 / VD-12 frozen description phrase — both registration
+#: surfaces (BaseTool.description and the MCP wrapper docstring) carry it.
+_DESCRIPTION = (
+ "Run one deterministic paper-trading step for a single account: a "
+ "deterministic paper-trading matching engine; never places real orders. "
+ "Matches the injected orders (or a strategy_path's per-day orders, Step 7) "
+ "against daily bars under the market's frozen rules (T+1, price limits, "
+ "board lots, fees), and returns one in-band JSON document — the success "
+ "result or an AM-5 error envelope (PAPER_DATA_NOT_READY / INVALID_REQUEST) "
+ "on the same channel, never a transport error. Research-only."
+)
+
+
+def _as_str(value: Any) -> str:
+ """Echo a raw payload field as a string, or ``""`` when it is not one.
+
+ The error envelope's ``account_id``/``market``/``range`` come from the raw
+ payload "where possible" (AM-4-4): a malformed ``market`` string is echoed
+ VERBATIM (T5 decision 5 — honest reporting beats self-consistency, so the
+ envelope's own market enum is the single documented degraded case), while a
+ non-string field degrades to ``""`` rather than leaking a non-string onto
+ the wire.
+ """
+ return value if isinstance(value, str) else ""
+
+
+def _error_document(
+ code: str,
+ account_id: str,
+ market: str,
+ from_date: str,
+ to_date: str,
+ message: str,
+ raw_payload: Any,
+) -> str:
+ """Serialize one in-band AM-5 error envelope to its wire JSON text.
+
+ ``received_state_hash`` is computed from the RAW payload (AM-4-1/AM-4-4)
+ and omitted — never null — when the coverage object is not computable.
+ """
+ envelope = ErrorEnvelope(
+ code=code,
+ account_id=account_id,
+ market=market,
+ range=DateRange(from_=from_date, to=to_date),
+ message=message,
+ received_state_hash=wire.received_state_hash_from_payload(raw_payload),
+ )
+ return wire.dumps_payload(wire.build_error_payload(envelope))
+
+
+def _default_cn_a_connector() -> Any | None:
+ """One shared ClickHouse connector for cn_a calendar+limits+bars, or None.
+
+ Probed with an AUTHENTICATED ``SELECT 1`` — never ``health_check()``, which
+ sends no credentials and 403s against a password-protected server even when
+ the configured credentials are valid (issues pit 18, observed live). An
+ unreachable server degrades to None: the bar leg then falls back to the
+ network source. The tool returns PAPER_DATA_NOT_READY when the calendar
+ is unavailable or cannot cover the requested dates.
+ """
+ try:
+ from src.clickhouse_connector import ClickHouseConnector
+
+ connector = ClickHouseConnector() # reads CLICKHOUSE_* env config
+ connector.query("SELECT 1")
+ return connector
+ except Exception as exc: # noqa: BLE001 — unreachable CH degrades, never crashes here
+ logger.debug("paper_trade cn_a ClickHouse connector unavailable: %s", exc)
+ return None
+
+
+def _resolve_clients(
+ market: str, calendar_client: Any, limits_client: Any, ch_client: Any
+) -> tuple[Any, Any, Any]:
+ """Resolve (calendar_client, limits_client, ch_client) for ``market``.
+
+ ``_AUTO`` seams resolve from ONE shared cn_a ClickHouse connector (calendar
+ = the connector itself, which structurally satisfies TradeCalendarClient;
+ limits = ClickHouseLimitsClient; bars = ClickHouseBarsClient). hk/us are
+ the approved AM-6 zero-calendar design: no calendar client, no cn_a limit
+ lookups, no CH bar leg — all None. Injected seams (tests) pass through
+ untouched, so no connector is ever built offline.
+ """
+ if market != CN_A_MARKET:
+ return (
+ None if calendar_client is _AUTO else calendar_client,
+ None if limits_client is _AUTO else limits_client,
+ None if ch_client is _AUTO else ch_client,
+ )
+ connector = None
+ if calendar_client is _AUTO or limits_client is _AUTO or ch_client is _AUTO:
+ connector = _default_cn_a_connector()
+ cal = connector if calendar_client is _AUTO else calendar_client
+ if limits_client is _AUTO:
+ lim = ClickHouseLimitsClient(connector) if connector is not None else None
+ else:
+ lim = limits_client
+ if ch_client is _AUTO:
+ ch = ClickHouseBarsClient(connector) if connector is not None else None
+ else:
+ ch = ch_client
+ return cal, lim, ch
+
+
+def run_paper_trade_step(
+ payload: Any,
+ *,
+ loader: Any = _AUTO,
+ ch_client: Any = _AUTO,
+ calendar_client: Any = _AUTO,
+ limits_client: Any = _AUTO,
+ corporate_action_unresolved_by_day: Any = None,
+ hk_lot_sizes: Any = None,
+ timeout_seconds: float | None = None,
+ _orders_at_end: bool = False,
+) -> str:
+ """Run one paper-trading step and return the single in-band JSON document.
+
+ Flow (T5 wire surface): ``parse_request`` → market data → ``match_orders``
+ (orders mode) or the lazily-imported ``strategy_exec.run_strategy_path``
+ (strategy_path mode, T7) → ``assemble_result`` → ``build_success_payload``
+ → ``dumps_payload``. A ``PaperTradeSchemaError`` or a semantic-gate
+ violation returns an in-band ``INVALID_REQUEST`` envelope; a
+ ``MatchOutcome.error`` returns its own in-band envelope (e.g.
+ ``PAPER_DATA_NOT_READY``). Injection seams (``loader``/``ch_client``/
+ ``calendar_client``/``limits_client``/…) default to ``_AUTO`` production
+ resolution; tests pass fakes so nothing touches the network.
+ """
+ raw_payload = payload if isinstance(payload, dict) else {}
+
+ # 1. Boundary parse (shape contract). A violation is non-retryable input.
+ try:
+ request = parse_request(payload)
+ except PaperTradeSchemaError as exc:
+ return _error_document(
+ "INVALID_REQUEST",
+ _as_str(raw_payload.get("account_id")),
+ _as_str(raw_payload.get("market")), # verbatim even when malformed
+ _as_str(raw_payload.get("from_date")),
+ _as_str(raw_payload.get("to_date")),
+ str(exc),
+ raw_payload,
+ )
+
+ # 2. Semantic gate owned by the tool (schema.py defers it): exactly one of
+ # orders / strategy_path. ``orders=()`` (empty array) is the valid
+ # zero-order pure-valuation path, so the test is `is not None`.
+ has_orders = request.orders is not None
+ has_strategy = request.strategy_path is not None
+ if has_orders == has_strategy:
+ message = (
+ "exactly one of orders or strategy_path must be provided, got both"
+ if has_orders
+ else "exactly one of orders or strategy_path must be provided, got neither"
+ )
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date, message, raw_payload,
+ )
+
+ # 3. Market data over the frozen window (universe = positions ∪ orders;
+ # strategy_path mode ALSO unions the strategy file's declared UNIVERSE
+ # literal — a cash-only account carries no position symbols and there
+ # are no orders, so without the declaration the fetch universe would be
+ # empty. strategy_universe is a pure AST read (never an execution) and
+ # degrades to (); the empty-declaration fallback keeps the existing
+ # behavior and T7's B1 path still owns a genuinely unusable universe.
+ # Orders mode never consults it.)
+ cal, lim, ch = _resolve_clients(request.market, calendar_client, limits_client, ch_client)
+ if request.market == CN_A_MARKET and cal is None:
+ return _error_document(
+ "PAPER_DATA_NOT_READY", request.account_id, request.market,
+ request.from_date, request.to_date,
+ "A-share trading calendar unavailable; configure a reachable ClickHouse trade_calendar and retry",
+ raw_payload)
+ if request.market == CN_A_MARKET:
+ try:
+ cal = snapshot_calendar(cal, request.from_date, request.to_date)
+ except CalendarUnavailableError as exc:
+ return _error_document(
+ "PAPER_DATA_NOT_READY", request.account_id, request.market,
+ request.from_date, request.to_date, str(exc), raw_payload)
+ symbols = data.symbols_for_request(request.account_state, request.orders)
+ if has_strategy:
+ from .strategy_exec import strategy_universe
+
+ declared = strategy_universe(request.strategy_path or "")
+ if declared:
+ symbols = tuple(sorted(set(symbols) | set(declared)))
+ try:
+ market_data = data.fetch_market_data(
+ request.market, symbols, request.from_date, request.to_date,
+ loader=loader, ch_client=ch,
+ )
+ except ValueError as exc:
+ # Data-layer input guards (from_date > to_date, unknown market, a
+ # clickhouse-named loader injection) are contract violations → in-band.
+ return _error_document(
+ "INVALID_REQUEST", request.account_id, request.market,
+ request.from_date, request.to_date, str(exc), raw_payload,
+ )
+
+ # 4. Mode dispatch. strategy_exec is T7 and imported lazily so this module
+ # stays importable (and the agent registry stays buildable) while T7 is
+ # in flight; both modes yield a MatchOutcome handled identically below.
+ if has_strategy:
+ from .strategy_exec import run_strategy_path
+
+ outcome = run_strategy_path(
+ request=request,
+ market_data=market_data,
+ calendar_client=cal,
+ limits_client=lim,
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day,
+ hk_lot_sizes=hk_lot_sizes,
+ timeout_seconds=timeout_seconds,
+ )
+ elif _orders_at_end:
+ # Saved accounts must scan every intervening day, including actions,
+ # while applying explicit orders only at the chosen execution close.
+ outcome = engine.run_day_loop(
+ market=request.market, account_state=request.account_state,
+ from_date=request.from_date, to_date=request.to_date, market_data=market_data,
+ orders_by_day={request.to_date: request.orders or ()}, fee_model=request.fee_model,
+ calendar_client=cal, limits_client=lim, hk_lot_sizes=hk_lot_sizes,
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day)
+ else:
+ outcome = engine.match_orders(
+ request,
+ market_data=market_data,
+ calendar_client=cal,
+ limits_client=lim,
+ corporate_action_unresolved_by_day=corporate_action_unresolved_by_day,
+ hk_lot_sizes=hk_lot_sizes,
+ )
+
+ # 5. In-band error envelope, or the success document. The hash covers the
+ # RAW received account_state (AM-4-1), never the parsed reconstruction.
+ if outcome.error is not None:
+ return _error_document(
+ outcome.error.code, request.account_id, request.market,
+ request.from_date, request.to_date, outcome.error.message, raw_payload,
+ )
+ result = wire.assemble_result(
+ request, outcome, raw_account_state=raw_payload.get("account_state")
+ )
+ return wire.dumps_payload(wire.build_success_payload(result))
+
+
+class PaperTradeStepTool(BaseTool):
+ """Deterministic paper-trading matching engine; never places real orders.
+
+ Read-only research tool (REQUIREMENTS R1): it reads market data and the
+ injected ledger, matches on paper under the frozen market rules, and
+ returns one in-band JSON document. It registers no broker / trading
+ connector path and writes nothing.
+ """
+
+ name = "paper_trade_step"
+ description = _DESCRIPTION
+ parameters = {
+ "type": "object",
+ "properties": {
+ "account_id": {
+ "type": "string",
+ "description": "Account identifier, echoed verbatim (R4).",
+ },
+ "market": {
+ "type": "string",
+ "enum": ["cn_a", "hk", "us"],
+ "description": "Market whose frozen rules govern matching.",
+ },
+ "account_state": {
+ "type": "object",
+ "description": (
+ "RM-injected ledger snapshot {cash, positions:[{symbol, qty, "
+ "avg_cost}]}. Hashed raw for received_state_hash (AM-4-1)."
+ ),
+ "properties": {
+ "cash": {"type": "number"},
+ "positions": {"type": "array", "items": {"type": "object"}},
+ },
+ "required": ["cash"],
+ },
+ "from_date": {
+ "type": "string",
+ "description": "Inclusive range start YYYY-MM-DD (orders mode: == to_date, AM-3).",
+ },
+ "to_date": {
+ "type": "string",
+ "description": "Inclusive range end YYYY-MM-DD (the target trading day).",
+ },
+ "orders": {
+ "type": "array",
+ "description": (
+ "Orders mode: array of {symbol, side, qty, limit?}. XOR with "
+ "strategy_path; an empty array is the pure-valuation path."
+ ),
+ "items": {"type": "object"},
+ },
+ "strategy_path": {
+ "type": "string",
+ "description": (
+ "Strategy mode (Step 7): path to an AST-hardened strategy whose "
+ "per-day orders are matched. XOR with orders."
+ ),
+ },
+ "fee_model": {
+ "type": "object",
+ "description": (
+ "Optional per-key fee overrides merged over the market defaults "
+ "(AM-4-3: RM always injects it explicitly)."
+ ),
+ },
+ },
+ "required": ["account_id", "market", "account_state", "from_date", "to_date"],
+ }
+ repeatable = True
+ is_readonly = True
+ # Not `deterministic`: the result depends on served market data, which
+ # changes between sessions, so identical args must not be served from cache.
+ deterministic = False
+
+ def execute(self, **kwargs: Any) -> str:
+ """Run one step and return the single in-band JSON document string."""
+ return run_paper_trade_step(dict(kwargs))
diff --git a/agent/src/tools/paper_trade/wire.py b/agent/src/tools/paper_trade/wire.py
new file mode 100644
index 000000000..f520cd2c9
--- /dev/null
+++ b/agent/src/tools/paper_trade/wire.py
@@ -0,0 +1,308 @@
+"""pt-v1.1 wire serialization for ``paper_trade_step`` (Step 5 / T5).
+
+The schema-closure surface the Step 6 tool calls: assembles the frozen
+:class:`~.schema.PaperTradeStepResult` / :class:`~.schema.ErrorEnvelope`
+documents from engine outcomes and serializes them into the single JSON
+document that travels on ``result.content[0].text``. Success and error
+share that one in-band channel (AM-5); transport-level MCP errors stay
+reserved for engine-internal faults.
+
+Frozen surfaces implemented here:
+
+* AM-4-1 coverage object — ``received_state_hash`` is computed over the RAW
+ received ``account_state`` JSON value, not the parsed dataclass
+ reconstruction: a key the LLM added or dropped must break the hash exactly
+ like a corrupted number, because RM compares against the hash of the
+ snapshot it injected (R7-5). ``fee_model`` enters the coverage object as
+ the EFFECTIVE value (AM-4-3: RM always injects it explicitly).
+* AM-4-4 — the error envelope carries ``received_state_hash`` only when the
+ coverage object is computable from the raw payload (state parseable,
+ market known, ids/dates present); otherwise the key is OMITTED, never null.
+* VD-15/B2 — ``fills[].reason`` dual mode: orders → ``""``; strategy_path →
+ the strategy reason truncated to <=200 characters without ever splitting a
+ multi-byte character (:func:`strategy_fill_reason`).
+* VD-4 serialization — ``sort_keys`` + compact separators + ``ensure_ascii
+ =False`` + ``allow_nan=False``: byte-deterministic strict JSON, no
+ timestamps anywhere (VD-7), NaN/Infinity refused.
+
+Determinism (R1-1): no clock, no randomness, no I/O — every input injected.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from dataclasses import replace
+from typing import TYPE_CHECKING, Any
+
+from .schema import (
+ ERROR_CODES,
+ MARKETS,
+ DateRange,
+ ErrorEnvelope,
+ PaperTradeSchemaError,
+ PaperTradeStepResult,
+ parse_account_state,
+)
+from .state_hash import compute_received_state_hash, effective_fee_model
+
+if TYPE_CHECKING:
+ from .engine import MatchOutcome
+ from .schema import PaperTradeStepRequest
+
+__all__ = [
+ "FILL_REASON_MAX_CHARS",
+ "ORDERS_FILL_REASON",
+ "assemble_result",
+ "build_error_payload",
+ "build_success_payload",
+ "dumps_payload",
+ "received_state_hash_from_payload",
+ "strategy_fill_reason",
+]
+
+#: VD-15/B2 frozen values: orders mode has no reason source (empty string,
+#: matching the RM DDL ``paper_trades.reason TEXT NOT NULL DEFAULT ''``);
+#: strategy_path mode truncates to 200 characters (code points).
+ORDERS_FILL_REASON = ""
+FILL_REASON_MAX_CHARS = 200
+
+
+def strategy_fill_reason(reason: str | None) -> str:
+ """VD-15/B2 strategy_path mode: truncate to <=200 characters, UTF-8 safe.
+
+ Python strings slice on code points, so a multi-byte character (CJK,
+ emoji) is never split and the result always encodes to well-formed
+ UTF-8. ``None`` (a strategy Order without reason text) → ``""``.
+ """
+ if reason is None:
+ return ORDERS_FILL_REASON
+ if not isinstance(reason, str):
+ raise TypeError(f"fill reason must be a string, got {type(reason).__name__}")
+ return reason[:FILL_REASON_MAX_CHARS]
+
+
+def received_state_hash_from_payload(payload: Any) -> str | None:
+ """AM-4-4: hash the raw coverage fields, or ``None`` when not computable.
+
+ Not computable = the received ``account_state`` fails the shape parse, or
+ the coverage object cannot be extracted (account_id/from_date/to_date not
+ strings, market outside the frozen enum, malformed fee_model). The error
+ envelope then OMITS ``received_state_hash`` — RM reads the absence as
+ "state unparseable" and must not burn its retry chain on a corrupt
+ snapshot. The hash covers the RAW ``account_state`` value (see the module
+ docstring) with the effective fee model merged over the market defaults.
+ """
+ if not isinstance(payload, dict):
+ return None
+ account_id = payload.get("account_id")
+ market = payload.get("market")
+ from_date = payload.get("from_date")
+ to_date = payload.get("to_date")
+ if not all(isinstance(value, str) for value in (account_id, market, from_date, to_date)):
+ return None
+ if market not in MARKETS:
+ return None
+ raw_state = payload.get("account_state")
+ try:
+ parse_account_state(raw_state)
+ except PaperTradeSchemaError:
+ return None
+ # Only a missing or explicit null fee_model defaults to {} — a PRESENT
+ # falsy non-dict ([] / "" / false / 0) is malformed, not absent, and the
+ # coverage object is not computable from it.
+ fee_model_raw = payload.get("fee_model")
+ if fee_model_raw is None:
+ fee_model_raw = {}
+ if not isinstance(fee_model_raw, dict):
+ return None
+ fee_model: dict[str, float] = {}
+ for key, value in fee_model_raw.items():
+ if not isinstance(key, str):
+ return None
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ try:
+ numeric = float(value)
+ except OverflowError:
+ return None # integer literal beyond the double range
+ if not math.isfinite(numeric):
+ return None
+ fee_model[key] = numeric
+ try:
+ return compute_received_state_hash(
+ account_id=account_id,
+ market=market,
+ account_state=raw_state,
+ fee_model=effective_fee_model(market, fee_model),
+ from_date=from_date,
+ to_date=to_date,
+ )
+ except (TypeError, ValueError):
+ # The raw state passed the shape parse but is not JCS-canonicalizable
+ # (non-str keys, non-JSON-native or non-finite values the parser does
+ # not read). AM-4-4: not computable → omit the hash, never raise out
+ # of the error path.
+ return None
+
+
+def assemble_result(
+ request: PaperTradeStepRequest,
+ outcome: MatchOutcome,
+ *,
+ raw_account_state: Any,
+) -> PaperTradeStepResult:
+ """Map a successful engine outcome onto the frozen success document.
+
+ ``raw_account_state`` MUST be the raw JSON value as received (the tool
+ input's ``account_state`` member) — hashing the parsed reconstruction
+ would launder LLM-introduced keys past the RM verification (AM-4-1).
+ The hash and the echo share ``outcome.effective_fee_model`` so the
+ covered fee model and the disclosed fee model cannot diverge.
+ """
+ if outcome.error is not None:
+ raise ValueError(
+ "assemble_result refuses an errored outcome: the in-band error "
+ "envelope (build_error_payload) is the only error channel (AM-5)"
+ )
+ received = compute_received_state_hash(
+ account_id=request.account_id,
+ market=request.market,
+ account_state=raw_account_state,
+ fee_model=outcome.effective_fee_model,
+ from_date=request.from_date,
+ to_date=request.to_date,
+ )
+ return PaperTradeStepResult(
+ account_id=request.account_id,
+ market=request.market,
+ range=DateRange(from_=request.from_date, to=request.to_date),
+ received_state_hash=received,
+ effective_fee_model=dict(outcome.effective_fee_model),
+ fills=outcome.fills,
+ rejected_orders=outcome.rejected_orders,
+ end_state=outcome.end_state,
+ nav_series=outcome.nav_series,
+ skipped_days=outcome.skipped_days,
+ warnings=outcome.warnings,
+ data_provenance=replace(
+ outcome.data_provenance, limit_provenance=tuple(outcome.limit_provenance)
+ ),
+ )
+
+
+def _provenance_payload(result: PaperTradeStepResult) -> dict[str, Any]:
+ prov = result.data_provenance
+ payload: dict[str, Any] = {"source": prov.source}
+ if prov.ch_as_of is not None:
+ payload["ch_as_of"] = prov.ch_as_of
+ if prov.network_as_of is not None:
+ payload["network_as_of"] = prov.network_as_of
+ if prov.bars_as_of is not None:
+ payload["bars_as_of"] = prov.bars_as_of
+ if prov.corporate_actions:
+ payload["corporate_actions"] = [dict(event) for event in prov.corporate_actions]
+ if prov.limit_provenance:
+ payload["limit_provenance"] = list(prov.limit_provenance)
+ return payload
+
+
+def build_success_payload(result: PaperTradeStepResult) -> dict[str, Any]:
+ """Serialize the success document (AMENDMENT §2.2 wire shape).
+
+ ``range.from_`` maps to the wire key ``"from"``; optional provenance
+ fields are omitted (never null) when unset; arrays keep the engine's
+ frozen order (VD-10: day-ascending, then input index).
+ """
+ return {
+ "schema_version": result.schema_version,
+ "tool": result.tool,
+ "account_id": result.account_id,
+ "market": result.market,
+ "range": {"from": result.range.from_, "to": result.range.to},
+ "received_state_hash": result.received_state_hash,
+ "effective_fee_model": dict(result.effective_fee_model),
+ "fills": [
+ {
+ "trade_date": fill.trade_date,
+ "symbol": fill.symbol,
+ "side": fill.side,
+ "qty": fill.qty,
+ "price": fill.price,
+ "fee": fill.fee,
+ "reason": fill.reason,
+ }
+ for fill in result.fills
+ ],
+ "rejected_orders": [
+ {
+ "trade_date": rejected.trade_date,
+ "symbol": rejected.symbol,
+ "side": rejected.side,
+ "qty": rejected.qty,
+ "reason_code": rejected.reason_code,
+ "detail": rejected.detail,
+ }
+ for rejected in result.rejected_orders
+ ],
+ "end_state": {
+ "cash": result.end_state.cash,
+ "positions": [
+ {"symbol": position.symbol, "qty": position.qty, "avg_cost": position.avg_cost}
+ for position in result.end_state.positions
+ ],
+ },
+ "nav_series": [
+ {
+ "date": point.date,
+ "nav": point.nav,
+ "cash": point.cash,
+ "position_value": point.position_value,
+ }
+ for point in result.nav_series
+ ],
+ "skipped_days": [
+ {"date": skipped.date, "reason": skipped.reason} for skipped in result.skipped_days
+ ],
+ "warnings": list(result.warnings),
+ "data_provenance": _provenance_payload(result),
+ }
+
+
+def build_error_payload(envelope: ErrorEnvelope) -> dict[str, Any]:
+ """Serialize the in-band error envelope (AM-5 frozen field set).
+
+ ``code`` outside the frozen 2-value vocabulary is an engine bug, not a
+ data condition — it raises (transport class) instead of shipping an
+ envelope RM cannot route. ``received_state_hash`` is included only when
+ present (AM-4-4); the key is never emitted as null.
+ """
+ if envelope.status != "error":
+ raise ValueError(f"error envelope status must be 'error', got {envelope.status!r}")
+ if envelope.code not in ERROR_CODES:
+ raise ValueError(
+ f"error code {envelope.code!r} is outside the frozen AM-5 vocabulary {ERROR_CODES}"
+ )
+ payload: dict[str, Any] = {
+ "status": envelope.status,
+ "code": envelope.code,
+ "account_id": envelope.account_id,
+ "market": envelope.market,
+ "range": {"from": envelope.range.from_, "to": envelope.range.to},
+ "message": envelope.message,
+ }
+ if envelope.received_state_hash is not None:
+ payload["received_state_hash"] = envelope.received_state_hash
+ return payload
+
+
+def dumps_payload(payload: Any) -> str:
+ """The single in-band JSON document text (VD-4 spelling, strict JSON).
+
+ Sorted keys + compact separators make the bytes deterministic for the
+ T1 goldens; ``ensure_ascii=False`` keeps UTF-8 raw; ``allow_nan=False``
+ refuses NaN/Infinity instead of emitting non-standard tokens.
+ """
+ return json.dumps(
+ payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
+ )
diff --git a/agent/tests/fixtures/paper_trade/golden/MANIFEST.json b/agent/tests/fixtures/paper_trade/golden/MANIFEST.json
new file mode 100644
index 000000000..65adb5a3f
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/golden/MANIFEST.json
@@ -0,0 +1,28 @@
+{
+ "schema": "paper_trade.golden_manifest/v1",
+ "generator": "one-off Step 5 (T5) generation from test_paper_trade_determinism.py scenarios; frozen at commit time",
+ "description": "T1 determinism goldens: exact wire bytes of dumps_payload(build_success_payload(assemble_result(...))) per market scenario. sha256 is of the exact on-disk bytes (single-line strict JSON, sorted keys, compact separators, raw UTF-8, no trailing newline). test_paper_trade_determinism.py regenerates each scenario and asserts byte equality. Frozen at Step 5; regeneration requires the VD-14 discipline (human-verified diff + commit message naming the reason).",
+ "goldens": [
+ {
+ "file": "cn_a_orders_single_day.json",
+ "sha256": "a19ac4342eaf37188567cd9a44e1e0ed67cf7ab5452a20b21a245b85388f1580",
+ "bytes": 919,
+ "market": "cn_a",
+ "scenario": "single-day orders run 2026-10-20: [{\"symbol\": \"600519.SH\", \"side\": \"buy\", \"qty\": 100}], cash 200000.0, fee_model = §4 cn_a defaults"
+ },
+ {
+ "file": "hk_orders_single_day.json",
+ "sha256": "9257ea18f4a25f5f9318f04468c0c0dc61e64e9ec92b6d0c05f553034cd09d0f",
+ "bytes": 898,
+ "market": "hk",
+ "scenario": "single-day orders run 2026-10-16: [{\"symbol\": \"00700.HK\", \"side\": \"buy\", \"qty\": 100}], cash 100000.0, fee_model = §4 hk defaults"
+ },
+ {
+ "file": "us_orders_single_day.json",
+ "sha256": "143896c9ada6bb437e9253fef124133ab3fd8fd74e3a0050af92492c2e8e0ca0",
+ "bytes": 777,
+ "market": "us",
+ "scenario": "single-day orders run 2026-10-16: [{\"symbol\": \"AAPL.US\", \"side\": \"buy\", \"qty\": 10}], cash 50000.0, fee_model = §4 us defaults"
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/paper_trade/golden/cn_a_orders_single_day.json b/agent/tests/fixtures/paper_trade/golden/cn_a_orders_single_day.json
new file mode 100644
index 000000000..e7f4feae7
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/golden/cn_a_orders_single_day.json
@@ -0,0 +1 @@
+{"account_id":"pa_golden_cn_a","data_provenance":{"bars_as_of":"2026-10-20","ch_as_of":"2026-10-19","limit_provenance":["600519.SH@2026-10-20:limits:heuristic"],"network_as_of":"2026-10-20","source":"clickhouse+tencent(merged)"},"effective_fee_model":{"commission_min":5.0,"commission_rate":0.00025,"stamp_tax_sell":0.0005,"transfer_fee":1e-05},"end_state":{"cash":57863.05,"positions":[{"avg_cost":1421.0,"qty":100.0,"symbol":"600519.SH"}]},"fills":[{"fee":36.95,"price":1421.0,"qty":100.0,"reason":"","side":"buy","symbol":"600519.SH","trade_date":"2026-10-20"}],"market":"cn_a","nav_series":[{"cash":57863.05,"date":"2026-10-20","nav":199963.05,"position_value":142100.0}],"range":{"from":"2026-10-20","to":"2026-10-20"},"received_state_hash":"dab1f488b5abd1d0042a0e8cdef80f817e227f4ec0bb14e72c29016e0b21d7a0","rejected_orders":[],"schema_version":"pt-v1.1","skipped_days":[],"tool":"paper_trade_step","warnings":[]}
\ No newline at end of file
diff --git a/agent/tests/fixtures/paper_trade/golden/hk_orders_single_day.json b/agent/tests/fixtures/paper_trade/golden/hk_orders_single_day.json
new file mode 100644
index 000000000..61865ecb4
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/golden/hk_orders_single_day.json
@@ -0,0 +1 @@
+{"account_id":"pa_golden_hk","data_provenance":{"bars_as_of":"2026-10-16","network_as_of":"2026-10-16","source":"tencent"},"effective_fee_model":{"commission_min":3.0,"commission_rate":0.0003,"regulatory_levy_rate":3e-05,"stamp_tax_rate":0.001},"end_state":{"cash":58164.21,"positions":[{"avg_cost":417.8,"qty":100.0,"symbol":"00700.HK"}]},"fills":[{"fee":55.79,"price":417.8,"qty":100.0,"reason":"","side":"buy","symbol":"00700.HK","trade_date":"2026-10-16"}],"market":"hk","nav_series":[{"cash":58164.21,"date":"2026-10-16","nav":99944.21,"position_value":41780.0}],"range":{"from":"2026-10-16","to":"2026-10-16"},"received_state_hash":"0a2e267d7c9f8e37b46016738214409d77452770f4ff689ec717f4965db9ae2a","rejected_orders":[],"schema_version":"pt-v1.1","skipped_days":[],"tool":"paper_trade_step","warnings":["lot assumption: 0700.HK sized on the default 100-share board lot (no lot table entry)"]}
\ No newline at end of file
diff --git a/agent/tests/fixtures/paper_trade/golden/us_orders_single_day.json b/agent/tests/fixtures/paper_trade/golden/us_orders_single_day.json
new file mode 100644
index 000000000..3119fa9fc
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/golden/us_orders_single_day.json
@@ -0,0 +1 @@
+{"account_id":"pa_golden_us","data_provenance":{"bars_as_of":"2026-10-16","network_as_of":"2026-10-16","source":"sina"},"effective_fee_model":{"commission_min":0.99,"commission_per_share":0.0049,"sec_fee_rate":0.0},"end_state":{"cash":46564.41,"positions":[{"avg_cost":343.46,"qty":10.0,"symbol":"AAPL.US"}]},"fills":[{"fee":0.99,"price":343.46,"qty":10.0,"reason":"","side":"buy","symbol":"AAPL.US","trade_date":"2026-10-16"}],"market":"us","nav_series":[{"cash":46564.41,"date":"2026-10-16","nav":49999.01,"position_value":3434.6}],"range":{"from":"2026-10-16","to":"2026-10-16"},"received_state_hash":"64ac7ff9596166cfad3405831d23c9c2523594ccfdce7e1c53051cf8794610d1","rejected_orders":[],"schema_version":"pt-v1.1","skipped_days":[],"tool":"paper_trade_step","warnings":[]}
\ No newline at end of file
diff --git a/agent/tests/fixtures/paper_trade/jcs_vectors.json b/agent/tests/fixtures/paper_trade/jcs_vectors.json
new file mode 100644
index 000000000..58cfca4ab
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/jcs_vectors.json
@@ -0,0 +1,161 @@
+{
+ "$comment": "Frozen JCS interpretation vectors for paper_trade_step received_state_hash (T11, AM-4-2 / VD-4). These vectors are the SOLE cross-repo interpretation authority: VT and RM each assert their own JCS implementation against them. Per VD-14 re-baseline protocol, once RM adopts them they are IMMUTABLE — regenerating them requires explicit human sign-off named in the commit message. Canonical strings below were hand-derived from RFC 8785 / ECMAScript Number::toString rules; sha256 = lowercase hex digest of the UTF-8 canonical string.",
+ "algorithm": {
+ "canonicalization": "RFC 8785 JCS as frozen by VD-4: object keys sorted by Unicode code point (json.dumps sort_keys semantics; identical to UTF-16 code-unit order for the BMP-only keys used here), numbers in ECMAScript shortest round-trip form (100000.0 == 100000 -> 100000; -0.0 -> 0; 1e21 -> 1e+21; 1e16 -> 10000000000000000), strings escaped per json.dumps(ensure_ascii=False), arrays order-sensitive (never sorted).",
+ "hash": "sha256 over the UTF-8 encoding of the canonical string, lowercase hex digest"
+ },
+ "vectors": [
+ {
+ "name": "key_order_shuffle_a",
+ "input": {
+ "market": "cn_a",
+ "account_id": "pa_01",
+ "cash": 1000.5
+ },
+ "canonical": "{\"account_id\":\"pa_01\",\"cash\":1000.5,\"market\":\"cn_a\"}",
+ "sha256": "bfbd8652f4a6a35d9514b793cb26b93c27bb45f4c33964495483052f09f0a349"
+ },
+ {
+ "name": "key_order_shuffle_b",
+ "input": {
+ "cash": 1000.5,
+ "account_id": "pa_01",
+ "market": "cn_a"
+ },
+ "canonical": "{\"account_id\":\"pa_01\",\"cash\":1000.5,\"market\":\"cn_a\"}",
+ "sha256": "bfbd8652f4a6a35d9514b793cb26b93c27bb45f4c33964495483052f09f0a349"
+ },
+ {
+ "name": "float_int_equiv_float",
+ "input": {
+ "qty": 100000.0
+ },
+ "canonical": "{\"qty\":100000}",
+ "sha256": "1174edd4f8641f5f0f9550fb88e64688e6c17c68a5465d88ca27e5c36909ecd1"
+ },
+ {
+ "name": "float_int_equiv_int",
+ "input": {
+ "qty": 100000
+ },
+ "canonical": "{\"qty\":100000}",
+ "sha256": "1174edd4f8641f5f0f9550fb88e64688e6c17c68a5465d88ca27e5c36909ecd1"
+ },
+ {
+ "name": "large_and_exponent_forms",
+ "input": {
+ "a": 1e+16,
+ "b": 1.2345678901234567e+20,
+ "c": 1e+21,
+ "d": 1e-06,
+ "e": 1.5e-07
+ },
+ "canonical": "{\"a\":10000000000000000,\"b\":123456789012345670000,\"c\":1e+21,\"d\":0.000001,\"e\":1.5e-7}",
+ "sha256": "2e8225e26a05653d9170ebcc02880be9dceab33e6b8549bd631a24df94b1609b"
+ },
+ {
+ "name": "negative_zero",
+ "input": {
+ "x": -0.0,
+ "y": 0.0,
+ "z": 0
+ },
+ "canonical": "{\"x\":0,\"y\":0,\"z\":0}",
+ "sha256": "35461afe4a2d42dcc8948534195c5e79c22332615508a7a0627de91e52c3b5c8"
+ },
+ {
+ "name": "unicode_symbol",
+ "input": {
+ "symbol": "600519.SH",
+ "name": "贵州茅台",
+ "note": "naïve café — ✓"
+ },
+ "canonical": "{\"name\":\"贵州茅台\",\"note\":\"naïve café — ✓\",\"symbol\":\"600519.SH\"}",
+ "sha256": "7998876ecec1a2204c0b9bdc5918a4bc799ab2343ce4bc985c1ffe898d068294"
+ },
+ {
+ "name": "empty_positions",
+ "input": {
+ "cash": 100000.0,
+ "positions": []
+ },
+ "canonical": "{\"cash\":100000,\"positions\":[]}",
+ "sha256": "78d7d86d7aa283ef41bed8aeec058cbf71a9728241f5ef3a6b8b0fc7e4b3d328"
+ },
+ {
+ "name": "array_order_ab",
+ "input": {
+ "positions": [
+ {
+ "symbol": "600519.SH",
+ "qty": 100,
+ "avg_cost": 1418.0
+ },
+ {
+ "symbol": "000001.SZ",
+ "qty": 200,
+ "avg_cost": 11.55
+ }
+ ]
+ },
+ "canonical": "{\"positions\":[{\"avg_cost\":1418,\"qty\":100,\"symbol\":\"600519.SH\"},{\"avg_cost\":11.55,\"qty\":200,\"symbol\":\"000001.SZ\"}]}",
+ "sha256": "3bbc93e93eb56ff41ce31f536e991cc9049311e5f77b6fc485ee80335b0f5b63"
+ },
+ {
+ "name": "array_order_ba",
+ "input": {
+ "positions": [
+ {
+ "symbol": "000001.SZ",
+ "qty": 200,
+ "avg_cost": 11.55
+ },
+ {
+ "symbol": "600519.SH",
+ "qty": 100,
+ "avg_cost": 1418.0
+ }
+ ]
+ },
+ "canonical": "{\"positions\":[{\"avg_cost\":11.55,\"qty\":200,\"symbol\":\"000001.SZ\"},{\"avg_cost\":1418,\"qty\":100,\"symbol\":\"600519.SH\"}]}",
+ "sha256": "b5009b3e3228d04e14d3fa3338124833ab79f9096dcb238a91cdb7ba6413c121"
+ },
+ {
+ "name": "json_base_tokens",
+ "input": {
+ "flag": true,
+ "other": false,
+ "nothing": null
+ },
+ "canonical": "{\"flag\":true,\"nothing\":null,\"other\":false}",
+ "sha256": "92d19a07cb5390c05daaed874239742c444fb8d6b76055a7d738d14d835b5737"
+ },
+ {
+ "name": "am4_hash_coverage_object",
+ "input": {
+ "to_date": "2026-10-20",
+ "from_date": "2026-10-20",
+ "fee_model": {
+ "transfer_fee": 1e-05,
+ "stamp_tax_sell": 0.0005,
+ "commission_min": 5.0,
+ "commission_rate": 0.00025
+ },
+ "market": "cn_a",
+ "account_state": {
+ "positions": [
+ {
+ "symbol": "600519.SH",
+ "avg_cost": 1418.0,
+ "qty": 100
+ }
+ ],
+ "cash": 98213.44
+ },
+ "account_id": "pa_deadbeefdeadbeefdeadbeef"
+ },
+ "canonical": "{\"account_id\":\"pa_deadbeefdeadbeefdeadbeef\",\"account_state\":{\"cash\":98213.44,\"positions\":[{\"avg_cost\":1418,\"qty\":100,\"symbol\":\"600519.SH\"}]},\"fee_model\":{\"commission_min\":5,\"commission_rate\":0.00025,\"stamp_tax_sell\":0.0005,\"transfer_fee\":0.00001},\"from_date\":\"2026-10-20\",\"market\":\"cn_a\",\"to_date\":\"2026-10-20\"}",
+ "sha256": "7314d251e44d563981b80d94c957f301a77b2c867fe229e7af264d39c643cac1"
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/paper_trade/market/MANIFEST.json b/agent/tests/fixtures/paper_trade/market/MANIFEST.json
new file mode 100644
index 000000000..5b53c5aef
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/market/MANIFEST.json
@@ -0,0 +1,107 @@
+{
+ "schema": "paper_trade.market_manifest/v1",
+ "generator": "record_market_fixtures.py (manual tool; tests never run it)",
+ "description": "Tamper-evident index over agent/tests/fixtures/paper_trade/market/*.json. sha256 is of the exact on-disk bytes; test_paper_trade_fixtures.py re-verifies them. Recorded fixtures are byte-frozen snapshots of the listed request_url replies (VD-14); synthetic fixtures are authored, engine-facing inputs for T7/T5, and their construction is documented per file.",
+ "fixtures": [
+ {
+ "file": "hk_00700_tencent.json",
+ "sha256": "af5ecba70140d160f9770f4e513486880f70a65f6573d7bad96ad09a52f4106d",
+ "bytes": 40277,
+ "rows": 256,
+ "first_date": "2025-10-02",
+ "last_date": "2026-10-16",
+ "market": "hk_equity",
+ "symbol": "00700.HK",
+ "source": "tencent",
+ "price_caliber": "raw",
+ "volume_unit": "shares",
+ "request_url": "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=hk00700,day,2025-10-01,2026-10-16,500,qfq",
+ "window": {
+ "start": "2025-10-01",
+ "end": "2026-10-16"
+ },
+ "recorded_at_utc": "2026-10-18T14:32:36Z",
+ "drop_stats": {
+ "wire_rows": 256,
+ "dropped_unparseable": 0,
+ "dropped_out_of_window": 0,
+ "dropped_duplicate_dates": 0,
+ "dropped_dirty_ohlc": 0
+ },
+ "caliber_note": "raw — Tencent serves no adjusted HK series: the fqkline reply carries only 'day' (never 'qfqday', #1493 / registry.py ('tencent',hk_equity)='raw'), so the ',qfq' request parameter changes nothing. Row layout is [date, open, close, high, low, volume]; a 7th event-dict element is ignored exactly like tencent_loader.py:206-217 (parses 6 fields).",
+ "construction": null
+ },
+ {
+ "file": "synthetic_holiday_gap.json",
+ "sha256": "88c5621fc27014b320d682c783e744ceeebe2878c1932757fb2500b7b759c360",
+ "bytes": 5069,
+ "rows": 24,
+ "first_date": "2026-03-02",
+ "last_date": "2026-04-10",
+ "market": "us_equity",
+ "symbol": "SYNTH-GAP",
+ "source": "synthetic",
+ "price_caliber": "raw",
+ "volume_unit": "shares",
+ "request_url": null,
+ "window": {
+ "start": "2026-03-02",
+ "end": "2026-04-10"
+ },
+ "recorded_at_utc": null,
+ "drop_stats": null,
+ "caliber_note": "authored unadjusted daily series for the calendar fail-closed seam (VD-5): weekends are implicit; the two documented gaps are trading-day absences, not calendar artifacts",
+ "construction": "24 weekday bars in five segments (5+4+5+5+5) from 2026-03-02 to 2026-04-10; open=prev close, close=100.0+0.25*i, high=max(o,c)+0.5, low=min(o,c)-0.5, volume=1000000.0; values binary-exact quarters. Gap 1 skips Mon 2026-03-09 (single holiday on a long weekend); Gap 2 skips the whole week 2026-03-23..2026-03-27 (multi-day closure, 5 trading days). gap_samples below pins both so tests can assert the authored gaps without hardcoding dates twice."
+ },
+ {
+ "file": "synthetic_split_4to1.json",
+ "sha256": "8c27a304aa4b125e04f23095e74f8777ff7274559770a1b6a80740b7fc5144fb",
+ "bytes": 22624,
+ "rows": 141,
+ "first_date": "2026-01-05",
+ "last_date": "2026-07-20",
+ "market": "us_equity",
+ "symbol": "SYNTH-4TO1",
+ "source": "synthetic",
+ "price_caliber": "raw",
+ "volume_unit": "shares",
+ "request_url": null,
+ "window": {
+ "start": "2026-01-05",
+ "end": "2026-07-20"
+ },
+ "recorded_at_utc": null,
+ "drop_stats": null,
+ "caliber_note": "authored unadjusted daily series: the 4:1 split cliff is present by construction and is NOT smoothed, mirroring the raw sina/us caliber the T7 detector must handle",
+ "construction": "141 consecutive weekdays from 2026-01-05; bars 0..19 pre-split with open=prev close, close=400.0+4.0*i, high=max(o,c)+1.0, low=min(o,c)-1.0, volume=1000000.0; bar 20 is the ex-date: every OHLC is exactly the prior close / 4 (476.0 -> 119.0, close-to-close ratio exactly 0.25) and volume is exactly 4x (1000000 -> 4000000, the same-direction multiple confirmation VD-6 requires); bars 21..140 drift with close=119.0+0.5*k and volume=4000000.0. All values are binary-exact quarters; no rounding anywhere. 120 bars follow the ex-date so a K=120 trading-day lookback (VD-6/B3 fetch window) puts the event exactly at the window edge."
+ },
+ {
+ "file": "us_AAPL_sina.json",
+ "sha256": "a16e75b1c115f47c29ee059687aa4ba4374919b5cb4d6d098aef07f75fa8bac5",
+ "bytes": 42223,
+ "rows": 263,
+ "first_date": "2025-10-01",
+ "last_date": "2026-10-16",
+ "market": "us_equity",
+ "symbol": "AAPL.US",
+ "source": "sina",
+ "price_caliber": "raw",
+ "volume_unit": null,
+ "request_url": "https://stock.finance.sina.com.cn/usstock/api/jsonp_v2.php/var%20x=/US_MinKService.getDailyK?symbol=AAPL",
+ "window": {
+ "start": "2025-10-01",
+ "end": "2026-10-16"
+ },
+ "recorded_at_utc": "2026-10-18T14:32:36Z",
+ "drop_stats": {
+ "wire_rows": 10055,
+ "dropped_unparseable": 0,
+ "dropped_out_of_window": 9792,
+ "dropped_duplicate_dates": 0,
+ "dropped_dirty_ohlc": 0
+ },
+ "caliber_note": "raw / unadjusted — no split scaling applied by the source; a close-to-close read across the 2020-08-31 4:1 ex-date reads ~0.2585. Pinned by registry.py PRICE_CALIBER_BY_SOURCE['sina']='raw' and live-confirmed 2026-10-18 (STEP0-LANE-A A1/A2); the recorded window itself does not contain that ex-date.",
+ "construction": null
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/paper_trade/market/hk_00700_tencent.json b/agent/tests/fixtures/paper_trade/market/hk_00700_tencent.json
new file mode 100644
index 000000000..a71b57521
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/market/hk_00700_tencent.json
@@ -0,0 +1,2078 @@
+{
+ "schema": "paper_trade.market_fixture/v1",
+ "market": "hk_equity",
+ "symbol": "00700.HK",
+ "source": "tencent",
+ "price_caliber": "raw",
+ "volume_unit": "shares",
+ "volume_unit_note": "tencent_loader.py:70 volume_units: a_share=lots, hk_equity=shares",
+ "request_url": "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=hk00700,day,2025-10-01,2026-10-16,500,qfq",
+ "request_headers": {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
+ "Referer": "https://web.ifzq.gtimg.cn/"
+ },
+ "window": {
+ "start": "2025-10-01",
+ "end": "2026-10-16"
+ },
+ "window_note": "single request: the window holds fewer than the 500-bar page cap, and Tencent honours the start clamp for such windows (tencent_loader.py:36-42).",
+ "recorded_at_utc": "2026-10-18T14:32:36Z",
+ "caliber_note": "raw — Tencent serves no adjusted HK series: the fqkline reply carries only 'day' (never 'qfqday', #1493 / registry.py ('tencent',hk_equity)='raw'), so the ',qfq' request parameter changes nothing. Row layout is [date, open, close, high, low, volume]; a 7th event-dict element is ignored exactly like tencent_loader.py:206-217 (parses 6 fields).",
+ "drop_stats": {
+ "wire_rows": 256,
+ "dropped_unparseable": 0,
+ "dropped_out_of_window": 0,
+ "dropped_duplicate_dates": 0,
+ "dropped_dirty_ohlc": 0
+ },
+ "bars": [
+ {
+ "date": "2025-10-02",
+ "open": 667.5,
+ "high": 683.0,
+ "low": 665.5,
+ "close": 676.5,
+ "volume": 17137745.0
+ },
+ {
+ "date": "2025-10-03",
+ "open": 677.0,
+ "high": 680.0,
+ "low": 670.0,
+ "close": 673.5,
+ "volume": 7125093.0
+ },
+ {
+ "date": "2025-10-06",
+ "open": 675.0,
+ "high": 682.5,
+ "low": 670.0,
+ "close": 677.5,
+ "volume": 7828323.0
+ },
+ {
+ "date": "2025-10-08",
+ "open": 680.0,
+ "high": 680.0,
+ "low": 669.5,
+ "close": 675.0,
+ "volume": 10540730.0
+ },
+ {
+ "date": "2025-10-09",
+ "open": 675.0,
+ "high": 681.0,
+ "low": 665.5,
+ "close": 675.5,
+ "volume": 14454705.0
+ },
+ {
+ "date": "2025-10-10",
+ "open": 669.0,
+ "high": 669.0,
+ "low": 647.5,
+ "close": 651.5,
+ "volume": 19904705.0
+ },
+ {
+ "date": "2025-10-13",
+ "open": 630.0,
+ "high": 648.5,
+ "low": 622.5,
+ "close": 639.0,
+ "volume": 38012175.0
+ },
+ {
+ "date": "2025-10-14",
+ "open": 642.5,
+ "high": 644.0,
+ "low": 617.0,
+ "close": 621.0,
+ "volume": 26797863.0
+ },
+ {
+ "date": "2025-10-15",
+ "open": 624.5,
+ "high": 633.0,
+ "low": 620.5,
+ "close": 627.0,
+ "volume": 18381023.0
+ },
+ {
+ "date": "2025-10-16",
+ "open": 626.0,
+ "high": 629.0,
+ "low": 615.5,
+ "close": 620.0,
+ "volume": 14285465.0
+ },
+ {
+ "date": "2025-10-17",
+ "open": 618.5,
+ "high": 620.5,
+ "low": 602.5,
+ "close": 608.0,
+ "volume": 18654519.0
+ },
+ {
+ "date": "2025-10-20",
+ "open": 624.0,
+ "high": 632.5,
+ "low": 621.5,
+ "close": 627.5,
+ "volume": 14963360.0
+ },
+ {
+ "date": "2025-10-21",
+ "open": 643.0,
+ "high": 644.0,
+ "low": 630.0,
+ "close": 630.5,
+ "volume": 14171988.0
+ },
+ {
+ "date": "2025-10-22",
+ "open": 626.0,
+ "high": 629.0,
+ "low": 616.5,
+ "close": 623.5,
+ "volume": 9979448.0
+ },
+ {
+ "date": "2025-10-23",
+ "open": 620.0,
+ "high": 636.0,
+ "low": 618.0,
+ "close": 633.0,
+ "volume": 12419348.0
+ },
+ {
+ "date": "2025-10-24",
+ "open": 639.0,
+ "high": 641.5,
+ "low": 633.5,
+ "close": 637.5,
+ "volume": 11997034.0
+ },
+ {
+ "date": "2025-10-27",
+ "open": 649.0,
+ "high": 656.0,
+ "low": 646.0,
+ "close": 656.0,
+ "volume": 16043970.0
+ },
+ {
+ "date": "2025-10-28",
+ "open": 656.0,
+ "high": 656.0,
+ "low": 641.0,
+ "close": 645.0,
+ "volume": 16295470.0
+ },
+ {
+ "date": "2025-10-30",
+ "open": 657.0,
+ "high": 664.0,
+ "low": 645.0,
+ "close": 651.0,
+ "volume": 21772780.0
+ },
+ {
+ "date": "2025-10-31",
+ "open": 651.5,
+ "high": 655.0,
+ "low": 629.0,
+ "close": 629.0,
+ "volume": 20578283.0
+ },
+ {
+ "date": "2025-11-03",
+ "open": 630.5,
+ "high": 634.0,
+ "low": 622.5,
+ "close": 628.0,
+ "volume": 11591004.0
+ },
+ {
+ "date": "2025-11-04",
+ "open": 631.0,
+ "high": 640.0,
+ "low": 625.5,
+ "close": 629.0,
+ "volume": 14972125.0
+ },
+ {
+ "date": "2025-11-05",
+ "open": 621.0,
+ "high": 632.0,
+ "low": 613.0,
+ "close": 629.0,
+ "volume": 13309811.0
+ },
+ {
+ "date": "2025-11-06",
+ "open": 629.5,
+ "high": 645.5,
+ "low": 629.5,
+ "close": 644.0,
+ "volume": 13081287.0
+ },
+ {
+ "date": "2025-11-07",
+ "open": 638.0,
+ "high": 643.0,
+ "low": 628.5,
+ "close": 634.0,
+ "volume": 13314360.0
+ },
+ {
+ "date": "2025-11-10",
+ "open": 641.0,
+ "high": 651.0,
+ "low": 641.0,
+ "close": 649.5,
+ "volume": 14513815.0
+ },
+ {
+ "date": "2025-11-11",
+ "open": 662.0,
+ "high": 662.0,
+ "low": 641.0,
+ "close": 650.0,
+ "volume": 13087772.0
+ },
+ {
+ "date": "2025-11-12",
+ "open": 655.0,
+ "high": 658.5,
+ "low": 652.0,
+ "close": 657.0,
+ "volume": 13658568.0
+ },
+ {
+ "date": "2025-11-13",
+ "open": 649.5,
+ "high": 660.0,
+ "low": 645.0,
+ "close": 656.0,
+ "volume": 17299913.0
+ },
+ {
+ "date": "2025-11-14",
+ "open": 645.0,
+ "high": 659.0,
+ "low": 640.0,
+ "close": 641.0,
+ "volume": 19956444.0
+ },
+ {
+ "date": "2025-11-17",
+ "open": 640.0,
+ "high": 642.5,
+ "low": 633.0,
+ "close": 636.5,
+ "volume": 13794477.0
+ },
+ {
+ "date": "2025-11-18",
+ "open": 628.0,
+ "high": 641.0,
+ "low": 620.5,
+ "close": 623.5,
+ "volume": 18818609.0
+ },
+ {
+ "date": "2025-11-19",
+ "open": 627.5,
+ "high": 631.5,
+ "low": 619.5,
+ "close": 622.5,
+ "volume": 13959708.0
+ },
+ {
+ "date": "2025-11-20",
+ "open": 626.5,
+ "high": 630.5,
+ "low": 615.5,
+ "close": 621.0,
+ "volume": 14015988.0
+ },
+ {
+ "date": "2025-11-21",
+ "open": 610.0,
+ "high": 615.0,
+ "low": 606.0,
+ "close": 610.0,
+ "volume": 23732050.0
+ },
+ {
+ "date": "2025-11-24",
+ "open": 615.0,
+ "high": 627.5,
+ "low": 613.5,
+ "close": 624.5,
+ "volume": 22376801.0
+ },
+ {
+ "date": "2025-11-25",
+ "open": 633.0,
+ "high": 635.0,
+ "low": 620.5,
+ "close": 625.0,
+ "volume": 14877620.0
+ },
+ {
+ "date": "2025-11-26",
+ "open": 628.5,
+ "high": 630.0,
+ "low": 618.0,
+ "close": 619.5,
+ "volume": 14429595.0
+ },
+ {
+ "date": "2025-11-27",
+ "open": 618.0,
+ "high": 620.5,
+ "low": 609.0,
+ "close": 611.5,
+ "volume": 15493209.0
+ },
+ {
+ "date": "2025-11-28",
+ "open": 611.5,
+ "high": 617.0,
+ "low": 608.5,
+ "close": 611.5,
+ "volume": 13216245.0
+ },
+ {
+ "date": "2025-12-01",
+ "open": 613.5,
+ "high": 623.0,
+ "low": 613.0,
+ "close": 619.5,
+ "volume": 12643338.0
+ },
+ {
+ "date": "2025-12-02",
+ "open": 625.5,
+ "high": 626.0,
+ "low": 615.0,
+ "close": 617.0,
+ "volume": 11460186.0
+ },
+ {
+ "date": "2025-12-03",
+ "open": 616.0,
+ "high": 616.0,
+ "low": 608.5,
+ "close": 611.0,
+ "volume": 11002158.0
+ },
+ {
+ "date": "2025-12-04",
+ "open": 610.0,
+ "high": 613.0,
+ "low": 605.0,
+ "close": 612.0,
+ "volume": 15329748.0
+ },
+ {
+ "date": "2025-12-05",
+ "open": 605.0,
+ "high": 611.0,
+ "low": 604.0,
+ "close": 610.0,
+ "volume": 14638391.0
+ },
+ {
+ "date": "2025-12-08",
+ "open": 607.5,
+ "high": 609.5,
+ "low": 604.0,
+ "close": 605.0,
+ "volume": 13421327.0
+ },
+ {
+ "date": "2025-12-09",
+ "open": 609.5,
+ "high": 610.0,
+ "low": 596.0,
+ "close": 602.5,
+ "volume": 17431321.0
+ },
+ {
+ "date": "2025-12-10",
+ "open": 602.0,
+ "high": 603.0,
+ "low": 595.0,
+ "close": 603.0,
+ "volume": 14750743.0
+ },
+ {
+ "date": "2025-12-11",
+ "open": 609.0,
+ "high": 612.0,
+ "low": 599.0,
+ "close": 601.5,
+ "volume": 12480887.0
+ },
+ {
+ "date": "2025-12-12",
+ "open": 608.0,
+ "high": 616.0,
+ "low": 601.5,
+ "close": 616.0,
+ "volume": 17825495.0
+ },
+ {
+ "date": "2025-12-15",
+ "open": 606.0,
+ "high": 608.5,
+ "low": 602.0,
+ "close": 603.0,
+ "volume": 15165502.0
+ },
+ {
+ "date": "2025-12-16",
+ "open": 602.5,
+ "high": 603.0,
+ "low": 592.0,
+ "close": 596.5,
+ "volume": 15987678.0
+ },
+ {
+ "date": "2025-12-17",
+ "open": 597.0,
+ "high": 606.0,
+ "low": 594.5,
+ "close": 605.0,
+ "volume": 14824785.0
+ },
+ {
+ "date": "2025-12-18",
+ "open": 601.0,
+ "high": 606.0,
+ "low": 599.0,
+ "close": 605.0,
+ "volume": 10153604.0
+ },
+ {
+ "date": "2025-12-19",
+ "open": 610.0,
+ "high": 617.5,
+ "low": 607.0,
+ "close": 614.0,
+ "volume": 17765762.0
+ },
+ {
+ "date": "2025-12-22",
+ "open": 620.0,
+ "high": 621.5,
+ "low": 610.0,
+ "close": 614.5,
+ "volume": 13868060.0
+ },
+ {
+ "date": "2025-12-23",
+ "open": 613.5,
+ "high": 614.5,
+ "low": 601.5,
+ "close": 602.0,
+ "volume": 15623392.0
+ },
+ {
+ "date": "2025-12-24",
+ "open": 598.0,
+ "high": 604.5,
+ "low": 598.0,
+ "close": 603.0,
+ "volume": 7324553.0
+ },
+ {
+ "date": "2025-12-29",
+ "open": 606.0,
+ "high": 611.0,
+ "low": 596.0,
+ "close": 596.5,
+ "volume": 18502650.0
+ },
+ {
+ "date": "2025-12-30",
+ "open": 598.5,
+ "high": 601.0,
+ "low": 594.0,
+ "close": 600.0,
+ "volume": 13582535.0
+ },
+ {
+ "date": "2025-12-31",
+ "open": 597.5,
+ "high": 602.5,
+ "low": 596.0,
+ "close": 599.0,
+ "volume": 10838209.0
+ },
+ {
+ "date": "2026-01-02",
+ "open": 600.5,
+ "high": 624.5,
+ "low": 600.5,
+ "close": 623.0,
+ "volume": 16200058.0
+ },
+ {
+ "date": "2026-01-05",
+ "open": 624.0,
+ "high": 628.0,
+ "low": 615.5,
+ "close": 624.5,
+ "volume": 19947025.0
+ },
+ {
+ "date": "2026-01-06",
+ "open": 627.0,
+ "high": 638.5,
+ "low": 626.0,
+ "close": 632.5,
+ "volume": 24168431.0
+ },
+ {
+ "date": "2026-01-07",
+ "open": 627.5,
+ "high": 629.5,
+ "low": 615.0,
+ "close": 624.5,
+ "volume": 21378622.0
+ },
+ {
+ "date": "2026-01-08",
+ "open": 618.5,
+ "high": 621.0,
+ "low": 610.0,
+ "close": 616.0,
+ "volume": 18742539.0
+ },
+ {
+ "date": "2026-01-09",
+ "open": 616.0,
+ "high": 617.0,
+ "low": 610.0,
+ "close": 611.0,
+ "volume": 17813669.0
+ },
+ {
+ "date": "2026-01-12",
+ "open": 616.0,
+ "high": 627.5,
+ "low": 613.5,
+ "close": 623.0,
+ "volume": 27530129.0
+ },
+ {
+ "date": "2026-01-13",
+ "open": 637.0,
+ "high": 639.0,
+ "low": 622.5,
+ "close": 627.5,
+ "volume": 24212695.0
+ },
+ {
+ "date": "2026-01-14",
+ "open": 634.0,
+ "high": 638.5,
+ "low": 626.0,
+ "close": 633.0,
+ "volume": 28677291.0
+ },
+ {
+ "date": "2026-01-15",
+ "open": 631.0,
+ "high": 632.5,
+ "low": 618.5,
+ "close": 622.0,
+ "volume": 26194252.0
+ },
+ {
+ "date": "2026-01-16",
+ "open": 627.0,
+ "high": 630.0,
+ "low": 613.5,
+ "close": 617.5,
+ "volume": 20616793.0
+ },
+ {
+ "date": "2026-01-19",
+ "open": 613.5,
+ "high": 614.5,
+ "low": 608.5,
+ "close": 610.0,
+ "volume": 13233330.0
+ },
+ {
+ "date": "2026-01-20",
+ "open": 601.0,
+ "high": 607.0,
+ "low": 598.0,
+ "close": 601.0,
+ "volume": 24332228.0
+ },
+ {
+ "date": "2026-01-21",
+ "open": 598.0,
+ "high": 606.0,
+ "low": 598.0,
+ "close": 602.5,
+ "volume": 16003431.0
+ },
+ {
+ "date": "2026-01-22",
+ "open": 604.5,
+ "high": 605.5,
+ "low": 596.0,
+ "close": 597.5,
+ "volume": 27168713.0
+ },
+ {
+ "date": "2026-01-23",
+ "open": 597.5,
+ "high": 602.0,
+ "low": 595.0,
+ "close": 595.0,
+ "volume": 19177660.0
+ },
+ {
+ "date": "2026-01-26",
+ "open": 595.0,
+ "high": 605.0,
+ "low": 594.0,
+ "close": 599.5,
+ "volume": 17439619.0
+ },
+ {
+ "date": "2026-01-27",
+ "open": 600.0,
+ "high": 610.5,
+ "low": 598.5,
+ "close": 607.0,
+ "volume": 23887447.0
+ },
+ {
+ "date": "2026-01-28",
+ "open": 613.0,
+ "high": 623.0,
+ "low": 610.5,
+ "close": 621.0,
+ "volume": 25577066.0
+ },
+ {
+ "date": "2026-01-29",
+ "open": 614.5,
+ "high": 625.0,
+ "low": 612.5,
+ "close": 622.0,
+ "volume": 22951530.0
+ },
+ {
+ "date": "2026-01-30",
+ "open": 615.0,
+ "high": 619.5,
+ "low": 605.5,
+ "close": 606.0,
+ "volume": 21479886.0
+ },
+ {
+ "date": "2026-02-02",
+ "open": 598.0,
+ "high": 604.5,
+ "low": 590.5,
+ "close": 598.5,
+ "volume": 27926332.0
+ },
+ {
+ "date": "2026-02-03",
+ "open": 598.5,
+ "high": 601.5,
+ "low": 561.0,
+ "close": 581.0,
+ "volume": 65128647.0
+ },
+ {
+ "date": "2026-02-04",
+ "open": 572.0,
+ "high": 574.5,
+ "low": 558.0,
+ "close": 558.0,
+ "volume": 60374834.0
+ },
+ {
+ "date": "2026-02-05",
+ "open": 550.0,
+ "high": 561.5,
+ "low": 541.0,
+ "close": 558.5,
+ "volume": 79306977.0
+ },
+ {
+ "date": "2026-02-06",
+ "open": 546.0,
+ "high": 557.5,
+ "low": 543.0,
+ "close": 547.5,
+ "volume": 35402860.0
+ },
+ {
+ "date": "2026-02-09",
+ "open": 550.0,
+ "high": 562.5,
+ "low": 550.0,
+ "close": 560.0,
+ "volume": 26375723.0
+ },
+ {
+ "date": "2026-02-10",
+ "open": 563.0,
+ "high": 566.0,
+ "low": 547.0,
+ "close": 551.0,
+ "volume": 29211865.0
+ },
+ {
+ "date": "2026-02-11",
+ "open": 543.0,
+ "high": 550.5,
+ "low": 543.0,
+ "close": 548.0,
+ "volume": 23759058.0
+ },
+ {
+ "date": "2026-02-12",
+ "open": 537.0,
+ "high": 541.0,
+ "low": 530.5,
+ "close": 535.5,
+ "volume": 39790780.0
+ },
+ {
+ "date": "2026-02-13",
+ "open": 525.5,
+ "high": 534.5,
+ "low": 525.0,
+ "close": 532.0,
+ "volume": 26900740.0
+ },
+ {
+ "date": "2026-02-16",
+ "open": 530.0,
+ "high": 535.0,
+ "low": 527.5,
+ "close": 533.0,
+ "volume": 7224483.0
+ },
+ {
+ "date": "2026-02-20",
+ "open": 531.5,
+ "high": 533.0,
+ "low": 518.0,
+ "close": 522.0,
+ "volume": 21351884.0
+ },
+ {
+ "date": "2026-02-23",
+ "open": 529.0,
+ "high": 543.0,
+ "low": 528.0,
+ "close": 538.0,
+ "volume": 22136687.0
+ },
+ {
+ "date": "2026-02-24",
+ "open": 534.5,
+ "high": 534.5,
+ "low": 516.0,
+ "close": 520.0,
+ "volume": 36134943.0
+ },
+ {
+ "date": "2026-02-25",
+ "open": 522.5,
+ "high": 529.0,
+ "low": 522.0,
+ "close": 522.5,
+ "volume": 22838866.0
+ },
+ {
+ "date": "2026-02-26",
+ "open": 529.0,
+ "high": 529.5,
+ "low": 512.0,
+ "close": 512.0,
+ "volume": 25547825.0
+ },
+ {
+ "date": "2026-02-27",
+ "open": 510.5,
+ "high": 530.5,
+ "low": 510.5,
+ "close": 518.0,
+ "volume": 32229030.0
+ },
+ {
+ "date": "2026-03-02",
+ "open": 511.5,
+ "high": 520.0,
+ "low": 507.0,
+ "close": 514.0,
+ "volume": 30816358.0
+ },
+ {
+ "date": "2026-03-03",
+ "open": 518.0,
+ "high": 525.5,
+ "low": 510.5,
+ "close": 510.5,
+ "volume": 27370602.0
+ },
+ {
+ "date": "2026-03-04",
+ "open": 506.0,
+ "high": 515.0,
+ "low": 498.8,
+ "close": 506.0,
+ "volume": 32965198.0
+ },
+ {
+ "date": "2026-03-05",
+ "open": 509.5,
+ "high": 515.5,
+ "low": 501.5,
+ "close": 502.0,
+ "volume": 23955443.0
+ },
+ {
+ "date": "2026-03-06",
+ "open": 504.0,
+ "high": 522.0,
+ "low": 502.0,
+ "close": 519.0,
+ "volume": 30359878.0
+ },
+ {
+ "date": "2026-03-09",
+ "open": 502.5,
+ "high": 517.5,
+ "low": 502.5,
+ "close": 516.0,
+ "volume": 31383491.0
+ },
+ {
+ "date": "2026-03-10",
+ "open": 525.0,
+ "high": 556.0,
+ "low": 525.0,
+ "close": 553.5,
+ "volume": 57862244.0
+ },
+ {
+ "date": "2026-03-11",
+ "open": 578.0,
+ "high": 578.0,
+ "low": 548.0,
+ "close": 552.0,
+ "volume": 47623240.0
+ },
+ {
+ "date": "2026-03-12",
+ "open": 550.5,
+ "high": 557.0,
+ "low": 541.5,
+ "close": 546.5,
+ "volume": 19663840.0
+ },
+ {
+ "date": "2026-03-13",
+ "open": 546.5,
+ "high": 558.5,
+ "low": 543.0,
+ "close": 547.5,
+ "volume": 17183958.0
+ },
+ {
+ "date": "2026-03-16",
+ "open": 551.0,
+ "high": 565.5,
+ "low": 543.5,
+ "close": 558.5,
+ "volume": 24217363.0
+ },
+ {
+ "date": "2026-03-17",
+ "open": 563.0,
+ "high": 566.0,
+ "low": 549.0,
+ "close": 550.0,
+ "volume": 22872974.0
+ },
+ {
+ "date": "2026-03-18",
+ "open": 546.5,
+ "high": 552.0,
+ "low": 542.5,
+ "close": 550.5,
+ "volume": 21350876.0
+ },
+ {
+ "date": "2026-03-19",
+ "open": 528.0,
+ "high": 529.5,
+ "low": 512.0,
+ "close": 513.0,
+ "volume": 59432770.0
+ },
+ {
+ "date": "2026-03-20",
+ "open": 505.0,
+ "high": 519.0,
+ "low": 505.0,
+ "close": 508.0,
+ "volume": 24924662.0
+ },
+ {
+ "date": "2026-03-23",
+ "open": 497.8,
+ "high": 506.0,
+ "low": 495.2,
+ "close": 498.4,
+ "volume": 35123702.0
+ },
+ {
+ "date": "2026-03-24",
+ "open": 508.0,
+ "high": 520.0,
+ "low": 500.0,
+ "close": 514.0,
+ "volume": 29358876.0
+ },
+ {
+ "date": "2026-03-25",
+ "open": 519.0,
+ "high": 521.5,
+ "low": 502.0,
+ "close": 505.5,
+ "volume": 37353909.0
+ },
+ {
+ "date": "2026-03-26",
+ "open": 501.0,
+ "high": 507.5,
+ "low": 495.0,
+ "close": 495.6,
+ "volume": 22623215.0
+ },
+ {
+ "date": "2026-03-27",
+ "open": 491.2,
+ "high": 498.2,
+ "low": 487.6,
+ "close": 493.4,
+ "volume": 20345920.0
+ },
+ {
+ "date": "2026-03-30",
+ "open": 485.0,
+ "high": 485.8,
+ "low": 476.0,
+ "close": 481.6,
+ "volume": 28410968.0
+ },
+ {
+ "date": "2026-03-31",
+ "open": 484.4,
+ "high": 492.0,
+ "low": 480.0,
+ "close": 484.0,
+ "volume": 25801397.0
+ },
+ {
+ "date": "2026-04-01",
+ "open": 504.0,
+ "high": 504.0,
+ "low": 493.0,
+ "close": 496.6,
+ "volume": 21275055.0
+ },
+ {
+ "date": "2026-04-02",
+ "open": 496.0,
+ "high": 496.0,
+ "low": 485.0,
+ "close": 489.2,
+ "volume": 17030828.0
+ },
+ {
+ "date": "2026-04-08",
+ "open": 504.5,
+ "high": 510.0,
+ "low": 501.0,
+ "close": 508.0,
+ "volume": 32856156.0
+ },
+ {
+ "date": "2026-04-09",
+ "open": 506.5,
+ "high": 514.5,
+ "low": 503.0,
+ "close": 508.5,
+ "volume": 20722763.0
+ },
+ {
+ "date": "2026-04-10",
+ "open": 508.0,
+ "high": 514.0,
+ "low": 501.0,
+ "close": 504.5,
+ "volume": 20671874.0
+ },
+ {
+ "date": "2026-04-13",
+ "open": 498.4,
+ "high": 503.0,
+ "low": 487.8,
+ "close": 490.0,
+ "volume": 21140848.0
+ },
+ {
+ "date": "2026-04-14",
+ "open": 497.4,
+ "high": 497.4,
+ "low": 486.2,
+ "close": 493.2,
+ "volume": 17833779.0
+ },
+ {
+ "date": "2026-04-15",
+ "open": 500.0,
+ "high": 510.0,
+ "low": 497.4,
+ "close": 499.0,
+ "volume": 20288791.0
+ },
+ {
+ "date": "2026-04-16",
+ "open": 506.5,
+ "high": 517.0,
+ "low": 504.0,
+ "close": 517.0,
+ "volume": 22559081.0
+ },
+ {
+ "date": "2026-04-17",
+ "open": 512.0,
+ "high": 517.0,
+ "low": 506.0,
+ "close": 510.5,
+ "volume": 13747249.0
+ },
+ {
+ "date": "2026-04-20",
+ "open": 509.5,
+ "high": 526.5,
+ "low": 504.5,
+ "close": 522.5,
+ "volume": 23428202.0
+ },
+ {
+ "date": "2026-04-21",
+ "open": 523.0,
+ "high": 525.5,
+ "low": 515.5,
+ "close": 519.0,
+ "volume": 13113816.0
+ },
+ {
+ "date": "2026-04-22",
+ "open": 513.5,
+ "high": 514.5,
+ "low": 502.0,
+ "close": 504.0,
+ "volume": 23170931.0
+ },
+ {
+ "date": "2026-04-23",
+ "open": 500.0,
+ "high": 502.0,
+ "low": 495.2,
+ "close": 495.2,
+ "volume": 23497267.0
+ },
+ {
+ "date": "2026-04-24",
+ "open": 487.0,
+ "high": 495.0,
+ "low": 487.0,
+ "close": 493.4,
+ "volume": 18566187.0
+ },
+ {
+ "date": "2026-04-27",
+ "open": 490.0,
+ "high": 491.0,
+ "low": 478.0,
+ "close": 478.6,
+ "volume": 45048027.0
+ },
+ {
+ "date": "2026-04-28",
+ "open": 476.0,
+ "high": 481.6,
+ "low": 472.0,
+ "close": 473.8,
+ "volume": 25793090.0
+ },
+ {
+ "date": "2026-04-29",
+ "open": 474.6,
+ "high": 480.6,
+ "low": 474.6,
+ "close": 479.2,
+ "volume": 19321018.0
+ },
+ {
+ "date": "2026-04-30",
+ "open": 474.0,
+ "high": 474.8,
+ "low": 463.2,
+ "close": 467.8,
+ "volume": 38406905.0
+ },
+ {
+ "date": "2026-05-04",
+ "open": 469.8,
+ "high": 478.8,
+ "low": 469.8,
+ "close": 473.0,
+ "volume": 23758824.0
+ },
+ {
+ "date": "2026-05-05",
+ "open": 469.0,
+ "high": 472.4,
+ "low": 465.6,
+ "close": 472.2,
+ "volume": 13004679.0
+ },
+ {
+ "date": "2026-05-06",
+ "open": 470.6,
+ "high": 473.4,
+ "low": 460.2,
+ "close": 463.0,
+ "volume": 44367227.0
+ },
+ {
+ "date": "2026-05-07",
+ "open": 472.2,
+ "high": 481.0,
+ "low": 472.2,
+ "close": 477.4,
+ "volume": 40989511.0
+ },
+ {
+ "date": "2026-05-08",
+ "open": 475.0,
+ "high": 475.6,
+ "low": 468.4,
+ "close": 471.4,
+ "volume": 25207039.0
+ },
+ {
+ "date": "2026-05-11",
+ "open": 465.0,
+ "high": 471.2,
+ "low": 463.6,
+ "close": 464.4,
+ "volume": 27814648.0
+ },
+ {
+ "date": "2026-05-12",
+ "open": 462.0,
+ "high": 469.0,
+ "low": 457.2,
+ "close": 457.2,
+ "volume": 32469707.0
+ },
+ {
+ "date": "2026-05-13",
+ "open": 456.0,
+ "high": 465.8,
+ "low": 454.0,
+ "close": 462.6,
+ "volume": 26616535.0
+ },
+ {
+ "date": "2026-05-14",
+ "open": 474.2,
+ "high": 479.6,
+ "low": 458.6,
+ "close": 460.2,
+ "volume": 39339032.0
+ },
+ {
+ "date": "2026-05-15",
+ "open": 459.0,
+ "high": 462.6,
+ "low": 454.2,
+ "close": 456.4,
+ "volume": 26449868.0
+ },
+ {
+ "date": "2026-05-18",
+ "open": 455.0,
+ "high": 457.8,
+ "low": 445.8,
+ "close": 449.2,
+ "volume": 29497076.0
+ },
+ {
+ "date": "2026-05-19",
+ "open": 449.2,
+ "high": 468.8,
+ "low": 448.6,
+ "close": 460.0,
+ "volume": 33736701.0
+ },
+ {
+ "date": "2026-05-20",
+ "open": 460.0,
+ "high": 463.4,
+ "low": 453.6,
+ "close": 455.2,
+ "volume": 18927606.0
+ },
+ {
+ "date": "2026-05-21",
+ "open": 460.0,
+ "high": 460.0,
+ "low": 438.4,
+ "close": 439.0,
+ "volume": 39653795.0
+ },
+ {
+ "date": "2026-05-22",
+ "open": 442.2,
+ "high": 445.0,
+ "low": 438.8,
+ "close": 441.4,
+ "volume": 23998219.0
+ },
+ {
+ "date": "2026-05-26",
+ "open": 438.0,
+ "high": 441.0,
+ "low": 432.0,
+ "close": 439.0,
+ "volume": 32795639.0
+ },
+ {
+ "date": "2026-05-27",
+ "open": 435.8,
+ "high": 442.6,
+ "low": 433.6,
+ "close": 434.4,
+ "volume": 24863984.0
+ },
+ {
+ "date": "2026-05-28",
+ "open": 431.0,
+ "high": 432.8,
+ "low": 420.4,
+ "close": 425.0,
+ "volume": 42196103.0
+ },
+ {
+ "date": "2026-05-29",
+ "open": 428.2,
+ "high": 438.4,
+ "low": 423.6,
+ "close": 427.2,
+ "volume": 48005475.0
+ },
+ {
+ "date": "2026-06-01",
+ "open": 432.4,
+ "high": 442.0,
+ "low": 430.0,
+ "close": 436.0,
+ "volume": 35164391.0
+ },
+ {
+ "date": "2026-06-02",
+ "open": 438.0,
+ "high": 484.8,
+ "low": 437.4,
+ "close": 481.6,
+ "volume": 101874275.0
+ },
+ {
+ "date": "2026-06-03",
+ "open": 484.0,
+ "high": 484.0,
+ "low": 461.6,
+ "close": 466.4,
+ "volume": 49104320.0
+ },
+ {
+ "date": "2026-06-04",
+ "open": 462.6,
+ "high": 468.6,
+ "low": 454.8,
+ "close": 459.0,
+ "volume": 29053909.0
+ },
+ {
+ "date": "2026-06-05",
+ "open": 461.6,
+ "high": 466.2,
+ "low": 452.2,
+ "close": 453.2,
+ "volume": 31649780.0
+ },
+ {
+ "date": "2026-06-08",
+ "open": 447.8,
+ "high": 458.2,
+ "low": 443.2,
+ "close": 446.4,
+ "volume": 29019096.0
+ },
+ {
+ "date": "2026-06-09",
+ "open": 443.8,
+ "high": 468.4,
+ "low": 443.2,
+ "close": 453.2,
+ "volume": 37387399.0
+ },
+ {
+ "date": "2026-06-10",
+ "open": 454.8,
+ "high": 471.0,
+ "low": 451.6,
+ "close": 465.6,
+ "volume": 35788237.0
+ },
+ {
+ "date": "2026-06-11",
+ "open": 469.8,
+ "high": 475.6,
+ "low": 455.0,
+ "close": 457.2,
+ "volume": 28580619.0
+ },
+ {
+ "date": "2026-06-12",
+ "open": 466.0,
+ "high": 467.0,
+ "low": 459.4,
+ "close": 463.6,
+ "volume": 22334646.0
+ },
+ {
+ "date": "2026-06-15",
+ "open": 475.0,
+ "high": 476.8,
+ "low": 457.8,
+ "close": 459.6,
+ "volume": 19748938.0
+ },
+ {
+ "date": "2026-06-16",
+ "open": 462.6,
+ "high": 462.6,
+ "low": 445.4,
+ "close": 447.4,
+ "volume": 24323142.0
+ },
+ {
+ "date": "2026-06-17",
+ "open": 445.6,
+ "high": 454.0,
+ "low": 445.4,
+ "close": 445.4,
+ "volume": 16962334.0
+ },
+ {
+ "date": "2026-06-18",
+ "open": 440.0,
+ "high": 446.2,
+ "low": 435.6,
+ "close": 440.2,
+ "volume": 30119117.0
+ },
+ {
+ "date": "2026-06-22",
+ "open": 439.0,
+ "high": 439.0,
+ "low": 428.4,
+ "close": 433.0,
+ "volume": 31563111.0
+ },
+ {
+ "date": "2026-06-23",
+ "open": 430.0,
+ "high": 432.4,
+ "low": 413.6,
+ "close": 414.8,
+ "volume": 43435789.0
+ },
+ {
+ "date": "2026-06-24",
+ "open": 414.0,
+ "high": 439.8,
+ "low": 412.6,
+ "close": 428.8,
+ "volume": 39958288.0
+ },
+ {
+ "date": "2026-06-25",
+ "open": 428.6,
+ "high": 428.6,
+ "low": 418.0,
+ "close": 421.4,
+ "volume": 29472428.0
+ },
+ {
+ "date": "2026-06-26",
+ "open": 418.0,
+ "high": 421.2,
+ "low": 411.0,
+ "close": 411.8,
+ "volume": 31872909.0
+ },
+ {
+ "date": "2026-06-29",
+ "open": 417.0,
+ "high": 432.0,
+ "low": 415.0,
+ "close": 420.2,
+ "volume": 33066070.0
+ },
+ {
+ "date": "2026-06-30",
+ "open": 421.2,
+ "high": 435.6,
+ "low": 418.4,
+ "close": 429.8,
+ "volume": 38994409.0
+ },
+ {
+ "date": "2026-07-02",
+ "open": 442.6,
+ "high": 447.0,
+ "low": 429.4,
+ "close": 430.2,
+ "volume": 40905100.0
+ },
+ {
+ "date": "2026-07-03",
+ "open": 433.0,
+ "high": 445.8,
+ "low": 431.2,
+ "close": 431.2,
+ "volume": 24957296.0
+ },
+ {
+ "date": "2026-07-06",
+ "open": 432.8,
+ "high": 453.4,
+ "low": 425.4,
+ "close": 452.0,
+ "volume": 41502083.0
+ },
+ {
+ "date": "2026-07-07",
+ "open": 459.0,
+ "high": 479.8,
+ "low": 457.0,
+ "close": 461.2,
+ "volume": 55418434.0
+ },
+ {
+ "date": "2026-07-08",
+ "open": 461.2,
+ "high": 482.8,
+ "low": 460.6,
+ "close": 478.8,
+ "volume": 56278627.0
+ },
+ {
+ "date": "2026-07-09",
+ "open": 479.0,
+ "high": 485.0,
+ "low": 467.2,
+ "close": 469.6,
+ "volume": 42402152.0
+ },
+ {
+ "date": "2026-07-10",
+ "open": 472.8,
+ "high": 473.6,
+ "low": 458.8,
+ "close": 460.2,
+ "volume": 40440298.0
+ },
+ {
+ "date": "2026-07-13",
+ "open": 463.2,
+ "high": 473.8,
+ "low": 456.2,
+ "close": 457.6,
+ "volume": 24291842.0
+ },
+ {
+ "date": "2026-07-14",
+ "open": 457.6,
+ "high": 459.2,
+ "low": 447.4,
+ "close": 456.2,
+ "volume": 25540540.0
+ },
+ {
+ "date": "2026-07-15",
+ "open": 467.6,
+ "high": 476.4,
+ "low": 455.4,
+ "close": 474.0,
+ "volume": 33780856.0
+ },
+ {
+ "date": "2026-07-16",
+ "open": 478.0,
+ "high": 494.8,
+ "low": 477.4,
+ "close": 484.0,
+ "volume": 42851475.0
+ },
+ {
+ "date": "2026-07-17",
+ "open": 488.8,
+ "high": 488.8,
+ "low": 458.0,
+ "close": 461.6,
+ "volume": 36237657.0
+ },
+ {
+ "date": "2026-07-20",
+ "open": 465.6,
+ "high": 481.8,
+ "low": 465.6,
+ "close": 477.8,
+ "volume": 30822839.0
+ },
+ {
+ "date": "2026-07-21",
+ "open": 478.2,
+ "high": 482.6,
+ "low": 472.8,
+ "close": 474.0,
+ "volume": 21362780.0
+ },
+ {
+ "date": "2026-07-22",
+ "open": 468.0,
+ "high": 468.0,
+ "low": 440.6,
+ "close": 440.6,
+ "volume": 66379871.0
+ },
+ {
+ "date": "2026-07-23",
+ "open": 440.0,
+ "high": 450.8,
+ "low": 439.0,
+ "close": 445.2,
+ "volume": 22888528.0
+ },
+ {
+ "date": "2026-07-24",
+ "open": 438.2,
+ "high": 438.8,
+ "low": 432.0,
+ "close": 434.6,
+ "volume": 22959603.0
+ },
+ {
+ "date": "2026-07-27",
+ "open": 438.8,
+ "high": 446.4,
+ "low": 435.4,
+ "close": 443.0,
+ "volume": 14454552.0
+ },
+ {
+ "date": "2026-07-28",
+ "open": 447.8,
+ "high": 452.0,
+ "low": 441.6,
+ "close": 447.2,
+ "volume": 18143997.0
+ },
+ {
+ "date": "2026-07-29",
+ "open": 453.0,
+ "high": 469.4,
+ "low": 450.0,
+ "close": 466.4,
+ "volume": 36203193.0
+ },
+ {
+ "date": "2026-07-30",
+ "open": 466.4,
+ "high": 475.0,
+ "low": 462.8,
+ "close": 471.8,
+ "volume": 31791979.0
+ },
+ {
+ "date": "2026-07-31",
+ "open": 470.0,
+ "high": 479.8,
+ "low": 462.0,
+ "close": 475.2,
+ "volume": 31100240.0
+ },
+ {
+ "date": "2026-08-03",
+ "open": 482.0,
+ "high": 491.0,
+ "low": 480.6,
+ "close": 490.4,
+ "volume": 38649910.0
+ },
+ {
+ "date": "2026-08-04",
+ "open": 491.0,
+ "high": 494.8,
+ "low": 480.8,
+ "close": 487.6,
+ "volume": 24860019.0
+ },
+ {
+ "date": "2026-08-05",
+ "open": 493.4,
+ "high": 497.8,
+ "low": 482.2,
+ "close": 492.2,
+ "volume": 25662478.0
+ },
+ {
+ "date": "2026-08-06",
+ "open": 491.0,
+ "high": 491.0,
+ "low": 479.0,
+ "close": 479.2,
+ "volume": 21801977.0
+ },
+ {
+ "date": "2026-08-07",
+ "open": 479.0,
+ "high": 483.2,
+ "low": 475.4,
+ "close": 478.8,
+ "volume": 16319939.0
+ },
+ {
+ "date": "2026-08-10",
+ "open": 479.0,
+ "high": 483.6,
+ "low": 476.4,
+ "close": 481.4,
+ "volume": 15508724.0
+ },
+ {
+ "date": "2026-08-11",
+ "open": 481.2,
+ "high": 483.8,
+ "low": 469.6,
+ "close": 470.8,
+ "volume": 19558079.0
+ },
+ {
+ "date": "2026-08-12",
+ "open": 464.6,
+ "high": 467.2,
+ "low": 456.2,
+ "close": 461.6,
+ "volume": 27593015.0
+ },
+ {
+ "date": "2026-08-13",
+ "open": 446.4,
+ "high": 452.2,
+ "low": 439.6,
+ "close": 441.0,
+ "volume": 66424623.0
+ },
+ {
+ "date": "2026-08-14",
+ "open": 436.0,
+ "high": 445.0,
+ "low": 436.0,
+ "close": 440.0,
+ "volume": 30601060.0
+ },
+ {
+ "date": "2026-08-17",
+ "open": 444.8,
+ "high": 450.4,
+ "low": 442.6,
+ "close": 446.4,
+ "volume": 19842808.0
+ },
+ {
+ "date": "2026-08-18",
+ "open": 444.2,
+ "high": 446.2,
+ "low": 437.6,
+ "close": 442.4,
+ "volume": 23218078.0
+ },
+ {
+ "date": "2026-08-19",
+ "open": 438.2,
+ "high": 449.4,
+ "low": 438.2,
+ "close": 447.2,
+ "volume": 19773887.0
+ },
+ {
+ "date": "2026-08-20",
+ "open": 454.6,
+ "high": 457.4,
+ "low": 448.8,
+ "close": 451.4,
+ "volume": 19621298.0
+ },
+ {
+ "date": "2026-08-21",
+ "open": 451.0,
+ "high": 457.2,
+ "low": 445.0,
+ "close": 457.0,
+ "volume": 22326906.0
+ },
+ {
+ "date": "2026-08-24",
+ "open": 450.0,
+ "high": 451.4,
+ "low": 438.4,
+ "close": 440.0,
+ "volume": 29180102.0
+ },
+ {
+ "date": "2026-08-25",
+ "open": 440.0,
+ "high": 444.6,
+ "low": 438.0,
+ "close": 442.0,
+ "volume": 13032108.0
+ },
+ {
+ "date": "2026-08-26",
+ "open": 445.0,
+ "high": 450.0,
+ "low": 443.2,
+ "close": 445.4,
+ "volume": 14643242.0
+ },
+ {
+ "date": "2026-08-27",
+ "open": 450.8,
+ "high": 451.8,
+ "low": 446.6,
+ "close": 447.8,
+ "volume": 11487100.0
+ },
+ {
+ "date": "2026-08-28",
+ "open": 444.0,
+ "high": 462.2,
+ "low": 443.4,
+ "close": 455.2,
+ "volume": 27742475.0
+ },
+ {
+ "date": "2026-08-31",
+ "open": 451.0,
+ "high": 456.2,
+ "low": 446.0,
+ "close": 453.0,
+ "volume": 20149770.0
+ },
+ {
+ "date": "2026-09-01",
+ "open": 446.4,
+ "high": 447.6,
+ "low": 440.6,
+ "close": 441.4,
+ "volume": 20289781.0
+ },
+ {
+ "date": "2026-09-02",
+ "open": 439.0,
+ "high": 441.4,
+ "low": 435.0,
+ "close": 438.2,
+ "volume": 21341328.0
+ },
+ {
+ "date": "2026-09-03",
+ "open": 444.2,
+ "high": 445.6,
+ "low": 433.0,
+ "close": 433.0,
+ "volume": 17387096.0
+ },
+ {
+ "date": "2026-09-04",
+ "open": 442.4,
+ "high": 447.6,
+ "low": 440.0,
+ "close": 442.8,
+ "volume": 24025286.0
+ },
+ {
+ "date": "2026-09-07",
+ "open": 440.6,
+ "high": 442.6,
+ "low": 438.2,
+ "close": 438.4,
+ "volume": 10442987.0
+ },
+ {
+ "date": "2026-09-08",
+ "open": 437.0,
+ "high": 439.8,
+ "low": 435.0,
+ "close": 435.4,
+ "volume": 10414838.0
+ },
+ {
+ "date": "2026-09-09",
+ "open": 436.2,
+ "high": 438.4,
+ "low": 432.8,
+ "close": 434.0,
+ "volume": 17643957.0
+ },
+ {
+ "date": "2026-09-10",
+ "open": 430.0,
+ "high": 430.8,
+ "low": 425.0,
+ "close": 425.6,
+ "volume": 22333165.0
+ },
+ {
+ "date": "2026-09-11",
+ "open": 419.4,
+ "high": 430.8,
+ "low": 419.4,
+ "close": 428.4,
+ "volume": 15628379.0
+ },
+ {
+ "date": "2026-09-14",
+ "open": 423.8,
+ "high": 435.4,
+ "low": 423.8,
+ "close": 430.6,
+ "volume": 11363985.0
+ },
+ {
+ "date": "2026-09-15",
+ "open": 428.0,
+ "high": 446.0,
+ "low": 428.0,
+ "close": 438.8,
+ "volume": 21791117.0
+ },
+ {
+ "date": "2026-09-16",
+ "open": 438.8,
+ "high": 438.8,
+ "low": 432.6,
+ "close": 433.4,
+ "volume": 12686315.0
+ },
+ {
+ "date": "2026-09-17",
+ "open": 426.2,
+ "high": 431.0,
+ "low": 425.0,
+ "close": 426.0,
+ "volume": 16185147.0
+ },
+ {
+ "date": "2026-09-18",
+ "open": 428.0,
+ "high": 430.4,
+ "low": 419.0,
+ "close": 419.0,
+ "volume": 28796138.0
+ },
+ {
+ "date": "2026-09-21",
+ "open": 424.6,
+ "high": 434.8,
+ "low": 423.0,
+ "close": 430.0,
+ "volume": 19669333.0
+ },
+ {
+ "date": "2026-09-22",
+ "open": 442.8,
+ "high": 463.4,
+ "low": 442.0,
+ "close": 451.6,
+ "volume": 70723438.0
+ },
+ {
+ "date": "2026-09-23",
+ "open": 453.4,
+ "high": 454.4,
+ "low": 438.6,
+ "close": 441.0,
+ "volume": 22309793.0
+ },
+ {
+ "date": "2026-09-24",
+ "open": 435.0,
+ "high": 439.8,
+ "low": 433.4,
+ "close": 438.4,
+ "volume": 14277944.0
+ },
+ {
+ "date": "2026-09-25",
+ "open": 433.8,
+ "high": 437.2,
+ "low": 431.2,
+ "close": 436.6,
+ "volume": 9113746.0
+ },
+ {
+ "date": "2026-09-28",
+ "open": 441.4,
+ "high": 447.0,
+ "low": 438.6,
+ "close": 439.8,
+ "volume": 15335550.0
+ },
+ {
+ "date": "2026-09-29",
+ "open": 439.4,
+ "high": 439.4,
+ "low": 431.6,
+ "close": 432.0,
+ "volume": 18015236.0
+ },
+ {
+ "date": "2026-09-30",
+ "open": 430.0,
+ "high": 432.2,
+ "low": 424.4,
+ "close": 431.0,
+ "volume": 22634903.0
+ },
+ {
+ "date": "2026-10-02",
+ "open": 422.0,
+ "high": 425.0,
+ "low": 419.8,
+ "close": 421.2,
+ "volume": 19108045.0
+ },
+ {
+ "date": "2026-10-05",
+ "open": 420.0,
+ "high": 423.6,
+ "low": 416.4,
+ "close": 423.0,
+ "volume": 8709438.0
+ },
+ {
+ "date": "2026-10-06",
+ "open": 426.4,
+ "high": 429.2,
+ "low": 425.6,
+ "close": 428.2,
+ "volume": 10030081.0
+ },
+ {
+ "date": "2026-10-07",
+ "open": 425.6,
+ "high": 426.0,
+ "low": 419.2,
+ "close": 420.6,
+ "volume": 12436640.0
+ },
+ {
+ "date": "2026-10-08",
+ "open": 422.0,
+ "high": 424.6,
+ "low": 411.2,
+ "close": 411.4,
+ "volume": 30202875.0
+ },
+ {
+ "date": "2026-10-09",
+ "open": 415.0,
+ "high": 425.8,
+ "low": 414.8,
+ "close": 424.8,
+ "volume": 20422500.0
+ },
+ {
+ "date": "2026-10-12",
+ "open": 428.4,
+ "high": 430.4,
+ "low": 423.4,
+ "close": 425.8,
+ "volume": 14011738.0
+ },
+ {
+ "date": "2026-10-13",
+ "open": 421.0,
+ "high": 425.6,
+ "low": 419.8,
+ "close": 425.2,
+ "volume": 12724935.0
+ },
+ {
+ "date": "2026-10-14",
+ "open": 421.4,
+ "high": 430.4,
+ "low": 416.4,
+ "close": 423.4,
+ "volume": 19933548.0
+ },
+ {
+ "date": "2026-10-15",
+ "open": 415.0,
+ "high": 422.6,
+ "low": 414.0,
+ "close": 417.8,
+ "volume": 20676017.0
+ },
+ {
+ "date": "2026-10-16",
+ "open": 424.0,
+ "high": 428.8,
+ "low": 415.8,
+ "close": 417.8,
+ "volume": 18752869.0
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/paper_trade/market/synthetic_holiday_gap.json b/agent/tests/fixtures/paper_trade/market/synthetic_holiday_gap.json
new file mode 100644
index 000000000..bfcd20fd1
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/market/synthetic_holiday_gap.json
@@ -0,0 +1,230 @@
+{
+ "schema": "paper_trade.market_fixture/v1",
+ "market": "us_equity",
+ "symbol": "SYNTH-GAP",
+ "source": "synthetic",
+ "price_caliber": "raw",
+ "volume_unit": "shares",
+ "window": {
+ "start": "2026-03-02",
+ "end": "2026-04-10"
+ },
+ "caliber_note": "authored unadjusted daily series for the calendar fail-closed seam (VD-5): weekends are implicit; the two documented gaps are trading-day absences, not calendar artifacts",
+ "synthetic_construction": "24 weekday bars in five segments (5+4+5+5+5) from 2026-03-02 to 2026-04-10; open=prev close, close=100.0+0.25*i, high=max(o,c)+0.5, low=min(o,c)-0.5, volume=1000000.0; values binary-exact quarters. Gap 1 skips Mon 2026-03-09 (single holiday on a long weekend); Gap 2 skips the whole week 2026-03-23..2026-03-27 (multi-day closure, 5 trading days). gap_samples below pins both so tests can assert the authored gaps without hardcoding dates twice.",
+ "gap_samples": [
+ {
+ "after_date": "2026-03-06",
+ "resume_date": "2026-03-10",
+ "missing_weekdays": [
+ "2026-03-09"
+ ],
+ "label": "single_holiday_long_weekend"
+ },
+ {
+ "after_date": "2026-03-20",
+ "resume_date": "2026-03-30",
+ "missing_weekdays": [
+ "2026-03-23",
+ "2026-03-24",
+ "2026-03-25",
+ "2026-03-26",
+ "2026-03-27"
+ ],
+ "label": "multi_day_closure"
+ }
+ ],
+ "bars": [
+ {
+ "date": "2026-03-02",
+ "open": 100.0,
+ "high": 100.5,
+ "low": 99.5,
+ "close": 100.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-03",
+ "open": 100.0,
+ "high": 100.75,
+ "low": 99.5,
+ "close": 100.25,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-04",
+ "open": 100.25,
+ "high": 101.0,
+ "low": 99.75,
+ "close": 100.5,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-05",
+ "open": 100.5,
+ "high": 101.25,
+ "low": 100.0,
+ "close": 100.75,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-06",
+ "open": 100.75,
+ "high": 101.5,
+ "low": 100.25,
+ "close": 101.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-10",
+ "open": 101.0,
+ "high": 101.75,
+ "low": 100.5,
+ "close": 101.25,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-11",
+ "open": 101.25,
+ "high": 102.0,
+ "low": 100.75,
+ "close": 101.5,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-12",
+ "open": 101.5,
+ "high": 102.25,
+ "low": 101.0,
+ "close": 101.75,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-13",
+ "open": 101.75,
+ "high": 102.5,
+ "low": 101.25,
+ "close": 102.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-16",
+ "open": 102.0,
+ "high": 102.75,
+ "low": 101.5,
+ "close": 102.25,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-17",
+ "open": 102.25,
+ "high": 103.0,
+ "low": 101.75,
+ "close": 102.5,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-18",
+ "open": 102.5,
+ "high": 103.25,
+ "low": 102.0,
+ "close": 102.75,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-19",
+ "open": 102.75,
+ "high": 103.5,
+ "low": 102.25,
+ "close": 103.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-20",
+ "open": 103.0,
+ "high": 103.75,
+ "low": 102.5,
+ "close": 103.25,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-30",
+ "open": 103.25,
+ "high": 104.0,
+ "low": 102.75,
+ "close": 103.5,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-03-31",
+ "open": 103.5,
+ "high": 104.25,
+ "low": 103.0,
+ "close": 103.75,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-01",
+ "open": 103.75,
+ "high": 104.5,
+ "low": 103.25,
+ "close": 104.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-02",
+ "open": 104.0,
+ "high": 104.75,
+ "low": 103.5,
+ "close": 104.25,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-03",
+ "open": 104.25,
+ "high": 105.0,
+ "low": 103.75,
+ "close": 104.5,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-06",
+ "open": 104.5,
+ "high": 105.25,
+ "low": 104.0,
+ "close": 104.75,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-07",
+ "open": 104.75,
+ "high": 105.5,
+ "low": 104.25,
+ "close": 105.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-08",
+ "open": 105.0,
+ "high": 105.75,
+ "low": 104.5,
+ "close": 105.25,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-09",
+ "open": 105.25,
+ "high": 106.0,
+ "low": 104.75,
+ "close": 105.5,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-04-10",
+ "open": 105.5,
+ "high": 106.25,
+ "low": 105.0,
+ "close": 105.75,
+ "volume": 1000000.0
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/paper_trade/market/synthetic_split_4to1.json b/agent/tests/fixtures/paper_trade/market/synthetic_split_4to1.json
new file mode 100644
index 000000000..209975d53
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/market/synthetic_split_4to1.json
@@ -0,0 +1,1154 @@
+{
+ "schema": "paper_trade.market_fixture/v1",
+ "market": "us_equity",
+ "symbol": "SYNTH-4TO1",
+ "source": "synthetic",
+ "price_caliber": "raw",
+ "volume_unit": "shares",
+ "window": {
+ "start": "2026-01-05",
+ "end": "2026-07-20"
+ },
+ "caliber_note": "authored unadjusted daily series: the 4:1 split cliff is present by construction and is NOT smoothed, mirroring the raw sina/us caliber the T7 detector must handle",
+ "synthetic_construction": "141 consecutive weekdays from 2026-01-05; bars 0..19 pre-split with open=prev close, close=400.0+4.0*i, high=max(o,c)+1.0, low=min(o,c)-1.0, volume=1000000.0; bar 20 is the ex-date: every OHLC is exactly the prior close / 4 (476.0 -> 119.0, close-to-close ratio exactly 0.25) and volume is exactly 4x (1000000 -> 4000000, the same-direction multiple confirmation VD-6 requires); bars 21..140 drift with close=119.0+0.5*k and volume=4000000.0. All values are binary-exact quarters; no rounding anywhere. 120 bars follow the ex-date so a K=120 trading-day lookback (VD-6/B3 fetch window) puts the event exactly at the window edge.",
+ "split_event": {
+ "ex_date": "2026-02-02",
+ "ratio": "4:1",
+ "close_before": 476.0,
+ "open_on_ex": 119.0,
+ "close_after": 119.0,
+ "volume_multiple": 4.0,
+ "bar_index": 20,
+ "bars_after_ex": 120
+ },
+ "bars": [
+ {
+ "date": "2026-01-05",
+ "open": 400.0,
+ "high": 401.0,
+ "low": 399.0,
+ "close": 400.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-06",
+ "open": 400.0,
+ "high": 405.0,
+ "low": 399.0,
+ "close": 404.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-07",
+ "open": 404.0,
+ "high": 409.0,
+ "low": 403.0,
+ "close": 408.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-08",
+ "open": 408.0,
+ "high": 413.0,
+ "low": 407.0,
+ "close": 412.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-09",
+ "open": 412.0,
+ "high": 417.0,
+ "low": 411.0,
+ "close": 416.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-12",
+ "open": 416.0,
+ "high": 421.0,
+ "low": 415.0,
+ "close": 420.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-13",
+ "open": 420.0,
+ "high": 425.0,
+ "low": 419.0,
+ "close": 424.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-14",
+ "open": 424.0,
+ "high": 429.0,
+ "low": 423.0,
+ "close": 428.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-15",
+ "open": 428.0,
+ "high": 433.0,
+ "low": 427.0,
+ "close": 432.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-16",
+ "open": 432.0,
+ "high": 437.0,
+ "low": 431.0,
+ "close": 436.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-19",
+ "open": 436.0,
+ "high": 441.0,
+ "low": 435.0,
+ "close": 440.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-20",
+ "open": 440.0,
+ "high": 445.0,
+ "low": 439.0,
+ "close": 444.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-21",
+ "open": 444.0,
+ "high": 449.0,
+ "low": 443.0,
+ "close": 448.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-22",
+ "open": 448.0,
+ "high": 453.0,
+ "low": 447.0,
+ "close": 452.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-23",
+ "open": 452.0,
+ "high": 457.0,
+ "low": 451.0,
+ "close": 456.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-26",
+ "open": 456.0,
+ "high": 461.0,
+ "low": 455.0,
+ "close": 460.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-27",
+ "open": 460.0,
+ "high": 465.0,
+ "low": 459.0,
+ "close": 464.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-28",
+ "open": 464.0,
+ "high": 469.0,
+ "low": 463.0,
+ "close": 468.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-29",
+ "open": 468.0,
+ "high": 473.0,
+ "low": 467.0,
+ "close": 472.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-01-30",
+ "open": 472.0,
+ "high": 477.0,
+ "low": 471.0,
+ "close": 476.0,
+ "volume": 1000000.0
+ },
+ {
+ "date": "2026-02-02",
+ "open": 119.0,
+ "high": 120.0,
+ "low": 118.0,
+ "close": 119.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-03",
+ "open": 119.0,
+ "high": 120.0,
+ "low": 118.5,
+ "close": 119.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-04",
+ "open": 119.5,
+ "high": 120.5,
+ "low": 119.0,
+ "close": 120.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-05",
+ "open": 120.0,
+ "high": 121.0,
+ "low": 119.5,
+ "close": 120.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-06",
+ "open": 120.5,
+ "high": 121.5,
+ "low": 120.0,
+ "close": 121.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-09",
+ "open": 121.0,
+ "high": 122.0,
+ "low": 120.5,
+ "close": 121.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-10",
+ "open": 121.5,
+ "high": 122.5,
+ "low": 121.0,
+ "close": 122.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-11",
+ "open": 122.0,
+ "high": 123.0,
+ "low": 121.5,
+ "close": 122.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-12",
+ "open": 122.5,
+ "high": 123.5,
+ "low": 122.0,
+ "close": 123.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-13",
+ "open": 123.0,
+ "high": 124.0,
+ "low": 122.5,
+ "close": 123.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-16",
+ "open": 123.5,
+ "high": 124.5,
+ "low": 123.0,
+ "close": 124.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-17",
+ "open": 124.0,
+ "high": 125.0,
+ "low": 123.5,
+ "close": 124.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-18",
+ "open": 124.5,
+ "high": 125.5,
+ "low": 124.0,
+ "close": 125.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-19",
+ "open": 125.0,
+ "high": 126.0,
+ "low": 124.5,
+ "close": 125.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-20",
+ "open": 125.5,
+ "high": 126.5,
+ "low": 125.0,
+ "close": 126.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-23",
+ "open": 126.0,
+ "high": 127.0,
+ "low": 125.5,
+ "close": 126.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-24",
+ "open": 126.5,
+ "high": 127.5,
+ "low": 126.0,
+ "close": 127.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-25",
+ "open": 127.0,
+ "high": 128.0,
+ "low": 126.5,
+ "close": 127.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-26",
+ "open": 127.5,
+ "high": 128.5,
+ "low": 127.0,
+ "close": 128.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-02-27",
+ "open": 128.0,
+ "high": 129.0,
+ "low": 127.5,
+ "close": 128.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-02",
+ "open": 128.5,
+ "high": 129.5,
+ "low": 128.0,
+ "close": 129.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-03",
+ "open": 129.0,
+ "high": 130.0,
+ "low": 128.5,
+ "close": 129.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-04",
+ "open": 129.5,
+ "high": 130.5,
+ "low": 129.0,
+ "close": 130.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-05",
+ "open": 130.0,
+ "high": 131.0,
+ "low": 129.5,
+ "close": 130.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-06",
+ "open": 130.5,
+ "high": 131.5,
+ "low": 130.0,
+ "close": 131.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-09",
+ "open": 131.0,
+ "high": 132.0,
+ "low": 130.5,
+ "close": 131.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-10",
+ "open": 131.5,
+ "high": 132.5,
+ "low": 131.0,
+ "close": 132.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-11",
+ "open": 132.0,
+ "high": 133.0,
+ "low": 131.5,
+ "close": 132.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-12",
+ "open": 132.5,
+ "high": 133.5,
+ "low": 132.0,
+ "close": 133.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-13",
+ "open": 133.0,
+ "high": 134.0,
+ "low": 132.5,
+ "close": 133.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-16",
+ "open": 133.5,
+ "high": 134.5,
+ "low": 133.0,
+ "close": 134.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-17",
+ "open": 134.0,
+ "high": 135.0,
+ "low": 133.5,
+ "close": 134.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-18",
+ "open": 134.5,
+ "high": 135.5,
+ "low": 134.0,
+ "close": 135.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-19",
+ "open": 135.0,
+ "high": 136.0,
+ "low": 134.5,
+ "close": 135.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-20",
+ "open": 135.5,
+ "high": 136.5,
+ "low": 135.0,
+ "close": 136.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-23",
+ "open": 136.0,
+ "high": 137.0,
+ "low": 135.5,
+ "close": 136.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-24",
+ "open": 136.5,
+ "high": 137.5,
+ "low": 136.0,
+ "close": 137.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-25",
+ "open": 137.0,
+ "high": 138.0,
+ "low": 136.5,
+ "close": 137.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-26",
+ "open": 137.5,
+ "high": 138.5,
+ "low": 137.0,
+ "close": 138.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-27",
+ "open": 138.0,
+ "high": 139.0,
+ "low": 137.5,
+ "close": 138.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-30",
+ "open": 138.5,
+ "high": 139.5,
+ "low": 138.0,
+ "close": 139.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-03-31",
+ "open": 139.0,
+ "high": 140.0,
+ "low": 138.5,
+ "close": 139.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-01",
+ "open": 139.5,
+ "high": 140.5,
+ "low": 139.0,
+ "close": 140.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-02",
+ "open": 140.0,
+ "high": 141.0,
+ "low": 139.5,
+ "close": 140.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-03",
+ "open": 140.5,
+ "high": 141.5,
+ "low": 140.0,
+ "close": 141.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-06",
+ "open": 141.0,
+ "high": 142.0,
+ "low": 140.5,
+ "close": 141.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-07",
+ "open": 141.5,
+ "high": 142.5,
+ "low": 141.0,
+ "close": 142.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-08",
+ "open": 142.0,
+ "high": 143.0,
+ "low": 141.5,
+ "close": 142.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-09",
+ "open": 142.5,
+ "high": 143.5,
+ "low": 142.0,
+ "close": 143.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-10",
+ "open": 143.0,
+ "high": 144.0,
+ "low": 142.5,
+ "close": 143.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-13",
+ "open": 143.5,
+ "high": 144.5,
+ "low": 143.0,
+ "close": 144.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-14",
+ "open": 144.0,
+ "high": 145.0,
+ "low": 143.5,
+ "close": 144.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-15",
+ "open": 144.5,
+ "high": 145.5,
+ "low": 144.0,
+ "close": 145.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-16",
+ "open": 145.0,
+ "high": 146.0,
+ "low": 144.5,
+ "close": 145.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-17",
+ "open": 145.5,
+ "high": 146.5,
+ "low": 145.0,
+ "close": 146.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-20",
+ "open": 146.0,
+ "high": 147.0,
+ "low": 145.5,
+ "close": 146.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-21",
+ "open": 146.5,
+ "high": 147.5,
+ "low": 146.0,
+ "close": 147.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-22",
+ "open": 147.0,
+ "high": 148.0,
+ "low": 146.5,
+ "close": 147.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-23",
+ "open": 147.5,
+ "high": 148.5,
+ "low": 147.0,
+ "close": 148.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-24",
+ "open": 148.0,
+ "high": 149.0,
+ "low": 147.5,
+ "close": 148.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-27",
+ "open": 148.5,
+ "high": 149.5,
+ "low": 148.0,
+ "close": 149.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-28",
+ "open": 149.0,
+ "high": 150.0,
+ "low": 148.5,
+ "close": 149.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-29",
+ "open": 149.5,
+ "high": 150.5,
+ "low": 149.0,
+ "close": 150.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-04-30",
+ "open": 150.0,
+ "high": 151.0,
+ "low": 149.5,
+ "close": 150.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-01",
+ "open": 150.5,
+ "high": 151.5,
+ "low": 150.0,
+ "close": 151.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-04",
+ "open": 151.0,
+ "high": 152.0,
+ "low": 150.5,
+ "close": 151.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-05",
+ "open": 151.5,
+ "high": 152.5,
+ "low": 151.0,
+ "close": 152.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-06",
+ "open": 152.0,
+ "high": 153.0,
+ "low": 151.5,
+ "close": 152.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-07",
+ "open": 152.5,
+ "high": 153.5,
+ "low": 152.0,
+ "close": 153.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-08",
+ "open": 153.0,
+ "high": 154.0,
+ "low": 152.5,
+ "close": 153.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-11",
+ "open": 153.5,
+ "high": 154.5,
+ "low": 153.0,
+ "close": 154.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-12",
+ "open": 154.0,
+ "high": 155.0,
+ "low": 153.5,
+ "close": 154.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-13",
+ "open": 154.5,
+ "high": 155.5,
+ "low": 154.0,
+ "close": 155.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-14",
+ "open": 155.0,
+ "high": 156.0,
+ "low": 154.5,
+ "close": 155.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-15",
+ "open": 155.5,
+ "high": 156.5,
+ "low": 155.0,
+ "close": 156.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-18",
+ "open": 156.0,
+ "high": 157.0,
+ "low": 155.5,
+ "close": 156.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-19",
+ "open": 156.5,
+ "high": 157.5,
+ "low": 156.0,
+ "close": 157.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-20",
+ "open": 157.0,
+ "high": 158.0,
+ "low": 156.5,
+ "close": 157.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-21",
+ "open": 157.5,
+ "high": 158.5,
+ "low": 157.0,
+ "close": 158.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-22",
+ "open": 158.0,
+ "high": 159.0,
+ "low": 157.5,
+ "close": 158.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-25",
+ "open": 158.5,
+ "high": 159.5,
+ "low": 158.0,
+ "close": 159.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-26",
+ "open": 159.0,
+ "high": 160.0,
+ "low": 158.5,
+ "close": 159.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-27",
+ "open": 159.5,
+ "high": 160.5,
+ "low": 159.0,
+ "close": 160.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-28",
+ "open": 160.0,
+ "high": 161.0,
+ "low": 159.5,
+ "close": 160.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-05-29",
+ "open": 160.5,
+ "high": 161.5,
+ "low": 160.0,
+ "close": 161.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-01",
+ "open": 161.0,
+ "high": 162.0,
+ "low": 160.5,
+ "close": 161.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-02",
+ "open": 161.5,
+ "high": 162.5,
+ "low": 161.0,
+ "close": 162.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-03",
+ "open": 162.0,
+ "high": 163.0,
+ "low": 161.5,
+ "close": 162.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-04",
+ "open": 162.5,
+ "high": 163.5,
+ "low": 162.0,
+ "close": 163.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-05",
+ "open": 163.0,
+ "high": 164.0,
+ "low": 162.5,
+ "close": 163.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-08",
+ "open": 163.5,
+ "high": 164.5,
+ "low": 163.0,
+ "close": 164.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-09",
+ "open": 164.0,
+ "high": 165.0,
+ "low": 163.5,
+ "close": 164.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-10",
+ "open": 164.5,
+ "high": 165.5,
+ "low": 164.0,
+ "close": 165.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-11",
+ "open": 165.0,
+ "high": 166.0,
+ "low": 164.5,
+ "close": 165.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-12",
+ "open": 165.5,
+ "high": 166.5,
+ "low": 165.0,
+ "close": 166.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-15",
+ "open": 166.0,
+ "high": 167.0,
+ "low": 165.5,
+ "close": 166.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-16",
+ "open": 166.5,
+ "high": 167.5,
+ "low": 166.0,
+ "close": 167.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-17",
+ "open": 167.0,
+ "high": 168.0,
+ "low": 166.5,
+ "close": 167.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-18",
+ "open": 167.5,
+ "high": 168.5,
+ "low": 167.0,
+ "close": 168.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-19",
+ "open": 168.0,
+ "high": 169.0,
+ "low": 167.5,
+ "close": 168.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-22",
+ "open": 168.5,
+ "high": 169.5,
+ "low": 168.0,
+ "close": 169.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-23",
+ "open": 169.0,
+ "high": 170.0,
+ "low": 168.5,
+ "close": 169.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-24",
+ "open": 169.5,
+ "high": 170.5,
+ "low": 169.0,
+ "close": 170.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-25",
+ "open": 170.0,
+ "high": 171.0,
+ "low": 169.5,
+ "close": 170.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-26",
+ "open": 170.5,
+ "high": 171.5,
+ "low": 170.0,
+ "close": 171.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-29",
+ "open": 171.0,
+ "high": 172.0,
+ "low": 170.5,
+ "close": 171.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-06-30",
+ "open": 171.5,
+ "high": 172.5,
+ "low": 171.0,
+ "close": 172.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-01",
+ "open": 172.0,
+ "high": 173.0,
+ "low": 171.5,
+ "close": 172.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-02",
+ "open": 172.5,
+ "high": 173.5,
+ "low": 172.0,
+ "close": 173.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-03",
+ "open": 173.0,
+ "high": 174.0,
+ "low": 172.5,
+ "close": 173.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-06",
+ "open": 173.5,
+ "high": 174.5,
+ "low": 173.0,
+ "close": 174.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-07",
+ "open": 174.0,
+ "high": 175.0,
+ "low": 173.5,
+ "close": 174.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-08",
+ "open": 174.5,
+ "high": 175.5,
+ "low": 174.0,
+ "close": 175.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-09",
+ "open": 175.0,
+ "high": 176.0,
+ "low": 174.5,
+ "close": 175.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-10",
+ "open": 175.5,
+ "high": 176.5,
+ "low": 175.0,
+ "close": 176.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-13",
+ "open": 176.0,
+ "high": 177.0,
+ "low": 175.5,
+ "close": 176.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-14",
+ "open": 176.5,
+ "high": 177.5,
+ "low": 176.0,
+ "close": 177.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-15",
+ "open": 177.0,
+ "high": 178.0,
+ "low": 176.5,
+ "close": 177.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-16",
+ "open": 177.5,
+ "high": 178.5,
+ "low": 177.0,
+ "close": 178.0,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-17",
+ "open": 178.0,
+ "high": 179.0,
+ "low": 177.5,
+ "close": 178.5,
+ "volume": 4000000.0
+ },
+ {
+ "date": "2026-07-20",
+ "open": 178.5,
+ "high": 179.5,
+ "low": 178.0,
+ "close": 179.0,
+ "volume": 4000000.0
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/paper_trade/market/us_AAPL_sina.json b/agent/tests/fixtures/paper_trade/market/us_AAPL_sina.json
new file mode 100644
index 000000000..89994e6e8
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/market/us_AAPL_sina.json
@@ -0,0 +1,2134 @@
+{
+ "schema": "paper_trade.market_fixture/v1",
+ "market": "us_equity",
+ "symbol": "AAPL.US",
+ "source": "sina",
+ "price_caliber": "raw",
+ "volume_unit": null,
+ "volume_unit_note": "the sina loader declares no volume_units; US bars carry volume_unit=None (sina_loader.py has no such class attribute)",
+ "request_url": "https://stock.finance.sina.com.cn/usstock/api/jsonp_v2.php/var%20x=/US_MinKService.getDailyK?symbol=AAPL",
+ "request_headers": {
+ "User-Agent": "Mozilla/5.0",
+ "Referer": "https://stock.finance.sina.com.cn/"
+ },
+ "window": {
+ "start": "2025-10-01",
+ "end": "2026-10-16"
+ },
+ "window_note": "sina serves the full history (1984-09-07 onward) with no window parameter; bars are clipped to the window at record time, the same clip as sina_loader.py:115-118.",
+ "recorded_at_utc": "2026-10-18T14:32:36Z",
+ "caliber_note": "raw / unadjusted — no split scaling applied by the source; a close-to-close read across the 2020-08-31 4:1 ex-date reads ~0.2585. Pinned by registry.py PRICE_CALIBER_BY_SOURCE['sina']='raw' and live-confirmed 2026-10-18 (STEP0-LANE-A A1/A2); the recorded window itself does not contain that ex-date.",
+ "drop_stats": {
+ "wire_rows": 10055,
+ "dropped_unparseable": 0,
+ "dropped_out_of_window": 9792,
+ "dropped_duplicate_dates": 0,
+ "dropped_dirty_ohlc": 0
+ },
+ "bars": [
+ {
+ "date": "2025-10-01",
+ "open": 255.04,
+ "high": 258.79,
+ "low": 254.93,
+ "close": 255.45,
+ "volume": 48713820.0
+ },
+ {
+ "date": "2025-10-02",
+ "open": 256.57,
+ "high": 258.18,
+ "low": 254.15,
+ "close": 257.13,
+ "volume": 42630179.0
+ },
+ {
+ "date": "2025-10-03",
+ "open": 254.66,
+ "high": 259.24,
+ "low": 253.95,
+ "close": 258.02,
+ "volume": 49155614.0
+ },
+ {
+ "date": "2025-10-06",
+ "open": 257.99,
+ "high": 259.07,
+ "low": 255.05,
+ "close": 256.69,
+ "volume": 44664081.0
+ },
+ {
+ "date": "2025-10-07",
+ "open": 256.81,
+ "high": 257.4,
+ "low": 255.43,
+ "close": 256.48,
+ "volume": 31955297.0
+ },
+ {
+ "date": "2025-10-08",
+ "open": 256.52,
+ "high": 258.52,
+ "low": 256.11,
+ "close": 258.06,
+ "volume": 36496845.0
+ },
+ {
+ "date": "2025-10-09",
+ "open": 257.81,
+ "high": 258.0,
+ "low": 253.14,
+ "close": 254.04,
+ "volume": 38321900.0
+ },
+ {
+ "date": "2025-10-10",
+ "open": 254.94,
+ "high": 256.38,
+ "low": 244.0,
+ "close": 245.27,
+ "volume": 61999050.0
+ },
+ {
+ "date": "2025-10-13",
+ "open": 249.38,
+ "high": 249.69,
+ "low": 245.56,
+ "close": 247.66,
+ "volume": 38142755.0
+ },
+ {
+ "date": "2025-10-14",
+ "open": 246.6,
+ "high": 248.84,
+ "low": 244.7,
+ "close": 247.77,
+ "volume": 35477865.0
+ },
+ {
+ "date": "2025-10-15",
+ "open": 249.49,
+ "high": 251.82,
+ "low": 247.47,
+ "close": 249.34,
+ "volume": 33893577.0
+ },
+ {
+ "date": "2025-10-16",
+ "open": 248.25,
+ "high": 249.04,
+ "low": 245.13,
+ "close": 247.45,
+ "volume": 39776781.0
+ },
+ {
+ "date": "2025-10-17",
+ "open": 248.02,
+ "high": 253.38,
+ "low": 247.27,
+ "close": 252.29,
+ "volume": 49146662.0
+ },
+ {
+ "date": "2025-10-20",
+ "open": 255.88,
+ "high": 264.38,
+ "low": 255.63,
+ "close": 262.24,
+ "volume": 90483005.0
+ },
+ {
+ "date": "2025-10-21",
+ "open": 261.88,
+ "high": 265.29,
+ "low": 261.83,
+ "close": 262.77,
+ "volume": 46695671.0
+ },
+ {
+ "date": "2025-10-22",
+ "open": 262.65,
+ "high": 262.85,
+ "low": 255.43,
+ "close": 258.45,
+ "volume": 45015182.0
+ },
+ {
+ "date": "2025-10-23",
+ "open": 259.94,
+ "high": 260.62,
+ "low": 258.01,
+ "close": 259.58,
+ "volume": 32754925.0
+ },
+ {
+ "date": "2025-10-24",
+ "open": 261.19,
+ "high": 264.13,
+ "low": 259.18,
+ "close": 262.82,
+ "volume": 38253714.0
+ },
+ {
+ "date": "2025-10-27",
+ "open": 264.88,
+ "high": 269.12,
+ "low": 264.65,
+ "close": 268.81,
+ "volume": 44888152.0
+ },
+ {
+ "date": "2025-10-28",
+ "open": 268.99,
+ "high": 269.89,
+ "low": 268.15,
+ "close": 269.0,
+ "volume": 41534759.0
+ },
+ {
+ "date": "2025-10-29",
+ "open": 269.27,
+ "high": 271.41,
+ "low": 267.11,
+ "close": 269.7,
+ "volume": 51086687.0
+ },
+ {
+ "date": "2025-10-30",
+ "open": 271.99,
+ "high": 274.14,
+ "low": 268.48,
+ "close": 271.4,
+ "volume": 69886534.0
+ },
+ {
+ "date": "2025-10-31",
+ "open": 276.99,
+ "high": 277.32,
+ "low": 269.16,
+ "close": 270.37,
+ "volume": 86167061.0
+ },
+ {
+ "date": "2025-11-03",
+ "open": 270.42,
+ "high": 270.85,
+ "low": 266.25,
+ "close": 269.05,
+ "volume": 50194575.0
+ },
+ {
+ "date": "2025-11-04",
+ "open": 268.32,
+ "high": 271.49,
+ "low": 267.62,
+ "close": 270.04,
+ "volume": 49274846.0
+ },
+ {
+ "date": "2025-11-05",
+ "open": 268.61,
+ "high": 271.7,
+ "low": 266.93,
+ "close": 270.14,
+ "volume": 43682531.0
+ },
+ {
+ "date": "2025-11-06",
+ "open": 267.89,
+ "high": 273.4,
+ "low": 267.89,
+ "close": 269.77,
+ "volume": 51203783.0
+ },
+ {
+ "date": "2025-11-07",
+ "open": 269.8,
+ "high": 272.29,
+ "low": 266.77,
+ "close": 268.47,
+ "volume": 48227176.0
+ },
+ {
+ "date": "2025-11-10",
+ "open": 268.96,
+ "high": 273.73,
+ "low": 267.45,
+ "close": 269.43,
+ "volume": 41312151.0
+ },
+ {
+ "date": "2025-11-11",
+ "open": 269.81,
+ "high": 275.91,
+ "low": 269.8,
+ "close": 275.25,
+ "volume": 46208200.0
+ },
+ {
+ "date": "2025-11-12",
+ "open": 275.0,
+ "high": 275.73,
+ "low": 271.7,
+ "close": 273.47,
+ "volume": 48397981.0
+ },
+ {
+ "date": "2025-11-13",
+ "open": 274.11,
+ "high": 276.7,
+ "low": 272.09,
+ "close": 272.95,
+ "volume": 49602754.0
+ },
+ {
+ "date": "2025-11-14",
+ "open": 271.05,
+ "high": 275.96,
+ "low": 269.6,
+ "close": 272.41,
+ "volume": 47431331.0
+ },
+ {
+ "date": "2025-11-17",
+ "open": 268.81,
+ "high": 270.49,
+ "low": 265.73,
+ "close": 267.46,
+ "volume": 45018260.0
+ },
+ {
+ "date": "2025-11-18",
+ "open": 269.99,
+ "high": 270.71,
+ "low": 265.32,
+ "close": 267.44,
+ "volume": 45677169.0
+ },
+ {
+ "date": "2025-11-19",
+ "open": 265.52,
+ "high": 272.21,
+ "low": 265.5,
+ "close": 268.56,
+ "volume": 40424414.0
+ },
+ {
+ "date": "2025-11-20",
+ "open": 270.83,
+ "high": 275.43,
+ "low": 265.92,
+ "close": 266.25,
+ "volume": 45823540.0
+ },
+ {
+ "date": "2025-11-21",
+ "open": 265.95,
+ "high": 273.33,
+ "low": 265.67,
+ "close": 271.49,
+ "volume": 59030832.0
+ },
+ {
+ "date": "2025-11-24",
+ "open": 270.9,
+ "high": 277.0,
+ "low": 270.9,
+ "close": 275.92,
+ "volume": 65585613.0
+ },
+ {
+ "date": "2025-11-25",
+ "open": 275.27,
+ "high": 280.38,
+ "low": 275.25,
+ "close": 276.97,
+ "volume": 46914220.0
+ },
+ {
+ "date": "2025-11-26",
+ "open": 276.96,
+ "high": 279.53,
+ "low": 276.63,
+ "close": 277.55,
+ "volume": 33431421.0
+ },
+ {
+ "date": "2025-11-28",
+ "open": 277.26,
+ "high": 279.0,
+ "low": 275.99,
+ "close": 278.85,
+ "volume": 19039075.0
+ },
+ {
+ "date": "2025-12-01",
+ "open": 278.01,
+ "high": 283.42,
+ "low": 276.14,
+ "close": 283.1,
+ "volume": 46587722.0
+ },
+ {
+ "date": "2025-12-02",
+ "open": 283.0,
+ "high": 287.4,
+ "low": 282.63,
+ "close": 286.19,
+ "volume": 53669393.0
+ },
+ {
+ "date": "2025-12-03",
+ "open": 286.2,
+ "high": 288.62,
+ "low": 283.3,
+ "close": 284.15,
+ "volume": 43538674.0
+ },
+ {
+ "date": "2025-12-04",
+ "open": 284.1,
+ "high": 284.73,
+ "low": 278.59,
+ "close": 280.7,
+ "volume": 43989031.0
+ },
+ {
+ "date": "2025-12-05",
+ "open": 280.54,
+ "high": 281.14,
+ "low": 278.05,
+ "close": 278.78,
+ "volume": 47265691.0
+ },
+ {
+ "date": "2025-12-08",
+ "open": 278.13,
+ "high": 279.67,
+ "low": 276.15,
+ "close": 277.89,
+ "volume": 38211741.0
+ },
+ {
+ "date": "2025-12-09",
+ "open": 278.16,
+ "high": 280.03,
+ "low": 276.92,
+ "close": 277.18,
+ "volume": 32192972.0
+ },
+ {
+ "date": "2025-12-10",
+ "open": 277.75,
+ "high": 279.75,
+ "low": 276.44,
+ "close": 278.78,
+ "volume": 33038011.0
+ },
+ {
+ "date": "2025-12-11",
+ "open": 279.1,
+ "high": 279.59,
+ "low": 273.81,
+ "close": 278.03,
+ "volume": 33247766.0
+ },
+ {
+ "date": "2025-12-12",
+ "open": 277.9,
+ "high": 279.22,
+ "low": 276.82,
+ "close": 278.28,
+ "volume": 39532668.0
+ },
+ {
+ "date": "2025-12-15",
+ "open": 280.15,
+ "high": 280.15,
+ "low": 272.84,
+ "close": 274.11,
+ "volume": 50409068.0
+ },
+ {
+ "date": "2025-12-16",
+ "open": 272.82,
+ "high": 275.5,
+ "low": 271.79,
+ "close": 274.61,
+ "volume": 37648627.0
+ },
+ {
+ "date": "2025-12-17",
+ "open": 275.01,
+ "high": 276.16,
+ "low": 271.64,
+ "close": 271.84,
+ "volume": 50138466.0
+ },
+ {
+ "date": "2025-12-18",
+ "open": 273.61,
+ "high": 273.63,
+ "low": 266.95,
+ "close": 272.19,
+ "volume": 51630473.0
+ },
+ {
+ "date": "2025-12-19",
+ "open": 272.14,
+ "high": 274.6,
+ "low": 269.9,
+ "close": 273.67,
+ "volume": 144631573.0
+ },
+ {
+ "date": "2025-12-22",
+ "open": 272.86,
+ "high": 273.88,
+ "low": 270.5,
+ "close": 270.97,
+ "volume": 36571827.0
+ },
+ {
+ "date": "2025-12-23",
+ "open": 270.84,
+ "high": 272.5,
+ "low": 269.56,
+ "close": 272.36,
+ "volume": 29641997.0
+ },
+ {
+ "date": "2025-12-24",
+ "open": 272.34,
+ "high": 275.43,
+ "low": 272.19,
+ "close": 273.81,
+ "volume": 17133225.0
+ },
+ {
+ "date": "2025-12-26",
+ "open": 274.16,
+ "high": 275.37,
+ "low": 272.86,
+ "close": 273.4,
+ "volume": 21521796.0
+ },
+ {
+ "date": "2025-12-29",
+ "open": 272.69,
+ "high": 274.36,
+ "low": 272.35,
+ "close": 273.76,
+ "volume": 23714986.0
+ },
+ {
+ "date": "2025-12-30",
+ "open": 272.81,
+ "high": 274.08,
+ "low": 272.28,
+ "close": 273.08,
+ "volume": 22139615.0
+ },
+ {
+ "date": "2025-12-31",
+ "open": 273.06,
+ "high": 273.68,
+ "low": 271.75,
+ "close": 271.86,
+ "volume": 27293584.0
+ },
+ {
+ "date": "2026-01-02",
+ "open": 272.25,
+ "high": 277.84,
+ "low": 269.0,
+ "close": 271.01,
+ "volume": 37838054.0
+ },
+ {
+ "date": "2026-01-05",
+ "open": 270.64,
+ "high": 271.51,
+ "low": 266.14,
+ "close": 267.26,
+ "volume": 45647185.0
+ },
+ {
+ "date": "2026-01-06",
+ "open": 267.0,
+ "high": 267.55,
+ "low": 262.12,
+ "close": 262.36,
+ "volume": 52352090.0
+ },
+ {
+ "date": "2026-01-07",
+ "open": 263.2,
+ "high": 263.68,
+ "low": 259.81,
+ "close": 260.33,
+ "volume": 48309414.0
+ },
+ {
+ "date": "2026-01-08",
+ "open": 257.02,
+ "high": 259.29,
+ "low": 255.7,
+ "close": 259.04,
+ "volume": 50419336.0
+ },
+ {
+ "date": "2026-01-09",
+ "open": 259.07,
+ "high": 260.21,
+ "low": 256.22,
+ "close": 259.37,
+ "volume": 39996966.0
+ },
+ {
+ "date": "2026-01-12",
+ "open": 259.16,
+ "high": 261.3,
+ "low": 256.8,
+ "close": 260.25,
+ "volume": 45263372.0
+ },
+ {
+ "date": "2026-01-13",
+ "open": 258.72,
+ "high": 261.81,
+ "low": 258.39,
+ "close": 261.05,
+ "volume": 45730796.0
+ },
+ {
+ "date": "2026-01-14",
+ "open": 259.49,
+ "high": 261.82,
+ "low": 256.71,
+ "close": 259.96,
+ "volume": 40019349.0
+ },
+ {
+ "date": "2026-01-15",
+ "open": 260.65,
+ "high": 261.04,
+ "low": 257.05,
+ "close": 258.21,
+ "volume": 39388475.0
+ },
+ {
+ "date": "2026-01-16",
+ "open": 257.9,
+ "high": 258.9,
+ "low": 254.93,
+ "close": 255.53,
+ "volume": 72142772.0
+ },
+ {
+ "date": "2026-01-20",
+ "open": 252.73,
+ "high": 254.79,
+ "low": 243.42,
+ "close": 246.7,
+ "volume": 80267504.0
+ },
+ {
+ "date": "2026-01-21",
+ "open": 248.7,
+ "high": 251.56,
+ "low": 245.18,
+ "close": 247.65,
+ "volume": 54641725.0
+ },
+ {
+ "date": "2026-01-22",
+ "open": 249.2,
+ "high": 251.0,
+ "low": 248.15,
+ "close": 248.35,
+ "volume": 39708293.0
+ },
+ {
+ "date": "2026-01-23",
+ "open": 247.32,
+ "high": 249.41,
+ "low": 244.68,
+ "close": 248.04,
+ "volume": 41688953.0
+ },
+ {
+ "date": "2026-01-26",
+ "open": 251.48,
+ "high": 256.56,
+ "low": 249.8,
+ "close": 255.41,
+ "volume": 55969183.0
+ },
+ {
+ "date": "2026-01-27",
+ "open": 259.17,
+ "high": 261.95,
+ "low": 258.21,
+ "close": 258.27,
+ "volume": 49648271.0
+ },
+ {
+ "date": "2026-01-28",
+ "open": 257.65,
+ "high": 258.86,
+ "low": 254.51,
+ "close": 256.44,
+ "volume": 41287969.0
+ },
+ {
+ "date": "2026-01-29",
+ "open": 258.0,
+ "high": 259.65,
+ "low": 254.41,
+ "close": 258.28,
+ "volume": 67252891.0
+ },
+ {
+ "date": "2026-01-30",
+ "open": 255.16,
+ "high": 261.9,
+ "low": 252.18,
+ "close": 259.48,
+ "volume": 92443303.0
+ },
+ {
+ "date": "2026-02-02",
+ "open": 260.03,
+ "high": 270.49,
+ "low": 259.2,
+ "close": 270.01,
+ "volume": 73913423.0
+ },
+ {
+ "date": "2026-02-03",
+ "open": 269.2,
+ "high": 271.88,
+ "low": 267.61,
+ "close": 269.48,
+ "volume": 64394650.0
+ },
+ {
+ "date": "2026-02-04",
+ "open": 272.29,
+ "high": 278.95,
+ "low": 272.29,
+ "close": 276.49,
+ "volume": 90545398.0
+ },
+ {
+ "date": "2026-02-05",
+ "open": 278.13,
+ "high": 279.5,
+ "low": 273.23,
+ "close": 275.91,
+ "volume": 52977396.0
+ },
+ {
+ "date": "2026-02-06",
+ "open": 277.12,
+ "high": 280.9,
+ "low": 276.93,
+ "close": 278.12,
+ "volume": 50453279.0
+ },
+ {
+ "date": "2026-02-09",
+ "open": 277.9,
+ "high": 278.2,
+ "low": 271.7,
+ "close": 274.62,
+ "volume": 44623355.0
+ },
+ {
+ "date": "2026-02-10",
+ "open": 274.88,
+ "high": 275.37,
+ "low": 272.94,
+ "close": 273.68,
+ "volume": 34376605.0
+ },
+ {
+ "date": "2026-02-11",
+ "open": 274.69,
+ "high": 280.18,
+ "low": 274.45,
+ "close": 275.5,
+ "volume": 51931208.0
+ },
+ {
+ "date": "2026-02-12",
+ "open": 275.59,
+ "high": 275.72,
+ "low": 260.18,
+ "close": 261.73,
+ "volume": 81077219.0
+ },
+ {
+ "date": "2026-02-13",
+ "open": 262.01,
+ "high": 262.23,
+ "low": 255.45,
+ "close": 255.78,
+ "volume": 56290673.0
+ },
+ {
+ "date": "2026-02-17",
+ "open": 258.05,
+ "high": 266.29,
+ "low": 255.54,
+ "close": 263.88,
+ "volume": 58468913.0
+ },
+ {
+ "date": "2026-02-18",
+ "open": 263.6,
+ "high": 266.82,
+ "low": 262.45,
+ "close": 264.35,
+ "volume": 34202996.0
+ },
+ {
+ "date": "2026-02-19",
+ "open": 262.6,
+ "high": 264.48,
+ "low": 260.05,
+ "close": 260.58,
+ "volume": 30845258.0
+ },
+ {
+ "date": "2026-02-20",
+ "open": 258.97,
+ "high": 264.75,
+ "low": 258.16,
+ "close": 264.58,
+ "volume": 42070374.0
+ },
+ {
+ "date": "2026-02-23",
+ "open": 263.49,
+ "high": 269.43,
+ "low": 263.38,
+ "close": 266.18,
+ "volume": 37308000.0
+ },
+ {
+ "date": "2026-02-24",
+ "open": 267.86,
+ "high": 274.89,
+ "low": 267.71,
+ "close": 272.14,
+ "volume": 47014549.0
+ },
+ {
+ "date": "2026-02-25",
+ "open": 271.78,
+ "high": 274.94,
+ "low": 271.05,
+ "close": 274.23,
+ "volume": 33714222.0
+ },
+ {
+ "date": "2026-02-26",
+ "open": 274.94,
+ "high": 276.11,
+ "low": 270.8,
+ "close": 272.95,
+ "volume": 32345105.0
+ },
+ {
+ "date": "2026-02-27",
+ "open": 272.81,
+ "high": 272.81,
+ "low": 262.89,
+ "close": 264.18,
+ "volume": 72366505.0
+ },
+ {
+ "date": "2026-03-02",
+ "open": 262.41,
+ "high": 266.53,
+ "low": 260.2,
+ "close": 264.72,
+ "volume": 41827920.0
+ },
+ {
+ "date": "2026-03-03",
+ "open": 263.48,
+ "high": 265.56,
+ "low": 260.13,
+ "close": 263.75,
+ "volume": 38568896.0
+ },
+ {
+ "date": "2026-03-04",
+ "open": 264.65,
+ "high": 266.15,
+ "low": 261.42,
+ "close": 262.52,
+ "volume": 39802859.0
+ },
+ {
+ "date": "2026-03-05",
+ "open": 260.79,
+ "high": 261.56,
+ "low": 257.25,
+ "close": 260.29,
+ "volume": 49658509.0
+ },
+ {
+ "date": "2026-03-06",
+ "open": 258.63,
+ "high": 258.77,
+ "low": 254.37,
+ "close": 257.46,
+ "volume": 41119995.0
+ },
+ {
+ "date": "2026-03-09",
+ "open": 255.69,
+ "high": 261.15,
+ "low": 253.68,
+ "close": 259.88,
+ "volume": 38218531.0
+ },
+ {
+ "date": "2026-03-10",
+ "open": 257.64,
+ "high": 262.48,
+ "low": 256.95,
+ "close": 260.83,
+ "volume": 30590691.0
+ },
+ {
+ "date": "2026-03-11",
+ "open": 261.09,
+ "high": 262.13,
+ "low": 259.55,
+ "close": 260.81,
+ "volume": 26218534.0
+ },
+ {
+ "date": "2026-03-12",
+ "open": 258.66,
+ "high": 258.95,
+ "low": 254.18,
+ "close": 255.76,
+ "volume": 40793922.0
+ },
+ {
+ "date": "2026-03-13",
+ "open": 255.48,
+ "high": 256.33,
+ "low": 249.52,
+ "close": 250.12,
+ "volume": 36929911.0
+ },
+ {
+ "date": "2026-03-16",
+ "open": 252.1,
+ "high": 253.88,
+ "low": 249.88,
+ "close": 252.82,
+ "volume": 32074181.0
+ },
+ {
+ "date": "2026-03-17",
+ "open": 252.96,
+ "high": 255.13,
+ "low": 252.18,
+ "close": 254.23,
+ "volume": 32361394.0
+ },
+ {
+ "date": "2026-03-18",
+ "open": 252.62,
+ "high": 254.94,
+ "low": 249.0,
+ "close": 249.94,
+ "volume": 35757686.0
+ },
+ {
+ "date": "2026-03-19",
+ "open": 249.4,
+ "high": 251.83,
+ "low": 247.3,
+ "close": 248.96,
+ "volume": 34864055.0
+ },
+ {
+ "date": "2026-03-20",
+ "open": 247.97,
+ "high": 249.2,
+ "low": 246.0,
+ "close": 247.99,
+ "volume": 88331039.0
+ },
+ {
+ "date": "2026-03-23",
+ "open": 253.97,
+ "high": 254.6,
+ "low": 250.28,
+ "close": 251.49,
+ "volume": 40546003.0
+ },
+ {
+ "date": "2026-03-24",
+ "open": 250.35,
+ "high": 254.82,
+ "low": 249.55,
+ "close": 251.64,
+ "volume": 45151904.0
+ },
+ {
+ "date": "2026-03-25",
+ "open": 254.09,
+ "high": 255.0,
+ "low": 251.6,
+ "close": 252.62,
+ "volume": 28476668.0
+ },
+ {
+ "date": "2026-03-26",
+ "open": 252.12,
+ "high": 257.0,
+ "low": 250.77,
+ "close": 252.89,
+ "volume": 41796650.0
+ },
+ {
+ "date": "2026-03-27",
+ "open": 253.9,
+ "high": 255.49,
+ "low": 248.07,
+ "close": 248.8,
+ "volume": 47899998.0
+ },
+ {
+ "date": "2026-03-30",
+ "open": 250.07,
+ "high": 250.87,
+ "low": 245.51,
+ "close": 246.63,
+ "volume": 39446015.0
+ },
+ {
+ "date": "2026-03-31",
+ "open": 247.91,
+ "high": 255.48,
+ "low": 247.1,
+ "close": 253.79,
+ "volume": 49597194.0
+ },
+ {
+ "date": "2026-04-01",
+ "open": 254.08,
+ "high": 256.18,
+ "low": 253.33,
+ "close": 255.63,
+ "volume": 40059432.0
+ },
+ {
+ "date": "2026-04-02",
+ "open": 254.2,
+ "high": 256.13,
+ "low": 250.65,
+ "close": 255.92,
+ "volume": 31288896.0
+ },
+ {
+ "date": "2026-04-06",
+ "open": 256.51,
+ "high": 262.16,
+ "low": 256.46,
+ "close": 258.86,
+ "volume": 29329910.0
+ },
+ {
+ "date": "2026-04-07",
+ "open": 256.15,
+ "high": 256.2,
+ "low": 245.7,
+ "close": 253.5,
+ "volume": 62147944.0
+ },
+ {
+ "date": "2026-04-08",
+ "open": 258.45,
+ "high": 259.75,
+ "low": 256.53,
+ "close": 258.9,
+ "volume": 41032627.0
+ },
+ {
+ "date": "2026-04-09",
+ "open": 259.0,
+ "high": 261.12,
+ "low": 256.07,
+ "close": 260.49,
+ "volume": 28121302.0
+ },
+ {
+ "date": "2026-04-10",
+ "open": 259.98,
+ "high": 262.19,
+ "low": 259.02,
+ "close": 260.48,
+ "volume": 31291385.0
+ },
+ {
+ "date": "2026-04-13",
+ "open": 259.73,
+ "high": 260.18,
+ "low": 256.66,
+ "close": 259.2,
+ "volume": 36234480.0
+ },
+ {
+ "date": "2026-04-14",
+ "open": 259.25,
+ "high": 261.93,
+ "low": 257.19,
+ "close": 258.83,
+ "volume": 48370710.0
+ },
+ {
+ "date": "2026-04-15",
+ "open": 258.16,
+ "high": 266.56,
+ "low": 257.81,
+ "close": 266.43,
+ "volume": 49913490.0
+ },
+ {
+ "date": "2026-04-16",
+ "open": 266.8,
+ "high": 267.16,
+ "low": 261.27,
+ "close": 263.4,
+ "volume": 43322984.0
+ },
+ {
+ "date": "2026-04-17",
+ "open": 266.96,
+ "high": 272.3,
+ "low": 266.72,
+ "close": 270.23,
+ "volume": 61436160.0
+ },
+ {
+ "date": "2026-04-20",
+ "open": 270.33,
+ "high": 274.27,
+ "low": 270.29,
+ "close": 273.05,
+ "volume": 36590135.0
+ },
+ {
+ "date": "2026-04-21",
+ "open": 271.5,
+ "high": 272.8,
+ "low": 265.4,
+ "close": 266.17,
+ "volume": 50209699.0
+ },
+ {
+ "date": "2026-04-22",
+ "open": 267.82,
+ "high": 273.74,
+ "low": 266.87,
+ "close": 273.17,
+ "volume": 43249072.0
+ },
+ {
+ "date": "2026-04-23",
+ "open": 275.05,
+ "high": 275.77,
+ "low": 271.65,
+ "close": 273.43,
+ "volume": 33399530.0
+ },
+ {
+ "date": "2026-04-24",
+ "open": 272.75,
+ "high": 273.06,
+ "low": 269.65,
+ "close": 271.06,
+ "volume": 38156959.0
+ },
+ {
+ "date": "2026-04-27",
+ "open": 266.09,
+ "high": 268.36,
+ "low": 265.07,
+ "close": 267.61,
+ "volume": 41466553.0
+ },
+ {
+ "date": "2026-04-28",
+ "open": 272.33,
+ "high": 273.23,
+ "low": 268.66,
+ "close": 270.71,
+ "volume": 40018566.0
+ },
+ {
+ "date": "2026-04-29",
+ "open": 267.55,
+ "high": 271.04,
+ "low": 267.04,
+ "close": 270.17,
+ "volume": 30047854.0
+ },
+ {
+ "date": "2026-04-30",
+ "open": 270.5,
+ "high": 276.0,
+ "low": 268.14,
+ "close": 271.35,
+ "volume": 91848046.0
+ },
+ {
+ "date": "2026-05-01",
+ "open": 278.86,
+ "high": 287.22,
+ "low": 278.37,
+ "close": 280.14,
+ "volume": 79915442.0
+ },
+ {
+ "date": "2026-05-04",
+ "open": 279.65,
+ "high": 280.63,
+ "low": 274.86,
+ "close": 276.83,
+ "volume": 46668395.0
+ },
+ {
+ "date": "2026-05-05",
+ "open": 276.93,
+ "high": 284.57,
+ "low": 276.5,
+ "close": 284.18,
+ "volume": 49311712.0
+ },
+ {
+ "date": "2026-05-06",
+ "open": 281.92,
+ "high": 288.03,
+ "low": 281.07,
+ "close": 287.51,
+ "volume": 58336056.0
+ },
+ {
+ "date": "2026-05-07",
+ "open": 289.27,
+ "high": 292.13,
+ "low": 285.78,
+ "close": 287.44,
+ "volume": 45224299.0
+ },
+ {
+ "date": "2026-05-08",
+ "open": 290.01,
+ "high": 294.76,
+ "low": 290.0,
+ "close": 293.32,
+ "volume": 52692736.0
+ },
+ {
+ "date": "2026-05-11",
+ "open": 291.98,
+ "high": 293.88,
+ "low": 290.23,
+ "close": 292.68,
+ "volume": 42247239.0
+ },
+ {
+ "date": "2026-05-12",
+ "open": 292.56,
+ "high": 295.27,
+ "low": 292.56,
+ "close": 294.8,
+ "volume": 45748129.0
+ },
+ {
+ "date": "2026-05-13",
+ "open": 293.5,
+ "high": 300.92,
+ "low": 293.5,
+ "close": 298.87,
+ "volume": 52684226.0
+ },
+ {
+ "date": "2026-05-14",
+ "open": 299.82,
+ "high": 300.45,
+ "low": 295.38,
+ "close": 298.21,
+ "volume": 35324918.0
+ },
+ {
+ "date": "2026-05-15",
+ "open": 297.9,
+ "high": 303.2,
+ "low": 296.52,
+ "close": 300.23,
+ "volume": 54862836.0
+ },
+ {
+ "date": "2026-05-18",
+ "open": 300.24,
+ "high": 300.66,
+ "low": 294.91,
+ "close": 297.84,
+ "volume": 34482925.0
+ },
+ {
+ "date": "2026-05-19",
+ "open": 296.97,
+ "high": 300.51,
+ "low": 296.35,
+ "close": 298.97,
+ "volume": 42243561.0
+ },
+ {
+ "date": "2026-05-20",
+ "open": 298.18,
+ "high": 302.8,
+ "low": 298.08,
+ "close": 302.25,
+ "volume": 38229843.0
+ },
+ {
+ "date": "2026-05-21",
+ "open": 301.06,
+ "high": 305.54,
+ "low": 300.4,
+ "close": 304.99,
+ "volume": 42965126.0
+ },
+ {
+ "date": "2026-05-22",
+ "open": 306.12,
+ "high": 311.4,
+ "low": 305.84,
+ "close": 308.82,
+ "volume": 43670211.0
+ },
+ {
+ "date": "2026-05-26",
+ "open": 309.56,
+ "high": 311.82,
+ "low": 307.67,
+ "close": 308.33,
+ "volume": 48000493.0
+ },
+ {
+ "date": "2026-05-27",
+ "open": 308.33,
+ "high": 313.26,
+ "low": 308.3,
+ "close": 310.85,
+ "volume": 50430918.0
+ },
+ {
+ "date": "2026-05-28",
+ "open": 310.68,
+ "high": 312.8,
+ "low": 309.57,
+ "close": 312.51,
+ "volume": 48220309.0
+ },
+ {
+ "date": "2026-05-29",
+ "open": 311.77,
+ "high": 315.0,
+ "low": 309.53,
+ "close": 312.06,
+ "volume": 70026752.0
+ },
+ {
+ "date": "2026-06-01",
+ "open": 309.62,
+ "high": 310.94,
+ "low": 305.02,
+ "close": 306.31,
+ "volume": 48849913.0
+ },
+ {
+ "date": "2026-06-02",
+ "open": 307.46,
+ "high": 315.45,
+ "low": 306.69,
+ "close": 315.2,
+ "volume": 44534686.0
+ },
+ {
+ "date": "2026-06-03",
+ "open": 314.18,
+ "high": 316.94,
+ "low": 308.85,
+ "close": 310.26,
+ "volume": 50836553.0
+ },
+ {
+ "date": "2026-06-04",
+ "open": 313.23,
+ "high": 313.54,
+ "low": 309.65,
+ "close": 311.23,
+ "volume": 44869122.0
+ },
+ {
+ "date": "2026-06-05",
+ "open": 312.86,
+ "high": 315.17,
+ "low": 307.15,
+ "close": 307.34,
+ "volume": 65310417.0
+ },
+ {
+ "date": "2026-06-08",
+ "open": 308.74,
+ "high": 317.4,
+ "low": 301.17,
+ "close": 301.54,
+ "volume": 77949069.0
+ },
+ {
+ "date": "2026-06-09",
+ "open": 300.27,
+ "high": 300.75,
+ "low": 287.78,
+ "close": 290.55,
+ "volume": 70108797.0
+ },
+ {
+ "date": "2026-06-10",
+ "open": 290.74,
+ "high": 294.75,
+ "low": 287.38,
+ "close": 291.58,
+ "volume": 52793241.0
+ },
+ {
+ "date": "2026-06-11",
+ "open": 293.72,
+ "high": 297.0,
+ "low": 289.59,
+ "close": 295.63,
+ "volume": 42572471.0
+ },
+ {
+ "date": "2026-06-12",
+ "open": 296.03,
+ "high": 297.14,
+ "low": 289.62,
+ "close": 291.13,
+ "volume": 38784770.0
+ },
+ {
+ "date": "2026-06-15",
+ "open": 294.12,
+ "high": 297.78,
+ "low": 291.7,
+ "close": 296.42,
+ "volume": 45732467.0
+ },
+ {
+ "date": "2026-06-16",
+ "open": 295.25,
+ "high": 300.48,
+ "low": 293.97,
+ "close": 299.24,
+ "volume": 39874404.0
+ },
+ {
+ "date": "2026-06-17",
+ "open": 300.85,
+ "high": 302.07,
+ "low": 294.36,
+ "close": 295.95,
+ "volume": 42745016.0
+ },
+ {
+ "date": "2026-06-18",
+ "open": 298.11,
+ "high": 300.57,
+ "low": 295.62,
+ "close": 298.01,
+ "volume": 85962167.0
+ },
+ {
+ "date": "2026-06-22",
+ "open": 297.31,
+ "high": 302.42,
+ "low": 296.76,
+ "close": 297.01,
+ "volume": 44879903.0
+ },
+ {
+ "date": "2026-06-23",
+ "open": 297.54,
+ "high": 301.64,
+ "low": 294.18,
+ "close": 294.3,
+ "volume": 52010924.0
+ },
+ {
+ "date": "2026-06-24",
+ "open": 295.36,
+ "high": 299.7,
+ "low": 292.94,
+ "close": 293.08,
+ "volume": 53081699.0
+ },
+ {
+ "date": "2026-06-25",
+ "open": 287.4,
+ "high": 288.8,
+ "low": 273.75,
+ "close": 275.15,
+ "volume": 107253600.0
+ },
+ {
+ "date": "2026-06-26",
+ "open": 275.0,
+ "high": 285.95,
+ "low": 274.21,
+ "close": 283.78,
+ "volume": 261775448.0
+ },
+ {
+ "date": "2026-06-29",
+ "open": 286.73,
+ "high": 288.37,
+ "low": 279.85,
+ "close": 281.74,
+ "volume": 66427002.0
+ },
+ {
+ "date": "2026-06-30",
+ "open": 281.17,
+ "high": 289.94,
+ "low": 280.69,
+ "close": 289.36,
+ "volume": 65100140.0
+ },
+ {
+ "date": "2026-07-01",
+ "open": 293.44,
+ "high": 296.59,
+ "low": 289.19,
+ "close": 294.38,
+ "volume": 50164212.0
+ },
+ {
+ "date": "2026-07-02",
+ "open": 294.12,
+ "high": 309.42,
+ "low": 293.68,
+ "close": 308.63,
+ "volume": 75400625.0
+ },
+ {
+ "date": "2026-07-06",
+ "open": 307.36,
+ "high": 314.2,
+ "low": 307.0,
+ "close": 312.66,
+ "volume": 53589968.0
+ },
+ {
+ "date": "2026-07-07",
+ "open": 315.29,
+ "high": 315.48,
+ "low": 310.15,
+ "close": 310.66,
+ "volume": 42490001.0
+ },
+ {
+ "date": "2026-07-08",
+ "open": 311.91,
+ "high": 314.82,
+ "low": 307.05,
+ "close": 313.39,
+ "volume": 41323441.0
+ },
+ {
+ "date": "2026-07-09",
+ "open": 310.51,
+ "high": 316.53,
+ "low": 308.16,
+ "close": 316.22,
+ "volume": 48124426.0
+ },
+ {
+ "date": "2026-07-10",
+ "open": 314.72,
+ "high": 316.91,
+ "low": 312.17,
+ "close": 315.32,
+ "volume": 34132284.0
+ },
+ {
+ "date": "2026-07-13",
+ "open": 317.01,
+ "high": 323.45,
+ "low": 315.78,
+ "close": 317.31,
+ "volume": 43257790.0
+ },
+ {
+ "date": "2026-07-14",
+ "open": 313.76,
+ "high": 316.19,
+ "low": 311.91,
+ "close": 314.86,
+ "volume": 36336718.0
+ },
+ {
+ "date": "2026-07-15",
+ "open": 317.62,
+ "high": 328.73,
+ "low": 317.32,
+ "close": 327.5,
+ "volume": 60957641.0
+ },
+ {
+ "date": "2026-07-16",
+ "open": 328.0,
+ "high": 334.68,
+ "low": 326.79,
+ "close": 333.26,
+ "volume": 62970581.0
+ },
+ {
+ "date": "2026-07-17",
+ "open": 331.98,
+ "high": 334.99,
+ "low": 329.0,
+ "close": 333.74,
+ "volume": 63407018.0
+ },
+ {
+ "date": "2026-07-20",
+ "open": 333.5,
+ "high": 333.71,
+ "low": 323.68,
+ "close": 326.59,
+ "volume": 53467988.0
+ },
+ {
+ "date": "2026-07-21",
+ "open": 323.13,
+ "high": 329.6,
+ "low": 322.22,
+ "close": 327.74,
+ "volume": 41338916.0
+ },
+ {
+ "date": "2026-07-22",
+ "open": 327.87,
+ "high": 329.0,
+ "low": 323.34,
+ "close": 325.89,
+ "volume": 38755929.0
+ },
+ {
+ "date": "2026-07-23",
+ "open": 321.73,
+ "high": 323.3,
+ "low": 319.35,
+ "close": 321.66,
+ "volume": 40840661.0
+ },
+ {
+ "date": "2026-07-24",
+ "open": 321.79,
+ "high": 334.37,
+ "low": 321.62,
+ "close": 333.02,
+ "volume": 47489415.0
+ },
+ {
+ "date": "2026-07-27",
+ "open": 334.54,
+ "high": 339.57,
+ "low": 334.02,
+ "close": 336.91,
+ "volume": 49604213.0
+ },
+ {
+ "date": "2026-07-28",
+ "open": 340.03,
+ "high": 342.89,
+ "low": 335.6,
+ "close": 340.08,
+ "volume": 51859037.0
+ },
+ {
+ "date": "2026-07-29",
+ "open": 339.73,
+ "high": 344.57,
+ "low": 337.35,
+ "close": 338.19,
+ "volume": 56090797.0
+ },
+ {
+ "date": "2026-07-30",
+ "open": 333.1,
+ "high": 334.75,
+ "low": 329.59,
+ "close": 333.43,
+ "volume": 74817792.0
+ },
+ {
+ "date": "2026-07-31",
+ "open": 304.81,
+ "high": 310.69,
+ "low": 300.0,
+ "close": 308.91,
+ "volume": 132489119.0
+ },
+ {
+ "date": "2026-08-03",
+ "open": 309.58,
+ "high": 311.8,
+ "low": 302.56,
+ "close": 303.42,
+ "volume": 75051881.0
+ },
+ {
+ "date": "2026-08-04",
+ "open": 302.73,
+ "high": 310.42,
+ "low": 301.32,
+ "close": 309.38,
+ "volume": 68000968.0
+ },
+ {
+ "date": "2026-08-05",
+ "open": 309.36,
+ "high": 311.71,
+ "low": 305.67,
+ "close": 311.0,
+ "volume": 49438729.0
+ },
+ {
+ "date": "2026-08-06",
+ "open": 314.34,
+ "high": 316.29,
+ "low": 309.23,
+ "close": 312.41,
+ "volume": 46139901.0
+ },
+ {
+ "date": "2026-08-07",
+ "open": 311.45,
+ "high": 314.81,
+ "low": 310.74,
+ "close": 313.33,
+ "volume": 34437181.0
+ },
+ {
+ "date": "2026-08-10",
+ "open": 306.83,
+ "high": 308.26,
+ "low": 304.61,
+ "close": 308.26,
+ "volume": 44812498.0
+ },
+ {
+ "date": "2026-08-11",
+ "open": 307.75,
+ "high": 309.97,
+ "low": 302.79,
+ "close": 304.91,
+ "volume": 37476744.0
+ },
+ {
+ "date": "2026-08-12",
+ "open": 305.1,
+ "high": 305.66,
+ "low": 300.57,
+ "close": 302.25,
+ "volume": 41657648.0
+ },
+ {
+ "date": "2026-08-13",
+ "open": 304.21,
+ "high": 306.0,
+ "low": 302.05,
+ "close": 305.26,
+ "volume": 40349265.0
+ },
+ {
+ "date": "2026-08-14",
+ "open": 306.0,
+ "high": 307.49,
+ "low": 304.3,
+ "close": 305.93,
+ "volume": 28229315.0
+ },
+ {
+ "date": "2026-08-17",
+ "open": 306.21,
+ "high": 307.66,
+ "low": 302.94,
+ "close": 305.59,
+ "volume": 38169259.0
+ },
+ {
+ "date": "2026-08-18",
+ "open": 307.58,
+ "high": 311.49,
+ "low": 305.74,
+ "close": 310.03,
+ "volume": 53424535.0
+ },
+ {
+ "date": "2026-08-19",
+ "open": 310.14,
+ "high": 319.28,
+ "low": 309.6,
+ "close": 316.83,
+ "volume": 50505621.0
+ },
+ {
+ "date": "2026-08-20",
+ "open": 317.45,
+ "high": 320.28,
+ "low": 310.65,
+ "close": 311.3,
+ "volume": 40959163.0
+ },
+ {
+ "date": "2026-08-21",
+ "open": 312.05,
+ "high": 312.38,
+ "low": 307.01,
+ "close": 309.35,
+ "volume": 46876815.0
+ },
+ {
+ "date": "2026-08-24",
+ "open": 311.47,
+ "high": 313.36,
+ "low": 309.97,
+ "close": 310.34,
+ "volume": 34673550.0
+ },
+ {
+ "date": "2026-08-25",
+ "open": 310.79,
+ "high": 313.59,
+ "low": 308.21,
+ "close": 309.9,
+ "volume": 25869807.0
+ },
+ {
+ "date": "2026-08-26",
+ "open": 310.3,
+ "high": 315.43,
+ "low": 308.8,
+ "close": 313.45,
+ "volume": 34024382.0
+ },
+ {
+ "date": "2026-08-27",
+ "open": 310.55,
+ "high": 315.4,
+ "low": 309.4,
+ "close": 314.58,
+ "volume": 32419233.0
+ },
+ {
+ "date": "2026-08-28",
+ "open": 316.85,
+ "high": 322.37,
+ "low": 315.45,
+ "close": 319.7,
+ "volume": 38649373.0
+ },
+ {
+ "date": "2026-08-31",
+ "open": 319.6,
+ "high": 321.24,
+ "low": 312.8,
+ "close": 316.85,
+ "volume": 41242724.0
+ },
+ {
+ "date": "2026-09-01",
+ "open": 316.98,
+ "high": 327.3,
+ "low": 314.73,
+ "close": 325.13,
+ "volume": 53167386.0
+ },
+ {
+ "date": "2026-09-02",
+ "open": 326.87,
+ "high": 328.4,
+ "low": 323.53,
+ "close": 324.96,
+ "volume": 33776365.0
+ },
+ {
+ "date": "2026-09-03",
+ "open": 324.87,
+ "high": 330.81,
+ "low": 324.11,
+ "close": 328.21,
+ "volume": 37225805.0
+ },
+ {
+ "date": "2026-09-04",
+ "open": 328.31,
+ "high": 328.93,
+ "low": 317.86,
+ "close": 319.97,
+ "volume": 39606884.0
+ },
+ {
+ "date": "2026-09-08",
+ "open": 317.1,
+ "high": 320.7,
+ "low": 314.9,
+ "close": 316.22,
+ "volume": 35477006.0
+ },
+ {
+ "date": "2026-09-09",
+ "open": 315.49,
+ "high": 319.15,
+ "low": 309.9,
+ "close": 315.34,
+ "volume": 65639939.0
+ },
+ {
+ "date": "2026-09-10",
+ "open": 316.67,
+ "high": 326.74,
+ "low": 316.51,
+ "close": 326.57,
+ "volume": 70011913.0
+ },
+ {
+ "date": "2026-09-11",
+ "open": 327.45,
+ "high": 336.22,
+ "low": 326.3,
+ "close": 332.27,
+ "volume": 50716810.0
+ },
+ {
+ "date": "2026-09-14",
+ "open": 334.79,
+ "high": 335.5,
+ "low": 331.34,
+ "close": 333.08,
+ "volume": 39269146.0
+ },
+ {
+ "date": "2026-09-15",
+ "open": 330.13,
+ "high": 331.78,
+ "low": 328.35,
+ "close": 331.34,
+ "volume": 31748183.0
+ },
+ {
+ "date": "2026-09-16",
+ "open": 332.53,
+ "high": 335.48,
+ "low": 330.7,
+ "close": 332.41,
+ "volume": 35980978.0
+ },
+ {
+ "date": "2026-09-17",
+ "open": 334.77,
+ "high": 338.34,
+ "low": 330.18,
+ "close": 337.0,
+ "volume": 36700216.0
+ },
+ {
+ "date": "2026-09-18",
+ "open": 337.9,
+ "high": 338.49,
+ "low": 332.53,
+ "close": 336.13,
+ "volume": 86588048.0
+ },
+ {
+ "date": "2026-09-21",
+ "open": 335.28,
+ "high": 339.64,
+ "low": 333.05,
+ "close": 338.98,
+ "volume": 34999133.0
+ },
+ {
+ "date": "2026-09-22",
+ "open": 340.13,
+ "high": 345.34,
+ "low": 338.75,
+ "close": 339.75,
+ "volume": 40711697.0
+ },
+ {
+ "date": "2026-09-23",
+ "open": 341.07,
+ "high": 341.8,
+ "low": 335.5,
+ "close": 337.02,
+ "volume": 31658794.0
+ },
+ {
+ "date": "2026-09-24",
+ "open": 336.72,
+ "high": 338.91,
+ "low": 334.3,
+ "close": 335.92,
+ "volume": 24732887.0
+ },
+ {
+ "date": "2026-09-25",
+ "open": 336.04,
+ "high": 341.67,
+ "low": 334.53,
+ "close": 341.07,
+ "volume": 30002507.0
+ },
+ {
+ "date": "2026-09-28",
+ "open": 340.37,
+ "high": 342.99,
+ "low": 338.04,
+ "close": 338.4,
+ "volume": 32820844.0
+ },
+ {
+ "date": "2026-09-29",
+ "open": 336.96,
+ "high": 337.08,
+ "low": 328.7,
+ "close": 329.4,
+ "volume": 38478017.0
+ },
+ {
+ "date": "2026-09-30",
+ "open": 330.8,
+ "high": 339.5,
+ "low": 330.14,
+ "close": 333.02,
+ "volume": 49988558.0
+ },
+ {
+ "date": "2026-10-01",
+ "open": 330.0,
+ "high": 332.48,
+ "low": 325.81,
+ "close": 330.32,
+ "volume": 36306322.0
+ },
+ {
+ "date": "2026-10-02",
+ "open": 333.26,
+ "high": 334.54,
+ "low": 330.61,
+ "close": 333.69,
+ "volume": 33278502.0
+ },
+ {
+ "date": "2026-10-05",
+ "open": 332.81,
+ "high": 336.21,
+ "low": 331.65,
+ "close": 332.89,
+ "volume": 34400850.0
+ },
+ {
+ "date": "2026-10-06",
+ "open": 332.28,
+ "high": 334.38,
+ "low": 330.62,
+ "close": 333.63,
+ "volume": 30449004.0
+ },
+ {
+ "date": "2026-10-07",
+ "open": 336.96,
+ "high": 338.67,
+ "low": 332.78,
+ "close": 336.67,
+ "volume": 34147860.0
+ },
+ {
+ "date": "2026-10-08",
+ "open": 336.81,
+ "high": 341.57,
+ "low": 335.9,
+ "close": 340.42,
+ "volume": 35332449.0
+ },
+ {
+ "date": "2026-10-09",
+ "open": 331.69,
+ "high": 338.61,
+ "low": 330.7,
+ "close": 336.64,
+ "volume": 37881136.0
+ },
+ {
+ "date": "2026-10-12",
+ "open": 338.21,
+ "high": 342.63,
+ "low": 337.6,
+ "close": 340.97,
+ "volume": 25900551.0
+ },
+ {
+ "date": "2026-10-13",
+ "open": 344.67,
+ "high": 348.15,
+ "low": 340.74,
+ "close": 341.27,
+ "volume": 38983814.0
+ },
+ {
+ "date": "2026-10-14",
+ "open": 344.61,
+ "high": 347.09,
+ "low": 341.72,
+ "close": 342.96,
+ "volume": 50061010.0
+ },
+ {
+ "date": "2026-10-15",
+ "open": 346.95,
+ "high": 347.85,
+ "low": 341.6,
+ "close": 342.0,
+ "volume": 39767218.0
+ },
+ {
+ "date": "2026-10-16",
+ "open": 346.08,
+ "high": 347.82,
+ "low": 340.46,
+ "close": 343.46,
+ "volume": 59946320.0
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/paper_trade/record_market_fixtures.py b/agent/tests/fixtures/paper_trade/record_market_fixtures.py
new file mode 100644
index 000000000..d65bc0336
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/record_market_fixtures.py
@@ -0,0 +1,401 @@
+#!/usr/bin/env python3
+"""Record the real-market paper-trade fixtures (VD-14, Step 1 / T1.5).
+
+MANUAL RECORDING TOOL — NEVER IMPORT OR EXECUTE THIS FROM A TEST.
+
+The repository's unit-test discipline for the paper-trade suite is 单测禁网
+(plan VD-14): tests only read frozen fixture files. This script is the one
+documented place where those files are produced: it performs live HTTP
+fetches against the two sources the plan pins (hk_equity = tencent,
+us_equity = sina), snapshots the upstream reply into a byte-stable JSON
+fixture, and rebuilds ``market/MANIFEST.json`` (sha256 tamper-evidence over
+every recorded fixture, synthetic ones included).
+
+Contract with the consumers:
+
+* Numbers are preserved exactly as the wire served them — parse ``float``
+ from the source string, no rescale, no rounding, no "fixing" of the raw
+ (unadjusted) US series. The raw caliber is the whole point of the T7
+ split-detection fixture (registry.py:296, live-confirmed 2026-10-18).
+* Bars are sorted ascending, dates unique; a dirty bar (failed the OHLC
+ bracket check) or a duplicate date is DROPPED WITH A WARNING and counted
+ in ``drop_stats`` — never silently.
+* Output is deterministic given the same upstream payload: fixed key order
+ (plain dict insertion order), ``json.dumps(indent=2, ensure_ascii=False)``
+ plus a trailing newline, written via temp file + atomic ``os.replace``.
+* Existing fixtures are never silently overwritten: re-recording requires
+ an explicit ``--force``.
+
+The ``cn_a`` leg of VD-14 is NOT handled here and must never be sourced
+from the network: it is pinned to a ClickHouse export. The ClickHouse
+instance (``172.24.165.51:8123``) is private-VPC-only and currently
+unreachable (open HIL), so that leg stays blocked — see the plan Step 1.
+
+Usage (manual, from the repository root):
+
+ conda run -n legonanobot python \
+ agent/tests/fixtures/paper_trade/record_market_fixtures.py --force
+ conda run -n legonanobot python \
+ agent/tests/fixtures/paper_trade/record_market_fixtures.py --manifest-only
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import logging
+import math
+import os
+import re
+import tempfile
+import urllib.request
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+FIXTURE_SCHEMA = "paper_trade.market_fixture/v1"
+MANIFEST_SCHEMA = "paper_trade.market_manifest/v1"
+
+#: Recording window frozen by the T1.5 task: a full year ending on the last
+#: completed trade date observed by the Step 0 lanes (2026-10-16, Friday).
+WINDOW_START = "2025-10-01"
+WINDOW_END = "2026-10-16"
+
+LOG = logging.getLogger("record_market_fixtures")
+
+_HERE = Path(__file__).resolve().parent
+
+# JSONP scaffolding, identical to backtest/loaders/sina_loader.py:41.
+_JSONP_ARRAY_RE = re.compile(r"(\[.*\])", re.DOTALL)
+
+_US_CALIBER_NOTE = (
+ "raw / unadjusted — no split scaling applied by the source; a "
+ "close-to-close read across the 2020-08-31 4:1 ex-date reads ~0.2585. "
+ "Pinned by registry.py PRICE_CALIBER_BY_SOURCE['sina']='raw' and "
+ "live-confirmed 2026-10-18 (STEP0-LANE-A A1/A2); the recorded window "
+ "itself does not contain that ex-date."
+)
+_HK_CALIBER_NOTE = (
+ "raw — Tencent serves no adjusted HK series: the fqkline reply carries "
+ "only 'day' (never 'qfqday', #1493 / registry.py ('tencent',hk_equity)="
+ "'raw'), so the ',qfq' request parameter changes nothing. Row layout is "
+ "[date, open, close, high, low, volume]; a 7th event-dict element is "
+ "ignored exactly like tencent_loader.py:206-217 (parses 6 fields)."
+)
+
+
+def _utcnow_iso() -> str:
+ """Second-resolution UTC stamp for ``recorded_at_utc`` (manual tool only)."""
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _http_get(url: str, headers: dict[str, str]) -> str:
+ request = urllib.request.Request(url, headers=headers)
+ with urllib.request.urlopen(request, timeout=30) as response:
+ return response.read().decode("utf-8")
+
+
+def _parse_tencent_rows(text: str, symbol_key: str) -> list[dict[str, Any]]:
+ """Return raw bars from a Tencent fqkline reply, loader-faithful.
+
+ Mirrors tencent_loader.py: ``qfqday or day`` key selection and the
+ 6-field row layout ``[date, open, close, high, low, volume]``; anything
+ past the sixth field (e.g. a buy-back event dict) is ignored.
+ """
+ data = json.loads(text)
+ if data.get("code") not in (0, None) and not data.get("data"):
+ raise ValueError(f"tencent fqkline error reply: code={data.get('code')}")
+ stock_data = data.get("data") or {}
+ block = stock_data.get(symbol_key) or {}
+ klines = block.get("qfqday") or block.get("day")
+ if not klines:
+ raise ValueError(f"tencent reply carries no day/qfqday rows for {symbol_key}")
+ rows: list[dict[str, Any]] = []
+ for k in klines:
+ if not isinstance(k, (list, tuple)) or len(k) < 6:
+ rows.append({"date": None})
+ continue
+ rows.append(
+ {
+ "date": str(k[0]),
+ "open": k[1],
+ "high": k[3],
+ "low": k[4],
+ "close": k[2],
+ "volume": k[5],
+ }
+ )
+ return rows
+
+
+def _parse_sina_bars(text: str) -> list[dict[str, Any]]:
+ """Return raw bars from the sina JSONP reply (d/o/h/l/c/v; 'a' ignored)."""
+ match = _JSONP_ARRAY_RE.search(text.strip())
+ if not match:
+ raise ValueError("no JSON array found in Sina JSONP response")
+ payload = json.loads(match.group(1))
+ if not isinstance(payload, list):
+ raise ValueError("Sina JSONP payload is not a list of bars")
+ rows: list[dict[str, Any]] = []
+ for bar in payload:
+ if not isinstance(bar, dict) or not all(f in bar for f in ("d", "o", "h", "l", "c", "v")):
+ rows.append({"date": None})
+ continue
+ rows.append(
+ {
+ "date": str(bar["d"]),
+ "open": bar["o"],
+ "high": bar["h"],
+ "low": bar["l"],
+ "close": bar["c"],
+ "volume": bar["v"],
+ }
+ )
+ return rows
+
+
+def _to_float(value: Any) -> Optional[float]:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _normalize(
+ raw_rows: list[dict[str, Any]], start_date: str, end_date: str, label: str
+) -> tuple[list[dict[str, Any]], dict[str, int]]:
+ """Clip to the window, dedup dates, drop dirty bars — each with a warning.
+
+ Returns ``(bars, drop_stats)``; ``bars`` is ascending by date with unique
+ dates and every bar passes ``high >= max(o,c,l)`` / ``low <= min(o,c,h)``
+ with strictly positive, finite OHLC prices.
+ """
+ stats = {
+ "wire_rows": len(raw_rows),
+ "dropped_unparseable": 0,
+ "dropped_out_of_window": 0,
+ "dropped_duplicate_dates": 0,
+ "dropped_dirty_ohlc": 0,
+ }
+ by_date: dict[str, dict[str, Any]] = {}
+ for row in raw_rows:
+ date = row.get("date")
+ values = {k: _to_float(row.get(k)) for k in ("open", "high", "low", "close", "volume")}
+ if not date or any(v is None for v in values.values()):
+ stats["dropped_unparseable"] += 1
+ LOG.warning("%s: dropped unparseable wire row %r", label, row)
+ continue
+ if not (start_date <= date <= end_date):
+ stats["dropped_out_of_window"] += 1
+ continue
+ op, hi, lo, cl = values["open"], values["high"], values["low"], values["close"]
+ finite = all(math.isfinite(v) for v in (op, hi, lo, cl, values["volume"]))
+ if not finite or min(op, hi, lo, cl) <= 0 or hi < max(op, cl, lo) or lo > min(op, cl, hi):
+ stats["dropped_dirty_ohlc"] += 1
+ LOG.warning("%s: dropped dirty bar %s (o,h,l,c=%s)", label, date, (op, hi, lo, cl))
+ continue
+ if date in by_date:
+ stats["dropped_duplicate_dates"] += 1
+ LOG.warning("%s: dropped duplicate date %s (keeping first)", label, date)
+ continue
+ by_date[date] = {
+ "date": date,
+ "open": op,
+ "high": hi,
+ "low": lo,
+ "close": cl,
+ "volume": values["volume"],
+ }
+ bars = [by_date[date] for date in sorted(by_date)]
+ return bars, stats
+
+
+#: The two legs VD-14 pins to a network source (cn_a is NOT here: it is a
+#: ClickHouse export, blocked on the HIL — never substitute a network source).
+SPECS: tuple[dict[str, Any], ...] = (
+ {
+ "file": "hk_00700_tencent.json",
+ "market": "hk_equity",
+ "symbol": "00700.HK",
+ "source": "tencent",
+ "price_caliber": "raw",
+ "volume_unit": "shares",
+ "volume_unit_note": (
+ "tencent_loader.py:70 volume_units: a_share=lots, hk_equity=shares"
+ ),
+ "request_url": (
+ "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=hk00700,"
+ f"day,{WINDOW_START},{WINDOW_END},500,qfq"
+ ),
+ "headers": {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
+ "Referer": "https://web.ifzq.gtimg.cn/",
+ },
+ "parser": lambda text: _parse_tencent_rows(text, "hk00700"),
+ "window_note": (
+ "single request: the window holds fewer than the 500-bar page cap,"
+ " and Tencent honours the start clamp for such windows"
+ " (tencent_loader.py:36-42)."
+ ),
+ "caliber_note": _HK_CALIBER_NOTE,
+ },
+ {
+ "file": "us_AAPL_sina.json",
+ "market": "us_equity",
+ "symbol": "AAPL.US",
+ "source": "sina",
+ "price_caliber": "raw",
+ "volume_unit": None,
+ "volume_unit_note": (
+ "the sina loader declares no volume_units; US bars carry "
+ "volume_unit=None (sina_loader.py has no such class attribute)"
+ ),
+ "request_url": (
+ "https://stock.finance.sina.com.cn/usstock/api/jsonp_v2.php/"
+ "var%20x=/US_MinKService.getDailyK?symbol=AAPL"
+ ),
+ "headers": {
+ "User-Agent": "Mozilla/5.0",
+ "Referer": "https://stock.finance.sina.com.cn/",
+ },
+ "parser": _parse_sina_bars,
+ "window_note": (
+ "sina serves the full history (1984-09-07 onward) with no window "
+ "parameter; bars are clipped to the window at record time, the "
+ "same clip as sina_loader.py:115-118."
+ ),
+ "caliber_note": _US_CALIBER_NOTE,
+ },
+)
+
+
+def _write_atomic(path: Path, document: dict[str, Any]) -> None:
+ payload = json.dumps(document, indent=2, ensure_ascii=False) + "\n"
+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ # mkstemp creates 0600; fixtures are normal readable data files.
+ os.chmod(tmp_name, 0o644)
+ os.replace(tmp_name, path)
+ finally:
+ if os.path.exists(tmp_name):
+ os.unlink(tmp_name)
+
+
+def record_spec(spec: dict[str, Any], market_dir: Path, force: bool) -> Optional[Path]:
+ path = market_dir / spec["file"]
+ if path.exists() and not force:
+ LOG.info("exists, skipping (use --force to re-record): %s", path.name)
+ return None
+ text = _http_get(spec["request_url"], spec["headers"])
+ raw_rows: list[dict[str, Any]] = spec["parser"](text)
+ bars, stats = _normalize(raw_rows, WINDOW_START, WINDOW_END, spec["file"])
+ if not bars:
+ raise RuntimeError(f"{spec['file']}: upstream produced no usable bars")
+ fixture: dict[str, Any] = {
+ "schema": FIXTURE_SCHEMA,
+ "market": spec["market"],
+ "symbol": spec["symbol"],
+ "source": spec["source"],
+ "price_caliber": spec["price_caliber"],
+ "volume_unit": spec["volume_unit"],
+ "volume_unit_note": spec["volume_unit_note"],
+ "request_url": spec["request_url"],
+ "request_headers": spec["headers"],
+ "window": {"start": WINDOW_START, "end": WINDOW_END},
+ "window_note": spec["window_note"],
+ "recorded_at_utc": _utcnow_iso(),
+ "caliber_note": spec["caliber_note"],
+ "drop_stats": stats,
+ "bars": bars,
+ }
+ _write_atomic(path, fixture)
+ LOG.info("wrote %s: %d bars %s..%s", path.name, len(bars), bars[0]["date"], bars[-1]["date"])
+ return path
+
+
+def build_manifest(market_dir: Path) -> Path:
+ """Recompute MANIFEST.json from the fixture files on disk (byte hashes)."""
+ entries: list[dict[str, Any]] = []
+ for path in sorted(market_dir.glob("*.json")):
+ if path.name == "MANIFEST.json":
+ continue
+ raw = path.read_bytes()
+ document: dict[str, Any] = json.loads(raw)
+ bars: list[dict[str, Any]] = document.get("bars", [])
+ entries.append(
+ {
+ "file": path.name,
+ "sha256": hashlib.sha256(raw).hexdigest(),
+ "bytes": len(raw),
+ "rows": len(bars),
+ "first_date": bars[0]["date"] if bars else None,
+ "last_date": bars[-1]["date"] if bars else None,
+ "market": document.get("market"),
+ "symbol": document.get("symbol"),
+ "source": document.get("source"),
+ "price_caliber": document.get("price_caliber"),
+ "volume_unit": document.get("volume_unit"),
+ "request_url": document.get("request_url"),
+ "window": document.get("window"),
+ "recorded_at_utc": document.get("recorded_at_utc"),
+ "drop_stats": document.get("drop_stats"),
+ "caliber_note": document.get("caliber_note"),
+ "construction": document.get("synthetic_construction"),
+ }
+ )
+ manifest: dict[str, Any] = {
+ "schema": MANIFEST_SCHEMA,
+ "generator": "record_market_fixtures.py (manual tool; tests never run it)",
+ "description": (
+ "Tamper-evident index over agent/tests/fixtures/paper_trade/market/*.json."
+ " sha256 is of the exact on-disk bytes; test_paper_trade_fixtures.py"
+ " re-verifies them. Recorded fixtures are byte-frozen snapshots of the"
+ " listed request_url replies (VD-14); synthetic fixtures are authored,"
+ " engine-facing inputs for T7/T5, and their construction is documented"
+ " per file."
+ ),
+ "fixtures": entries,
+ }
+ path = market_dir / "MANIFEST.json"
+ _write_atomic(path, manifest)
+ LOG.info("rebuilt %s over %d fixtures", path.name, len(entries))
+ return path
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument(
+ "--market-dir",
+ type=Path,
+ default=_HERE / "market",
+ help="fixture directory (default: ./market next to this script)",
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ help="re-record and overwrite existing real fixtures (needs live network)",
+ )
+ parser.add_argument(
+ "--manifest-only",
+ action="store_true",
+ help="skip all HTTP; only rebuild MANIFEST.json from the files on disk",
+ )
+ args = parser.parse_args(argv)
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
+
+ market_dir: Path = args.market_dir
+ market_dir.mkdir(parents=True, exist_ok=True)
+
+ if not args.manifest_only:
+ for spec in SPECS:
+ record_spec(spec, market_dir, args.force)
+
+ build_manifest(market_dir)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/agent/tests/fixtures/paper_trade/strategies/golden_sample_sma.py b/agent/tests/fixtures/paper_trade/strategies/golden_sample_sma.py
new file mode 100644
index 000000000..598f87668
--- /dev/null
+++ b/agent/tests/fixtures/paper_trade/strategies/golden_sample_sma.py
@@ -0,0 +1,63 @@
+"""Golden sample paper-trade strategy (T7 / VD-8 minimal ctx contract).
+
+The reference strategy for the ``paper_trade_step`` strategy_path mode: an
+SMA(5)/SMA(20) crossover over the served universe. It exercises exactly the
+frozen minimal ctx surface and nothing more (R-V11):
+
+* ``ctx.account_state`` — read-only ledger after previous days have matched.
+* ``ctx.symbols`` — the served universe, sorted.
+* ``ctx.history(symbol)`` — OHLCV bars strictly before ``trade_date``
+ (orders fill at the execution day’s close), as a copy.
+* ``ctx.sma(close, period)`` — the technical_indicators pure-function surface.
+
+Declares the optional module-level ``UNIVERSE`` literal (the strategy-universe
+convention): a pure AST read (``strategy_exec.strategy_universe``, never an
+execution) extracts it, the T6 tool unions it into the market-data fetch
+universe, and the executor unions it into ``ctx.symbols`` — so the strategy
+also serves a cash-only account whose empty position list would otherwise
+prefetch nothing. Absent or malformed declarations fall back to the served
+universe (positions ∪ fetched symbols).
+
+Contract shape (enforced by the executor): ``class SignalEngine`` with
+``generate_signals(self, ctx, trade_date)`` returning a list of order objects
+``{"symbol", "side", "qty", "limit"?, "reason"?}``. The class name matters:
+``SignalEngine`` is the entry the backtest AST sandbox's runtime-reachable
+scrubber scans, so this file is validated by the same hardened pass as every
+backtest signal engine (AM-8 — no raw import, no network/subprocess/eval/
+os.environ/unsafe-open anywhere on the executed path).
+
+Deterministic by construction: no clock, no randomness, no I/O — the same
+file + ledger state + trading day always yields the same orders.
+"""
+
+UNIVERSE = ("SYNTH-4TO1",)
+
+
+class SignalEngine:
+ """SMA(5)/SMA(20) crossover: buy 100 on a golden cross, exit on a death cross."""
+
+ def generate_signals(self, ctx, trade_date):
+ held = {position.symbol: position.qty for position in ctx.account_state.positions}
+ orders = []
+ for symbol in ctx.symbols:
+ close = ctx.history(symbol)["close"]
+ fast = ctx.sma(close, 5)
+ slow = ctx.sma(close, 20)
+ if fast is None or slow is None:
+ continue
+ quantity = held.get(symbol, 0.0)
+ if fast > slow and quantity == 0.0:
+ orders.append({
+ "symbol": symbol,
+ "side": "buy",
+ "qty": 100,
+ "reason": f"golden sma5 {fast:.4f} > sma20 {slow:.4f}",
+ })
+ elif fast < slow and quantity > 0.0:
+ orders.append({
+ "symbol": symbol,
+ "side": "sell",
+ "qty": quantity,
+ "reason": f"golden sma5 {fast:.4f} < sma20 {slow:.4f}",
+ })
+ return orders
diff --git a/agent/tests/test_mcp_server_smoke.py b/agent/tests/test_mcp_server_smoke.py
index 920a2c9ab..998a6f674 100644
--- a/agent/tests/test_mcp_server_smoke.py
+++ b/agent/tests/test_mcp_server_smoke.py
@@ -62,6 +62,7 @@ REQUIRED_TOOL_NAMES = {
"trading_history",
"alpha_zoo",
"alpha_bench",
+ "paper_trade_step",
}
diff --git a/agent/tests/test_paper_accounts.py b/agent/tests/test_paper_accounts.py
new file mode 100644
index 000000000..ce93d22e5
--- /dev/null
+++ b/agent/tests/test_paper_accounts.py
@@ -0,0 +1,262 @@
+"""Forward account clocks, real matching, persistence and concurrent writes."""
+
+import json
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime, timezone
+from threading import Barrier
+
+import pandas as pd
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from src.api import paper_trade_routes as routes
+from src.tools.paper_trade.accounts import AccountConflict, PaperAccounts
+from src.tools.paper_trade.tool import run_paper_trade_step
+
+
+class RawLoader:
+ name = "sina"
+
+ def fetch(self, codes, *args, **kwargs):
+ return {
+ code: pd.DataFrame(
+ {
+ "open": [10.0, 11.0],
+ "high": [10.0, 11.0],
+ "low": [10.0, 11.0],
+ "close": [10.0, 11.0],
+ "volume": [1000.0, 1000.0],
+ },
+ index=pd.to_datetime(["2026-10-19", "2026-10-20"]),
+ )
+ for code in codes
+ }
+
+
+def matching(payload):
+ return run_paper_trade_step(payload, loader=RawLoader(), _orders_at_end=True)
+
+
+def service(tmp_path):
+ return PaperAccounts(
+ tmp_path / "accounts.db",
+ clock=lambda: datetime(2026, 10, 20, 22, tzinfo=timezone.utc),
+ step=matching,
+ )
+
+
+def create(service, **kwargs):
+ return service.create(
+ label="Research",
+ market="us",
+ account_state={"cash": 1000, "positions": []},
+ **kwargs,
+ )
+
+
+def test_real_step_persists_and_prevents_replay(service):
+ account = create(service)
+ reply = service.advance(
+ account["id"],
+ expected_revision=0,
+ to_date="2026-10-20",
+ orders=[{"symbol": "AAPL.US", "side": "buy", "qty": 10}],
+ )
+ assert reply["committed"]
+ assert reply["account"]["account_state"]["cash"] == 889.01
+ assert service.get(account["id"])["revision"] == 1
+ assert service.history(account["id"])[0]["fills"][0]["price"] == 11
+ with pytest.raises(AccountConflict):
+ service.advance(
+ account["id"], expected_revision=0, to_date="2026-10-20", orders=[]
+ )
+ with pytest.raises(ValueError, match="Execution date"):
+ service.advance(
+ account["id"], expected_revision=1, to_date="2026-10-20", orders=[]
+ )
+
+
+def test_no_backdating_future_or_incomplete_session(service):
+ account = create(service)
+ for day in ("2026-10-19", "2026-10-21"):
+ with pytest.raises(ValueError, match="Execution date"):
+ service.advance(account["id"], expected_revision=0, to_date=day, orders=[])
+ service.clock = lambda: datetime(2026, 10, 20, 20, 10, tzinfo=timezone.utc)
+ with pytest.raises(ValueError, match="completed session"):
+ service.advance(
+ account["id"], expected_revision=0, to_date="2026-10-20", orders=[]
+ )
+ assert service.get(account["id"])["revision"] == 0
+
+
+def test_next_session_start_uses_market_timezone_and_skips_weekend(service):
+ service.clock = lambda: datetime(
+ 2026, 10, 24, 1, tzinfo=timezone.utc
+ ) # Friday in NY
+ account = create(service, start="next_session")
+ assert account["start_on"] == "2026-10-26"
+
+
+def test_failure_does_not_save_or_consume_revision(service):
+ account = create(service)
+ service.step = lambda _: json.dumps(
+ {"status": "error", "code": "PAPER_DATA_NOT_READY"}
+ )
+ reply = service.advance(
+ account["id"], expected_revision=0, to_date="2026-10-20", orders=[]
+ )
+ assert not reply["committed"]
+ assert service.get(account["id"]) == account
+ assert service.history(account["id"]) == []
+
+
+def test_concurrent_match_commits_only_once(service):
+ account = create(service)
+ barrier = Barrier(2)
+
+ def step(payload):
+ result = matching(payload)
+ barrier.wait(timeout=10)
+ return result
+
+ def advance():
+ another = PaperAccounts(service.path, clock=service.clock, step=step)
+ try:
+ return another.advance(
+ account["id"], expected_revision=0, to_date="2026-10-20", orders=[]
+ )
+ except AccountConflict:
+ return "conflict"
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ results = list(pool.map(lambda _: advance(), range(2)))
+ assert results.count("conflict") == 1
+ assert len(service.history(account["id"])) == 1
+
+
+def test_api_and_cli_share_saved_account(service, monkeypatch, capsys, tmp_path):
+ from cli.commands import paper_trade as cli
+ import argparse
+
+ monkeypatch.setattr(routes, "PaperAccounts", lambda: service)
+ monkeypatch.setattr(cli, "PaperAccounts", lambda: service)
+ app = FastAPI()
+ routes.register_paper_trade_routes(app)
+ app.dependency_overrides[routes.require_auth] = lambda: None
+ app.dependency_overrides[routes.require_settings_write_auth] = lambda: None
+ client = TestClient(app)
+ created = client.post(
+ "/api/paper-accounts",
+ json={
+ "label": "Web account",
+ "market": "us",
+ "account_state": {"cash": 500, "positions": []},
+ },
+ )
+ assert created.status_code == 200
+ account = created.json()
+ parser = argparse.ArgumentParser()
+ cli.add_parser(parser.add_subparsers(dest="command"))
+ assert cli.dispatch(parser.parse_args(["paper", "show", account["id"]])) == 0
+ assert json.loads(capsys.readouterr().out)["label"] == "Web account"
+ reply = client.post(
+ f'/api/paper-accounts/{account["id"]}/advance',
+ json={"expected_revision": 0, "to_date": "2026-10-20", "orders": []},
+ )
+ assert reply.status_code == 200 and reply.json()["committed"]
+ assert (
+ client.post(
+ f'/api/paper-accounts/{account["id"]}/advance',
+ json={"expected_revision": 0, "to_date": "2026-10-20", "orders": []},
+ ).status_code
+ == 409
+ )
+ assert (
+ client.get(f'/api/paper-accounts/{account["id"]}/history').json()[0][
+ "end_state"
+ ]["cash"]
+ == 500
+ )
+
+
+def test_api_write_auth_cannot_be_bypassed_by_read_auth(service, monkeypatch):
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(routes, "PaperAccounts", lambda: service)
+ app = FastAPI()
+ routes.register_paper_trade_routes(app)
+ app.dependency_overrides[routes.require_auth] = lambda: None
+
+ def refuse():
+ raise HTTPException(403, "write denied")
+
+ app.dependency_overrides[routes.require_settings_write_auth] = refuse
+ client = TestClient(app)
+ assert client.get("/api/paper-accounts").status_code == 200
+ assert (
+ client.post(
+ "/api/paper-accounts",
+ json={"label": "x", "market": "us", "account_state": {"cash": 1}},
+ ).status_code
+ == 403
+ )
+ assert client.post("/api/paper-trade/step", json={}).status_code == 403
+
+
+def test_saved_account_scans_intervening_days_before_applying_target_orders(service):
+ service.clock = lambda: datetime(2026, 10, 19, 22, tzinfo=timezone.utc)
+ account = create(service)
+ service.clock = lambda: datetime(2026, 10, 20, 22, tzinfo=timezone.utc)
+ reply = service.advance(
+ account["id"],
+ expected_revision=0,
+ to_date="2026-10-20",
+ orders=[{"symbol": "AAPL.US", "side": "buy", "qty": 1}],
+ )
+ assert [n["date"] for n in reply["result"]["nav_series"]] == [
+ "2026-10-19",
+ "2026-10-20",
+ ]
+ assert [f["trade_date"] for f in reply["result"]["fills"]] == ["2026-10-20"]
+
+
+def test_account_cannot_skip_over_an_unverified_split(service):
+ class SplitLoader:
+ name = "sina"
+
+ def fetch(self, codes, *args, **kwargs):
+ return {
+ code: pd.DataFrame(
+ {
+ "open": [100.0, 25.0, 26.0],
+ "high": [100.0, 25.0, 26.0],
+ "low": [100.0, 25.0, 26.0],
+ "close": [100.0, 25.0, 26.0],
+ "volume": [1000.0, 4000.0, 4000.0],
+ },
+ index=pd.to_datetime(["2026-10-19", "2026-10-20", "2026-10-21"]),
+ )
+ for code in codes
+ }
+
+ service.clock = lambda: datetime(2026, 10, 19, 22, tzinfo=timezone.utc)
+ account = service.create(
+ label="Split check",
+ market="us",
+ account_state={
+ "cash": 1000,
+ "positions": [{"symbol": "AAPL.US", "qty": 100, "avg_cost": 100}],
+ },
+ )
+ service.clock = lambda: datetime(2026, 10, 21, 22, tzinfo=timezone.utc)
+ service.step = lambda payload: run_paper_trade_step(
+ payload, loader=SplitLoader(), _orders_at_end=True
+ )
+ result = service.advance(
+ account["id"], expected_revision=0, to_date="2026-10-21", orders=[]
+ )
+ assert not result["committed"]
+ assert result["result"]["code"] == "PAPER_DATA_NOT_READY"
+ assert service.get(account["id"]) == account
diff --git a/agent/tests/test_paper_trade_calendar.py b/agent/tests/test_paper_trade_calendar.py
new file mode 100644
index 000000000..929e9ce6c
--- /dev/null
+++ b/agent/tests/test_paper_trade_calendar.py
@@ -0,0 +1,139 @@
+"""Offline tests for the paper_trade calendar seam (AM-6 / VD-5).
+
+cn_a: ClickHouse trade_calendar lookup through an INJECTABLE fake client —
+recorded rows only, never the network (ClickHouse is unreachable anyway;
+the plan raised HIL for live probes). hk/us: the approved AM-6
+zero-calendar design (G1 2026-10-19) — calendar lookups stay closed
+(NotImplementedError); day verdicts flow through bar availability in
+calendar.classify_zero_calendar_day instead.
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade.calendar import is_trading_day, trading_days_in_range
+
+_COLUMNS = ["exchange", "cal_date", "is_open", "pretrade_date"]
+
+
+class FakeCalendarClient:
+ """Returns recorded trade_calendar rows; captures requested ranges."""
+
+ def __init__(self, rows: list[tuple[str, str, int]]) -> None:
+ self.requested_ranges: list[tuple[str, str]] = []
+ self._records = [
+ {"exchange": exchange, "cal_date": cal_date, "is_open": is_open, "pretrade_date": ""}
+ for exchange, cal_date, is_open in rows
+ ]
+
+ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:
+ self.requested_ranges.append((start_date, end_date))
+ return pd.DataFrame(self._records, columns=_COLUMNS)
+
+
+# A realistic cn_a week: Thu 10-15 .. Tue 10-20, weekend closed, plus the
+# National Day holiday 2026-10-01.
+_OCTOBER_ROWS: list[tuple[str, str, int]] = [
+ ("SSE", "2026-10-01", 0),
+ ("SSE", "2026-10-15", 1),
+ ("SSE", "2026-10-16", 1),
+ ("SSE", "2026-10-17", 0),
+ ("SSE", "2026-10-18", 0),
+ ("SSE", "2026-10-19", 1),
+ ("SSE", "2026-10-20", 1),
+]
+
+
+def cn_a_client() -> FakeCalendarClient:
+ return FakeCalendarClient(_OCTOBER_ROWS)
+
+
+def test_open_trading_day_is_true(cn_a_client: FakeCalendarClient) -> None:
+ assert is_trading_day(cn_a_client, "cn_a", "2026-10-20") is True
+
+
+def test_weekend_row_is_false(cn_a_client: FakeCalendarClient) -> None:
+ assert is_trading_day(cn_a_client, "cn_a", "2026-10-18") is False
+
+
+def test_holiday_row_is_false(cn_a_client: FakeCalendarClient) -> None:
+ assert is_trading_day(cn_a_client, "cn_a", "2026-10-01") is False
+
+
+def test_missing_row_fails_closed_to_false(cn_a_client: FakeCalendarClient) -> None:
+ # The table is the truth source: a date it does not cover is NOT a
+ # confirmed trading day.
+ assert is_trading_day(cn_a_client, "cn_a", "2026-12-25") is False
+
+
+def test_multi_exchange_rows_aggregate_as_any_open() -> None:
+ client = FakeCalendarClient(
+ [("SSE", "2026-10-20", 1), ("SZSE", "2026-10-20", 0), ("SSE", "2026-10-19", 0), ("SZSE", "2026-10-19", 0)]
+ )
+ assert is_trading_day(client, "cn_a", "2026-10-20") is True
+ assert is_trading_day(client, "cn_a", "2026-10-19") is False
+
+
+def test_trading_days_in_range_enumerates_ascending(cn_a_client: FakeCalendarClient) -> None:
+ days = trading_days_in_range(cn_a_client, "cn_a", "2026-10-15", "2026-10-20")
+ assert days == ("2026-10-15", "2026-10-16", "2026-10-19", "2026-10-20")
+
+
+def test_range_is_passed_through_to_the_client(cn_a_client: FakeCalendarClient) -> None:
+ trading_days_in_range(cn_a_client, "cn_a", "2026-10-15", "2026-10-20")
+ assert cn_a_client.requested_ranges == [("2026-10-15", "2026-10-20")]
+
+
+def test_single_day_lookup_queries_that_day_only(cn_a_client: FakeCalendarClient) -> None:
+ is_trading_day(cn_a_client, "cn_a", "2026-10-20")
+ assert cn_a_client.requested_ranges == [("2026-10-20", "2026-10-20")]
+
+
+def test_out_of_range_rows_from_a_sloppy_client_are_clamped() -> None:
+ client = FakeCalendarClient([("SSE", "2026-10-20", 1), ("SSE", "2026-11-02", 1)])
+ assert trading_days_in_range(client, "cn_a", "2026-10-19", "2026-10-21") == ("2026-10-20",)
+
+
+def test_yyyymmdd_cal_date_spelling_is_normalized() -> None:
+ # The stored cal_date spelling is unverified while CH is unreachable
+ # (Step 0 DD-5 live recheck pending); tushare-lineage exports use
+ # YYYYMMDD. Both spellings must serve the same verdicts.
+ client = FakeCalendarClient([("SSE", "20261020", 1), ("SSE", "20261018", 0)])
+ assert is_trading_day(client, "cn_a", "2026-10-20") is True
+ assert is_trading_day(client, "cn_a", "2026-10-18") is False
+ assert trading_days_in_range(client, "cn_a", "2026-10-18", "2026-10-20") == ("2026-10-20",)
+
+
+def test_unrecognized_date_format_fails_closed(cn_a_client: FakeCalendarClient) -> None:
+ with pytest.raises(ValueError, match="unrecognized calendar date"):
+ is_trading_day(cn_a_client, "cn_a", "2026/10/20")
+
+
[email protected]("market", ["hk", "us"])
+def test_hk_and_us_calendar_lookups_stay_closed_by_am6_design(
+ cn_a_client: FakeCalendarClient, market: str
+) -> None:
+ # AM-6 zero-calendar design, APPROVED at G1 (2026-10-19): hk/us day
+ # verdicts come from bar availability (calendar.classify_zero_calendar_day
+ # over the data layer's facts), never from a calendar lookup — the repo
+ # carries no hk/us calendar and the zero-new-dependency red line forbids
+ # one. These lookups staying NotImplementedError IS the approved
+ # fail-closed behavior (tested via the T2/T3 matrix seams), not a gap.
+ with pytest.raises(NotImplementedError, match="zero-calendar"):
+ is_trading_day(cn_a_client, market, "2026-10-20")
+ with pytest.raises(NotImplementedError, match="zero-calendar"):
+ trading_days_in_range(cn_a_client, market, "2026-10-15", "2026-10-20")
+
+
+def test_unknown_market_raises_value_error(cn_a_client: FakeCalendarClient) -> None:
+ with pytest.raises(ValueError, match="unknown market"):
+ is_trading_day(cn_a_client, "crypto", "2026-10-20")
+
+
+def test_lookups_are_deterministic(cn_a_client: FakeCalendarClient) -> None:
+ first = trading_days_in_range(cn_a_client, "cn_a", "2026-10-01", "2026-10-20")
+ second = trading_days_in_range(cn_a_client, "cn_a", "2026-10-01", "2026-10-20")
+ assert first == second
diff --git a/agent/tests/test_paper_trade_corporate_actions.py b/agent/tests/test_paper_trade_corporate_actions.py
new file mode 100644
index 000000000..cf09438c2
--- /dev/null
+++ b/agent/tests/test_paper_trade_corporate_actions.py
@@ -0,0 +1,475 @@
+"""T7-gate corporate-action matrix for the paper_trade engine (Step 4 / T4).
+
+Covers R6/AM-2/VD-6: the frozen clean-ratio set, the triple gate (price /
+volume / NAV-continuity), the fail-closed unresolved path (structured
+``corporate_action_unresolved`` rejection — never a guessed ratio, never a
+silent pass, never a half-day), note-2 scan semantics (a historical split
+inside the K=120 lookback never fires), the cn_a call-site exemption, the
+union of the detector with the injectable T3 seam, and the skipped-day
+semantics (``market_closed_inferred`` + warning, ``suspended`` carry-forward)
+extended — not duplicated — from the T3 rejections matrix. Market data =
+the frozen VD-14 fixture ``synthetic_split_4to1.json`` (event 2026-02-02,
+476.0 → 119.0, volume 1e6 → 4e6) reused for BOTH hk and us: the detector is
+market-agnostic. Offline: fixture-backed fake loaders only.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from decimal import Decimal
+from fractions import Fraction
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade import corporate_actions, engine
+from src.tools.paper_trade.data import fetch_market_data
+from src.tools.paper_trade.schema import (
+ REASON_CODES, AccountState, Order, Position, parse_request,
+)
+
+_FIXTURE = Path(__file__).parent / "fixtures" / "paper_trade" / "market" / "synthetic_split_4to1.json"
+_SYM = "SYNTH-4TO1"
+_PREV = "2026-01-30" # bar 19, close 476.0, volume 1e6
+_EX = "2026-02-02" # bar 20 = ex-date, close 119.0, volume 4e6 (frozen fixture)
+_NEXT = "2026-02-03" # bar 21, close 119.5
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "sina") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+class FakeChClient:
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ return pd.DataFrame()
+
+
+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 _fixture_frame() -> pd.DataFrame:
+ document = json.loads(_FIXTURE.read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]]
+
+
+def _frame(rows: list[tuple[str, float, float]]) -> pd.DataFrame:
+ records = [
+ {"trade_date": day, "open": close, "high": close, "low": close, "close": close,
+ "volume": volume}
+ for day, close, volume in rows
+ ]
+ frame = pd.DataFrame(records)
+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])
+ return frame.set_index("trade_date")
+
+
+def _fetch(market: str, frames: dict[str, pd.DataFrame], from_date: str, to_date: str,
+ symbols: list[str] | None = None):
+ return fetch_market_data(market, symbols if symbols is not None else list(frames),
+ from_date, to_date, loader=FakeLoader(frames))
+
+
+def _request(market: str, cash: float, positions: list[dict], orders: list[dict], day: str):
+ return parse_request({
+ "account_id": "pa_ca", "market": market,
+ "account_state": {"cash": cash, "positions": positions},
+ "orders": orders, "from_date": day, "to_date": day, "fee_model": {},
+ })
+
+
+def _codes(outcome) -> list[str]:
+ return [rejected.reason_code for rejected in outcome.rejected_orders]
+
+
+# ── The frozen detector contract (pure unit level) ──
+
+
+def test_frozen_ratio_set_is_exactly_the_contract_set() -> None:
+ # R6-1/VD-6: {2,3,4,5,10,3/2} ∪ reciprocals — qty-multiplier semantics.
+ assert corporate_actions.CLEAN_QTY_MULTIPLIERS == (
+ Fraction(2), Fraction(3), Fraction(4), Fraction(5), Fraction(10), Fraction(3, 2),
+ Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5), Fraction(1, 10),
+ Fraction(2, 3),
+ )
+ assert corporate_actions.NAV_CONTINUITY_REL_TOL == Fraction(1, 10000) # ±0.01% frozen
+
+
[email protected]("mult", corporate_actions.CLEAN_QTY_MULTIPLIERS)
+def test_every_frozen_multiplier_classifies_clean(mult: Fraction) -> None:
+ # close 60.0 → 60/mult and volume 1200 → 1200×mult are exact decimals for
+ # every frozen multiplier, so the triple gate passes with zero slack.
+ verdict = corporate_actions.classify_boundary(
+ close_before=60.0, close_after=float(Decimal(60) / Decimal(mult.numerator) * Decimal(mult.denominator)),
+ volume_before=1200.0,
+ volume_after=float(Decimal(1200) * Decimal(mult.numerator) / Decimal(mult.denominator)),
+ qty=Decimal(100))
+ assert verdict.kind == corporate_actions.KIND_CLEAN
+ assert verdict.qty_multiplier == mult
+
+
+def test_classify_clean_4to1_uses_the_fixture_numbers() -> None:
+ verdict = corporate_actions.classify_boundary(
+ close_before=476.0, close_after=119.0,
+ volume_before=1_000_000.0, volume_after=4_000_000.0, qty=Decimal(100))
+ assert verdict.kind == corporate_actions.KIND_CLEAN
+ assert verdict.qty_multiplier == Fraction(4)
+ assert verdict.observed_ratio == Decimal("0.25")
+
+
[email protected](("before", "after", "vol_after"), [
+ (100.0, 40.0, 2_500_000.0), # 0.4x crash-shaped, volume "confirms" 2.5x
+ (100.0, 250.0, 400_000.0), # 2.5x jump-shaped, volume "confirms" 0.4x
+])
+def test_non_clean_large_discontinuity_is_unresolved_never_guessed(
+ before: float, after: float, vol_after: float) -> None:
+ verdict = corporate_actions.classify_boundary(
+ close_before=before, close_after=after,
+ volume_before=1_000_000.0, volume_after=vol_after, qty=Decimal(100))
+ assert verdict.kind == corporate_actions.KIND_UNRESOLVED
+ assert verdict.qty_multiplier is None # never guess a ratio
+
+
+def test_clean_price_ratio_with_wrong_volume_is_unresolved() -> None:
+ # Exact 0.25 price ratio but volume did NOT move 4x → the same-direction
+ # multiple confirmation fails → fail-closed, not a silent split.
+ verdict = corporate_actions.classify_boundary(
+ close_before=476.0, close_after=119.0,
+ volume_before=1_000_000.0, volume_after=1_000_000.0, qty=Decimal(100))
+ assert verdict.kind == corporate_actions.KIND_UNRESOLVED
+
+
[email protected]("vol_after", [0.0, float("nan")])
+def test_unverifiable_volume_on_a_candidate_fails_closed(vol_after: float) -> None:
+ verdict = corporate_actions.classify_boundary(
+ close_before=100.0, close_after=50.0,
+ volume_before=1000.0, volume_after=vol_after, qty=Decimal(100))
+ assert verdict.kind == corporate_actions.KIND_UNRESOLVED
+
+
+def test_nav_gate_is_the_binding_confirmation_for_held_positions() -> None:
+ # Price ratio 119.06/476.0 = 0.250126… passes the 1e-3 price gate but the
+ # adjusted NAV drifts 0.05% > the frozen ±0.01% → unresolved when held …
+ kwargs = dict(close_before=476.0, close_after=119.06,
+ volume_before=1_000_000.0, volume_after=4_000_000.0)
+ held = corporate_actions.classify_boundary(qty=Decimal(100), **kwargs)
+ assert held.kind == corporate_actions.KIND_UNRESOLVED
+ # … and vacuous for a flat symbol (no ledger to preserve): the price gate
+ # (1e-3) governs. Documented asymmetry — registered in the STEP4 receipt.
+ flat = corporate_actions.classify_boundary(qty=Decimal(0), **kwargs)
+ assert flat.kind == corporate_actions.KIND_CLEAN
+ assert flat.qty_multiplier == Fraction(4)
+
+
[email protected](("before", "after"), [
+ (100.0, 100.0), (100.0, 70.0), (100.0, 140.0), (100.0, 67.0), (100.0, 149.0),
+])
+def test_neutral_band_moves_are_not_candidates(before: float, after: float) -> None:
+ verdict = corporate_actions.classify_boundary(
+ close_before=before, close_after=after,
+ volume_before=1000.0, volume_after=4000.0, qty=Decimal(100))
+ assert verdict.kind == corporate_actions.KIND_NONE
+
+
[email protected](("before", "after"), [
+ (0.0, 100.0), (-5.0, 100.0), (float("nan"), 100.0), (100.0, float("nan")), (100.0, 0.0),
+])
+def test_missing_or_non_positive_closes_are_insufficient_evidence(
+ before: float, after: float) -> None:
+ verdict = corporate_actions.classify_boundary(
+ close_before=before, close_after=after,
+ volume_before=1000.0, volume_after=4000.0, qty=Decimal(100))
+ assert verdict.kind == corporate_actions.KIND_NONE # no event, no crash
+
+
+# ── Engine integration: the clean 4:1 path (dual market, one fixture) ──
+
+
[email protected]("market", ["hk", "us"])
+def test_clean_price_ratio_cannot_authorize_a_ledger_split(market: str) -> None:
+ # The fixture resembles a 4:1 split, but the same OHLC/volume can be a
+ # crash. It cannot authorize creating 300 additional shares.
+ market_data = _fetch(market, {_SYM: _fixture_frame()}, _PREV, _EX)
+ outcome = engine.run_day_loop(
+ market=market,
+ account_state=AccountState(cash=100000.0,
+ positions=(_position(_SYM, 100, 400.0),)),
+ from_date=_PREV, to_date=_EX, orders_by_day={}, market_data=market_data,
+ )
+ assert outcome.error is not None
+ assert outcome.error.code == "PAPER_DATA_NOT_READY"
+ assert "cannot establish a split" in outcome.error.message
+ assert outcome.fills == ()
+ assert outcome.nav_series == ()
+ assert outcome.end_state.positions[0].qty == 100
+
+
[email protected](("market", "fee"), [("hk", 63.71), ("us", 1.96)])
+def test_no_sale_of_inferred_extra_shares(market: str, fee: float) -> None:
+ # from_date IS the ex-date: the BEFORE bar (2026-01-30) lives in the K=120
+ # lookback — the note-2 window requirement. Selling 400 (the ADJUSTED qty)
+ # can only fill if the split applied BEFORE matching; without it the ladder
+ # would reject insufficient_position (only 100 held).
+ market_data = _fetch(market, {_SYM: _fixture_frame()}, _EX, _EX)
+ outcome = engine.match_orders(
+ _request(market, 10000.0, [_position_dict(_SYM, 100, 400.0)],
+ [{"symbol": _SYM, "side": "sell", "qty": 400}], _EX),
+ market_data=market_data,
+ )
+ assert outcome.error is not None
+ assert outcome.error.code == "PAPER_DATA_NOT_READY"
+ assert "cannot establish a split" in outcome.error.message
+ assert outcome.fills == ()
+ assert outcome.nav_series == ()
+ assert outcome.end_state.positions[0].qty == 100
+
+
+def test_clean_split_run_is_deterministic_and_warning_timestamp_free() -> None:
+ market_data = _fetch("us", {_SYM: _fixture_frame()}, _PREV, _EX)
+ state = AccountState(cash=100000.0, positions=(_position(_SYM, 100, 400.0),))
+ first = engine.run_day_loop(market="us", account_state=state, from_date=_PREV, to_date=_EX,
+ orders_by_day={}, market_data=market_data)
+ second = engine.run_day_loop(market="us", account_state=state, from_date=_PREV, to_date=_EX,
+ orders_by_day={}, market_data=market_data)
+ assert first.warnings == second.warnings
+ assert first.nav_series == second.nav_series
+ assert first.end_state == second.end_state
+ assert first.data_provenance == second.data_provenance
+ for warning in first.warnings: # VD-7: deterministic English, no timestamps
+ assert re.search(r"\d{2}:\d{2}", warning) is None
+
+
+# ── Engine integration: the fail-closed unresolved path ──
+
+
[email protected](("rows", "ratio_str"), [
+ ([("2026-03-02", 100.0, 1_000_000.0), ("2026-03-03", 40.0, 2_500_000.0)], "0.4"),
+ ([("2026-03-02", 100.0, 1_000_000.0), ("2026-03-03", 250.0, 400_000.0)], "2.5"),
+])
+def test_unresolved_discontinuity_rejects_fail_closed_no_half_day(
+ rows: list[tuple[str, float, float]], ratio_str: str) -> None:
+ day = rows[-1][0]
+ market_data = _fetch("us", {"DIRTY.US": _frame(rows)}, day, day)
+ outcome = engine.match_orders(
+ _request("us", 100000.0, [_position_dict("DIRTY.US", 100, 90.0)],
+ [{"symbol": "DIRTY.US", "side": "buy", "qty": 10}], day),
+ market_data=market_data,
+ )
+ assert outcome.error is None # in-band structured rejection, never a crash
+ assert _codes(outcome) == ["corporate_action_unresolved"]
+ assert outcome.rejected_orders[0].reason_code in REASON_CODES # frozen vocabulary
+ assert "fail-closed" in outcome.rejected_orders[0].detail
+ assert outcome.fills == ()
+ assert len(outcome.nav_series) == 1 # the day still commits exactly one nav row
+ position = outcome.end_state.positions[0]
+ assert (position.qty, position.avg_cost) == (100, 90.0) # NOT adjusted
+ assert outcome.nav_series[0].position_value == 100 * rows[-1][1] # valued at the day's close
+ assert outcome.data_provenance.corporate_actions == (
+ {"symbol": "DIRTY.US", "date": day, "ratio": ratio_str, "detected": False},)
+ assert any("corporate action unresolved" in w and "DIRTY.US" in w for w in outcome.warnings)
+
+
+def test_clean_ratio_with_wrong_volume_rejects_instead_of_splitting() -> None:
+ # Exact 0.25 close ratio but flat volume: the engine must NOT silently
+ # apply the split — the symbol's orders reject and the ledger stays put.
+ frames = {_SYM: _frame([(_PREV, 476.0, 1_000_000.0), (_EX, 119.0, 1_000_000.0)])}
+ market_data = _fetch("us", frames, _EX, _EX)
+ outcome = engine.match_orders(
+ _request("us", 10000.0, [_position_dict(_SYM, 100, 400.0)],
+ [{"symbol": _SYM, "side": "sell", "qty": 400}], _EX),
+ market_data=market_data,
+ )
+ assert _codes(outcome) == ["corporate_action_unresolved"]
+ assert outcome.fills == ()
+ position = outcome.end_state.positions[0]
+ assert (position.qty, position.avg_cost) == (100, 400.0)
+ assert outcome.data_provenance.corporate_actions[0]["detected"] is False
+
+
+def test_missing_volume_on_a_candidate_day_rejects_fail_closed() -> None:
+ frames = {"NOVOL.US": _frame([(_PREV, 100.0, 1000.0), (_EX, 50.0, float("nan"))])}
+ market_data = _fetch("us", frames, _EX, _EX)
+ outcome = engine.match_orders(
+ _request("us", 10000.0, [], [{"symbol": "NOVOL.US", "side": "buy", "qty": 10}], _EX),
+ market_data=market_data,
+ )
+ assert _codes(outcome) == ["corporate_action_unresolved"]
+ assert outcome.data_provenance.corporate_actions[0]["detected"] is False
+
+
+def test_injected_t3_seam_unions_with_detector_output_not_replaced() -> None:
+ # DIRTY.US is unresolved by the detector; CLEAN.US is healthy but injected
+ # through the T3 seam. BOTH must reject — the merge is a union.
+ frames = {
+ "DIRTY.US": _frame([(_PREV, 100.0, 1_000_000.0), (_EX, 40.0, 2_500_000.0)]),
+ "CLEAN.US": _frame([(_PREV, 50.0, 1000.0), (_EX, 50.5, 1000.0)]),
+ }
+ market_data = _fetch("us", frames, _EX, _EX)
+ outcome = engine.match_orders(
+ _request("us", 100000.0, [],
+ [{"symbol": "DIRTY.US", "side": "buy", "qty": 10},
+ {"symbol": "CLEAN.US", "side": "buy", "qty": 10}], _EX),
+ market_data=market_data,
+ corporate_action_unresolved_by_day={_EX: ["CLEAN.US"]},
+ )
+ assert _codes(outcome) == ["corporate_action_unresolved", "corporate_action_unresolved"]
+ assert {r.symbol for r in outcome.rejected_orders} == {"DIRTY.US", "CLEAN.US"}
+ # Only the detector's symbol lands in provenance; the seam stays injection-only.
+ assert [e["symbol"] for e in outcome.data_provenance.corporate_actions] == ["DIRTY.US"]
+
+
+# ── Note 2: lookback history never fires ──
+
+
+def test_note2_historical_split_in_lookback_never_fires() -> None:
+ # Simulate the day AFTER the ex-date: the 4:1 cliff (2026-02-02) is inside
+ # the served K=120 lookback but its AFTER-date is not a simulated day, so
+ # there is NO event, NO rejection, and a normal order fills.
+ market_data = _fetch("us", {_SYM: _fixture_frame()}, _NEXT, _NEXT)
+ assert _EX in market_data.data[_SYM].bar_dates # the split bar IS served (lookback)
+ outcome = engine.match_orders(
+ _request("us", 100000.0, [_position_dict(_SYM, 100, 119.0)],
+ [{"symbol": _SYM, "side": "buy", "qty": 10}], _NEXT),
+ market_data=market_data,
+ )
+ assert outcome.error is None
+ assert _codes(outcome) == []
+ assert outcome.data_provenance.corporate_actions == ()
+ assert not any("corporate action" in w for w in outcome.warnings)
+ assert outcome.fills[0].price == 119.5
+ position = outcome.end_state.positions[0]
+ assert position.qty == 110
+ assert position.avg_cost == 119.0455 # (100×119 + 10×119.5)/110 → 4dp HALF_UP
+ # The untouched 100-share position was NOT split-adjusted (note 2).
+ assert outcome.nav_series[0].position_value == pytest.approx(110 * 119.5)
+
+
+def test_no_prior_bar_means_insufficient_evidence_no_event() -> None:
+ frames = {"FIRST.US": _frame([(_EX, 100.0, 1000.0)])} # first bar of the window
+ market_data = _fetch("us", frames, _EX, _EX)
+ outcome = engine.match_orders(
+ _request("us", 100000.0, [], [{"symbol": "FIRST.US", "side": "buy", "qty": 10}], _EX),
+ market_data=market_data,
+ )
+ assert _codes(outcome) == []
+ assert len(outcome.fills) == 1
+ assert outcome.data_provenance.corporate_actions == ()
+
+
+def test_non_positive_prior_close_yields_no_event_not_a_crash() -> None:
+ # The prior bar fails the R-V3 sanity gate (negative close): the boundary
+ # is skipped as insufficient evidence — no event, no crash; the target bar
+ # itself is tradable so the order fills.
+ frames = {"NEG.US": _frame([(_PREV, -5.0, 1000.0), (_EX, 100.0, 1000.0)])}
+ market_data = _fetch("us", frames, _EX, _EX)
+ outcome = engine.match_orders(
+ _request("us", 100000.0, [], [{"symbol": "NEG.US", "side": "buy", "qty": 10}], _EX),
+ market_data=market_data,
+ )
+ assert _codes(outcome) == []
+ assert len(outcome.fills) == 1
+ assert outcome.data_provenance.corporate_actions == ()
+ assert any("price sanity" in w for w in outcome.warnings) # data-layer warning kept
+
+
+# ── cn_a exemption (call-site) ──
+
+
+def test_raw_cn_a_is_not_exempt_from_detection() -> None:
+ # Raw A-share execution must reject the same unresolved discontinuity
+ # as HK/US. It cannot use the former adjusted-series exemption.
+ frames = {"600000.SH": _frame([(_PREV, 100.0, 1_000_000.0), (_EX, 40.0, 2_500_000.0)])}
+ market_data = fetch_market_data("cn_a", ["600000.SH"], _EX, _EX,
+ loader=FakeLoader(frames, name="tencent"),
+ ch_client=FakeChClient())
+ outcome = engine.match_orders(
+ _request("cn_a", 100000.0, [], [{"symbol": "600000.SH", "side": "buy", "qty": 100}], _EX),
+ market_data=market_data,
+ calendar_client=FakeCalendarClient(frozenset({_EX})),
+ )
+ assert outcome.error is None
+ assert _codes(outcome) == ["corporate_action_unresolved"]
+ assert outcome.fills == ()
+
+
+# ── Skipped semantics with the CA plan active (extends the T3 matrix) ──
+
+
+def test_market_closed_inferred_skips_with_warning_while_the_plan_is_active() -> None:
+ # hk mid-range all-market zero bar (2026-03-03): skipped
+ # market_closed_inferred + mandatory warning, no nav row, its defensive
+ # order rejects suspended — and the CA scan (matching days only) adds
+ # nothing: the neutral 100.0 → 100.5 boundary is not a candidate.
+ frames = {"00700.HK": _frame([("2026-03-02", 100.0, 1_000_000.0),
+ ("2026-03-04", 100.5, 1_000_000.0)])}
+ market_data = _fetch("hk", frames, "2026-03-02", "2026-03-04")
+ outcome = engine.run_day_loop(
+ market="hk", account_state=AccountState(cash=50000.0),
+ from_date="2026-03-02", to_date="2026-03-04",
+ orders_by_day={"2026-03-03": (Order("00700.HK", "buy", 100),)},
+ market_data=market_data,
+ )
+ assert outcome.error is None
+ assert [(s.date, s.reason) for s in outcome.skipped_days] == [
+ ("2026-03-03", "market_closed_inferred")]
+ assert any("2026-03-03" in w and "inferred closed" in w for w in outcome.warnings)
+ assert _codes(outcome) == ["suspended"] # never non_trading_day for hk/us
+ assert [nav.date for nav in outcome.nav_series] == ["2026-03-02", "2026-03-04"]
+ assert outcome.data_provenance.corporate_actions == ()
+
+
+def test_suspended_symbol_carries_forward_beside_a_clean_split() -> None:
+ # Per-symbol independence on the ex-date: SYNTH-4TO1 splits cleanly while
+ # HALT.US has no bar (suspended) — its order rejects, its position values
+ # at the last close (50.0), and the day still commits ONE nav row.
+ frames = {
+ _SYM: _fixture_frame(),
+ "HALT.US": _frame([(_PREV, 50.0, 1000.0)]),
+ }
+ market_data = _fetch("us", frames, _PREV, _EX, symbols=[_SYM, "HALT.US"])
+ outcome = engine.run_day_loop(
+ market="us",
+ account_state=AccountState(cash=100000.0, positions=(
+ _position(_SYM, 100, 400.0), _position("HALT.US", 100, 48.0))),
+ from_date=_PREV, to_date=_EX,
+ orders_by_day={_EX: (Order("HALT.US", "buy", 10),)},
+ market_data=market_data,
+ )
+ assert outcome.error is not None
+ assert outcome.error.code == "PAPER_DATA_NOT_READY"
+ assert "cannot establish a split" in outcome.error.message
+ assert outcome.fills == ()
+ assert outcome.nav_series == ()
+ assert outcome.end_state.positions[0].qty == 100
+
+
+# ── helpers ──
+
+
+def _position(symbol: str, qty: float, avg_cost: float) -> Position:
+ return Position(symbol=symbol, qty=qty, avg_cost=avg_cost)
+
+
+def _position_dict(symbol: str, qty: float, avg_cost: float) -> dict:
+ return {"symbol": symbol, "qty": qty, "avg_cost": avg_cost}
diff --git a/agent/tests/test_paper_trade_determinism.py b/agent/tests/test_paper_trade_determinism.py
new file mode 100644
index 000000000..f5b8910ca
--- /dev/null
+++ b/agent/tests/test_paper_trade_determinism.py
@@ -0,0 +1,365 @@
+"""T1 gate — pt-v1.1 wire determinism goldens (Step 5 / T5).
+
+Three markets, one golden group each: the exact wire bytes that
+``wire.dumps_payload(wire.build_success_payload(...))`` produces for a
+fixture-backed single-day orders run, frozen under
+``agent/tests/fixtures/paper_trade/golden/``. The determinism claim (R1-1):
+the same input run twice yields byte-identical JSON, an identical sha256, and
+bytes equal to the frozen golden. Fee/cash/nav values inside each scenario
+are the hand-computed cents already pinned by the T3 goldens
+(test_paper_trade_golden_*.py), so a golden is self-verifying, not circular.
+
+The error path is deterministic too: an AM-5 in-band PAPER_DATA_NOT_READY
+envelope built twice from the same not-ready input is byte-identical.
+
+Offline by construction: fake loaders / fake CH client / fake calendar
+client, no network (``--disable-socket`` hard gate), no clock (every date is
+an injected literal).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade import engine, wire
+from src.tools.paper_trade.data import fetch_market_data
+from src.tools.paper_trade.schema import (
+ DateRange,
+ ErrorEnvelope,
+ load_contract_schema,
+ parse_request,
+ validate_payload,
+)
+from src.tools.paper_trade.state_hash import effective_fee_model, state_hash
+
+_GOLDEN_DIR = Path(__file__).parent / "fixtures" / "paper_trade" / "golden"
+_MARKET_DIR = Path(__file__).parent / "fixtures" / "paper_trade" / "market"
+_SHA_RE = re.compile(r"^[0-9a-f]{64}$")
+
+_CN_A_DAY = "2026-10-20" # Tuesday
+_CN_A_PREV = "2026-10-19"
+_HK_US_DAY = "2026-10-16" # Friday; last bar of both recorded fixtures
+
+# §4 terminal default fee models (state_hash._DEFAULT_FEE_MODELS, frozen).
+_CN_A_FEES = {
+ "commission_rate": 0.00025,
+ "commission_min": 5.0,
+ "stamp_tax_sell": 0.0005,
+ "transfer_fee": 0.00001,
+}
+_HK_FEES = {
+ "commission_rate": 0.0003,
+ "commission_min": 3.0,
+ "stamp_tax_rate": 0.001,
+ "regulatory_levy_rate": 0.00003,
+}
+_US_FEES = {
+ "commission_per_share": 0.0049,
+ "commission_min": 0.99,
+ "sec_fee_rate": 0.0,
+}
+
+
+class FakeChClient:
+ def __init__(self, frames: dict[str, pd.DataFrame]) -> None:
+ self._frames = frames
+
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ return self._frames.get(ts_code, pd.DataFrame())
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str) -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+class FakeCalendarClient:
+ """cn_a CH trade_calendar truth: exactly the open days given."""
+
+ def __init__(self, open_days: tuple[str, ...]) -> None:
+ self._open = set(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 _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 _recorded_frame(filename: str) -> pd.DataFrame:
+ document = json.loads((_MARKET_DIR / filename).read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]]
+
+
+def _payload(account_id: str, market: str, cash: float, orders: list[dict], day: str,
+ fees: dict[str, float]) -> dict:
+ return {
+ "account_id": account_id,
+ "market": market,
+ "account_state": {"cash": cash, "positions": []},
+ "orders": orders,
+ "from_date": day,
+ "to_date": day,
+ "fee_model": dict(fees),
+ }
+
+
+def _run_to_wire_text(payload: dict, market_data, calendar_client=None) -> str:
+ request = parse_request(payload)
+ outcome = engine.match_orders(
+ request, market_data=market_data, calendar_client=calendar_client
+ )
+ assert outcome.error is None, outcome.error
+ result = wire.assemble_result(
+ request, outcome, raw_account_state=payload["account_state"]
+ )
+ return wire.dumps_payload(wire.build_success_payload(result))
+
+
+# ── Per-market scenarios (fresh fakes on every call — full-pipeline reruns) ──
+
+
+def _scenario_cn_a() -> tuple[str, dict]:
+ # Merged AM-9 frame: CH leg serves T-1 (10-19 close 1418.0), tencent leg
+ # serves the target day (10-20 close 1421.0). Buy 100 → fee 36.95,
+ # cash 57863.05, nav 199963.05 (hand-computed in test_paper_trade_golden_cn_a).
+ payload = _payload("pa_golden_cn_a", "cn_a", 200000.0,
+ [{"symbol": "600519.SH", "side": "buy", "qty": 100}],
+ _CN_A_DAY, _CN_A_FEES)
+ market_data = fetch_market_data(
+ "cn_a", ["600519.SH"], _CN_A_DAY, _CN_A_DAY,
+ loader=FakeLoader({"600519.SH": _frame([(_CN_A_DAY, 1421.0)])}, "tencent"),
+ ch_client=FakeChClient({"600519.SH": _frame([(_CN_A_PREV, 1418.0)])}),
+ )
+ return _run_to_wire_text(payload, market_data,
+ FakeCalendarClient((_CN_A_DAY,))), payload
+
+
+def _scenario_hk() -> tuple[str, dict]:
+ # Recorded tencent fixture (raw caliber), target 2026-10-16 close 417.8.
+ # Buy 100 → fee 55.79, cash 58164.21, nav 99944.21 (golden_hk hand math).
+ payload = _payload("pa_golden_hk", "hk", 100000.0,
+ [{"symbol": "00700.HK", "side": "buy", "qty": 100}],
+ _HK_US_DAY, _HK_FEES)
+ market_data = fetch_market_data(
+ "hk", ["00700.HK"], _HK_US_DAY, _HK_US_DAY,
+ loader=FakeLoader({"00700.HK": _recorded_frame("hk_00700_tencent.json")}, "tencent"),
+ )
+ return _run_to_wire_text(payload, market_data), payload
+
+
+def _scenario_us() -> tuple[str, dict]:
+ # Recorded sina fixture (raw caliber), target 2026-10-16 close 343.46.
+ # Buy 10 → fee 0.99 (minimum dominates), cash 46564.41, nav 49999.01.
+ payload = _payload("pa_golden_us", "us", 50000.0,
+ [{"symbol": "AAPL.US", "side": "buy", "qty": 10}],
+ _HK_US_DAY, _US_FEES)
+ market_data = fetch_market_data(
+ "us", ["AAPL.US"], _HK_US_DAY, _HK_US_DAY,
+ loader=FakeLoader({"AAPL.US": _recorded_frame("us_AAPL_sina.json")}, "sina"),
+ )
+ return _run_to_wire_text(payload, market_data), payload
+
+
+_SCENARIOS = {"cn_a": _scenario_cn_a, "hk": _scenario_hk, "us": _scenario_us}
+_GOLDEN_FILES = {
+ "cn_a": "cn_a_orders_single_day.json",
+ "hk": "hk_orders_single_day.json",
+ "us": "us_orders_single_day.json",
+}
+_MARKETS = sorted(_SCENARIOS)
+
+
+def _manifest() -> dict:
+ return json.loads((_GOLDEN_DIR / "MANIFEST.json").read_text(encoding="utf-8"))
+
+
+def _sha256(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+# ── T1: double-run byte/sha parity ──
+
+
[email protected]("market", _MARKETS)
+def test_double_run_produces_identical_bytes_and_sha(market: str) -> None:
+ first_text, _ = _SCENARIOS[market]()
+ second_text, _ = _SCENARIOS[market]()
+ assert first_text == second_text
+ assert _sha256(first_text.encode("utf-8")) == _sha256(second_text.encode("utf-8"))
+
+
+# ── T1: frozen golden bytes + manifest sha ──
+
+
[email protected]("market", _MARKETS)
+def test_wire_bytes_match_the_frozen_golden(market: str) -> None:
+ text, _ = _SCENARIOS[market]()
+ golden_bytes = (_GOLDEN_DIR / _GOLDEN_FILES[market]).read_bytes()
+ assert text.encode("utf-8") == golden_bytes
+ entry = next(g for g in _manifest()["goldens"] if g["file"] == _GOLDEN_FILES[market])
+ assert _sha256(golden_bytes) == entry["sha256"]
+ assert len(golden_bytes) == entry["bytes"]
+
+
+def test_golden_manifest_covers_exactly_the_three_markets() -> None:
+ files = {g["file"] for g in _manifest()["goldens"]}
+ assert files == set(_GOLDEN_FILES.values())
+ assert {g["market"] for g in _manifest()["goldens"]} == {"cn_a", "hk", "us"}
+ for golden in _manifest()["goldens"]:
+ assert _SHA_RE.match(golden["sha256"])
+
+
+# ── Golden content is self-verifying (hand-computed cents, frozen echoes) ──
+
+
[email protected]("market", _MARKETS)
+def test_golden_carries_the_frozen_contract_echoes(market: str) -> None:
+ text, payload = _SCENARIOS[market]()
+ doc = json.loads(text)
+ assert doc["schema_version"] == "pt-v1.1"
+ assert doc["tool"] == "paper_trade_step"
+ assert doc["account_id"] == payload["account_id"]
+ assert doc["market"] == market
+ assert doc["range"] == {"from": payload["from_date"], "to": payload["to_date"]}
+ assert _SHA_RE.match(doc["received_state_hash"])
+ assert doc["effective_fee_model"] == effective_fee_model(market, payload["fee_model"])
+ assert all(fill["reason"] == "" for fill in doc["fills"]) # VD-15 orders mode
+ # AM-4-1: the hash equals sha256(JCS(coverage object)) computed by hand.
+ assert doc["received_state_hash"] == state_hash({
+ "account_id": payload["account_id"],
+ "market": market,
+ "account_state": payload["account_state"],
+ "fee_model": effective_fee_model(market, payload["fee_model"]),
+ "from_date": payload["from_date"],
+ "to_date": payload["to_date"],
+ })
+
+
+def test_cn_a_golden_embeds_hand_computed_cents_and_merged_provenance() -> None:
+ doc = json.loads(_SCENARIOS["cn_a"]()[0])
+ fill = doc["fills"][0]
+ assert (fill["trade_date"], fill["symbol"], fill["side"]) == (_CN_A_DAY, "600519.SH", "buy")
+ assert (fill["qty"], fill["price"], fill["fee"]) == (100.0, 1421.0, 36.95)
+ assert doc["end_state"] == {
+ "cash": 57863.05,
+ "positions": [{"symbol": "600519.SH", "qty": 100.0, "avg_cost": 1421.0}],
+ }
+ assert doc["nav_series"] == [
+ {"date": _CN_A_DAY, "nav": 199963.05, "cash": 57863.05, "position_value": 142100.0}
+ ]
+ assert doc["rejected_orders"] == [] and doc["skipped_days"] == [] and doc["warnings"] == []
+ # AM-9 merged-frame provenance + VD-11 heuristic band token.
+ assert doc["data_provenance"] == {
+ "source": "clickhouse+tencent(merged)",
+ "ch_as_of": _CN_A_PREV,
+ "network_as_of": _CN_A_DAY,
+ "bars_as_of": _CN_A_DAY,
+ "limit_provenance": [f"600519.SH@{_CN_A_DAY}:limits:heuristic"],
+ }
+
+
+def test_hk_golden_embeds_hand_computed_cents_and_lot_warning() -> None:
+ doc = json.loads(_SCENARIOS["hk"]()[0])
+ fill = doc["fills"][0]
+ assert (fill["qty"], fill["price"], fill["fee"]) == (100.0, 417.8, 55.79)
+ assert doc["end_state"]["cash"] == 58164.21
+ assert doc["nav_series"][0] == {
+ "date": _HK_US_DAY, "nav": 99944.21, "cash": 58164.21, "position_value": 41780.0
+ }
+ # The lot-assumption diagnostic keys on the board-lot mechanism's
+ # normalized symbol spelling (0700.HK), as pinned by the T3 hk golden.
+ assert doc["warnings"] == [
+ "lot assumption: 0700.HK sized on the default 100-share board lot "
+ "(no lot table entry)"
+ ]
+ prov = doc["data_provenance"]
+ assert prov["source"] == "tencent"
+ assert prov["bars_as_of"] == _HK_US_DAY and prov["network_as_of"] == _HK_US_DAY
+ assert "ch_as_of" not in prov and "limit_provenance" not in prov
+
+
+def test_us_golden_embeds_hand_computed_cents() -> None:
+ doc = json.loads(_SCENARIOS["us"]()[0])
+ fill = doc["fills"][0]
+ assert (fill["qty"], fill["price"], fill["fee"]) == (10.0, 343.46, 0.99)
+ assert doc["end_state"]["cash"] == 46564.41
+ assert doc["nav_series"][0] == {
+ "date": _HK_US_DAY, "nav": 49999.01, "cash": 46564.41, "position_value": 3434.6
+ }
+ assert doc["warnings"] == []
+ prov = doc["data_provenance"]
+ assert prov["source"] == "sina" and prov["bars_as_of"] == _HK_US_DAY
+ assert "ch_as_of" not in prov and "limit_provenance" not in prov
+
+
+# ── AM-5 error path determinism (in-band envelope, never transport) ──
+
+
+def _not_ready_envelope_text() -> str:
+ # cn_a target day with no bar on either leg → PAPER_DATA_NOT_READY.
+ payload = _payload("pa_golden_cn_a", "cn_a", 200000.0,
+ [{"symbol": "600519.SH", "side": "buy", "qty": 100}],
+ _CN_A_DAY, _CN_A_FEES)
+ request = parse_request(payload)
+ market_data = fetch_market_data(
+ "cn_a", ["600519.SH"], _CN_A_DAY, _CN_A_DAY,
+ loader=FakeLoader({"600519.SH": _frame([(_CN_A_PREV, 1418.0)])}, "tencent"),
+ ch_client=FakeChClient({}),
+ )
+ outcome = engine.match_orders(
+ request, market_data=market_data, calendar_client=FakeCalendarClient((_CN_A_DAY,))
+ )
+ assert outcome.error is not None
+ assert outcome.error.code == "PAPER_DATA_NOT_READY"
+ envelope = ErrorEnvelope(
+ code=outcome.error.code,
+ account_id=request.account_id,
+ market=request.market,
+ range=DateRange(from_=request.from_date, to=request.to_date),
+ message=outcome.error.message,
+ received_state_hash=wire.received_state_hash_from_payload(payload),
+ )
+ return wire.dumps_payload(wire.build_error_payload(envelope))
+
+
+def test_error_envelope_bytes_are_deterministic_and_schema_valid() -> None:
+ first = _not_ready_envelope_text()
+ second = _not_ready_envelope_text()
+ assert first == second
+ assert _sha256(first.encode("utf-8")) == _sha256(second.encode("utf-8"))
+ doc = json.loads(first)
+ assert doc["status"] == "error"
+ assert doc["code"] == "PAPER_DATA_NOT_READY"
+ assert doc["account_id"] == "pa_golden_cn_a" # verbatim even on error (AM-4-4)
+ assert _SHA_RE.match(doc["received_state_hash"]) # state was parseable
+ assert "target bar 2026-10-20 not available" in doc["message"]
+ assert validate_payload(doc, load_contract_schema("error_envelope")) == []
diff --git a/agent/tests/test_paper_trade_fixtures.py b/agent/tests/test_paper_trade_fixtures.py
new file mode 100644
index 000000000..eaea68f04
--- /dev/null
+++ b/agent/tests/test_paper_trade_fixtures.py
@@ -0,0 +1,296 @@
+"""VD-14 offline fixture-loadability tests (Step 1 / T1.5).
+
+Proves the paper-trade market fixtures load fully OFFLINE, self-describe
+their provenance (source / caliber / window), and that the tamper-evident
+manifest matches the on-disk bytes — the same sha256 idea the repo already
+uses for run cards (test_run_card.py:330-353).
+
+This file must pass under ``pytest --disable-socket``: it starts no
+network, never imports ``record_market_fixtures.py`` (a MANUAL recording
+tool that lives beside the fixtures), and validates only committed bytes.
+
+Scope honesty: the VD-14 ``cn_a`` leg (ClickHouse export) is BLOCKED on the
+open ClickHouse HIL and is intentionally absent — these tests never claim
+three-market fixture coverage, and no network source is substituted for it.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from datetime import date
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+_FIXTURE_DIR = Path(__file__).parent / "fixtures" / "paper_trade" / "market"
+_MANIFEST_NAME = "MANIFEST.json"
+_FIXTURE_SCHEMA = "paper_trade.market_fixture/v1"
+
+#: The two legs VD-14 pins to a network recording source, with the identity
+#: each fixture file must carry.
+RECORDED_FIXTURES: dict[str, dict[str, str]] = {
+ "hk_00700_tencent.json": {
+ "market": "hk_equity",
+ "symbol": "00700.HK",
+ "source": "tencent",
+ "request_url_prefix": "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get?",
+ },
+ "us_AAPL_sina.json": {
+ "market": "us_equity",
+ "symbol": "AAPL.US",
+ "source": "sina",
+ "request_url_prefix": "https://stock.finance.sina.com.cn/usstock/api/",
+ },
+}
+SYNTHETIC_FIXTURES: dict[str, dict[str, str]] = {
+ "synthetic_split_4to1.json": {"market": "us_equity", "symbol": "SYNTH-4TO1"},
+ "synthetic_holiday_gap.json": {"market": "us_equity", "symbol": "SYNTH-GAP"},
+}
+ALL_FIXTURES = set(RECORDED_FIXTURES) | set(SYNTHETIC_FIXTURES)
+
+_CORE_KEYS = {
+ "schema",
+ "market",
+ "symbol",
+ "source",
+ "price_caliber",
+ "window",
+ "bars",
+ "caliber_note",
+}
+_RECORDED_EXTRA_KEYS = {
+ "volume_unit",
+ "request_url",
+ "request_headers",
+ "recorded_at_utc",
+ "drop_stats",
+}
+_SYNTHETIC_EXTRA_KEYS = {"volume_unit", "synthetic_construction"}
+_BAR_KEYS = {"date", "open", "high", "low", "close", "volume"}
+_WINDOW_START, _WINDOW_END = "2025-10-01", "2026-10-16"
+
+#: VD-6 frozen split-detector thresholds: {2, 3, 4, 5, 10, 3:2} and their
+#: reciprocals. Pinned here verbatim from the plan; the detector (Step 4)
+#: must read the same set.
+_FROZEN_SPLIT_RATIOS = [
+ 2.0,
+ 3.0,
+ 4.0,
+ 5.0,
+ 10.0,
+ 1.5,
+ 1 / 2,
+ 1 / 3,
+ 1 / 4,
+ 1 / 5,
+ 2 / 3,
+]
+
+_US_CALIBER_NOTE_SUBSTRING = (
+ "raw / unadjusted — no split scaling applied by the source; a "
+ "close-to-close read across the 2020-08-31 4:1 ex-date reads ~0.2585"
+)
+
+
+def _load(name: str) -> dict[str, Any]:
+ with (_FIXTURE_DIR / name).open(encoding="utf-8") as handle:
+ return json.load(handle)
+
+
+def _load_manifest() -> dict[str, Any]:
+ return _load(_MANIFEST_NAME)
+
+
+def _is_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def _valid_iso_date(value: str) -> bool:
+ if not isinstance(value, str) or len(value) != 10 or value[4] != "-" or value[7] != "-":
+ return False
+ try:
+ date.fromisoformat(value)
+ except ValueError:
+ return False
+ return True
+
+
[email protected]("name", sorted(ALL_FIXTURES))
+def test_fixture_file_exists(name: str) -> None:
+ assert (_FIXTURE_DIR / name).is_file(), f"missing committed fixture {name}"
+
+
[email protected]("name", sorted(ALL_FIXTURES))
+def test_fixture_parses_with_documented_keys(name: str) -> None:
+ doc = _load(name)
+ expected = _CORE_KEYS | (_RECORDED_EXTRA_KEYS if name in RECORDED_FIXTURES else _SYNTHETIC_EXTRA_KEYS)
+ missing = expected - doc.keys()
+ assert not missing, f"{name}: missing documented keys {sorted(missing)}"
+ assert doc["schema"] == _FIXTURE_SCHEMA
+ identity = RECORDED_FIXTURES.get(name) or SYNTHETIC_FIXTURES[name]
+ assert doc["market"] == identity["market"]
+ assert doc["symbol"] == identity["symbol"]
+ if name in RECORDED_FIXTURES:
+ assert doc["source"] == identity["source"]
+ assert doc["request_url"].startswith(identity["request_url_prefix"])
+ assert doc["recorded_at_utc"].endswith("Z")
+ assert doc["price_caliber"] == "raw"
+ assert doc["window"] == {"start": _WINDOW_START, "end": _WINDOW_END}
+ else:
+ assert doc["source"] == "synthetic"
+ assert isinstance(doc["synthetic_construction"], str) and doc["synthetic_construction"]
+
+
[email protected]("name", sorted(ALL_FIXTURES))
+def test_bars_sorted_unique_and_ohlc_sane(name: str) -> None:
+ doc = _load(name)
+ bars = doc["bars"]
+ assert bars, f"{name}: fixture must carry at least one bar"
+ window = doc["window"]
+ dates = [bar["date"] for bar in bars]
+ assert all(_valid_iso_date(d) for d in dates)
+ assert dates == sorted(dates), f"{name}: bars are not ascending by date"
+ assert len(set(dates)) == len(dates), f"{name}: duplicate bar dates"
+ assert window["start"] <= dates[0] and dates[-1] <= window["end"]
+ for bar in bars:
+ assert set(bar) == _BAR_KEYS, f"{name} {bar.get('date')}: unexpected bar keys"
+ op, hi, lo, cl = (bar["open"], bar["high"], bar["low"], bar["close"])
+ assert all(_is_number(v) for v in (op, hi, lo, cl, bar["volume"]))
+ assert all(math.isfinite(v) for v in (op, hi, lo, cl, bar["volume"]))
+ assert min(op, hi, lo, cl) > 0, f"{name} {bar['date']}: non-positive OHLC"
+ assert hi >= max(op, cl, lo), f"{name} {bar['date']}: high violates OHLC bracket"
+ assert lo <= min(op, cl, hi), f"{name} {bar['date']}: low violates OHLC bracket"
+ assert _is_number(bar["volume"]) and bar["volume"] >= 0
+
+
+def test_recorded_window_ends_on_last_completed_trade_date() -> None:
+ for name in RECORDED_FIXTURES:
+ bars = _load(name)["bars"]
+ assert bars[-1]["date"] == _WINDOW_END, f"{name}: does not end on {_WINDOW_END}"
+
+
+def test_recorded_drop_stats_are_clean() -> None:
+ for name in RECORDED_FIXTURES:
+ stats = _load(name)["drop_stats"]
+ assert stats["dropped_dirty_ohlc"] == 0, f"{name}: recorded series had dirty bars dropped"
+ assert stats["dropped_duplicate_dates"] == 0, f"{name}: recorded series had duplicate dates"
+ assert stats["dropped_unparseable"] == 0, f"{name}: wire rows failed to parse"
+ assert stats["wire_rows"] >= len(_load(name)["bars"])
+
+
+def test_sina_window_clip_is_the_only_drop_on_the_us_leg() -> None:
+ stats = _load("us_AAPL_sina.json")["drop_stats"]
+ # sina serves the full history with no window parameter; the clip is the
+ # one expected reduction, matching sina_loader.py:115-118.
+ assert stats["dropped_out_of_window"] == stats["wire_rows"] - len(_load("us_AAPL_sina.json")["bars"])
+
+
+def test_us_fixture_documents_the_raw_unadjusted_caliber() -> None:
+ doc = _load("us_AAPL_sina.json")
+ assert doc["price_caliber"] == "raw"
+ assert _US_CALIBER_NOTE_SUBSTRING in doc["caliber_note"]
+ manifest_entry = next(f for f in _load_manifest()["fixtures"] if f["file"] == "us_AAPL_sina.json")
+ assert _US_CALIBER_NOTE_SUBSTRING in manifest_entry["caliber_note"]
+ assert doc["volume_unit"] is None, "sina declares no volume unit (sina_loader has no volume_units)"
+
+
+def test_hk_fixture_declares_share_volume_units_and_raw_caliber() -> None:
+ doc = _load("hk_00700_tencent.json")
+ assert doc["price_caliber"] == "raw"
+ assert doc["volume_unit"] == "shares"
+ assert "day" in doc["caliber_note"] and "qfq" in doc["caliber_note"]
+
+
+def test_manifest_covers_exactly_the_fixture_files() -> None:
+ manifest = _load_manifest()
+ files = {entry["file"] for entry in manifest["fixtures"]}
+ on_disk = {p.name for p in _FIXTURE_DIR.glob("*.json") if p.name != _MANIFEST_NAME}
+ assert files == on_disk == ALL_FIXTURES
+
+
+def test_manifest_sha256_bytes_and_counts_match_reality() -> None:
+ manifest = _load_manifest()
+ assert manifest["schema"] == "paper_trade.market_manifest/v1"
+ for entry in manifest["fixtures"]:
+ path = _FIXTURE_DIR / entry["file"]
+ raw = path.read_bytes()
+ digest = hashlib.sha256(raw).hexdigest()
+ assert entry["sha256"] == digest, f"{entry['file']}: manifest sha256 drifted from bytes"
+ assert entry["bytes"] == len(raw)
+ doc = json.loads(raw)
+ assert entry["rows"] == len(doc["bars"])
+ assert entry["first_date"] == doc["bars"][0]["date"]
+ assert entry["last_date"] == doc["bars"][-1]["date"]
+ assert entry["market"] == doc["market"]
+ assert entry["symbol"] == doc["symbol"]
+
+
+def test_manifest_recorded_entries_carry_full_provenance() -> None:
+ for name, identity in RECORDED_FIXTURES.items():
+ entry = next(f for f in _load_manifest()["fixtures"] if f["file"] == name)
+ assert entry["request_url"] == _load(name)["request_url"]
+ assert entry["window"] == {"start": _WINDOW_START, "end": _WINDOW_END}
+ assert entry["recorded_at_utc"] == _load(name)["recorded_at_utc"]
+ assert entry["source"] == identity["source"]
+ assert entry["price_caliber"] == "raw"
+
+
+def test_split_fixture_contains_one_frozen_ratio_break() -> None:
+ bars = _load("synthetic_split_4to1.json")["bars"]
+ hits = []
+ for i in range(1, len(bars)):
+ ratio = bars[i]["close"] / bars[i - 1]["close"]
+ for threshold in _FROZEN_SPLIT_RATIOS:
+ if math.isclose(ratio, threshold, rel_tol=1e-12):
+ hits.append((i, ratio))
+ break
+ assert len(hits) == 1, f"synthetic split fixture must contain exactly one frozen-ratio break, got {hits}"
+ index, ratio = hits[0]
+ assert ratio == 0.25, "the single break must be the clean 4:1 split (close ratio exactly 0.25)"
+ vol_ratio = bars[index]["volume"] / bars[index - 1]["volume"]
+ assert vol_ratio >= 2.0, "split break needs a same-direction volume multiple for VD-6 confirmation"
+ event = _load("synthetic_split_4to1.json")["split_event"]
+ assert event["ex_date"] == bars[index]["date"]
+ assert event["bar_index"] == index
+ assert event["close_before"] == bars[index - 1]["close"]
+ assert event["close_after"] == bars[index]["close"]
+
+
+def test_split_fixture_keeps_the_event_inside_a_K120_lookback_edge() -> None:
+ # VD-6/B3: the fetch window is [from_date - K trading days, to_date];
+ # 120 bars after the ex-date put the event exactly at the K=120 edge.
+ doc = _load("synthetic_split_4to1.json")
+ assert doc["split_event"]["bars_after_ex"] == 120
+ assert len(doc["bars"]) == doc["split_event"]["bar_index"] + 121
+
+
+def test_holiday_gap_fixture_gaps_match_bars() -> None:
+ doc = _load("synthetic_holiday_gap.json")
+ bars = doc["bars"]
+ dates = [bar["date"] for bar in bars]
+ samples = doc["gap_samples"]
+ assert len(samples) >= 2, "fixture must carry at least two gap samples"
+ assert any(len(s["missing_weekdays"]) >= 3 for s in samples), "one gap must be multi-day"
+ for sample in samples:
+ after, resume = sample["after_date"], sample["resume_date"]
+ assert after in dates and resume in dates
+ between = [d for d in dates if after < d < resume]
+ assert not between, f"{sample['label']}: bars leaked into the authored gap {after}..{resume}"
+ expected = [d for d in _weekdays_between(after, resume) if d not in dates]
+ assert sorted(expected) == sorted(sample["missing_weekdays"])
+
+
+def _weekdays_between(start: str, end: str) -> list[str]:
+ """Weekday dates strictly between two ISO dates (gap audit helper)."""
+ day = date.fromisoformat(start)
+ stop = date.fromisoformat(end)
+ out: list[str] = []
+ day = date.fromordinal(day.toordinal() + 1)
+ while day < stop:
+ if day.weekday() < 5:
+ out.append(day.isoformat())
+ day = date.fromordinal(day.toordinal() + 1)
+ return out
diff --git a/agent/tests/test_paper_trade_golden_cn_a.py b/agent/tests/test_paper_trade_golden_cn_a.py
new file mode 100644
index 000000000..0ce2711e5
--- /dev/null
+++ b/agent/tests/test_paper_trade_golden_cn_a.py
@@ -0,0 +1,260 @@
+"""T2-gate cn_a golden sample: state+orders → fills/nav/end_state (Step 3 / T3).
+
+Fees are hand-computed to the cent (VD-9 Decimal + ROUND_HALF_UP); the
+arithmetic is written out in the comments of each test. Offline by
+construction: fake CH bar client + fake network loader + fake calendar
+client, never the network (``--disable-socket`` is a hard gate).
+"""
+
+from __future__ import annotations
+
+from decimal import Decimal
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade import engine
+from src.tools.paper_trade.data import fetch_market_data
+from src.tools.paper_trade.rules import MarketRules
+from src.tools.paper_trade.schema import parse_request
+
+# §4 cn_a default fee matrix (state_hash._DEFAULT_FEE_MODELS terminal values).
+_FEE_MODEL = {
+ "commission_rate": 0.00025, # 万2.5 bilateral
+ "commission_min": 5.0, # ¥5 minimum
+ "stamp_tax_sell": 0.0005, # 万5 sell-only
+ "transfer_fee": 0.00001, # 万0.1 bilateral
+}
+
+_DAY = "2026-10-20" # Tuesday
+_PREV = "2026-10-19"
+
+
+class FakeChClient:
+ def __init__(self, frames: dict[str, pd.DataFrame]) -> None:
+ self._frames = frames
+
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ return self._frames.get(ts_code, pd.DataFrame())
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "tencent") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+class FakeCalendarClient:
+ """CH trade_calendar rows; the golden week is fully open on the target."""
+
+ def __init__(self, open_days: tuple[str, ...] = (_DAY,)) -> None:
+ self._open = set(open_days)
+
+ def get_trade_calendar(self, start_date: str, end_date: str) -> pd.DataFrame:
+ rows = []
+ for day in pd.date_range(start_date, end_date):
+ iso = day.strftime("%Y-%m-%d")
+ rows.append({"exchange": "SSE", "cal_date": iso, "is_open": int(iso in self._open),
+ "pretrade_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 _fetch(frames: dict[str, pd.DataFrame], symbols: list[str], day: str = _DAY):
+ return fetch_market_data(
+ "cn_a", symbols, day, day, loader=FakeLoader(frames), ch_client=FakeChClient({})
+ )
+
+
+def _request(cash: float, positions: list[dict], orders: list[dict], day: str = _DAY):
+ return parse_request({
+ "account_id": "pa_golden_cn_a", "market": "cn_a",
+ "account_state": {"cash": cash, "positions": positions},
+ "orders": orders, "from_date": day, "to_date": day,
+ "fee_model": dict(_FEE_MODEL),
+ })
+
+
+def _match(request, market_data, **kwargs) -> engine.MatchOutcome:
+ return engine.match_orders(
+ request, market_data=market_data,
+ calendar_client=kwargs.pop("calendar_client", None) or FakeCalendarClient(),
+ **kwargs,
+ )
+
+
+# 600519.SH: prev close 1418.0 (heuristic band 1276.20..1559.80), target 1421.0.
+_FRAMES = {"600519.SH": _frame([(_PREV, 1418.0), (_DAY, 1421.0)])}
+
+
+def test_cn_a_buy_golden_fee_hand_computed_to_the_cent() -> None:
+ # Hand computation (VD-9, Decimal ROUND_HALF_UP):
+ # notional = 100 × 1421.00 = 142100.00
+ # commission = max(142100.00 × 0.00025, 5.00) = max(35.525, 5) = 35.525
+ # transfer = 142100.00 × 0.00001 = 1.421
+ # stamp(buy) = 0
+ # fee = 35.525 + 1.421 = 36.946 → quantize 2dp HALF_UP = 36.95
+ # cash_end = 200000.00 − 142100.00 − 36.95 = 57863.05
+ # nav = 57863.05 + 100 × 1421.00 = 199963.05
+ outcome = _match(_request(200000.0, [], [{"symbol": "600519.SH", "side": "buy", "qty": 100}]),
+ _fetch(_FRAMES, ["600519.SH"]))
+
+ assert outcome.error is None
+ assert len(outcome.fills) == 1
+ fill = outcome.fills[0]
+ assert (fill.trade_date, fill.symbol, fill.side, fill.qty) == (_DAY, "600519.SH", "buy", 100)
+ assert fill.price == 1421.0 # fill price = close (§4)
+ assert fill.fee == 36.95
+ assert fill.reason == "" # VD-15: orders mode
+ assert outcome.rejected_orders == ()
+ assert outcome.end_state.cash == 57863.05
+ assert outcome.end_state.positions[0].symbol == "600519.SH"
+ assert outcome.end_state.positions[0].qty == 100
+ assert outcome.end_state.positions[0].avg_cost == 1421.0
+ nav = outcome.nav_series[0]
+ assert (nav.date, nav.nav, nav.cash, nav.position_value) == (_DAY, 199963.05, 57863.05, 142100.0)
+ # VD-11: no limits client injected → heuristic band path, provenance recorded.
+ assert any("limits:heuristic" in token for token in outcome.limit_provenance)
+
+
+def test_cn_a_sell_golden_fee_hand_computed_to_the_cent() -> None:
+ # Hand computation:
+ # notional = 100 × 1425.50 = 142550.00
+ # commission = max(142550.00 × 0.00025, 5) = 35.6375
+ # transfer = 142550.00 × 0.00001 = 1.4255
+ # stamp(sell)= 142550.00 × 0.0005 = 71.275
+ # fee = 35.6375 + 1.4255 + 71.275 = 108.338 → 2dp HALF_UP = 108.34
+ # cash_end = 1000.00 + 142550.00 − 108.34 = 143441.66
+ frames = {"600519.SH": _frame([(_PREV, 1421.0), (_DAY, 1425.5)])}
+ outcome = _match(
+ _request(1000.0, [{"symbol": "600519.SH", "qty": 100, "avg_cost": 1418.0}],
+ [{"symbol": "600519.SH", "side": "sell", "qty": 100}]),
+ _fetch(frames, ["600519.SH"]),
+ )
+
+ assert outcome.error is None
+ assert outcome.fills[0].fee == 108.34
+ assert outcome.end_state.cash == 143441.66
+ assert outcome.end_state.positions == () # fully closed, zero-qty dropped
+ assert outcome.nav_series[0].nav == 143441.66
+ assert outcome.nav_series[0].position_value == 0.0
+
+
+def test_cn_a_commission_minimum_dominates_small_orders() -> None:
+ # Hand computation: notional = 100 × 10.00 = 1000.00
+ # commission = max(1000 × 0.00025 = 0.25, 5.00) = 5.00
+ # transfer = 1000 × 0.00001 = 0.01
+ # fee = 5.01
+ frames = {"600519.SH": _frame([(_PREV, 10.0), (_DAY, 10.0)])}
+ outcome = _match(_request(100000.0, [], [{"symbol": "600519.SH", "side": "buy", "qty": 100}]),
+ _fetch(frames, ["600519.SH"]))
+ assert outcome.fills[0].fee == 5.01
+ assert outcome.end_state.cash == 100000.0 - 1000.0 - 5.01
+
+
+def test_cn_a_avg_cost_is_the_fee_exclusive_weighted_average() -> None:
+ # Existing 100 @ 10.00 + buy 100 @ close 11.00:
+ # avg_cost = (100×10.00 + 100×11.00) / 200 = 10.50 (fee-exclusive, 4dp)
+ # fee: notional 1100 → comm max(0.275, 5) = 5, transfer 0.011 → 5.011 → 5.01
+ # cash = 5000 − 1100.00 − 5.01 = 3894.99; nav = 3894.99 + 200×11.00 = 6094.99
+ frames = {"600519.SH": _frame([(_PREV, 10.5), (_DAY, 11.0)])}
+ outcome = _match(
+ _request(5000.0, [{"symbol": "600519.SH", "qty": 100, "avg_cost": 10.0}],
+ [{"symbol": "600519.SH", "side": "buy", "qty": 100}]),
+ _fetch(frames, ["600519.SH"]),
+ )
+ position = outcome.end_state.positions[0]
+ assert (position.qty, position.avg_cost) == (200, 10.5)
+ assert outcome.fills[0].fee == 5.01
+ assert outcome.end_state.cash == 3894.99
+ assert outcome.nav_series[0].nav == 6094.99
+
+
+def test_decimal_fee_matches_the_reused_engine_primitive_values() -> None:
+ # E2/VD-2 numeric-agreement pin: the Decimal matrix equals the reused
+ # ChinaAEngine.calc_commission float primitive (pre-quantization), and the
+ # quantized terminal value is the hand-computed cent.
+ from backtest.engines.china_a import ChinaAEngine
+
+ primitive = ChinaAEngine({})
+ rules = MarketRules("cn_a", _FEE_MODEL)
+ buy_float = primitive.calc_commission(100, 1421.0, 1, True)
+ sell_float = primitive.calc_commission(100, 1425.5, -1, False)
+ assert buy_float == pytest.approx(36.946, abs=1e-9)
+ assert sell_float == pytest.approx(108.338, abs=1e-9)
+ assert abs(float(rules.fee("buy", 100, 1421.0)) - buy_float) <= 0.005
+ assert abs(float(rules.fee("sell", 100, 1425.5)) - sell_float) <= 0.005
+ assert rules.fee("buy", 100, 1421.0) == Decimal("36.95")
+ assert rules.fee("sell", 100, 1425.5) == Decimal("108.34")
+
+
+def test_serial_matching_input_order_decides_who_gets_the_cash() -> None:
+ # VD-10: orders array order = matching order (frozen tie-breaker).
+ # cash 142200.00; 600519.SH buy cost = 142100.00 + 36.95 = 142136.95;
+ # 000001.SZ buy cost = 1000.00 + 5.01 = 1005.01. Both do NOT fit.
+ frames = {
+ "600519.SH": _frame([(_PREV, 1418.0), (_DAY, 1421.0)]),
+ "000001.SZ": _frame([(_PREV, 9.9), (_DAY, 10.0)]),
+ }
+ market_data = _fetch(frames, ["000001.SZ", "600519.SH"])
+ big = {"symbol": "600519.SH", "side": "buy", "qty": 100}
+ small = {"symbol": "000001.SZ", "side": "buy", "qty": 100}
+
+ forward = _match(_request(142200.0, [], [big, small]), market_data)
+ assert [f.symbol for f in forward.fills] == ["600519.SH"]
+ assert forward.rejected_orders[0].symbol == "000001.SZ"
+ assert forward.rejected_orders[0].reason_code == "insufficient_cash"
+ # nav = 63.05 + 100×1421.00 = 142163.05
+ assert forward.nav_series[0].nav == 142163.05
+
+ reversed_ = _match(_request(142200.0, [], [small, big]), market_data)
+ assert [f.symbol for f in reversed_.fills] == ["000001.SZ"]
+ assert reversed_.rejected_orders[0].symbol == "600519.SH"
+ assert reversed_.rejected_orders[0].reason_code == "insufficient_cash"
+
+
+def test_fee_model_override_flows_through_to_the_effective_values() -> None:
+ # R7-3 pass-through (T5 finalizes the wire echo): an injected override
+ # wins over the default. notional 1000 → comm 1000×0.01 = 10.00,
+ # transfer 0.01 → fee 10.01.
+ frames = {"600519.SH": _frame([(_PREV, 10.0), (_DAY, 10.0)])}
+ request = parse_request({
+ "account_id": "pa_golden_cn_a", "market": "cn_a",
+ "account_state": {"cash": 100000.0, "positions": []},
+ "orders": [{"symbol": "600519.SH", "side": "buy", "qty": 100}],
+ "from_date": _DAY, "to_date": _DAY,
+ "fee_model": {**_FEE_MODEL, "commission_rate": 0.01},
+ })
+ outcome = _match(request, _fetch(frames, ["600519.SH"]))
+ assert outcome.fills[0].fee == 10.01
+ assert outcome.effective_fee_model["commission_rate"] == 0.01
+ assert outcome.effective_fee_model["commission_min"] == 5.0
+
+
+def test_same_inputs_produce_identical_outcomes() -> None:
+ # Determinism (R1-1) at the outcome level; byte-level sha goldens are T5.
+ market_data = _fetch(_FRAMES, ["600519.SH"])
+ request = _request(200000.0, [], [{"symbol": "600519.SH", "side": "buy", "qty": 100}])
+ first = _match(request, market_data)
+ second = _match(request, market_data)
+ assert first.fills == second.fills
+ assert first.rejected_orders == second.rejected_orders
+ assert first.nav_series == second.nav_series
+ assert first.end_state == second.end_state
+ assert first.warnings == second.warnings
+ assert first.effective_fee_model == second.effective_fee_model
diff --git a/agent/tests/test_paper_trade_golden_hk.py b/agent/tests/test_paper_trade_golden_hk.py
new file mode 100644
index 000000000..9e16e02a1
--- /dev/null
+++ b/agent/tests/test_paper_trade_golden_hk.py
@@ -0,0 +1,162 @@
+"""T2-gate hk golden sample: state+orders → fills/nav/end_state (Step 3 / T3).
+
+Market data = the VD-14 recorded tencent fixture (hk_00700_tencent.json,
+raw caliber, last bar 2026-10-16 close 417.8). Fees hand-computed to the
+cent (VD-9): commission 0.03% min HK$3 + stamp duty 0.1% per order per side
+quantized to WHOLE HKD ROUND_HALF_UP (the registered VD-9 choice; HKEX
+itself ceils) + regulatory levy 0.003%. Offline: fixture-backed fake
+loader only (``--disable-socket`` hard gate).
+"""
+
+from __future__ import annotations
+
+import json
+from decimal import Decimal
+from pathlib import Path
+
+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.rules import MarketRules
+from src.tools.paper_trade.schema import parse_request
+
+_FIXTURE = Path(__file__).parent / "fixtures" / "paper_trade" / "market" / "hk_00700_tencent.json"
+_DAY = "2026-10-16" # fixture's last bar; close 417.8
+_CLOSE = 417.8
+
+# §4 hk default fee matrix (state_hash._DEFAULT_FEE_MODELS terminal values).
+_FEE_MODEL = {
+ "commission_rate": 0.0003, # 0.03%
+ "commission_min": 3.0, # HK$3 minimum
+ "stamp_tax_rate": 0.001, # 0.1% per order per side, whole HKD
+ "regulatory_levy_rate": 0.00003, # ≈0.003% combined levies
+}
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "tencent") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+def _fixture_frame() -> pd.DataFrame:
+ document = json.loads(_FIXTURE.read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]]
+
+
+def _fetch(symbols: list[str], frames: dict[str, pd.DataFrame] | None = None):
+ frames = frames if frames is not None else {"00700.HK": _fixture_frame()}
+ return fetch_market_data("hk", symbols, _DAY, _DAY, loader=FakeLoader(frames))
+
+
+def _request(cash: float, positions: list[dict], orders: list[dict]):
+ return parse_request({
+ "account_id": "pa_golden_hk", "market": "hk",
+ "account_state": {"cash": cash, "positions": positions},
+ "orders": orders, "from_date": _DAY, "to_date": _DAY,
+ "fee_model": dict(_FEE_MODEL),
+ })
+
+
+def test_hk_buy_golden_fee_hand_computed_to_the_cent() -> None:
+ # Hand computation (VD-9, Decimal ROUND_HALF_UP), close = 417.8:
+ # notional = 100 × 417.80 = 41780.00
+ # commission = max(41780 × 0.0003, 3) = max(12.534, 3) = 12.534
+ # stamp = 41780 × 0.001 = 41.78 → whole HKD HALF_UP = 42
+ # levy = 41780 × 0.00003 = 1.2534
+ # fee = 12.534 + 42 + 1.2534 = 55.7874 → 2dp HALF_UP = 55.79
+ # cash_end = 100000.00 − 41780.00 − 55.79 = 58164.21
+ # nav = 58164.21 + 100 × 417.80 = 99944.21
+ outcome = engine.match_orders(
+ _request(100000.0, [], [{"symbol": "00700.HK", "side": "buy", "qty": 100}]),
+ market_data=_fetch(["00700.HK"]),
+ )
+
+ assert outcome.error is None
+ fill = outcome.fills[0]
+ assert (fill.trade_date, fill.symbol, fill.side, fill.qty) == (_DAY, "00700.HK", "buy", 100)
+ assert fill.price == _CLOSE # fill price = close (§4)
+ assert fill.fee == 55.79
+ assert fill.reason == "" # VD-15: orders mode
+ assert outcome.end_state.cash == 58164.21
+ assert outcome.end_state.positions[0].qty == 100
+ assert outcome.end_state.positions[0].avg_cost == _CLOSE
+ nav = outcome.nav_series[0]
+ assert (nav.date, nav.nav, nav.cash, nav.position_value) == (_DAY, 99944.21, 58164.21, 41780.0)
+ # DD-4 fallback chain: no lot table entry → default 100 + diagnostic warning.
+ assert any("lot assumption" in w and "0700.HK" in w for w in outcome.warnings)
+
+
+def test_hk_stamp_tax_quantizes_half_up_to_whole_hkd_not_banker() -> None:
+ # VD-9 pin: notional 40500 → stamp 40.5 → HALF_UP → 41
+ # (Python's builtin banker's rounding would give 40).
+ # commission = max(40500 × 0.0003 = 12.15, 3) = 12.15
+ # levy = 40500 × 0.00003 = 1.215
+ # fee = 12.15 + 41 + 1.215 = 54.365 → 2dp HALF_UP = 54.37
+ rules = MarketRules("hk", _FEE_MODEL)
+ assert rules.fee("buy", 100, 405.0) == Decimal("54.37")
+ assert round(40.5) == 40 # the banker's-rounding trap this matrix avoids
+
+
+def test_hk_same_day_round_trip_is_allowed_t0() -> None:
+ # §4 settlement row: hk is T+0 — buy→sell on the same day both fill.
+ # buy fee = 55.79 (as above); sell fee identical at the same close
+ # cash_end = 100000 − 41780.00 − 55.79 + 41780.00 − 55.79 = 99888.42
+ outcome = engine.match_orders(
+ _request(100000.0, [], [
+ {"symbol": "00700.HK", "side": "buy", "qty": 100},
+ {"symbol": "00700.HK", "side": "sell", "qty": 100},
+ ]),
+ market_data=_fetch(["00700.HK"]),
+ )
+ assert outcome.error is None
+ assert [(f.side, f.fee) for f in outcome.fills] == [("buy", 55.79), ("sell", 55.79)]
+ assert outcome.rejected_orders == ()
+ assert outcome.end_state.cash == 99888.42
+ assert outcome.end_state.positions == ()
+ assert outcome.nav_series[0].nav == 99888.42
+
+
+def test_hk_order_violating_the_board_lot_is_rejected() -> None:
+ # §4 lot row: qty 150 is not a multiple of the (default) 100-share board
+ # lot → lot_size rejection, structured, no crash, cash untouched.
+ outcome = engine.match_orders(
+ _request(100000.0, [], [{"symbol": "00700.HK", "side": "buy", "qty": 150}]),
+ market_data=_fetch(["00700.HK"]),
+ )
+ assert outcome.fills == ()
+ rejected = outcome.rejected_orders[0]
+ assert rejected.reason_code == "lot_size"
+ assert "100-share" in rejected.detail
+ assert outcome.end_state.cash == 100000.0
+ assert len(outcome.nav_series) == 1 # the day still commits its nav row
+
+
+def test_hk_lot_table_injection_overrides_the_default() -> None:
+ # DD-4: an injected per-symbol lot table (live tencent quote idx-60 is a
+ # T9b wiring concern) flows into the reused _hk_board_lot mechanism.
+ rules = MarketRules("hk", _FEE_MODEL, hk_lot_sizes={"00700.HK": 400})
+ assert rules.lot_size("00700.HK") == 400
+ assert rules.lot_violation("00700.HK", 100) is True
+ assert rules.lot_violation("00700.HK", 400) is False
+ assert rules.lot_assumptions == {} # table hit → no fallback diagnostic
+
+
+def test_hk_golden_is_deterministic() -> None:
+ market_data = _fetch(["00700.HK"])
+ request = _request(100000.0, [], [{"symbol": "00700.HK", "side": "buy", "qty": 100}])
+ first = engine.match_orders(request, market_data=market_data)
+ second = engine.match_orders(request, market_data=market_data)
+ assert first.fills == second.fills
+ assert first.nav_series == second.nav_series
+ assert first.end_state == second.end_state
+ assert first.warnings == second.warnings
diff --git a/agent/tests/test_paper_trade_golden_us.py b/agent/tests/test_paper_trade_golden_us.py
new file mode 100644
index 000000000..b3ae4b388
--- /dev/null
+++ b/agent/tests/test_paper_trade_golden_us.py
@@ -0,0 +1,151 @@
+"""T2-gate us golden sample: state+orders → fills/nav/end_state (Step 3 / T3).
+
+Market data = the VD-14 recorded sina fixture (us_AAPL_sina.json, raw
+caliber, last bar 2026-10-16 close 343.46). Fees hand-computed to the cent
+(VD-9): commission $0.0049/share min $0.99, SEC fee simplified to 0 (§4 —
+the registered terminal value; any micro-adjustment is a delivery-note
+item). Offline: fixture-backed fake loader only (``--disable-socket``).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+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
+
+_FIXTURE = Path(__file__).parent / "fixtures" / "paper_trade" / "market" / "us_AAPL_sina.json"
+_DAY = "2026-10-16" # fixture's last bar; close 343.46
+_CLOSE = 343.46
+
+# §4 us default fee matrix (state_hash._DEFAULT_FEE_MODELS terminal values).
+_FEE_MODEL = {
+ "commission_per_share": 0.0049, # $0.0049/share
+ "commission_min": 0.99, # $0.99 minimum
+ "sec_fee_rate": 0.0, # simplified to zero (§4)
+}
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "sina") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+def _fixture_frame() -> pd.DataFrame:
+ document = json.loads(_FIXTURE.read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]]
+
+
+def _fetch(symbols: list[str]):
+ return fetch_market_data(
+ "us", symbols, _DAY, _DAY, loader=FakeLoader({"AAPL.US": _fixture_frame()})
+ )
+
+
+def _request(cash: float, positions: list[dict], orders: list[dict]):
+ return parse_request({
+ "account_id": "pa_golden_us", "market": "us",
+ "account_state": {"cash": cash, "positions": positions},
+ "orders": orders, "from_date": _DAY, "to_date": _DAY,
+ "fee_model": dict(_FEE_MODEL),
+ })
+
+
+def test_us_buy_golden_fee_hand_computed_to_the_cent() -> None:
+ # Hand computation (VD-9, Decimal ROUND_HALF_UP), close = 343.46:
+ # notional = 10 × 343.46 = 3434.60
+ # commission = max(10 × 0.0049 = 0.049, 0.99) = 0.99 (minimum dominates)
+ # SEC fee = 3434.60 × 0.0 = 0 (§4 simplified)
+ # fee = 0.99
+ # cash_end = 50000.00 − 3434.60 − 0.99 = 46564.41
+ # nav = 46564.41 + 10 × 343.46 = 49999.01
+ outcome = engine.match_orders(
+ _request(50000.0, [], [{"symbol": "AAPL.US", "side": "buy", "qty": 10}]),
+ market_data=_fetch(["AAPL.US"]),
+ )
+
+ assert outcome.error is None
+ fill = outcome.fills[0]
+ assert (fill.trade_date, fill.symbol, fill.side, fill.qty) == (_DAY, "AAPL.US", "buy", 10)
+ assert fill.price == _CLOSE # fill price = close (§4)
+ assert fill.fee == 0.99
+ assert fill.reason == "" # VD-15: orders mode
+ assert outcome.end_state.cash == 46564.41
+ assert outcome.end_state.positions[0].qty == 10
+ assert outcome.end_state.positions[0].avg_cost == _CLOSE
+ nav = outcome.nav_series[0]
+ assert (nav.date, nav.nav, nav.cash, nav.position_value) == (_DAY, 49999.01, 46564.41, 3434.6)
+ assert outcome.warnings == () # us lot = 1 share: no board-lot assumptions
+
+
+def test_us_commission_scales_above_the_minimum() -> None:
+ # Hand computation: 1000 shares → commission = max(1000 × 0.0049 = 4.90,
+ # 0.99) = 4.90; notional = 1000 × 343.46 = 343460.00
+ # cash_end = 400000.00 − 343460.00 − 4.90 = 56535.10
+ # nav = 56535.10 + 343460.00 = 399995.10
+ outcome = engine.match_orders(
+ _request(400000.0, [], [{"symbol": "AAPL.US", "side": "buy", "qty": 1000}]),
+ market_data=_fetch(["AAPL.US"]),
+ )
+ assert outcome.fills[0].fee == 4.9
+ assert outcome.end_state.cash == 56535.10
+ assert outcome.nav_series[0].nav == 399995.10
+
+
+def test_us_fractional_qty_violates_the_one_share_lot() -> None:
+ # §4 lot row: us = 1 share — fractional qty rejects lot_size (the paper
+ # engine never rounds a user-stated qty), structured and no crash.
+ outcome = engine.match_orders(
+ _request(50000.0, [], [{"symbol": "AAPL.US", "side": "buy", "qty": 1.5}]),
+ market_data=_fetch(["AAPL.US"]),
+ )
+ assert outcome.fills == ()
+ assert outcome.rejected_orders[0].reason_code == "lot_size"
+ assert outcome.end_state.cash == 50000.0
+ assert len(outcome.nav_series) == 1 # the day still commits its nav row
+
+
+def test_us_same_day_sell_then_buy_both_fill_t0() -> None:
+ # §4 settlement row: us is T+0. Sell the seeded 10 shares, buy 10 back:
+ # sell proceeds = 3434.60 − 0.99 = 3433.61
+ # buy cost = 3434.60 + 0.99 = 3435.59
+ # cash_end = 50000.00 + 3433.61 − 3435.59 = 49998.02
+ # new avg_cost = 343.46 (re-opened at the fill price)
+ # nav = 49998.02 + 10 × 343.46 = 53432.62
+ outcome = engine.match_orders(
+ _request(50000.0, [{"symbol": "AAPL.US", "qty": 10, "avg_cost": 340.0}], [
+ {"symbol": "AAPL.US", "side": "sell", "qty": 10},
+ {"symbol": "AAPL.US", "side": "buy", "qty": 10},
+ ]),
+ market_data=_fetch(["AAPL.US"]),
+ )
+ assert outcome.error is None
+ assert [(f.side, f.fee) for f in outcome.fills] == [("sell", 0.99), ("buy", 0.99)]
+ assert outcome.rejected_orders == ()
+ assert outcome.end_state.cash == 49998.02
+ assert outcome.end_state.positions[0].avg_cost == _CLOSE
+ assert outcome.nav_series[0].nav == 53432.62
+
+
+def test_us_golden_is_deterministic() -> None:
+ market_data = _fetch(["AAPL.US"])
+ request = _request(50000.0, [], [{"symbol": "AAPL.US", "side": "buy", "qty": 10}])
+ first = engine.match_orders(request, market_data=market_data)
+ second = engine.match_orders(request, market_data=market_data)
+ assert first.fills == second.fills
+ assert first.nav_series == second.nav_series
+ assert first.end_state == second.end_state
+ assert first.warnings == second.warnings
diff --git a/agent/tests/test_paper_trade_jcs.py b/agent/tests/test_paper_trade_jcs.py
new file mode 100644
index 000000000..6f15ef251
--- /dev/null
+++ b/agent/tests/test_paper_trade_jcs.py
@@ -0,0 +1,336 @@
+"""T11 — JCS frozen-vector tests for paper_trade state hashing (AM-4-2 / VD-4).
+
+The vector file ``agent/tests/fixtures/paper_trade/jcs_vectors.json`` is the
+SOLE cross-repo interpretation authority: the RM side asserts its own JCS
+implementation against the same vectors. Per the VD-14 re-baseline protocol
+the vectors are immutable once RM adopts them — regeneration requires human
+sign-off named in the commit message.
+
+Also smoke-tests the finalized pt-v1.1 contract schema (VD-13 file +
+dependency-free subset validator); the full T6 gate lives in
+test_paper_trade_schema.py (Step 5).
+
+Offline: no network, no clock, no writes.
+"""
+
+from __future__ import annotations
+
+import json
+from decimal import Decimal
+from pathlib import Path
+
+import pytest
+
+from src.tools.paper_trade.schema import (
+ ERROR_CODES,
+ REASON_CODES,
+ SKIPPED_DAY_REASONS,
+ load_contract_schema,
+ validate_payload,
+)
+from src.tools.paper_trade.state_hash import (
+ canonicalize,
+ compute_received_state_hash,
+ effective_fee_model,
+ state_hash,
+)
+
+_VECTORS_PATH = Path(__file__).parent / "fixtures" / "paper_trade" / "jcs_vectors.json"
+
+
+def _load_vectors() -> list[dict]:
+ document = json.loads(_VECTORS_PATH.read_text(encoding="utf-8"))
+ vectors = document["vectors"]
+ assert vectors, "frozen vector file must not be empty"
+ return vectors
+
+
+_VECTORS = _load_vectors()
+_BY_NAME = {vector["name"]: vector for vector in _VECTORS}
+_VECTOR_IDS = [vector["name"] for vector in _VECTORS]
+
+
+# ── Frozen vectors: canonical form AND hash, per vector ──
+
+
[email protected]("vector", _VECTORS, ids=_VECTOR_IDS)
+def test_canonical_form_matches_frozen_vector(vector: dict) -> None:
+ assert canonicalize(vector["input"]) == vector["canonical"]
+
+
[email protected]("vector", _VECTORS, ids=_VECTOR_IDS)
+def test_state_hash_matches_frozen_vector(vector: dict) -> None:
+ assert state_hash(vector["input"]) == vector["sha256"]
+
+
+def test_vector_file_pins_sha256_of_canonical_string() -> None:
+ """The stored digest must be sha256 of the stored canonical bytes.
+
+ Guards the artifact itself: a vector whose sha was not derived from its
+ canonical string would silently desynchronize VT and RM.
+ """
+ import hashlib
+
+ for vector in _VECTORS:
+ expected = hashlib.sha256(vector["canonical"].encode("utf-8")).hexdigest()
+ assert vector["sha256"] == expected, vector["name"]
+
+
+# ── T11 semantic assertions (the vector-independent half of the gate) ──
+
+
+def test_key_order_shuffle_is_invariant() -> None:
+ a = {"market": "cn_a", "account_id": "pa_01", "cash": 1000.5}
+ b = {"cash": 1000.5, "account_id": "pa_01", "market": "cn_a"}
+ c = {"account_id": "pa_01", "market": "cn_a", "cash": 1000.5}
+ assert canonicalize(a) == canonicalize(b) == canonicalize(c)
+ assert state_hash(a) == state_hash(b) == _BY_NAME["key_order_shuffle_a"]["sha256"]
+
+
+def test_integral_float_and_int_are_equivalent() -> None:
+ # 100000.0 ≡ 100000 — the headline JCS number rule (AM-4-1).
+ assert canonicalize({"qty": 100000.0}) == canonicalize({"qty": 100000}) == '{"qty":100000}'
+ assert _BY_NAME["float_int_equiv_float"]["sha256"] == _BY_NAME["float_int_equiv_int"]["sha256"]
+
+
+def test_large_and_exponent_forms_follow_ecmascript() -> None:
+ assert canonicalize(1e16) == "10000000000000000" # n=17 ≤ 21: plain form
+ assert canonicalize(1.2345678901234567e20) == "123456789012345670000" # n=21 boundary
+ assert canonicalize(1e21) == "1e+21" # n=22: exponential
+ assert canonicalize(-1e21) == "-1e+21"
+ assert canonicalize(1e-6) == "0.000001" # n=-5 > -6: plain form
+ assert canonicalize(1.5e-7) == "1.5e-7" # n=-6: exponential
+
+
+def test_negative_zero_canonicalizes_to_positive_zero() -> None:
+ assert canonicalize(-0.0) == "0"
+ assert canonicalize({"x": -0.0}) == canonicalize({"x": 0.0}) == canonicalize({"x": 0})
+
+
+def test_shortest_round_trip_repr_is_used() -> None:
+ # The classic float artifact: shortest digits that round-trip.
+ assert canonicalize(0.1 + 0.2) == "0.30000000000000004"
+ assert canonicalize(0.3) == "0.3"
+
+
+def test_unicode_symbols_stay_raw_utf8() -> None:
+ text = canonicalize({"symbol": "600519.SH", "name": "贵州茅台", "note": "naïve café — ✓"})
+ assert "贵州茅台" in text # ensure_ascii=False: no \uXXXX escaping for BMP text
+ assert "\\u" not in text
+
+
+def test_empty_positions_canonical_form() -> None:
+ assert canonicalize({"cash": 100000.0, "positions": []}) == '{"cash":100000,"positions":[]}'
+
+
+def test_array_order_is_semantic() -> None:
+ ab = _BY_NAME["array_order_ab"]["input"]
+ ba = _BY_NAME["array_order_ba"]["input"]
+ assert canonicalize(ab) != canonicalize(ba)
+ assert state_hash(ab) != state_hash(ba)
+ # Same element set — only the order differs, and order is part of the hash.
+ assert sorted(ab["positions"], key=lambda p: p["symbol"]) == sorted(
+ ba["positions"], key=lambda p: p["symbol"]
+ )
+
+
+def test_json_base_tokens() -> None:
+ assert canonicalize(True) == "true"
+ assert canonicalize(False) == "false"
+ assert canonicalize(None) == "null"
+ assert canonicalize({"flag": True}) == '{"flag":true}' # bool is NOT int 1
+
+
+def test_non_json_types_fail_closed() -> None:
+ with pytest.raises(TypeError):
+ canonicalize(Decimal("1.5")) # Decimal must be converted by the caller (VD-9)
+ with pytest.raises(TypeError):
+ canonicalize({1: "int key"}) # JSON object keys must be str
+ with pytest.raises(TypeError):
+ canonicalize(object())
+
+
+def test_non_finite_floats_fail_closed() -> None:
+ with pytest.raises(ValueError):
+ canonicalize(float("nan"))
+ with pytest.raises(ValueError):
+ canonicalize(float("inf"))
+
+
+def test_canonicalization_is_deterministic_across_calls() -> None:
+ payload = _BY_NAME["am4_hash_coverage_object"]["input"]
+ assert canonicalize(payload) == canonicalize(payload)
+ assert state_hash(payload) == state_hash(payload)
+
+
+# ── AM-4 coverage object + effective_fee_model echo ──
+
+
+def test_received_state_hash_covers_the_frozen_am4_object() -> None:
+ account_state = {"cash": 98213.44, "positions": [{"symbol": "600519.SH", "qty": 100, "avg_cost": 1418.0}]}
+ fee_model = {
+ "commission_rate": 0.00025,
+ "commission_min": 5.0,
+ "stamp_tax_sell": 0.0005,
+ "transfer_fee": 0.00001,
+ }
+ computed = compute_received_state_hash(
+ account_id="pa_deadbeefdeadbeefdeadbeef",
+ market="cn_a",
+ account_state=account_state,
+ fee_model=fee_model,
+ from_date="2026-10-20",
+ to_date="2026-10-20",
+ )
+ # Identical to hashing the frozen coverage object by hand (AM-4-1).
+ manual = state_hash(
+ {
+ "account_id": "pa_deadbeefdeadbeefdeadbeef",
+ "market": "cn_a",
+ "account_state": account_state,
+ "fee_model": fee_model,
+ "from_date": "2026-10-20",
+ "to_date": "2026-10-20",
+ }
+ )
+ assert computed == manual == _BY_NAME["am4_hash_coverage_object"]["sha256"]
+
+
+def test_effective_fee_model_echoes_cn_a_defaults() -> None:
+ # FROZEN terminal values (G1 approved 2026-10-19): REQUIREMENTS §4 matrix,
+ # cn_a key names verbatim per AMENDMENT §2.2 / APPROVAL note 5. Any
+ # change = major schema bump with RM written confirmation.
+ assert effective_fee_model("cn_a") == {
+ "commission_rate": 0.00025,
+ "commission_min": 5.0,
+ "stamp_tax_sell": 0.0005,
+ "transfer_fee": 0.00001,
+ }
+
+
+def test_effective_fee_model_echoes_hk_defaults() -> None:
+ # FROZEN terminal values (APPROVAL note 5): hk key names mapped
+ # item-by-item to the §4 matrix — commission 0.03% min HK$3, stamp duty
+ # 0.1% per side (whole HKD ROUND_HALF_UP, VD-9 registered), regulatory
+ # levy ≈0.003% combined.
+ assert effective_fee_model("hk") == {
+ "commission_rate": 0.0003,
+ "commission_min": 3.0,
+ "stamp_tax_rate": 0.001,
+ "regulatory_levy_rate": 0.00003,
+ }
+
+
+def test_effective_fee_model_echoes_us_defaults() -> None:
+ # FROZEN terminal values (APPROVAL note 5): us key names mapped to the
+ # §4 matrix — $0.0049/share min $0.99, SEC fee simplified to 0 (VD-9
+ # registered).
+ assert effective_fee_model("us") == {
+ "commission_per_share": 0.0049,
+ "commission_min": 0.99,
+ "sec_fee_rate": 0.0,
+ }
+
+
+def test_effective_fee_model_merges_overrides_per_key() -> None:
+ merged = effective_fee_model("cn_a", {"commission_rate": 0.0003, "custom_key": 1.5})
+ assert merged["commission_rate"] == 0.0003 # overridden
+ assert merged["commission_min"] == 5.0 # default kept
+ assert merged["custom_key"] == 1.5 # caller keys pass through
+
+
+def test_effective_fee_model_unknown_market_fails_closed() -> None:
+ with pytest.raises(ValueError, match="unknown market"):
+ effective_fee_model("crypto")
+
+
+# ── Contract-schema skeleton smoke (full T6 lands in Step 5) ──
+
+
+_MINIMAL_RESULT = {
+ "schema_version": "pt-v1.1",
+ "tool": "paper_trade_step",
+ "account_id": "pa_01",
+ "market": "cn_a",
+ "range": {"from": "2026-10-20", "to": "2026-10-20"},
+ "received_state_hash": "0" * 64,
+ "effective_fee_model": {"commission_rate": 0.00025},
+ "fills": [],
+ "rejected_orders": [],
+ "end_state": {"cash": 100000.0, "positions": []},
+ "nav_series": [
+ {"date": "2026-10-20", "nav": 100000.0, "cash": 100000.0, "position_value": 0.0}
+ ],
+ "skipped_days": [],
+ "warnings": [],
+ "data_provenance": {"source": "clickhouse+tencent(merged)"},
+}
+
+
+class TestContractSchemaSkeleton:
+ def test_named_schemas_load(self) -> None:
+ result_schema = load_contract_schema("result")
+ envelope_schema = load_contract_schema("error_envelope")
+ assert result_schema["type"] == "object"
+ assert "received_state_hash" in result_schema["properties"]
+ assert "effective_fee_model" in result_schema["properties"]
+ assert envelope_schema["properties"]["status"]["const"] == "error"
+
+ def test_unknown_schema_name_fails_closed(self) -> None:
+ with pytest.raises(KeyError):
+ load_contract_schema("request")
+
+ def test_minimal_result_payload_validates(self) -> None:
+ assert validate_payload(_MINIMAL_RESULT, load_contract_schema("result")) == []
+
+ def test_validator_reports_missing_wrong_and_extra(self) -> None:
+ payload = dict(_MINIMAL_RESULT)
+ del payload["tool"]
+ payload["market"] = "crypto"
+ payload["unexpected"] = 1
+ payload["rejected_orders"] = [
+ {
+ "trade_date": "2026-10-20",
+ "symbol": "600519.SH",
+ "side": "buy",
+ "qty": 100,
+ "reason_code": "not_in_vocabulary",
+ "detail": "",
+ }
+ ]
+ errors = validate_payload(payload, load_contract_schema("result"))
+ joined = "\n".join(errors)
+ assert "missing required property 'tool'" in joined
+ assert "not in enum" in joined # market
+ assert "additional property 'unexpected'" in joined
+ assert "not_in_vocabulary" in joined # reason_code enum
+
+ def test_error_envelope_validates(self) -> None:
+ envelope = {
+ "status": "error",
+ "code": "PAPER_DATA_NOT_READY",
+ "account_id": "pa_01",
+ "market": "cn_a",
+ "range": {"from": "2026-10-20", "to": "2026-10-20"},
+ "received_state_hash": "0" * 64,
+ "message": "target bar 2026-10-20 not available from served sources",
+ }
+ assert validate_payload(envelope, load_contract_schema("error_envelope")) == []
+ bad = dict(envelope, code="SOMETHING_ELSE")
+ assert validate_payload(bad, load_contract_schema("error_envelope")) != []
+
+ def test_vocabularies_are_closed_and_consistent_with_schema_file(self) -> None:
+ # AM-14: 11 reason_code + 2 skipped reason + 2 error code — the
+ # schema.py tuples and the jsonschema enums must agree exactly.
+ assert (len(REASON_CODES), len(SKIPPED_DAY_REASONS), len(ERROR_CODES)) == (11, 2, 2)
+ result_schema = load_contract_schema("result")
+ reason_enum = result_schema["properties"]["rejected_orders"]["items"]["properties"][
+ "reason_code"
+ ]["enum"]
+ skipped_enum = result_schema["properties"]["skipped_days"]["items"]["properties"]["reason"][
+ "enum"
+ ]
+ code_enum = load_contract_schema("error_envelope")["properties"]["code"]["enum"]
+ assert tuple(reason_enum) == REASON_CODES
+ assert tuple(skipped_enum) == SKIPPED_DAY_REASONS
+ assert tuple(code_enum) == ERROR_CODES
diff --git a/agent/tests/test_paper_trade_limits.py b/agent/tests/test_paper_trade_limits.py
new file mode 100644
index 000000000..d8f699a48
--- /dev/null
+++ b/agent/tests/test_paper_trade_limits.py
@@ -0,0 +1,176 @@
+"""T13-gate limit-order semantics matrix (AM-7 frozen, Step 3 / T3).
+
+buy fills only when close ≤ limit / sell only when close ≥ limit, fill price
+= close (marketable orders improve to the close); violation →
+``limit_not_marketable``; cn_a band checks (limit_up/limit_down) take
+precedence over the limit check (AM-14 order). Offline: fake clients only.
+"""
+
+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], name: str = "tencent") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c 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 _run_cn_a(orders: list[dict], close: float, prev_close: float = 10.0,
+ positions: list[dict] | None = None):
+ frames = {_SYM: _frame([(_PREV, prev_close), (_DAY, close)])}
+ market_data = fetch_market_data("cn_a", [_SYM], _DAY, _DAY,
+ loader=FakeLoader(frames), ch_client=FakeChClient())
+ request = parse_request({
+ "account_id": "pa_limits", "market": "cn_a",
+ "account_state": {"cash": 1000000.0, "positions": positions or []},
+ "orders": orders, "from_date": _DAY, "to_date": _DAY, "fee_model": {},
+ })
+ return engine.match_orders(request, market_data=market_data,
+ calendar_client=FakeCalendarClient())
+
+
+def _run_hk(orders: list[dict], close: float):
+ frames = {"00700.HK": _frame([(_PREV, close * 0.99), (_DAY, close)])}
+ market_data = fetch_market_data("hk", ["00700.HK"], _DAY, _DAY, loader=FakeLoader(frames))
+ request = parse_request({
+ "account_id": "pa_limits", "market": "hk",
+ "account_state": {"cash": 1000000.0, "positions": []},
+ "orders": orders, "from_date": _DAY, "to_date": _DAY, "fee_model": {},
+ })
+ return engine.match_orders(request, market_data=market_data)
+
+
+# ── AM-7 matrix: buy side ──
+
+
+def test_buy_limit_above_close_fills_at_the_close() -> None:
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "buy", "qty": 100, "limit": 11.0}], close=10.5)
+ assert outcome.fills[0].price == 10.5 # price improves to the close
+ assert outcome.rejected_orders == ()
+
+
+def test_buy_limit_equal_to_close_fills_boundary_inclusive() -> None:
+ # AM-7: buy fills when close ≤ limit — equality is marketable.
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "buy", "qty": 100, "limit": 10.5}], close=10.5)
+ assert len(outcome.fills) == 1 and outcome.fills[0].price == 10.5
+
+
+def test_buy_limit_below_close_is_rejected_limit_not_marketable() -> None:
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "buy", "qty": 100, "limit": 10.0}], close=10.5)
+ assert outcome.fills == ()
+ rejected = outcome.rejected_orders[0]
+ assert rejected.reason_code == "limit_not_marketable"
+ assert rejected.detail == "close 10.50 > limit 10.00"
+
+
+# ── AM-7 matrix: sell side (symmetric) ──
+
+
+def test_sell_limit_below_close_fills_at_the_close() -> None:
+ held = [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}]
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "sell", "qty": 100, "limit": 10.0}],
+ close=10.5, positions=held)
+ assert outcome.fills[0].price == 10.5
+ assert outcome.rejected_orders == ()
+
+
+def test_sell_limit_equal_to_close_fills_boundary_inclusive() -> None:
+ held = [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}]
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "sell", "qty": 100, "limit": 10.5}],
+ close=10.5, positions=held)
+ assert len(outcome.fills) == 1
+
+
+def test_sell_limit_above_close_is_rejected_limit_not_marketable() -> None:
+ held = [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}]
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "sell", "qty": 100, "limit": 11.0}],
+ close=10.5, positions=held)
+ assert outcome.fills == ()
+ rejected = outcome.rejected_orders[0]
+ assert rejected.reason_code == "limit_not_marketable"
+ assert rejected.detail == "close 10.50 < limit 11.00"
+
+
+def test_market_order_without_limit_fills_regardless_of_direction() -> None:
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "buy", "qty": 100}], close=10.5)
+ assert len(outcome.fills) == 1 and outcome.fills[0].price == 10.5
+
+
+# ── Band precedence (AM-14: limit_up/limit_down BEFORE limit_not_marketable) ──
+
+
+def test_limit_up_wins_over_limit_not_marketable() -> None:
+ # prev 10.0 → up band 11.00; close 11.0 is at the band AND above the
+ # 10.00 limit — the frozen order reports limit_up (slot 6 before 7).
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "buy", "qty": 100, "limit": 10.0}], close=11.0)
+ assert outcome.rejected_orders[0].reason_code == "limit_up"
+
+
+def test_limit_down_wins_over_limit_not_marketable() -> None:
+ # prev 10.0 → down band 9.00; close 9.0 at band AND below a 9.50 sell
+ # limit — limit_down wins.
+ held = [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}]
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "sell", "qty": 100, "limit": 9.5}],
+ close=9.0, positions=held)
+ assert outcome.rejected_orders[0].reason_code == "limit_down"
+
+
+def test_marketable_limit_inside_the_band_still_fills() -> None:
+ # close 10.5, band 9.00..11.00, buy limit 10.5 → fills at the close.
+ outcome = _run_cn_a([{"symbol": _SYM, "side": "buy", "qty": 100, "limit": 10.5}], close=10.5)
+ assert len(outcome.fills) == 1
+
+
+# ── hk: AM-7 applies, bands do NOT (§4: hk has no price limits) ──
+
+
+def test_hk_limit_semantics_apply_without_band_codes() -> None:
+ filled = _run_hk([{"symbol": "00700.HK", "side": "buy", "qty": 100, "limit": 10.5}], close=10.5)
+ assert len(filled.fills) == 1 and filled.fills[0].price == 10.5
+ rejected = _run_hk([{"symbol": "00700.HK", "side": "buy", "qty": 100, "limit": 10.0}], close=10.5)
+ assert rejected.rejected_orders[0].reason_code == "limit_not_marketable"
+ # A 10%+ up move never yields limit_up in hk — the code is cn_a-only.
+ big_move = _run_hk([{"symbol": "00700.HK", "side": "buy", "qty": 100}], close=11.0)
+ assert len(big_move.fills) == 1
+ assert all(r.reason_code not in {"limit_up", "limit_down"} for r in big_move.rejected_orders)
diff --git a/agent/tests/test_paper_trade_limits_cn_a.py b/agent/tests/test_paper_trade_limits_cn_a.py
new file mode 100644
index 000000000..dae9e09b1
--- /dev/null
+++ b/agent/tests/test_paper_trade_limits_cn_a.py
@@ -0,0 +1,220 @@
+"""Offline tests for cn_a price-limit / ST / suspension lookups (VD-11).
+
+Table-first (fake CH client with recorded rows), heuristic fallback (the
+imported china_a._price_limit board ratios + Decimal ROUND_HALF_UP), and
+provenance recording. Never the network, never live ClickHouse.
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade.limits_cn_a import (
+ PROV_LIMITS_HEURISTIC,
+ PROV_LIMITS_TABLE,
+ PROV_LIMITS_UNAVAILABLE,
+ PROV_LIMIT_LIST_ROW,
+ PROV_ST_NO_ROW,
+ PROV_ST_ROW,
+ PROV_SUSPEND_NO_ROW,
+ PROV_SUSPEND_ROW,
+ ClickHouseLimitsClient,
+ get_limit_status,
+ heuristic_limit_prices,
+)
+
+_TRADE_DATE = "2026-10-20"
+
+
+class FakeLimitsClient:
+ """Canned per-table rows; each getter returns the recorded DataFrame."""
+
+ def __init__(
+ self,
+ *,
+ stk_limit: list[dict] | None = None,
+ st: list[dict] | None = None,
+ suspend: list[dict] | None = None,
+ limit_list: list[dict] | None = None,
+ ) -> None:
+ self._stk_limit = stk_limit or []
+ self._st = st or []
+ self._suspend = suspend or []
+ self._limit_list = limit_list or []
+
+ def get_stk_limit(self, trade_date: str, ts_code: str) -> pd.DataFrame:
+ return pd.DataFrame(self._stk_limit)
+
+ def get_stk_st_daily(self, trade_date: str, ts_code: str) -> pd.DataFrame:
+ return pd.DataFrame(self._st)
+
+ def get_stk_suspend(self, trade_date: str, ts_code: str) -> pd.DataFrame:
+ return pd.DataFrame(self._suspend)
+
+ def get_stk_limit_list(self, trade_date: str, ts_code: str) -> pd.DataFrame:
+ return pd.DataFrame(self._limit_list)
+
+
+# ── Table-first path ──
+
+
+def test_table_hit_serves_absolute_prices() -> None:
+ client = FakeLimitsClient(stk_limit=[{"up_limit": 11.0, "down_limit": 9.0}])
+ status = get_limit_status(client, "600519.SH", _TRADE_DATE)
+ assert status.up_limit == 11.0
+ assert status.down_limit == 9.0
+ assert PROV_LIMITS_TABLE in status.provenance
+ assert PROV_LIMITS_HEURISTIC not in status.provenance
+
+
+def test_table_wins_over_prev_close_heuristic() -> None:
+ client = FakeLimitsClient(stk_limit=[{"up_limit": 11.0, "down_limit": 9.0}])
+ status = get_limit_status(client, "600519.SH", _TRADE_DATE, prev_close=999.0)
+ assert status.up_limit == 11.0
+ assert PROV_LIMITS_TABLE in status.provenance
+
+
+# ── Heuristic fallback path ──
+
+
+ ("ts_code", "expected"),
+ [
+ ("600519.SH", (11.0, 9.0)), # main board ±10%
+ ("000001.SZ", (11.0, 9.0)), # main board ±10%
+ ("300001.SZ", (12.0, 8.0)), # ChiNext ±20%
+ ("688001.SH", (12.0, 8.0)), # STAR ±20%
+ ("830799.BJ", (13.0, 7.0)), # BSE ±30%
+ ],
+)
+def test_heuristic_board_ratios_match_the_engine_primitive(ts_code: str, expected: tuple[float, float]) -> None:
+ client = FakeLimitsClient()
+ status = get_limit_status(client, ts_code, _TRADE_DATE, prev_close=10.0)
+ assert (status.up_limit, status.down_limit) == expected
+ assert PROV_LIMITS_HEURISTIC in status.provenance
+
+
+def test_st_from_table_overrides_heuristic_ratio_to_five_percent() -> None:
+ # The engine heuristic cannot detect ST from the code alone (known gap);
+ # the paper path closes it with stk_st_daily.
+ client = FakeLimitsClient(st=[{"type": "ST", "type_name": "ST"}])
+ status = get_limit_status(client, "600519.SH", _TRADE_DATE, prev_close=10.0)
+ assert status.is_st is True
+ assert (status.up_limit, status.down_limit) == (10.5, 9.5)
+ assert PROV_ST_ROW in status.provenance
+
+
+def test_heuristic_quantizes_half_up_not_banker() -> None:
+ # VD-9 trap pin: 10.05 × 1.1 = 11.055 → HALF_UP → 11.06.
+ # Builtin round(11.055, 2) gives 11.05 (float 11.0549999… + banker's).
+ up, down = heuristic_limit_prices("600519.SH", 10.05, is_st=False)
+ assert up == 11.06
+ # 10.05 × 0.9 = 9.045 → HALF_UP → 9.05 (builtin round would give 9.04).
+ assert down == 9.05
+
+
+def test_heuristic_rejects_non_positive_prev_close() -> None:
+ with pytest.raises(ValueError, match="prev_close must be positive"):
+ heuristic_limit_prices("600519.SH", 0.0, is_st=False)
+ with pytest.raises(ValueError, match="prev_close must be positive"):
+ heuristic_limit_prices("600519.SH", -1.5, is_st=False)
+
+
+def test_no_table_and_no_prev_close_never_fabricates_a_band() -> None:
+ client = FakeLimitsClient()
+ status = get_limit_status(client, "600519.SH", _TRADE_DATE)
+ assert status.up_limit is None
+ assert status.down_limit is None
+ assert PROV_LIMITS_UNAVAILABLE in status.provenance
+
+
+# ── ST / suspension facets ──
+
+
+def test_no_st_row_reports_not_st_with_provenance() -> None:
+ status = get_limit_status(FakeLimitsClient(), "600519.SH", _TRADE_DATE, prev_close=10.0)
+ assert status.is_st is False
+ assert PROV_ST_NO_ROW in status.provenance
+
+
+def test_suspension_row_marks_suspended() -> None:
+ client = FakeLimitsClient(suspend=[{"suspend_type": "S", "suspend_timing": ""}])
+ status = get_limit_status(client, "600519.SH", _TRADE_DATE)
+ assert status.is_suspended is True
+ assert PROV_SUSPEND_ROW in status.provenance
+
+
+def test_resumption_row_is_not_a_suspension() -> None:
+ # tushare-lineage semantics: suspend_type R = resumed trading that day.
+ client = FakeLimitsClient(suspend=[{"suspend_type": "R", "suspend_timing": ""}])
+ status = get_limit_status(client, "600519.SH", _TRADE_DATE)
+ assert status.is_suspended is False
+ assert PROV_SUSPEND_ROW in status.provenance
+
+
+def test_no_suspension_row_reports_not_suspended_with_provenance() -> None:
+ status = get_limit_status(FakeLimitsClient(), "600519.SH", _TRADE_DATE, prev_close=10.0)
+ assert status.is_suspended is False
+ assert PROV_SUSPEND_NO_ROW in status.provenance
+
+
+# ── Auxiliary stk_limit_list_d flag ──
+
+
+def test_limit_list_flag_passes_through() -> None:
+ client = FakeLimitsClient(limit_list=[{"limit": "U"}])
+ status = get_limit_status(client, "600519.SH", _TRADE_DATE, prev_close=10.0)
+ assert status.limit_list_flag == "U"
+ assert PROV_LIMIT_LIST_ROW in status.provenance
+
+
+def test_limit_list_absent_leaves_flag_none() -> None:
+ status = get_limit_status(FakeLimitsClient(), "600519.SH", _TRADE_DATE, prev_close=10.0)
+ assert status.limit_list_flag is None
+ assert PROV_LIMIT_LIST_ROW not in status.provenance
+
+
+# ── Determinism ──
+
+
+def test_lookup_is_deterministic() -> None:
+ client = FakeLimitsClient(
+ stk_limit=[{"up_limit": 11.0, "down_limit": 9.0}],
+ st=[{"type": "ST", "type_name": "ST"}],
+ )
+ first = get_limit_status(client, "600519.SH", _TRADE_DATE, prev_close=10.0)
+ second = get_limit_status(client, "600519.SH", _TRADE_DATE, prev_close=10.0)
+ assert first == second
+ assert first.provenance == second.provenance
+
+
+# ── ClickHouse adapter (SQL shape only — no live CH) ──
+
+
+class FakeConnector:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, dict[str, str]]] = []
+
+ def query(self, sql: str, params: dict[str, str] | None = None) -> pd.DataFrame:
+ self.calls.append((sql, params or {}))
+ return pd.DataFrame([])
+
+
+def test_adapter_sql_names_tables_and_columns_explicitly() -> None:
+ connector = FakeConnector()
+ client = ClickHouseLimitsClient(connector)
+ client.get_stk_limit(_TRADE_DATE, "600519.SH")
+ client.get_stk_st_daily(_TRADE_DATE, "600519.SH")
+ client.get_stk_suspend(_TRADE_DATE, "600519.SH")
+ client.get_stk_limit_list(_TRADE_DATE, "600519.SH")
+
+ assert len(connector.calls) == 4
+ for sql, params in connector.calls:
+ assert "SELECT *" not in sql # clickhouse_columns.py contract
+ assert params == {"param_trade_date": _TRADE_DATE, "param_ts_code": "600519.SH"}
+
+ by_table = {sql.split("FROM ")[1].split(" ")[0]: sql for sql, _ in connector.calls}
+ assert set(by_table) == {"stk_limit", "stk_st_daily", "stk_suspend", "stk_limit_list_d"}
+ assert "up_limit, down_limit" in by_table["stk_limit"]
+ assert "`limit`" in by_table["stk_limit_list_d"] # SQL keyword, backtick-quoted
diff --git a/agent/tests/test_paper_trade_multiday.py b/agent/tests/test_paper_trade_multiday.py
new file mode 100644
index 000000000..fa3d95d2d
--- /dev/null
+++ b/agent/tests/test_paper_trade_multiday.py
@@ -0,0 +1,286 @@
+"""T4 gate (orders form): 3 sequential single-day calls thread state (AM-3).
+
+Day k's ``account_state`` = day k-1's ``end_state`` converted to the wire
+shape ``{cash, positions:[{symbol,qty,avg_cost}]}`` — the mechanical
+threading RM performs for orders-mode catch-up (AM-3/RM-2). The chain-hash
+assertion is R7-5's catch-up check computed IN THE TEST (T5 owns the
+``received_state_hash`` wire field; ``MatchOutcome`` deliberately does not
+carry it): the hash over call k's injected state / effective fee model /
+dates must equal ``sha256(JCS(day k-1 end_state as account_state shape))``
+under the same frozen AM-4-1 coverage object.
+Market = us (T+0), frame = the frozen ``synthetic_split_4to1`` fixture's
+post-split region (2026-02-03..05, closes 119.5/120.0/120.5) — which also
+implicitly exercises note 2: the 4:1 cliff (2026-02-02) sits inside every
+call's K=120 lookback and must never fire.
+
+The T4-gate strategy_path form (T7) lives at the bottom: ONE call over three
+trading days whose range spans a weekend (2026-02-05..09), the same order
+schedule threaded through the engine's internal day chaining, and the
+byte-identical replay obligation (sha256 over the canonical outcome dump)
+that only this form carries.
+Offline: fixture-backed fake loader.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import hashlib
+import json
+from pathlib import Path
+
+import pandas as pd
+
+from src.config.paths import get_runtime_root
+from src.tools.paper_trade import engine, state_hash, strategy_exec
+from src.tools.paper_trade.data import fetch_market_data
+from src.tools.paper_trade.schema import parse_request
+
+_FIXTURE = Path(__file__).parent / "fixtures" / "paper_trade" / "market" / "synthetic_split_4to1.json"
+_SYM = "SYNTH-4TO1"
+_ACCOUNT = "pa_multiday"
+_MARKET = "us"
+
+# §4 us default fee matrix, injected explicitly (AM-4-3: RM always injects).
+_FEE_MODEL = {
+ "commission_per_share": 0.0049,
+ "commission_min": 0.99,
+ "sec_fee_rate": 0.0,
+}
+
+_DAYS = ("2026-02-03", "2026-02-04", "2026-02-05")
+_ORDERS = (
+ [{"symbol": _SYM, "side": "buy", "qty": 100}],
+ [{"symbol": _SYM, "side": "sell", "qty": 50}, {"symbol": _SYM, "side": "buy", "qty": 20}],
+ [{"symbol": _SYM, "side": "sell", "qty": 70}],
+)
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "sina") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+def _fixture_frame() -> pd.DataFrame:
+ document = json.loads(_FIXTURE.read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]]
+
+
+def _fetch(day: str):
+ return fetch_market_data(_MARKET, [_SYM], day, day,
+ loader=FakeLoader({_SYM: _fixture_frame()}))
+
+
+def _state_shape(end_state) -> dict:
+ # end_state → account_state wire shape (the exact conversion RM threads).
+ return {
+ "cash": end_state.cash,
+ "positions": [
+ {"symbol": p.symbol, "qty": p.qty, "avg_cost": p.avg_cost}
+ for p in end_state.positions
+ ],
+ }
+
+
+def _effective_fee_model() -> dict:
+ return state_hash.effective_fee_model(_MARKET, dict(_FEE_MODEL))
+
+
+def _hash(account_state: dict, day: str) -> str:
+ return state_hash.compute_received_state_hash(
+ account_id=_ACCOUNT, market=_MARKET, account_state=account_state,
+ fee_model=_effective_fee_model(), from_date=day, to_date=day,
+ )
+
+
+def _run_sequence() -> list[tuple[str, dict, object]]:
+ # Returns [(day, injected_state, outcome)] for the 3-call catch-up chain.
+ runs: list[tuple[str, dict, object]] = []
+ state: dict = {"cash": 50000.0, "positions": []}
+ for day, orders in zip(_DAYS, _ORDERS):
+ request = parse_request({
+ "account_id": _ACCOUNT, "market": _MARKET, "account_state": state,
+ "orders": orders, "from_date": day, "to_date": day,
+ "fee_model": dict(_FEE_MODEL),
+ })
+ outcome = engine.match_orders(request, market_data=_fetch(day))
+ assert outcome.error is None
+ runs.append((day, state, outcome))
+ # Wire round-trip: the next call's state is the JSON-parsed end_state
+ # (proves JCS stability across serialization, not just in-memory).
+ state = json.loads(json.dumps(_state_shape(outcome.end_state)))
+ return runs
+
+
+def test_chain_hash_equals_prior_end_state_under_the_frozen_coverage() -> None:
+ runs = _run_sequence()
+ assert [day for day, _, _ in runs] == list(_DAYS)
+ for k in (1, 2):
+ day, injected, _ = runs[k]
+ prev_shape = _state_shape(runs[k - 1][2].end_state)
+ # R7-5 chain check: call k's hash over the injected state ≡ the hash
+ # over day k-1's end_state in the account_state shape.
+ assert _hash(injected, day) == _hash(prev_shape, day)
+ # Literal JCS form: sha256(JCS(end_state as account_state shape)).
+ assert state_hash.state_hash(injected) == state_hash.state_hash(prev_shape)
+ assert injected == prev_shape # threading is lossless (float round-trip)
+
+
+def test_three_day_ledger_continuity_hand_computed() -> None:
+ first, second, third = (outcome for _, _, outcome in _run_sequence())
+
+ # Day 1 (2026-02-03, close 119.5): buy 100 → notional 11950.00, fee
+ # max(100×0.0049, 0.99) = 0.99; cash 50000 − 11950.99 = 38049.01.
+ assert [(f.side, f.qty, f.price, f.fee) for f in first.fills] == [
+ ("buy", 100, 119.5, 0.99)]
+ assert first.end_state.cash == 38049.01
+ assert first.end_state.positions[0].qty == 100
+ assert first.end_state.positions[0].avg_cost == 119.5
+ assert [(n.date, n.nav) for n in first.nav_series] == [("2026-02-03", 49999.01)]
+
+ # Day 2 (close 120.0): sell 50 → +6000.00 − 0.99; buy 20 → −2400.00 − 0.99;
+ # cash 38049.01 + 5999.01 − 2400.99 = 41647.03; qty 70, avg_cost
+ # (50×119.5 + 20×120.0)/70 = 8375/70 = 119.642857… → 4dp HALF_UP 119.6429.
+ assert [(f.side, f.qty, f.price, f.fee) for f in second.fills] == [
+ ("sell", 50, 120.0, 0.99), ("buy", 20, 120.0, 0.99)]
+ assert second.rejected_orders == ()
+ assert second.end_state.cash == 41647.03
+ assert second.end_state.positions[0].qty == 70
+ assert second.end_state.positions[0].avg_cost == 119.6429
+ assert [(n.date, n.nav) for n in second.nav_series] == [("2026-02-04", 50047.03)]
+
+ # Day 3 (close 120.5): sell 70 → +8435.00 − 0.99; cash 41647.03 + 8434.01
+ # = 50081.04; the position closes out (zero-qty rows dropped).
+ assert [(f.side, f.qty, f.price, f.fee) for f in third.fills] == [
+ ("sell", 70, 120.5, 0.99)]
+ assert third.end_state.cash == 50081.04
+ assert third.end_state.positions == ()
+ assert [(n.date, n.nav) for n in third.nav_series] == [("2026-02-05", 50081.04)]
+
+ for outcome in (first, second, third):
+ assert outcome.skipped_days == ()
+ # Note 2: the 2026-02-02 split sits in every call's lookback and the
+ # detector never fires on it — no events, no rejections, no warnings.
+ assert outcome.data_provenance.corporate_actions == ()
+ assert not any("corporate action" in w for w in outcome.warnings)
+
+
+def test_sequence_replay_is_deterministic() -> None:
+ first_run = _run_sequence()
+ second_run = _run_sequence()
+ for (_, _, a), (_, _, b) in zip(first_run, second_run):
+ assert a.fills == b.fills
+ assert a.rejected_orders == b.rejected_orders
+ assert a.nav_series == b.nav_series
+ assert a.end_state == b.end_state
+ assert a.warnings == b.warnings
+ assert a.data_provenance == b.data_provenance
+ assert a.effective_fee_model == b.effective_fee_model == _effective_fee_model()
+
+
+# ── T4-gate strategy_path form (T7): ONE call, 3 trading days, weekend inside ──
+
+_STRATEGY_SCHEDULE_SOURCE = '''"""Date-keyed schedule strategy (T4 gate, strategy_path form)."""
+
+_SCHEDULE = {
+ "2026-02-05": [{"symbol": "SYNTH-4TO1", "side": "buy", "qty": 100, "reason": "form day 1"}],
+ "2026-02-06": [
+ {"symbol": "SYNTH-4TO1", "side": "sell", "qty": 50, "reason": "form day 2 exit"},
+ {"symbol": "SYNTH-4TO1", "side": "buy", "qty": 20, "reason": "form day 2 re-entry"},
+ ],
+ "2026-02-09": [{"symbol": "SYNTH-4TO1", "side": "sell", "qty": 70, "reason": "form day 3"}],
+}
+
+
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ return _SCHEDULE.get(trade_date, [])
+'''
+
+
+def _install_strategy(name: str, source: str) -> str:
+ # The T7 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 _run_strategy_form():
+ request = parse_request({
+ "account_id": _ACCOUNT, "market": _MARKET,
+ "account_state": {"cash": 50000.0, "positions": []},
+ "from_date": "2026-02-05", "to_date": "2026-02-09",
+ "strategy_path": _install_strategy("multiday_form.py", _STRATEGY_SCHEDULE_SOURCE),
+ "fee_model": dict(_FEE_MODEL),
+ })
+ market_data = fetch_market_data(_MARKET, [_SYM], "2026-02-05", "2026-02-09",
+ loader=FakeLoader({_SYM: _fixture_frame()}))
+ return strategy_exec.run_strategy_path(request=request, market_data=market_data)
+
+
+def _canonical_sha(outcome) -> str:
+ # test_run_card.py:330-353 instrument: sha256 over the canonical JSON dump.
+ document = {
+ "fills": [dataclasses.astuple(fill) for fill in outcome.fills],
+ "rejected": [dataclasses.astuple(item) for item in outcome.rejected_orders],
+ "nav": [dataclasses.astuple(point) for point in outcome.nav_series],
+ "skipped": [dataclasses.astuple(item) for item in outcome.skipped_days],
+ "end_state": dataclasses.astuple(outcome.end_state),
+ "warnings": list(outcome.warnings),
+ "provenance": dataclasses.astuple(outcome.data_provenance),
+ "fee_model": outcome.effective_fee_model,
+ "error": dataclasses.astuple(outcome.error) if outcome.error is not None else None,
+ }
+ text = json.dumps(document, sort_keys=True, default=str,
+ separators=(",", ":"), ensure_ascii=False)
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
+
+
+def test_strategy_path_single_call_three_day_form() -> None:
+ outcome = _run_strategy_form()
+ assert outcome.error is None
+ # One call, three matching days (02-05 Thu, 02-06 Fri, 02-09 Mon); the
+ # weekend is inside the range and implicit for us — no skip rows, nav
+ # continues across it. Closes 120.5/121.0/121.5; hand-computed chain:
+ # d1 −12050.99 → 37949.01; d2 +6049.01 −2420.99 → 41577.03 (70 @ 120.6429);
+ # d3 +8504.01 → 50081.04 — identical to the orders-form chain above, but
+ # threaded INSIDE the single call (previous day's end_state = next day's
+ # input, R1-2).
+ assert [(f.trade_date, f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [
+ ("2026-02-05", "buy", 100, 120.5, 0.99),
+ ("2026-02-06", "sell", 50, 121.0, 0.99),
+ ("2026-02-06", "buy", 20, 121.0, 0.99),
+ ("2026-02-09", "sell", 70, 121.5, 0.99),
+ ]
+ # VD-15/B2 strategy mode: the strategy's reason text reaches every fill.
+ assert [f.reason for f in outcome.fills] == [
+ "form day 1", "form day 2 exit", "form day 2 re-entry", "form day 3"]
+ assert outcome.end_state.cash == 50081.04
+ assert outcome.end_state.positions == ()
+ assert [(n.date, n.nav) for n in outcome.nav_series] == [
+ ("2026-02-05", 49999.01), ("2026-02-06", 50047.03), ("2026-02-09", 50081.04)]
+ assert outcome.skipped_days == ()
+ assert outcome.rejected_orders == ()
+ # Note 2 in strategy mode: the 4:1 cliff (2026-02-02) sits inside the
+ # K=120 lookback and never fires — no events, no rejections, no warnings.
+ assert outcome.data_provenance.corporate_actions == ()
+ assert not any("corporate action" in w for w in outcome.warnings)
+ assert outcome.effective_fee_model == _effective_fee_model()
+
+
+def test_strategy_path_replay_is_byte_identical() -> None:
+ # The byte-identical replay obligation rides THIS form only (plan §T4
+ # gate): two full runs — separate spawned children, separate fetches —
+ # must produce the same sha256 over the canonical outcome dump.
+ assert _canonical_sha(_run_strategy_form()) == _canonical_sha(_run_strategy_form())
diff --git a/agent/tests/test_paper_trade_nonfinite_prices.py b/agent/tests/test_paper_trade_nonfinite_prices.py
new file mode 100644
index 000000000..c98176619
--- /dev/null
+++ b/agent/tests/test_paper_trade_nonfinite_prices.py
@@ -0,0 +1,55 @@
+"""Non-finite feed prices must not reach matching or ledger valuation."""
+
+import json
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade.tool import run_paper_trade_step
+
+
[email protected]("column", ["open", "high", "low", "close"])
[email protected]("value", [float("inf"), float("-inf"), float("nan")])
+def test_nonfinite_price_rejects_order_and_keeps_finite_valuation(column, value):
+ frame = pd.DataFrame(
+ {
+ "open": [100.0, 100.0],
+ "high": [100.0, 100.0],
+ "low": [100.0, 100.0],
+ "close": [100.0, 100.0],
+ "volume": [1000.0, 1000.0],
+ },
+ index=pd.to_datetime(["2026-10-19", "2026-10-20"]),
+ )
+ frame.loc[pd.Timestamp("2026-10-20"), column] = value
+
+ class Loader:
+ name = "fixture"
+
+ def fetch(self, *args, **kwargs):
+ return {"AAPL": frame}
+
+ result = json.loads(
+ run_paper_trade_step(
+ {
+ "account_id": "finite-prices",
+ "market": "us",
+ "account_state": {
+ "cash": 1000,
+ "positions": [{"symbol": "AAPL", "qty": 1, "avg_cost": 80}],
+ },
+ "from_date": "2026-10-20",
+ "to_date": "2026-10-20",
+ "orders": [{"symbol": "AAPL", "side": "sell", "qty": 1}],
+ },
+ loader=Loader(),
+ ch_client=None,
+ calendar_client=None,
+ limits_client=None,
+ )
+ )
+ assert result["fills"] == []
+ assert result["rejected_orders"][0]["reason_code"] == "suspended"
+ assert result["end_state"]["cash"] == 1000
+ assert result["nav_series"][0]["nav"] == 1100
+ json.dumps(result, allow_nan=False)
diff --git a/agent/tests/test_paper_trade_perf.py b/agent/tests/test_paper_trade_perf.py
new file mode 100644
index 000000000..22fd8fb18
--- /dev/null
+++ b/agent/tests/test_paper_trade_perf.py
@@ -0,0 +1,217 @@
+"""T8 gate — paper-trade performance budget (REQUIREMENTS §7 T8, plan §T8).
+
+Budgets (fixture environment; live-network latency is out of scope — the RM
+E2E measures that separately):
+
+* single day, single account, 10 positions + 10 orders: < 60s;
+* 5-trading-day catch-up: < 300s in BOTH accepted forms — five sequential
+ orders-mode single-day calls threading ``end_state`` → ``account_state``
+ (AM-3/RM-2), AND one strategy_path call spanning the five days. The
+ strategy form runs the REAL executor: one spawned child per call (~4s
+ startup) inside the budget — never faked (plan §T8).
+
+Deterministic and offline: injected fake loaders serve synthetic flat frames
+(zero network — the ``--disable-socket`` hard gate covers this file), every
+date is injected, the tool reads no clock. Budgets are asserted with
+``time.perf_counter()``, never merely printed. All tests carry the
+registered ``slow`` marker (pyproject.toml): optional to select via ``-m
+slow``, mandatory at the delivery gate, re-run quarterly against rot.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.config.paths import get_runtime_root
+from src.tools.paper_trade.tool import run_paper_trade_step
+
+pytestmark = pytest.mark.slow
+
+_SINGLE_DAY_BUDGET_S = 60.0
+_CATCHUP_BUDGET_S = 300.0
+
+_MARKET = "us"
+_ACCOUNT = "pa_perf"
+_SYM = "PERF-00.US"
+_SYMBOLS = tuple(f"PERF-{i:02d}.US" for i in range(10))
+
+# Five consecutive trading days (Mon..Fri, us zero-calendar: served bars on
+# every weekday make all five matching days — no market_closed_inferred skip).
+_CATCHUP_DAYS = ("2026-03-02", "2026-03-03", "2026-03-04", "2026-03-05", "2026-03-06")
+_SINGLE_DAY = _CATCHUP_DAYS[-1]
+
+# §4 us default fee matrix, injected explicitly (AM-4-3). Every scheduled
+# qty prices at flat 100.0, so each fee = max(qty×0.0049, 0.99) = 0.99.
+_FEE_MODEL = {"commission_per_share": 0.0049, "commission_min": 0.99, "sec_fee_rate": 0.0}
+
+# The 5-day order schedule, shared by BOTH catch-up forms so they exercise
+# identical matching work: buy 100 / sell 40 / buy 60 / sell 20 / sell 100.
+_SCHEDULE = (
+ [{"symbol": _SYM, "side": "buy", "qty": 100}],
+ [{"symbol": _SYM, "side": "sell", "qty": 40}],
+ [{"symbol": _SYM, "side": "buy", "qty": 60}],
+ [{"symbol": _SYM, "side": "sell", "qty": 20}],
+ [{"symbol": _SYM, "side": "sell", "qty": 100}],
+)
+_FINAL_CASH = 99995.05 # 100000 −10000.99 +3999.01 −6000.99 +1999.01 +9999.01
+
+
+class FakeLoader:
+ """Fixture-environment network leg: serves pre-built frames, zero I/O."""
+
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "sina") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+def _flat_frames(symbols: tuple[str, ...], end_day: str, *, bars: int = 130) -> dict[str, pd.DataFrame]:
+ """Per-symbol flat 100.0 frame: ``bars`` business days ending ``end_day``.
+
+ Flat closes keep the T4 detector silent (close-to-close ratio 1.0 — no
+ clean split ratio, no unresolved discontinuity) and cover the frozen
+ K=120 lookback window (VD-6/B3), mirroring the production fetch shape.
+ """
+ days = pd.bdate_range(end=end_day, periods=bars)
+ frame = pd.DataFrame(
+ {"trade_date": days, "open": 100.0, "high": 100.0, "low": 100.0,
+ "close": 100.0, "volume": 10000.0}
+ ).set_index("trade_date")
+ return {symbol: frame for symbol in symbols}
+
+
+def _payload(**overrides) -> dict:
+ base = {
+ "account_id": _ACCOUNT,
+ "market": _MARKET,
+ "account_state": {"cash": 100000.0, "positions": []},
+ "from_date": _SINGLE_DAY,
+ "to_date": _SINGLE_DAY,
+ "fee_model": dict(_FEE_MODEL),
+ }
+ base.update(overrides)
+ return base
+
+
+def test_single_day_ten_positions_ten_orders_under_budget() -> None:
+ # T8 gate form 1: single day, single account, ≤10 positions + ≤10 orders.
+ payload = _payload(
+ account_state={
+ "cash": 1000000.0,
+ "positions": [{"symbol": s, "qty": 100, "avg_cost": 100.0} for s in _SYMBOLS],
+ },
+ orders=[{"symbol": s, "side": "sell", "qty": 50} for s in _SYMBOLS],
+ )
+ loader = FakeLoader(_flat_frames(_SYMBOLS, _SINGLE_DAY))
+
+ started = time.perf_counter()
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+ elapsed = time.perf_counter() - started
+
+ assert elapsed < _SINGLE_DAY_BUDGET_S, (
+ f"single-day step took {elapsed:.2f}s, budget {_SINGLE_DAY_BUDGET_S}s")
+ assert "status" not in doc, doc # success document, not an error envelope
+ assert len(doc["fills"]) == 10
+ assert all(f["side"] == "sell" and f["qty"] == 50.0 and f["price"] == 100.0
+ for f in doc["fills"])
+ # 1000000 + 10×(50×100.0 − 0.99); every position keeps 50 shares.
+ assert doc["end_state"]["cash"] == 1049990.1
+ assert sorted(p["qty"] for p in doc["end_state"]["positions"]) == [50.0] * 10
+
+
+def test_five_day_orders_catchup_under_budget() -> None:
+ # T8 gate form 2a: five sequential single-day orders-mode calls (AM-3),
+ # threading day k−1's end_state into day k's account_state (RM-2) over
+ # the JSON wire shape — the mechanical catch-up RM performs.
+ loader = FakeLoader(_flat_frames((_SYM,), _CATCHUP_DAYS[-1]))
+ state: dict = {"cash": 100000.0, "positions": []}
+ docs: list[dict] = []
+
+ started = time.perf_counter()
+ for day, orders in zip(_CATCHUP_DAYS, _SCHEDULE, strict=True):
+ doc = json.loads(run_paper_trade_step(
+ _payload(account_state=state, orders=orders, from_date=day, to_date=day),
+ loader=loader))
+ assert "status" not in doc, doc
+ docs.append(doc)
+ state = {
+ "cash": doc["end_state"]["cash"],
+ "positions": [dict(p) for p in doc["end_state"]["positions"]],
+ }
+ elapsed = time.perf_counter() - started
+
+ assert elapsed < _CATCHUP_BUDGET_S, (
+ f"5-day orders catch-up took {elapsed:.2f}s, budget {_CATCHUP_BUDGET_S}s")
+ assert [len(doc["fills"]) for doc in docs] == [1, 1, 1, 1, 1]
+ assert [doc["range"]["from"] for doc in docs] == list(_CATCHUP_DAYS)
+ assert docs[-1]["end_state"]["cash"] == _FINAL_CASH
+ assert docs[-1]["end_state"]["positions"] == []
+
+
+_STRATEGY_SOURCE = '''"""Date-keyed 5-day schedule strategy (T8 perf gate, strategy_path form)."""
+
+UNIVERSE = ("PERF-00.US",)
+
+_SCHEDULE = {
+ "2026-03-02": [{"symbol": "PERF-00.US", "side": "buy", "qty": 100, "reason": "perf d1"}],
+ "2026-03-03": [{"symbol": "PERF-00.US", "side": "sell", "qty": 40, "reason": "perf d2"}],
+ "2026-03-04": [{"symbol": "PERF-00.US", "side": "buy", "qty": 60, "reason": "perf d3"}],
+ "2026-03-05": [{"symbol": "PERF-00.US", "side": "sell", "qty": 20, "reason": "perf d4"}],
+ "2026-03-06": [{"symbol": "PERF-00.US", "side": "sell", "qty": 100, "reason": "perf d5"}],
+}
+
+
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ return _SCHEDULE.get(trade_date, [])
+'''
+
+
+def test_five_day_strategy_path_single_call_under_budget() -> None:
+ # T8 gate form 2b: ONE strategy_path call over the five trading days.
+ # The real T7 executor runs — one spawned child (~4s startup) inside the
+ # budget. The declared UNIVERSE prefetches the cash-only account's
+ # symbol (T6×T7 integration convention).
+ root = get_runtime_root() / "strategies"
+ root.mkdir(parents=True, exist_ok=True)
+ strategy = root / "perf_schedule_5day.py"
+ strategy.write_text(_STRATEGY_SOURCE, encoding="utf-8")
+
+ loader = FakeLoader(_flat_frames((_SYM,), _CATCHUP_DAYS[-1]))
+ payload = _payload(
+ strategy_path=str(strategy),
+ from_date=_CATCHUP_DAYS[0], to_date=_CATCHUP_DAYS[-1],
+ )
+
+ started = time.perf_counter()
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+ elapsed = time.perf_counter() - started
+
+ assert elapsed < _CATCHUP_BUDGET_S, (
+ f"5-day strategy_path call took {elapsed:.2f}s, budget {_CATCHUP_BUDGET_S}s")
+ assert "status" not in doc, doc
+ assert [f["trade_date"] for f in doc["fills"]] == list(_CATCHUP_DAYS)
+ assert [f["reason"] for f in doc["fills"]] == [
+ "perf d1", "perf d2", "perf d3", "perf d4", "perf d5"]
+ assert len(doc["nav_series"]) == 5
+ assert doc["end_state"]["cash"] == _FINAL_CASH
+ assert doc["end_state"]["positions"] == []
+
+
+def test_strategy_file_resides_in_the_fixture_sandbox() -> None:
+ # Guard for the perf form 2b prerequisite: the runtime root is the
+ # conftest-sandboxed ~/.vibe-trading (VIBE_TRADING_HOME popped, HOME
+ # redirected), never the user's real home.
+ assert Path(get_runtime_root()).is_relative_to(Path.home())
+ assert get_runtime_root().name == ".vibe-trading"
+ assert "vibe-trading-test-home-" in str(Path.home())
diff --git a/agent/tests/test_paper_trade_production_caliber.py b/agent/tests/test_paper_trade_production_caliber.py
new file mode 100644
index 000000000..8135e911f
--- /dev/null
+++ b/agent/tests/test_paper_trade_production_caliber.py
@@ -0,0 +1,82 @@
+"""Production loader resolution must not silently reprice a cash ledger."""
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade import data
+
+
+ "market,source,adjustment,accepted",
+ [
+ ("us", "yfinance", None, False),
+ ("us", "sina", None, True),
+ ("hk", "tencent", None, True),
+ ("hk", "tencent", "split_dividend", False),
+ ("us", "unverified", None, False),
+ ("cn_a", "tencent", "split_dividend", False),
+ ],
+)
+def test_resolved_loader_requires_raw_prices(
+ monkeypatch, market, source, adjustment, accepted
+):
+ frame = pd.DataFrame(
+ {
+ "open": [100.0],
+ "high": [100.0],
+ "low": [100.0],
+ "close": [100.0],
+ "volume": [1000.0],
+ },
+ index=pd.to_datetime(["2026-10-20"]),
+ )
+ if adjustment:
+ frame.attrs["adjustment"] = adjustment
+
+ class Loader:
+ name = source
+
+ def fetch(self, *args, **kwargs):
+ return {"TEST": frame}
+
+ monkeypatch.setattr(data, "_resolve_network_loader", lambda *a, **kw: Loader())
+ result = data.fetch_market_data(
+ market,
+ ("TEST",),
+ "2026-10-20",
+ "2026-10-20",
+ ch_client=None,
+ )
+ assert data.assess_readiness(result, "2026-10-20").ready is accepted
+ if not accepted:
+ assert any("requires raw prices" in warning for warning in result.warnings)
+
+
+def test_tencent_execution_adapter_reads_only_the_raw_endpoint(monkeypatch):
+ from backtest.loaders.tencent_loader import DataLoader
+ from src.tools.paper_trade.raw_loader import TencentRawLoader
+ calls = []
+
+ def fetch(self, code, start, end, forward_adjusted=True):
+ calls.append(forward_adjusted)
+ return pd.DataFrame({"close": [11.]}, index=pd.to_datetime(["2026-10-20"]))
+
+ monkeypatch.setattr(DataLoader, "_fetch_one", fetch)
+ frame = TencentRawLoader().fetch(["000001.SZ"], "2026-10-19", "2026-10-20")["000001.SZ"]
+ assert calls == [False]
+ assert frame.attrs["adjustment"] == "raw"
+
+
+def test_missing_calendar_is_retryable_not_a_closed_day():
+ import json
+ from src.tools.paper_trade.tool import run_paper_trade_step
+
+ class IncompleteCalendar:
+ def get_trade_calendar(self, *args):
+ return pd.DataFrame(columns=["cal_date", "is_open"])
+
+ document = json.loads(run_paper_trade_step({"account_id": "a", "market": "cn_a",
+ "account_state": {"cash": 1000}, "from_date": "2026-10-20", "to_date": "2026-10-20", "orders": []},
+ calendar_client=IncompleteCalendar(), limits_client=None, ch_client=None, loader=None))
+ assert document["code"] == "PAPER_DATA_NOT_READY"
+ assert "incomplete" in document["message"]
diff --git a/agent/tests/test_paper_trade_purity.py b/agent/tests/test_paper_trade_purity.py
new file mode 100644
index 000000000..1a8612d3e
--- /dev/null
+++ b/agent/tests/test_paper_trade_purity.py
@@ -0,0 +1,312 @@
+"""T9 gate — zero side effects / zero credentials / zero live connectors + G1 ledger closure.
+
+Four surfaces (plan §T8, REQUIREMENTS §7 T9, §9 red lines):
+
+1. FILE-TREE PURITY (dynamic): real ``run_paper_trade_step`` calls — orders
+ mode (us single-leg AND the cn_a federated path) and strategy_path mode
+ (real spawned child) — leave the sandboxed runtime root
+ (``get_runtime_root()``, the conftest-redirected ``~/.vibe-trading``) and
+ a controlled cwd byte-identical: same relative paths, same content
+ sha256, nothing created or deleted (directories and symlinks included).
+2. ZERO CREDENTIALS (static): the paper-trade source surface performs no
+ direct environment read and names no RM credential constant/env name.
+ The ONLY sanctioned secret path is the pre-existing ``CLICKHOUSE_*`` env
+ config (``acs_ro`` read-only user, REQUIREMENTS §3-6) consumed through
+ the EXISTING ``get_env_config()``/``ClickHouseConnector`` layer — the
+ lowercase ``cfg.clickhouse_*`` attribute reads in data.py are that path,
+ not an RM credential surface, and no module here reads env itself.
+3. ZERO LIVE CONNECTORS (static): no scoped ``trading_*`` connector call
+ surface and no order-placement verb anywhere in the package. The scan
+ is the SCOPED regex — a bare ``trading_`` grep is a KNOWN FALSE RED:
+ the frozen pt-v1.1 vocabulary (``non_trading_day``/``trading_day``) and
+ the calendar helpers (``is_trading_day``/``trading_days_in_range``) are
+ contract words, never connector calls, and must not be "fixed".
+4. G1 LEDGER CLOSED (static): zero residual STEP1 ledger markers across the
+ ledger scan surface (package source, ``agent/tests``, the pt-v1.1
+ contract JSON). The marker literal is assembled by a runtime join, so
+ this file — source AND compiled ``.pyc`` constant table — never contains
+ it and the scan never self-matches (CPython constant-folds a plain
+ ``"a" + "b"`` BinOp into the code object; ``"".join`` cannot be folded).
+
+Offline: injected fake loaders/clients, zero network (``--disable-socket``
+hard gate). The strategy child spawns through ``multiprocessing`` pipes —
+POSIX socketpair at the C layer, which pytest-socket does not intercept.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.config.paths import get_runtime_root
+from src.tools.paper_trade import tool as tool_module
+from src.tools.paper_trade.tool import run_paper_trade_step
+
+_PACKAGE_DIR = Path(tool_module.__file__).resolve().parent
+_TESTS_DIR = Path(__file__).resolve().parent
+_CONTRACT_JSON = _TESTS_DIR.parents[1] / "schema" / "tool_contracts" / "paper_trade_step-v1.1.json"
+
+# Runtime-assembled so the contiguous literal exists in neither this file's
+# source nor its .pyc (see module docstring §4) — the acceptance grep over
+# agent/tests/ must not self-match on the scanner itself.
+_LEDGER_MARKER = "".join(("TODO-", "G1"))
+
+_US_DAY = "2026-03-06" # Friday
+_CN_A_DAY = "2026-03-06"
+_CN_A_PREV = "2026-03-05"
+_US_FEES = {"commission_per_share": 0.0049, "commission_min": 0.99, "sec_fee_rate": 0.0}
+_CN_A_FEES = {
+ "commission_rate": 0.00025, "commission_min": 5.0,
+ "stamp_tax_sell": 0.0005, "transfer_fee": 0.00001,
+}
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "sina") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+class FakeChClient:
+ def __init__(self, frames: dict[str, pd.DataFrame]) -> None:
+ self._frames = frames
+
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ return self._frames.get(ts_code, pd.DataFrame())
+
+
+class FakeCalendarClient:
+ def __init__(self, open_days: tuple[str, ...]) -> None:
+ self._open = set(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 _frame(day: str, close: float) -> pd.DataFrame:
+ record = {"trade_date": day, "open": close, "high": close, "low": close,
+ "close": close, "volume": 1000.0}
+ frame = pd.DataFrame([record])
+ frame["trade_date"] = pd.to_datetime(frame["trade_date"])
+ return frame.set_index("trade_date")
+
+
+def _snapshot_tree(root: Path) -> dict[str, str]:
+ """Byte-level tree snapshot: relative path → sha256 (file) / "dir" / link target.
+
+ Directories are recorded so a created/removed EMPTY directory is a diff;
+ symlinks are recorded by target (never followed into foreign trees).
+ """
+ tree: dict[str, str] = {}
+ if not root.exists():
+ return tree
+ for path in sorted(root.rglob("*")):
+ rel = path.relative_to(root).as_posix()
+ if path.is_symlink():
+ tree[rel] = f"link:{path.readlink().as_posix()}"
+ elif path.is_dir():
+ tree[rel] = "dir"
+ elif path.is_file():
+ tree[rel] = hashlib.sha256(path.read_bytes()).hexdigest()
+ return tree
+
+
+def controlled_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """chdir into a seeded sentinel directory and return it for snapshotting."""
+ (tmp_path / "sentinel.txt").write_text("paper-trade purity sentinel\n", encoding="utf-8")
+ (tmp_path / "nested").mkdir()
+ (tmp_path / "nested" / "data.json").write_text('{"untouched": true}\n', encoding="utf-8")
+ monkeypatch.chdir(tmp_path)
+ return tmp_path
+
+
+def _assert_trees_frozen(runtime_before: dict[str, str], cwd_before: dict[str, str],
+ cwd: Path) -> None:
+ assert _snapshot_tree(get_runtime_root()) == runtime_before
+ assert _snapshot_tree(cwd) == cwd_before
+
+
+# ── 1. file-tree purity (dynamic, real tool calls) ──
+
+
+def test_orders_mode_us_leaves_runtime_root_and_cwd_byte_identical(controlled_cwd: Path) -> None:
+ payload = {
+ "account_id": "pa_purity", "market": "us",
+ "account_state": {"cash": 50000.0, "positions": []},
+ "orders": [{"symbol": "PUR.US", "side": "buy", "qty": 10}],
+ "from_date": _US_DAY, "to_date": _US_DAY, "fee_model": dict(_US_FEES),
+ }
+ loader = FakeLoader({"PUR.US": _frame(_US_DAY, 100.0)})
+ runtime_before = _snapshot_tree(get_runtime_root())
+ cwd_before = _snapshot_tree(controlled_cwd)
+
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+
+ assert "status" not in doc, doc # the guarded call really succeeded
+ assert doc["fills"][0]["fee"] == 0.99
+ _assert_trees_frozen(runtime_before, cwd_before, controlled_cwd)
+
+
+def test_orders_mode_cn_a_federated_leaves_runtime_root_and_cwd_byte_identical(
+ controlled_cwd: Path,
+) -> None:
+ # The cn_a two-leg federation (AM-9) with every seam injected: no
+ # ClickHouse connector is built, no env config is read, nothing writes.
+ payload = {
+ "account_id": "pa_purity", "market": "cn_a",
+ "account_state": {"cash": 200000.0, "positions": []},
+ "orders": [{"symbol": "600519.SH", "side": "buy", "qty": 100}],
+ "from_date": _CN_A_DAY, "to_date": _CN_A_DAY, "fee_model": dict(_CN_A_FEES),
+ }
+ loader = FakeLoader({"600519.SH": _frame(_CN_A_DAY, 1421.0)}, "tencent")
+ ch_client = FakeChClient({"600519.SH": _frame(_CN_A_PREV, 1418.0)})
+ calendar_client = FakeCalendarClient((_CN_A_DAY,))
+ runtime_before = _snapshot_tree(get_runtime_root())
+ cwd_before = _snapshot_tree(controlled_cwd)
+
+ doc = json.loads(run_paper_trade_step(
+ payload, loader=loader, ch_client=ch_client,
+ calendar_client=calendar_client, limits_client=None))
+
+ assert "status" not in doc, doc
+ assert doc["fills"][0]["fee"] == 36.95 # the cn_a golden cents
+ assert doc["data_provenance"]["source"] == "clickhouse+tencent(merged)"
+ _assert_trees_frozen(runtime_before, cwd_before, controlled_cwd)
+
+
+_STRATEGY_SOURCE = '''"""Purity probe strategy: one buy, zero I/O."""
+
+UNIVERSE = ("PUR.US",)
+
+
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ return [{"symbol": "PUR.US", "side": "buy", "qty": 10, "reason": "purity probe"}]
+'''
+
+
+def test_strategy_path_mode_leaves_runtime_root_and_cwd_byte_identical(controlled_cwd: Path) -> None:
+ # The strategy install is SETUP and happens BEFORE the snapshot: the
+ # guarded surface is the tool call (which spawns the real T7 child),
+ # not the test's own fixture writes.
+ root = get_runtime_root() / "strategies"
+ root.mkdir(parents=True, exist_ok=True)
+ strategy = root / "purity_probe.py"
+ strategy.write_text(_STRATEGY_SOURCE, encoding="utf-8")
+
+ payload = {
+ "account_id": "pa_purity", "market": "us",
+ "account_state": {"cash": 50000.0, "positions": []},
+ "strategy_path": str(strategy),
+ "from_date": _US_DAY, "to_date": _US_DAY, "fee_model": dict(_US_FEES),
+ }
+ loader = FakeLoader({"PUR.US": _frame(_US_DAY, 100.0)})
+ runtime_before = _snapshot_tree(get_runtime_root())
+ cwd_before = _snapshot_tree(controlled_cwd)
+
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+
+ assert "status" not in doc, doc
+ assert [f["reason"] for f in doc["fills"]] == ["purity probe"]
+ _assert_trees_frozen(runtime_before, cwd_before, controlled_cwd)
+
+
+# ── 2/3. zero credentials, zero live connectors (static source scans) ──
+
+
+def _package_sources() -> list[Path]:
+ return sorted(
+ path for path in _PACKAGE_DIR.rglob("*.py") if "__pycache__" not in path.parts
+ )
+
+
+def _scan(pattern: re.Pattern[str], paths: list[Path]) -> list[str]:
+ hits: list[str] = []
+ for path in paths:
+ text = path.read_text(encoding="utf-8")
+ for match in pattern.finditer(text):
+ line = text.count("\n", 0, match.start()) + 1
+ hits.append(f"{path.name}:{line}:{match.group(0)}")
+ return hits
+
+
+def test_source_surface_reads_no_environment_and_names_no_rm_credentials() -> None:
+ # Zero-credential red line (REQUIREMENTS §3-6/§9): the package itself
+ # never reads env and never names a credential constant. Uppercase
+ # CLICKHOUSE_* env names are included: even the sanctioned acs_ro secret
+ # must flow through the pre-existing config layer (lowercase cfg.*
+ # attribute reads in data.py), never a direct env read in this package.
+ env_read = re.compile(r"os\.environ|os\.getenv|environ\.get\(")
+ credential = re.compile(
+ r"API_KEY|SECRET|PASSWORD|PASSWD|PRIVATE_KEY|ACCESS_KEY|CREDENTIAL"
+ r"|BEARER|KEYRING|AUTH_TOKEN|RM_TOKEN|RM_API|RM_SECRET|RM_KEY"
+ r"|CLICKHOUSE_USER|CLICKHOUSE_PASSWORD|CLICKHOUSE_HOST|CLICKHOUSE_LLM"
+ )
+ sources = _package_sources()
+ assert sources, "the paper_trade package must contain source files"
+ assert _scan(env_read, sources) == []
+ assert _scan(credential, sources) == []
+
+
+def test_source_surface_calls_no_live_trading_connector() -> None:
+ # Zero-live red line (REQUIREMENTS R1/§9), package-wide: the SCOPED
+ # connector regex (a bare "trading_" grep false-reds on the frozen
+ # non_trading_day/trading_day vocabulary — see module docstring §3),
+ # plus the order-placement verbs and the broker-layer import root.
+ scoped = re.compile(
+ r"trading_(account|orders|positions|quote|history|check|connections|select|place|cancel)"
+ )
+ broker_surface = re.compile(r"place_order|cancel_order|src\.trading")
+ sources = _package_sources()
+ assert _scan(scoped, sources) == []
+ assert _scan(broker_surface, sources) == []
+
+
+# ── 4. G1 ledger closure (static scan) ──
+
+
+def _ledger_scan_surface() -> list[Path]:
+ # Mirrors the plan's acceptance grep surface (package source +
+ # agent/tests + the contract JSON), restricted to TEXT files with
+ # __pycache__ excluded — binary .pyc hits are the known grep pitfall,
+ # and comments never compile into .pyc anyway.
+ text_files = [
+ path
+ for root in (_PACKAGE_DIR, _TESTS_DIR)
+ for path in root.rglob("*")
+ if path.suffix in {".py", ".json"} and path.is_file() and "__pycache__" not in path.parts
+ ]
+ return [*sorted(text_files), _CONTRACT_JSON]
+
+
+def test_g1_ledger_has_zero_residual_markers() -> None:
+ # STEP1 ledger closure (18 markers / 8 files): each task removed its own
+ # surface at the frozen pt-v1.1 value (T2 calendar×2, T5 schema×5 +
+ # state_hash×3 + contract JSON×4 + tests×2, T6 __init__×1, T8
+ # limits_cn_a×1 — the provenance token comment, now FROZEN). Zero
+ # residual anywhere on the ledger surface.
+ surface = _ledger_scan_surface()
+ assert _CONTRACT_JSON in surface
+ assert len(surface) > 20, "scan surface must cover the package, the tests and the contract"
+ hits = [
+ str(path) for path in surface
+ if _LEDGER_MARKER in path.read_text(encoding="utf-8")
+ ]
+ assert hits == []
diff --git a/agent/tests/test_paper_trade_readiness.py b/agent/tests/test_paper_trade_readiness.py
new file mode 100644
index 000000000..e8202877d
--- /dev/null
+++ b/agent/tests/test_paper_trade_readiness.py
@@ -0,0 +1,418 @@
+"""T5-gate readiness tests for the paper_trade data layer (Step 2 / T2).
+
+Offline by construction: every fetch injects a fake CH bar client and a fake
+network loader, so no test resolves the real registry chain or touches the
+network (``--disable-socket`` is a hard gate). Contract anchors:
+
+* AM-9 — readiness is judged on the FEDERATED MERGED frame: CH missing the
+ target day while the network leg serves it ⇒ READY (judging on the CH frame
+ alone would false-alarm every trading day); both legs missing ⇒ in-band
+ ``PAPER_DATA_NOT_READY`` material (never an exception).
+* AM-6 — hk/us zero-calendar three-state matrix: target-day all-market zero
+ bar ⇒ not_ready; mid-range all-market zero bar ⇒ ``market_closed_inferred``
+ + warning (NOT a failure, never silently ``non_trading_day``); single-symbol
+ zero bar ⇒ suspended fact + carry-forward valuation.
+* R-V3 — non-positive OHLC bars flag the symbol-day untradable + structured
+ warning, no crash.
+* VD-6/B3 — K=120 lookback trim; VD-10 — sorted symbols, frozen order.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade import data as data_layer
+from src.tools.paper_trade.calendar import (
+ VERDICT_MARKET_CLOSED_INFERRED,
+ VERDICT_NOT_READY,
+ VERDICT_TRADING_DAY,
+ classify_zero_calendar_day,
+ hk_us_candidate_days,
+)
+from src.tools.paper_trade.data import (
+ LOOKBACK_TRADING_DAYS,
+ assess_readiness,
+ day_bar_availability,
+ fetch_market_data,
+ symbols_for_request,
+)
+from src.tools.paper_trade.schema import (
+ ERROR_CODES,
+ SKIPPED_DAY_REASONS,
+ AccountState,
+ DateRange,
+ ErrorEnvelope,
+ Order,
+ Position,
+)
+
+_FIXTURE_DIR = Path(__file__).parent / "fixtures" / "paper_trade" / "market"
+
+
+class FakeChClient:
+ """Recorded CH bar leg; captures requested ranges."""
+
+ def __init__(self, frames: dict[str, pd.DataFrame]) -> None:
+ self._frames = frames
+ self.calls: list[tuple[str, str, str]] = []
+
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ self.calls.append((ts_code, start_date, end_date))
+ return self._frames.get(ts_code, pd.DataFrame())
+
+
+class FakeLoader:
+ """Recorded network leg speaking the DataLoaderProtocol fetch shape."""
+
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "tencent") -> None:
+ self.name = name
+ self._frames = frames
+ self.calls: list[tuple[list[str], str, str, str]] = []
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(
+ self,
+ codes: list[str],
+ start_date: str,
+ end_date: str,
+ *,
+ interval: str = "1D",
+ fields: list[str] | None = None,
+ ) -> dict[str, pd.DataFrame]:
+ self.calls.append((list(codes), start_date, end_date, interval))
+ return {code: self._frames[code] for code in codes if code in self._frames}
+
+
+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 _fixture_frame(name: str) -> tuple[pd.DataFrame, dict]:
+ document = json.loads((_FIXTURE_DIR / name).read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]], document
+
+
+# A realistic cn_a week: CH holds Thu 10-15 / Fri 10-16 (T-1 caliber); the
+# network leg serves Mon 10-20 (the target day) after the close.
+_CH_HISTORY = _frame([("2026-10-15", 1418.0), ("2026-10-16", 1425.5)])
+_NET_TODAY = _frame([("2026-10-20", 1430.0)])
+
+
+def _fetch_cn_a(ch_frames, net_frames, symbols=("600519.SH",), **kwargs):
+ return fetch_market_data(
+ "cn_a",
+ list(symbols),
+ kwargs.pop("from_date", "2026-10-20"),
+ kwargs.pop("to_date", "2026-10-20"),
+ loader=FakeLoader(net_frames, name="tencent"),
+ ch_client=FakeChClient(ch_frames),
+ **kwargs,
+ )
+
+
+# ── AM-9: cn_a federated merged-frame readiness, dual path ──
+
+
+def test_network_leg_supplies_target_day_is_ready_even_though_ch_lacks_it() -> None:
+ result = _fetch_cn_a({"600519.SH": _CH_HISTORY}, {"600519.SH": _NET_TODAY})
+
+ verdict = assess_readiness(result, "2026-10-20")
+ assert verdict.ready is True
+ assert verdict.code is None
+
+ prov = result.provenance
+ assert prov.source == "clickhouse+tencent(merged)"
+ assert prov.ch_as_of == "2026-10-16"
+ assert prov.network_as_of == "2026-10-20"
+ assert prov.bars_as_of == "2026-10-20"
+
+ merged = result.data["600519.SH"]
+ assert merged.bar_dates == frozenset({"2026-10-15", "2026-10-16", "2026-10-20"})
+ assert merged.valuation_price == 1430.0
+ assert merged.valuation_basis == "last_close"
+
+
+def test_both_legs_missing_target_day_yields_not_ready_material() -> None:
+ result = _fetch_cn_a({"600519.SH": _CH_HISTORY}, {"600519.SH": _CH_HISTORY})
+
+ verdict = assess_readiness(result, "2026-10-20")
+ assert verdict.ready is False
+ assert verdict.code == "PAPER_DATA_NOT_READY"
+ assert verdict.code in ERROR_CODES
+ assert "target bar 2026-10-20" in verdict.message
+ assert "2026-10-16" in verdict.message
+
+
+def test_not_ready_materializes_as_in_band_error_envelope() -> None:
+ result = _fetch_cn_a({"600519.SH": _CH_HISTORY}, {})
+ verdict = assess_readiness(result, "2026-10-20")
+
+ envelope = ErrorEnvelope(
+ code=verdict.code,
+ account_id="pa_x",
+ market="cn_a",
+ range=DateRange(from_="2026-10-20", to="2026-10-20"),
+ message=verdict.message,
+ )
+ assert envelope.status == "error"
+ assert envelope.code in ERROR_CODES
+ assert envelope.account_id == "pa_x"
+
+
+def test_ch_unreachable_degrades_to_network_only_and_still_ready() -> None:
+ result = fetch_market_data(
+ "cn_a",
+ ["600519.SH"],
+ "2026-10-20",
+ "2026-10-20",
+ loader=FakeLoader({"600519.SH": _NET_TODAY}, name="tencent"),
+ ch_client=None,
+ )
+ verdict = assess_readiness(result, "2026-10-20")
+ assert verdict.ready is True
+ assert result.provenance.source == "tencent"
+ assert result.provenance.ch_as_of is None
+ assert result.provenance.network_as_of == "2026-10-20"
+
+
+def test_single_symbol_missing_target_bar_is_a_suspended_fact_not_not_ready() -> None:
+ symbols = ("000001.SZ", "600519.SH")
+ result = _fetch_cn_a(
+ {"600519.SH": _CH_HISTORY},
+ {"600519.SH": _NET_TODAY},
+ symbols=symbols,
+ )
+ assert assess_readiness(result, "2026-10-20").ready is True
+ availability = day_bar_availability(result, ["2026-10-20"])
+ assert availability == {"2026-10-20": ("600519.SH",)}
+ # The zero-bar symbol values at avg_cost with a structured warning (B3).
+ missing = result.data["000001.SZ"]
+ assert missing.valuation_price is None
+ assert missing.valuation_basis == "avg_cost"
+ assert any("000001.SZ" in warning and "avg_cost" in warning for warning in result.warnings)
+
+
+def test_no_available_source_is_a_warning_and_not_ready_never_a_crash(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(data_layer, "_resolve_network_loader", lambda *_a, **_k: None)
+ result = fetch_market_data(
+ "cn_a", ["600519.SH"], "2026-10-20", "2026-10-20", ch_client=None
+ )
+ assert result.provenance.source == "unavailable"
+ assert any("no available data source" in warning for warning in result.warnings)
+ verdict = assess_readiness(result, "2026-10-20")
+ assert verdict.ready is False
+ assert verdict.code == "PAPER_DATA_NOT_READY"
+
+
+# ── AM-6: hk/us zero-calendar three-state matrix ──
+
+
+def test_mid_range_zero_bars_are_market_closed_inferred_not_a_failure() -> None:
+ frame, document = _fixture_frame("synthetic_holiday_gap.json")
+ result = fetch_market_data(
+ "us",
+ ["SYNTH-GAP"],
+ "2026-03-02",
+ "2026-04-10",
+ loader=FakeLoader({"SYNTH-GAP": frame}, name="sina"),
+ )
+ candidates = hk_us_candidate_days("2026-03-02", "2026-04-10")
+ availability = day_bar_availability(result, candidates)
+
+ for gap in document["gap_samples"]:
+ for day in gap["missing_weekdays"]:
+ verdict = classify_zero_calendar_day(
+ "us", day, is_target_day=False, symbols=("SYNTH-GAP",),
+ symbols_with_bars=availability[day],
+ )
+ assert verdict.kind == VERDICT_MARKET_CLOSED_INFERRED
+ assert verdict.kind != "non_trading_day" # never silent
+ assert verdict.kind in SKIPPED_DAY_REASONS # frozen vocabulary member
+ assert verdict.warning is not None and day in verdict.warning
+
+ # The run itself is NOT a failure: the target day is served and ready.
+ assert availability["2026-04-10"] == ("SYNTH-GAP",)
+ assert assess_readiness(result, "2026-04-10").ready is True
+ trading = classify_zero_calendar_day(
+ "us", "2026-04-10", is_target_day=True, symbols=("SYNTH-GAP",),
+ symbols_with_bars=availability["2026-04-10"],
+ )
+ assert trading.kind == VERDICT_TRADING_DAY
+ assert trading.suspended_symbols == ()
+
+
+def test_target_day_all_market_zero_bar_classifies_as_not_ready() -> None:
+ verdict = classify_zero_calendar_day(
+ "hk", "2026-10-20", is_target_day=True, symbols=("00700.HK",), symbols_with_bars=()
+ )
+ assert verdict.kind == VERDICT_NOT_READY
+ assert verdict.warning is None
+
+
+def test_single_symbol_zero_bar_on_trading_day_is_suspended_set() -> None:
+ verdict = classify_zero_calendar_day(
+ "hk", "2026-10-20", is_target_day=False,
+ symbols=("00700.HK", "09988.HK"), symbols_with_bars=("00700.HK",),
+ )
+ assert verdict.kind == VERDICT_TRADING_DAY
+ assert verdict.suspended_symbols == ("09988.HK",)
+
+
+def test_classify_refuses_cn_a_and_candidate_days_are_weekdays_only() -> None:
+ with pytest.raises(ValueError, match="hk/us only"):
+ classify_zero_calendar_day(
+ "cn_a", "2026-10-20", is_target_day=True, symbols=("600519.SH",),
+ symbols_with_bars=(),
+ )
+ assert hk_us_candidate_days("2026-10-15", "2026-10-20") == (
+ "2026-10-15", "2026-10-16", "2026-10-19", "2026-10-20",
+ )
+ with pytest.raises(ValueError):
+ hk_us_candidate_days("2026-10-20", "2026-10-15")
+
+
+def test_hk_target_day_zero_bar_through_fetch_is_not_ready() -> None:
+ result = fetch_market_data(
+ "hk",
+ ["00700.HK"],
+ "2026-10-20",
+ "2026-10-20",
+ loader=FakeLoader({"00700.HK": _CH_HISTORY}, name="tencent"),
+ )
+ verdict = assess_readiness(result, "2026-10-20")
+ assert verdict.ready is False
+ assert verdict.code == "PAPER_DATA_NOT_READY"
+ assert result.provenance.source == "tencent"
+ assert result.provenance.ch_as_of is None
+
+
+# ── R-V3 price sanity gate ──
+
+
+def test_non_positive_price_bars_flag_untradable_days_with_warning() -> None:
+ rows = [
+ ("2026-10-15", -3.5), # additive-qfq old level gone negative
+ ("2026-10-16", 0.0),
+ ("2026-10-20", 12.25),
+ ]
+ result = _fetch_cn_a({}, {"600519.SH": _frame(rows)})
+ symbol_data = result.data["600519.SH"]
+ assert symbol_data.untradable_dates == ("2026-10-15", "2026-10-16")
+ assert symbol_data.has_bar("2026-10-20")
+ assert symbol_data.valuation_price == 12.25
+ assert any("price sanity" in warning and "600519.SH" in warning for warning in result.warnings)
+ # The gate never crashes and never blocks the healthy target day.
+ assert assess_readiness(result, "2026-10-20").ready is True
+
+
+def test_all_window_closes_non_positive_falls_back_to_avg_cost() -> None:
+ result = _fetch_cn_a({}, {"600519.SH": _frame([("2026-10-20", -1.0)])})
+ symbol_data = result.data["600519.SH"]
+ assert symbol_data.valuation_price is None
+ assert symbol_data.valuation_basis == "avg_cost"
+ assert any("avg_cost" in warning for warning in result.warnings)
+
+
+# ── VD-6/B3 window freeze + VD-10 deterministic ordering ──
+
+
+def test_lookback_window_trims_to_exactly_k_trading_bars() -> None:
+ long_history = pd.DataFrame(
+ {
+ "open": 10.0, "high": 10.0, "low": 10.0, "close": 10.0, "volume": 1.0,
+ },
+ index=pd.DatetimeIndex(
+ pd.bdate_range(end="2026-10-16", periods=LOOKBACK_TRADING_DAYS + 30),
+ name="trade_date",
+ ),
+ )
+ target = _frame([("2026-10-20", 11.0)])
+ merged = pd.concat([long_history, target])
+ result = _fetch_cn_a({}, {"600519.SH": merged})
+ frame = result.data["600519.SH"].frame
+ before = frame[frame.index < pd.Timestamp("2026-10-20")]
+ assert len(before) == LOOKBACK_TRADING_DAYS
+ assert frame.index.max() == pd.Timestamp("2026-10-20")
+
+
+def test_symbols_are_sorted_before_fetch_and_frozen_in_output() -> None:
+ net = {"000001.SZ": _NET_TODAY, "300750.SZ": _NET_TODAY, "600519.SH": _NET_TODAY}
+ loader = FakeLoader(net, name="tencent")
+ result = fetch_market_data(
+ "cn_a",
+ ["600519.SH", "000001.SZ", "300750.SZ", "000001.SZ"],
+ "2026-10-20",
+ "2026-10-20",
+ loader=loader,
+ ch_client=FakeChClient({}),
+ )
+ assert result.symbols == ("000001.SZ", "300750.SZ", "600519.SH")
+ assert list(result.data) == list(result.symbols)
+ assert loader.calls[0][0] == ["000001.SZ", "300750.SZ", "600519.SH"]
+
+
+def test_symbols_for_request_is_the_sorted_union_of_positions_and_orders() -> None:
+ state = AccountState(
+ cash=1000.0,
+ positions=(Position("600519.SH", 100, 1418.0), Position("000001.SZ", 200, 10.5)),
+ )
+ orders = (Order("600519.SH", "buy", 100), Order("300750.SZ", "sell", 50))
+ assert symbols_for_request(state, orders) == ("000001.SZ", "300750.SZ", "600519.SH")
+ # Zero-order pure-valuation path.
+ assert symbols_for_request(state, None) == ("000001.SZ", "600519.SH")
+ assert symbols_for_request(AccountState(cash=1.0), ()) == ()
+
+
+def test_empty_universe_is_vacuously_ready() -> None:
+ result = fetch_market_data(
+ "cn_a", [], "2026-10-20", "2026-10-20",
+ loader=FakeLoader({}), ch_client=FakeChClient({}),
+ )
+ assert result.symbols == ()
+ assert assess_readiness(result, "2026-10-20").ready is True
+
+
+# ── Input validation + determinism ──
+
+
+def test_invalid_inputs_fail_closed_with_deterministic_messages() -> None:
+ with pytest.raises(ValueError, match="unknown market"):
+ fetch_market_data("crypto", ["BTC-USDT"], "2026-10-20", "2026-10-20")
+ with pytest.raises(ValueError, match="from_date"):
+ fetch_market_data(
+ "cn_a", ["600519.SH"], "2026-10-21", "2026-10-20",
+ loader=FakeLoader({}), ch_client=None,
+ )
+ with pytest.raises(ValueError, match="clickhouse"):
+ fetch_market_data(
+ "cn_a", ["600519.SH"], "2026-10-20", "2026-10-20",
+ loader=FakeLoader({}, name="clickhouse"), ch_client=None,
+ )
+
+
+def test_same_inputs_produce_identical_results() -> None:
+ def run():
+ return _fetch_cn_a({"600519.SH": _CH_HISTORY}, {"600519.SH": _NET_TODAY})
+
+ first, second = run(), run()
+ assert first.symbols == second.symbols
+ assert first.provenance == second.provenance
+ assert first.warnings == second.warnings
+ assert first.data["600519.SH"].bar_dates == second.data["600519.SH"].bar_dates
+ assert first.data["600519.SH"].frame.equals(second.data["600519.SH"].frame)
diff --git a/agent/tests/test_paper_trade_rejections.py b/agent/tests/test_paper_trade_rejections.py
new file mode 100644
index 000000000..adc313e3b
--- /dev/null
+++ b/agent/tests/test_paper_trade_rejections.py
@@ -0,0 +1,417 @@
+"""T3-gate negative-path matrix for the paper_trade matching engine.
+
+Covers every frozen reason_code (≥1 case each, 11 total), the AM-14
+first-match order (multi-reason orders report only the first hit), the
+t_plus_1/insufficient_position discrimination (available = total −
+bought_today), same-symbol dual orders (buy→sell rejects the sell t_plus_1;
+sell→buy both fill), the AM-6 skipped-day semantics (cn_a non_trading_day /
+hk-us market_closed_inferred + warning), the R-V3 sanity-gate mapping
+(suspended), the T4 corporate-action seam, and the no-crash / no-half-day
+invariants. Offline: fake loader / CH / calendar clients only.
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade import engine
+from src.tools.paper_trade.data import fetch_market_data
+from src.tools.paper_trade.rules import REJECTION_ORDER
+from src.tools.paper_trade.schema import REASON_CODES, AccountState, Order, 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], name: str = "tencent") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+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 _frame(rows: list[tuple[str, float]]) -> pd.DataFrame:
+ if not rows:
+ return pd.DataFrame() # served as an empty window → unknown_symbol facts
+ 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")
+
+
+# Default cn_a tape: prev close 10.0 → heuristic band 9.00..11.00; target 10.5.
+_TAPE = {_SYM: _frame([(_PREV, 10.0), (_DAY, 10.5)])}
+
+
+def _fetch_cn_a(frames: dict[str, pd.DataFrame] | None = None, symbols: list[str] | None = None,
+ from_date: str = _DAY, to_date: str = _DAY):
+ frames = _TAPE if frames is None else frames
+ symbols = symbols if symbols is not None else list(frames)
+ return fetch_market_data("cn_a", symbols, from_date, to_date,
+ loader=FakeLoader(frames), ch_client=FakeChClient())
+
+
+def _cn_a(cash=100000.0, positions=(), orders=(), frames=None, symbols=None,
+ open_days=frozenset({_DAY}), from_date=_DAY, to_date=_DAY, **kwargs):
+ market_data = _fetch_cn_a(frames, symbols, from_date, to_date)
+ request = parse_request({
+ "account_id": "pa_rej", "market": "cn_a",
+ "account_state": {"cash": cash, "positions": list(positions)},
+ "orders": list(orders), "from_date": from_date, "to_date": to_date, "fee_model": {},
+ })
+ return engine.match_orders(request, market_data=market_data,
+ calendar_client=FakeCalendarClient(open_days), **kwargs)
+
+
+def _buy(symbol=_SYM, qty=100, limit=None):
+ order = {"symbol": symbol, "side": "buy", "qty": qty}
+ if limit is not None:
+ order["limit"] = limit
+ return order
+
+
+def _sell(symbol=_SYM, qty=100, limit=None):
+ order = {"symbol": symbol, "side": "sell", "qty": qty}
+ if limit is not None:
+ order["limit"] = limit
+ return order
+
+
+def _codes(outcome) -> list[str]:
+ return [rejected.reason_code for rejected in outcome.rejected_orders]
+
+
+# ── The frozen ladder itself ──
+
+
+def test_rejection_order_constant_is_the_am14_frozen_sequence() -> None:
+ assert REJECTION_ORDER == (
+ "unknown_symbol", "non_trading_day", "suspended", "corporate_action_unresolved",
+ "lot_size", "limit_up", "limit_down", "limit_not_marketable",
+ "t_plus_1", "insufficient_position", "insufficient_cash",
+ )
+ assert len(REJECTION_ORDER) == 11
+ assert set(REJECTION_ORDER) <= set(REASON_CODES) # closed vocabulary
+
+
+# ── One case per frozen reason_code ──
+
+
+def test_unknown_symbol_when_the_window_served_no_bar_at_all() -> None:
+ outcome = _cn_a(orders=[_buy("999999.SH")], symbols=[_SYM, "999999.SH"],
+ frames={**_TAPE, "999999.SH": _frame([])})
+ assert _codes(outcome) == ["unknown_symbol"]
+ assert "999999.SH" in outcome.rejected_orders[0].detail
+ assert outcome.fills == ()
+
+
+def test_non_trading_day_skips_the_day_and_rejects_its_orders() -> None:
+ outcome = _cn_a(orders=[_buy()], open_days=frozenset()) # calendar closed
+ assert _codes(outcome) == ["non_trading_day"]
+ assert [(s.date, s.reason) for s in outcome.skipped_days] == [(_DAY, "non_trading_day")]
+ assert outcome.nav_series == () # R3: skipped days produce NO nav row
+ assert outcome.fills == ()
+ assert outcome.end_state.cash == 100000.0 # state untouched — no half-day
+
+
+def test_suspended_when_the_symbol_has_no_bar_today() -> None:
+ # Halted symbol: bar yesterday, none today; a healthy symbol still fills.
+ frames = {
+ _SYM: _TAPE[_SYM],
+ "000001.SZ": _frame([(_PREV, 10.0)]), # no target-day bar
+ }
+ outcome = _cn_a(
+ positions=[{"symbol": "000001.SZ", "qty": 100, "avg_cost": 9.5}],
+ orders=[_buy("000001.SZ"), _buy(_SYM)],
+ frames=frames, symbols=[_SYM, "000001.SZ"],
+ )
+ assert _codes(outcome) == ["suspended"]
+ assert outcome.rejected_orders[0].symbol == "000001.SZ"
+ assert [f.symbol for f in outcome.fills] == [_SYM]
+ # Carry-forward valuation: the halted position values at its last close
+ # (10.0), not avg_cost — nav = cash + 100×10.5 (filled) + 100×10.0.
+ cash = 100000.0 - 1050.0 - 5.01
+ assert outcome.nav_series[0].position_value == 100 * 10.5 + 100 * 10.0
+ assert outcome.nav_series[0].nav == pytest.approx(cash + 2050.0)
+
+
+def test_corporate_action_unresolved_through_the_injectable_t4_seam() -> None:
+ # The detector is T4; the slot + rejection channel are reserved and
+ # injectable per day (default empty ⇒ never fires).
+ outcome = _cn_a(orders=[_buy()], corporate_action_unresolved_by_day={_DAY: [_SYM]})
+ assert _codes(outcome) == ["corporate_action_unresolved"]
+ assert "fail-closed" in outcome.rejected_orders[0].detail
+ default = _cn_a(orders=[_buy()])
+ assert _codes(default) == [] and len(default.fills) == 1
+
+
+def test_lot_size_rejections_for_illegal_quantities() -> None:
+ for qty in (150, 99, 0, -100, 100.5):
+ outcome = _cn_a(orders=[_buy(qty=qty)])
+ assert _codes(outcome) == ["lot_size"], qty
+ assert "100-share" in outcome.rejected_orders[0].detail
+ assert _codes(_cn_a(orders=[_sell(qty=150)],
+ positions=[{"symbol": _SYM, "qty": 200, "avg_cost": 10.0}])) == ["lot_size"]
+
+
+def test_limit_up_rejects_a_buy_at_the_upper_band() -> None:
+ # prev 10.0 → heuristic up limit 11.00; close 11.0 = band → buy rejected.
+ frames = {_SYM: _frame([(_PREV, 10.0), (_DAY, 11.0)])}
+ outcome = _cn_a(orders=[_buy()], frames=frames)
+ assert _codes(outcome) == ["limit_up"]
+ assert "up limit 11.00" in outcome.rejected_orders[0].detail
+
+
+def test_limit_down_rejects_a_sell_at_the_lower_band() -> None:
+ # prev 10.0 → down limit 9.00; close 9.0 = band → sell rejected.
+ frames = {_SYM: _frame([(_PREV, 10.0), (_DAY, 9.0)])}
+ outcome = _cn_a(positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}],
+ orders=[_sell()], frames=frames)
+ assert _codes(outcome) == ["limit_down"]
+ assert "down limit 9.00" in outcome.rejected_orders[0].detail
+
+
+def test_limit_not_marketable_rejects_a_buy_above_the_limit() -> None:
+ outcome = _cn_a(orders=[_buy(limit=10.0)]) # close 10.5 > limit 10.0
+ assert _codes(outcome) == ["limit_not_marketable"]
+ assert outcome.rejected_orders[0].detail == "close 10.50 > limit 10.00"
+
+
+def test_t_plus_1_rejects_selling_shares_bought_the_same_day() -> None:
+ outcome = _cn_a(orders=[_buy(), _sell()]) # buy fills first (VD-10 order)
+ assert [f.side for f in outcome.fills] == ["buy"]
+ assert _codes(outcome) == ["t_plus_1"]
+ assert "T+1" in outcome.rejected_orders[0].detail
+
+
+def test_insufficient_position_when_qty_exceeds_the_total_holding() -> None:
+ outcome = _cn_a(positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}],
+ orders=[_sell(qty=200)])
+ assert _codes(outcome) == ["insufficient_position"]
+ outcome_empty = _cn_a(orders=[_sell(qty=100)]) # no position at all
+ assert _codes(outcome_empty) == ["insufficient_position"]
+
+
+def test_insufficient_cash_when_cost_exceeds_cash() -> None:
+ # cost = 100 × 10.50 + 5.01 = 1055.01 > 100.00
+ outcome = _cn_a(cash=100.0, orders=[_buy()])
+ assert _codes(outcome) == ["insufficient_cash"]
+ assert "exceeds cash" in outcome.rejected_orders[0].detail
+ assert outcome.end_state.cash == 100.0
+
+
+# ── t_plus_1 vs insufficient_position discrimination (AM-14 note) ──
+
+
+def test_discrimination_total_vs_available_position() -> None:
+ held = [{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}]
+ # buy 100 today → total 200, available 100. sell 200: total ≥ qty >
+ # available → t_plus_1 (NOT insufficient_position).
+ t1 = _cn_a(positions=held, orders=[_buy(), _sell(qty=200)])
+ assert [f.side for f in t1.fills] == ["buy"]
+ assert _codes(t1) == ["t_plus_1"]
+ # sell 300: qty > total → insufficient_position.
+ ip = _cn_a(positions=held, orders=[_buy(), _sell(qty=300)])
+ assert _codes(ip) == ["insufficient_position"]
+ # sell 100: qty ≤ available → fills.
+ ok = _cn_a(positions=held, orders=[_buy(), _sell(qty=100)])
+ assert _codes(ok) == [] and [f.side for f in ok.fills] == ["buy", "sell"]
+
+
+def test_same_symbol_sell_then_buy_both_fill_on_the_same_day() -> None:
+ outcome = _cn_a(positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 10.0}],
+ orders=[_sell(), _buy()])
+ assert _codes(outcome) == []
+ assert [f.side for f in outcome.fills] == ["sell", "buy"]
+ assert outcome.end_state.positions[0].qty == 100
+
+
+# ── AM-14 first-match: multi-reason orders report ONLY the first hit ──
+
+
+def test_first_match_unknown_symbol_beats_non_trading_day() -> None:
+ outcome = _cn_a(orders=[_buy("999999.SH")], symbols=[_SYM, "999999.SH"],
+ frames={**_TAPE, "999999.SH": _frame([])}, open_days=frozenset())
+ assert _codes(outcome) == ["unknown_symbol"] # slot 1, not slot 2
+
+
+def test_first_match_suspended_beats_lot_size() -> None:
+ # The healthy _SYM bar keeps the target day ready (AM-6①); the halted
+ # symbol's order hits slot 3 (suspended) before slot 5 (lot_size).
+ frames = {**_TAPE, "000001.SZ": _frame([(_PREV, 10.0)])}
+ outcome = _cn_a(orders=[_buy("000001.SZ", qty=150)], frames=frames,
+ symbols=[_SYM, "000001.SZ"])
+ assert _codes(outcome) == ["suspended"] # slot 3, not slot 5
+
+
+def test_first_match_corporate_action_beats_lot_size_and_suspended() -> None:
+ seam = {_DAY: [_SYM, "000001.SZ"]}
+ ca_lot = _cn_a(orders=[_buy(qty=150)], corporate_action_unresolved_by_day=seam)
+ assert _codes(ca_lot) == ["corporate_action_unresolved"] # slot 4, not slot 5
+ frames = {**_TAPE, "000001.SZ": _frame([(_PREV, 10.0)])}
+ ca_susp = _cn_a(orders=[_buy("000001.SZ")], frames=frames, symbols=[_SYM, "000001.SZ"],
+ corporate_action_unresolved_by_day=seam)
+ assert _codes(ca_susp) == ["suspended"] # slot 3, not slot 4
+
+
+def test_first_match_lot_size_beats_insufficient_cash() -> None:
+ outcome = _cn_a(cash=1.0, orders=[_buy(qty=150)])
+ assert _codes(outcome) == ["lot_size"] # slot 5, not slot 10
+
+
+def test_first_match_limit_up_beats_limit_not_marketable() -> None:
+ # close 11.0 = up band AND above the 10.00 limit → limit_up wins (slot 6).
+ frames = {_SYM: _frame([(_PREV, 10.0), (_DAY, 11.0)])}
+ outcome = _cn_a(orders=[_buy(limit=10.0)], frames=frames)
+ assert _codes(outcome) == ["limit_up"]
+
+
+# ── R-V3 price sanity gate → suspended (documented mapping) ──
+
+
+def test_untradable_bar_rejects_suspended_and_values_carry_forward() -> None:
+ frames = {_SYM: _frame([(_PREV, 10.0), (_DAY, -3.5)])} # additive-qfq gone negative
+ outcome = _cn_a(positions=[{"symbol": _SYM, "qty": 100, "avg_cost": 9.0}],
+ orders=[_buy()], frames=frames)
+ assert _codes(outcome) == ["suspended"]
+ assert "price sanity gate" in outcome.rejected_orders[0].detail
+ # Valuation skips the non-positive bar: 100 × last positive close 10.0.
+ assert outcome.nav_series[0].position_value == 1000.0
+ assert any("price sanity" in w for w in outcome.warnings) # data-layer warning kept
+
+
+# ── Day-level semantics: skipped days, multi-day loop, no half-day ──
+
+
+def test_mixed_day_commits_exactly_one_nav_row_and_a_consistent_ledger() -> None:
+ outcome = _cn_a(cash=2000.0, orders=[_buy(), _buy(qty=200)]) # second: no cash
+ assert len(outcome.fills) == 1 and _codes(outcome) == ["insufficient_cash"]
+ assert len(outcome.nav_series) == 1 # per-day atomicity: one nav row
+ nav = outcome.nav_series[0]
+ # cash = 2000 − 1050.00 − 5.01 = 944.99; position 100 × 10.5 = 1050.00
+ assert nav.cash == 944.99 and nav.position_value == 1050.0
+ assert nav.nav == 1994.99
+ assert outcome.end_state.cash == nav.cash # ledger ↔ nav consistent
+
+
+def test_cn_a_multiday_loop_skips_closed_days_and_resets_t_plus_1() -> None:
+ # Mon 10-19 open, Tue 10-20 closed, Wed 10-21 open. Buy Monday, an
+ # order on the closed Tuesday rejects non_trading_day, sell Wednesday
+ # (T+1 availability resets each day; day-1 state carries into day-3).
+ frames = {_SYM: _frame([("2026-10-16", 9.9), ("2026-10-19", 10.0), ("2026-10-21", 10.2)])}
+ market_data = _fetch_cn_a(frames, [_SYM], "2026-10-19", "2026-10-21")
+ outcome = engine.run_day_loop(
+ market="cn_a",
+ account_state=AccountState(cash=100000.0),
+ from_date="2026-10-19", to_date="2026-10-21",
+ orders_by_day={
+ "2026-10-19": (Order(_SYM, "buy", 100),),
+ "2026-10-20": (Order(_SYM, "buy", 100),),
+ "2026-10-21": (Order(_SYM, "sell", 100),),
+ },
+ market_data=market_data,
+ calendar_client=FakeCalendarClient(frozenset({"2026-10-19", "2026-10-21"})),
+ )
+ assert outcome.error is None
+ assert [(s.date, s.reason) for s in outcome.skipped_days] == [("2026-10-20", "non_trading_day")]
+ assert _codes(outcome) == ["non_trading_day"]
+ assert [f.trade_date for f in outcome.fills] == ["2026-10-19", "2026-10-21"]
+ assert [n.date for n in outcome.nav_series] == ["2026-10-19", "2026-10-21"] # ascending, no skip row
+ # Monday: fee 5.01 → cash 98994.99, nav 99994.99. Wednesday: sell
+ # notional 1020.00, fee = 5 + 0.0102 + 0.51 = 5.5202 → 5.52;
+ # cash = 98994.99 + 1020.00 − 5.52 = 100009.47.
+ assert outcome.nav_series[0].nav == 99994.99
+ assert outcome.fills[1].fee == 5.52
+ assert outcome.end_state.cash == 100009.47
+ assert outcome.end_state.positions == ()
+
+
+def test_hk_mid_range_zero_bar_is_market_closed_inferred_with_warning() -> None:
+ # AM-6②: Mon/Wed served, Tue all-market zero bar → skipped
+ # market_closed_inferred + mandatory warning; NEVER non_trading_day.
+ frames = {"00700.HK": _frame([("2026-10-19", 100.0), ("2026-10-21", 102.0)])}
+ market_data = fetch_market_data("hk", ["00700.HK"], "2026-10-19", "2026-10-21",
+ loader=FakeLoader(frames))
+ outcome = engine.run_day_loop(
+ market="hk",
+ account_state=AccountState(cash=100000.0),
+ from_date="2026-10-19", to_date="2026-10-21",
+ orders_by_day={
+ "2026-10-19": (Order("00700.HK", "buy", 100),),
+ "2026-10-20": (Order("00700.HK", "buy", 100),), # defensive: rejected suspended
+ "2026-10-21": (Order("00700.HK", "sell", 100),),
+ },
+ market_data=market_data,
+ )
+ assert outcome.error is None
+ assert [(s.date, s.reason) for s in outcome.skipped_days] == [
+ ("2026-10-20", "market_closed_inferred")]
+ assert any("2026-10-20" in w and "inferred closed" in w for w in outcome.warnings)
+ assert "non_trading_day" not in {s.reason for s in outcome.skipped_days}
+ assert _codes(outcome) == ["suspended"] # the closed day's defensive order
+ # Mon buy: notional 10000, comm max(3.0, 3) = 3.00, stamp 10 → 10,
+ # levy 0.3 → fee 13.30; cash 89986.70, nav 99986.70.
+ # Wed sell: notional 10200, comm 3.06, stamp 10.2 → 10, levy 0.306 →
+ # fee 13.366 → 13.37; cash 89986.70 + 10200.00 − 13.37 = 100173.33.
+ assert outcome.fills[0].fee == 13.3 and outcome.fills[1].fee == 13.37
+ assert [n.date for n in outcome.nav_series] == ["2026-10-19", "2026-10-21"]
+ assert outcome.nav_series[0].nav == 99986.7
+ assert outcome.end_state.cash == 100173.33
+
+
+def test_hk_empty_universe_short_circuits_the_classifier_to_cash_only_navs() -> None:
+ # T2 handoff contradiction: assess_readiness treats an empty universe as
+ # vacuously ready while classify_zero_calendar_day reads it literally as
+ # all-market zero bar. A cash-only account must still get its nav rows —
+ # the engine short-circuits the classifier (success proves it: a
+ # classified target day would have failed the run).
+ market_data = fetch_market_data("hk", [], "2026-10-19", "2026-10-20",
+ loader=FakeLoader({}))
+ outcome = engine.run_day_loop(
+ market="hk", account_state=AccountState(cash=5000.0),
+ from_date="2026-10-19", to_date="2026-10-20", orders_by_day={},
+ market_data=market_data,
+ )
+ assert outcome.error is None
+ assert outcome.skipped_days == ()
+ assert [(n.date, n.nav, n.position_value) for n in outcome.nav_series] == [
+ ("2026-10-19", 5000.0, 0.0), ("2026-10-20", 5000.0, 0.0)]
+
+
+def test_target_day_all_market_zero_bar_returns_not_ready_material() -> None:
+ # AM-6①/AM-9: the in-band PAPER_DATA_NOT_READY material, never matching
+ # on stale data, never an exception.
+ frames = {_SYM: _frame([(_PREV, 10.0)])} # target day missing everywhere
+ outcome = _cn_a(orders=[_buy()], frames=frames)
+ 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 == () and outcome.rejected_orders == ()
diff --git a/agent/tests/test_paper_trade_schema.py b/agent/tests/test_paper_trade_schema.py
new file mode 100644
index 000000000..c7bd4f819
--- /dev/null
+++ b/agent/tests/test_paper_trade_schema.py
@@ -0,0 +1,567 @@
+"""T6 gate — pt-v1.1 wire-contract schema validation (Step 5 / T5).
+
+Validates the ACTUAL wire documents the Step 5 builders produce (success and
+AM-5 error envelope) through the existing dependency-free validator against
+the finalized ``schema/tool_contracts/paper_trade_step-v1.1.json``, and pins
+the frozen surfaces: ``schema_version``/``account_id`` verbatim echoes, the
+closed 11+2+2 vocabularies (every member accepted, a non-member rejected),
+the three-market ``effective_fee_model`` key sets (APPROVAL note 5), the
+``fills[].reason`` dual mode (VD-15/B2), and the AM-4-4 rule that the error
+envelope carries ``received_state_hash`` only when the state is parseable.
+
+Offline: no network, no clock, no writes.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from src.tools.paper_trade import wire
+from src.tools.paper_trade.schema import (
+ ERROR_CODES,
+ MARKETS,
+ REASON_CODES,
+ SCHEMA_VERSION,
+ SIDES,
+ SKIPPED_DAY_REASONS,
+ TOOL_NAME,
+ AccountState,
+ DataProvenance,
+ DateRange,
+ ErrorEnvelope,
+ Fill,
+ NavPoint,
+ PaperTradeSchemaError,
+ PaperTradeStepResult,
+ Position,
+ RejectedOrder,
+ SkippedDay,
+ load_contract_schema,
+ parse_account_state,
+ parse_request,
+ validate_payload,
+)
+from src.tools.paper_trade.state_hash import effective_fee_model, state_hash
+
+_GOLDEN_DIR = Path(__file__).parent / "fixtures" / "paper_trade" / "golden"
+
+# §4 terminal default key sets, frozen per APPROVAL note 5 (delivery note #7).
+_FROZEN_FEE_KEYS = {
+ "cn_a": {
+ "commission_rate": 0.00025,
+ "commission_min": 5.0,
+ "stamp_tax_sell": 0.0005,
+ "transfer_fee": 0.00001,
+ },
+ "hk": {
+ "commission_rate": 0.0003,
+ "commission_min": 3.0,
+ "stamp_tax_rate": 0.001,
+ "regulatory_levy_rate": 0.00003,
+ },
+ "us": {
+ "commission_per_share": 0.0049,
+ "commission_min": 0.99,
+ "sec_fee_rate": 0.0,
+ },
+}
+
+
+def _rich_result(**overrides) -> PaperTradeStepResult:
+ """A semantically coherent cn_a strategy_path-shaped document exercising
+ every success-schema field (multi-day range with a weekend skip)."""
+ fields: dict = dict(
+ account_id="pa_schema-echo_01",
+ market="cn_a",
+ range=DateRange(from_="2026-10-17", to="2026-10-20"),
+ received_state_hash="0" * 64,
+ effective_fee_model=dict(_FROZEN_FEE_KEYS["cn_a"]),
+ fills=(
+ Fill(trade_date="2026-10-20", symbol="600519.SH", side="buy",
+ qty=100.0, price=1421.0, fee=36.95, reason=""),
+ ),
+ rejected_orders=(
+ RejectedOrder(trade_date="2026-10-20", symbol="000001.SZ", side="sell",
+ qty=200.0, reason_code="insufficient_position",
+ detail="sell qty 200.0 exceeds position 0.0"),
+ ),
+ end_state=AccountState(
+ cash=57863.05,
+ positions=(Position(symbol="600519.SH", qty=100.0, avg_cost=1421.0),),
+ ),
+ nav_series=(
+ NavPoint(date="2026-10-20", nav=199963.05, cash=57863.05,
+ position_value=142100.0),
+ ),
+ skipped_days=(
+ SkippedDay(date="2026-10-17", reason="non_trading_day"),
+ SkippedDay(date="2026-10-18", reason="non_trading_day"),
+ ),
+ warnings=("valuation: 000001.SZ has no usable close; position valued at avg_cost",),
+ data_provenance=DataProvenance(
+ source="clickhouse+tencent(merged)",
+ bars_as_of="2026-10-20",
+ ch_as_of="2026-10-19",
+ network_as_of="2026-10-20",
+ limit_provenance=("600519.SH@2026-10-20:limits:heuristic",),
+ ),
+ )
+ fields.update(overrides)
+ return PaperTradeStepResult(**fields)
+
+
+def _rich_payload(**overrides) -> dict:
+ return wire.build_success_payload(_rich_result(**overrides))
+
+
+def _envelope(**overrides) -> ErrorEnvelope:
+ fields: dict = dict(
+ code="PAPER_DATA_NOT_READY",
+ account_id="pa_schema-echo_01",
+ market="cn_a",
+ range=DateRange(from_="2026-10-20", to="2026-10-20"),
+ message="target bar 2026-10-20 not available from served sources",
+ received_state_hash="0" * 64,
+ )
+ fields.update(overrides)
+ return ErrorEnvelope(**fields)
+
+
+# ── Success document validates through the finalized contract schema ──
+
+
+def test_rich_success_payload_validates() -> None:
+ assert validate_payload(_rich_payload(), load_contract_schema("result")) == []
+
+
+def test_corporate_actions_provenance_entry_validates() -> None:
+ payload = _rich_payload(
+ market="hk",
+ effective_fee_model=dict(_FROZEN_FEE_KEYS["hk"]),
+ data_provenance=DataProvenance(
+ source="tencent",
+ bars_as_of="2026-10-16",
+ network_as_of="2026-10-16",
+ corporate_actions=(
+ {"symbol": "00700.HK", "date": "2026-10-16", "ratio": "4:1",
+ "detected": True},
+ {"symbol": "9988.HK", "date": "2026-10-16", "ratio": "0.2531",
+ "detected": False},
+ ),
+ ),
+ )
+ assert validate_payload(payload, load_contract_schema("result")) == []
+
+
[email protected]("golden", sorted(p.name for p in _GOLDEN_DIR.glob("*_orders_*.json")))
+def test_frozen_goldens_validate_against_the_result_schema(golden: str) -> None:
+ document = json.loads((_GOLDEN_DIR / golden).read_bytes())
+ assert validate_payload(document, load_contract_schema("result")) == []
+
+
+# ── Verbatim echoes + wire key spelling ──
+
+
+def test_schema_version_and_tool_are_the_frozen_literals() -> None:
+ payload = _rich_payload()
+ assert payload["schema_version"] == SCHEMA_VERSION == "pt-v1.1"
+ assert payload["tool"] == TOOL_NAME == "paper_trade_step"
+
+
+def test_account_id_is_echoed_verbatim() -> None:
+ payload = _rich_payload(account_id="pa_verbatim-echo_42")
+ assert payload["account_id"] == "pa_verbatim-echo_42"
+ envelope_payload = wire.build_error_payload(
+ _envelope(account_id="pa_verbatim-echo_42"))
+ assert envelope_payload["account_id"] == "pa_verbatim-echo_42"
+
+
+def test_range_uses_the_wire_key_from_not_the_dataclass_spelling() -> None:
+ payload = _rich_payload()
+ assert payload["range"] == {"from": "2026-10-17", "to": "2026-10-20"}
+ assert "from_" not in json.dumps(payload)
+
+
+# ── Closed vocabularies: 11 + 2 + 2, both directions ──
+
+
+def test_vocabulary_sizes_are_frozen_at_11_2_2() -> None:
+ assert (len(REASON_CODES), len(SKIPPED_DAY_REASONS), len(ERROR_CODES)) == (11, 2, 2)
+ assert MARKETS == ("cn_a", "hk", "us")
+ assert SIDES == ("buy", "sell")
+
+
[email protected]("code", REASON_CODES)
+def test_every_frozen_reason_code_is_accepted(code: str) -> None:
+ rejected = RejectedOrder(trade_date="2026-10-20", symbol="600519.SH", side="buy",
+ qty=100.0, reason_code=code, detail="")
+ payload = _rich_payload(rejected_orders=(rejected,))
+ assert validate_payload(payload, load_contract_schema("result")) == []
+
+
[email protected]("reason", SKIPPED_DAY_REASONS)
+def test_every_frozen_skipped_reason_is_accepted(reason: str) -> None:
+ payload = _rich_payload(skipped_days=(SkippedDay(date="2026-10-17", reason=reason),))
+ assert validate_payload(payload, load_contract_schema("result")) == []
+
+
[email protected]("code", ERROR_CODES)
+def test_every_frozen_error_code_is_accepted(code: str) -> None:
+ payload = wire.build_error_payload(_envelope(code=code))
+ assert validate_payload(payload, load_contract_schema("error_envelope")) == []
+
+
+def test_out_of_vocabulary_values_are_rejected() -> None:
+ result_schema = load_contract_schema("result")
+ bad_reason = _rich_payload(rejected_orders=(
+ RejectedOrder(trade_date="2026-10-20", symbol="600519.SH", side="buy",
+ qty=100.0, reason_code="not_in_vocabulary", detail=""),))
+ assert any("not_in_vocabulary" in e for e in validate_payload(bad_reason, result_schema))
+ bad_skipped = _rich_payload(skipped_days=(SkippedDay(date="2026-10-17", reason="holiday"),))
+ assert any("holiday" in e for e in validate_payload(bad_skipped, result_schema))
+ bad_market = _rich_payload(market="crypto")
+ assert any("crypto" in e for e in validate_payload(bad_market, result_schema))
+ bad_side = _rich_payload(fills=(
+ Fill(trade_date="2026-10-20", symbol="600519.SH", side="hold",
+ qty=100.0, price=1421.0, fee=36.95, reason=""),))
+ assert any("hold" in e for e in validate_payload(bad_side, result_schema))
+
+
+def test_schema_rejects_wrong_version_missing_field_and_extra_field() -> None:
+ result_schema = load_contract_schema("result")
+ wrong_version = _rich_payload()
+ wrong_version["schema_version"] = "pt-v1.0"
+ assert any("const" in e for e in validate_payload(wrong_version, result_schema))
+ missing = _rich_payload()
+ del missing["received_state_hash"]
+ assert any("received_state_hash" in e for e in validate_payload(missing, result_schema))
+ extra = _rich_payload()
+ extra["unexpected"] = 1
+ assert any("unexpected" in e for e in validate_payload(extra, result_schema))
+ extra_prov = _rich_payload()
+ extra_prov["data_provenance"]["merge_state"] = "x"
+ assert any("merge_state" in e for e in validate_payload(extra_prov, result_schema))
+
+
+# ── effective_fee_model: three-market key echo (APPROVAL note 5) ──
+
+
[email protected]("market", sorted(_FROZEN_FEE_KEYS))
+def test_effective_fee_model_echoes_the_frozen_market_key_set(market: str) -> None:
+ assert effective_fee_model(market) == _FROZEN_FEE_KEYS[market]
+ payload = _rich_payload(
+ market=market, effective_fee_model=dict(effective_fee_model(market)))
+ assert payload["effective_fee_model"] == _FROZEN_FEE_KEYS[market]
+ assert validate_payload(payload, load_contract_schema("result")) == []
+
+
+def test_injected_fee_overrides_echo_in_full() -> None:
+ merged = effective_fee_model("cn_a", {"commission_rate": 0.0003, "custom_key": 1.5})
+ payload = _rich_payload(effective_fee_model=merged)
+ assert payload["effective_fee_model"]["commission_rate"] == 0.0003
+ assert payload["effective_fee_model"]["commission_min"] == 5.0
+ assert payload["effective_fee_model"]["custom_key"] == 1.5
+
+
+# ── fills[].reason dual mode (VD-15/B2) ──
+
+
+def test_orders_mode_reason_is_the_empty_string() -> None:
+ assert wire.ORDERS_FILL_REASON == ""
+ payload = _rich_payload()
+ assert payload["fills"][0]["reason"] == ""
+
+
+def test_strategy_reason_at_the_boundary_is_kept_whole() -> None:
+ exact = "a" * wire.FILL_REASON_MAX_CHARS
+ assert wire.strategy_fill_reason(exact) == exact
+ assert len(wire.strategy_fill_reason(exact + "b")) == wire.FILL_REASON_MAX_CHARS
+ assert wire.strategy_fill_reason(exact + "b") == exact
+
+
+def test_strategy_reason_truncation_never_splits_multibyte_characters() -> None:
+ cjk = "贵" * (wire.FILL_REASON_MAX_CHARS + 5)
+ truncated = wire.strategy_fill_reason(cjk)
+ assert len(truncated) == wire.FILL_REASON_MAX_CHARS
+ assert truncated == "贵" * wire.FILL_REASON_MAX_CHARS
+ assert truncated.encode("utf-8").decode("utf-8") == truncated
+ emoji = "👍" * (wire.FILL_REASON_MAX_CHARS + 1)
+ assert wire.strategy_fill_reason(emoji) == "👍" * wire.FILL_REASON_MAX_CHARS
+ mixed = "a" * (wire.FILL_REASON_MAX_CHARS - 1) + "€" + "tail"
+ assert wire.strategy_fill_reason(mixed) == "a" * (wire.FILL_REASON_MAX_CHARS - 1) + "€"
+
+
+def test_strategy_reason_none_maps_to_empty_and_non_str_fails_closed() -> None:
+ assert wire.strategy_fill_reason(None) == ""
+ with pytest.raises(TypeError):
+ wire.strategy_fill_reason(123) # type: ignore[arg-type]
+
+
+# ── AM-5 error envelope ──
+
+
+def test_error_envelope_validates_with_and_without_the_state_hash() -> None:
+ schema = load_contract_schema("error_envelope")
+ with_hash = wire.build_error_payload(_envelope())
+ assert validate_payload(with_hash, schema) == []
+ assert with_hash["received_state_hash"] == "0" * 64
+ without = wire.build_error_payload(_envelope(received_state_hash=None))
+ assert validate_payload(without, schema) == []
+ assert "received_state_hash" not in without # AM-4-4: omitted, never null
+ assert without["status"] == "error"
+ assert without["range"] == {"from": "2026-10-20", "to": "2026-10-20"}
+
+
+def test_error_envelope_field_set_is_exactly_the_frozen_am5_set() -> None:
+ assert set(wire.build_error_payload(_envelope())) == {
+ "status", "code", "account_id", "market", "range", "message",
+ "received_state_hash",
+ }
+ assert set(wire.build_error_payload(_envelope(received_state_hash=None))) == {
+ "status", "code", "account_id", "market", "range", "message",
+ }
+
+
+def test_unknown_error_code_and_status_fail_closed_before_serialization() -> None:
+ with pytest.raises(ValueError, match="frozen AM-5 vocabulary"):
+ wire.build_error_payload(_envelope(code="SOMETHING_ELSE"))
+ with pytest.raises(ValueError, match="status"):
+ wire.build_error_payload(_envelope(status="ok"))
+ bad = wire.build_error_payload(_envelope())
+ bad["code"] = "SOMETHING_ELSE"
+ assert validate_payload(bad, load_contract_schema("error_envelope")) != []
+ bad_status = wire.build_error_payload(_envelope())
+ bad_status["status"] = "ok"
+ assert any("const" in e
+ for e in validate_payload(bad_status, load_contract_schema("error_envelope")))
+
+
+# ── AM-4-4: received_state_hash_from_payload presence rules ──
+
+
+def _parseable_payload() -> dict:
+ return {
+ "account_id": "pa_hash_01",
+ "market": "cn_a",
+ "account_state": {"cash": 98213.44,
+ "positions": [{"symbol": "600519.SH", "qty": 100, "avg_cost": 1418.0}]},
+ "orders": [{"symbol": "600519.SH", "side": "buy", "qty": 100}],
+ "from_date": "2026-10-20",
+ "to_date": "2026-10-20",
+ "fee_model": dict(_FROZEN_FEE_KEYS["cn_a"]),
+ }
+
+
+def test_hash_is_present_and_manual_when_the_state_is_parseable() -> None:
+ payload = _parseable_payload()
+ computed = wire.received_state_hash_from_payload(payload)
+ manual = state_hash({
+ "account_id": payload["account_id"],
+ "market": payload["market"],
+ "account_state": payload["account_state"],
+ "fee_model": effective_fee_model("cn_a", payload["fee_model"]),
+ "from_date": payload["from_date"],
+ "to_date": payload["to_date"],
+ })
+ assert computed == manual
+ assert computed is not None and len(computed) == 64
+
+
+def test_hash_covers_the_raw_state_so_extra_keys_change_it() -> None:
+ payload = _parseable_payload()
+ baseline = wire.received_state_hash_from_payload(payload)
+ corrupted = _parseable_payload()
+ corrupted["account_state"]["positions"][0]["qty"] = 101
+ assert wire.received_state_hash_from_payload(corrupted) != baseline
+ enriched = _parseable_payload()
+ enriched["account_state"]["note"] = "llm-added key"
+ assert wire.received_state_hash_from_payload(enriched) != baseline
+ # int/float spelling is JCS-equivalent: 100 vs 100.0 must NOT change it.
+ respelled = _parseable_payload()
+ respelled["account_state"]["cash"] = 98213.44
+ respelled["account_state"]["positions"][0]["qty"] = 100.0
+ assert wire.received_state_hash_from_payload(respelled) == baseline
+
+
[email protected]("mutate", [
+ lambda p: p.update(account_state={"cash": "abc", "positions": []}),
+ lambda p: p.pop("account_state"),
+ lambda p: p.update(market="crypto"),
+ lambda p: p.pop("market"),
+ lambda p: p.update(account_id=42),
+ lambda p: p.pop("from_date"),
+ lambda p: p.update(fee_model=["not", "a", "dict"]),
+ lambda p: p.update(fee_model={"commission_rate": "0.00025"}),
+])
+def test_hash_is_absent_when_the_coverage_object_is_not_computable(mutate) -> None:
+ payload = _parseable_payload()
+ mutate(payload)
+ assert wire.received_state_hash_from_payload(payload) is None
+
+
+def test_hash_is_absent_for_non_dict_payloads() -> None:
+ assert wire.received_state_hash_from_payload(None) is None
+ assert wire.received_state_hash_from_payload("account_state") is None
+ assert wire.received_state_hash_from_payload([]) is None
+
+
+# ── AM-4-4 malformed-input boundary: falsy/non-finite never hash, never raise ──
+
+
[email protected]("falsy", [[], "", False, 0, 0.0])
+def test_falsy_non_dict_fee_model_is_malformed_not_absent(falsy) -> None:
+ # A PRESENT falsy fee_model is a corrupted injection, not an omission:
+ # `or {}` laundering it into the defaults would hash a coverage object
+ # RM never injected (the exact divergence AM-4 exists to catch).
+ payload = _parseable_payload()
+ payload["fee_model"] = falsy
+ assert wire.received_state_hash_from_payload(payload) is None
+
+
+def test_missing_none_or_empty_fee_model_hashes_with_market_defaults() -> None:
+ baseline = wire.received_state_hash_from_payload(_parseable_payload())
+ missing = _parseable_payload()
+ del missing["fee_model"]
+ nulled = _parseable_payload()
+ nulled["fee_model"] = None
+ emptied = _parseable_payload()
+ emptied["fee_model"] = {}
+ hashes = {
+ wire.received_state_hash_from_payload(variant)
+ for variant in (missing, nulled, emptied)
+ }
+ assert hashes == {baseline}
+ assert baseline is not None
+
+
[email protected]("value", [float("nan"), float("inf"), float("-inf"), 10**400])
+def test_non_representable_fee_values_are_not_computable(value) -> None:
+ payload = _parseable_payload()
+ payload["fee_model"] = {"commission_rate": value}
+ assert wire.received_state_hash_from_payload(payload) is None
+
+
[email protected]("cash", [float("nan"), float("inf"), float("-inf")])
+def test_non_finite_account_state_is_not_computable(cash: float) -> None:
+ payload = _parseable_payload()
+ payload["account_state"] = {"cash": cash, "positions": []}
+ assert wire.received_state_hash_from_payload(payload) is None
+
+
+def test_non_finite_position_number_is_not_computable() -> None:
+ payload = _parseable_payload()
+ payload["account_state"] = {
+ "cash": 1000.0,
+ "positions": [{"symbol": "600519.SH", "qty": float("nan"), "avg_cost": 1418.0}],
+ }
+ assert wire.received_state_hash_from_payload(payload) is None
+
+
+def test_raw_state_that_shape_parses_but_cannot_canonicalize_is_not_computable() -> None:
+ # The shape parser reads cash/positions only; a non-str key elsewhere in
+ # the raw state (TypeError in JCS) or a non-finite extra value
+ # (ValueError in JCS) must land as None, never raise out of the error path.
+ keyed = _parseable_payload()
+ keyed["account_state"] = {"cash": 1000.0, "positions": [], 1: "non-string key"}
+ assert wire.received_state_hash_from_payload(keyed) is None
+ valued = _parseable_payload()
+ valued["account_state"] = {"cash": 1000.0, "positions": [], "note": float("nan")}
+ assert wire.received_state_hash_from_payload(valued) is None
+
+
[email protected]("falsy", [[], "", False, 0])
+def test_parse_request_rejects_falsy_non_dict_fee_model(falsy) -> None:
+ payload = _parseable_payload()
+ payload["fee_model"] = falsy
+ with pytest.raises(PaperTradeSchemaError, match="fee_model must be an object"):
+ parse_request(payload)
+
+
[email protected]("absent", ["missing", "none", "empty"])
+def test_parse_request_accepts_absent_fee_model_as_empty(absent: str) -> None:
+ payload = _parseable_payload()
+ if absent == "missing":
+ del payload["fee_model"]
+ elif absent == "none":
+ payload["fee_model"] = None
+ else:
+ payload["fee_model"] = {}
+ assert parse_request(payload).fee_model == {}
+
+
[email protected]("value", [float("nan"), float("inf"), float("-inf"), 10**400])
+def test_parse_request_rejects_non_finite_numbers_everywhere(value) -> None:
+ in_state = _parseable_payload()
+ in_state["account_state"] = {"cash": value, "positions": []}
+ with pytest.raises(PaperTradeSchemaError, match="finite"):
+ parse_request(in_state)
+ in_order = _parseable_payload()
+ in_order["orders"] = [{"symbol": "600519.SH", "side": "buy", "qty": value}]
+ with pytest.raises(PaperTradeSchemaError, match="finite"):
+ parse_request(in_order)
+ in_limit = _parseable_payload()
+ in_limit["orders"] = [{"symbol": "600519.SH", "side": "buy", "qty": 100, "limit": value}]
+ with pytest.raises(PaperTradeSchemaError, match="finite"):
+ parse_request(in_limit)
+ in_fee = _parseable_payload()
+ in_fee["fee_model"] = {"commission_rate": value}
+ with pytest.raises(PaperTradeSchemaError, match="finite"):
+ parse_request(in_fee)
+
+
[email protected]("value", [float("nan"), float("inf"), float("-inf")])
+def test_parse_account_state_rejects_non_finite(value: float) -> None:
+ with pytest.raises(PaperTradeSchemaError, match="finite"):
+ parse_account_state({"cash": value, "positions": []})
+ with pytest.raises(PaperTradeSchemaError, match="finite"):
+ parse_account_state(
+ {"cash": 1.0, "positions": [{"symbol": "600519.SH", "qty": 100, "avg_cost": value}]}
+ )
+
+
+# ── assemble_result fail-closed on errored outcomes ──
+
+
+def test_assemble_result_refuses_an_errored_outcome() -> None:
+ from src.tools.paper_trade.engine import EngineError, MatchOutcome
+ from src.tools.paper_trade.schema import PaperTradeStepRequest
+
+ request = PaperTradeStepRequest(
+ account_id="pa_01", market="cn_a", account_state=AccountState(cash=0.0),
+ from_date="2026-10-20", to_date="2026-10-20",
+ )
+ errored = MatchOutcome(
+ end_state=AccountState(cash=0.0),
+ error=EngineError("PAPER_DATA_NOT_READY", "target bar not available"),
+ )
+ with pytest.raises(ValueError, match="errored outcome"):
+ wire.assemble_result(request, errored, raw_account_state={"cash": 0.0, "positions": []})
+
+
+# ── VD-4 serialization spelling ──
+
+
+def test_dumps_payload_is_sorted_compact_and_deterministic() -> None:
+ payload = {"b": 1, "a": [2, {"d": 4, "c": 3}]}
+ assert wire.dumps_payload(payload) == '{"a":[2,{"c":3,"d":4}],"b":1}'
+ assert wire.dumps_payload(payload) == wire.dumps_payload(payload)
+ assert wire.dumps_payload({"b": 1, "a": 2}) == '{"a":2,"b":1}'
+
+
+def test_dumps_payload_keeps_utf8_raw_and_refuses_non_finite() -> None:
+ assert "贵州茅台" in wire.dumps_payload({"name": "贵州茅台"})
+ with pytest.raises(ValueError):
+ wire.dumps_payload({"nav": float("nan")})
+ with pytest.raises(ValueError):
+ wire.dumps_payload({"nav": float("inf")})
+
+
+def test_packaged_schema_matches_the_published_wire_contract():
+ from pathlib import Path
+ import src.tools.paper_trade.schema as schema
+ public = Path(__file__).resolve().parents[2] / "schema" / "tool_contracts" / "paper_trade_step-v1.1.json"
+ packaged = Path(schema.__file__).with_name("paper_trade_step-v1.1.json")
+ assert packaged.read_bytes() == public.read_bytes()
diff --git a/agent/tests/test_paper_trade_strategy_path.py b/agent/tests/test_paper_trade_strategy_path.py
new file mode 100644
index 000000000..d255bff01
--- /dev/null
+++ b/agent/tests/test_paper_trade_strategy_path.py
@@ -0,0 +1,650 @@
+"""T7 gate: strategy_path execution — B1 frozen semantics + AM-8 blocking surface.
+
+Covers the Step-7 contract surfaces:
+
+* the golden sample strategy (fixture ``strategies/golden_sample_sma.py``)
+ runs through the hardened executor and wires ``fills[].reason`` (VD-15/B2);
+* the optional module-level ``UNIVERSE`` literal (strategy-universe
+ convention): ``strategy_universe`` extracts it by pure AST read (the source
+ is never executed), ``run_strategy_path`` unions it into the child's
+ ``ctx.symbols``, and every convention/path violation degrades to the served
+ universe (positions ∪ fetched symbols) as the fallback;
+* multi-day single-call chaining, the T4 split detector in strategy mode, and
+ note-2 (a lookback-window split never fires);
+* B1: per-day timeout (busy loop AND blocked sleep — the SIGKILL really
+ interrupts) / per-day exception → the WHOLE call is in-band
+ ``INVALID_REQUEST`` with the frozen message
+ ``strategy_execution_timeout:{date}`` / ``strategy_execution_error:{date}:
+ {ExceptionClassName}``, and a day-k failure never returns days 1..k-1;
+* the executor blocking surface (socket / subprocess / os.system / eval /
+ unsafe open / broker-layer imports) rejected BEFORE execution — the source
+ never runs (canary file assertion); allowed math/pandas/quantlib imports
+ still run;
+* path policy (strategies-root containment, symlink escape, suffix, size cap,
+ sanitized syntax errors), AM-9 readiness outranking strategy failures, and
+ cross-run reproducibility (sha256 over the canonical outcome dump).
+
+Offline: fixture-backed fake loader; strategy execution runs in a spawned
+child (no network anywhere — the AST sandbox rejects it in strategy code).
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import hashlib
+import json
+import time
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.config.paths import get_runtime_root
+from src.tools.paper_trade import engine, strategy_exec
+from src.tools.paper_trade.data import fetch_market_data
+from src.tools.paper_trade.schema import parse_request
+
+_FIXTURES = Path(__file__).parent / "fixtures" / "paper_trade"
+_SPLIT_FIXTURE = _FIXTURES / "market" / "synthetic_split_4to1.json"
+_GOLDEN_STRATEGY = _FIXTURES / "strategies" / "golden_sample_sma.py"
+_SYM = "SYNTH-4TO1"
+_MARKET = "us"
+_ACCOUNT = "pa_strategy"
+_DAY = "2026-02-27" # fixture index 39: close 128.5, sma5 127.5, sma20 123.75
+
+# §4 us default fee matrix, injected explicitly (AM-4-3).
+_FEE_MODEL = {"commission_per_share": 0.0049, "commission_min": 0.99, "sec_fee_rate": 0.0}
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "sina") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+def _fixture_frame() -> pd.DataFrame:
+ document = json.loads(_SPLIT_FIXTURE.read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]]
+
+
+def _fetch(from_date: str, to_date: str, frame: pd.DataFrame | None = None):
+ return fetch_market_data(_MARKET, [_SYM], from_date, to_date,
+ loader=FakeLoader({_SYM: _fixture_frame() if frame is None else frame}))
+
+
+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 (VIBE_TRADING_HOME is popped).
+ 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 _install_golden() -> str:
+ return _install_strategy("golden_sample_sma.py", _GOLDEN_STRATEGY.read_text(encoding="utf-8"))
+
+
+def _request(strategy_path: str, *, from_date: str = _DAY, to_date: str = _DAY,
+ cash: float = 50000.0, positions: tuple[dict, ...] = (), market: str = _MARKET):
+ return parse_request({
+ "account_id": _ACCOUNT, "market": market,
+ "account_state": {"cash": cash, "positions": list(positions)},
+ "from_date": from_date, "to_date": to_date,
+ "strategy_path": strategy_path, "fee_model": dict(_FEE_MODEL),
+ })
+
+
+def _canonical(outcome) -> dict:
+ return {
+ "fills": [dataclasses.astuple(fill) for fill in outcome.fills],
+ "rejected": [dataclasses.astuple(item) for item in outcome.rejected_orders],
+ "nav": [dataclasses.astuple(point) for point in outcome.nav_series],
+ "skipped": [dataclasses.astuple(item) for item in outcome.skipped_days],
+ "end_state": dataclasses.astuple(outcome.end_state),
+ "warnings": list(outcome.warnings),
+ "provenance": dataclasses.astuple(outcome.data_provenance),
+ "fee_model": outcome.effective_fee_model,
+ "error": dataclasses.astuple(outcome.error) if outcome.error is not None else None,
+ }
+
+
+def _canonical_sha(outcome) -> str:
+ # test_run_card.py:330-353 instrument: byte-level determinism via sha256
+ # over the canonical JSON dump.
+ text = json.dumps(_canonical(outcome), sort_keys=True, default=str,
+ separators=(",", ":"), ensure_ascii=False)
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
+
+
+def _assert_whole_call_failure(outcome, message: str, request) -> None:
+ # B1: the WHOLE call failed in-band — frozen message verbatim, empty
+ # arrays, the input state untouched (no partial day 1..k-1 output).
+ assert outcome.error is not None
+ assert outcome.error.code == "INVALID_REQUEST"
+ assert outcome.error.message == message
+ assert outcome.fills == ()
+ assert outcome.rejected_orders == ()
+ assert outcome.nav_series == ()
+ assert outcome.skipped_days == ()
+ assert outcome.end_state == request.account_state
+
+
+_SCHEDULE_SOURCE = '''"""Date-keyed schedule strategy (3-day chaining form)."""
+
+_SCHEDULE = {
+ "2026-02-05": [{"symbol": "SYNTH-4TO1", "side": "buy", "qty": 100, "reason": "schedule day 1"}],
+ "2026-02-06": [
+ {"symbol": "SYNTH-4TO1", "side": "sell", "qty": 50, "reason": "schedule day 2 exit"},
+ {"symbol": "SYNTH-4TO1", "side": "buy", "qty": 20, "reason": "schedule day 2 re-entry"},
+ ],
+ "2026-02-09": [{"symbol": "SYNTH-4TO1", "side": "sell", "qty": 70, "reason": "schedule day 3"}],
+}
+
+
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ return _SCHEDULE.get(trade_date, [])
+'''
+
+_HANG_SOURCE = '''"""Busy-loop hang strategy."""
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ while True:
+ pass
+'''
+
+_SLEEP_SOURCE = '''"""Blocked-sleep hang strategy."""
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ import time
+ time.sleep(300)
+ return []
+'''
+
+
+def test_golden_sample_strategy_runs_and_wires_reason() -> None:
+ day = "2026-03-02"
+ outcome = strategy_exec.run_strategy_path(
+ request=_request(_install_golden(), from_date=day, to_date=day), market_data=_fetch(day, day))
+ assert outcome.error is None
+ # Hand-computed: close 129.0, sma5 127.5 > sma20 123.75 → buy 100;
+ # us fee max(100×0.0049, 0.99) = 0.99; cash 50000 − 12850.00 − 0.99.
+ assert [(f.trade_date, f.symbol, f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [
+ (day, _SYM, "buy", 100, 129.0, 0.99)]
+ # VD-15/B2 strategy mode: the strategy's reason text reaches the fill.
+ assert outcome.fills[0].reason == "golden sma5 127.5000 > sma20 123.7500"
+ assert len(outcome.fills[0].reason) <= 200
+ assert outcome.end_state.cash == 37099.01
+ assert [(p.symbol, p.qty, p.avg_cost) for p in outcome.end_state.positions] == [(_SYM, 100, 129.0)]
+ assert [(n.date, n.nav) for n in outcome.nav_series] == [(day, 49999.01)]
+ assert outcome.rejected_orders == ()
+
+
+def test_three_day_single_call_chains_the_ledger() -> None:
+ path = _install_strategy("schedule_3day.py", _SCHEDULE_SOURCE)
+ outcome = strategy_exec.run_strategy_path(
+ request=_request(path, from_date="2026-02-05", to_date="2026-02-09"),
+ market_data=_fetch("2026-02-05", "2026-02-09"))
+ assert outcome.error is None
+ # Closes 120.5/121.0/121.5; the weekend (02-07/08) is implicit for us —
+ # no skip vocabulary, nav continues across it. Hand-computed chain:
+ # d1 −12050.99 → 37949.01; d2 +6049.01 −2420.99 → 41577.03 (70 @ 120.6429);
+ # d3 +8504.01 → 50081.04, position closed.
+ assert [(f.trade_date, f.side, f.qty, f.price, f.fee) for f in outcome.fills] == [
+ ("2026-02-05", "buy", 100, 120.5, 0.99),
+ ("2026-02-06", "sell", 50, 121.0, 0.99),
+ ("2026-02-06", "buy", 20, 121.0, 0.99),
+ ("2026-02-09", "sell", 70, 121.5, 0.99),
+ ]
+ assert [f.reason for f in outcome.fills] == [
+ "schedule day 1", "schedule day 2 exit", "schedule day 2 re-entry", "schedule day 3"]
+ assert outcome.end_state.cash == 50081.04
+ assert outcome.end_state.positions == ()
+ assert [(n.date, n.nav) for n in outcome.nav_series] == [
+ ("2026-02-05", 49999.01), ("2026-02-06", 50047.03), ("2026-02-09", 50081.04)]
+ assert outcome.skipped_days == ()
+ # Note 2: the 4:1 cliff (2026-02-02) sits inside the K=120 lookback and
+ # must never fire — no events, no rejections, no warnings.
+ assert outcome.data_provenance.corporate_actions == ()
+ assert outcome.rejected_orders == ()
+ assert not any("corporate action" in w for w in outcome.warnings)
+
+
+def test_t4_split_detection_applies_in_strategy_mode() -> None:
+ # Position 100 @ 476 held across the 2026-02-02 ex-date (clean 4:1): the
+ # detector adjusts to 400 @ 119.0 BEFORE the day's orders, so the
+ # strategy's sell of 400 on 02-03 can only fill if T4 ran in this mode.
+ source = '''"""Post-split exit strategy."""
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ if trade_date == "2026-02-03":
+ return [{"symbol": "SYNTH-4TO1", "side": "sell", "qty": 400, "reason": "post-split exit"}]
+ return []
+'''
+ path = _install_strategy("split_exit.py", source)
+ outcome = strategy_exec.run_strategy_path(
+ request=_request(path, from_date="2026-01-30", to_date="2026-02-03", cash=1000.0,
+ positions=({"symbol": _SYM, "qty": 100, "avg_cost": 476.0},)),
+ market_data=_fetch("2026-01-30", "2026-02-03"))
+ assert outcome.error is not None
+ assert outcome.error.code == "PAPER_DATA_NOT_READY"
+ assert outcome.end_state.positions[0].qty == 100
+ assert outcome.fills == ()
+ assert outcome.nav_series == ()
+
+
[email protected]("kind", ["busy_loop", "blocked_sleep"])
+def test_per_day_timeout_really_interrupts_and_freezes_the_message(kind: str) -> None:
+ source = _HANG_SOURCE if kind == "busy_loop" else _SLEEP_SOURCE
+ path = _install_strategy(f"hang_{kind}.py", source)
+ request = _request(path, from_date="2026-02-05", to_date="2026-02-05")
+ started = time.monotonic()
+ outcome = strategy_exec.run_strategy_path(
+ request=request, market_data=_fetch("2026-02-05", "2026-02-05"), timeout_seconds=1.0)
+ elapsed = time.monotonic() - started
+ # SIGKILL, not a cooperative unwind: the blocked sleep(300) child dies at
+ # the 1s budget, so the call returns in startup + budget, never ~300s.
+ assert elapsed < 60.0
+ _assert_whole_call_failure(outcome, "strategy_execution_timeout:2026-02-05", request)
+
+
+def test_day_two_exception_never_returns_day_one_results() -> None:
+ source = '''"""Day-2 exception strategy."""
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ if trade_date == "2026-02-05":
+ return [{"symbol": "SYNTH-4TO1", "side": "buy", "qty": 100, "reason": "day 1 would fill"}]
+ if trade_date == "2026-02-06":
+ raise ZeroDivisionError("boom")
+ return []
+'''
+ path = _install_strategy("exc_day2.py", source)
+ request = _request(path, from_date="2026-02-05", to_date="2026-02-09")
+ outcome = strategy_exec.run_strategy_path(
+ request=request, market_data=_fetch("2026-02-05", "2026-02-09"))
+ # B1: day k fails → the whole call errors; day 1's fill/nav are NOT returned.
+ _assert_whole_call_failure(
+ outcome, "strategy_execution_error:2026-02-06:ZeroDivisionError", request)
+
+
+_BLOCKED_BODIES = [
+ ("socket_import", [" import socket", " return [{'symbol': socket.gethostname(), 'side': 'buy', 'qty': 1}]"]),
+ ("subprocess_run", [" import subprocess", " return [] if subprocess.run(['true']) else []"]),
+ ("os_system", [" import os", " return [] if os.system('true') == 0 else []"]),
+ ("os_environ", [" import os", " return [] if os.environ else []"]),
+ ("eval_call", [" return [] if eval('1+1') == 2 else []"]),
+ ("open_write", [" open('evil.txt', 'w').write('x')", " return []"]),
+ ("open_abs_read", [" return open('/etc/passwd').read()"]),
+ ("broker_service", [" from src.trading.service import place_order", " return []"]),
+ ("broker_connector", [" import src.trading.connectors.okx.sdk", " return []"]),
+ ("dunder_import", [" return __import__('os').getcwd()"]),
+]
+
+
[email protected]("case_id,body", _BLOCKED_BODIES, ids=[c[0] for c in _BLOCKED_BODIES])
+def test_executor_blocking_surface_rejects_before_execution(case_id, body) -> None:
+ # AM-8 regression, mirroring test_backtest_runner_security.py bodies: the
+ # validator rejects in the PARENT (no child is ever spawned), so nothing
+ # runs — the canary file assertion proves it for the write payload.
+ source = "\n".join(['"""Blocked strategy."""', "class SignalEngine:",
+ " def generate_signals(self, ctx, trade_date):", *body])
+ path = _install_strategy(f"blocked_{case_id}.py", source)
+ request = _request(path)
+ outcome = strategy_exec.run_strategy_path(request=request, market_data=_fetch(_DAY, _DAY))
+ _assert_whole_call_failure(outcome, f"strategy_execution_error:{_DAY}:ValueError", request)
+ assert not (Path.cwd() / "evil.txt").exists()
+ assert not (Path.home() / "evil.txt").exists()
+
+
+def test_allowed_math_pandas_quantlib_strategy_still_runs() -> None:
+ source = '''"""Allowed imports strategy."""
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ import math
+ import pandas as pd
+ from src.quantlib.fixedincome import bond_price
+ symbol = ctx.symbols[0]
+ close = ctx.history(symbol)["close"]
+ if math.isfinite(float(close.iloc[-1])) and pd is not None and bond_price is not None:
+ return [{"symbol": symbol, "side": "buy", "qty": 1, "reason": "allowed imports ran"}]
+ return []
+'''
+ path = _install_strategy("allowed_imports.py", source)
+ outcome = strategy_exec.run_strategy_path(
+ request=_request(path), market_data=_fetch(_DAY, _DAY))
+ assert outcome.error is None
+ assert [(f.side, f.qty, f.reason) for f in outcome.fills] == [("buy", 1, "allowed imports ran")]
+
+
+def test_cross_run_reproducibility_is_byte_identical() -> None:
+ path = _install_golden()
+ first = strategy_exec.run_strategy_path(request=_request(path), market_data=_fetch(_DAY, _DAY))
+ second = strategy_exec.run_strategy_path(request=_request(path), market_data=_fetch(_DAY, _DAY))
+ assert first.error is None and second.error is None
+ # Same file + same state + same day = same orders, across separate child
+ # processes (no cross-run state): sha256 over the canonical dump.
+ assert _canonical_sha(first) == _canonical_sha(second)
+ assert first.fills == second.fills
+ assert first.end_state == second.end_state
+ assert first.nav_series == second.nav_series
+
+
+def _reasons_source(reasons: list) -> str:
+ return "\n".join([
+ '"""Reason boundary strategy."""',
+ f"_REASONS = {reasons!r}",
+ "",
+ "class SignalEngine:",
+ " def generate_signals(self, ctx, trade_date):",
+ " orders = []",
+ " for reason in _REASONS:",
+ ' orders.append({"symbol": "SYNTH-4TO1", "side": "buy", "qty": 1, "reason": reason})',
+ " return orders",
+ ])
+
+
+def test_fill_reason_boundaries_are_utf8_safe_and_capped_at_200() -> None:
+ emoji_reason = "🎯" * 199 + "y" * 50
+ reasons = ["r" * 200, "x" * 250, emoji_reason, None]
+ path = _install_strategy("reason_bounds.py", _reasons_source(reasons))
+ outcome = strategy_exec.run_strategy_path(request=_request(path), market_data=_fetch(_DAY, _DAY))
+ assert outcome.error is None
+ got = [f.reason for f in outcome.fills]
+ assert got == ["r" * 200, "x" * 200, emoji_reason[:200], ""]
+ for reason in got:
+ assert len(reason) <= 200
+ reason.encode("utf-8") # never a split multi-byte character
+ assert got[2] == "🎯" * 199 + "y" # code-point slice kept the 4-byte char whole
+
+
+_MALFORMED_BODIES = [
+ ("non_list_return", [" return 42"]),
+ ("bad_side", [' return [{"symbol": "SYNTH-4TO1", "side": "hold", "qty": 1}]']),
+ ("nan_qty", [' return [{"symbol": "SYNTH-4TO1", "side": "buy", "qty": float("nan")}]']),
+ ("non_str_reason", [' return [{"symbol": "SYNTH-4TO1", "side": "buy", "qty": 1, "reason": 42}]']),
+ ("non_dict_entry", [' return ["SYNTH-4TO1"]']),
+]
+
+
[email protected]("case_id,body", _MALFORMED_BODIES, ids=[c[0] for c in _MALFORMED_BODIES])
+def test_malformed_strategy_output_is_a_frozen_strategy_order_error(case_id, body) -> None:
+ source = "\n".join(['"""Malformed output strategy."""', "class SignalEngine:",
+ " def generate_signals(self, ctx, trade_date):", *body])
+ path = _install_strategy(f"malformed_{case_id}.py", source)
+ request = _request(path)
+ outcome = strategy_exec.run_strategy_path(request=request, market_data=_fetch(_DAY, _DAY))
+ _assert_whole_call_failure(
+ outcome, f"strategy_execution_error:{_DAY}:StrategyOrderError", request)
+
+
+def test_path_policy_rejects_before_any_read_or_execute(tmp_path) -> None:
+ valid = _GOLDEN_STRATEGY.read_text(encoding="utf-8")
+ root = get_runtime_root() / "strategies"
+ root.mkdir(parents=True, exist_ok=True)
+ runtime_root = get_runtime_root()
+ (runtime_root / "escape.py").write_text(valid, encoding="utf-8")
+ (runtime_root / "outside_target.py").write_text(valid, encoding="utf-8")
+ (root / "strategy.txt").write_text(valid, encoding="utf-8")
+ (root / "dir.py").mkdir(exist_ok=True)
+ (root / "big.py").write_text("a" * (strategy_exec._MAX_STRATEGY_BYTES + 1), encoding="utf-8")
+ (root / "broken.py").write_text("SECRET_MARKER = (\n", encoding="utf-8")
+ (tmp_path / "outside.py").write_text(valid, encoding="utf-8")
+ symlink_case = {}
+ try:
+ (root / "link.py").symlink_to(runtime_root / "outside_target.py")
+ symlink_case = {"symlink_escape": str(root / "link.py")}
+ except OSError:
+ pass # symlink creation privileges (Windows) — case skipped, not failed
+
+ cases = {
+ "traversal": str(root / ".." / "escape.py"),
+ "absolute_outside": str(tmp_path / "outside.py"),
+ "wrong_suffix": str(root / "strategy.txt"),
+ "missing_file": str(root / "nope.py"),
+ "directory_named_py": str(root / "dir.py"),
+ "oversize": str(root / "big.py"),
+ "empty_path": "",
+ **symlink_case,
+ }
+ market_data = _fetch(_DAY, _DAY)
+ for label, strategy_path in cases.items():
+ request = _request(strategy_path)
+ outcome = strategy_exec.run_strategy_path(request=request, market_data=market_data)
+ assert outcome.error is not None, label
+ assert outcome.error.code == "INVALID_REQUEST", label
+ assert outcome.error.message == f"strategy_execution_error:{_DAY}:StrategyPathError", label
+ assert outcome.fills == () and outcome.nav_series == (), label
+ assert outcome.end_state == request.account_state, label
+
+ # Syntax errors never echo source text (the target may be a non-strategy
+ # file whose contents must not leak into the wire message).
+ outcome = strategy_exec.run_strategy_path(
+ request=_request(str(root / "broken.py")), market_data=market_data)
+ assert outcome.error is not None
+ assert outcome.error.message == f"strategy_execution_error:{_DAY}:StrategyPathError"
+ assert "SECRET_MARKER" not in outcome.error.message
+
+
+def test_readiness_gate_outranks_a_hanging_strategy() -> None:
+ # AM-9 runs BEFORE validation/execution: a retryable data fact is never
+ # masked by the non-retryable timeout of a strategy that never runs.
+ truncated = _fixture_frame().loc[: pd.Timestamp("2026-02-20")]
+ path = _install_strategy("hang_notready.py", _HANG_SOURCE)
+ request = _request(path, from_date="2026-02-20", to_date="2026-02-23")
+ started = time.monotonic()
+ outcome = strategy_exec.run_strategy_path(
+ request=request, market_data=_fetch("2026-02-20", "2026-02-23", frame=truncated))
+ assert time.monotonic() - started < 30.0 # no spawn, no 1s budget wait
+ assert outcome.error is not None
+ assert outcome.error.code == "PAPER_DATA_NOT_READY"
+ assert outcome.fills == () and outcome.nav_series == ()
+
+
+class FakeChClient:
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ return pd.DataFrame()
+
+
+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": 0,
+ "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 test_no_matching_days_validates_but_never_runs_the_strategy() -> None:
+ # cn_a calendar truth closes the whole range: the strategy is validated
+ # (contract enforcement) but never executed — a raise-if-called body
+ # proves it, and the call succeeds with two non_trading_day skips.
+ source = '''"""Must-not-run strategy."""
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ raise RuntimeError("must not run on a closed calendar")
+'''
+ path = _install_strategy("must_not_run.py", source)
+ frame = pd.DataFrame(
+ [{"trade_date": "2026-02-06", "open": 10.0, "high": 10.0, "low": 10.0,
+ "close": 10.0, "volume": 1000.0}]).set_index(pd.to_datetime(["2026-02-06"]))
+ market_data = fetch_market_data(
+ "cn_a", ["600519.SH"], "2026-02-07", "2026-02-08",
+ loader=FakeLoader({"600519.SH": frame}, name="tencent"), ch_client=FakeChClient())
+ request = _request(path, from_date="2026-02-07", to_date="2026-02-08", market="cn_a")
+ outcome = strategy_exec.run_strategy_path(
+ request=request, market_data=market_data, calendar_client=FakeCalendarClient())
+ assert outcome.error is None
+ assert [(s.date, s.reason) for s in outcome.skipped_days] == [
+ ("2026-02-07", "non_trading_day"), ("2026-02-08", "non_trading_day")]
+ assert outcome.fills == () and outcome.nav_series == ()
+
+
+def test_seam_misuse_and_bad_timeout_raise_transport_class() -> None:
+ market_data = _fetch(_DAY, _DAY)
+ orders_only = parse_request({
+ "account_id": _ACCOUNT, "market": _MARKET,
+ "account_state": {"cash": 50000.0, "positions": []},
+ "from_date": _DAY, "to_date": _DAY,
+ "orders": [{"symbol": _SYM, "side": "buy", "qty": 100}], "fee_model": {},
+ })
+ with pytest.raises(ValueError, match="strategy_path"):
+ strategy_exec.run_strategy_path(request=orders_only, market_data=market_data)
+
+ both = parse_request({
+ "account_id": _ACCOUNT, "market": _MARKET,
+ "account_state": {"cash": 50000.0, "positions": []},
+ "from_date": _DAY, "to_date": _DAY,
+ "orders": [{"symbol": _SYM, "side": "buy", "qty": 100}],
+ "strategy_path": _install_golden(), "fee_model": {},
+ })
+ with pytest.raises(ValueError, match="orders must be absent"):
+ strategy_exec.run_strategy_path(request=both, market_data=market_data)
+
+ mismatch = _request(_install_golden(), market="hk")
+ with pytest.raises(ValueError, match="market_data was fetched for"):
+ strategy_exec.run_strategy_path(request=mismatch, market_data=market_data)
+
+ good = _request(_install_golden())
+ for bad in (0, -1.0, float("nan"), float("inf"), "5", True):
+ with pytest.raises(ValueError, match="finite positive"):
+ strategy_exec.run_strategy_path(
+ request=good, market_data=market_data, timeout_seconds=bad)
+
+
+def test_orders_mode_fill_reason_stays_empty() -> None:
+ # VD-15/B2 contrast half: the orders mode keeps "" (goldens pin the wire
+ # bytes; this pins the engine boundary the strategy mode shares).
+ request = parse_request({
+ "account_id": _ACCOUNT, "market": _MARKET,
+ "account_state": {"cash": 50000.0, "positions": []},
+ "from_date": _DAY, "to_date": _DAY,
+ "orders": [{"symbol": _SYM, "side": "buy", "qty": 100}], "fee_model": dict(_FEE_MODEL),
+ })
+ outcome = engine.match_orders(request, market_data=_fetch(_DAY, _DAY))
+ assert outcome.error is None
+ assert [f.reason for f in outcome.fills] == [""]
+
+
+# ── the optional UNIVERSE declaration (strategy_universe: pure AST read) ──
+
+
+def test_strategy_universe_extracts_literal_tuple_and_list() -> None:
+ tuple_path = _install_strategy("universe_tuple.py", 'UNIVERSE = ("SYM-B", "SYM-A", "SYM-B")\n')
+ assert strategy_exec.strategy_universe(tuple_path) == ("SYM-A", "SYM-B") # sorted, deduped
+ list_path = _install_strategy("universe_list.py", 'UNIVERSE = ["SYM-X", "SYM-Y"]\n')
+ assert strategy_exec.strategy_universe(list_path) == ("SYM-X", "SYM-Y")
+ annotated = _install_strategy("universe_ann.py", 'UNIVERSE: tuple = ("SYM-Z",)\n')
+ assert strategy_exec.strategy_universe(annotated) == ("SYM-Z",)
+ # The golden fixture declares the synthetic symbol the T6/T7 gates serve.
+ assert strategy_exec.strategy_universe(_install_golden()) == (_SYM,)
+
+
+_UNIVERSE_REJECTIONS = {
+ "absent": 'OTHER = ("SYM",)\n',
+ "call": 'UNIVERSE = tuple("SYM")\n',
+ "expression": 'UNIVERSE = ("SYM",) * 2\n',
+ "bare_string": 'UNIVERSE = "SYM"\n',
+ "dict": 'UNIVERSE = {"SYM": 1}\n',
+ "non_string_entry": 'UNIVERSE = ("SYM", 42)\n',
+ "empty_string_entry": 'UNIVERSE = ("SYM", "")\n',
+ "invalid_syntax": "UNIVERSE = (\n",
+}
+
+
[email protected]("case_id", sorted(_UNIVERSE_REJECTIONS))
+def test_strategy_universe_convention_violations_degrade_to_empty(case_id) -> None:
+ path = _install_strategy(f"universe_bad_{case_id}.py", _UNIVERSE_REJECTIONS[case_id])
+ assert strategy_exec.strategy_universe(path) == ()
+
+
+def test_strategy_universe_path_policy_rejections_degrade_to_empty(tmp_path) -> None:
+ root = get_runtime_root() / "strategies"
+ root.mkdir(parents=True, exist_ok=True)
+ outside = tmp_path / "outside.py"
+ outside.write_text('UNIVERSE = ("SYM",)\n', encoding="utf-8")
+ wrong_suffix = root / "universe_policy.txt"
+ wrong_suffix.write_text('UNIVERSE = ("SYM",)\n', encoding="utf-8")
+ cases = {
+ "outside_root": str(outside),
+ "missing_file": str(root / "universe_nope.py"),
+ "wrong_suffix": str(wrong_suffix),
+ "empty_path": "",
+ "blank_path": " ",
+ }
+ for label, path in cases.items():
+ assert strategy_exec.strategy_universe(path) == (), label
+
+
+def test_strategy_universe_never_executes_the_source() -> None:
+ # No-execution proof: an exec/import would fire the canary write and
+ # propagate the raise; the pure AST read returns the declaration untouched
+ # (the raise sits BEFORE the assignment, so only a parse can see it).
+ source = (
+ "import pathlib\n"
+ "pathlib.Path('universe_canary.txt').write_text('executed')\n"
+ "raise RuntimeError('strategy_universe must never execute the source')\n"
+ 'UNIVERSE = ("SYM-A", "SYM-B")\n'
+ )
+ path = _install_strategy("universe_noexec.py", source)
+ assert strategy_exec.strategy_universe(path) == ("SYM-A", "SYM-B")
+ assert not (Path.cwd() / "universe_canary.txt").exists()
+ assert not (Path.home() / "universe_canary.txt").exists()
+
+
+def test_declared_universe_joins_ctx_symbols_without_child_io() -> None:
+ # run_strategy_path unions the declared UNIVERSE into the child's
+ # ctx.symbols (sorted union with the served universe); a declared symbol
+ # with no served data reads an empty history — the child never fetches.
+ source = '''"""Universe-declaring strategy (ctx union probe)."""
+UNIVERSE = ("SYNTH-4TO1", "NO-DATA-SYM")
+
+
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ if tuple(ctx.symbols) != ("NO-DATA-SYM", "SYNTH-4TO1"):
+ raise AssertionError("ctx.symbols must be the sorted served+declared union")
+ if not ctx.history("NO-DATA-SYM").empty:
+ raise AssertionError("a declared symbol without served data reads an empty history")
+ return [{"symbol": "SYNTH-4TO1", "side": "buy", "qty": 1,
+ "reason": "+".join(ctx.symbols)}]
+'''
+ path = _install_strategy("universe_ctx.py", source)
+ outcome = strategy_exec.run_strategy_path(
+ request=_request(path), market_data=_fetch(_DAY, _DAY))
+ assert outcome.error is None
+ assert [(f.side, f.qty, f.reason) for f in outcome.fills] == [
+ ("buy", 1, "NO-DATA-SYM+SYNTH-4TO1")]
+
+
+def test_strategy_uses_prior_bars_and_receives_previous_fills():
+ path = _install_strategy("causal_state.py", '''
+class SignalEngine:
+ def generate_signals(self, ctx, trade_date):
+ history = ctx.history(ctx.symbols[0])
+ if str(history.index[-1].date()) >= trade_date:
+ raise AssertionError("execution bar leaked")
+ if ctx.account_state.positions:
+ if ctx.account_state.cash >= 50000:
+ raise AssertionError("stale cash")
+ return [{"symbol": ctx.symbols[0], "side": "sell",
+ "qty": ctx.account_state.positions[0].qty}]
+ return [{"symbol": ctx.symbols[0], "side": "buy", "qty": 10}]
+''')
+ request = _request(path, from_date="2026-02-05", to_date="2026-02-06")
+ outcome = strategy_exec.run_strategy_path(
+ request=request, market_data=_fetch(request.from_date, request.to_date))
+ assert outcome.error is None
+ assert [(fill.trade_date, fill.side, fill.qty) for fill in outcome.fills] == [
+ ("2026-02-05", "buy", 10), ("2026-02-06", "sell", 10)]
+ assert outcome.end_state.positions == ()
diff --git a/agent/tests/test_paper_trade_tool.py b/agent/tests/test_paper_trade_tool.py
new file mode 100644
index 000000000..add22fade
--- /dev/null
+++ b/agent/tests/test_paper_trade_tool.py
@@ -0,0 +1,521 @@
+"""T6 gate — ``paper_trade_step`` tool entry + MCP wrapper (Step 6).
+
+Covers the registration seam end to end, offline: the orders-mode success
+document, the in-band ``PAPER_DATA_NOT_READY`` envelope, ``INVALID_REQUEST``
+for every malformed-input class (shape parse, the tool-owned orders XOR
+strategy_path gate, a reversed range, the AM-3 single-day rule), the AM-4-1
+rule that ``received_state_hash`` covers the RAW account_state (an added key
+breaks it, an int/float respelling does not), the single degraded error-envelope
+case (a malformed ``market`` echoed verbatim, T5 decision 5), the strategy_path
+routing into the lazily-imported T7 ``strategy_exec.run_strategy_path`` (fake,
+including the ``strategy_universe`` prefetch seam and its orders-mode absence),
+the strategy_path end-to-end universe regression (a cash-only account + the
+golden fixture's declared ``UNIVERSE`` must prefetch and fill), and the
+hand-written MCP wrapper (payload build + delegation + description).
+
+The research-only red line is asserted statically: the tool module carries no
+scoped ``trading_*`` connector surface and no order-placement call.
+
+Offline by construction: fake loader / fake CH client / fake calendar client,
+no network (``--disable-socket`` hard gate), no clock (every date injected).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import sys
+import types
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.config.paths import get_runtime_root
+from src.tools.paper_trade import engine, state_hash
+from src.tools.paper_trade import tool as tool_module
+from src.tools.paper_trade.schema import (
+ MARKETS,
+ load_contract_schema,
+ validate_payload,
+)
+from src.tools.paper_trade.tool import PaperTradeStepTool, run_paper_trade_step
+
+_CN_A_DAY = "2026-10-20" # Tuesday
+_CN_A_PREV = "2026-10-19"
+_HK_DAY = "2026-10-16" # Friday
+_SHA_RE = re.compile(r"^[0-9a-f]{64}$")
+
+# The T7 synthetic fixture day (index 39: close 128.5, sma5 127.5, sma20
+# 123.75 — the golden SMA cross) and the §4 us default fee matrix (AM-4-3).
+_US_DAY = "2026-03-02"
+_US_FEES = {"commission_per_share": 0.0049, "commission_min": 0.99, "sec_fee_rate": 0.0}
+_FIXTURES = Path(__file__).parent / "fixtures" / "paper_trade"
+_SYNTH_FIXTURE = _FIXTURES / "market" / "synthetic_split_4to1.json"
+_GOLDEN_STRATEGY = _FIXTURES / "strategies" / "golden_sample_sma.py"
+
+_CN_A_FEES = {
+ "commission_rate": 0.00025,
+ "commission_min": 5.0,
+ "stamp_tax_sell": 0.0005,
+ "transfer_fee": 0.00001,
+}
+_HK_FEES = {
+ "commission_rate": 0.0003,
+ "commission_min": 3.0,
+ "stamp_tax_rate": 0.001,
+ "regulatory_levy_rate": 0.00003,
+}
+
+
+class FakeChClient:
+ def __init__(self, frames: dict[str, pd.DataFrame]) -> None:
+ self._frames = frames
+
+ def get_bars(self, ts_code: str, start_date: str, end_date: str) -> pd.DataFrame:
+ return self._frames.get(ts_code, pd.DataFrame())
+
+
+class FakeLoader:
+ def __init__(self, frames: dict[str, pd.DataFrame], name: str = "tencent") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c in self._frames}
+
+
+class FakeCalendarClient:
+ """cn_a CH trade_calendar truth: exactly the given days are open."""
+
+ def __init__(self, open_days: tuple[str, ...]) -> None:
+ self._open = set(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 _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 _payload(**overrides) -> dict:
+ base = {
+ "account_id": "pa_t6",
+ "market": "cn_a",
+ "account_state": {"cash": 200000.0, "positions": []},
+ "orders": [{"symbol": "600519.SH", "side": "buy", "qty": 100}],
+ "from_date": _CN_A_DAY,
+ "to_date": _CN_A_DAY,
+ "fee_model": dict(_CN_A_FEES),
+ }
+ base.update(overrides)
+ return base
+
+
+def _cn_a_fakes(*, target_bar: float | None = 1421.0, prev_bar: float | None = 1418.0):
+ """Fake loader/ch/calendar for a cn_a run; ``None`` omits that leg's bar."""
+ loader_frames = {"600519.SH": _frame([(_CN_A_DAY, target_bar)])} if target_bar else {}
+ ch_frames = {"600519.SH": _frame([(_CN_A_PREV, prev_bar)])} if prev_bar else {}
+ return {
+ "loader": FakeLoader(loader_frames, "tencent"),
+ "ch_client": FakeChClient(ch_frames),
+ "calendar_client": FakeCalendarClient((_CN_A_DAY,)),
+ "limits_client": None, # heuristic band (the cn_a golden path)
+ }
+
+
+# ── orders-mode success document ──
+
+
+def test_orders_mode_returns_the_success_document() -> None:
+ text = run_paper_trade_step(_payload(), **_cn_a_fakes())
+ doc = json.loads(text)
+ assert doc["schema_version"] == "pt-v1.1"
+ assert doc["tool"] == "paper_trade_step"
+ assert doc["account_id"] == "pa_t6"
+ assert doc["market"] == "cn_a"
+ assert doc["range"] == {"from": _CN_A_DAY, "to": _CN_A_DAY}
+ assert _SHA_RE.match(doc["received_state_hash"])
+ # Hand-computed cn_a cents (the T3/T5 golden): buy 100 @ 1421.0, fee 36.95.
+ assert doc["fills"][0] == {
+ "trade_date": _CN_A_DAY, "symbol": "600519.SH", "side": "buy",
+ "qty": 100.0, "price": 1421.0, "fee": 36.95, "reason": "",
+ }
+ assert doc["end_state"]["cash"] == 57863.05
+ assert doc["data_provenance"]["source"] == "clickhouse+tencent(merged)"
+ assert validate_payload(doc, load_contract_schema("result")) == []
+
+
+def test_success_document_is_byte_deterministic_across_runs() -> None:
+ first = run_paper_trade_step(_payload(), **_cn_a_fakes())
+ second = run_paper_trade_step(_payload(), **_cn_a_fakes())
+ assert first == second
+
+
+# ── AM-5 in-band PAPER_DATA_NOT_READY envelope ──
+
+
+def test_target_day_without_a_bar_returns_in_band_not_ready() -> None:
+ # Neither leg serves the target day → readiness fails → in-band envelope.
+ fakes = _cn_a_fakes(target_bar=None, prev_bar=1418.0)
+ doc = json.loads(run_paper_trade_step(_payload(), **fakes))
+ assert doc["status"] == "error"
+ assert doc["code"] == "PAPER_DATA_NOT_READY"
+ assert doc["account_id"] == "pa_t6" # verbatim even on error (AM-4-4)
+ assert doc["market"] == "cn_a"
+ assert doc["range"] == {"from": _CN_A_DAY, "to": _CN_A_DAY}
+ assert _SHA_RE.match(doc["received_state_hash"]) # state was parseable
+ assert f"target bar {_CN_A_DAY} not available" in doc["message"]
+ assert validate_payload(doc, load_contract_schema("error_envelope")) == []
+
+
+# ── INVALID_REQUEST: shape parse, semantic gate, range rules ──
+
+
+def test_malformed_market_is_invalid_request_echoed_verbatim() -> None:
+ doc = json.loads(run_paper_trade_step(_payload(market="xyz")))
+ assert doc["status"] == "error"
+ assert doc["code"] == "INVALID_REQUEST"
+ # T5 decision 5: the raw malformed market is echoed verbatim (honest
+ # reporting), so the envelope's own market enum is the single degraded
+ # case — the only validation error is the market enum.
+ assert doc["market"] == "xyz"
+ assert "market must be one of" in doc["message"]
+ # market not in MARKETS → the coverage object is not computable → hash omitted.
+ assert "received_state_hash" not in doc
+ errors = validate_payload(doc, load_contract_schema("error_envelope"))
+ assert errors and all("market" in e for e in errors)
+
+
+def test_missing_account_id_is_invalid_request_with_empty_echo() -> None:
+ payload = _payload()
+ del payload["account_id"]
+ doc = json.loads(run_paper_trade_step(payload))
+ assert doc["code"] == "INVALID_REQUEST"
+ assert doc["account_id"] == "" # non-string degrades to "" (never leaks)
+ assert "account_id" in doc["message"]
+
+
+def test_non_dict_payload_is_invalid_request() -> None:
+ doc = json.loads(run_paper_trade_step(["not", "an", "object"]))
+ assert doc["code"] == "INVALID_REQUEST"
+ assert doc["account_id"] == "" and doc["market"] == ""
+ assert "received_state_hash" not in doc
+
+
+def test_both_orders_and_strategy_path_violates_the_xor_gate() -> None:
+ payload = _payload(strategy_path="agent/strategies/x.py")
+ doc = json.loads(run_paper_trade_step(payload))
+ assert doc["code"] == "INVALID_REQUEST"
+ assert "got both" in doc["message"]
+ assert doc["account_id"] == "pa_t6" and doc["market"] == "cn_a"
+
+
+def test_neither_orders_nor_strategy_path_violates_the_xor_gate() -> None:
+ payload = _payload(orders=None)
+ doc = json.loads(run_paper_trade_step(payload))
+ assert doc["code"] == "INVALID_REQUEST"
+ assert "got neither" in doc["message"]
+
+
+def test_reversed_range_is_invalid_request() -> None:
+ # hk avoids the cn_a connector; fetch_market_data guards from > to first.
+ payload = _payload(market="hk", from_date=_HK_DAY, to_date="2026-10-15",
+ fee_model=dict(_HK_FEES),
+ orders=[{"symbol": "00700.HK", "side": "buy", "qty": 100}])
+ doc = json.loads(run_paper_trade_step(payload))
+ assert doc["code"] == "INVALID_REQUEST"
+ assert "from_date" in doc["message"] and "to_date" in doc["message"]
+
+
+def test_orders_mode_multiday_is_invalid_request() -> None:
+ # AM-3 single-day gate lives in the engine and surfaces as in-band material.
+ payload = _payload(market="hk", from_date="2026-10-15", to_date=_HK_DAY,
+ fee_model=dict(_HK_FEES),
+ orders=[{"symbol": "00700.HK", "side": "buy", "qty": 100}])
+ loader = FakeLoader({"00700.HK": _frame([("2026-10-15", 416.0), (_HK_DAY, 417.8)])}, "tencent")
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+ assert doc["code"] == "INVALID_REQUEST"
+ assert "from_date == to_date" in doc["message"]
+
+
+# ── AM-4-1: received_state_hash covers the RAW account_state ──
+
+
+def _hk_success_hash(account_state: dict) -> str:
+ payload = _payload(market="hk", account_state=account_state, from_date=_HK_DAY,
+ to_date=_HK_DAY, fee_model=dict(_HK_FEES),
+ orders=[{"symbol": "00700.HK", "side": "buy", "qty": 100}])
+ loader = FakeLoader({"00700.HK": _frame([(_HK_DAY, 417.8)])}, "tencent")
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+ assert "received_state_hash" in doc, doc
+ return doc["received_state_hash"]
+
+
+def test_added_account_state_key_changes_the_hash() -> None:
+ base = _hk_success_hash({"cash": 100000.0, "positions": []})
+ with_extra = _hk_success_hash({"cash": 100000.0, "positions": [], "note": "llm-added"})
+ assert base != with_extra # the raw value is hashed, not the parsed reconstruction
+
+
+def test_int_float_respelling_does_not_change_the_hash() -> None:
+ as_float = _hk_success_hash({"cash": 100000.0, "positions": []})
+ as_int = _hk_success_hash({"cash": 100000, "positions": []})
+ assert as_float == as_int # JCS number canonicalization (state_hash)
+
+
+# ── strategy_path routing into the lazily-imported T7 module ──
+
+
+def test_strategy_path_routes_to_run_strategy_path(monkeypatch: pytest.MonkeyPatch) -> None:
+ recorded: dict = {}
+
+ def _fake_run_strategy_path(**kwargs):
+ recorded.update(kwargs)
+ request = kwargs["request"]
+ return engine.MatchOutcome(
+ end_state=request.account_state,
+ effective_fee_model=state_hash.effective_fee_model(request.market, dict(request.fee_model)),
+ data_provenance=kwargs["market_data"].provenance,
+ )
+
+ universe_calls: list = []
+
+ def _fake_strategy_universe(path):
+ universe_calls.append(path)
+ return ()
+
+ fake_module = types.ModuleType("src.tools.paper_trade.strategy_exec")
+ fake_module.run_strategy_path = _fake_run_strategy_path
+ fake_module.strategy_universe = _fake_strategy_universe
+ monkeypatch.setitem(sys.modules, "src.tools.paper_trade.strategy_exec", fake_module)
+
+ payload = _payload(market="hk", orders=None, strategy_path="agent/strategies/x.py",
+ from_date=_HK_DAY, to_date=_HK_DAY, fee_model=dict(_HK_FEES),
+ account_state={"cash": 100000.0,
+ "positions": [{"symbol": "00700.HK", "qty": 100, "avg_cost": 400.0}]})
+ loader = FakeLoader({"00700.HK": _frame([(_HK_DAY, 417.8)])}, "tencent")
+ doc = json.loads(run_paper_trade_step(payload, loader=loader, timeout_seconds=12.5))
+
+ # The T7 seam receives exactly the contracted kwargs.
+ assert set(recorded) == {
+ "request", "market_data", "calendar_client", "limits_client",
+ "corporate_action_unresolved_by_day", "hk_lot_sizes", "timeout_seconds",
+ }
+ assert recorded["request"].strategy_path == "agent/strategies/x.py"
+ assert recorded["timeout_seconds"] == 12.5
+ assert recorded["calendar_client"] is None # hk zero-calendar (AM-6)
+ # The universe prefetch seam was consulted exactly once, with the request's
+ # strategy_path; a () declaration keeps the positions-only fetch universe.
+ assert universe_calls == ["agent/strategies/x.py"]
+ assert recorded["market_data"].symbols == ("00700.HK",)
+ # The fake outcome is assembled into the success document.
+ assert doc["tool"] == "paper_trade_step" and doc["market"] == "hk"
+ assert validate_payload(doc, load_contract_schema("result")) == []
+
+
+def test_orders_mode_never_consults_strategy_universe(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The UNIVERSE prefetch is strategy_path-mode ONLY: orders mode derives its
+ # universe from positions ∪ orders and must never touch the T7 module (the
+ # fake below lacks run_strategy_path entirely, so any import of it fails).
+ def _boom(path):
+ raise AssertionError("orders mode must not consult strategy_universe")
+
+ fake_module = types.ModuleType("src.tools.paper_trade.strategy_exec")
+ fake_module.strategy_universe = _boom
+ monkeypatch.setitem(sys.modules, "src.tools.paper_trade.strategy_exec", fake_module)
+
+ payload = _payload(market="hk", from_date=_HK_DAY, to_date=_HK_DAY,
+ fee_model=dict(_HK_FEES),
+ orders=[{"symbol": "00700.HK", "side": "buy", "qty": 100}])
+ loader = FakeLoader({"00700.HK": _frame([(_HK_DAY, 417.8)])}, "tencent")
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+ assert "status" not in doc # success document, not an error envelope
+ assert doc["fills"][0]["symbol"] == "00700.HK"
+
+
+# ── strategy_path end-to-end: declared UNIVERSE prefetch (T6×T7 integration) ──
+
+
+def _synth_frame() -> pd.DataFrame:
+ document = json.loads(_SYNTH_FIXTURE.read_text(encoding="utf-8"))
+ frame = pd.DataFrame(document["bars"])
+ frame["trade_date"] = pd.to_datetime(frame["date"])
+ return frame.set_index("trade_date")[["open", "high", "low", "close", "volume"]]
+
+
+def test_strategy_path_cash_only_account_fills_via_declared_universe() -> None:
+ # The end-to-end regression for the universe gap: a cash-only account (no
+ # positions) + strategy_path (no orders) prefetched an EMPTY universe, so
+ # the golden SMA strategy saw no symbols and the call "succeeded" with
+ # zero fills. The fixture's declared UNIVERSE = ("SYNTH-4TO1",) must
+ # reach the fetch universe through the real T6 → T7 → engine chain (no
+ # strategy_exec fake here; the child really spawns).
+ root = get_runtime_root() / "strategies"
+ root.mkdir(parents=True, exist_ok=True)
+ strategy = root / "golden_sample_sma.py"
+ strategy.write_text(_GOLDEN_STRATEGY.read_text(encoding="utf-8"), encoding="utf-8")
+
+ payload = _payload(
+ market="us", orders=None, strategy_path=str(strategy),
+ account_state={"cash": 50000.0, "positions": []},
+ from_date=_US_DAY, to_date=_US_DAY, fee_model=dict(_US_FEES),
+ )
+ loader = FakeLoader({"SYNTH-4TO1": _synth_frame()}, "sina")
+ doc = json.loads(run_paper_trade_step(payload, loader=loader))
+
+ assert "status" not in doc, doc # success document, not an error envelope
+ # Hand-computed us golden: close 128.5, fee max(100×0.0049, 0.99) = 0.99;
+ # cash 50000 − 12850.00 − 0.99 = 37099.01 (mirrors the direct T7 gate).
+ assert doc["fills"] == [{
+ "trade_date": _US_DAY, "symbol": "SYNTH-4TO1", "side": "buy",
+ "qty": 100.0, "price": 129.0, "fee": 0.99,
+ "reason": "golden sma5 127.5000 > sma20 123.7500",
+ }]
+ assert doc["end_state"]["cash"] == 37099.01
+ assert [(p["symbol"], p["qty"]) for p in doc["end_state"]["positions"]] == [
+ ("SYNTH-4TO1", 100.0)]
+ assert validate_payload(doc, load_contract_schema("result")) == []
+
+
+# ── the hand-written MCP wrapper (VD-12) ──
+
+
+def _mcp_wrapper():
+ import mcp_server
+
+ return mcp_server, (
+ getattr(mcp_server.paper_trade_step, "fn", None)
+ or getattr(mcp_server.paper_trade_step, "__wrapped__", mcp_server.paper_trade_step)
+ )
+
+
+def test_mcp_wrapper_builds_the_payload_and_delegates(monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: dict = {}
+
+ def _recorder(payload, **kwargs):
+ captured["payload"] = payload
+ captured["kwargs"] = kwargs
+ return "SENTINEL"
+
+ monkeypatch.setattr(tool_module, "run_paper_trade_step", _recorder)
+ _mcp_server, wrapper = _mcp_wrapper()
+ out = wrapper(
+ account_id="pa_mcp", market="hk",
+ account_state={"cash": 1.0, "positions": []},
+ from_date=_HK_DAY, to_date=_HK_DAY,
+ orders=[{"symbol": "00700.HK", "side": "buy", "qty": 100}],
+ fee_model={"commission_min": 3.0},
+ )
+ assert out == "SENTINEL"
+ payload = captured["payload"]
+ assert payload["account_id"] == "pa_mcp" and payload["market"] == "hk"
+ assert payload["orders"] == [{"symbol": "00700.HK", "side": "buy", "qty": 100}]
+ assert payload["fee_model"] == {"commission_min": 3.0}
+ # Optional keys absent from the call are absent from the payload (never null).
+ assert "strategy_path" not in payload
+
+
+def test_mcp_wrapper_omits_absent_optional_keys(monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: dict = {}
+
+ def _recorder(payload, **kwargs):
+ captured["payload"] = payload
+ return "X"
+
+ monkeypatch.setattr(tool_module, "run_paper_trade_step", _recorder)
+ _mcp_server, wrapper = _mcp_wrapper()
+ wrapper(account_id="a", market="us", account_state={"cash": 0.0, "positions": []},
+ from_date=_HK_DAY, to_date=_HK_DAY)
+ payload = captured["payload"]
+ assert "orders" not in payload and "strategy_path" not in payload and "fee_model" not in payload
+
+
+def test_mcp_wrapper_description_carries_the_frozen_phrase() -> None:
+ mcp_server, _wrapper = _mcp_wrapper()
+ phrase = "deterministic paper-trading matching engine; never places real orders"
+ assert phrase in (mcp_server.paper_trade_step.__doc__ or "")
+ assert phrase in PaperTradeStepTool.description
+
+
+def test_mcp_wrapper_end_to_end_matches_the_core_offline(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Drive the real wrapper → real core for hk, stubbing only the network leg.
+ from src.tools.paper_trade import data as data_layer
+
+ monkeypatch.setattr(data_layer, "_resolve_network_loader",
+ lambda *_a, **_k: FakeLoader({"00700.HK": _frame([(_HK_DAY, 417.8)])}, "tencent"))
+ _mcp_server, wrapper = _mcp_wrapper()
+ via_wrapper = wrapper(
+ account_id="pa_e2e", market="hk",
+ account_state={"cash": 100000.0, "positions": []},
+ from_date=_HK_DAY, to_date=_HK_DAY,
+ orders=[{"symbol": "00700.HK", "side": "buy", "qty": 100}],
+ fee_model=dict(_HK_FEES),
+ )
+ via_core = run_paper_trade_step(
+ {"account_id": "pa_e2e", "market": "hk",
+ "account_state": {"cash": 100000.0, "positions": []},
+ "from_date": _HK_DAY, "to_date": _HK_DAY,
+ "orders": [{"symbol": "00700.HK", "side": "buy", "qty": 100}],
+ "fee_model": dict(_HK_FEES)},
+ loader=FakeLoader({"00700.HK": _frame([(_HK_DAY, 417.8)])}, "tencent"),
+ )
+ assert via_wrapper == via_core
+ assert json.loads(via_wrapper)["fills"][0]["fee"] == 55.79 # hk golden cents
+
+
+# ── research-only red line (REQUIREMENTS R1) ──
+
+
+def test_tool_module_exposes_no_trading_connector_or_order_surface() -> None:
+ source = Path(tool_module.__file__).read_text(encoding="utf-8")
+ scoped = re.compile(r"trading_(account|orders|positions|quote|history|check|connections|select|place|cancel)")
+ assert not scoped.search(source)
+ assert "place_order" not in source and "cancel_order" not in source
+
+
+def test_tool_is_registered_readonly_and_available() -> None:
+ tool = PaperTradeStepTool()
+ assert tool.name == "paper_trade_step"
+ assert tool.is_readonly is True
+ assert tool.check_available() is True
+ assert tool.parameters["required"] == [
+ "account_id", "market", "account_state", "from_date", "to_date",
+ ]
+ assert set(tool.parameters["properties"]["market"]["enum"]) == set(MARKETS)
+
+
+def test_execute_delegates_the_kwargs_payload_to_the_core(monkeypatch: pytest.MonkeyPatch) -> None:
+ # execute() carries no injection seams, so stub the core to prove the
+ # BaseTool hands its kwargs through as the raw payload dict (offline).
+ captured: dict = {}
+
+ def _recorder(payload, **kwargs):
+ captured["payload"] = payload
+ return "DOC"
+
+ monkeypatch.setattr(tool_module, "run_paper_trade_step", _recorder)
+ out = PaperTradeStepTool().execute(
+ account_id="a", market="hk", account_state={"cash": 0.0, "positions": []},
+ from_date=_HK_DAY, to_date=_HK_DAY, orders=[],
+ )
+ assert out == "DOC"
+ assert captured["payload"]["account_id"] == "a"
+ assert captured["payload"]["market"] == "hk"
+ assert captured["payload"]["orders"] == []
diff --git a/agent/tests/test_paper_trade_validation.py b/agent/tests/test_paper_trade_validation.py
new file mode 100644
index 000000000..bcfaf43ed
--- /dev/null
+++ b/agent/tests/test_paper_trade_validation.py
@@ -0,0 +1,190 @@
+"""T12-gate orders-mode validation half (AM-3, Step 3 / T3).
+
+orders mode is single-day only: ``from_date != to_date`` → stable in-band
+``INVALID_REQUEST`` material (T6 maps it to the envelope) — no matching, no
+half-day. The strategy_path timeout half of T12 lands with T7 (B1 frozen
+message formats ``strategy_execution_timeout:{date}`` /
+``strategy_execution_error:{date}:{class}``); nothing here pre-empts it.
+Offline: fake clients only.
+"""
+
+from __future__ import annotations
+
+import pandas as pd
+import pytest
+
+from src.tools.paper_trade import engine
+from src.tools.paper_trade.data import fetch_market_data
+from src.tools.paper_trade.schema import ERROR_CODES, AccountState, Order, 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], name: str = "tencent") -> None:
+ self.name = name
+ self._frames = frames
+
+ def is_available(self) -> bool:
+ return True
+
+ def fetch(self, codes, start_date, end_date, *, interval="1D", fields=None):
+ return {c: self._frames[c] for c in codes if c 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 _cn_a_data(from_date: str = _DAY, to_date: str = _DAY):
+ frames = {_SYM: _frame([(_PREV, 10.0), (_DAY, 10.5)])}
+ return fetch_market_data("cn_a", [_SYM], from_date, to_date,
+ loader=FakeLoader(frames), ch_client=FakeChClient())
+
+
+def _request(from_date: str, to_date: str, orders: list[dict] | None, market: str = "cn_a"):
+ payload = {
+ "account_id": "pa_validation", "market": market,
+ "account_state": {"cash": 100000.0, "positions": []},
+ "from_date": from_date, "to_date": to_date, "fee_model": {},
+ }
+ if orders is not None:
+ payload["orders"] = orders
+ return parse_request(payload)
+
+
+_BUY = [{"symbol": _SYM, "side": "buy", "qty": 100}]
+
+
+def test_orders_mode_multi_day_range_is_invalid_request_material() -> None:
+ outcome = engine.match_orders(
+ _request(_PREV, _DAY, _BUY), market_data=_cn_a_data(_PREV, _DAY),
+ calendar_client=FakeCalendarClient(),
+ )
+ assert outcome.error is not None
+ assert outcome.error.code == "INVALID_REQUEST"
+ assert outcome.error.code in ERROR_CODES # frozen vocabulary member
+ assert "from_date == to_date" in outcome.error.message
+ assert f"from_date={_PREV}" in outcome.error.message and f"to_date={_DAY}" in outcome.error.message
+ # No matching, no half-day: every output array is empty, state untouched.
+ assert outcome.fills == () and outcome.rejected_orders == ()
+ assert outcome.nav_series == () and outcome.skipped_days == ()
+ assert outcome.end_state.cash == 100000.0
+
+
+def test_orders_mode_reversed_range_is_also_invalid_request() -> None:
+ outcome = engine.match_orders(
+ _request(_DAY, _PREV, _BUY), market_data=_cn_a_data(_PREV, _DAY),
+ calendar_client=FakeCalendarClient(),
+ )
+ assert outcome.error is not None and outcome.error.code == "INVALID_REQUEST"
+ assert outcome.nav_series == ()
+
+
+def test_missing_orders_array_is_invalid_request_and_names_the_t7_seam() -> None:
+ # strategy_path mode (orders=None) is not this entry's contract; the
+ # timeout/error half of T12 (B1 frozen messages) lands with T7.
+ outcome = engine.match_orders(
+ _request(_DAY, _DAY, None), market_data=_cn_a_data(),
+ calendar_client=FakeCalendarClient(),
+ )
+ assert outcome.error is not None and outcome.error.code == "INVALID_REQUEST"
+ assert "Step 7" in outcome.error.message
+ assert outcome.fills == () and outcome.nav_series == ()
+
+
+def test_cn_a_without_an_injected_calendar_client_fails_loud() -> None:
+ # AM-6: the CH calendar is the cn_a truth — a missing client is an engine
+ # wiring fault (transport class), never a silent weekday fallback.
+ with pytest.raises(ValueError, match="TradeCalendarClient"):
+ engine.match_orders(_request(_DAY, _DAY, _BUY), market_data=_cn_a_data())
+
+
+def test_market_mismatch_between_data_and_request_fails_loud() -> None:
+ with pytest.raises(ValueError, match="market_data was fetched for"):
+ engine.match_orders(_request(_DAY, _DAY, _BUY, market="hk"), market_data=_cn_a_data())
+
+
+def test_zero_order_pure_valuation_path_produces_a_cash_plus_position_nav() -> None:
+ # Empty orders array (NOT None) is the zero-order pure-valuation path:
+ # one nav row, no fills, position valued at the day's close.
+ request = parse_request({
+ "account_id": "pa_validation", "market": "cn_a",
+ "account_state": {"cash": 1000.0,
+ "positions": [{"symbol": _SYM, "qty": 100, "avg_cost": 9.0}]},
+ "orders": [], "from_date": _DAY, "to_date": _DAY, "fee_model": {},
+ })
+ outcome = engine.match_orders(request, market_data=_cn_a_data(),
+ calendar_client=FakeCalendarClient())
+ assert outcome.error is None
+ assert outcome.fills == () and outcome.rejected_orders == ()
+ assert outcome.nav_series[0].nav == 1000.0 + 100 * 10.5
+ assert outcome.end_state.positions[0].avg_cost == 9.0 # untouched
+
+
+def test_hk_needs_no_calendar_client_zero_calendar_by_design() -> None:
+ frames = {"00700.HK": _frame([(_PREV, 400.0), (_DAY, 417.8)])}
+ market_data = fetch_market_data("hk", ["00700.HK"], _DAY, _DAY, loader=FakeLoader(frames))
+ outcome = engine.match_orders(
+ _request(_DAY, _DAY, [{"symbol": "00700.HK", "side": "buy", "qty": 100}], market="hk"),
+ market_data=market_data,
+ )
+ assert outcome.error is None
+ assert len(outcome.fills) == 1 and outcome.fills[0].price == 417.8
+
+
+def test_run_day_loop_rejects_a_reversed_range_deterministically() -> None:
+ frames = {"00700.HK": _frame([(_DAY, 417.8)])}
+ market_data = fetch_market_data("hk", ["00700.HK"], _DAY, _DAY, loader=FakeLoader(frames))
+ with pytest.raises(ValueError, match="> to_date"):
+ engine.run_day_loop(
+ market="hk", account_state=AccountState(cash=1.0),
+ from_date=_DAY, to_date=_PREV,
+ orders_by_day={_DAY: (Order("00700.HK", "buy", 100),)},
+ market_data=market_data,
+ )
+
+
[email protected](("market", "symbol"), [("hk", "00700.HK"), ("us", "AAPL.US")])
+def test_zero_bar_target_day_returns_in_band_not_ready_never_a_raise(market: str, symbol: str) -> None:
+ # AM-9/AM-6① regression (orchestrator-found): the target day has only a
+ # prior-day bar, so the merged frame is all-market zero on the target —
+ # the readiness gate must return the in-band PAPER_DATA_NOT_READY
+ # material, never the transport-class RuntimeError the day-plan builder
+ # used to raise before the gate ran.
+ frames = {symbol: _frame([(_PREV, 100.0)])}
+ market_data = fetch_market_data(market, [symbol], _DAY, _DAY, loader=FakeLoader(frames))
+ outcome = engine.run_day_loop(
+ market=market, account_state=AccountState(cash=1000.0),
+ from_date=_DAY, to_date=_DAY, orders_by_day={}, market_data=market_data,
+ )
+ assert outcome.error is not None
+ assert outcome.error.code == "PAPER_DATA_NOT_READY"
+ assert outcome.error.code in ERROR_CODES
+ assert f"target bar {_DAY}" in outcome.error.message
+ assert outcome.fills == () and outcome.rejected_orders == ()
+ assert outcome.nav_series == () and outcome.skipped_days == ()
+ assert outcome.end_state.cash == 1000.0 # state untouched — no half-day
diff --git a/frontend/src/components/layout/__tests__/Navigation.test.tsx b/frontend/src/components/layout/__tests__/Navigation.test.tsx
index 5757e26e6..5a6bbbd66 100644
--- a/frontend/src/components/layout/__tests__/Navigation.test.tsx
+++ b/frontend/src/components/layout/__tests__/Navigation.test.tsx
@@ -13,7 +13,7 @@ function renderNavigation(path = "/", collapsed = false) {
it("keeps every feature directly reachable and distinguishes tasks from tools and setup", () => {
renderNavigation();
expect(within(screen.getByRole("region", { name: "Everyday research" })).getAllByRole("link").map((link) => link.getAttribute("href")))
- .toEqual(["/", "/reports", "/portfolio"]);
+ .toEqual(["/", "/reports", "/paper-trading", "/portfolio"]);
expect(within(screen.getByRole("region", { name: "Specialized analysis" })).getAllByRole("link").map((link) => link.getAttribute("href")))
.toEqual(["/alpha-zoo", "/options", "/correlation"]);
expect(within(screen.getByRole("region", { name: "Automation & setup" })).getAllByRole("link").map((link) => link.getAttribute("href")))
@@ -54,7 +54,7 @@ it("opens a labeled feature menu in compact mode and returns focus on Escape", (
expect(within(menu).getByText("Options analysis")).toBeVisible();
expect(within(menu).getByText("Pixel Office")).toBeVisible();
expect(within(menu).getByText("Trading status")).toBeVisible();
- expect(within(menu).getAllByRole("link")).toHaveLength(10);
+ expect(within(menu).getAllByRole("link")).toHaveLength(11);
fireEvent.keyDown(document, { key: "Escape" });
expect(screen.queryByRole("navigation", { name: "Browse features" })).not.toBeInTheDocument();
expect(trigger).toHaveFocus();
@@ -68,3 +68,12 @@ it("closes the feature menu after selecting a destination", () => {
expect(screen.queryByRole("navigation", { name: "Browse features" })).not.toBeInTheDocument();
expect(screen.getByText("How to use Backtest reports")).toBeInTheDocument();
});
+
+
+it("links paper accounts and explains completed-session simulation", () => {
+ renderNavigation("/paper-trading");
+ expect(screen.getByRole("link", { name: "Paper trading" })).toHaveAttribute("aria-current", "page");
+ fireEvent.click(screen.getByText("How to use Paper trading"));
+ expect(screen.getByText(/No broker orders are sent/)).toBeVisible();
+ expect(screen.getByText(/Only completed daily bars can settle/)).toBeVisible();
+});
diff --git a/frontend/src/components/layout/navigation.ts b/frontend/src/components/layout/navigation.ts
index baf65ab59..d3a417a13 100644
--- a/frontend/src/components/layout/navigation.ts
+++ b/frontend/src/components/layout/navigation.ts
@@ -1,9 +1,10 @@
-import { Building2, Activity, BarChart3, Bot, CalendarClock, CandlestickChart, FileText, Layers, Settings, WalletCards } from "lucide-react";
+import { FlaskConical, Building2, Activity, BarChart3, Bot, CalendarClock, CandlestickChart, FileText, Layers, Settings, WalletCards } from "lucide-react";
export const NAVIGATION_GROUPS = [
{ id: "research", items: [
{ id: "agent", to: "/", icon: Bot },
{ id: "reports", to: "/reports", icon: FileText },
+ { id: "paperTrading", to: "/paper-trading", icon: FlaskConical },
{ id: "portfolio", to: "/portfolio", icon: WalletCards },
] },
{ id: "analysis", items: [
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index d59c3bc82..d4ebfb6b3 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -22,7 +22,8 @@
"scheduled": "كرر مهمة بحثية وفق جدول زمني.",
"runtime": "تحقق من اتصالات الوسطاء وحالة تشغيل التداول.",
"settings": "اضبط النماذج ومصادر البيانات واتصالات الوسطاء.",
- "pixelOffice": "خطط لمهام البحث ووزعها. إسناد المهمة لا يبدأ تنفيذها؛ الرتب مجرد تسميات ولا تمنح صلاحيات تداول."
+ "pixelOffice": "خطط لمهام البحث ووزعها. إسناد المهمة لا يبدأ تنفيذها؛ الرتب مجرد تسميات ولا تمنح صلاحيات تداول.",
+ "paperTrading": "اختبر التداول اليومي بأموال افتراضية. لا تُرسل أوامر إلى الوسيط. النتائج تستثني التوزيعات النقدية ولا تمثل العائد الإجمالي."
},
"instructions": {
"reports": "اطلب أولاً من المساعد اختبار استراتيجية تاريخياً، ثم افتح نتائجها هنا. نزّل ملفات PDF والمستندات المنشأة في الدردشة من المحادثة الأصلية.",
@@ -33,7 +34,8 @@
"scheduled": "أدخل تعليمات البحث وتكراره واحفظها. يلزم تفعيل المجدول المحلي لتشغيل المهام، وإعداد قناة لإرسال النتائج.",
"runtime": "اضبط اتصال الوسيط أولاً في الإعدادات أو صفحة المحفظة. تعتمد عمليات التداول المتاحة على قدرات الوسيط والتفويض الذي تمنحه.",
"settings": "اضبط نموذجاً للبدء. أضف مصادر بيانات أو اتصالات وسطاء حسب المهمة؛ لا يحتاج بحث بيانات السوق العامة إلى حساب وسيط.",
- "pixelOffice": "خطط لمهام البحث ووزعها. إسناد المهمة لا يبدأ تنفيذها؛ الرتب مجرد تسميات ولا تمنح صلاحيات تداول."
+ "pixelOffice": "خطط لمهام البحث ووزعها. إسناد المهمة لا يبدأ تنفيذها؛ الرتب مجرد تسميات ولا تمنح صلاحيات تداول.",
+ "paperTrading": "تُستخدم الشموع اليومية المكتملة فقط. تقرأ الاستراتيجيات بيانات الأيام السابقة وتنفذ بسعر إغلاق يوم التنفيذ. انتظر 30 دقيقة بعد الإغلاق المعتاد؛ لا تُجدول أي عمليات تلقائية."
}
},
"layout": {
@@ -64,7 +66,8 @@
"mainNavigation": "التنقل الرئيسي",
"about": "حول",
"sessionsLoadFailed": "تعذر تحميل المحادثات.",
- "pixelOffice": "المكتب البكسلي"
+ "pixelOffice": "المكتب البكسلي",
+ "paperTrading": "التداول التجريبي"
},
"runtime": {
"monitorBadge": "مراقبة التداول",
@@ -2487,5 +2490,49 @@
"limitsNote": "يبدأ كل قرار محادثة جديدة. تُفحص الحدود بعد الرد وقد تتجاوزها تكلفة ذلك الرد. غياب الاستخدام أو تجاوز الميزانية يفعّل مفتاح الإيقاف الحالي.",
"pricesNote": "الأسعار تقديرات يحددها المشغّل. استخدم أعلى سعر للإدخال أو كتابة الذاكرة المؤقتة؛ لا يشمل التقدير خصوماتها أو استدعاءات النموذج المساعدة.",
"stopToEdit": "أوقف المشغّل قبل تعديل الإعدادات."
+ },
+ "paper": {
+ "title": "التداول التجريبي",
+ "description": "اختبر التداول اليومي بأموال افتراضية. لا تُرسل أوامر إلى الوسيط. النتائج تستثني التوزيعات النقدية ولا تمثل العائد الإجمالي.",
+ "accounts": "الحسابات",
+ "newAccount": "حساب تجريبي جديد",
+ "eligible": "يبدأ من {{date}}؛ تُنتظر الجلسة المتاحة التالية في أيام العطلات.",
+ "cash": "النقد",
+ "pending": "بانتظار التسوية الأولى",
+ "label": "اسم الحساب",
+ "market": "السوق",
+ "start": "البداية",
+ "today": "اليوم",
+ "nextSession": "جلسة التداول التالية",
+ "initialPositions": "المراكز الأولية (الكمية ومتوسط التكلفة)",
+ "symbol": "الرمز (مثل AAPL.US)",
+ "quantity": "الكمية",
+ "cost": "متوسط التكلفة",
+ "remove": "إزالة",
+ "addPosition": "إضافة مركز",
+ "create": "إنشاء حساب",
+ "working": "جارٍ التنفيذ…",
+ "advance": "تسوية الخطوة اليومية",
+ "executionNote": "تُستخدم الشموع اليومية المكتملة فقط. تقرأ الاستراتيجيات بيانات الأيام السابقة وتنفذ بسعر إغلاق يوم التنفيذ. انتظر 30 دقيقة بعد الإغلاق المعتاد؛ لا تُجدول أي عمليات تلقائية.",
+ "date": "تاريخ التنفيذ",
+ "mode": "طريقة الإدخال",
+ "orders": "أوامر محددة",
+ "strategy": "ملف استراتيجية",
+ "strategyPath": "مسار داخل مجلد strategies في بيئة التشغيل",
+ "side": "الاتجاه",
+ "buy": "شراء",
+ "sell": "بيع",
+ "addOrder": "إضافة أمر",
+ "emptyOrders": "بدون أوامر يُحسب التقييم فقط. تُنفذ أوامر السوق عند الإغلاق اليومي؛ هذه ليست محاكاة تنفيذ لحظي.",
+ "saved": "تم حفظ السجل.",
+ "notSaved": "لم يتغير السجل. راجع النتيجة قبل إعادة المحاولة.",
+ "result": "نتيجة الخطوة",
+ "price": "السعر",
+ "fee": "الرسوم",
+ "history": "سجل قيمة الحساب",
+ "nav": "صافي قيمة الأصول",
+ "us": "أسهم أمريكية · USD",
+ "hk": "أسهم هونغ كونغ · HKD",
+ "cn_a": "أسهم صينية A · CNY"
}
}
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 64e343daf..146ce62a0 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -28,7 +28,8 @@
"scheduled": "Eine Recherche nach Zeitplan wiederholen.",
"runtime": "Brokerverbindungen und den Betriebsstatus des Handels prüfen.",
"settings": "Modelle, Datenquellen und Brokerverbindungen konfigurieren.",
- "pixelOffice": "Plane und verteile Rechercheaufgaben. Eine Zuweisung startet keine Ausführung. Ränge sind Bezeichnungen und erteilen keine Handelsrechte."
+ "pixelOffice": "Plane und verteile Rechercheaufgaben. Eine Zuweisung startet keine Ausführung. Ränge sind Bezeichnungen und erteilen keine Handelsrechte.",
+ "paperTrading": "Tägliche Trades mit virtuellem Kapital testen. Es werden keine Brokeraufträge gesendet. Bardividenden sind nicht enthalten; die Ergebnisse zeigen keine Gesamtrendite."
},
"instructions": {
"reports": "Bitte den Assistenten zuerst um einen Strategie-Backtest und öffne hier die Ergebnisse. Im Chat erstellte PDFs und andere Dokumente lädst du in der ursprünglichen Unterhaltung herunter.",
@@ -39,7 +40,8 @@
"scheduled": "Gib einen Rechercheauftrag ein, wähle die Häufigkeit und speichere. Für die Ausführung muss der lokale Planer aktiviert sein; zur Zustellung ist ein eingerichteter Kanal nötig.",
"runtime": "Richte zuerst unter Einstellungen oder Portfolio eine Brokerverbindung ein. Verfügbare Handelsaktionen hängen von den Brokerfunktionen und deiner Autorisierung ab.",
"settings": "Richte zunächst ein Modell ein. Ergänze Datenquellen oder Brokerverbindungen nach Bedarf; für öffentliche Marktrecherche ist kein Brokerkonto nötig.",
- "pixelOffice": "Plane und verteile Rechercheaufgaben. Eine Zuweisung startet keine Ausführung. Ränge sind Bezeichnungen und erteilen keine Handelsrechte."
+ "pixelOffice": "Plane und verteile Rechercheaufgaben. Eine Zuweisung startet keine Ausführung. Ränge sind Bezeichnungen und erteilen keine Handelsrechte.",
+ "paperTrading": "Nur abgeschlossene Tageskerzen werden abgerechnet. Strategien sehen vorherige Tage und handeln zum Schlusskurs des Ausführungstags. Bitte 30 Minuten nach regulärem Börsenschluss warten; es wird keine automatische Ausführung geplant."
}
},
"layout": {
@@ -70,7 +72,8 @@
"about": "Über",
"portfolio": "Kontopositionen",
"sessionsLoadFailed": "Gespräche können nicht geladen werden.",
- "pixelOffice": "Pixelbüro"
+ "pixelOffice": "Pixelbüro",
+ "paperTrading": "Simulierter Handel"
},
"runtime": {
"monitorBadge": "Runtime-Monitor",
@@ -2487,5 +2490,49 @@
"limitsNote": "Jede Entscheidung beginnt eine neue Unterhaltung. Limits werden nach der Antwort geprüft und können um diese Antwort überschritten werden. Fehlender Verbrauch oder eine Überschreitung löst den vorhandenen Notstopp aus.",
"pricesNote": "Preise sind Betreiberschätzungen. Den höchsten Eingabe-/Cache-Schreibpreis verwenden; Cache-Rabatte und zusätzliche Modellaufrufe sind nicht enthalten.",
"stopToEdit": "Vor Änderungen den Runner stoppen."
+ },
+ "paper": {
+ "title": "Simulierter Handel",
+ "description": "Tägliche Trades mit virtuellem Kapital testen. Es werden keine Brokeraufträge gesendet. Bardividenden sind nicht enthalten; die Ergebnisse zeigen keine Gesamtrendite.",
+ "accounts": "Konten",
+ "newAccount": "Neues Simulationskonto",
+ "eligible": "Ab {{date}} möglich; an Feiertagen wird auf die nächste verfügbare Sitzung gewartet.",
+ "cash": "Bargeld",
+ "pending": "Erste Abrechnung ausstehend",
+ "label": "Kontoname",
+ "market": "Markt",
+ "start": "Beginn",
+ "today": "Heute",
+ "nextSession": "Nächster Handelstag",
+ "initialPositions": "Anfangspositionen (Menge und Durchschnittskosten)",
+ "symbol": "Symbol (z. B. AAPL.US)",
+ "quantity": "Menge",
+ "cost": "Durchschnittskosten",
+ "remove": "Entfernen",
+ "addPosition": "Position hinzufügen",
+ "create": "Konto erstellen",
+ "working": "Wird verarbeitet…",
+ "advance": "Tagesschritt abrechnen",
+ "executionNote": "Nur abgeschlossene Tageskerzen werden abgerechnet. Strategien sehen vorherige Tage und handeln zum Schlusskurs des Ausführungstags. Bitte 30 Minuten nach regulärem Börsenschluss warten; es wird keine automatische Ausführung geplant.",
+ "date": "Ausführungsdatum",
+ "mode": "Eingabemodus",
+ "orders": "Explizite Aufträge",
+ "strategy": "Strategiedatei",
+ "strategyPath": "Pfad im strategies-Ordner der Laufzeitumgebung",
+ "side": "Richtung",
+ "buy": "Kaufen",
+ "sell": "Verkaufen",
+ "addOrder": "Auftrag hinzufügen",
+ "emptyOrders": "Ohne Aufträge wird nur bewertet. Marktaufträge werden zum Tagesschluss ausgeführt; keine Intraday-Simulation.",
+ "saved": "Kontobuch gespeichert.",
+ "notSaved": "Kontobuch unverändert. Ergebnis vor erneutem Versuch prüfen.",
+ "result": "Schrittergebnis",
+ "price": "Preis",
+ "fee": "Gebühr",
+ "history": "Kontowertverlauf",
+ "nav": "Nettovermögenswert",
+ "us": "US-Aktien · USD",
+ "hk": "Hongkong-Aktien · HKD",
+ "cn_a": "Chinesische A-Aktien · CNY"
}
}
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 76328abca..4e0182f21 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -28,7 +28,8 @@
"scheduled": "Repeat a research task on a schedule.",
"runtime": "Check broker connections and trading runtime status.",
"settings": "Configure models, data sources, and broker connections.",
- "pixelOffice": "Plan and assign research tasks. Assignment does not start execution; ranks are labels and grant no trading permissions."
+ "pixelOffice": "Plan and assign research tasks. Assignment does not start execution; ranks are labels and grant no trading permissions.",
+ "paperTrading": "Test daily trades with simulated funds. No broker orders are sent. Results exclude cash dividends and are not a total-return record."
},
"instructions": {
"reports": "Ask the research assistant to backtest a strategy first, then open its results here. Download PDFs and other chat-generated documents from the original conversation.",
@@ -39,7 +40,8 @@
"scheduled": "Enter a research instruction, choose its cadence, and save. The local scheduler must be enabled for jobs to run; delivery also needs a configured channel.",
"runtime": "Configure a broker connection in Settings or Portfolio first. Available trading actions depend on that broker's capabilities and your authorization.",
"settings": "Configure a model to start. Add data sources or broker connections as your task needs them; public-market research does not require a broker account.",
- "pixelOffice": "Plan and assign research tasks. Assignment does not start execution; ranks are labels and grant no trading permissions."
+ "pixelOffice": "Plan and assign research tasks. Assignment does not start execution; ranks are labels and grant no trading permissions.",
+ "paperTrading": "Only completed daily bars can settle. Strategies see prior days only and fill at the execution day’s close. Wait until 30 minutes after the regular market close; no background execution is scheduled."
}
},
"layout": {
@@ -70,7 +72,8 @@
"mainNavigation": "Main navigation",
"about": "About",
"sessionsLoadFailed": "Cannot load conversations.",
- "pixelOffice": "Pixel Office"
+ "pixelOffice": "Pixel Office",
+ "paperTrading": "Paper trading"
},
"runtime": {
"monitorBadge": "Runtime Monitor",
@@ -2487,5 +2490,49 @@
"limitsNote": "Each decision starts a fresh conversation. Usage limits stop after a response and may overshoot by that response. Missing usage or an exceeded budget trips the existing kill switch.",
"pricesNote": "Prices are operator estimates. Use the highest applicable input/cache-write rate; cache discounts and auxiliary model calls are not included in the estimate.",
"stopToEdit": "Stop the runner before editing these settings."
+ },
+ "paper": {
+ "title": "Paper trading",
+ "description": "Test daily trades with simulated funds. No broker orders are sent. Results exclude cash dividends and are not a total-return record.",
+ "accounts": "Accounts",
+ "newAccount": "New paper account",
+ "eligible": "Eligible from {{date}}; holidays wait for the next available session.",
+ "cash": "Cash",
+ "pending": "Awaiting first session",
+ "label": "Account name",
+ "market": "Market",
+ "start": "Start",
+ "today": "Today",
+ "nextSession": "Next trading session",
+ "initialPositions": "Initial positions (quantity and average cost)",
+ "symbol": "Symbol (e.g. AAPL.US)",
+ "quantity": "Quantity",
+ "cost": "Average cost",
+ "remove": "Remove",
+ "addPosition": "Add position",
+ "create": "Create account",
+ "working": "Working…",
+ "advance": "Settle daily step",
+ "executionNote": "Only completed daily bars can settle. Strategies see prior days only and fill at the execution day’s close. Wait until 30 minutes after the regular market close; no background execution is scheduled.",
+ "date": "Execution date",
+ "mode": "Input mode",
+ "orders": "Explicit orders",
+ "strategy": "Strategy file",
+ "strategyPath": "Path within your runtime strategies folder",
+ "side": "Side",
+ "buy": "Buy",
+ "sell": "Sell",
+ "addOrder": "Add order",
+ "emptyOrders": "No orders means valuation only. Market orders fill at the daily close; this is not an intraday execution simulator.",
+ "saved": "Ledger saved.",
+ "notSaved": "No ledger change. Review the result before retrying.",
+ "result": "Step result",
+ "price": "Price",
+ "fee": "Fee",
+ "history": "Account value history",
+ "nav": "Net asset value",
+ "us": "US equities · USD",
+ "hk": "Hong Kong equities · HKD",
+ "cn_a": "A-shares · CNY"
}
}
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index d747beeb6..52b59303f 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -28,7 +28,8 @@
"scheduled": "Repite una investigación según un horario.",
"runtime": "Comprueba conexiones de brókeres y el estado de ejecución de operaciones.",
"settings": "Configura modelos, fuentes de datos y conexiones de brókeres.",
- "pixelOffice": "Planifica y asigna tareas de investigación. La asignación no inicia la ejecución; los rangos son etiquetas y no conceden permisos de negociación."
+ "pixelOffice": "Planifica y asigna tareas de investigación. La asignación no inicia la ejecución; los rangos son etiquetas y no conceden permisos de negociación.",
+ "paperTrading": "Prueba operaciones diarias con fondos ficticios. No se envían órdenes al bróker. Los resultados excluyen dividendos en efectivo y no representan la rentabilidad total."
},
"instructions": {
"reports": "Primero pide al asistente un backtest de una estrategia y abre aquí sus resultados. Descarga los PDF y documentos generados en el chat desde la conversación original.",
@@ -39,7 +40,8 @@
"scheduled": "Introduce la instrucción de investigación, elige la frecuencia y guarda. El programador local debe estar activado para ejecutar tareas; el envío requiere un canal configurado.",
"runtime": "Primero configura una conexión de bróker en Ajustes o Cartera. Las operaciones disponibles dependen de sus capacidades y de tu autorización.",
"settings": "Configura un modelo para empezar. Añade datos o conexiones de brókeres según lo necesites; investigar datos públicos de mercado no requiere una cuenta de bróker.",
- "pixelOffice": "Planifica y asigna tareas de investigación. La asignación no inicia la ejecución; los rangos son etiquetas y no conceden permisos de negociación."
+ "pixelOffice": "Planifica y asigna tareas de investigación. La asignación no inicia la ejecución; los rangos son etiquetas y no conceden permisos de negociación.",
+ "paperTrading": "Solo se liquidan velas diarias completas. Las estrategias leen días anteriores y ejecutan al cierre del día indicado. Espera 30 minutos tras el cierre habitual; no se programa ejecución automática."
}
},
"layout": {
@@ -70,7 +72,8 @@
"mainNavigation": "Navegación principal",
"about": "Acerca de",
"sessionsLoadFailed": "No se pueden cargar las conversaciones.",
- "pixelOffice": "Oficina de píxeles"
+ "pixelOffice": "Oficina de píxeles",
+ "paperTrading": "Trading simulado"
},
"runtime": {
"monitorBadge": "Monitor de Runtime",
@@ -2487,5 +2490,49 @@
"limitsNote": "Cada decisión usa una conversación nueva. Los límites se comprueban tras la respuesta y pueden excederse en ese importe. El uso desconocido o un exceso activa el interruptor de parada existente.",
"pricesNote": "Las tarifas son estimaciones del operador. Use la mayor tarifa de entrada/escritura en caché; se excluyen los descuentos de caché y las llamadas auxiliares.",
"stopToEdit": "Detenga el ejecutor antes de cambiar estos ajustes."
+ },
+ "paper": {
+ "title": "Trading simulado",
+ "description": "Prueba operaciones diarias con fondos ficticios. No se envían órdenes al bróker. Los resultados excluyen dividendos en efectivo y no representan la rentabilidad total.",
+ "accounts": "Cuentas",
+ "newAccount": "Nueva cuenta simulada",
+ "eligible": "Disponible desde {{date}}; los festivos esperan a la siguiente sesión disponible.",
+ "cash": "Efectivo",
+ "pending": "Pendiente de la primera liquidación",
+ "label": "Nombre de la cuenta",
+ "market": "Mercado",
+ "start": "Inicio",
+ "today": "Hoy",
+ "nextSession": "Próxima sesión bursátil",
+ "initialPositions": "Posiciones iniciales (cantidad y coste medio)",
+ "symbol": "Símbolo (p. ej. AAPL.US)",
+ "quantity": "Cantidad",
+ "cost": "Coste medio",
+ "remove": "Eliminar",
+ "addPosition": "Añadir posición",
+ "create": "Crear cuenta",
+ "working": "Procesando…",
+ "advance": "Liquidar paso diario",
+ "executionNote": "Solo se liquidan velas diarias completas. Las estrategias leen días anteriores y ejecutan al cierre del día indicado. Espera 30 minutos tras el cierre habitual; no se programa ejecución automática.",
+ "date": "Fecha de ejecución",
+ "mode": "Modo de entrada",
+ "orders": "Órdenes explícitas",
+ "strategy": "Archivo de estrategia",
+ "strategyPath": "Ruta dentro de la carpeta strategies del entorno",
+ "side": "Lado",
+ "buy": "Comprar",
+ "sell": "Vender",
+ "addOrder": "Añadir orden",
+ "emptyOrders": "Sin órdenes, solo se valora la cuenta. Las órdenes de mercado se ejecutan al cierre diario; no se simula la ejecución intradía.",
+ "saved": "Libro guardado.",
+ "notSaved": "El libro no cambió. Revisa el resultado antes de reintentar.",
+ "result": "Resultado del paso",
+ "price": "Precio",
+ "fee": "Comisión",
+ "history": "Historial del valor de la cuenta",
+ "nav": "Valor liquidativo",
+ "us": "Acciones de EE. UU. · USD",
+ "hk": "Acciones de Hong Kong · HKD",
+ "cn_a": "Acciones A de China · CNY"
}
}
diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.json
index 3228c8f6b..e4ae08961 100644
--- a/frontend/src/i18n/locales/fa.json
+++ b/frontend/src/i18n/locales/fa.json
@@ -28,7 +28,8 @@
"scheduled": "یک کار پژوهشی را طبق زمان‌بندی تکرار کنید.",
"runtime": "اتصال کارگزاران و وضعیت اجرای معاملات را بررسی کنید.",
"settings": "مدل‌ها، منابع داده و اتصال کارگزاران را تنظیم کنید.",
- "pixelOffice": "کارهای پژوهشی را برنامه‌ریزی و واگذار کنید. واگذاری باعث شروع اجرا نمی‌شود؛ رتبه‌ها فقط برچسب هستند و مجوز معامله نمی‌دهند."
+ "pixelOffice": "کارهای پژوهشی را برنامه‌ریزی و واگذار کنید. واگذاری باعث شروع اجرا نمی‌شود؛ رتبه‌ها فقط برچسب هستند و مجوز معامله نمی‌دهند.",
+ "paperTrading": "معاملات روزانه را با سرمایهٔ مجازی آزمایش کنید. سفارشی به کارگزار ارسال نمی‌شود. نتایج شامل سود نقدی نیست و بازده کل را نشان نمی‌دهد."
},
"instructions": {
"reports": "ابتدا از دستیار پژوهش بخواهید راهبردی را پس‌آزمایی کند، سپس نتیجه را اینجا باز کنید. PDFها و سایر اسناد ساخته‌شده در گفتگو را از همان گفتگو دریافت کنید.",
@@ -39,7 +40,8 @@
"scheduled": "دستور پژوهش و تناوب اجرا را وارد و ذخیره کنید. زمان‌بند محلی باید برای اجرای کار فعال باشد؛ ارسال نیز به کانال تنظیم‌شده نیاز دارد.",
"runtime": "ابتدا در تنظیمات یا سبد دارایی یک اتصال کارگزاری بسازید. عملیات قابل استفاده به قابلیت‌های کارگزار و مجوز شما بستگی دارد.",
"settings": "برای شروع یک مدل تنظیم کنید. منابع داده یا اتصال کارگزاران را بر اساس نیاز اضافه کنید؛ پژوهش با داده‌های عمومی به حساب کارگزاری نیاز ندارد.",
- "pixelOffice": "کارهای پژوهشی را برنامه‌ریزی و واگذار کنید. واگذاری باعث شروع اجرا نمی‌شود؛ رتبه‌ها فقط برچسب هستند و مجوز معامله نمی‌دهند."
+ "pixelOffice": "کارهای پژوهشی را برنامه‌ریزی و واگذار کنید. واگذاری باعث شروع اجرا نمی‌شود؛ رتبه‌ها فقط برچسب هستند و مجوز معامله نمی‌دهند.",
+ "paperTrading": "فقط کندل‌های روزانهٔ تکمیل‌شده تسویه می‌شوند. راهبرد داده‌های روزهای قبل را می‌بیند و با قیمت پایانی روز اجرا معامله می‌کند. تا ۳۰ دقیقه پس از پایان عادی بازار صبر کنید؛ اجرای خودکار زمان‌بندی نمی‌شود."
}
},
"layout": {
@@ -70,7 +72,8 @@
"mainNavigation": "ناوبری اصلی",
"about": "درباره",
"sessionsLoadFailed": "گفتگوها بارگذاری نمی‌شوند.",
- "pixelOffice": "دفتر پیکسلی"
+ "pixelOffice": "دفتر پیکسلی",
+ "paperTrading": "معاملهٔ آزمایشی"
},
"runtime": {
"monitorBadge": "مانیتور ران‌تایم",
@@ -2487,5 +2490,49 @@
"limitsNote": "هر تصمیم گفت‌وگوی تازه‌ای آغاز می‌کند. سقف‌ها پس از پاسخ بررسی می‌شوند و ممکن است به اندازه آن پاسخ عبور کنند. نبود آمار مصرف یا عبور از بودجه کلید توقف موجود را فعال می‌کند.",
"pricesNote": "نرخ‌ها برآورد اپراتورند. بالاترین نرخ ورودی/نوشتن حافظه نهان را وارد کنید؛ تخفیف حافظه نهان و فراخوانی‌های کمکی محاسبه نمی‌شوند.",
"stopToEdit": "پیش از تغییر تنظیمات اجراکننده را متوقف کنید."
+ },
+ "paper": {
+ "title": "معاملهٔ آزمایشی",
+ "description": "معاملات روزانه را با سرمایهٔ مجازی آزمایش کنید. سفارشی به کارگزار ارسال نمی‌شود. نتایج شامل سود نقدی نیست و بازده کل را نشان نمی‌دهد.",
+ "accounts": "حساب‌ها",
+ "newAccount": "حساب آزمایشی جدید",
+ "eligible": "شروع از {{date}}؛ در تعطیلات تا جلسهٔ معاملاتی بعدی منتظر می‌ماند.",
+ "cash": "وجه نقد",
+ "pending": "در انتظار نخستین تسویه",
+ "label": "نام حساب",
+ "market": "بازار",
+ "start": "شروع",
+ "today": "امروز",
+ "nextSession": "جلسهٔ معاملاتی بعدی",
+ "initialPositions": "دارایی‌های اولیه (تعداد و میانگین بهای خرید)",
+ "symbol": "نماد (مانند AAPL.US)",
+ "quantity": "تعداد",
+ "cost": "میانگین بهای خرید",
+ "remove": "حذف",
+ "addPosition": "افزودن دارایی",
+ "create": "ایجاد حساب",
+ "working": "در حال پردازش…",
+ "advance": "تسویهٔ گام روزانه",
+ "executionNote": "فقط کندل‌های روزانهٔ تکمیل‌شده تسویه می‌شوند. راهبرد داده‌های روزهای قبل را می‌بیند و با قیمت پایانی روز اجرا معامله می‌کند. تا ۳۰ دقیقه پس از پایان عادی بازار صبر کنید؛ اجرای خودکار زمان‌بندی نمی‌شود.",
+ "date": "تاریخ اجرا",
+ "mode": "روش ورود",
+ "orders": "سفارش‌های مشخص",
+ "strategy": "فایل راهبرد",
+ "strategyPath": "مسیر در پوشهٔ strategies محیط اجرا",
+ "side": "جهت",
+ "buy": "خرید",
+ "sell": "فروش",
+ "addOrder": "افزودن سفارش",
+ "emptyOrders": "بدون سفارش فقط ارزش‌گذاری انجام می‌شود. سفارش بازار با قیمت پایانی روز اجرا می‌شود؛ اجرای درون‌روزی شبیه‌سازی نمی‌شود.",
+ "saved": "دفتر حساب ذخیره شد.",
+ "notSaved": "دفتر حساب تغییر نکرد. پیش از تلاش مجدد نتیجه را بررسی کنید.",
+ "result": "نتیجهٔ گام",
+ "price": "قیمت",
+ "fee": "کارمزد",
+ "history": "تاریخچهٔ ارزش حساب",
+ "nav": "خالص ارزش دارایی",
+ "us": "سهام آمریکا · USD",
+ "hk": "سهام هنگ‌کنگ · HKD",
+ "cn_a": "سهام A چین · CNY"
}
}
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 5daf85376..849b414fe 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -28,7 +28,8 @@
"scheduled": "Ulangi tugas riset sesuai jadwal.",
"runtime": "Periksa koneksi broker dan status pelaksanaan perdagangan.",
"settings": "Atur model, sumber data, dan koneksi broker.",
- "pixelOffice": "Rencanakan dan tugaskan riset. Penugasan tidak memulai eksekusi; pangkat hanya label dan tidak memberikan izin transaksi."
+ "pixelOffice": "Rencanakan dan tugaskan riset. Penugasan tidak memulai eksekusi; pangkat hanya label dan tidak memberikan izin transaksi.",
+ "paperTrading": "Uji transaksi harian dengan dana virtual. Tidak ada pesanan yang dikirim ke broker. Hasil tidak mencakup dividen tunai dan bukan imbal hasil total."
},
"instructions": {
"reports": "Minta asisten melakukan backtest strategi terlebih dahulu, lalu buka hasilnya di sini. Unduh PDF dan dokumen yang dibuat di chat dari percakapan asal.",
@@ -39,7 +40,8 @@
"scheduled": "Isi instruksi riset, pilih frekuensi, dan simpan. Penjadwal lokal harus diaktifkan agar tugas berjalan; pengiriman juga memerlukan kanal yang telah diatur.",
"runtime": "Atur koneksi broker di Pengaturan atau Portofolio terlebih dahulu. Tindakan perdagangan yang tersedia bergantung pada kemampuan broker dan otorisasi Anda.",
"settings": "Atur model untuk memulai. Tambahkan data atau koneksi broker sesuai kebutuhan; riset data pasar publik tidak memerlukan akun broker.",
- "pixelOffice": "Rencanakan dan tugaskan riset. Penugasan tidak memulai eksekusi; pangkat hanya label dan tidak memberikan izin transaksi."
+ "pixelOffice": "Rencanakan dan tugaskan riset. Penugasan tidak memulai eksekusi; pangkat hanya label dan tidak memberikan izin transaksi.",
+ "paperTrading": "Hanya candle harian yang selesai dapat diproses. Strategi membaca hari sebelumnya dan dieksekusi pada penutupan hari eksekusi. Tunggu 30 menit setelah penutupan reguler; tidak ada eksekusi otomatis yang dijadwalkan."
}
},
"layout": {
@@ -70,7 +72,8 @@
"mainNavigation": "Navigasi utama",
"about": "Tentang",
"sessionsLoadFailed": "Percakapan tidak dapat dimuat.",
- "pixelOffice": "Kantor piksel"
+ "pixelOffice": "Kantor piksel",
+ "paperTrading": "Trading simulasi"
},
"runtime": {
"monitorBadge": "Monitor Runtime",
@@ -2487,5 +2490,49 @@
"limitsNote": "Setiap keputusan memakai percakapan baru. Batas diperiksa setelah respons dan dapat terlampaui sebesar respons itu. Penggunaan yang hilang atau anggaran terlampaui memicu sakelar penghentian yang ada.",
"pricesNote": "Harga adalah perkiraan operator. Gunakan tarif masukan/penulisan cache tertinggi; diskon cache dan panggilan tambahan tidak termasuk.",
"stopToEdit": "Hentikan runner sebelum mengubah pengaturan."
+ },
+ "paper": {
+ "title": "Trading simulasi",
+ "description": "Uji transaksi harian dengan dana virtual. Tidak ada pesanan yang dikirim ke broker. Hasil tidak mencakup dividen tunai dan bukan imbal hasil total.",
+ "accounts": "Akun",
+ "newAccount": "Akun simulasi baru",
+ "eligible": "Mulai paling awal {{date}}; hari libur menunggu sesi berikutnya yang tersedia.",
+ "cash": "Kas",
+ "pending": "Menunggu penyelesaian pertama",
+ "label": "Nama akun",
+ "market": "Pasar",
+ "start": "Mulai",
+ "today": "Hari ini",
+ "nextSession": "Sesi perdagangan berikutnya",
+ "initialPositions": "Posisi awal (jumlah dan biaya rata-rata)",
+ "symbol": "Simbol (mis. AAPL.US)",
+ "quantity": "Jumlah",
+ "cost": "Biaya rata-rata",
+ "remove": "Hapus",
+ "addPosition": "Tambah posisi",
+ "create": "Buat akun",
+ "working": "Memproses…",
+ "advance": "Selesaikan langkah harian",
+ "executionNote": "Hanya candle harian yang selesai dapat diproses. Strategi membaca hari sebelumnya dan dieksekusi pada penutupan hari eksekusi. Tunggu 30 menit setelah penutupan reguler; tidak ada eksekusi otomatis yang dijadwalkan.",
+ "date": "Tanggal eksekusi",
+ "mode": "Mode masukan",
+ "orders": "Pesanan langsung",
+ "strategy": "Berkas strategi",
+ "strategyPath": "Jalur dalam folder strategies lingkungan runtime",
+ "side": "Sisi",
+ "buy": "Beli",
+ "sell": "Jual",
+ "addOrder": "Tambah pesanan",
+ "emptyOrders": "Tanpa pesanan, hanya valuasi. Pesanan pasar dieksekusi pada penutupan harian; bukan simulasi intrahari.",
+ "saved": "Buku akun tersimpan.",
+ "notSaved": "Buku akun tidak berubah. Tinjau hasil sebelum mencoba lagi.",
+ "result": "Hasil langkah",
+ "price": "Harga",
+ "fee": "Biaya",
+ "history": "Riwayat nilai akun",
+ "nav": "Nilai aset bersih",
+ "us": "Saham AS · USD",
+ "hk": "Saham Hong Kong · HKD",
+ "cn_a": "Saham A Tiongkok · CNY"
}
}
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 507f74e13..c23c75d11 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -22,7 +22,8 @@
"scheduled": "リサーチを指定した周期で繰り返します。",
"runtime": "ブローカーの接続と取引の稼働状況を確認します。",
"settings": "モデル、データソース、ブローカー接続を設定します。",
- "pixelOffice": "調査タスクを計画・割り当てます。割り当てでは実行は始まりません。役職はラベルであり、取引権限を付与しません。"
+ "pixelOffice": "調査タスクを計画・割り当てます。割り当てでは実行は始まりません。役職はラベルであり、取引権限を付与しません。",
+ "paperTrading": "仮想資金で日次取引を検証します。証券会社へ注文は送りません。現金配当を含まず、総収益ではありません。"
},
"instructions": {
"reports": "まずアシスタントに戦略のバックテストを依頼し、ここで結果を開きます。会話で作成した PDF などは元の会話からダウンロードします。",
@@ -33,7 +34,8 @@
"scheduled": "リサーチ指示と周期を入力して保存します。実行にはローカルのスケジューラーを有効にする必要があり、配信にはチャネル設定も必要です。",
"runtime": "先に設定または保有資産ページでブローカーを接続します。利用できる取引操作はブローカーの機能とあなたの許可に依存します。",
"settings": "まずモデルを設定します。必要に応じてデータソースやブローカー接続を追加します。公開市場のリサーチにはブローカー口座は不要です。",
- "pixelOffice": "調査タスクを計画・割り当てます。割り当てでは実行は始まりません。役職はラベルであり、取引権限を付与しません。"
+ "pixelOffice": "調査タスクを計画・割り当てます。割り当てでは実行は始まりません。役職はラベルであり、取引権限を付与しません。",
+ "paperTrading": "確定した日足のみを使用します。戦略は前日までのデータを読み、執行日の終値で約定します。通常の取引終了から30分お待ちください。自動実行は設定されません。"
}
},
"layout": {
@@ -64,7 +66,8 @@
"mainNavigation": "メインナビゲーション",
"about": "概要",
"sessionsLoadFailed": "会話を読み込めません。",
- "pixelOffice": "ピクセルオフィス"
+ "pixelOffice": "ピクセルオフィス",
+ "paperTrading": "模擬取引"
},
"runtime": {
"monitorBadge": "取引モニター",
@@ -2487,5 +2490,49 @@
"limitsNote": "判断ごとに新しい会話を使います。応答後に上限を確認するため、その応答分を超過する場合があります。使用量不明や超過時は既存の停止スイッチが作動します。",
"pricesNote": "料金は利用者が設定する推定値です。入力・キャッシュ書込の最高料金を使ってください。キャッシュ割引と補助モデル呼び出しは推定に含みません。",
"stopToEdit": "変更する前にランナーを停止してください。"
+ },
+ "paper": {
+ "title": "模擬取引",
+ "description": "仮想資金で日次取引を検証します。証券会社へ注文は送りません。現金配当を含まず、総収益ではありません。",
+ "accounts": "口座",
+ "newAccount": "模擬口座を作成",
+ "eligible": "{{date}} 以降に開始。休場日は次の利用可能な取引日を待ちます。",
+ "cash": "現金",
+ "pending": "初回の決済待ち",
+ "label": "口座名",
+ "market": "市場",
+ "start": "開始",
+ "today": "今日",
+ "nextSession": "次の取引日",
+ "initialPositions": "初期保有(数量と平均取得価格)",
+ "symbol": "銘柄(例 AAPL.US)",
+ "quantity": "数量",
+ "cost": "平均取得価格",
+ "remove": "削除",
+ "addPosition": "保有を追加",
+ "create": "口座を作成",
+ "working": "処理中…",
+ "advance": "日次取引を決済",
+ "executionNote": "確定した日足のみを使用します。戦略は前日までのデータを読み、執行日の終値で約定します。通常の取引終了から30分お待ちください。自動実行は設定されません。",
+ "date": "執行日",
+ "mode": "入力方法",
+ "orders": "注文を指定",
+ "strategy": "戦略ファイル",
+ "strategyPath": "実行環境の strategies フォルダー内のパス",
+ "side": "売買",
+ "buy": "買い",
+ "sell": "売り",
+ "addOrder": "注文を追加",
+ "emptyOrders": "注文がなければ評価のみ。成行注文は日次終値で約定し、日中の執行は再現しません。",
+ "saved": "台帳を保存しました。",
+ "notSaved": "台帳は変更されていません。結果を確認して再試行してください。",
+ "result": "実行結果",
+ "price": "価格",
+ "fee": "手数料",
+ "history": "口座価値の履歴",
+ "nav": "純資産額",
+ "us": "米国株 · USD",
+ "hk": "香港株 · HKD",
+ "cn_a": "中国A株 · CNY"
}
}
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 07a29f6dc..c7de29119 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -22,7 +22,8 @@
"scheduled": "지정한 주기로 리서치를 반복합니다.",
"runtime": "브로커 연결과 거래 실행 상태를 확인합니다.",
"settings": "모델, 데이터 소스, 브로커 연결을 설정합니다.",
- "pixelOffice": "리서치 작업을 계획하고 배정합니다. 배정만으로 실행되지는 않으며, 직급은 거래 권한을 부여하지 않는 표시에 불과합니다."
+ "pixelOffice": "리서치 작업을 계획하고 배정합니다. 배정만으로 실행되지는 않으며, 직급은 거래 권한을 부여하지 않는 표시에 불과합니다.",
+ "paperTrading": "가상 자금으로 일별 거래를 테스트합니다. 증권사에 주문을 보내지 않습니다. 현금 배당을 제외하므로 총수익이 아닙니다."
},
"instructions": {
"reports": "먼저 도우미에게 전략 백테스트를 요청한 후 여기에서 결과를 엽니다. 대화에서 생성한 PDF 등은 원래 대화에서 다운로드하세요.",
@@ -33,7 +34,8 @@
"scheduled": "리서치 지시와 실행 주기를 입력하고 저장하세요. 실행하려면 로컬 스케줄러가 활성화되어 있어야 하며, 결과 전달에는 채널 설정이 필요합니다.",
"runtime": "먼저 설정 또는 보유 자산 페이지에서 브로커를 연결하세요. 사용 가능한 거래 작업은 브로커 기능과 사용자의 승인에 따라 달라집니다.",
"settings": "먼저 모델을 설정하세요. 필요에 따라 데이터 소스나 브로커 연결을 추가하면 됩니다. 공개 시장 리서치에는 브로커 계좌가 필요하지 않습니다.",
- "pixelOffice": "리서치 작업을 계획하고 배정합니다. 배정만으로 실행되지는 않으며, 직급은 거래 권한을 부여하지 않는 표시에 불과합니다."
+ "pixelOffice": "리서치 작업을 계획하고 배정합니다. 배정만으로 실행되지는 않으며, 직급은 거래 권한을 부여하지 않는 표시에 불과합니다.",
+ "paperTrading": "완료된 일봉만 결산합니다. 전략은 이전 날짜의 데이터만 읽고 실행일 종가로 체결됩니다. 정규장 종료 후 30분을 기다리세요. 자동 실행은 예약되지 않습니다."
}
},
"layout": {
@@ -64,7 +66,8 @@
"mainNavigation": "주 내비게이션",
"about": "소개",
"sessionsLoadFailed": "대화를 불러올 수 없습니다.",
- "pixelOffice": "픽셀 오피스"
+ "pixelOffice": "픽셀 오피스",
+ "paperTrading": "모의 거래"
},
"runtime": {
"monitorBadge": "거래 모니터",
@@ -2487,5 +2490,49 @@
"limitsNote": "결정마다 새 대화를 사용합니다. 응답 후 사용량을 확인하므로 해당 응답만큼 초과할 수 있습니다. 사용량 누락이나 예산 초과 시 기존 중지 스위치가 작동합니다.",
"pricesNote": "요금은 운영자 추정값입니다. 입력/캐시 쓰기의 가장 높은 요금을 사용하세요. 캐시 할인과 보조 모델 호출은 추정에 포함되지 않습니다.",
"stopToEdit": "설정을 변경하기 전에 실행기를 중지하세요."
+ },
+ "paper": {
+ "title": "모의 거래",
+ "description": "가상 자금으로 일별 거래를 테스트합니다. 증권사에 주문을 보내지 않습니다. 현금 배당을 제외하므로 총수익이 아닙니다.",
+ "accounts": "계좌",
+ "newAccount": "모의 계좌 만들기",
+ "eligible": "{{date}}부터 시작 가능하며 휴장일에는 다음 거래일을 기다립니다.",
+ "cash": "현금",
+ "pending": "첫 결산 대기",
+ "label": "계좌 이름",
+ "market": "시장",
+ "start": "시작",
+ "today": "오늘",
+ "nextSession": "다음 거래일",
+ "initialPositions": "초기 보유 종목 (수량 및 평균 단가)",
+ "symbol": "종목 (예: AAPL.US)",
+ "quantity": "수량",
+ "cost": "평균 단가",
+ "remove": "삭제",
+ "addPosition": "보유 종목 추가",
+ "create": "계좌 생성",
+ "working": "처리 중…",
+ "advance": "일별 거래 결산",
+ "executionNote": "완료된 일봉만 결산합니다. 전략은 이전 날짜의 데이터만 읽고 실행일 종가로 체결됩니다. 정규장 종료 후 30분을 기다리세요. 자동 실행은 예약되지 않습니다.",
+ "date": "실행 날짜",
+ "mode": "입력 방식",
+ "orders": "직접 주문",
+ "strategy": "전략 파일",
+ "strategyPath": "런타임 strategies 폴더 내 경로",
+ "side": "매매 구분",
+ "buy": "매수",
+ "sell": "매도",
+ "addOrder": "주문 추가",
+ "emptyOrders": "주문이 없으면 평가만 합니다. 시장가 주문은 일별 종가에 체결되며 장중 실행은 모사하지 않습니다.",
+ "saved": "장부를 저장했습니다.",
+ "notSaved": "장부는 변경되지 않았습니다. 결과를 확인한 후 다시 시도하세요.",
+ "result": "실행 결과",
+ "price": "가격",
+ "fee": "수수료",
+ "history": "계좌 가치 기록",
+ "nav": "순자산 가치",
+ "us": "미국 주식 · USD",
+ "hk": "홍콩 주식 · HKD",
+ "cn_a": "중국 A주 · CNY"
}
}
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index 7589029ec..81c3dd0fd 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -28,7 +28,8 @@
"scheduled": "Repita uma pesquisa em horários definidos.",
"runtime": "Confira conexões de corretoras e o estado de execução das operações.",
"settings": "Configure modelos, fontes de dados e conexões de corretoras.",
- "pixelOffice": "Planeje e atribua tarefas de pesquisa. A atribuição não inicia a execução; os cargos são rótulos e não concedem permissões de negociação."
+ "pixelOffice": "Planeje e atribua tarefas de pesquisa. A atribuição não inicia a execução; os cargos são rótulos e não concedem permissões de negociação.",
+ "paperTrading": "Teste operações diárias com recursos fictícios. Nenhuma ordem é enviada à corretora. Os resultados excluem dividendos em dinheiro e não representam retorno total."
},
"instructions": {
"reports": "Primeiro peça ao assistente um backtest de uma estratégia e abra os resultados aqui. Baixe PDFs e documentos gerados no chat na conversa original.",
@@ -39,7 +40,8 @@
"scheduled": "Informe a instrução de pesquisa, escolha a frequência e salve. O agendador local deve estar habilitado para executar tarefas; a entrega também requer um canal configurado.",
"runtime": "Primeiro configure uma conexão de corretora em Configurações ou Carteira. As operações disponíveis dependem dos recursos da corretora e da sua autorização.",
"settings": "Configure um modelo para começar. Adicione dados ou conexões de corretoras conforme necessário; pesquisas com dados públicos de mercado não exigem conta em corretora.",
- "pixelOffice": "Planeje e atribua tarefas de pesquisa. A atribuição não inicia a execução; os cargos são rótulos e não concedem permissões de negociação."
+ "pixelOffice": "Planeje e atribua tarefas de pesquisa. A atribuição não inicia a execução; os cargos são rótulos e não concedem permissões de negociação.",
+ "paperTrading": "Somente candles diários completos são liquidados. As estratégias leem dias anteriores e executam no fechamento do dia indicado. Aguarde 30 minutos após o fechamento regular; nenhuma execução automática é agendada."
}
},
"layout": {
@@ -70,7 +72,8 @@
"mainNavigation": "Navegação principal",
"about": "Sobre",
"sessionsLoadFailed": "Não foi possível carregar as conversas.",
- "pixelOffice": "Escritório pixel"
+ "pixelOffice": "Escritório pixel",
+ "paperTrading": "Negociação simulada"
},
"runtime": {
"monitorBadge": "Monitor de Runtime",
@@ -2487,5 +2490,49 @@
"limitsNote": "Cada decisão usa uma nova conversa. Os limites são verificados após a resposta e podem exceder pelo valor dessa resposta. Uso desconhecido ou excesso aciona a parada de emergência existente.",
"pricesNote": "Os preços são estimativas do operador. Use a maior tarifa de entrada/gravação em cache; descontos de cache e chamadas auxiliares não estão incluídos.",
"stopToEdit": "Pare o executor antes de alterar as configurações."
+ },
+ "paper": {
+ "title": "Negociação simulada",
+ "description": "Teste operações diárias com recursos fictícios. Nenhuma ordem é enviada à corretora. Os resultados excluem dividendos em dinheiro e não representam retorno total.",
+ "accounts": "Contas",
+ "newAccount": "Nova conta simulada",
+ "eligible": "Disponível a partir de {{date}}; feriados aguardam a próxima sessão disponível.",
+ "cash": "Saldo em dinheiro",
+ "pending": "Aguardando a primeira liquidação",
+ "label": "Nome da conta",
+ "market": "Mercado",
+ "start": "Início",
+ "today": "Hoje",
+ "nextSession": "Próximo pregão",
+ "initialPositions": "Posições iniciais (quantidade e custo médio)",
+ "symbol": "Símbolo (ex.: AAPL.US)",
+ "quantity": "Quantidade",
+ "cost": "Custo médio",
+ "remove": "Remover",
+ "addPosition": "Adicionar posição",
+ "create": "Criar conta",
+ "working": "Processando…",
+ "advance": "Liquidar etapa diária",
+ "executionNote": "Somente candles diários completos são liquidados. As estratégias leem dias anteriores e executam no fechamento do dia indicado. Aguarde 30 minutos após o fechamento regular; nenhuma execução automática é agendada.",
+ "date": "Data de execução",
+ "mode": "Modo de entrada",
+ "orders": "Ordens explícitas",
+ "strategy": "Arquivo de estratégia",
+ "strategyPath": "Caminho na pasta strategies do ambiente",
+ "side": "Lado",
+ "buy": "Comprar",
+ "sell": "Vender",
+ "addOrder": "Adicionar ordem",
+ "emptyOrders": "Sem ordens, apenas avalia a conta. Ordens a mercado executam no fechamento diário; não há simulação intradiária.",
+ "saved": "Registro salvo.",
+ "notSaved": "O registro não mudou. Confira o resultado antes de tentar novamente.",
+ "result": "Resultado da etapa",
+ "price": "Preço",
+ "fee": "Taxa",
+ "history": "Histórico do valor da conta",
+ "nav": "Patrimônio líquido",
+ "us": "Ações dos EUA · USD",
+ "hk": "Ações de Hong Kong · HKD",
+ "cn_a": "Ações A da China · CNY"
}
}
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index 6236923be..432edeb68 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -36,7 +36,8 @@
"mainNavigation": "Ana gezinme",
"about": "Hakkında",
"sessionsLoadFailed": "Konuşmalar yüklenemiyor.",
- "pixelOffice": "Piksel Ofis"
+ "pixelOffice": "Piksel Ofis",
+ "paperTrading": "Sanal işlem"
},
"runtime": {
"monitorBadge": "Çalışma durumu izleyicisi",
@@ -2334,7 +2335,8 @@
"scheduled": "Bir araştırma görevini zamanlayarak tekrarlayın.",
"runtime": "Aracı kurum bağlantılarını ve işlem çalışma durumunu kontrol edin.",
"settings": "Modelleri, veri kaynaklarını ve aracı kurum bağlantılarını yapılandırın.",
- "pixelOffice": "Araştırma görevlerini planlayın ve atayın. Atama yürütmeyi başlatmaz; rütbeler yalnızca etikettir ve işlem yetkisi vermez."
+ "pixelOffice": "Araştırma görevlerini planlayın ve atayın. Atama yürütmeyi başlatmaz; rütbeler yalnızca etikettir ve işlem yetkisi vermez.",
+ "paperTrading": "Günlük işlemleri sanal fonlarla deneyin. Aracı kuruma emir gönderilmez. Sonuçlar nakit temettüleri içermez ve toplam getiriyi göstermez."
},
"instructions": {
"reports": "Önce araştırma asistanından bir stratejiyi geriye dönük test etmesini isteyin, ardından sonuçları burada açın. PDF ve diğer sohbet belgelerini özgün konuşmadan indirin.",
@@ -2345,7 +2347,8 @@
"scheduled": "Araştırma talimatını girin, sıklığını seçip kaydedin. Çalıştırma için yerel zamanlayıcı etkin olmalıdır; gönderim için de yapılandırılmış bir kanal gerekir.",
"runtime": "Önce Ayarlar veya Portföy’de bir aracı kurum bağlantısı kurun. Kullanılabilir işlemler, kurumun yeteneklerine ve verdiğiniz yetkiye bağlıdır.",
"settings": "Başlamak için bir model yapılandırın. Gerektikçe veri kaynakları veya aracı kurum bağlantıları ekleyin; kamuya açık piyasa araştırması için aracı kurum hesabı gerekmez.",
- "pixelOffice": "Araştırma görevlerini planlayın ve atayın. Atama yürütmeyi başlatmaz; rütbeler yalnızca etikettir ve işlem yetkisi vermez."
+ "pixelOffice": "Araştırma görevlerini planlayın ve atayın. Atama yürütmeyi başlatmaz; rütbeler yalnızca etikettir ve işlem yetkisi vermez.",
+ "paperTrading": "Yalnızca tamamlanmış günlük mumlar işlenir. Stratejiler önceki günleri okur ve işlem gününün kapanışında gerçekleşir. Normal kapanıştan 30 dakika sonrasını bekleyin; otomatik çalıştırma planlanmaz."
}
},
"analysis": {
@@ -2487,5 +2490,49 @@
"limitsNote": "Her karar yeni bir konuşma başlatır. Sınırlar yanıttan sonra kontrol edilir ve o yanıt kadar aşılabilir. Eksik kullanım veya aşım mevcut durdurma anahtarını tetikler.",
"pricesNote": "Fiyatlar operatör tahminidir. En yüksek girdi/önbellek yazma ücretini kullanın; önbellek indirimleri ve yardımcı çağrılar dahil değildir.",
"stopToEdit": "Ayarları değiştirmeden önce çalıştırıcıyı durdurun."
+ },
+ "paper": {
+ "title": "Sanal işlem",
+ "description": "Günlük işlemleri sanal fonlarla deneyin. Aracı kuruma emir gönderilmez. Sonuçlar nakit temettüleri içermez ve toplam getiriyi göstermez.",
+ "accounts": "Hesaplar",
+ "newAccount": "Yeni sanal hesap",
+ "eligible": "{{date}} tarihinden itibaren; tatillerde sonraki uygun seans beklenir.",
+ "cash": "Nakit",
+ "pending": "İlk hesaplama bekleniyor",
+ "label": "Hesap adı",
+ "market": "Piyasa",
+ "start": "Başlangıç",
+ "today": "Bugün",
+ "nextSession": "Sonraki işlem seansı",
+ "initialPositions": "Başlangıç pozisyonları (miktar ve ortalama maliyet)",
+ "symbol": "Sembol (ör. AAPL.US)",
+ "quantity": "Miktar",
+ "cost": "Ortalama maliyet",
+ "remove": "Kaldır",
+ "addPosition": "Pozisyon ekle",
+ "create": "Hesap oluştur",
+ "working": "İşleniyor…",
+ "advance": "Günlük adımı hesapla",
+ "executionNote": "Yalnızca tamamlanmış günlük mumlar işlenir. Stratejiler önceki günleri okur ve işlem gününün kapanışında gerçekleşir. Normal kapanıştan 30 dakika sonrasını bekleyin; otomatik çalıştırma planlanmaz.",
+ "date": "İşlem tarihi",
+ "mode": "Giriş modu",
+ "orders": "Doğrudan emirler",
+ "strategy": "Strateji dosyası",
+ "strategyPath": "Çalışma ortamının strategies klasöründeki yol",
+ "side": "Yön",
+ "buy": "Al",
+ "sell": "Sat",
+ "addOrder": "Emir ekle",
+ "emptyOrders": "Emir yoksa yalnızca değerleme yapılır. Piyasa emirleri günlük kapanışta gerçekleşir; gün içi işlem simülasyonu değildir.",
+ "saved": "Hesap kaydedildi.",
+ "notSaved": "Hesap değişmedi. Yeniden denemeden önce sonucu inceleyin.",
+ "result": "Adım sonucu",
+ "price": "Fiyat",
+ "fee": "Ücret",
+ "history": "Hesap değeri geçmişi",
+ "nav": "Net varlık değeri",
+ "us": "ABD hisseleri · USD",
+ "hk": "Hong Kong hisseleri · HKD",
+ "cn_a": "Çin A hisseleri · CNY"
}
}
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 60d731055..1e036a919 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -22,7 +22,8 @@
"scheduled": "按指定时间重复执行研究任务。",
"runtime": "查看券商连接和交易运行状态。",
"settings": "配置模型、数据源和券商连接。",
- "pixelOffice": "规划和分配研究任务。分配任务不会启动执行;职级只是标签,不授予交易权限。"
+ "pixelOffice": "规划和分配研究任务。分配任务不会启动执行;职级只是标签,不授予交易权限。",
+ "paperTrading": "使用模拟资金测试每日交易,不向券商发送订单。结果不含现金分红,不代表总回报。"
},
"instructions": {
"reports": "先在研究助手中描述策略并完成回测,再到这里打开结果。聊天生成的 PDF 等文档在原对话中下载。",
@@ -33,7 +34,8 @@
"scheduled": "填写研究指令、选择执行频率并保存。任务执行需要启用本地调度服务;推送结果还需配置投递渠道。",
"runtime": "先在设置或持仓页配置券商连接。可用的交易操作取决于该券商的能力和你的授权。",
"settings": "初次使用先配置模型。按任务需要添加数据源或券商连接;研究公开行情无需连接券商账户。",
- "pixelOffice": "规划和分配研究任务。分配任务不会启动执行;职级只是标签,不授予交易权限。"
+ "pixelOffice": "规划和分配研究任务。分配任务不会启动执行;职级只是标签,不授予交易权限。",
+ "paperTrading": "仅结算已完成的日线。策略只读取此前数据,在执行日收盘价成交。请等正常收市后 30 分钟;不会自动安排后台执行。"
}
},
"layout": {
@@ -64,7 +66,8 @@
"mainNavigation": "主导航",
"about": "关于",
"sessionsLoadFailed": "无法加载会话。",
- "pixelOffice": "像素办公室"
+ "pixelOffice": "像素办公室",
+ "paperTrading": "模拟交易"
},
"runtime": {
"monitorBadge": "交易监控",
@@ -2487,5 +2490,49 @@
"limitsNote": "每次决策使用新会话。收到响应后检查用量,可能超出该次响应的费用。用量缺失或预算超限会触发现有停机开关。",
"pricesNote": "费率由用户配置。输入使用适用的最高输入/缓存写入费率;估算不包含缓存折扣和辅助模型调用。",
"stopToEdit": "请先停止 runner,再修改设置。"
+ },
+ "paper": {
+ "title": "模拟交易",
+ "description": "使用模拟资金测试每日交易,不向券商发送订单。结果不含现金分红,不代表总回报。",
+ "accounts": "账户",
+ "newAccount": "新建模拟账户",
+ "eligible": "最早从 {{date}} 开始;节假日等待下一可用交易日。",
+ "cash": "现金",
+ "pending": "等待首次结算",
+ "label": "账户名称",
+ "market": "市场",
+ "start": "开始时间",
+ "today": "今天",
+ "nextSession": "下一个交易日",
+ "initialPositions": "初始持仓(数量与平均成本)",
+ "symbol": "代码(如 AAPL.US)",
+ "quantity": "数量",
+ "cost": "平均成本",
+ "remove": "移除",
+ "addPosition": "添加持仓",
+ "create": "创建账户",
+ "working": "处理中…",
+ "advance": "结算每日交易",
+ "executionNote": "仅结算已完成的日线。策略只读取此前数据,在执行日收盘价成交。请等正常收市后 30 分钟;不会自动安排后台执行。",
+ "date": "执行日期",
+ "mode": "输入方式",
+ "orders": "指定订单",
+ "strategy": "策略文件",
+ "strategyPath": "运行目录 strategies 文件夹内的路径",
+ "side": "方向",
+ "buy": "买入",
+ "sell": "卖出",
+ "addOrder": "添加订单",
+ "emptyOrders": "无订单时只估值。市价单按每日收盘价成交,不模拟盘中执行。",
+ "saved": "账本已保存。",
+ "notSaved": "账本未变更。请查看结果后再重试。",
+ "result": "本次结果",
+ "price": "价格",
+ "fee": "费用",
+ "history": "账户净值历史",
+ "nav": "资产净值",
+ "us": "美股 · USD",
+ "hk": "港股 · HKD",
+ "cn_a": "A 股 · CNY"
}
}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 1ce6afcce..d21141fad 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2140,3 +2140,29 @@ export interface OfficeSnapshot {
agents: { id: string; name: string; role: string; color: string; rank: "Operator" | "Senior" | "Lead"; load: number }[];
tasks: { id: string; title: string; description: string; priority: "low" | "normal" | "high"; assigned_to: string | null; status: "queued" | "assigned" | "completed"; result: string }[];
}
+
+export interface PaperPosition { symbol: string; qty: number; avg_cost: number }
+export interface PaperOrder { symbol: string; side: "buy" | "sell"; qty: number; limit?: number }
+export interface PaperResult {
+ code?: string; message?: string;
+ end_state?: { cash: number; positions: PaperPosition[] };
+ fills?: { trade_date: string; symbol: string; side: string; qty: number; price: number; fee: number }[];
+ rejected_orders?: { trade_date: string; symbol: string; reason_code: string }[];
+ nav_series?: { date: string; nav: number; cash: number }[];
+ warnings?: string[];
+ data_provenance?: { source: string; bars_as_of: string | null };
+}
+export interface PaperAccount {
+ id: string; label: string; market: "cn_a" | "hk" | "us"; currency: string;
+ start_on: string; last_date: string | null; revision: number;
+ account_state: { cash: number; positions: PaperPosition[] };
+ last_result: PaperResult | null;
+}
+export const paperApi = {
+ list: () => request<PaperAccount[]>("/api/paper-accounts"),
+ create: (body: { label: string; market: string; start: string; account_state: { cash: number; positions: PaperPosition[] } }) =>
+ request<PaperAccount>("/api/paper-accounts", { method: "POST", body: JSON.stringify(body) }),
+ advance: (id: string, body: { expected_revision: number; to_date: string; orders?: PaperOrder[]; strategy_path?: string }) =>
+ request<{ account: PaperAccount; result: PaperResult; committed: boolean }>(`/api/paper-accounts/${encodeURIComponent(id)}/advance`, { method: "POST", body: JSON.stringify(body) }),
+ history: (id: string) => request<PaperResult[]>(`/api/paper-accounts/${encodeURIComponent(id)}/history`),
+};
diff --git a/frontend/src/pages/PaperTrading.tsx b/frontend/src/pages/PaperTrading.tsx
new file mode 100644
index 000000000..680bc90d9
--- /dev/null
+++ b/frontend/src/pages/PaperTrading.tsx
@@ -0,0 +1,573 @@
+import { useEffect, useState, type FormEvent } from "react";
+import { useTranslation } from "react-i18next";
+import { FlaskConical, Plus, Trash2 } from "lucide-react";
+import {
+ paperApi,
+ type PaperAccount,
+ type PaperOrder,
+ type PaperPosition,
+ type PaperResult,
+} from "@/lib/api";
+
+const field =
+ "w-full rounded-lg border border-border bg-background px-3 py-2 text-sm";
+const button =
+ "rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted disabled:opacity-50";
+const panel = "rounded-2xl border border-border bg-card p-5 space-y-4";
+
+export function PaperTrading() {
+ const { t } = useTranslation();
+ const [accounts, setAccounts] = useState<PaperAccount[]>([]);
+ const [selected, setSelected] = useState("");
+ const [label, setLabel] = useState("");
+ const [market, setMarket] = useState("us");
+ const [start, setStart] = useState("today");
+ const [cash, setCash] = useState("100000");
+ const [positions, setPositions] = useState<PaperPosition[]>([]);
+ const [orders, setOrders] = useState<PaperOrder[]>([]);
+ const [mode, setMode] = useState("orders");
+ const [strategy, setStrategy] = useState("");
+ const [date, setDate] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [notice, setNotice] = useState("");
+ const [result, setResult] = useState<PaperResult | null>(null);
+ const [history, setHistory] = useState<PaperResult[]>([]);
+ const account = accounts.find((a) => a.id === selected);
+ const currency =
+ account?.currency ?? { cn_a: "CNY", hk: "HKD", us: "USD" }[market];
+
+ useEffect(() => {
+ let active = true;
+ paperApi
+ .list()
+ .then((items) => {
+ if (active) setAccounts(items);
+ })
+ .catch((e: Error) => {
+ if (active) setError(e.message);
+ });
+ return () => {
+ active = false;
+ };
+ }, []);
+ useEffect(() => {
+ let active = true;
+ setHistory([]);
+ setResult(null);
+ setNotice("");
+ setOrders([]);
+ setDate("");
+ if (selected)
+ paperApi
+ .history(selected)
+ .then((items) => {
+ if (active) setHistory(items);
+ })
+ .catch((e: Error) => {
+ if (active) setError(e.message);
+ });
+ return () => {
+ active = false;
+ };
+ }, [selected]);
+
+ async function create(event: FormEvent) {
+ event.preventDefault();
+ setBusy(true);
+ setError("");
+ try {
+ const created = await paperApi.create({
+ label,
+ market,
+ start,
+ account_state: { cash: Number(cash), positions },
+ });
+ setAccounts((items) => [created, ...items]);
+ setSelected(created.id);
+ setLabel("");
+ setPositions([]);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ }
+ async function advance(event: FormEvent) {
+ event.preventDefault();
+ if (!account) return;
+ setBusy(true);
+ setError("");
+ setNotice("");
+ try {
+ const reply = await paperApi.advance(account.id, {
+ expected_revision: account.revision,
+ to_date: date,
+ ...(mode === "strategy" ? { strategy_path: strategy } : { orders }),
+ });
+ setAccounts((items) =>
+ items.map((a) => (a.id === reply.account.id ? reply.account : a)),
+ );
+ setResult(reply.result);
+ setNotice(t(reply.committed ? "paper.saved" : "paper.notSaved"));
+ if (reply.committed) setHistory((items) => [...items, reply.result]);
+ } catch (e) {
+ setError((e as Error).message);
+ // A timed-out request may have committed. Reload before any explicit retry.
+ try {
+ setAccounts(await paperApi.list());
+ } catch {
+ /* The original error stays visible. */
+ }
+ } finally {
+ setBusy(false);
+ }
+ }
+ const shown = result ?? account?.last_result;
+ const number = (value: number) =>
+ value.toLocaleString(undefined, { maximumFractionDigits: 4 });
+ return (
+ <div className="mx-auto max-w-6xl space-y-6 p-4 sm:p-8">
+ <header className="space-y-2">
+ <div className="flex items-center gap-3">
+ <FlaskConical className="text-primary" />
+ <h1 className="text-2xl font-semibold">{t("paper.title")}</h1>
+ </div>
+ <p className="max-w-3xl text-sm text-muted-foreground">
+ {t("paper.description")}
+ </p>
+ </header>
+ {error && (
+ <div
+ role="alert"
+ className="rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm"
+ >
+ {error}
+ </div>
+ )}
+ <div className="grid gap-6 lg:grid-cols-[minmax(260px,1fr)_2fr]">
+ <aside className="space-y-4">
+ <section className={panel}>
+ <label className="block text-sm font-medium">
+ {t("paper.accounts")}
+ <select
+ className={`${field} mt-2`}
+ value={selected}
+ disabled={busy}
+ onChange={(e) => setSelected(e.target.value)}
+ >
+ <option value="">{t("paper.newAccount")}</option>
+ {accounts.map((a) => (
+ <option key={a.id} value={a.id}>
+ {a.label} · {a.currency}
+ </option>
+ ))}
+ </select>
+ </label>
+ {account && (
+ <>
+ <p className="text-sm text-muted-foreground">
+ {t("paper.eligible", { date: account.start_on })}
+ </p>
+ <p className="text-2xl font-semibold">
+ {number(account.account_state.cash)}{" "}
+ <span className="text-sm">{currency}</span>
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t("paper.cash")} · {account.last_date ?? t("paper.pending")}
+ </p>
+ {account.account_state.positions.map((p) => (
+ <div
+ key={p.symbol}
+ className="flex justify-between gap-2 text-sm"
+ >
+ <span>{p.symbol}</span>
+ <span>
+ {number(p.qty)} × {number(p.avg_cost)}
+ </span>
+ </div>
+ ))}
+ </>
+ )}
+ </section>
+ </aside>
+ <main className="min-w-0 space-y-5">
+ {!account ? (
+ <form onSubmit={create} className={panel}>
+ <h2 className="text-lg font-semibold">{t("paper.newAccount")}</h2>
+ <label className="block text-sm">
+ {t("paper.label")}
+ <input
+ className={`${field} mt-1`}
+ required
+ maxLength={80}
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ />
+ </label>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className="text-sm">
+ {t("paper.market")}
+ <select
+ className={`${field} mt-1`}
+ value={market}
+ onChange={(e) => setMarket(e.target.value)}
+ >
+ {(["us", "hk", "cn_a"] as const).map((m) => (
+ <option key={m} value={m}>
+ {t(`paper.${m}`)}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="text-sm">
+ {t("paper.start")}
+ <select
+ className={`${field} mt-1`}
+ value={start}
+ onChange={(e) => setStart(e.target.value)}
+ >
+ <option value="today">{t("paper.today")}</option>
+ <option value="next_session">
+ {t("paper.nextSession")}
+ </option>
+ </select>
+ </label>
+ </div>
+ <label className="block text-sm">
+ {t("paper.cash")} ({currency})
+ <input
+ className={`${field} mt-1`}
+ type="number"
+ min="0"
+ step="any"
+ required
+ value={cash}
+ onChange={(e) => setCash(e.target.value)}
+ />
+ </label>
+ <p className="text-sm font-medium">
+ {t("paper.initialPositions")}
+ </p>
+ {positions.map((p, i) => (
+ <div
+ className="grid grid-cols-[2fr_1fr_1fr_auto] gap-2"
+ key={i}
+ >
+ <input
+ aria-label={t("paper.symbol")}
+ placeholder={t("paper.symbol")}
+ className={field}
+ required
+ value={p.symbol}
+ onChange={(e) =>
+ setPositions((ps) =>
+ ps.map((v, j) =>
+ j === i ? { ...v, symbol: e.target.value } : v,
+ ),
+ )
+ }
+ />
+ <input
+ aria-label={t("paper.quantity")}
+ className={field}
+ type="number"
+ min="0.00000001"
+ step="any"
+ required
+ value={p.qty}
+ onChange={(e) =>
+ setPositions((ps) =>
+ ps.map((v, j) =>
+ j === i ? { ...v, qty: Number(e.target.value) } : v,
+ ),
+ )
+ }
+ />
+ <input
+ aria-label={t("paper.cost")}
+ className={field}
+ type="number"
+ min="0.00000001"
+ step="any"
+ required
+ value={p.avg_cost}
+ onChange={(e) =>
+ setPositions((ps) =>
+ ps.map((v, j) =>
+ j === i
+ ? { ...v, avg_cost: Number(e.target.value) }
+ : v,
+ ),
+ )
+ }
+ />
+ <button
+ type="button"
+ className={button}
+ aria-label={t("paper.remove")}
+ onClick={() =>
+ setPositions((ps) => ps.filter((_, j) => j !== i))
+ }
+ >
+ <Trash2 size={16} />
+ </button>
+ </div>
+ ))}
+ <button
+ type="button"
+ className={`${button} flex items-center gap-2`}
+ onClick={() =>
+ setPositions((ps) => [
+ ...ps,
+ { symbol: "", qty: 1, avg_cost: 1 },
+ ])
+ }
+ >
+ <Plus size={16} />
+ {t("paper.addPosition")}
+ </button>
+ <button
+ disabled={busy}
+ className={`${button} bg-primary text-primary-foreground`}
+ >
+ {t(busy ? "paper.working" : "paper.create")}
+ </button>
+ </form>
+ ) : (
+ <form onSubmit={advance} className={panel}>
+ <h2 className="text-lg font-semibold">{t("paper.advance")}</h2>
+ <p className="text-sm text-muted-foreground">
+ {t("paper.executionNote")}
+ </p>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className="text-sm">
+ {t("paper.date")}
+ <input
+ type="date"
+ required
+ className={`${field} mt-1`}
+ min={account.start_on}
+ value={date}
+ onChange={(e) => setDate(e.target.value)}
+ />
+ </label>
+ <label className="text-sm">
+ {t("paper.mode")}
+ <select
+ className={`${field} mt-1`}
+ value={mode}
+ onChange={(e) => setMode(e.target.value)}
+ >
+ <option value="orders">{t("paper.orders")}</option>
+ <option value="strategy">{t("paper.strategy")}</option>
+ </select>
+ </label>
+ </div>
+ {mode === "strategy" ? (
+ <label className="block text-sm">
+ {t("paper.strategyPath")}
+ <input
+ className={`${field} mt-1`}
+ required
+ value={strategy}
+ onChange={(e) => setStrategy(e.target.value)}
+ />
+ </label>
+ ) : (
+ <>
+ {orders.map((o, i) => (
+ <div
+ key={i}
+ className="grid grid-cols-[2fr_1fr_1fr_auto] gap-2"
+ >
+ <input
+ aria-label={t("paper.symbol")}
+ placeholder={t("paper.symbol")}
+ className={field}
+ required
+ value={o.symbol}
+ onChange={(e) =>
+ setOrders((os) =>
+ os.map((v, j) =>
+ j === i ? { ...v, symbol: e.target.value } : v,
+ ),
+ )
+ }
+ />
+ <select
+ aria-label={t("paper.side")}
+ className={field}
+ value={o.side}
+ onChange={(e) =>
+ setOrders((os) =>
+ os.map((v, j) =>
+ j === i
+ ? {
+ ...v,
+ side: e.target.value as "buy" | "sell",
+ }
+ : v,
+ ),
+ )
+ }
+ >
+ <option value="buy">{t("paper.buy")}</option>
+ <option value="sell">{t("paper.sell")}</option>
+ </select>
+ <input
+ aria-label={t("paper.quantity")}
+ type="number"
+ min="0.00000001"
+ step="any"
+ required
+ className={field}
+ value={o.qty}
+ onChange={(e) =>
+ setOrders((os) =>
+ os.map((v, j) =>
+ j === i
+ ? { ...v, qty: Number(e.target.value) }
+ : v,
+ ),
+ )
+ }
+ />
+ <button
+ type="button"
+ className={button}
+ aria-label={t("paper.remove")}
+ onClick={() =>
+ setOrders((os) => os.filter((_, j) => j !== i))
+ }
+ >
+ <Trash2 size={16} />
+ </button>
+ </div>
+ ))}
+ <button
+ type="button"
+ className={button}
+ onClick={() =>
+ setOrders((os) => [
+ ...os,
+ { symbol: "", side: "buy", qty: 1 },
+ ])
+ }
+ >
+ {t("paper.addOrder")}
+ </button>
+ <p className="text-xs text-muted-foreground">
+ {t("paper.emptyOrders")}
+ </p>
+ </>
+ )}
+ <button
+ disabled={busy}
+ className={`${button} bg-primary text-primary-foreground`}
+ >
+ {t(busy ? "paper.working" : "paper.advance")}
+ </button>
+ </form>
+ )}
+ {notice && (
+ <p role="status" className="text-sm">
+ {notice}
+ </p>
+ )}
+ {shown && (
+ <section className={panel}>
+ <h2 className="font-semibold">{t("paper.result")}</h2>
+ {shown.code && (
+ <p role="alert">
+ {shown.code}: {shown.message}
+ </p>
+ )}
+ {shown.data_provenance && (
+ <p className="text-xs text-muted-foreground">
+ {shown.data_provenance.source} ·{" "}
+ {shown.data_provenance.bars_as_of}
+ </p>
+ )}
+ {!!shown.fills?.length && (
+ <div className="overflow-x-auto">
+ <table className="w-full text-left text-sm">
+ <thead>
+ <tr>
+ {(
+ [
+ "date",
+ "symbol",
+ "side",
+ "quantity",
+ "price",
+ "fee",
+ ] as const
+ ).map((key) => (
+ <th key={key} className="p-2">
+ {t(`paper.${key}`)}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {shown.fills.map((f, i) => (
+ <tr key={i} className="border-t border-border">
+ <td className="p-2">{f.trade_date}</td>
+ <td>{f.symbol}</td>
+ <td>
+ {t(f.side === "buy" ? "paper.buy" : "paper.sell")}
+ </td>
+ <td>{number(f.qty)}</td>
+ <td>{number(f.price)}</td>
+ <td>{number(f.fee)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ {shown.rejected_orders?.map((r, i) => (
+ <p key={i} className="text-sm text-destructive">
+ {r.symbol}: {r.reason_code}
+ </p>
+ ))}
+ {shown.warnings?.map((w, i) => (
+ <p key={i} className="text-xs text-muted-foreground">
+ {w}
+ </p>
+ ))}
+ </section>
+ )}
+ {!!history.length && (
+ <section className={panel}>
+ <h2 className="font-semibold">
+ {t("paper.history")} ({currency})
+ </h2>
+ <div className="max-h-64 overflow-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr>
+ <th className="text-left">{t("paper.date")}</th>
+ <th className="text-right">{t("paper.nav")}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {history
+ .flatMap((h) => h.nav_series ?? [])
+ .map((n) => (
+ <tr key={n.date} className="border-t border-border">
+ <td className="py-2">{n.date}</td>
+ <td className="text-right">{number(n.nav)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </section>
+ )}
+ </main>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/pages/__tests__/PaperTrading.test.tsx b/frontend/src/pages/__tests__/PaperTrading.test.tsx
new file mode 100644
index 000000000..16982ba8a
--- /dev/null
+++ b/frontend/src/pages/__tests__/PaperTrading.test.tsx
@@ -0,0 +1,40 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { PaperTrading } from "../PaperTrading";
+import { paperApi } from "@/lib/api";
+
+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock("@/lib/api", () => ({ paperApi: { list: vi.fn(), create: vi.fn(), advance: vi.fn(), history: vi.fn() } }));
+const account = { id: "paper-1", label: "Example", market: "us", currency: "USD", start_on: "2026-10-20", last_date: null, revision: 7, account_state: { cash: 1000, positions: [] }, last_result: null } as const;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(paperApi.list).mockResolvedValue([{ ...account }]);
+ vi.mocked(paperApi.history).mockResolvedValue([]);
+});
+
+test("sends the loaded revision and shows an in-band failure without claiming a saved ledger", async () => {
+ vi.mocked(paperApi.advance).mockResolvedValue({ account: { ...account }, committed: false, result: { code: "PAPER_DATA_NOT_READY", message: "Await daily data" } });
+ render(<PaperTrading />);
+ await screen.findByRole("option", { name: "Example · USD" });
+ fireEvent.change(screen.getByLabelText("paper.accounts"), { target: { value: "paper-1" } });
+ fireEvent.change(await screen.findByLabelText("paper.date"), { target: { value: "2026-10-20" } });
+ fireEvent.click(screen.getByRole("button", { name: "paper.advance" }));
+ await waitFor(() => expect(paperApi.advance).toHaveBeenCalledWith("paper-1", { expected_revision: 7, to_date: "2026-10-20", orders: [] }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("PAPER_DATA_NOT_READY");
+ expect(screen.getByRole("status")).toHaveTextContent("paper.notSaved");
+ expect(screen.queryByText("paper.saved")).not.toBeInTheDocument();
+});
+
+test("preserves configurable initial ledger and next-session selection", async () => {
+ vi.mocked(paperApi.create).mockResolvedValue({ ...account });
+ render(<PaperTrading />);
+ fireEvent.change(screen.getByLabelText("paper.label"), { target: { value: "My simulated account" } });
+ fireEvent.change(screen.getByLabelText("paper.start"), { target: { value: "next_session" } });
+ fireEvent.change(screen.getByLabelText(/paper.cash/), { target: { value: "2500" } });
+ fireEvent.click(screen.getByRole("button", { name: "paper.addPosition" }));
+ fireEvent.change(screen.getByLabelText("paper.symbol"), { target: { value: "AAPL.US" } });
+ fireEvent.change(screen.getByLabelText("paper.quantity"), { target: { value: "5" } });
+ fireEvent.change(screen.getByLabelText("paper.cost"), { target: { value: "100" } });
+ fireEvent.click(screen.getByRole("button", { name: "paper.create" }));
+ await waitFor(() => expect(paperApi.create).toHaveBeenCalledWith({ label: "My simulated account", market: "us", start: "next_session", account_state: { cash: 2500, positions: [{ symbol: "AAPL.US", qty: 5, avg_cost: 100 }] } }));
+});
diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx
index c6611d464..443258f5b 100644
--- a/frontend/src/router.tsx
+++ b/frontend/src/router.tsx
@@ -22,6 +22,7 @@ const Scheduled = lazy(() =>
const Reports = lazy(() =>
import("@/pages/Reports").then((m) => ({ default: m.Reports })),
);
+const PaperTrading = lazy(() => import("@/pages/PaperTrading").then((m) => ({ default: m.PaperTrading })));
const Portfolio = lazy(() =>
import("@/pages/Portfolio").then((m) => ({ default: m.Portfolio })),
);
@@ -65,6 +66,7 @@ export const router = createBrowserRouter([
{ path: "/runtime", element: wrap(Runtime) },
{ path: "/scheduled", element: wrap(Scheduled) },
{ path: "/reports", element: wrap(Reports) },
+ { path: "/paper-trading", element: wrap(PaperTrading) },
{ path: "/portfolio", element: wrap(Portfolio) },
{ path: "/settings", element: wrap(Settings) },
{ path: "/runs/:runId", element: wrap(RunDetail) },
diff --git a/pyproject.toml b/pyproject.toml
index faef3cf6b..2d8fabd31 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -110,6 +110,8 @@ include = ["src*", "backtest*", "cli*", "evals*"]
"skills/**/*.json",
"skills/**/*.py",
"providers/*.json",
+ "tools/paper_trade/*.json",
+ "tools/paper_trade/*.md",
"pixel_agents/*.json",
"scheduled_research/playbooks/*.md",
"swarm/presets/*.yaml",
@@ -292,6 +294,7 @@ pythonpath = ["agent"]
markers = [
"unit: Unit tests (fast, no network)",
"integration: Integration tests (may need network)",
+ "slow: Paper-trade performance-budget gates; run at the delivery gate",
]
[tool.ruff]
diff --git a/schema/tool_contracts/paper_trade_step-v1.1.json b/schema/tool_contracts/paper_trade_step-v1.1.json
new file mode 100644
index 000000000..78b83b9c3
--- /dev/null
+++ b/schema/tool_contracts/paper_trade_step-v1.1.json
@@ -0,0 +1,248 @@
+{
+ "$comment": "FINALIZED pt-v1.1 — G1 opened by the RM written approval of 2026-10-19 (PAPER_TRADING_ENGINE_APPROVAL_GRANTED_PT_V1.1.md). First tool-contract schema in this repo (VD-13 landing spot; the root schema/ tree otherwise holds ClickHouse DDL only). Field set per AMENDMENT §2.2/§2.3 and AM-14 vocabularies; frozen per the approval §5 declaration: vocabulary or field-set changes = major schema bump with RM written confirmation, additive fields = minor (REQUIREMENTS §9). Two named schemas live under 'schemas': 'result' (success out-param document) and 'error_envelope' (in-band error, AM-5). Both stay within the keyword subset the dependency-free validator in agent/src/tools/paper_trade/schema.py implements (type/const/enum/required/properties/items/additionalProperties), so the file is a standard draft-2020-12 document that the real jsonschema library can also consume.",
+ "contract": "paper_trade_step",
+ "version": "pt-v1.1",
+ "status": "final",
+ "schemas": {
+ "result": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.1/result.json",
+ "title": "paper_trade_step success result (pt-v1.1)",
+ "type": "object",
+ "required": [
+ "schema_version",
+ "tool",
+ "account_id",
+ "market",
+ "range",
+ "received_state_hash",
+ "effective_fee_model",
+ "fills",
+ "rejected_orders",
+ "end_state",
+ "nav_series",
+ "skipped_days",
+ "warnings",
+ "data_provenance"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "schema_version": {
+ "type": "string",
+ "const": "pt-v1.1",
+ "$comment": "FROZEN const — pt-v1.1 is the first frozen implementation version (G1 approved 2026-10-19; AMENDMENT header version-semantics ruling); any change = major schema bump"
+ },
+ "tool": { "type": "string", "const": "paper_trade_step" },
+ "account_id": {
+ "type": "string",
+ "minLength": 1,
+ "$comment": "verbatim echo of the input (R4)"
+ },
+ "market": { "type": "string", "enum": ["cn_a", "hk", "us"] },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "sha256(JCS(non-order inputs)) — AM-4/R7; 64 lowercase hex"
+ },
+ "effective_fee_model": {
+ "type": "object",
+ "$comment": "Full echo of the fee parameters in effect (R7-3). Default key names FROZEN per APPROVAL note 5 / REQUIREMENTS §4 (state_hash.py _DEFAULT_FEE_MODELS, delivery note #7): cn_a = commission_rate 0.00025, commission_min 5.0, stamp_tax_sell 0.0005, transfer_fee 0.00001; hk = commission_rate 0.0003, commission_min 3.0, stamp_tax_rate 0.001, regulatory_levy_rate 0.00003; us = commission_per_share 0.0049, commission_min 0.99, sec_fee_rate 0.0. Per-key merge: RM always injects fee_model explicitly (AM-4-3) and injected keys pass through, so the object stays open by design."
+ },
+ "fills": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "price", "fee", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": { "type": "string", "enum": ["buy", "sell"] },
+ "qty": { "type": "number" },
+ "price": { "type": "number" },
+ "fee": { "type": "number" },
+ "reason": {
+ "type": "string",
+ "$comment": "VD-15: orders mode = empty string; strategy_path mode = strategy reason text truncated to <=200 chars (UTF-8 safe)"
+ }
+ }
+ }
+ },
+ "rejected_orders": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["trade_date", "symbol", "side", "qty", "reason_code", "detail"],
+ "additionalProperties": false,
+ "properties": {
+ "trade_date": { "type": "string" },
+ "symbol": { "type": "string" },
+ "side": { "type": "string", "enum": ["buy", "sell"] },
+ "qty": { "type": "number" },
+ "reason_code": {
+ "type": "string",
+ "enum": [
+ "insufficient_cash",
+ "insufficient_position",
+ "t_plus_1",
+ "limit_up",
+ "limit_down",
+ "suspended",
+ "lot_size",
+ "non_trading_day",
+ "unknown_symbol",
+ "corporate_action_unresolved",
+ "limit_not_marketable"
+ ],
+ "$comment": "AM-14 closed vocabulary (11) — any change = major schema bump"
+ },
+ "detail": { "type": "string" }
+ }
+ }
+ },
+ "end_state": {
+ "type": "object",
+ "required": ["cash", "positions"],
+ "additionalProperties": false,
+ "properties": {
+ "cash": { "type": "number" },
+ "positions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "qty", "avg_cost"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "qty": { "type": "number" },
+ "avg_cost": { "type": "number" }
+ }
+ }
+ }
+ }
+ },
+ "nav_series": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "nav", "cash", "position_value"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "nav": { "type": "number" },
+ "cash": { "type": "number" },
+ "position_value": { "type": "number" }
+ }
+ }
+ },
+ "skipped_days": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["date", "reason"],
+ "additionalProperties": false,
+ "properties": {
+ "date": { "type": "string" },
+ "reason": {
+ "type": "string",
+ "enum": ["non_trading_day", "market_closed_inferred"],
+ "$comment": "AM-14 closed vocabulary (2): non_trading_day = cn_a only (CH calendar truth); market_closed_inferred = hk/us only, always accompanied by a warning (AM-6)"
+ }
+ }
+ }
+ },
+ "warnings": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "deterministic English strings, never contain timestamps (VD-7 / R1 hard semantics 1)"
+ },
+ "data_provenance": {
+ "type": "object",
+ "required": ["source"],
+ "additionalProperties": false,
+ "properties": {
+ "source": {
+ "type": "string",
+ "$comment": "AM-9 merged-frame form for cn_a, e.g. 'clickhouse+tencent(merged)'"
+ },
+ "ch_as_of": { "type": "string" },
+ "network_as_of": { "type": "string" },
+ "bars_as_of": { "type": "string" },
+ "corporate_actions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["symbol", "date", "ratio", "detected"],
+ "additionalProperties": false,
+ "properties": {
+ "symbol": { "type": "string" },
+ "date": { "type": "string" },
+ "ratio": {
+ "type": "string",
+ "$comment": "clean hit = ratio label (e.g. '4:1'); unresolved = the observed close-to-close ratio as a decimal string (fail-closed fact, never a guess)"
+ },
+ "detected": {
+ "type": "boolean",
+ "$comment": "true = clean split applied; false = unresolved fail-closed rejection (corporate_action_unresolved). Typed to match the T4 emitter (corporate_actions.py); reconciled from the draft's string typing at G1 finalization as its module docstring assigned to T5"
+ }
+ }
+ }
+ },
+ "limit_provenance": {
+ "type": "array",
+ "items": { "type": "string" },
+ "$comment": "VD-11 cn_a limit/ST/suspension path tokens, '<symbol>@<date>:<token>' — token set frozen (limits_cn_a.py): limits:stk_limit / limits:heuristic / limits:unavailable / st:stk_st_daily / st:stk_st_daily-no-row / suspend:stk_suspend / suspend:stk_suspend-no-row / limit_list:stk_limit_list_d. Present only for cn_a runs that consulted the band seam"
+ }
+ },
+ "$comment": "Extension set FINALIZED at G1 (was draft-open): AM-9 merge-state fields (ch_as_of/network_as_of/bars_as_of), T4 corporate_actions, VD-11 limit_provenance. Optional fields are omitted when unset, never null. Further additions = minor schema bump (APPROVAL §5)"
+ }
+ }
+ },
+ "error_envelope": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://vibe-trading.local/schemas/tool_contracts/paper_trade_step-v1.1/error_envelope.json",
+ "title": "paper_trade_step in-band error envelope (pt-v1.1, AM-5)",
+ "type": "object",
+ "required": ["status", "code", "account_id", "market", "range", "message"],
+ "additionalProperties": false,
+ "properties": {
+ "status": { "type": "string", "const": "error" },
+ "code": {
+ "type": "string",
+ "enum": ["PAPER_DATA_NOT_READY", "INVALID_REQUEST"],
+ "$comment": "AM-14 closed vocabulary (2 + transport reserved): PAPER_DATA_NOT_READY = retryable (RM 30min x 3); INVALID_REQUEST = non-retryable. Transport-level MCP errors are reserved for engine-internal faults."
+ },
+ "account_id": {
+ "type": "string",
+ "$comment": "verbatim echo even on the error path (AM-4-4/AM-5)"
+ },
+ "market": { "type": "string", "enum": ["cn_a", "hk", "us"] },
+ "range": {
+ "type": "object",
+ "required": ["from", "to"],
+ "additionalProperties": false,
+ "properties": {
+ "from": { "type": "string" },
+ "to": { "type": "string" }
+ }
+ },
+ "received_state_hash": {
+ "type": "string",
+ "$comment": "present only when the received account_state was parseable (AM-4-4); omitted otherwise, never null — RM reads the absence as 'state unparseable' and must not burn its retry chain"
+ },
+ "message": {
+ "type": "string",
+ "$comment": "deterministic English, no timestamps (VD-7). Frozen formats include strategy_execution_timeout:{YYYY-MM-DD} and strategy_execution_error:{YYYY-MM-DD}:{exception class} (VD-8/B1, Step 7)"
+ }
+ }
+ }
+ }
+}