"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(tools): get_southbound_flow — the only live Stock-Connect net-flow signal
shadowinlife70bea5b164cb
diff --git a/README.md b/README.mdindex 074a04c7b..e2d46784d 100644--- a/README.md+++ b/README.md@@ -1400,7 +1400,7 @@ Posting `{}` schedules a template on its own suggested cadence with its declared## 🔌 MCP Plugin-Vibe-Trading exposes 74 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 75 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`:@@ -1469,7 +1469,7 @@ with `--host` / `--port`.</details>-**MCP tools exposed (74):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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_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`.+**MCP tools exposed (75):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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`.### SWARM external MCP tools@@ -1843,7 +1843,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 — 74 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 75 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core@@ -1858,7 +1858,7 @@ Vibe-Trading/│ │ ├── memory/ # Cross-session persistent memory│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)│ │ │-│ │ ├── tools/ # 107 auto-discovered agent tools+│ │ ├── tools/ # 108 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.mdindex d9bac8f13..787fbb847 100644--- a/README_ar.md+++ b/README_ar.md@@ -1225,7 +1225,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-يعرض Vibe-Trading 74 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.+يعرض Vibe-Trading 75 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.**متغيرات البيئة:** العميل هو من يشغّل الخادم بنفسه، لذا لا يصل إليه `export` من الـ shell أبداً —— اضبطها في كتلة `env` الخاصة بالعميل. كود الاختبار الخلفي المولَّد محصور ضمن جذور التشغيل المسموح بها، لذا تحتاج إلى `VIBE_TRADING_ALLOWED_RUN_ROOTS` لكتابة النتائج في دليل عمل خاص بك:@@ -1281,7 +1281,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**أدوات MCP المعروضة (74):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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_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`.+**أدوات MCP المعروضة (75):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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`.### أدوات MCP الخارجية في SWARM@@ -1641,7 +1641,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 — 74 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 75 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core@@ -1656,7 +1656,7 @@ Vibe-Trading/│ │ ├── memory/ # Cross-session persistent memory│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)│ │ │-│ │ ├── tools/ # 107 auto-discovered agent tools+│ │ ├── tools/ # 108 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.mdindex 9e8678e74..7dd4df14d 100644--- a/README_es.md+++ b/README_es.md@@ -1285,7 +1285,7 @@ Enviar `{}` programa una plantilla con su propia cadencia sugerida y sus valores## 🔌 MCP Plugin-Vibe-Trading expone 74 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 75 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`:@@ -1356,7 +1356,7 @@ dirección de bind con `--host` / `--port`.</details>-**MCP tools expuestas (74):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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_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`.+**MCP tools expuestas (75):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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`.### SWARM external MCP tools@@ -1729,7 +1729,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 — 74 herramientas para OpenClaw / Claude Desktop+│ ├── mcp_server.py # Servidor MCP — 75 herramientas para OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # Núcleo del agente ReAct@@ -1744,7 +1744,7 @@ Vibe-Trading/│ │ ├── memory/ # Memoria persistente entre sesiones│ │ │ └── persistent.py # memoria basada en archivos (~/.vibe-trading/memory/)│ │ │-│ │ ├── tools/ # 107 herramientas de agente autodescubiertas+│ │ ├── tools/ # 108 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_ja.md b/README_ja.mdindex a17dad171..a40cca429 100644--- a/README_ja.md+++ b/README_ja.md@@ -1227,7 +1227,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-Vibe-Trading は MCP-compatible client 向けに 74 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 向けに 75 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` が必要です:@@ -1283,7 +1283,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**公開される MCP tools(74):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_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`.+**公開される MCP tools(75):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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`.### SWARM の外部 MCP tools@@ -1649,7 +1649,7 @@ Vibe-Trading/├── agent/ # バックエンド (Python)│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 74 tools+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 75 tools│ ││ ├── src/│ │ ├── agent/ # ReAct エージェントコア@@ -1664,7 +1664,7 @@ Vibe-Trading/│ │ ├── memory/ # クロスセッション永続メモリ│ │ │ └── persistent.py # ファイルベースメモリ (~/.vibe-trading/memory/)│ │ │-│ │ ├── tools/ # 107 個の自動検出エージェントツール+│ │ ├── tools/ # 108 個の自動検出エージェントツール│ │ │ ├── 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.mdindex e3f01aa3f..a1cf42d25 100644--- a/README_ko.md+++ b/README_ko.md@@ -1228,7 +1228,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-Vibe-Trading은 모든 MCP-compatible client를 위해 74개 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를 위해 75개 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`가 필요합니다:@@ -1284,7 +1284,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**노출되는 MCP tools(74):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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_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`.+**노출되는 MCP tools(75):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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`.### SWARM 외부 MCP tools@@ -1646,7 +1646,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 — 74 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 75 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core@@ -1661,7 +1661,7 @@ Vibe-Trading/│ │ ├── memory/ # Cross-session persistent memory│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)│ │ │-│ │ ├── tools/ # 107 auto-discovered agent tools+│ │ ├── tools/ # 108 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.mdindex 47c58a9c6..4c1c24d89 100644--- a/README_zh.md+++ b/README_zh.md@@ -1232,7 +1232,7 @@ POST `{}` 即按模板自身的建议节奏和默认变量排程。渲染后的## 🔌 MCP Plugin-Vibe-Trading 为任何 MCP-compatible client 暴露 74 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。+Vibe-Trading 为任何 MCP-compatible client 暴露 75 个 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`:@@ -1288,7 +1288,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**暴露的 MCP tools(74):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_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`.+**暴露的 MCP tools(75):** `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`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `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`.### SWARM 的外部 MCP tools@@ -1644,7 +1644,7 @@ Vibe-Trading/├── agent/ # 后端(Python)│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP server —— 74 个工具,面向 OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server —— 75 个工具,面向 OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent 内核@@ -1659,7 +1659,7 @@ Vibe-Trading/│ │ ├── memory/ # 跨 session 持久记忆│ │ │ └── persistent.py # 基于文件的记忆(~/.vibe-trading/memory/)│ │ │-│ │ ├── tools/ # 107 个自动发现的 agent 工具+│ │ ├── tools/ # 108 个自动发现的 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.mdindex 7ec783762..1ad7170bc 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 (74)+## Available MCP Tools (75)| Tool | Description | API Key ||------|-------------|---------|@@ -154,6 +154,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `get_fund_flow` | Capital fund-flow (main/retail net inflow) | None* || `get_dragon_tiger` | Dragon-tiger list (龙虎榜) top buyer/seller seats | None* || `get_northbound_flow` | Northbound (Stock Connect) net flow | None* |+| `get_southbound_flow` | Southbound (Stock Connect) net buy into HK (Eastmoney/HKEX) | None || `get_margin_trading` | Margin trading & short-selling balances | None* || `get_block_trades` | Block-trade (大宗交易) records | None* || `get_shareholder_count` | Shareholder-count history per symbol | None* |diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex eaee3d302..87da352e1 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -6,10 +6,11 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,AKShare are free). Trading connector tools are profile-scoped and require theselected connector's own local app or OAuth setup.-Surfaces 74 tools: skills, research goals, strategy discovery,+Surfaces 75 tools: skills, research goals, strategy discovery,backtest/factor/options/patternanalysis, market data, fundamentals & capital-flow & news & discovery-(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_margin_trading /+(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 /@@ -1975,6 +1976,26 @@ def get_northbound_flow(lookback_days: int = 30) -> str:return registry.execute("get_northbound_flow", {"lookback_days": lookback_days})+def get_southbound_flow(lookback_days: int = 30) -> str:+ """Fetch Southbound (Stock-Connect) net capital flow into Hong Kong equities.++ Returns the latest trading day's net buy plus recent daily history, split+ into 港股通(沪) and 港股通(深) channels (units: 100M HKD, 亿) from the+ Eastmoney datacenter — cross-verified against HKEX official daily+ statistics — falling back to the HKEX official report (latest trading day+ snapshot) when Eastmoney is unavailable. Southbound is the only+ Stock-Connect direction whose daily net buy is still officially disclosed+ (the northbound net ended 2024-08-30; see get_northbound_flow). Read-only,+ no credentials; HK market only.++ Args:+ lookback_days: Trailing trading days of daily net-buy history to return.+ """+ registry = _get_registry()+ return registry.execute("get_southbound_flow", {"lookback_days": lookback_days})++@mcp.tooldef get_margin_trading(code: str, days: int = 30) -> str:"""Fetch an A-share stock's daily margin-trading (融资融券) balances (Eastmoney).diff --git a/agent/src/skills/hk-connect-flow/SKILL.md b/agent/src/skills/hk-connect-flow/SKILL.mdindex e6b072e24..1447b90d3 100644--- a/agent/src/skills/hk-connect-flow/SKILL.md+++ b/agent/src/skills/hk-connect-flow/SKILL.md@@ -154,6 +154,19 @@ connect_score = {## Data Access+### Via agent tools (no code, throttled, envelope-standard)++```python+# Daily Southbound net buy — 港股通(沪)/(深) channels, unit 100M HKD (亿).+# Eastmoney datacenter primary (cross-verified against HKEX official daily+# statistics); HKEX official report as keyless fallback (latest day snapshot):+get_southbound_flow(lookback_days=20)+```++> ⚠️ Do NOT read daily southbound flow from tushare `moneyflow_hsgt`:+> its `ggt_ss`/`ggt_sz`/`south_money` fields now carry the **cumulative**+> net-bought stock (万亿-scale, near-constant day to day), not daily flow.+### Via Tushare (A-share perspective)```python@@ -190,7 +203,7 @@ hsi = yf.download("^HSI", start="2025-01-01", end="2026-03-30", progress=False)|--------|--------|-----------|-----------|| Northbound daily net buy | Tushare / HKEX | Daily | >RMB 5B = significant || Northbound 20-day cumulative | Calculated | Daily | >RMB 30B = trend |-| Southbound daily net buy | Tushare / HKEX | Daily | >HKD 3B = significant |+| Southbound daily net buy | get_southbound_flow (Eastmoney ↔ HKEX) | Daily | >HKD 3B = significant || AH Premium Index | Hang Seng | Daily | >130 = H-share value || Quota utilization | HKEX | Intraday | >50% = strong conviction || NB Top 10 concentration | Tushare | Daily | Top 3 names >50% = concentrated bet |diff --git a/agent/src/tools/southbound_tool.py b/agent/src/tools/southbound_tool.pynew file mode 100644index 000000000..a2736a231--- /dev/null+++ b/agent/src/tools/southbound_tool.py@@ -0,0 +1,362 @@+"""Southbound (Stock-Connect) net capital flow tool.++Southbound flow is the net capital moving from mainland China into+Hong Kong equities through the 港股通(沪)/ 港股通(深) channels. Since the+2024-08-30 HKEX disclosure reform ended northbound daily net-buy+publishing (#1481), southbound is the only Stock-Connect direction whose+daily net buy is still officially disclosed — HKEX publishes per-channel+Buy/Sell Turnover every trading day, and Eastmoney's datacenter series+cross-checks against it exactly (#1483).++Sources, in order:++* **Eastmoney datacenter** ``RPT_MUTUAL_DEAL_HISTORY`` (``MUTUAL_TYPE``+ ``002`` = 港股通沪, ``004`` = 港股通深) through the shared throttled+ client: daily net buy (``NET_DEAL_AMT``), buy/sell turnover and the+ cumulative net series, unit 100M HKD (亿). Verified against HKEX+ official daily statistics to the cent on 2026-09-15/16/17.+* **HKEX official** Stock Connect Daily Statistics report (keyless JS+ feed): latest available trading day only, net = Buy Turnover − Sell+ Turnover per channel, converted from million HKD to the envelope unit.++There is deliberately **no tushare path**: ``moneyflow_hsgt``'s+southbound fields (``ggt_ss``/``ggt_sz``/``south_money``) now carry the+*cumulative* net-bought stock, not daily flow — ``ggt_ss`` equals+Eastmoney's ``ACCUM_DEAL_AMT`` exactly and moves ~0.4% across a six-week+window (#1483) — so serving them as flow would mislabel a stock as a+rate.++This tool is read-only: it places no orders and reaches no live trading+endpoint.+"""++from __future__ import annotations++import datetime as dt+import json+import logging+from typing import Any++import requests++from backtest.loaders import eastmoney_client+from src.agent.tools import BaseTool++logger = logging.getLogger(__name__)++# Eastmoney datacenter report carrying the Stock-Connect daily history.+# MUTUAL_TYPE: "002" = 港股通(沪), "004" = 港股通(深). Amounts are in+# 100M HKD (亿); NET_DEAL_AMT cross-checks against HKEX Buy − Sell exactly.+_DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"+_REPORT_NAME = "RPT_MUTUAL_DEAL_HISTORY"+_CHANNEL_TYPES = {"shanghai_connect": "002", "shenzhen_connect": "004"}++# HKEX official daily statistics (keyless). One JS file per trading day;+# the southbound sections carry Buy/Sell Turnover in million HKD.+_HKEX_DAILY_URL = "https://www.hkex.com.hk/eng/csm/DailyStat/data_tab_daily_{date}e.js"+_HKEX_WALKBACK_DAYS = 7+_HKEX_TIMEOUT_S = 12+_HKEX_HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; vibe-trading)"}++_DEFAULT_LOOKBACK_DAYS = 30+_MAX_LOOKBACK_DAYS = 250++_NOTE = (+ "Southbound daily net buy is still officially disclosed (HKEX Buy/Sell "+ "Turnover); tushare moneyflow_hsgt southbound fields are NOT used here: "+ "they drifted to cumulative net-bought stock, not daily flow (#1483)."+)+++def _coerce_float(value: Any) -> float | None:+ """Coerce a raw provider cell to ``float``, ``None`` on missing/garbage."""+ if value in (None, "", "-", "null"):+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _trade_date(raw: Any) -> str | None:+ """Normalize an Eastmoney ``TRADE_DATE`` cell to ``YYYY-MM-DD``."""+ text = str(raw or "").strip()+ return text[:10] if len(text) >= 10 else None+++def _clamp_lookback(value: Any) -> int:+ """Clamp a requested lookback to ``[1, _MAX_LOOKBACK_DAYS]``."""+ try:+ days = int(value)+ except (TypeError, ValueError, OverflowError):+ return _DEFAULT_LOOKBACK_DAYS+ return max(1, min(days, _MAX_LOOKBACK_DAYS))+++def _fetch_eastmoney_channel(mutual_type: str, days: int) -> list[dict[str, Any]]:+ """Fetch one 港股通 channel's daily rows, newest first.++ Args:+ mutual_type: Eastmoney ``MUTUAL_TYPE`` code ("002" or "004").+ days: Number of trailing trading days to request.++ Returns:+ Raw datacenter rows (possibly empty).++ Raises:+ Exception: Network/decoding failures propagate for the caller's+ fallback policy.+ """+ payload = eastmoney_client.get_json(+ _DATACENTER_URL,+ params={+ "reportName": _REPORT_NAME,+ "columns": "ALL",+ "source": "WEB",+ "client": "WEB",+ "filter": f'(MUTUAL_TYPE="{mutual_type}")',+ "sortColumns": "TRADE_DATE",+ "sortTypes": "-1",+ "pageNumber": "1",+ "pageSize": str(days),+ },+ )+ result = payload.get("result") if isinstance(payload, dict) else None+ rows = result.get("data") if isinstance(result, dict) else None+ return rows if isinstance(rows, list) else []+++def _merge_eastmoney(days: int) -> list[dict[str, Any]]:+ """Fetch both 港股通 channels and merge them into ascending daily rows.++ Args:+ days: Trailing trading days per channel.++ Returns:+ Ascending list of ``{trade_date, shanghai_connect, shenzhen_connect,+ total}`` dicts (net buy, 100M HKD). Empty when neither channel+ serves rows.+ """+ per_channel: dict[str, dict[str, float | None]] = {}+ for key, mutual_type in _CHANNEL_TYPES.items():+ for row in _fetch_eastmoney_channel(mutual_type, days):+ date = _trade_date(row.get("TRADE_DATE"))+ if date is None:+ continue+ net = _coerce_float(row.get("NET_DEAL_AMT"))+ per_channel.setdefault(date, {})[key] = (+ round(net, 4) if net is not None else None+ )+ history: list[dict[str, Any]] = []+ for date in sorted(per_channel):+ entry = per_channel[date]+ shanghai = entry.get("shanghai_connect")+ shenzhen = entry.get("shenzhen_connect")+ values = [v for v in (shanghai, shenzhen) if v is not None]+ history.append(+ {+ "trade_date": date,+ "shanghai_connect": shanghai,+ "shenzhen_connect": shenzhen,+ "total": round(sum(values), 4) if values else None,+ }+ )+ return history[-days:]+++def _parse_hkex_report(text: str) -> dict[str, Any] | None:+ """Extract southbound nets from one HKEX daily-statistics JS payload.++ Args:+ text: Raw ``data_tab_daily_<date>e.js`` body (``tabData = [...]``).++ Returns:+ ``{trade_date, shanghai_connect, shenzhen_connect, total}`` in 100M+ HKD, or ``None`` when the southbound sections are absent.+ """+ try:+ payload = json.loads(text[text.index("[") : text.rindex("]") + 1])+ except (ValueError, json.JSONDecodeError):+ return None+ nets: dict[str, float] = {}+ date: str | None = None+ for section in payload if isinstance(payload, list) else []:+ market = section.get("market")+ if market not in ("SSE Southbound", "SZSE Southbound"):+ continue+ date = date or section.get("date")+ for content in section.get("content", []):+ table = content.get("table", {})+ schema = (table.get("schema") or [[]])[0]+ # The aggregate summary table is the one led by Total Turnover+ # with one metric per row. The section's second table (top-10+ # stocks) also carries Buy/Sell Turnover columns but one row per+ # stock — it must not be mistaken for the summary.+ if not schema or schema[0] != "Total Turnover":+ continue+ if "Buy Turnover" not in schema or "Sell Turnover" not in schema:+ continue+ cells: list[str] = []+ for row in table.get("tr", []):+ for cell in row.get("td", []):+ cells.append(cell[0] if isinstance(cell, list) else cell)+ values = dict(zip(schema, cells))+ buy = _coerce_float(str(values.get("Buy Turnover", "")).replace(",", ""))+ sell = _coerce_float(str(values.get("Sell Turnover", "")).replace(",", ""))+ if buy is not None and sell is not None:+ # million HKD → 100M HKD to match the Eastmoney caliber.+ nets[market] = round((buy - sell) / 100.0, 4)+ break+ if not nets:+ return None+ shanghai = nets.get("SSE Southbound")+ shenzhen = nets.get("SZSE Southbound")+ values = [v for v in (shanghai, shenzhen) if v is not None]+ return {+ "trade_date": date,+ "shanghai_connect": shanghai,+ "shenzhen_connect": shenzhen,+ "total": round(sum(values), 4) if values else None,+ }+++def _fetch_hkex_latest() -> dict[str, Any] | None:+ """Walk back up to a week for the latest HKEX daily-statistics report.++ Returns:+ The parsed southbound snapshot row, or ``None`` when no trading+ day within the walkback window serves a usable report.+ """+ today = dt.date.today()+ for offset in range(_HKEX_WALKBACK_DAYS + 1):+ day = today - dt.timedelta(days=offset)+ url = _HKEX_DAILY_URL.format(date=day.strftime("%Y%m%d"))+ try:+ response = requests.get(url, timeout=_HKEX_TIMEOUT_S, headers=_HKEX_HEADERS)+ except requests.RequestException as exc:+ logger.debug("HKEX daily statistics unreachable for %s: %s", day, exc)+ return None+ if response.status_code == 404:+ continue # weekend / holiday / not yet published+ if response.status_code != 200:+ logger.debug(+ "HKEX daily statistics HTTP %s for %s", response.status_code, day+ )+ continue+ row = _parse_hkex_report(response.text)+ if row is not None:+ return row+ return None+++class SouthboundFlowTool(BaseTool):+ """Fetch Southbound (Stock-Connect) net capital flow into Hong Kong."""++ name = "get_southbound_flow"+ description = (+ "MARKET-WIDE Southbound (Stock-Connect / 南向) net capital flow for "+ "the whole Hong Kong market: the aggregate daily net buy from the "+ "mainland through the 港股通(沪) and 港股通(深) channels (units: "+ "100M HKD, 亿), as the latest trading day plus a recent daily "+ "history. Southbound is the only Stock-Connect direction whose daily "+ "net buy is still officially disclosed (HKEX; the northbound net "+ "ended 2024-08-30 — see get_northbound_flow). This is a market-level "+ "total, NOT per-stock flow (for a given symbol's order-bucket inflow "+ "use get_fund_flow). Read-only. Example: "+ "get_southbound_flow(lookback_days=10)."+ )+ parameters = {+ "type": "object",+ "properties": {+ "lookback_days": {+ "type": "integer",+ "description": (+ "Number of trailing trading days of daily net-buy history "+ f"to return, clamped to 1..{_MAX_LOOKBACK_DAYS}."+ ),+ "default": _DEFAULT_LOOKBACK_DAYS,+ },+ },+ "required": [],+ }++ def execute(self, **kwargs: Any) -> str:+ """Fetch latest + recent-daily Southbound net flow as a JSON envelope.++ Args:+ **kwargs: Accepts ``lookback_days`` (int, default+ :data:`_DEFAULT_LOOKBACK_DAYS`).++ Returns:+ A JSON string envelope ``{"ok": true, "market": "HK",+ "source": "eastmoney"|"hkex", "data": {...}}`` on success, or+ ``{"ok": false, "error": str}`` when neither source serves data.+ """+ lookback_days = _clamp_lookback(+ kwargs.get("lookback_days", _DEFAULT_LOOKBACK_DAYS)+ )++ history: list[dict[str, Any]] = []+ eastmoney_error: str | None = None+ try:+ history = _merge_eastmoney(lookback_days)+ except Exception as exc: # noqa: BLE001 - fall back to HKEX official+ eastmoney_error = str(exc)+ logger.warning("southbound eastmoney fetch failed: %s", exc)++ if history:+ latest = history[-1]+ return json.dumps(+ {+ "ok": True,+ "market": "HK",+ "source": "eastmoney",+ "data": {+ "unit": "100M HKD",+ "lookback_days": lookback_days,+ "note": _NOTE,+ "realtime": latest,+ "history": history,+ },+ },+ ensure_ascii=False,+ )++ snapshot = _fetch_hkex_latest()+ if snapshot is not None:+ reason = (+ f"eastmoney datacenter unavailable ({eastmoney_error})"+ if eastmoney_error+ else "eastmoney datacenter returned no rows"+ )+ return json.dumps(+ {+ "ok": True,+ "market": "HK",+ "source": "hkex",+ "warnings": [+ f"{reason}; used the HKEX official daily statistics — "+ "latest trading day snapshot only"+ ],+ "data": {+ "unit": "100M HKD",+ "lookback_days": lookback_days,+ "note": _NOTE,+ "realtime": snapshot,+ "history": [snapshot],+ },+ },+ ensure_ascii=False,+ )++ return json.dumps(+ {+ "ok": False,+ "error": (+ "southbound flow unavailable: eastmoney datacenter "+ f"({'failed: ' + eastmoney_error if eastmoney_error else 'empty'})"+ "; HKEX official daily statistics unavailable"+ ),+ },+ ensure_ascii=False,+ )diff --git a/agent/tests/test_southbound_tool.py b/agent/tests/test_southbound_tool.pynew file mode 100644index 000000000..7bf58cf58--- /dev/null+++ b/agent/tests/test_southbound_tool.py@@ -0,0 +1,225 @@+"""Tests for get_southbound_flow: envelopes, source fallback, HTTP fully mocked.++Eastmoney datacenter calls are mocked at ``southbound_tool.eastmoney_client``+and HKEX report fetches at ``southbound_tool.requests.get``, so no test+touches a live endpoint. Fixture figures mirror the HKEX-cross-verified+2026-09-17 values (港股通沪 net 25.0239亿 == Buy 26,387.65M − Sell+23,885.26M HKD).+"""++from __future__ import annotations++import json+from unittest.mock import MagicMock, patch++from src.tools import southbound_tool as sb+++def _em_rows(channel_net: dict[str, float]) -> dict:+ """Build one datacenter payload for a channel's NET_DEAL_AMT map."""+ return {+ "result": {+ "data": [+ {+ "TRADE_DATE": f"{date} 00:00:00",+ "NET_DEAL_AMT": net,+ "BUY_AMT": net + 10.0,+ "SELL_AMT": 10.0,+ }+ for date, net in sorted(channel_net.items(), reverse=True)+ ]+ }+ }+++def _fake_get_json(url: str, *, params: dict):+ assert url == sb._DATACENTER_URL+ if '"002"' in params["filter"]:+ return _em_rows({"2026-09-16": 26.6898, "2026-09-17": 25.0239})+ return _em_rows({"2026-09-16": 8.6076, "2026-09-17": 9.9861})+++class TestEastmoneyEnvelope:+ def test_returns_merged_history_and_latest(self):+ with patch.object(sb.eastmoney_client, "get_json", side_effect=_fake_get_json):+ text = sb.SouthboundFlowTool().execute(lookback_days=10)++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["market"] == "HK"+ assert payload["source"] == "eastmoney"++ data = payload["data"]+ assert data["unit"] == "100M HKD"+ assert data["lookback_days"] == 10+ assert "cumulative" in data["note"]++ history = data["history"]+ assert [row["trade_date"] for row in history] == [+ "2026-09-16",+ "2026-09-17",+ ]+ assert history[-1]["shanghai_connect"] == 25.0239+ assert history[-1]["shenzhen_connect"] == 9.9861+ assert history[-1]["total"] == round(25.0239 + 9.9861, 4)+ assert data["realtime"] == history[-1]++ def test_history_trimmed_to_lookback(self):+ with patch.object(sb.eastmoney_client, "get_json", side_effect=_fake_get_json):+ text = sb.SouthboundFlowTool().execute(lookback_days=1)+ payload = json.loads(text)+ history = payload["data"]["history"]+ assert len(history) == 1+ assert history[0]["trade_date"] == "2026-09-17"++ def test_lookback_clamped_to_ceiling(self):+ with patch.object(sb.eastmoney_client, "get_json", side_effect=_fake_get_json):+ text = sb.SouthboundFlowTool().execute(lookback_days=99999)+ payload = json.loads(text)+ assert payload["data"]["lookback_days"] == sb._MAX_LOOKBACK_DAYS++ def test_one_channel_missing_leaves_none_and_partial_total(self):+ def fake(url: str, *, params: dict):+ if '"002"' in params["filter"]:+ return _em_rows({"2026-09-17": 25.0239})+ return {"result": {"data": []}}++ with patch.object(sb.eastmoney_client, "get_json", side_effect=fake):+ text = sb.SouthboundFlowTool().execute(lookback_days=5)+ row = json.loads(text)["data"]["history"][-1]+ assert row["shanghai_connect"] == 25.0239+ assert row["shenzhen_connect"] is None+ assert row["total"] == 25.0239+++class TestHkexFallback:+ _HKEX_JS = (+ "tabData = ["+ '{"id":0,"date":"2026-09-17","market":"SSE Southbound","content":['+ '{"table":{"schema":[["Total Turnover","Buy Turnover","Sell Turnover"]],'+ '"tr":[{"td":[["50,272.91"]]},{"td":[["26,387.65"]]},'+ '{"td":[["23,885.26"]]}]}},'+ # Decoy: the top-10 stocks table also carries Buy/Sell Turnover+ # columns, one multi-cell row per stock — the parser must skip it+ # (regression for the live-payload bug where it overwrote the net+ # with (rank4 − rank5)/100 = −0.01).+ '{"table":{"schema":[["Rank","Stock Code","Stock Name",'+ '"Buy Turnover","Sell Turnover","Total Turnover"]],'+ '"tr":[{"td":[["1","02513","Z.AI","2,057,313,700",'+ '"1,369,978,206","3,427,291,906"]]},'+ '{"td":[["2","06869","YOFC","1,150,696,524",'+ '"1,290,739,110","2,441,435,634"]]}]}}]},'+ '{"id":1,"date":"2026-09-17","market":"SZSE Southbound","content":['+ '{"table":{"schema":[["Total Turnover","Buy Turnover","Sell Turnover"]],'+ '"tr":[{"td":[["27,737.22"]]},{"td":[["14,298.99"]]},'+ '{"td":[["13,438.23"]]}]}}]}'+ "];"+ )++ def _mock_response(self, status: int = 200, text: str = "") -> MagicMock:+ response = MagicMock()+ response.status_code = status+ response.text = text+ return response++ def test_eastmoney_failure_falls_back_to_hkex_snapshot(self):+ with (+ patch.object(+ sb.eastmoney_client, "get_json", side_effect=RuntimeError("HTTP 429")+ ),+ patch.object(+ sb.requests, "get", return_value=self._mock_response(200, self._HKEX_JS)+ ),+ ):+ text = sb.SouthboundFlowTool().execute(lookback_days=5)++ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["source"] == "hkex"+ assert "HKEX official daily statistics" in payload["warnings"][0]+ assert "HTTP 429" in payload["warnings"][0]++ snapshot = payload["data"]["realtime"]+ assert snapshot["trade_date"] == "2026-09-17"+ # (26,387.65 − 23,885.26) / 100 = 25.0239 亿 HKD+ assert snapshot["shanghai_connect"] == round(2502.39 / 100, 4)+ assert snapshot["shenzhen_connect"] == round(860.76 / 100, 4)+ assert payload["data"]["history"] == [snapshot]++ def test_eastmoney_empty_rows_also_falls_back(self):+ empty = {"result": {"data": []}}+ with (+ patch.object(sb.eastmoney_client, "get_json", return_value=empty),+ patch.object(+ sb.requests, "get", return_value=self._mock_response(200, self._HKEX_JS)+ ),+ ):+ text = sb.SouthboundFlowTool().execute(lookback_days=5)+ payload = json.loads(text)+ assert payload["source"] == "hkex"+ assert "returned no rows" in payload["warnings"][0]++ def test_hkex_walks_back_past_404(self):+ responses = [+ self._mock_response(404),+ self._mock_response(200, self._HKEX_JS),+ ]+ with (+ patch.object(+ sb.eastmoney_client, "get_json", side_effect=RuntimeError("down")+ ),+ patch.object(sb.requests, "get", side_effect=responses) as get,+ ):+ text = sb.SouthboundFlowTool().execute(lookback_days=5)+ payload = json.loads(text)+ assert payload["ok"] is True+ assert payload["source"] == "hkex"+ assert get.call_count == 2++ def test_both_sources_down_returns_error_envelope(self):+ with (+ patch.object(+ sb.eastmoney_client, "get_json", side_effect=RuntimeError("HTTP 500")+ ),+ patch.object(+ sb.requests, "get", side_effect=sb.requests.RequestException("dns")+ ),+ ):+ text = sb.SouthboundFlowTool().execute(lookback_days=5)+ payload = json.loads(text)+ assert payload["ok"] is False+ assert "eastmoney datacenter" in payload["error"]+ assert "HKEX" in payload["error"]+++class TestHkexParser:+ def test_missing_southbound_sections_returns_none(self):+ js = (+ "tabData = ["+ '{"date":"2026-09-17","market":"SSE Northbound","content":['+ '{"table":{"schema":[["Total Turnover"]],"tr":[{"td":[["1.0"]]}]}}]}'+ "];"+ )+ assert sb._parse_hkex_report(js) is None++ def test_garbage_body_returns_none(self):+ assert sb._parse_hkex_report("<html>not js</html>") is None+++class TestToolMetadata:+ def test_name_and_params(self):+ tool = sb.SouthboundFlowTool()+ assert tool.name == "get_southbound_flow"+ assert tool.is_readonly is True+ assert tool.parameters["required"] == []+ assert "lookback_days" in tool.parameters["properties"]++ def test_description_scopes_to_market_wide_southbound(self):+ desc = sb.SouthboundFlowTool().description+ assert desc.startswith("MARKET-WIDE Southbound")+ assert "南向" in desc+ # Disambiguates against the per-stock tool and the northbound one.+ assert "get_fund_flow" in desc+ assert "NOT per-stock" in desc+ assert "get_northbound_flow" in desc+ assert "get_southbound_flow(lookback_days=10)" in desc