"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Make Gildata research tools opt-in and require explicit quote selection
Haozhe Wu0af09d597eb9
diff --git a/README.md b/README.mdindex 076b07cf6..ac5a8c629 100644--- a/README.md+++ b/README.md@@ -249,7 +249,7 @@- **2026-07-09** 🧯 **Docker startup unblocked + provider/CLI contributor batch**: Docker/server startup no longer crashes when FastAPI route iteration sees an included-router-like entry without `path` ([#450](https://github.com/HKUDS/Vibe-Trading/issues/450), thanks @Penn-Live). We also landed the queued quick-win contributor fixes: loader `fetch()` signatures now match the protocol across OKX / Tushare / yfinance ([#437](https://github.com/HKUDS/Vibe-Trading/pull/437), thanks @shadowinlife), the CLI resume prompt preserves the first user message ([#448](https://github.com/HKUDS/Vibe-Trading/pull/448), closes [#447](https://github.com/HKUDS/Vibe-Trading/issues/447), thanks @morluto), Codex OAuth defaults to `openai-codex/gpt-5.4` ([#446](https://github.com/HKUDS/Vibe-Trading/pull/446), thanks @morluto), Kimi for Coding is available as a distinct provider ([#435](https://github.com/HKUDS/Vibe-Trading/pull/435), thanks @yxhuang), opencode provider mappings are wired ([#444](https://github.com/HKUDS/Vibe-Trading/pull/444), thanks @imsankz), and Tushare reference code fences now say `python` instead of `pyhton` ([#449](https://github.com/HKUDS/Vibe-Trading/pull/449), thanks @flash1234pku). Validation included focused server/CLI/provider/loader tests plus a Docker build and `/health` smoke.-- **2026-07-08** 💎 **Fundamental factor layer (Phase 1) + optional QVeris premium data + maintainer day**: PIT-safe SEC fundamentals now flow into daily factor panels — `fund:*` panel columns, filed-date anchoring with restatement and YTD-frame protection, and 4 new quality/value factors (registry now 460 alphas). Data routing gains an optional premium track: the 18 free sources stay the default, while QVeris unlocks 63+ providers via Settings → QVeris or `vibe-trading data mode paid` (see the QVeris section below). Also: `api_server` modularization completed (1,103 → 371 lines, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) closing [#331](https://github.com/HKUDS/Vibe-Trading/issues/331), thanks @shadowinlife), backtest `validation.json` no longer requires a pre-existing artifacts dir ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), thanks @isaveall), clearer `--swarm-run` errors ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), thanks @isaveall), and we reverted the governance stack that broke session chats ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), thanks @yxhuang for the precise diagnosis).+- **2026-07-08** 💎 **Fundamental factor layer (Phase 1) + optional QVeris premium data + maintainer day**: PIT-safe SEC fundamentals now flow into daily factor panels — `fund:*` panel columns, filed-date anchoring with restatement and YTD-frame protection, and 4 new quality/value factors (registry now 460 alphas). Also: `api_server` modularization completed (1,103 → 371 lines, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) closing [#331](https://github.com/HKUDS/Vibe-Trading/issues/331), thanks @shadowinlife), backtest `validation.json` no longer requires a pre-existing artifacts dir ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), thanks @isaveall), clearer `--swarm-run` errors ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), thanks @isaveall), and we reverted the governance stack that broke session chats ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), thanks @yxhuang for the precise diagnosis).- **2026-07-07** ✅ **Contributor PR batch**: merged the queued contributor work for IM channel timeout configuration ([#413](https://github.com/HKUDS/Vibe-Trading/pull/413), thanks @SyntaxSawdust), Alpha Library social previews and the beginner tutorial ([#396](https://github.com/HKUDS/Vibe-Trading/pull/396), [#393](https://github.com/HKUDS/Vibe-Trading/pull/393), thanks @kadaliao), value-investing skills / tools / committee presets ([#407](https://github.com/HKUDS/Vibe-Trading/pull/407), thanks @sambazhu), zero-sized order-field handling in `trading_place_order` ([#417](https://github.com/HKUDS/Vibe-Trading/pull/417), thanks @irfanallana-oss), and timezone-aware UTC timestamps across session/API paths ([#397](https://github.com/HKUDS/Vibe-Trading/pull/397), thanks @mustafakamal88).@@ -645,7 +645,7 @@ vibe-trading research-artifact search --query "NVDA"## 📡 Data Sources & Smart Fallback-One `get_market_data` call, **29 market-data sources**, one of them the optional **QVeris** premium marketplace. Set `source: "auto"` — the loader picks by symbol, then walks a per-market chain ordered by **IP-ban risk**: never-banned public sources first, throttled / key-gated ones last. Zero config, no single point of failure.+One `get_market_data` call, **28 market-data sources**. Set `source: "auto"` — the loader picks by symbol, then walks a per-market chain ordered by **IP-ban risk**: never-banned public sources first, throttled / key-gated ones last. Zero config, no single point of failure.| Source | Markets | Auth | Role ||--------|---------|------|------|@@ -654,13 +654,12 @@ One `get_market_data` call, **29 market-data sources**, one of them the optional| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `gildata` | A-share | token (Settings / `GILDATA_TOKEN`) | Hundsun Juyuan (恒生聚源) commercial feed — forward-adjusted dailies, joins the A-share chain tail |+| `gildata` | A / HK / CN index | `GILDATA_TOKEN` + `market_quotes` | Market quotes (explicit Gildata requests only) · `source="gildata"` || `yahoo` | US / HK / Canada / UK | none | direct chart/quotes/options; TSX `.TO` / TSXV `.V`; LSE `.L` with declared-currency normalization || `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV || `yfinance` | US / HK / Canada / UK | none | wrapper; TSX `.TO` / TSXV `.V`; LSE `.L` under the same GBP/GBp contract || `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |-| `qveris` | global multi-asset | key · credits | **premium marketplace** — 63+ providers via one key (explicit-only, never in auto fallback) || `nobitex` · `wallex` | crypto (Iranian Toman pairs) | none | public UDF endpoints; **explicit-only** — the only Toman-quoted sources, so they never join the crypto chain where a USD-quoted series could stand in for one || `okx` · `ccxt` · `binance` | crypto | none | OKX + 100+ exchanges + Binance historical / USD-M perps || `futu` | HK / A | OpenD | optional local FutuOpenD |@@ -671,22 +670,18 @@ One `get_market_data` call, **29 market-data sources**, one of them the optional| `b3_cotahist` | Brazil (B3) | none | official daily B3 cash/odd-lot bars (raw, BRL) from the local store populated by `python -m src.br_data sync`; offline fallback for `.SA` || `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |-Setting `GILDATA_TOKEN` enables combined queries via `gildata_fin_query`, stock screening with cross-period indicators via `gildata_stock_selection`, and Gildata stock candidates in `search_symbol`.--The optional Shannon portfolio diagnosis tab on the correlation page uses `GILDATA_TOKEN` to show A-share portfolio style exposures, a stock exposure heatmap and volatility contribution shares. An optional as-of date and entered weights define the snapshot; these shares are not loss probabilities.-Local sources can read bar dates from a `DatetimeIndex`, with or without aconfigured `date_format`; an explicitly mapped date column takes precedence.**Fallback chains (by IP-ban risk):**-- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`+- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`- **US** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`-- **HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `gildata` · `local`+- **HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`- **India (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`- **Brazil (B3 `.SA`)** → `yahoo` · `yfinance` · `b3_cotahist` · `local`- **Korea (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`-- **Indices** → `yahoo` · `yfinance` · `gildata` · `local`+- **Indices** → `yahoo` · `yfinance` · `local`- **UK (LSE)** → `yahoo` · `yfinance` · `local` *(declared GBP/GBp quotes only)*- **Crypto** → `okx` · `binance` · `ccxt` · `yfinance` · `local`- **Forex / metals** → `mt5` · `akshare` · `yfinance` · `local`@@ -753,15 +748,9 @@ In an Agent conversation, ask explicitly: **"Use Longbridge to fetch QQQ.US histBeyond OHLCV, **29 read-only data tools** reach into fundamentals & flow — fund flow, dragon-tiger, northbound, southbound, margin, block trades, shareholder count, lockup, sector, research reports, broker research search, news, SEC filings, Chinese-market announcements, financial statements, PIT fundamentals, options chains, crypto order-book depth, stock profile, market screening, symbol search, macro, China macro (EDB), iwencai, institutional holdings (13F), ETF look-through, off-exchange fund NAV, prediction markets, and research papers — all exposed over MCP. An explicit `local:` symbol never silently falls back to a network source.-<!-- QVERIS-START -->-### 💎 Optional premium data — QVeris--<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">--**Data: free routing or premium, your choice.** Free stays the default: 29 built-in sources with ban-risk fallback, no key, no cost. Premium via QVeris adds 10,000+ capabilities (per QVeris) across 63+ providers for options Greeks, premium fundamentals, China/HK/global data, macro, crypto, news, and filings; failed calls are not charged. Enable it in Settings -> QVeris or `vibe-trading data mode paid`.+### Data partner · [Gildata](https://www.gildata.com/products/datamap)-*QVeris disclosure: [signing up through the Vibe-Trading referral link](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) gets you **+1,000 bonus credits** and supports the project.*-<!-- QVERIS-END -->+Each Gildata feature requires a token and a separate opt-in under Settings → Data sources. This includes fund NAVs, macro indicators, announcements, broker reports, combined queries, screening, symbol search, portfolio diagnosis and explicitly requested quotes. All nine features are off by default. A saved token alone enables none of them, including after an upgrade. Even with market quotes enabled, Gildata is used only when explicitly selected. Free sources never fall back to Gildata.---@@ -770,15 +759,15 @@ Beyond OHLCV, **29 read-only data tools** reach into fundamentals & flow — funDetailed inventories are folded below to keep the main README scannable. Open them when you want to inspect the available building blocks.<details>-<summary><b>Finance Skill Library</b> <sub>90 skills across 9 categories</sub></summary>+<summary><b>Finance Skill Library</b> <sub>89 skills across 9 categories</sub></summary>-- 📊 90 specialized finance skills organized into 9 categories+- 📊 89 specialized finance skills organized into 9 categories- 🌐 Complete coverage from traditional markets to crypto & DeFi- 🔬 Comprehensive capabilities spanning data sourcing to quantitative research| Category | Skills | Examples ||----------|--------|----------|-| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 23 | `factor-research`, `correlation-regime`, `macro-analysis`, `global-macro`, `valuation-model`, `investor-lenses`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1381,7 +1370,7 @@ vibe-trading provider doctor # print redacted provider/proxy/package diagnostic| `/connector` | Trading connector profiles (status / start / halt) || `/halt` | Kill switch — halt ALL live trading now || `/resume` | Clear the kill switch (re-enable live trading) |-| `/data` | Data routing mode |+| `/data` | Data partner settings || `/quit` | Exit (also: q, exit, :q) |</details>@@ -1936,7 +1925,7 @@ Posting `{}` schedules a template on its own suggested cadence with its declared## 🔌 MCP Plugin-Vibe-Trading exposes 84 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 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.**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`:@@ -2005,7 +1994,7 @@ with `--host` / `--port`.</details>-**MCP tools exposed (84):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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 tools exposed (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`, `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`.`web_search` tries its existing Sogou and Bing China fallbacks when ddgs returnsno results or fails. Set `VIBE_TRADING_SEARCH_BING_FALLBACK=0` to disable both.@@ -2057,7 +2046,7 @@ Browse on ClawHub: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/vi<details><summary><b>OpenSpace — self-evolving skills</b></summary>-All 90 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.+All 89 finance skills are published on [open-space.cloud](https://open-space.cloud) and evolve autonomously through OpenSpace's self-evolution engine.To use with OpenSpace, add both MCP servers to your agent config:@@ -2079,7 +2068,7 @@ To use with OpenSpace, add both MCP servers to your agent config:}```-OpenSpace will auto-discover all 90 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.+OpenSpace will auto-discover all 89 skills, enabling auto-fix, auto-improve, and community sharing. Search for Vibe-Trading skills via `search_skills("finance backtest")` in any OpenSpace-connected agent.</details>@@ -2450,13 +2439,13 @@ 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 — 84 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core│ │ │ ├── loop.py # 5-layer compression + read/write tool batching│ │ │ ├── context.py # system prompt + auto-recall from persistent memory-│ │ │ ├── skills.py # skill loader (90 bundled + user-created via CRUD)+│ │ │ ├── skills.py # skill loader (89 bundled + user-created via CRUD)│ │ │ ├── tools.py # tool base class + registry│ │ │ ├── memory.py # lightweight workspace state per run│ │ │ ├── frontmatter.py # shared YAML frontmatter parser@@ -2483,7 +2472,7 @@ Vibe-Trading/│ │ ├── api/ # FastAPI route modules│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream│ │ │-│ │ ├── skills/ # 90 finance skills in 9 categories (SKILL.md each)+│ │ ├── skills/ # 89 finance skills in 9 categories (SKILL.md each)│ │ ├── swarm/ # Swarm DAG execution engine│ │ │ └── presets/ # 30 swarm preset YAML definitions│ │ ├── session/ # Multi-turn chat + FTS5 session search@@ -2491,7 +2480,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist+│ ├── loaders/ # 28 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, india_broker, tickerall, gildata, b3_cotahist│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_ar.md b/README_ar.mdindex fa6cc279f..b161dd6d5 100644--- a/README_ar.md+++ b/README_ar.md@@ -242,7 +242,7 @@- **2026-07-09** 🧯 **إزالة عائق بدء Docker + دفعة مساهمين لـ provider/CLI**: لم يعد بدء Docker/server ينهار عندما يمرّ FastAPI route iteration على عنصر included-router-like لا يملك `path` ([#450](https://github.com/HKUDS/Vibe-Trading/issues/450)، شكراً @Penn-Live). كما دُمجت دفعة quick-win من إصلاحات المساهمين: توحّدت تواقيع `fetch()` في loaders الخاصة بـ OKX / Tushare / yfinance مع البروتوكول ([#437](https://github.com/HKUDS/Vibe-Trading/pull/437)، شكراً @shadowinlife)، ويحفظ CLI resume prompt أول رسالة يكتبها المستخدم ([#448](https://github.com/HKUDS/Vibe-Trading/pull/448)، يغلق [#447](https://github.com/HKUDS/Vibe-Trading/issues/447)، شكراً @morluto)، وتحوّل default في Codex OAuth إلى `openai-codex/gpt-5.4` ([#446](https://github.com/HKUDS/Vibe-Trading/pull/446)، شكراً @morluto)، وأصبح Kimi for Coding مزوداً مستقلاً ([#435](https://github.com/HKUDS/Vibe-Trading/pull/435)، شكراً @yxhuang)، ووُصلت opencode provider mappings ([#444](https://github.com/HKUDS/Vibe-Trading/pull/444)، شكراً @imsankz)، كما صُححت code fences في مراجع Tushare من `pyhton` إلى `python` ([#449](https://github.com/HKUDS/Vibe-Trading/pull/449)، شكراً @flash1234pku). شمل التحقق focused server/CLI/provider/loader tests وDocker build و`/health` smoke.-- **2026-07-08** 💎 **طبقة العوامل الأساسية (المرحلة 1) + بيانات QVeris المدفوعة الاختيارية + يوم صيانة**: بيانات SEC المالية الآمنة زمنياً (PIT-safe) تتدفق الآن مباشرة إلى panels العوامل اليومية —— أعمدة `fund:*`، وتثبيت على تاريخ `filed` (مع حماية من إعادة البيانات وإطارات YTD)، و4 عوامل جودة/قيمة جديدة (يضم zoo الآن 460 alphas). اكتسب توجيه البيانات مساراً مدفوعاً اختيارياً: تبقى المصادر المجانية الـ18 هي الافتراضية، بينما يفتح QVeris أكثر من 63 مزوداً عبر Settings → QVeris أو `vibe-trading data mode paid` (انظر قسم QVeris أدناه). أيضاً: اكتملت وحدات `api_server` (من 1,103 إلى 371 سطراً، [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) يغلق [#331](https://github.com/HKUDS/Vibe-Trading/issues/331)، شكراً @shadowinlife)، ولم يعد `validation.json` في الاختبار الخلفي يتطلب وجود دليل artifacts مسبقاً ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429)، شكراً @isaveall)، وأصبحت أخطاء `--swarm-run` أوضح ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428)، شكراً @isaveall)، وقمنا بالتراجع عن governance stack الذي عطّل محادثات الجلسات ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433)، شكراً @yxhuang على التشخيص الدقيق).+- **2026-07-08** 💎 **طبقة العوامل الأساسية (المرحلة 1) + بيانات QVeris المدفوعة الاختيارية + يوم صيانة**: بيانات SEC المالية الآمنة زمنياً (PIT-safe) تتدفق الآن مباشرة إلى panels العوامل اليومية —— أعمدة `fund:*`، وتثبيت على تاريخ `filed` (مع حماية من إعادة البيانات وإطارات YTD)، و4 عوامل جودة/قيمة جديدة (يضم zoo الآن 460 alphas). أيضاً: اكتملت وحدات `api_server` (من 1,103 إلى 371 سطراً، [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) يغلق [#331](https://github.com/HKUDS/Vibe-Trading/issues/331)، شكراً @shadowinlife)، ولم يعد `validation.json` في الاختبار الخلفي يتطلب وجود دليل artifacts مسبقاً ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429)، شكراً @isaveall)، وأصبحت أخطاء `--swarm-run` أوضح ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428)، شكراً @isaveall)، وقمنا بالتراجع عن governance stack الذي عطّل محادثات الجلسات ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433)، شكراً @yxhuang على التشخيص الدقيق).- **2026-07-07** ✅ **دفعة PR للمساهمين**: دُمجت أعمال المساهمين المنتظرة: إعداد IM channel timeout ([#413](https://github.com/HKUDS/Vibe-Trading/pull/413)، شكراً @SyntaxSawdust)، وAlpha Library social previews ودليل المبتدئين ([#396](https://github.com/HKUDS/Vibe-Trading/pull/396)، [#393](https://github.com/HKUDS/Vibe-Trading/pull/393)، شكراً @kadaliao)، وvalue-investing skills / tools / committee presets ([#407](https://github.com/HKUDS/Vibe-Trading/pull/407)، شكراً @sambazhu)، ومعالجة حقول order sizing ذات القيمة الصفرية في `trading_place_order` ([#417](https://github.com/HKUDS/Vibe-Trading/pull/417)، شكراً @irfanallana-oss)، وtimezone-aware UTC timestamps عبر session/API paths ([#397](https://github.com/HKUDS/Vibe-Trading/pull/397)، شكراً @mustafakamal88).@@ -503,7 +503,7 @@ vibe-trading connector install /tmp/my-broker## 📡 مصادر البيانات والتراجع الذكي-استدعاء واحد لـ `get_market_data`، **29 مصدر بيانات سوقية**، أحدها سوق **QVeris** المدفوع الاختياري (إضافة إلى سوق مدفوع اختياري **QVeris**). اضبط `source: "auto"` — يختار المُحمّل حسب الرمز، ثم يسير عبر سلسلة لكل سوق مرتبة بحسب **خطر حظر عنوان IP**: المصادر العامة التي لا تُحظر أبداً أولاً، والمصادر المُقيّدة أو المحمية بمفتاح أخيراً. بلا أي إعداد، ولا نقطة فشل واحدة.+استدعاء واحد لـ `get_market_data`، **28 مصدر بيانات سوقية**. اضبط `source: "auto"` — يختار المُحمّل حسب الرمز، ثم يسير عبر سلسلة لكل سوق مرتبة بحسب **خطر حظر عنوان IP**: المصادر العامة التي لا تُحظر أبداً أولاً، والمصادر المُقيّدة أو المحمية بمفتاح أخيراً. بلا أي إعداد، ولا نقطة فشل واحدة.| Source | Markets | Auth | Role ||--------|---------|------|------|@@ -512,13 +512,12 @@ vibe-trading connector install /tmp/my-broker| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `gildata` | A-share | token (Settings / `GILDATA_TOKEN`) | Hundsun Juyuan (恒生聚源) commercial feed — forward-adjusted dailies, joins the A-share chain tail |+| `gildata` | A / HK / CN index | `GILDATA_TOKEN` + `market_quotes` | أسعار السوق (عند طلب Gildata صراحةً فقط) · `source="gildata"` || `yahoo` | US / HK / كندا / المملكة المتحدة | none | direct chart/quotes/options؛ TSX `.TO` / TSXV `.V`؛ تطبيع LSE `.L` حسب العملة المعلنة || `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV || `yfinance` | US / HK / كندا / المملكة المتحدة | none | wrapper؛ TSX `.TO` / TSXV `.V`؛ يلتزم LSE `.L` بعقد GBP/GBp نفسه || `longbridge` | US / HK | App Key + App Secret + Access Token | مصدر OHLCV تاريخي اختياري؛ ثبّت الـ SDK الاختياري || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |-| `qveris` | أصول عالمية متعددة | key · credits | **سوق مدفوع** — 63+ مزوداً بمفتاح واحد (اختيار صريح فقط، خارج التراجع التلقائي) || `nobitex` · `wallex` | العملات المشفّرة (أزواج بالتومان الإيراني) | لا شيء | نقاط نهاية UDF عامة، **بالاختيار الصريح فقط** — فهما المصدران الوحيدان المسعّران بالتومان، ولذلك لا ينضمان أبدًا إلى سلسلة العملات المشفّرة حيث قد تحل محلهما سلسلة مسعّرة بالدولار || `okx` · `ccxt` · `binance` | crypto | none | OKX + 100+ exchanges + Binance historical / USD-M perps || `futu` | HK / A | OpenD | optional local FutuOpenD |@@ -529,19 +528,15 @@ vibe-trading connector install /tmp/my-broker| `b3_cotahist` | Brazil (B3) | none | شموع B3 اليومية المحلية للسوق النقدي والكسور (خام، BRL)، عبر `python -m src.br_data sync`؛ مصدر بديل دون اتصال لـ `.SA` || `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |-يؤدي ضبط `GILDATA_TOKEN` إلى تفعيل الاستعلامات المجمعة عبر `gildata_fin_query`، وفرز الأسهم مع مؤشرات لفترات تقارير متعددة عبر `gildata_stock_selection`، وإضافة مرشحي الأسهم من Gildata إلى `search_symbol`.--تستخدم علامة تبويب تشخيص المحفظة الاختيارية Shannon في صفحة الارتباط `GILDATA_TOKEN` لعرض تعرض محفظة أسهم A لعوامل النمط، وخريطة حرارية لكل سهم، وحصص المساهمة في التقلب. يمكن تحديد تاريخ التحليل وأوزان الحيازات؛ وهذه الحصص ليست احتمالات خسارة.-**سلاسل التراجع (بحسب خطر حظر عنوان IP):**-- **أسهم A** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`+- **أسهم A** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`- **أسهم US** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`-- **أسهم HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `gildata` · `local`+- **أسهم HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`- **أسهم الهند (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`- **Brazil (B3 `.SA`)** → `yahoo` · `yfinance` · `b3_cotahist` · `local`- **كوريا (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`-- **المؤشرات** → `yahoo` · `yfinance` · `gildata` · `local`+- **المؤشرات** → `yahoo` · `yfinance` · `local`- **المملكة المتحدة (LSE)** → `yahoo` · `yfinance` · `local` *(الأسعار المعلنة بـ GBP/GBp فقط)*- **الكريبتو** → `okx` · `binance` · `ccxt` · `yfinance` · `local`- **الفوركس / المعادن** → `mt5` · `akshare` · `yfinance` · `local`@@ -580,15 +575,9 @@ LONGBRIDGE_ACCESS_TOKEN=...إلى جانب OHLCV، تصل **29 أداة بيانات للقراءة فقط** إلى الأساسيات والتدفقات — تدفق الأموال، والتنين والنمر، والتدفق الشمالي، والتدفق الجنوبي، والهامش، والصفقات الكتلية، وعدد المساهمين، وفترة الإغلاق، والقطاعات، وتقارير الأبحاث، والبحث في تقارير الوسطاء، والأخبار، وإيداعات SEC، وإعلانات السوق الصينية، والقوائم المالية، والأساسيات وفق PIT، وسلاسل الخيارات، وعمق دفتر أوامر العملات المشفرة، وملف الشركة، وفحص السوق، والبحث عن الرموز، والاقتصاد الكلي، والاقتصاد الكلي الصيني (EDB)، وiwencai، والحيازات المؤسسية (13F)، وتفكيك محافظ ETF، وصافي قيمة أصول الصناديق الصينية خارج البورصة، وأسواق التنبؤ، والأوراق البحثية — وكلها مكشوفة عبر MCP. ولا يتراجع رمز `local:` صريح أبداً وبصمت إلى مصدر شبكي.-<!-- QVERIS-START -->-### 💎 بيانات مدفوعة اختيارية — QVeris--<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">--**البيانات المجانية هي الافتراضي، والمدفوعة عند الحاجة.** تبقى المصادر الـ29 المدمجة مجانية مع تراجع ذكي بحسب خطر الحظر، بلا مفتاح ولا تكلفة. عبر QVeris يفتح مفتاح واحد 63+ مزوداً و10,000+ capabilities (per QVeris) للـ options Greeks، والأساسيات المتقدمة، وبيانات الصين/هونغ كونغ/العالم، والماكرو، والكريبتو، والأخبار، والـ filings؛ ولا تُحتسب المكالمات الفاشلة. فعّله من Settings → QVeris أو `vibe-trading data mode paid`.+### شريك البيانات · [Gildata](https://www.gildata.com/products/datamap)-*QVeris disclosure: التسجيل عبر [رابط إحالة Vibe-Trading](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) يمنحك **+1,000 رصيداً** إضافياً ويدعم المشروع.*-<!-- QVERIS-END -->+تتطلب كل ميزة من ميزات Gildata رمز وصول وتفعيلًا منفصلًا من إعدادات مصادر البيانات. تظل جميع الميزات معطلة افتراضيًا حتى بعد الترقية.---@@ -597,15 +586,15 @@ LONGBRIDGE_ACCESS_TOKEN=...القوائم التفصيلية مطوية أدناه حتى يبقى README سهل القراءة. افتحها عندما تريد فحص اللبنات المتاحة.<details>-<summary><b>مكتبة المهارات المالية</b> <sub>90 مهارة عبر 9 فئات</sub></summary>+<summary><b>مكتبة المهارات المالية</b> <sub>89 مهارة عبر 9 فئات</sub></summary>-- 📊 90 مهارة مالية متخصصة منظمة في 9 فئات+- 📊 89 مهارة مالية متخصصة منظمة في 9 فئات- 🌐 تغطية كاملة من الأسواق التقليدية إلى الكريبتو وDeFi- 🔬 قدرات شاملة من مصادر البيانات إلى البحث الكمي| الفئة | المهارات | أمثلة ||----------|--------|----------|-| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 23 | `factor-research`, `correlation-regime`, `macro-analysis`, `global-macro`, `valuation-model`, `investor-lenses`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1060,7 +1049,7 @@ vibe-trading provider doctor # طباعة تشخيصات المزود/الوك| `/connector` | ملفات موصّلات التداول (الحالة / التشغيل / الإيقاف) || `/halt` | مفتاح الإيقاف — أوقف كل التداول الحي فوراً || `/resume` | إلغاء مفتاح الإيقاف (إعادة تفعيل التداول الحي) |-| `/data` | وضع توجيه البيانات |+| `/data` | إعدادات شريك البيانات || `/quit` | خروج (أيضاً q و exit و :q) |</details>@@ -1338,7 +1327,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-يعرض Vibe-Trading 84 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.+يعرض Vibe-Trading 81 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.**متغيرات البيئة:** العميل هو من يشغّل الخادم بنفسه، لذا لا يصل إليه `export` من الـ shell أبداً —— اضبطها في كتلة `env` الخاصة بالعميل. كود الاختبار الخلفي المولَّد محصور ضمن جذور التشغيل المسموح بها، لذا تحتاج إلى `VIBE_TRADING_ALLOWED_RUN_ROOTS` لكتابة النتائج في دليل عمل خاص بك:@@ -1394,7 +1383,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**أدوات MCP المعروضة (84):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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 المعروضة (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`, `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@@ -1418,7 +1407,7 @@ npx clawhub@latest install vibe-trading --force<details><summary><b>OpenSpace — مهارات ذاتية التطور</b></summary>-كل المهارات المالية الـ 90 منشورة على [open-space.cloud](https://open-space.cloud) وتتطور ذاتياً عبر محرك التطور الذاتي في OpenSpace.+كل المهارات المالية الـ 89 منشورة على [open-space.cloud](https://open-space.cloud) وتتطور ذاتياً عبر محرك التطور الذاتي في OpenSpace.للاستخدام مع OpenSpace، أضف خادمي MCP إلى إعداد وكيلك:@@ -1440,7 +1429,7 @@ npx clawhub@latest install vibe-trading --force}```-سيكتشف OpenSpace كل المهارات الـ 90 تلقائياً، مما يتيح auto-fix وauto-improve والمشاركة المجتمعية. ابحث عن مهارات Vibe-Trading عبر `search_skills("finance backtest")` في أي وكيل متصل بـ OpenSpace.+سيكتشف OpenSpace كل المهارات الـ 89 تلقائياً، مما يتيح auto-fix وauto-improve والمشاركة المجتمعية. ابحث عن مهارات Vibe-Trading عبر `search_skills("finance backtest")` في أي وكيل متصل بـ OpenSpace.</details>@@ -1754,13 +1743,13 @@ 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 — 84 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core│ │ │ ├── loop.py # 5-layer compression + read/write tool batching│ │ │ ├── context.py # system prompt + auto-recall from persistent memory-│ │ │ ├── skills.py # skill loader (90 bundled + user-created via CRUD)+│ │ │ ├── skills.py # skill loader (89 bundled + user-created via CRUD)│ │ │ ├── tools.py # tool base class + registry│ │ │ ├── memory.py # lightweight workspace state per run│ │ │ ├── frontmatter.py # shared YAML frontmatter parser@@ -1787,7 +1776,7 @@ Vibe-Trading/│ │ ├── api/ # وحدات مسارات FastAPI│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream│ │ │-│ │ ├── skills/ # 90 finance skills in 9 categories (SKILL.md each)+│ │ ├── skills/ # 89 finance skills in 9 categories (SKILL.md each)│ │ ├── swarm/ # Swarm DAG execution engine│ │ │ └── presets/ # 30 swarm preset YAML definitions│ │ ├── session/ # Multi-turn chat + FTS5 session search@@ -1795,7 +1784,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist+│ ├── loaders/ # 28 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, india_broker, tickerall, gildata, b3_cotahist│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_es.md b/README_es.mdindex 3c81cca62..445eed30c 100644--- a/README_es.md+++ b/README_es.md@@ -242,7 +242,7 @@- **2026-07-09** 🧯 **Desbloqueo del arranque de Docker + lote de contribuidores de proveedores/CLI**: el arranque de Docker/servidor ya no falla cuando la iteración de rutas de FastAPI encuentra una entrada tipo router incluido sin `path` ([#450](https://github.com/HKUDS/Vibe-Trading/issues/450), gracias @Penn-Live). También incorporamos las correcciones rápidas en cola de contribuidores: las firmas de `fetch()` de los loaders ahora coinciden con el protocolo en OKX / Tushare / yfinance ([#437](https://github.com/HKUDS/Vibe-Trading/pull/437), gracias @shadowinlife), el prompt de reanudación de la CLI preserva el primer mensaje del usuario ([#448](https://github.com/HKUDS/Vibe-Trading/pull/448), cierra [#447](https://github.com/HKUDS/Vibe-Trading/issues/447), gracias @morluto), el OAuth de Codex usa por defecto `openai-codex/gpt-5.4` ([#446](https://github.com/HKUDS/Vibe-Trading/pull/446), gracias @morluto), Kimi for Coding está disponible como un proveedor distinto ([#435](https://github.com/HKUDS/Vibe-Trading/pull/435), gracias @yxhuang), los mapeos de proveedor de opencode están conectados ([#444](https://github.com/HKUDS/Vibe-Trading/pull/444), gracias @imsankz), y los bloques de código de referencia de Tushare ahora dicen `python` en lugar de `pyhton` ([#449](https://github.com/HKUDS/Vibe-Trading/pull/449), gracias @flash1234pku). La validación incluyó tests focalizados de servidor/CLI/proveedor/loader además de un build de Docker y un smoke test de `/health`.-- **2026-07-08** 💎 **Capa de factores fundamentales (Fase 1) + datos premium opcionales de QVeris + día de mantenimiento**: los fundamentales de la SEC seguros ante PIT ahora fluyen a los paneles de factores diarios — columnas de panel `fund:*`, anclaje por fecha de presentación con protección ante reformulaciones y marcos YTD, y 4 nuevos factores de calidad/valor (el registro ya tiene 460 alphas). El enrutamiento de datos gana una vía premium opcional: las 18 fuentes gratuitas siguen siendo la opción por defecto, mientras que QVeris desbloquea más de 63 proveedores vía Settings → QVeris o `vibe-trading data mode paid` (ver la sección de QVeris más abajo). Además: se completa la modularización de `api_server` (1,103 → 371 líneas, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) cerrando [#331](https://github.com/HKUDS/Vibe-Trading/issues/331), gracias @shadowinlife), el `validation.json` del backtest ya no requiere un directorio de artefactos preexistente ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), gracias @isaveall), errores de `--swarm-run` más claros ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), gracias @isaveall), y revertimos la pila de gobernanza que rompía los chats de sesión ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), gracias @yxhuang por el diagnóstico preciso).+- **2026-07-08** 💎 **Capa de factores fundamentales (Fase 1) + datos premium opcionales de QVeris + día de mantenimiento**: los fundamentales de la SEC seguros ante PIT ahora fluyen a los paneles de factores diarios — columnas de panel `fund:*`, anclaje por fecha de presentación con protección ante reformulaciones y marcos YTD, y 4 nuevos factores de calidad/valor (el registro ya tiene 460 alphas). Además: se completa la modularización de `api_server` (1,103 → 371 líneas, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) cerrando [#331](https://github.com/HKUDS/Vibe-Trading/issues/331), gracias @shadowinlife), el `validation.json` del backtest ya no requiere un directorio de artefactos preexistente ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), gracias @isaveall), errores de `--swarm-run` más claros ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), gracias @isaveall), y revertimos la pila de gobernanza que rompía los chats de sesión ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), gracias @yxhuang por el diagnóstico preciso).- **2026-07-07** ✅ **Lote de PR de contribuidores**: se fusionó el trabajo en cola de contribuidores para la configuración de timeout de canales IM ([#413](https://github.com/HKUDS/Vibe-Trading/pull/413), gracias @SyntaxSawdust), las vistas previas sociales de Alpha Library y el tutorial para principiantes ([#396](https://github.com/HKUDS/Vibe-Trading/pull/396), [#393](https://github.com/HKUDS/Vibe-Trading/pull/393), gracias @kadaliao), skills / herramientas / presets de comité de value investing ([#407](https://github.com/HKUDS/Vibe-Trading/pull/407), gracias @sambazhu), el manejo de campos de orden de tamaño cero en `trading_place_order` ([#417](https://github.com/HKUDS/Vibe-Trading/pull/417), gracias @irfanallana-oss), y timestamps UTC con reconocimiento de zona horaria en las rutas de sesión/API ([#397](https://github.com/HKUDS/Vibe-Trading/pull/397), gracias @mustafakamal88).@@ -502,7 +502,7 @@ La mayoría de las ejecuciones siguen la misma ruta de evidencia: enrutar la sol## 📡 Fuentes de Datos y Fallback Inteligente-Una sola llamada `get_market_data`, **29 fuentes de datos de mercado**, una de ellas el mercado premium opcional **QVeris** (además del mercado premium opcional **QVeris**). Establece `source: "auto"`: el cargador elige según el símbolo y luego recorre una cadena por mercado ordenada por **riesgo de bloqueo de IP**: primero las fuentes públicas que nunca se bloquean, al final las limitadas o que requieren clave. Cero configuración, sin punto único de fallo.+Una sola llamada `get_market_data`, **28 fuentes de datos de mercado**. Establece `source: "auto"`: el cargador elige según el símbolo y luego recorre una cadena por mercado ordenada por **riesgo de bloqueo de IP**: primero las fuentes públicas que nunca se bloquean, al final las limitadas o que requieren clave. Cero configuración, sin punto único de fallo.| Fuente | Mercados | Autenticación | Rol ||--------|---------|------|------|@@ -511,13 +511,12 @@ Una sola llamada `get_market_data`, **29 fuentes de datos de mercado**, una de e| `eastmoney` | A / EE. UU. / HK | ninguna | OHLCV + herramientas de fundamentales y flujo profundas (limitada) || `baostock` · `akshare` | A (+ EE. UU./HK/futuros/macro/fx) | ninguna | fallbacks gratuitos || `tushare` | A / HK / futuros / fondos / macro | token | la más completa para A-share |-| `gildata` | acciones A | token (Configuración / `GILDATA_TOKEN`) | fuente comercial Hundsun Juyuan (恒生聚源) — diarios ajustados hacia adelante, se une al final de la cadena de acciones A |+| `gildata` | A / HK / CN index | `GILDATA_TOKEN` + `market_quotes` | Cotizaciones (solo al seleccionar Gildata expresamente) · `source="gildata"` || `yahoo` | EE. UU. / HK / Canadá / Reino Unido | ninguna | gráfico/cotizaciones/opciones directos; TSX `.TO` / TSXV `.V`; LSE `.L` con normalización según la divisa declarada || `sina` · `stooq` | EE. UU. | ninguna | velas hasta 1984 · CSV EOD || `yfinance` | EE. UU. / HK / Canadá / Reino Unido | ninguna | wrapper; TSX `.TO` / TSXV `.V`; LSE `.L` bajo el mismo contrato GBP/GBp || `longbridge` | EE. UU. / HK | App Key + App Secret + Access Token | fuente OHLCV histórica opcional; instala el SDK opcional || `finnhub` · `alphavantage` · `tiingo` · `fmp` | EE. UU. | clave | proveedores opcionales |-| `qveris` | multiactivo global | clave · créditos | **mercado premium** — 63+ proveedores mediante una sola clave (solo explícito, nunca en el fallback automático) || `nobitex` · `wallex` | cripto (pares cotizados en tomán iraní) | ninguna | endpoints UDF públicos, **solo por selección explícita**: son las únicas fuentes cotizadas en tomán, así que nunca entran en la cadena de cripto, donde una serie cotizada en USD podría suplantarlas || `okx` · `ccxt` · `binance` | cripto | ninguna | OKX + 100+ exchanges + históricos de Binance / perpetuos USD-M || `futu` | HK / A | OpenD | FutuOpenD local opcional |@@ -528,19 +527,15 @@ Una sola llamada `get_market_data`, **29 fuentes de datos de mercado**, una de e| `b3_cotahist` | Brazil (B3) | none | barras diarias oficiales del mercado al contado y de lotes fraccionarios (sin ajustar, BRL), importadas con `python -m src.br_data sync`; alternativa local para `.SA` || `local` | cualquiera | ninguna | tu propio CSV / Parquet / DuckDB mediante el prefijo `local:` |-Al configurar `GILDATA_TOKEN`, se habilitan las consultas combinadas con `gildata_fin_query`, el filtrado de acciones con indicadores de varios periodos mediante `gildata_stock_selection` y los candidatos de acciones de Gildata en `search_symbol`.--La pestaña opcional de diagnóstico Shannon en la página de correlación usa `GILDATA_TOKEN` para mostrar exposiciones de estilo de una cartera de acciones A, un mapa de calor por acción y contribuciones a la volatilidad. Admite fecha y pesos de cartera; estas contribuciones no son probabilidades de pérdida.-**Cadenas de fallback (por riesgo de bloqueo de IP):**-- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`+- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`- **EE. UU.** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`-- **HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `gildata` · `local`+- **HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`- **India (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`- **Brazil (B3 `.SA`)** → `yahoo` · `yfinance` · `b3_cotahist` · `local`- **Corea (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`-- **Índices** → `yahoo` · `yfinance` · `gildata` · `local`+- **Índices** → `yahoo` · `yfinance` · `local`- **Reino Unido (LSE)** → `yahoo` · `yfinance` · `local` *(solo cotizaciones declaradas en GBP/GBp)*- **Cripto** → `okx` · `binance` · `ccxt` · `yfinance` · `local`- **Forex / metales** → `mt5` · `akshare` · `yfinance` · `local`@@ -579,15 +574,9 @@ En una conversación con el Agent, pide explícitamente: **"Use Longbridge to feMás allá del OHLCV, **29 herramientas de datos de solo lectura** alcanzan fundamentales y flujo: flujo de fondos, dragon-tiger, northbound, southbound, margen, operaciones en bloque, número de accionistas, lockup, sector, informes de investigación, búsqueda de informes de brókers, noticias, presentaciones ante la SEC, anuncios del mercado chino, estados financieros, fundamentales PIT, cadenas de opciones, profundidad del libro de órdenes cripto, perfil de la acción, screening de mercado, búsqueda de símbolos, macro, macro de China (EDB), iwencai, tenencias institucionales (13F), look-through de ETF, NAV de fondos chinos no cotizados, mercados de predicción y papers de investigación, todo expuesto a través de MCP. Un símbolo `local:` explícito nunca recurre en silencio a una fuente de red.-<!-- QVERIS-START -->-### 💎 Datos premium opcionales — QVeris--<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">--**Datos: enrutamiento gratuito o premium, tú decides.** Lo gratuito sigue siendo el valor por defecto: 29 fuentes integradas con fallback por riesgo de bloqueo, sin clave, sin costo. Lo premium mediante QVeris añade más de 10.000 capacidades (según QVeris) en 63+ proveedores para Greeks de opciones, fundamentales premium, datos de China/HK/globales, macro, cripto, noticias y presentaciones regulatorias; las llamadas fallidas no se cobran. Actívalo en Settings -> QVeris o con `vibe-trading data mode paid`.+### Socio de datos · [Gildata](https://www.gildata.com/products/datamap)-*Aviso de QVeris: [registrarte a través del enlace de referido de Vibe-Trading](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) te da **+1.000 créditos de bonificación** y apoya el proyecto.*-<!-- QVERIS-END -->+Cada función de Gildata requiere un token y se activa por separado en los ajustes de fuentes de datos. Todas están desactivadas por defecto, incluso después de actualizar.---@@ -596,15 +585,15 @@ Más allá del OHLCV, **29 herramientas de datos de solo lectura** alcanzan fundLos inventarios detallados se pliegan a continuación para mantener el README principal fácil de escanear. Ábrelos cuando quieras inspeccionar los bloques de construcción disponibles.<details>-<summary><b>Biblioteca de Skills Financieras</b> <sub>90 skills en 9 categorías</sub></summary>+<summary><b>Biblioteca de Skills Financieras</b> <sub>89 skills en 9 categorías</sub></summary>-- 📊 90 skills financieras especializadas organizadas en 9 categorías+- 📊 89 skills financieras especializadas organizadas en 9 categorías- 🌐 Cobertura completa desde mercados tradicionales hasta cripto y DeFi- 🔬 Capacidades integrales que abarcan desde el sourcing de datos hasta la investigación cuantitativa| Categoría | Skills | Ejemplos ||----------|--------|----------|-| Fuente de Datos | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |+| Fuente de Datos | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Estrategia | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Análisis | 23 | `factor-research`, `correlation-regime`, `macro-analysis`, `global-macro`, `valuation-model`, `investor-lenses`, `credit-analysis`, `dividend-analysis` || Clase de Activo | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1098,7 +1087,7 @@ vibe-trading provider doctor # imprime diagnósticos redactados de provider/pro| `/connector` | Perfiles de conectores de trading (estado / iniciar / detener) || `/halt` | Interruptor de emergencia — detiene TODO el trading en vivo de inmediato || `/resume` | Desactiva el interruptor de emergencia (reactiva el trading en vivo) |-| `/data` | Modo de enrutamiento de datos |+| `/data` | Configuración del socio de datos || `/quit` | Salir (también: q, exit, :q) |</details>@@ -1398,7 +1387,7 @@ Enviar `{}` programa una plantilla con su propia cadencia sugerida y sus valores## 🔌 MCP Plugin-Vibe-Trading expone 84 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 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.**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`:@@ -1469,7 +1458,7 @@ dirección de bind con `--host` / `--port`.</details>-**MCP tools expuestas (84):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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 tools expuestas (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`, `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@@ -1493,7 +1482,7 @@ Explora en ClawHub: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/v<details><summary><b>OpenSpace — self-evolving skills</b></summary>-Los 90 skills de finanzas están publicados en [open-space.cloud](https://open-space.cloud) y evolucionan de forma autónoma mediante el motor de auto-evolución de OpenSpace.+Los 89 skills de finanzas están publicados en [open-space.cloud](https://open-space.cloud) y evolucionan de forma autónoma mediante el motor de auto-evolución de OpenSpace.Para usarlo con OpenSpace, añade ambos servidores MCP a la configuración de tu agente:@@ -1515,7 +1504,7 @@ Para usarlo con OpenSpace, añade ambos servidores MCP a la configuración de tu}```-OpenSpace descubrirá automáticamente los 90 skills, habilitando auto-fix, auto-improve y compartición comunitaria. Busca skills de Vibe-Trading mediante `search_skills("finance backtest")` en cualquier agente conectado a OpenSpace.+OpenSpace descubrirá automáticamente los 89 skills, habilitando auto-fix, auto-improve y compartición comunitaria. Busca skills de Vibe-Trading mediante `search_skills("finance backtest")` en cualquier agente conectado a OpenSpace.</details>@@ -1842,13 +1831,13 @@ 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 — 84 herramientas para OpenClaw / Claude Desktop+│ ├── mcp_server.py # Servidor MCP — 81 herramientas para OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # Núcleo del agente ReAct│ │ │ ├── loop.py # compresión de 5 capas + agrupación de herramientas de lectura/escritura│ │ │ ├── context.py # system prompt + auto-recuperación desde memoria persistente-│ │ │ ├── skills.py # cargador de skills (90 incluidas + creadas por el usuario vía CRUD)+│ │ │ ├── skills.py # cargador de skills (89 incluidas + creadas por el usuario vía CRUD)│ │ │ ├── tools.py # clase base de herramientas + registro│ │ │ ├── memory.py # estado ligero del workspace por ejecución│ │ │ ├── frontmatter.py # parser de frontmatter YAML compartido@@ -1875,7 +1864,7 @@ Vibe-Trading/│ │ ├── api/ # Módulos de rutas FastAPI│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, flujo SSE│ │ │-│ │ ├── skills/ # 90 skills financieras en 9 categorías (un SKILL.md cada una)+│ │ ├── skills/ # 89 skills financieras en 9 categorías (un SKILL.md cada una)│ │ ├── swarm/ # Motor de ejecución de DAG swarm│ │ │ └── presets/ # 30 definiciones YAML de presets swarm│ │ ├── session/ # Chat multi-turno + búsqueda de sesiones FTS5@@ -1883,7 +1872,7 @@ Vibe-Trading/│ ││ └── backtest/ # Motores de backtest│ ├── engines/ # 11 motores + motor compuesto multi-mercado + options_portfolio-│ ├── loaders/ # 29 fuentes: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist+│ ├── loaders/ # 28 fuentes: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, india_broker, tickerall, gildata, b3_cotahist│ │ ├── base.py # Protocolo DataLoader│ │ └── registry.py # Registro + cadenas de fallback automáticas│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_id.md b/README_id.mdindex 51f40a6e0..a2c3ced4b 100644--- a/README_id.md+++ b/README_id.md@@ -292,7 +292,7 @@- **2026-07-09** 🧯 **Startup Docker tidak lagi terblokir + batch contributor provider/CLI**: startup Docker/server tidak lagi crash ketika iterasi route FastAPI melihat entry mirip included-router tanpa `path` ([#450](https://github.com/HKUDS/Vibe-Trading/issues/450), terima kasih @Penn-Live). Kami juga memasukkan queued quick-win fix dari contributor: signature loader `fetch()` sekarang sesuai protocol untuk OKX / Tushare / yfinance ([#437](https://github.com/HKUDS/Vibe-Trading/pull/437), terima kasih @shadowinlife), prompt resume CLI mempertahankan message pertama user ([#448](https://github.com/HKUDS/Vibe-Trading/pull/448), menutup [#447](https://github.com/HKUDS/Vibe-Trading/issues/447), terima kasih @morluto), default Codex OAuth menjadi `openai-codex/gpt-5.4` ([#446](https://github.com/HKUDS/Vibe-Trading/pull/446), terima kasih @morluto), Kimi for Coding tersedia sebagai provider terpisah ([#435](https://github.com/HKUDS/Vibe-Trading/pull/435), terima kasih @yxhuang), mapping provider opencode terhubung ([#444](https://github.com/HKUDS/Vibe-Trading/pull/444), terima kasih @imsankz), dan code fence referensi Tushare sekarang menulis `python` alih-alih `pyhton` ([#449](https://github.com/HKUDS/Vibe-Trading/pull/449), terima kasih @flash1234pku). Validation mencakup focused test server/CLI/provider/loader plus Docker build dan smoke `/health`.-- **2026-07-08** 💎 **Layer fundamental factor (Phase 1) + optional premium data QVeris + maintainer day**: fundamentals SEC yang PIT-safe sekarang masuk langsung ke daily factor panel — column panel `fund:*`, anchoring berdasarkan filed date dengan proteksi restatement dan YTD frame, serta 4 factor quality/value baru (registry sekarang 460 alpha). Data routing mendapat optional premium track: 18 source gratis tetap menjadi default, sedangkan QVeris membuka 63+ provider melalui Settings → QVeris atau `vibe-trading data mode paid` (lihat bagian QVeris di bawah). Juga: modularisasi `api_server` selesai (1.103 → 371 baris, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) menutup [#331](https://github.com/HKUDS/Vibe-Trading/issues/331), terima kasih @shadowinlife), `validation.json` backtest tidak lagi membutuhkan directory artifacts yang sudah ada sebelumnya ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), terima kasih @isaveall), error `--swarm-run` lebih jelas ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), terima kasih @isaveall), dan kami merevert governance stack yang merusak session chat ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), terima kasih @yxhuang atas diagnosis yang presisi).+- **2026-07-08** 💎 **Layer fundamental factor (Phase 1) + optional premium data QVeris + maintainer day**: fundamentals SEC yang PIT-safe sekarang masuk langsung ke daily factor panel — column panel `fund:*`, anchoring berdasarkan filed date dengan proteksi restatement dan YTD frame, serta 4 factor quality/value baru (registry sekarang 460 alpha). Juga: modularisasi `api_server` selesai (1.103 → 371 baris, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424) menutup [#331](https://github.com/HKUDS/Vibe-Trading/issues/331), terima kasih @shadowinlife), `validation.json` backtest tidak lagi membutuhkan directory artifacts yang sudah ada sebelumnya ([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), terima kasih @isaveall), error `--swarm-run` lebih jelas ([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), terima kasih @isaveall), dan kami merevert governance stack yang merusak session chat ([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), terima kasih @yxhuang atas diagnosis yang presisi).- **2026-07-07** ✅ **Batch PR contributor**: queued contributor work untuk konfigurasi timeout IM channel digabungkan ([#413](https://github.com/HKUDS/Vibe-Trading/pull/413), terima kasih @SyntaxSawdust), bersama social preview Alpha Library dan tutorial pemula ([#396](https://github.com/HKUDS/Vibe-Trading/pull/396), [#393](https://github.com/HKUDS/Vibe-Trading/pull/393), terima kasih @kadaliao), skill / tool / committee preset value-investing ([#407](https://github.com/HKUDS/Vibe-Trading/pull/407), terima kasih @sambazhu), penanganan zero-sized order field di `trading_place_order` ([#417](https://github.com/HKUDS/Vibe-Trading/pull/417), terima kasih @irfanallana-oss), dan timestamp UTC timezone-aware di seluruh path session/API ([#397](https://github.com/HKUDS/Vibe-Trading/pull/397), terima kasih @mustafakamal88).@@ -664,7 +664,7 @@ the wall-clock activity watchdog.## 📡 Sumber Data & Smart Fallback-Satu call `get_market_data`, **29 sumber data market**, salah satunya marketplace premium opsional **QVeris**. Atur `source: "auto"` — loader memilih berdasarkan simbol lalu mengikuti chain per market yang diurutkan berdasarkan **risiko IP-ban**: sumber publik yang tidak pernah diblokir lebih dulu, sumber throttled / membutuhkan key belakangan. Zero-config, tanpa single point of failure.+Satu call `get_market_data`, **28 sumber data market**. Atur `source: "auto"` — loader memilih berdasarkan simbol lalu mengikuti chain per market yang diurutkan berdasarkan **risiko IP-ban**: sumber publik yang tidak pernah diblokir lebih dulu, sumber throttled / membutuhkan key belakangan. Zero-config, tanpa single point of failure.| Sumber | Market | Auth | Peran ||--------|---------|------|------|@@ -673,13 +673,12 @@ Satu call `get_market_data`, **29 sumber data market**, salah satunya marketplac| `eastmoney` | A / AS / HK | tidak ada | OHLCV + fundamental mendalam & tool flow (throttled) || `baostock` · `akshare` | A (+ AS/HK/futures/makro/fx) | tidak ada | fallback gratis || `tushare` | A / HK / futures / fund / makro | token | A-share paling kaya |-| `gildata` | A-share | token (Settings / `GILDATA_TOKEN`) | feed komersial Hundsun Juyuan (恒生聚源) — data harian forward-adjusted, bergabung di ujung chain A-share |+| `gildata` | A / HK / CN index | `GILDATA_TOKEN` + `market_quotes` | Harga pasar (hanya jika Gildata dipilih secara eksplisit) · `source="gildata"` || `yahoo` | AS / HK / Kanada / UK | tidak ada | chart/quote/options langsung; TSX `.TO` / TSXV `.V`; LSE `.L` dengan normalisasi mata uang yang dideklarasikan || `sina` · `stooq` | AS | tidak ada | K-line hingga 1984 · EOD CSV || `yfinance` | AS / HK / Kanada / UK | tidak ada | wrapper; TSX `.TO` / TSXV `.V`; LSE `.L` dengan contract GBP/GBp yang sama || `longbridge` | AS / HK | App Key + App Secret + Access Token | sumber historis OHLCV opsional; instal SDK opsional || `finnhub` · `alphavantage` · `tiingo` · `fmp` | AS | key | provider opsional |-| `qveris` | global multi-aset | key · kredit | **marketplace premium** — 63+ provider melalui satu key (hanya eksplisit, tidak pernah masuk auto fallback) || `nobitex` · `wallex` | crypto (pair Iranian Toman) | tidak ada | endpoint UDF publik; **hanya eksplisit** — satu-satunya sumber berdenominasi Toman, sehingga tidak masuk chain crypto yang dapat menggantikannya dengan series USD || `okx` · `ccxt` · `binance` | crypto | tidak ada | OKX + 100+ exchange + historis Binance / USD-M perps || `futu` | HK / A | OpenD | FutuOpenD lokal opsional |@@ -690,19 +689,15 @@ Satu call `get_market_data`, **29 sumber data market**, salah satunya marketplac| `b3_cotahist` | Brazil (B3) | none | bar harian resmi B3 untuk pasar tunai/odd-lot (mentah, BRL), diimpor dengan `python -m src.br_data sync`; cadangan luring untuk `.SA` || `local` | apa pun | tidak ada | CSV / Parquet / DuckDB Anda sendiri melalui prefix `local:` |-Mengatur `GILDATA_TOKEN` mengaktifkan kueri gabungan melalui `gildata_fin_query`, penyaringan saham dengan indikator lintas periode melalui `gildata_stock_selection`, dan kandidat saham Gildata di `search_symbol`.--Tab diagnosis portofolio Shannon opsional pada halaman korelasi menggunakan `GILDATA_TOKEN` untuk menampilkan eksposur gaya portofolio saham A, peta panas eksposur per saham, dan porsi kontribusi volatilitas. Tanggal analisis dan bobot kepemilikan dapat ditentukan; kontribusi ini bukan probabilitas kerugian.-**Fallback chain (berdasarkan risiko IP-ban):**-- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`+- **A-share** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`- **US** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`-- **HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `gildata` · `local`+- **HK** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`- **India (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`- **Brazil (B3 `.SA`)** → `yahoo` · `yfinance` · `b3_cotahist` · `local`- **Korea (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`-- **Indeks** → `yahoo` · `yfinance` · `gildata` · `local`+- **Indeks** → `yahoo` · `yfinance` · `local`- **UK (LSE)** → `yahoo` · `yfinance` · `local` *(declared GBP/GBp quotes only)*- **Crypto** → `okx` · `binance` · `ccxt` · `yfinance` · `local`- **Forex / metals** → `mt5` · `akshare` · `yfinance` · `local`@@ -741,15 +736,9 @@ Dalam percakapan Agent, minta secara eksplisit: **"Gunakan Longbridge untuk mengDi luar OHLCV, **29 tool data read-only** menjangkau fundamental & flow — fund flow, dragon-tiger, northbound, southbound, margin, block trade, jumlah pemegang saham, lockup, sektor, laporan riset, pencarian riset broker, berita, filing SEC, pengumuman pasar China, laporan keuangan, fundamental PIT, options chain, kedalaman order book kripto, profil saham, market screening, pencarian simbol, makro, makro China (EDB), iwencai, kepemilikan institusi (13F), ETF look-through, NAV reksa dana off-exchange China, prediction market, dan paper riset — semuanya tersedia melalui MCP. Simbol `local:` eksplisit tidak pernah diam-diam fallback ke sumber jaringan.-<!-- QVERIS-START -->-### 💎 Data premium opsional — QVeris--<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">--**Data: routing gratis atau premium, pilihan Anda.** Mode gratis tetap default: 29 sumber bawaan dengan fallback berdasarkan risiko ban, tanpa key dan tanpa biaya. Premium melalui QVeris menambahkan 10.000+ kapabilitas (menurut QVeris) dari 63+ provider untuk options Greeks, fundamental premium, data China/HK/global, makro, crypto, berita, dan filing; call yang gagal tidak dikenakan biaya. Aktifkan di Settings -> QVeris atau `vibe-trading data mode paid`.+### Mitra data · [Gildata](https://www.gildata.com/products/datamap)-*Disclosure QVeris: [mendaftar melalui referral link Vibe-Trading](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) memberi Anda **+1.000 bonus kredit** sekaligus mendukung proyek.*-<!-- QVERIS-END -->+Setiap fitur Gildata memerlukan token dan harus diaktifkan secara terpisah di pengaturan sumber data. Semuanya nonaktif secara bawaan, termasuk setelah pembaruan.---@@ -759,15 +748,15 @@ Di luar OHLCV, **29 tool data read-only** menjangkau fundamental & flow — fundInventaris detail dilipat di bawah agar README utama tetap mudah dipindai. Buka bagian yang Anda perlukan saat ingin memeriksa building block yang tersedia.<details>-<summary><b>Library Skill Finansial</b> <sub>90 skill dalam 9 kategori</sub></summary>+<summary><b>Library Skill Finansial</b> <sub>89 skill dalam 9 kategori</sub></summary>-- 📊 90 skill finansial khusus yang diorganisasi dalam 9 kategori+- 📊 89 skill finansial khusus yang diorganisasi dalam 9 kategori- 🌐 Cakupan lengkap dari market tradisional hingga crypto & DeFi- 🔬 Kapabilitas menyeluruh dari sourcing data hingga riset quant| Kategori | Skill | Contoh ||----------|--------|----------|-| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 23 | `factor-research`, `correlation-regime`, `macro-analysis`, `global-macro`, `valuation-model`, `investor-lenses`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1285,7 +1274,7 @@ vibe-trading provider doctor # print redacted provider/proxy/package diagnostic| `/connector` | Profil connector trading (status / start / halt) || `/halt` | Penghentian darurat — hentikan SEMUA live trading sekarang || `/resume` | Nonaktifkan penghentian darurat (aktifkan kembali live trading) |-| `/data` | Mode routing data |+| `/data` | Pengaturan mitra data || `/quit` | Keluar (juga: q, exit, :q) |</details>@@ -1644,7 +1633,7 @@ Mengirim `{}` akan menjadwalkan template memakai cadence yang disarankan beserta<a id="-mcp-plugin"></a>## 🔌 Plugin MCP-Vibe-Trading mengekspos 84 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 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.**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`:@@ -1713,7 +1702,7 @@ dengan `--host` / `--port`.</details>-**Tool MCP yang diekspos (84):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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 yang diekspos (81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`, `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@@ -1737,7 +1726,7 @@ Jelajahi di ClawHub: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/<details><summary><b>OpenSpace — skill yang berkembang sendiri</b></summary>-Semua 90 skill finansial dipublikasikan di [open-space.cloud](https://open-space.cloud) dan berkembang secara otonom melalui engine self-evolution OpenSpace.+Semua 89 skill finansial dipublikasikan di [open-space.cloud](https://open-space.cloud) dan berkembang secara otonom melalui engine self-evolution OpenSpace.Untuk menggunakan OpenSpace, tambahkan kedua server MCP ke config agent Anda:@@ -1759,7 +1748,7 @@ Untuk menggunakan OpenSpace, tambahkan kedua server MCP ke config agent Anda:}```-OpenSpace akan menemukan seluruh 90 skill secara otomatis, mengaktifkan auto-fix, auto-improve, dan sharing komunitas. Cari skill Vibe-Trading melalui `search_skills("finance backtest")` pada agent mana pun yang terhubung OpenSpace.+OpenSpace akan menemukan seluruh 89 skill secara otomatis, mengaktifkan auto-fix, auto-improve, dan sharing komunitas. Cari skill Vibe-Trading melalui `search_skills("finance backtest")` pada agent mana pun yang terhubung OpenSpace.</details>@@ -2087,13 +2076,13 @@ 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 — 84 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core│ │ │ ├── loop.py # 5-layer compression + read/write tool batching│ │ │ ├── context.py # system prompt + auto-recall from persistent memory-│ │ │ ├── skills.py # skill loader (90 bundled + user-created via CRUD)+│ │ │ ├── skills.py # skill loader (89 bundled + user-created via CRUD)│ │ │ ├── tools.py # tool base class + registry│ │ │ ├── memory.py # lightweight workspace state per run│ │ │ ├── frontmatter.py # shared YAML frontmatter parser@@ -2120,7 +2109,7 @@ Vibe-Trading/│ │ ├── api/ # FastAPI route modules│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream│ │ │-│ │ ├── skills/ # 90 finance skills in 9 categories (SKILL.md each)+│ │ ├── skills/ # 89 finance skills in 9 categories (SKILL.md each)│ │ ├── swarm/ # Swarm DAG execution engine│ │ │ └── presets/ # 30 swarm preset YAML definitions│ │ ├── session/ # Multi-turn chat + FTS5 session search@@ -2128,7 +2117,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist+│ ├── loaders/ # 28 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, india_broker, tickerall, gildata, b3_cotahist│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_ja.md b/README_ja.mdindex 71fcbba4d..1148a6d3a 100644--- a/README_ja.md+++ b/README_ja.md@@ -242,7 +242,7 @@- **2026-07-09** 🧯 **Docker 起動ブロック解除 + provider/CLI contributor batch**:FastAPI の route 走査で `path` を持たない included-router-like エントリに当たっても、Docker/server startup がクラッシュしなくなりました([#450](https://github.com/HKUDS/Vibe-Trading/issues/450)、@Penn-Live さんに感謝)。あわせて、キューにあった quick-win contributor fixes も入りました:OKX / Tushare / yfinance の loader `fetch()` signature を protocol と揃え([#437](https://github.com/HKUDS/Vibe-Trading/pull/437)、@shadowinlife さんに感謝)、CLI resume prompt は最初のユーザーメッセージを保持します([#448](https://github.com/HKUDS/Vibe-Trading/pull/448)、[#447](https://github.com/HKUDS/Vibe-Trading/issues/447) をクローズ、@morluto さんに感謝)。Codex OAuth default は `openai-codex/gpt-5.4` に更新され([#446](https://github.com/HKUDS/Vibe-Trading/pull/446)、@morluto さんに感謝)、Kimi for Coding は独立 provider として利用可能になり([#435](https://github.com/HKUDS/Vibe-Trading/pull/435)、@yxhuang さんに感謝)、opencode provider mapping も接続されました([#444](https://github.com/HKUDS/Vibe-Trading/pull/444)、@imsankz さんに感謝)。Tushare reference の code fence も `pyhton` から `python` に修正済みです([#449](https://github.com/HKUDS/Vibe-Trading/pull/449)、@flash1234pku さんに感謝)。検証は focused server/CLI/provider/loader tests、Docker build、`/health` smoke を含みます。-- **2026-07-08** 💎 **ファンダメンタル因子レイヤー(Phase 1)+ オプションの QVeris 有料データ + メンテナンスデー**:PIT-safe な SEC 財務データが日次因子 panel に直接流れ込むようになりました —— `fund:*` panel 列、filed 日アンカリング(リステートメント・YTD フレーム防護付き)、新規クオリティ/バリュー因子 4 本(zoo は 460 alphas に)。データルーティングにオプションの有料トラックを追加:18 の無料ソースが引き続きデフォルトで、QVeris は Settings → QVeris または `vibe-trading data mode paid` から 63+ providers を解放します(下の QVeris セクション参照)。ほかに:`api_server` のモジュール化が完了(1,103 → 371 行、[#424](https://github.com/HKUDS/Vibe-Trading/pull/424) が [#331](https://github.com/HKUDS/Vibe-Trading/issues/331) をクローズ、@shadowinlife さんに感謝)、バックテストの `validation.json` が artifacts ディレクトリの事前存在を要求しなくなり([#429](https://github.com/HKUDS/Vibe-Trading/pull/429)、@isaveall さんに感謝)、`--swarm-run` のエラーが明確になり([#428](https://github.com/HKUDS/Vibe-Trading/issues/428)、@isaveall さんに感謝)、セッションチャットを壊した governance stack を revert しました([#433](https://github.com/HKUDS/Vibe-Trading/issues/433)、的確な診断をくれた @yxhuang さんに感謝)。+- **2026-07-08** 💎 **ファンダメンタル因子レイヤー(Phase 1)+ オプションの QVeris 有料データ + メンテナンスデー**:PIT-safe な SEC 財務データが日次因子 panel に直接流れ込むようになりました —— `fund:*` panel 列、filed 日アンカリング(リステートメント・YTD フレーム防護付き)、新規クオリティ/バリュー因子 4 本(zoo は 460 alphas に)。ほかに:`api_server` のモジュール化が完了(1,103 → 371 行、[#424](https://github.com/HKUDS/Vibe-Trading/pull/424) が [#331](https://github.com/HKUDS/Vibe-Trading/issues/331) をクローズ、@shadowinlife さんに感謝)、バックテストの `validation.json` が artifacts ディレクトリの事前存在を要求しなくなり([#429](https://github.com/HKUDS/Vibe-Trading/pull/429)、@isaveall さんに感謝)、`--swarm-run` のエラーが明確になり([#428](https://github.com/HKUDS/Vibe-Trading/issues/428)、@isaveall さんに感謝)、セッションチャットを壊した governance stack を revert しました([#433](https://github.com/HKUDS/Vibe-Trading/issues/433)、的確な診断をくれた @yxhuang さんに感謝)。- **2026-07-07** ✅ **Contributor PR batch**:キューにあった contributor work を merge しました。IM channel timeout configuration([#413](https://github.com/HKUDS/Vibe-Trading/pull/413)、@SyntaxSawdust さんに感謝)、Alpha Library social previews と beginner tutorial([#396](https://github.com/HKUDS/Vibe-Trading/pull/396)、[#393](https://github.com/HKUDS/Vibe-Trading/pull/393)、@kadaliao さんに感謝)、value-investing skills / tools / committee presets([#407](https://github.com/HKUDS/Vibe-Trading/pull/407)、@sambazhu さんに感謝)、`trading_place_order` の zero-sized order-field handling([#417](https://github.com/HKUDS/Vibe-Trading/pull/417)、@irfanallana-oss さんに感謝)、session/API paths の timezone-aware UTC timestamps([#397](https://github.com/HKUDS/Vibe-Trading/pull/397)、@mustafakamal88 さんに感謝)です。@@ -503,7 +503,7 @@ vibe-trading connector install /tmp/my-broker## 📡 データソースとスマートフォールバック-1 回の `get_market_data` 呼び出しで **29 のマーケットデータソース**(うち **QVeris** はオプションの有料マーケットプレイス)にアクセスできます。`source: "auto"` を指定すれば、loader が銘柄に応じてソースを選び、**IP 規制リスク**の順に並んだ市場別チェーンをたどります。規制を受けない公開ソースを先に、スロットリングや key を要するソースを最後に試します。設定不要、単一障害点なし。+1 回の `get_market_data` 呼び出しで **28 のマーケットデータソース**にアクセスできます。`source: "auto"` を指定すれば、loader が銘柄に応じてソースを選び、**IP 規制リスク**の順に並んだ市場別チェーンをたどります。規制を受けない公開ソースを先に、スロットリングや key を要するソースを最後に試します。設定不要、単一障害点なし。| Source | Markets | Auth | Role ||--------|---------|------|------|@@ -512,13 +512,12 @@ vibe-trading connector install /tmp/my-broker| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `gildata` | A-share | token (Settings / `GILDATA_TOKEN`) | Hundsun Juyuan (恒生聚源) commercial feed — forward-adjusted dailies, joins the A-share chain tail |+| `gildata` | A / HK / CN index | `GILDATA_TOKEN` + `market_quotes` | 相場データ(Gildataを明示した場合のみ) · `source="gildata"` || `yahoo` | US / HK / カナダ / 英国 | none | direct chart/quotes/options;TSX `.TO` / TSXV `.V`;LSE `.L` は明示通貨で正規化 || `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV || `yfinance` | US / HK / カナダ / 英国 | none | wrapper;TSX `.TO` / TSXV `.V`;LSE `.L` は同じ GBP/GBp 契約に従う || `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |-| `qveris` | グローバル・マルチアセット | key · credits | **プレミアムマーケットプレイス** — 1つの key で 63+ providers(明示指定のみ、auto フォールバック対象外) || `nobitex` · `wallex` | 暗号資産(イラン・トマン建てペア) | なし | 公開 UDF エンドポイント。**明示指定のみ** — トマン建ての唯一の供給元であり、USD 建て系列が代役になりうる crypto チェーンには決して加わりません || `okx` · `ccxt` · `binance` | crypto | none | OKX + 100+ exchanges + Binance historical / USD-M perps || `futu` | HK / A | OpenD | optional local FutuOpenD |@@ -529,19 +528,15 @@ vibe-trading connector install /tmp/my-broker| `b3_cotahist` | Brazil (B3) | none | ローカル B3 公式現物・単元未満株の日足(未調整、BRL)。`python -m src.br_data sync` で取得する `.SA` のオフライン代替ソース || `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |-`GILDATA_TOKEN` を設定すると、複合照会の `gildata_fin_query`、複数報告期間の指標を取得できる銘柄スクリーニングの `gildata_stock_selection`、および `search_symbol` の聚源銘柄候補を利用できます。--相関分析ページの任意機能「Shannon保有診断」は `GILDATA_TOKEN` を使用し、A株ポートフォリオのスタイル・エクスポージャー、個別銘柄のヒートマップ、ボラティリティ寄与率を表示します。基準日と保有比率を指定でき、寄与率は損失確率を意味しません。-**フォールバックチェーン(IP 規制リスク順):**-- **A 株** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`+- **A 株** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`- **米国株** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`-- **香港株** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `gildata` · `local`+- **香港株** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`- **インド株(NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`- **Brazil (B3 `.SA`)** → `yahoo` · `yfinance` · `b3_cotahist` · `local`- **韓国(KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`-- **指数** → `yahoo` · `yfinance` · `gildata` · `local`+- **指数** → `yahoo` · `yfinance` · `local`- **英国(LSE)** → `yahoo` · `yfinance` · `local` *(GBP/GBp と明示されたクォートのみ)*- **暗号資産** → `okx` · `binance` · `ccxt` · `yfinance` · `local`- **為替/貴金属** → `mt5` · `akshare` · `yfinance` · `local`@@ -580,15 +575,9 @@ Agent との対話では明示的に依頼してください:**「LongbridgeOHLCV にとどまらず、**29 の読み取り専用データツール**がファンダメンタルズと資金フローまで踏み込みます。資金フロー、龍虎榜、北向資金、南向資金、信用取引、大口取引、株主数、ロックアップ、セクター、調査レポート、証券会社レポート検索、ニュース、SEC filings、中国市場の公告、財務諸表、PIT ファンダメンタルズ、オプションチェーン、暗号資産の板の厚み、銘柄プロファイル、市場スクリーニング、銘柄検索、マクロ、中国マクロ(EDB)、問財、機関投資家保有(13F)、ETF ルックスルー、中国の場外ファンド基準価額、予測市場、論文検索まで、すべて MCP 経由で公開されます。明示的な `local:` 銘柄が暗黙のうちにネットワークソースへフォールバックすることは決してありません。-<!-- QVERIS-START -->-### 💎 オプションのプレミアムデータ — QVeris--<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">--**データは無料ルーティングが標準、必要なときだけプレミアム。** 既定では 29 の内蔵ソースが自動フォールバックし、key も費用も不要です。QVeris を使うと、63+ providers と 10,000+ capabilities(per QVeris)で、オプション Greeks、高度なファンダメンタルズ、中国・香港・グローバルデータ、マクロ、暗号資産、ニュース、filings を補えます。失敗した call は課金されません。Settings → QVeris または `vibe-trading data mode paid` で有効化できます。+### データパートナー · [Gildata](https://www.gildata.com/products/datamap)-*QVeris disclosure: [Vibe-Trading の紹介リンク](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) から登録すると **+1,000 クレジット** が追加付与され、プロジェクトの支援にもなります。*-<!-- QVERIS-END -->+Gildataの各機能にはトークンが必要です。データソース設定で個別に有効にできます。アップグレード後も既定ではすべて無効です。---@@ -597,15 +586,15 @@ OHLCV にとどまらず、**29 の読み取り専用データツール**がフメイン README を読みやすく保つため、詳細な一覧は以下に折りたたんでいます。利用できる構成要素を確認したいときに開いてください。<details>-<summary><b>Finance Skill Library</b> <sub>9カテゴリにわたる90 skills</sub></summary>+<summary><b>Finance Skill Library</b> <sub>9カテゴリにわたる89 skills</sub></summary>-- 📊 90 の金融特化 skills を 9 カテゴリに整理+- 📊 89 の金融特化 skills を 9 カテゴリに整理- 🌐 伝統的市場から crypto & DeFi まで完全カバー- 🔬 データ取得からクオンツリサーチまでを横断する包括的能力| Category | Skills | Examples ||----------|--------|----------|-| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 23 | `factor-research`, `correlation-regime`, `macro-analysis`, `global-macro`, `valuation-model`, `investor-lenses`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1065,7 +1054,7 @@ vibe-trading provider doctor # 秘匿処理済みの provider/proxy/package 診| `/connector` | 取引 connector profile(状態 / 開始 / 停止) || `/halt` | キルスイッチ — すべてのライブ取引を即時停止 || `/resume` | キルスイッチを解除(ライブ取引を再開) |-| `/data` | データルーティングモード |+| `/data` | データパートナー設定 || `/quit` | 終了(q、exit、:q も可) |</details>@@ -1340,7 +1329,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-Vibe-Trading は MCP-compatible client 向けに 84 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 向けに 81 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` が必要です:@@ -1396,7 +1385,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**公開される MCP tools(84):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`.+**公開される MCP tools(81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`, `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@@ -1420,7 +1409,7 @@ ClawHub で見る: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills/vi<details><summary><b>OpenSpace — self-evolving skills</b></summary>-90 の finance skills はすべて [open-space.cloud](https://open-space.cloud) に公開され、OpenSpace の self-evolution engine を通じて自律的に進化します。+89 の finance skills はすべて [open-space.cloud](https://open-space.cloud) に公開され、OpenSpace の self-evolution engine を通じて自律的に進化します。OpenSpace と使うには、agent config に両方の MCP servers を追加してください。@@ -1442,7 +1431,7 @@ OpenSpace と使うには、agent config に両方の MCP servers を追加し}```-OpenSpace は 90 skills を自動検出し、auto-fix、auto-improve、community sharing を可能にします。OpenSpace-connected agent では `search_skills("finance backtest")` から Vibe-Trading skills を検索できます。+OpenSpace は 89 skills を自動検出し、auto-fix、auto-improve、community sharing を可能にします。OpenSpace-connected agent では `search_skills("finance backtest")` から Vibe-Trading skills を検索できます。</details>@@ -1762,13 +1751,13 @@ Vibe-Trading/├── agent/ # バックエンド (Python)│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 84 tools+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 81 tools│ ││ ├── src/│ │ ├── agent/ # ReAct エージェントコア│ │ │ ├── loop.py # 5 層コンテキスト圧縮 + read/write ツールバッチング│ │ │ ├── context.py # システムプロンプト + 永続メモリからの自動 recall-│ │ │ ├── skills.py # skill ローダー(90 個同梱 + CRUD でユーザー作成)+│ │ │ ├── skills.py # skill ローダー(89 個同梱 + CRUD でユーザー作成)│ │ │ ├── tools.py # ツール基底クラス + レジストリ│ │ │ ├── memory.py # run ごとの軽量ワークスペース状態│ │ │ ├── frontmatter.py # 共有 YAML frontmatter パーサー@@ -1795,7 +1784,7 @@ Vibe-Trading/│ │ ├── api/ # FastAPI ルートモジュール│ │ │ └── alpha_routes.py # /alpha/list、/alpha/{id}、/alpha/bench、SSE ストリーム│ │ │-│ │ ├── skills/ # 9 カテゴリ 90 個の finance skills(各 SKILL.md)+│ │ ├── skills/ # 9 カテゴリ 89 個の finance skills(各 SKILL.md)│ │ ├── swarm/ # Swarm DAG 実行エンジン│ │ │ └── presets/ # 30 個の swarm preset YAML 定義│ │ ├── session/ # マルチターンチャット + FTS5 セッション検索@@ -1803,7 +1792,7 @@ Vibe-Trading/│ ││ └── backtest/ # バックテストエンジン│ ├── engines/ # 11 エンジン + クロスマーケット composite engine + options_portfolio-│ ├── loaders/ # 29 ソース: tushare、okx、nobitex、wallex、binance、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、pykrx、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、longbridge、mt5、qveris、india_broker、tickerall、gildata, b3_cotahist+│ ├── loaders/ # 28 ソース: tushare、okx、nobitex、wallex、binance、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、pykrx、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、longbridge、mt5、india_broker、tickerall、gildata, b3_cotahist│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + 自動フォールバックチェーン│ └── optimizers/ # MVO、equal vol、max div、risk paritydiff --git a/README_ko.md b/README_ko.mdindex b3b82b80a..e08acf637 100644--- a/README_ko.md+++ b/README_ko.md@@ -242,7 +242,7 @@- **2026-07-09** 🧯 **Docker 시작 차단 해소 + provider/CLI contributor batch**: FastAPI route 순회 중 `path`가 없는 included-router-like 항목을 만나도 Docker/server startup이 더 이상 crash하지 않습니다([#450](https://github.com/HKUDS/Vibe-Trading/issues/450), @Penn-Live 님 감사합니다). 대기 중이던 quick-win contributor fixes도 함께 반영했습니다: OKX / Tushare / yfinance loader `fetch()` signature가 protocol과 맞춰졌고([#437](https://github.com/HKUDS/Vibe-Trading/pull/437), @shadowinlife 님 감사합니다), CLI resume prompt는 첫 사용자 메시지를 보존합니다([#448](https://github.com/HKUDS/Vibe-Trading/pull/448), [#447](https://github.com/HKUDS/Vibe-Trading/issues/447) 닫힘, @morluto 님 감사합니다). Codex OAuth default는 `openai-codex/gpt-5.4`로 업데이트됐고([#446](https://github.com/HKUDS/Vibe-Trading/pull/446), @morluto 님 감사합니다), Kimi for Coding은 별도 provider로 사용할 수 있으며([#435](https://github.com/HKUDS/Vibe-Trading/pull/435), @yxhuang 님 감사합니다), opencode provider mappings도 연결됐습니다([#444](https://github.com/HKUDS/Vibe-Trading/pull/444), @imsankz 님 감사합니다). Tushare reference code fence도 `pyhton`에서 `python`으로 고쳤습니다([#449](https://github.com/HKUDS/Vibe-Trading/pull/449), @flash1234pku 님 감사합니다). 검증에는 focused server/CLI/provider/loader tests, Docker build, `/health` smoke가 포함됩니다.-- **2026-07-08** 💎 **펀더멘털 팩터 레이어(Phase 1) + 선택형 QVeris 유료 데이터 + 메인터넌스 데이**: PIT-safe SEC 재무 데이터가 이제 일별 팩터 panel로 바로 흘러듭니다 —— `fund:*` panel 컬럼, filed 날짜 앵커링(재작성·YTD 프레임 보호), 신규 퀄리티/밸류 팩터 4종(zoo는 이제 460 alphas). 데이터 라우팅에 선택형 유료 트랙 추가: 18개 무료 소스가 여전히 기본값이며, QVeris는 Settings → QVeris 또는 `vibe-trading data mode paid`로 63+ providers를 엽니다(아래 QVeris 섹션 참조). 또한: `api_server` 모듈화 완료(1,103 → 371줄, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424)가 [#331](https://github.com/HKUDS/Vibe-Trading/issues/331)을 닫음, @shadowinlife 님 감사합니다), 백테스트 `validation.json`이 artifacts 디렉터리 사전 존재를 요구하지 않게 되었고([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), @isaveall 님 감사합니다), `--swarm-run` 오류 메시지가 명확해졌으며([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), @isaveall 님 감사합니다), 세션 채팅을 망가뜨린 governance stack을 revert했습니다([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), 정확한 진단을 해준 @yxhuang 님 감사합니다).+- **2026-07-08** 💎 **펀더멘털 팩터 레이어(Phase 1) + 선택형 QVeris 유료 데이터 + 메인터넌스 데이**: PIT-safe SEC 재무 데이터가 이제 일별 팩터 panel로 바로 흘러듭니다 —— `fund:*` panel 컬럼, filed 날짜 앵커링(재작성·YTD 프레임 보호), 신규 퀄리티/밸류 팩터 4종(zoo는 이제 460 alphas). 또한: `api_server` 모듈화 완료(1,103 → 371줄, [#424](https://github.com/HKUDS/Vibe-Trading/pull/424)가 [#331](https://github.com/HKUDS/Vibe-Trading/issues/331)을 닫음, @shadowinlife 님 감사합니다), 백테스트 `validation.json`이 artifacts 디렉터리 사전 존재를 요구하지 않게 되었고([#429](https://github.com/HKUDS/Vibe-Trading/pull/429), @isaveall 님 감사합니다), `--swarm-run` 오류 메시지가 명확해졌으며([#428](https://github.com/HKUDS/Vibe-Trading/issues/428), @isaveall 님 감사합니다), 세션 채팅을 망가뜨린 governance stack을 revert했습니다([#433](https://github.com/HKUDS/Vibe-Trading/issues/433), 정확한 진단을 해준 @yxhuang 님 감사합니다).- **2026-07-07** ✅ **Contributor PR batch**: 대기 중이던 contributor 작업을 merge했습니다. IM channel timeout configuration([#413](https://github.com/HKUDS/Vibe-Trading/pull/413), @SyntaxSawdust 님 감사합니다), Alpha Library social previews 및 beginner tutorial([#396](https://github.com/HKUDS/Vibe-Trading/pull/396), [#393](https://github.com/HKUDS/Vibe-Trading/pull/393), @kadaliao 님 감사합니다), value-investing skills / tools / committee presets([#407](https://github.com/HKUDS/Vibe-Trading/pull/407), @sambazhu 님 감사합니다), `trading_place_order`의 zero-sized order-field handling([#417](https://github.com/HKUDS/Vibe-Trading/pull/417), @irfanallana-oss 님 감사합니다), session/API paths의 timezone-aware UTC timestamps([#397](https://github.com/HKUDS/Vibe-Trading/pull/397), @mustafakamal88 님 감사합니다))입니다.@@ -503,7 +503,7 @@ vibe-trading connector install /tmp/my-broker## 📡 데이터 소스 & 스마트 폴백-`get_market_data` 한 번의 호출, **29개 시장 데이터 소스**(그중 **QVeris**는 선택형 유료 마켓플레이스). `source: "auto"`로 설정하면 로더가 심볼에 따라 소스를 고르고, 시장별 체인을 **IP 차단 위험** 순으로 따라갑니다: 절대 차단되지 않는 공개 소스를 먼저, 속도 제한 / 키 기반 소스를 마지막에 둡니다. 설정 불필요, 단일 장애 지점 없음.+`get_market_data` 한 번의 호출, **28개 시장 데이터 소스**. `source: "auto"`로 설정하면 로더가 심볼에 따라 소스를 고르고, 시장별 체인을 **IP 차단 위험** 순으로 따라갑니다: 절대 차단되지 않는 공개 소스를 먼저, 속도 제한 / 키 기반 소스를 마지막에 둡니다. 설정 불필요, 단일 장애 지점 없음.| Source | Markets | Auth | Role ||--------|---------|------|------|@@ -512,13 +512,12 @@ vibe-trading connector install /tmp/my-broker| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `gildata` | A-share | token (Settings / `GILDATA_TOKEN`) | Hundsun Juyuan (恒生聚源) commercial feed — forward-adjusted dailies, joins the A-share chain tail |+| `gildata` | A / HK / CN index | `GILDATA_TOKEN` + `market_quotes` | 시세 (Gildata를 직접 지정한 경우만) · `source="gildata"` || `yahoo` | US / HK / 캐나다 / 영국 | none | direct chart/quotes/options; TSX `.TO` / TSXV `.V`; LSE `.L`은 명시 통화로 정규화 || `sina` · `stooq` | US | none | K-line to 1984 · EOD CSV || `yfinance` | US / HK / 캐나다 / 영국 | none | wrapper; TSX `.TO` / TSXV `.V`; LSE `.L`은 동일한 GBP/GBp 계약 준수 || `longbridge` | US / HK | App Key + App Secret + Access Token | optional historical OHLCV source; install the optional SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |-| `qveris` | 글로벌 멀티에셋 | key · credits | **프리미엄 마켓플레이스** — key 하나로 63+ providers (명시 지정 전용, auto 폴백 제외) || `nobitex` · `wallex` | 크립토(이란 토만 표시 페어) | 없음 | 공개 UDF 엔드포인트, **명시 지정 전용** — 토만 표시 소스는 이 둘뿐이라, USD 표시 시세가 대신 들어올 수 있는 crypto 체인에는 절대 합류하지 않습니다 || `okx` · `ccxt` · `binance` | crypto | none | OKX + 100+ exchanges + Binance historical / USD-M perps || `futu` | HK / A | OpenD | optional local FutuOpenD |@@ -529,19 +528,15 @@ vibe-trading connector install /tmp/my-broker| `b3_cotahist` | Brazil (B3) | none | 로컬 B3 공식 현물·단주 일봉(미조정, BRL). `python -m src.br_data sync`로 가져오는 `.SA` 오프라인 대체 소스 || `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |-`GILDATA_TOKEN`을 설정하면 통합 질의용 `gildata_fin_query`, 여러 보고기간의 지표를 함께 조회하는 종목 선별용 `gildata_stock_selection`, `search_symbol`의 Gildata 종목 후보를 사용할 수 있습니다.--상관관계 페이지의 선택 기능인 Shannon 포트폴리오 진단은 `GILDATA_TOKEN`을 사용해 A주 포트폴리오의 스타일 노출, 종목별 노출 히트맵, 변동성 기여 비중을 보여줍니다. 기준일과 보유 비중을 지정할 수 있으며, 기여 비중은 손실 확률이 아닙니다.-**폴백 체인 (IP 차단 위험 순):**-- **A주** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`+- **A주** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`- **미국** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`-- **홍콩** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `gildata` · `local`+- **홍콩** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`- **인도 (NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`- **Brazil (B3 `.SA`)** → `yahoo` · `yfinance` · `b3_cotahist` · `local`- **한국 (KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`-- **지수** → `yahoo` · `yfinance` · `gildata` · `local`+- **지수** → `yahoo` · `yfinance` · `local`- **영국 (LSE)** → `yahoo` · `yfinance` · `local` *(명시된 GBP/GBp 호가만 허용)*- **크립토** → `okx` · `binance` · `ccxt` · `yfinance` · `local`- **외환/귀금속** → `mt5` · `akshare` · `yfinance` · `local`@@ -580,15 +575,9 @@ Agent 대화에서는 명시적으로 요청하세요: **"Longbridge로 QQQ.USOHLCV를 넘어 **29개 읽기 전용 데이터 도구**가 펀더멘털과 자금 흐름까지 닿습니다 — 자금 흐름, 용호방(dragon-tiger), 북향(northbound), 남향(southbound), 신용거래, 대종거래, 주주 수, 보호예수, 섹터, 리서치 리포트, 증권사 리포트 검색, 뉴스, SEC 공시, 중국 시장 공시, 재무제표, PIT 펀더멘털, 옵션 체인, 암호화폐 호가 깊이, 종목 프로필, 시장 스크리닝, 심볼 검색, 매크로, 중국 매크로(EDB), 원차이(iwencai), 기관 보유(13F), ETF 룩스루, 중국 장외 펀드 NAV, 예측 시장, 논문 검색 — 모두 MCP로 노출됩니다. 명시적인 `local:` 심볼은 절대 조용히 네트워크 소스로 폴백하지 않습니다.-<!-- QVERIS-START -->-### 💎 선택형 프리미엄 데이터 — QVeris--<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">--**데이터는 기본 무료 라우팅, 필요할 때만 프리미엄.** 기본값은 29개 내장 소스와 차단 위험 기반 폴백이며 key도 비용도 없습니다. QVeris를 켜면 63+ providers와 10,000+ capabilities(per QVeris)로 옵션 Greeks, 고급 펀더멘털, 중국/홍콩/글로벌 데이터, 매크로, 크립토, 뉴스, filings를 보강할 수 있고 실패한 호출은 과금되지 않습니다. Settings → QVeris 또는 `vibe-trading data mode paid`에서 활성화하세요.+### 데이터 파트너 · [Gildata](https://www.gildata.com/products/datamap)-*QVeris disclosure: [Vibe-Trading 추천 링크](https://qveris.ai/?ref=Vyjjo5G_1cAHJA)로 가입하면 **+1,000 크레딧**을 추가로 받고 프로젝트를 후원하게 됩니다.*-<!-- QVERIS-END -->+Gildata 기능은 각각 토큰이 필요하며 데이터 소스 설정에서 개별적으로 켤 수 있습니다. 업그레이드 후에도 기본값은 모두 꺼짐입니다.---@@ -597,15 +586,15 @@ OHLCV를 넘어 **29개 읽기 전용 데이터 도구**가 펀더멘털과 자메인 README를 읽기 쉽게 유지하기 위해 상세 목록은 아래에 접어 두었습니다. 사용 가능한 구성 요소를 확인하고 싶을 때 열어보세요.<details>-<summary><b>금융 스킬 라이브러리</b> <sub>9개 카테고리 90개 스킬</sub></summary>+<summary><b>금융 스킬 라이브러리</b> <sub>9개 카테고리 89개 스킬</sub></summary>-- 📊 9개 카테고리로 구성된 90개 전문 금융 스킬+- 📊 9개 카테고리로 구성된 89개 전문 금융 스킬- 🌐 전통 시장부터 크립토 & DeFi까지 완전한 커버리지- 🔬 데이터 sourcing부터 정량 리서치까지 포괄하는 기능| 카테고리 | 스킬 | 예시 ||----------|------|------|-| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 23 | `factor-research`, `correlation-regime`, `macro-analysis`, `global-macro`, `valuation-model`, `investor-lenses`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1063,7 +1052,7 @@ vibe-trading provider doctor # 마스킹된 provider/proxy/패키지 진단 출| `/connector` | 트레이딩 커넥터 프로필(상태 / 시작 / 중지) || `/halt` | 킬 스위치 — 모든 실거래 즉시 중단 || `/resume` | 킬 스위치 해제(실거래 재개) |-| `/data` | 데이터 라우팅 모드 |+| `/data` | 데이터 파트너 설정 || `/quit` | 종료(q, exit, :q 도 가능) |</details>@@ -1341,7 +1330,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-Vibe-Trading은 모든 MCP-compatible client를 위해 84개 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를 위해 81개 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`가 필요합니다:@@ -1397,7 +1386,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**노출되는 MCP tools(84):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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 tools(81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`, `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@@ -1421,7 +1410,7 @@ ClawHub에서 보기: [clawhub.ai/skills/vibe-trading](https://clawhub.ai/skills<details><summary><b>OpenSpace — 자가 진화 스킬</b></summary>-90개 finance skills는 모두 [open-space.cloud](https://open-space.cloud)에 게시되어 있으며 OpenSpace의 self-evolution engine을 통해 자율적으로 발전합니다.+89개 finance skills는 모두 [open-space.cloud](https://open-space.cloud)에 게시되어 있으며 OpenSpace의 self-evolution engine을 통해 자율적으로 발전합니다.OpenSpace와 함께 사용하려면 두 MCP server를 agent config에 추가하세요:@@ -1443,7 +1432,7 @@ OpenSpace와 함께 사용하려면 두 MCP server를 agent config에 추가하}```-OpenSpace는 90개 skills를 모두 자동 발견하여 auto-fix, auto-improve, community sharing을 활성화합니다. OpenSpace-connected agent에서 `search_skills("finance backtest")`로 Vibe-Trading skills를 검색하세요.+OpenSpace는 89개 skills를 모두 자동 발견하여 auto-fix, auto-improve, community sharing을 활성화합니다. OpenSpace-connected agent에서 `search_skills("finance backtest")`로 Vibe-Trading skills를 검색하세요.</details>@@ -1759,13 +1748,13 @@ 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 — 84 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent core│ │ │ ├── loop.py # 5-layer compression + read/write tool batching│ │ │ ├── context.py # system prompt + auto-recall from persistent memory-│ │ │ ├── skills.py # skill loader (90 bundled + user-created via CRUD)+│ │ │ ├── skills.py # skill loader (89 bundled + user-created via CRUD)│ │ │ ├── tools.py # tool base class + registry│ │ │ ├── memory.py # lightweight workspace state per run│ │ │ ├── frontmatter.py # shared YAML frontmatter parser@@ -1792,7 +1781,7 @@ Vibe-Trading/│ │ ├── api/ # FastAPI 라우트 모듈│ │ │ └── alpha_routes.py # /alpha/list, /alpha/{id}, /alpha/bench, SSE stream│ │ │-│ │ ├── skills/ # 90 finance skills in 9 categories (SKILL.md each)+│ │ ├── skills/ # 89 finance skills in 9 categories (SKILL.md each)│ │ ├── swarm/ # Swarm DAG execution engine│ │ │ └── presets/ # 30 swarm preset YAML definitions│ │ ├── session/ # Multi-turn chat + FTS5 session search@@ -1800,7 +1789,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 11 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 29 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, qveris, india_broker, tickerall, gildata, b3_cotahist+│ ├── loaders/ # 28 sources: tushare, okx, nobitex, wallex, binance, yfinance, akshare, baostock, tencent, mootdx, ccxt, futu, pykrx, local, eastmoney, sina, stooq, yahoo, finnhub, alphavantage, tiingo, fmp, longbridge, mt5, india_broker, tickerall, gildata, b3_cotahist│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_zh.md b/README_zh.mdindex bd6867070..0b46d5cc3 100644--- a/README_zh.md+++ b/README_zh.md@@ -249,7 +249,7 @@- **2026-07-09** 🧯 **Docker 启动解阻 + provider/CLI 贡献者批次**:当 FastAPI route 遍历遇到没有 `path` 的 included-router-like 条目时,Docker/server 启动不再直接崩溃([#450](https://github.com/HKUDS/Vibe-Trading/issues/450),感谢 @Penn-Live)。同时合入一批排队中的 quick-win 贡献者修复:OKX / Tushare / yfinance 的 loader `fetch()` 签名已对齐协议([#437](https://github.com/HKUDS/Vibe-Trading/pull/437),感谢 @shadowinlife),CLI resume prompt 会保留用户输入的第一句话([#448](https://github.com/HKUDS/Vibe-Trading/pull/448),关闭 [#447](https://github.com/HKUDS/Vibe-Trading/issues/447),感谢 @morluto),Codex OAuth 默认模型更新为 `openai-codex/gpt-5.4`([#446](https://github.com/HKUDS/Vibe-Trading/pull/446),感谢 @morluto),Kimi for Coding 成为独立 provider([#435](https://github.com/HKUDS/Vibe-Trading/pull/435),感谢 @yxhuang),opencode provider 映射已接入([#444](https://github.com/HKUDS/Vibe-Trading/pull/444),感谢 @imsankz),Tushare reference code fence 也从 `pyhton` 修成 `python`([#449](https://github.com/HKUDS/Vibe-Trading/pull/449),感谢 @flash1234pku)。验证包含 focused server/CLI/provider/loader tests、Docker build 和 `/health` smoke。-- **2026-07-08** 💎 **基本面因子层(Phase 1)+ 可选 QVeris 付费数据 + 维护日**:PIT-safe 的 SEC 财报数据现在直接进日频因子 panel —— `fund:*` 面板列、以 filed 日锚定(重述与 YTD 帧防护),新增 4 个质量/价值因子(zoo 现 460 个)。数据路由新增可选付费轨:18 个免费源仍是默认,QVeris 一把 key 解锁 63+ provider,入口 Settings → QVeris 或 `vibe-trading data mode paid`(见下方 QVeris 小节)。另外:`api_server` 模块化收官(1,103 → 371 行,[#424](https://github.com/HKUDS/Vibe-Trading/pull/424) 关闭 [#331](https://github.com/HKUDS/Vibe-Trading/issues/331),感谢 @shadowinlife)、回测 `validation.json` 不再要求 artifacts 目录预先存在([#429](https://github.com/HKUDS/Vibe-Trading/pull/429),感谢 @isaveall)、`--swarm-run` 报错更清晰([#428](https://github.com/HKUDS/Vibe-Trading/issues/428),感谢 @isaveall),以及我们 revert 了导致会话聊天崩溃的 governance stack([#433](https://github.com/HKUDS/Vibe-Trading/issues/433),感谢 @yxhuang 的精准诊断)。+- **2026-07-08** 💎 **基本面因子层(Phase 1)+ 可选 QVeris 付费数据 + 维护日**:PIT-safe 的 SEC 财报数据现在直接进日频因子 panel —— `fund:*` 面板列、以 filed 日锚定(重述与 YTD 帧防护),新增 4 个质量/价值因子(zoo 现 460 个)。另外:`api_server` 模块化收官(1,103 → 371 行,[#424](https://github.com/HKUDS/Vibe-Trading/pull/424) 关闭 [#331](https://github.com/HKUDS/Vibe-Trading/issues/331),感谢 @shadowinlife)、回测 `validation.json` 不再要求 artifacts 目录预先存在([#429](https://github.com/HKUDS/Vibe-Trading/pull/429),感谢 @isaveall)、`--swarm-run` 报错更清晰([#428](https://github.com/HKUDS/Vibe-Trading/issues/428),感谢 @isaveall),以及我们 revert 了导致会话聊天崩溃的 governance stack([#433](https://github.com/HKUDS/Vibe-Trading/issues/433),感谢 @yxhuang 的精准诊断)。- **2026-07-07** ✅ **贡献者 PR 批次**:合入了排队中的贡献者工作:IM channel timeout 配置([#413](https://github.com/HKUDS/Vibe-Trading/pull/413),感谢 @SyntaxSawdust)、Alpha Library 社交预览图与入门教程([#396](https://github.com/HKUDS/Vibe-Trading/pull/396)、[#393](https://github.com/HKUDS/Vibe-Trading/pull/393),感谢 @kadaliao)、value-investing skills / tools / committee presets([#407](https://github.com/HKUDS/Vibe-Trading/pull/407),感谢 @sambazhu)、`trading_place_order` 的零值 order sizing 字段处理([#417](https://github.com/HKUDS/Vibe-Trading/pull/417),感谢 @irfanallana-oss),以及 session/API 路径的 timezone-aware UTC timestamp([#397](https://github.com/HKUDS/Vibe-Trading/pull/397),感谢 @mustafakamal88)。@@ -534,7 +534,7 @@ vibe-trading research-artifact search --query "NVDA"## 📡 数据源与智能 Fallback-一次 `get_market_data` 调用,**29 个行情数据源**(其中 **QVeris** 是可选的付费市场)。设 `source: "auto"`——loader 按符号自动选源,再沿按 **被封 IP 风险** 排序的同市场链向下走(永不封的公开源在前,限速 / 需 key 的在后)。零配置,无单点故障。+一次 `get_market_data` 调用,**28 个行情数据源**。设 `source: "auto"`——loader 按符号自动选源,再沿按 **被封 IP 风险** 排序的同市场链向下走(永不封的公开源在前,限速 / 需 key 的在后)。零配置,无单点故障。| Source | Markets | Auth | Role ||--------|---------|------|------|@@ -543,13 +543,12 @@ vibe-trading research-artifact search --query "NVDA"| `eastmoney` | A / US / HK | none | OHLCV + deep fundamentals & flow tools (throttled) || `baostock` · `akshare` | A (+ US/HK/futures/macro/fx) | none | free fallbacks || `tushare` | A / HK / futures / fund / macro | token | richest A-share |-| `gildata` | A-share | token (Settings / `GILDATA_TOKEN`) | Hundsun Juyuan (恒生聚源) commercial feed — forward-adjusted dailies, joins the A-share chain tail |+| `gildata` | A / HK / CN index | `GILDATA_TOKEN` + `market_quotes` | 聚源行情(仅在指定聚源时使用) · `source="gildata"` || `yahoo` | 美股 / 港股 / 加拿大 / 英国 | none | direct chart/quotes/options;TSX `.TO` / TSXV `.V`;LSE `.L` 按明示币种归一化 || `sina` · `stooq` | 美股 | none | K-line to 1984 · EOD CSV || `yfinance` | 美股 / 港股 / 加拿大 / 英国 | none | wrapper;TSX `.TO` / TSXV `.V`;LSE `.L` 遵守同一 GBP/GBp 合同 || `longbridge` | 美股 / 港股 | App Key + App Secret + Access Token | 可选历史 OHLCV 数据源;需安装可选 SDK || `finnhub` · `alphavantage` · `tiingo` · `fmp` | US | key | optional providers |-| `qveris` | 全球多资产 | key · credits | **付费市场** — 一把 key 通 63+ 家(仅显式选用,绝不进 auto 链) || `nobitex` · `wallex` | 加密(伊朗托曼计价对) | 无 | 公开 UDF 端点;**仅显式选用** —— 它们是唯二以托曼计价的源,绝不进 crypto 链,以免用 USDT 计价的序列冒名顶替 || `okx` · `ccxt` · `binance` | crypto | none | OKX + 100+ exchanges + Binance 历史 / USD-M 永续 || `futu` | HK / A | OpenD | optional local FutuOpenD |@@ -560,19 +559,15 @@ vibe-trading research-artifact search --query "NVDA"| `b3_cotahist` | Brazil (B3) | none | 本地 B3 官方现货/零股日线(原始价格、BRL),由 `python -m src.br_data sync` 导入;`.SA` 的离线后备源 || `local` | any | none | your own CSV / Parquet / DuckDB via `local:` prefix |-配置 `GILDATA_TOKEN` 后,可使用聚源综合问数 `gildata_fin_query`、支持跨期指标的智能选股 `gildata_stock_selection`,并为证券检索 `search_symbol` 增加聚源候选来源。--相关性页面提供可选的香农持仓诊断:配置 `GILDATA_TOKEN` 后,可查看 A 股组合风格暴露、个股暴露热力图和组合波动贡献占比;支持可选截至日期及持仓权重,波动贡献占比不是亏损概率。-**Fallback 链(按被封 IP 风险排序):**-- **A股** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `gildata` · `local`+- **A股** → `tencent` · `eastmoney` · `baostock` · `akshare` · `tushare` · `local`- **美股** → `yahoo` · `stooq` · `sina` · `eastmoney` · `yfinance` · `tiingo` · `fmp` · `finnhub` · `alphavantage` · `longbridge` · `akshare` · `local`-- **港股** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `gildata` · `local`+- **港股** → `tencent` · `eastmoney` · `yahoo` · `futu` · `akshare` · `yfinance` · `tushare` · `longbridge` · `local`- **印度(NSE/BSE)** → `yahoo` · `yfinance` · `india_broker` · `local`- **Brazil (B3 `.SA`)** → `yahoo` · `yfinance` · `b3_cotahist` · `local`- **韩国(KOSPI/KOSDAQ)** → `pykrx` · `yahoo` · `yfinance` · `local`-- **指数** → `yahoo` · `yfinance` · `gildata` · `local`+- **指数** → `yahoo` · `yfinance` · `local`- **英国(LSE)** → `yahoo` · `yfinance` · `local` *(仅接受明示为 GBP/GBp 的报价)*- **加密** → `okx` · `binance` · `ccxt` · `yfinance` · `local`- **外汇 / 贵金属** → `mt5` · `akshare` · `yfinance` · `local`@@ -635,15 +630,9 @@ LONGBRIDGE_ACCESS_TOKEN=...除 OHLCV 外,**29 个只读数据工具**深入基本面与资金面——资金流、龙虎榜、北向、南向、两融、大宗交易、股东户数、解禁、板块、研报、券商研报检索、新闻、SEC 文件、中国市场公告、财务报表、PIT 基本面、期权链、加密货币盘口深度、个股档案、全市场筛选、代码搜索、宏观、中国宏观(EDB)、问财、机构持仓(13F)、ETF 穿透、场外基金净值、预测市场、论文检索——全部经 MCP 暴露。显式 `local:` 源永不静默 fallback 到网络源。-<!-- QVERIS-START -->-### 💎 可选付费数据 — QVeris--<img src="https://www.qveris.com/logo-color.png" alt="QVeris" height="36">--**数据可走免费,也可按需上付费。** 默认仍是 29 个内置免费源:自动 fallback、无需 key、无成本。通过 QVeris 可用一个 key 解锁 63+ provider、10,000+ capabilities(per QVeris),覆盖期权 Greeks、高级基本面、中国/港股/全球数据、宏观、加密、新闻与 filings;失败调用不扣费。入口在 Settings → QVeris 或 `vibe-trading data mode paid`。+### 数据合作方 · [Gildata](https://www.gildata.com/products/datamap)-*QVeris 披露:通过 [Vibe-Trading 推荐链接](https://qveris.ai/?ref=Vyjjo5G_1cAHJA) 注册可额外获得 **1,000 积分**,同时支持本项目。*-<!-- QVERIS-END -->+在设置的「数据源」中分别启用场外基金净值、中国宏观指标、公司和基金公告、券商研报、综合问数、智能选股、证券检索候选、香农持仓诊断和显式指定的行情。每项都需要聚源 Token。九项功能默认全部关闭。即使升级前已保存 Token,也要逐项手动开启。开启行情后,只有明确指定聚源才会使用;免费源查不到时不会自动转用聚源。---@@ -652,15 +641,15 @@ LONGBRIDGE_ACCESS_TOKEN=...为保持主 README 易读,详细清单折叠在下方。需要检查可用构件时可展开查看。<details>-<summary><b>Finance Skill Library</b> <sub>9 个类别中的 90 个 skills</sub></summary>+<summary><b>Finance Skill Library</b> <sub>9 个类别中的 89 个 skills</sub></summary>-- 📊 90 个专业金融 skills,分布在 9 个类别中+- 📊 89 个专业金融 skills,分布在 9 个类别中- 🌐 覆盖传统市场、加密与 DeFi- 🔬 从数据源到量化研究的完整能力链路| 类别 | Skills | 示例 ||------|--------|------|-| Data Source | 10 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar`, `qveris` |+| Data Source | 9 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt`, `eastmoney`, `sec-edgar` || Strategy | 19 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 23 | `factor-research`, `correlation-regime`, `macro-analysis`, `global-macro`, `valuation-model`, `investor-lenses`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -1110,7 +1099,7 @@ vibe-trading provider doctor # 打印脱敏后的 provider/proxy/依赖诊断| `/connector` | 交易连接器 profile(状态 / 启动 / 停止) || `/halt` | kill switch —— 立即停止全部实盘活动 || `/resume` | 解除 kill switch(重新允许实盘) |-| `/data` | 数据路由模式 |+| `/data` | 数据合作方设置 || `/quit` | 退出(也可用 q、exit、:q) |</details>@@ -1385,7 +1374,7 @@ POST `{}` 即按模板自身的建议节奏和默认变量排程。渲染后的## 🔌 MCP Plugin-Vibe-Trading 为任何 MCP-compatible client 暴露 84 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。+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。**环境变量:** server 由 client 自己 spawn,因此在 shell 里 `export` 永远传不进去 —— 请写在 client 的 `env` 块里。生成的回测代码被限制在 allowed run roots 内,所以要把结果写进你自己的工作目录,需要 `VIBE_TRADING_ALLOWED_RUN_ROOTS`:@@ -1441,7 +1430,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**暴露的 MCP tools(84):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`.+**暴露的 MCP tools(81):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `update_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_backtest_runs`, `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`, `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@@ -1465,7 +1454,7 @@ npx clawhub@latest install vibe-trading --force<details><summary><b>OpenSpace — 自进化 skills</b></summary>-全部 90 个 finance skills 都发布在 [open-space.cloud](https://open-space.cloud),并通过 OpenSpace 的自进化引擎自主演进。+全部 89 个 finance skills 都发布在 [open-space.cloud](https://open-space.cloud),并通过 OpenSpace 的自进化引擎自主演进。要配合 OpenSpace 使用,请将两个 MCP servers 都加入你的 agent config:@@ -1487,7 +1476,7 @@ npx clawhub@latest install vibe-trading --force}```-OpenSpace 会自动发现全部 90 个 skills,启用 auto-fix、auto-improve 和社区分享。在任意已连接 OpenSpace 的智能体中,可通过 `search_skills("finance backtest")` 搜索 Vibe-Trading skills。+OpenSpace 会自动发现全部 89 个 skills,启用 auto-fix、auto-improve 和社区分享。在任意已连接 OpenSpace 的智能体中,可通过 `search_skills("finance backtest")` 搜索 Vibe-Trading skills。</details>@@ -1797,13 +1786,13 @@ Vibe-Trading/├── agent/ # 后端(Python)│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP server —— 84 个工具,面向 OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server —— 81 个工具,面向 OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent 内核│ │ │ ├── loop.py # 5 层上下文压缩 + 读/写工具批处理│ │ │ ├── context.py # system prompt + 持久记忆自动召回-│ │ │ ├── skills.py # skill loader(90 个内置 + 通过 CRUD 创建的用户 skill)+│ │ │ ├── skills.py # skill loader(89 个内置 + 通过 CRUD 创建的用户 skill)│ │ │ ├── tools.py # tool 基类 + 注册表│ │ │ ├── memory.py # 每个 run 的轻量 workspace 状态│ │ │ ├── frontmatter.py # 共享的 YAML frontmatter 解析器@@ -1830,7 +1819,7 @@ Vibe-Trading/│ │ ├── api/ # FastAPI 路由模块│ │ │ └── alpha_routes.py # /alpha/list、/alpha/{id}、/alpha/bench、SSE 流│ │ │-│ │ ├── skills/ # 9 个类别共 90 个 finance skills(每个一份 SKILL.md)+│ │ ├── skills/ # 9 个类别共 89 个 finance skills(每个一份 SKILL.md)│ │ ├── swarm/ # Swarm DAG 执行引擎│ │ │ └── presets/ # 30 个 swarm preset YAML 定义│ │ ├── session/ # 多轮对话 + FTS5 session 搜索@@ -1838,7 +1827,7 @@ Vibe-Trading/│ ││ └── backtest/ # 回测引擎│ ├── engines/ # 11 个引擎 + 跨市场 composite 引擎 + options_portfolio-│ ├── loaders/ # 29 个数据源:tushare、okx、nobitex、wallex、binance、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、pykrx、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、longbridge、mt5、qveris、india_broker、tickerall、gildata, b3_cotahist+│ ├── loaders/ # 28 个数据源:tushare、okx、nobitex、wallex、binance、yfinance、akshare、baostock、tencent、mootdx、ccxt、futu、pykrx、local、eastmoney、sina、stooq、yahoo、finnhub、alphavantage、tiingo、fmp、longbridge、mt5、india_broker、tickerall、gildata, b3_cotahist│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + 自动 fallback 链路│ └── optimizers/ # MVO、equal vol、max div、risk paritydiff --git a/agent/.env.example b/agent/.env.exampleindex 819b369cd..3a14e5825 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -204,8 +204,8 @@ TUSHARE_TOKEN=your-tushare-token# chain (same sources, new order); invalid values are ignored with a warning.# Also editable in the Web UI: Settings -> Data Source Priority. Example —# put the paid Tushare feed first for A-shares (default order is-# tencent,eastmoney,baostock,akshare,tushare,gildata,local):-# MARKET_DATA_ORDER_A_SHARE=tushare,tencent,eastmoney,baostock,akshare,gildata,local+# tencent,eastmoney,baostock,akshare,tushare,local):+# MARKET_DATA_ORDER_A_SHARE=tushare,tencent,eastmoney,baostock,akshare,local# Caliber caveat: sources differ in adjustment basis (e.g. yahoo/yfinance serve# raw OHLC while tencent/eastmoney/tushare/baostock/gildata serve adjusted# prices), so a reordered chain can change backtest numbers.@@ -233,8 +233,10 @@ TUSHARE_TOKEN=your-tushare-token# ALPHAVANTAGE_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)# TIINGO_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)# FMP_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)-# GILDATA_TOKEN=xxx # optional Gildata (恒生聚源) provider — commercial token via [email protected]; joins the a_share/hk_equity chain tails for OHLCV (selectable get_market_data source) and powers the get_fund_nav OTC-fund NAV tool-# Also enables gildata_fin_query for mixed data queries and gildata_stock_selection for screening with cross-period indicators.+# GILDATA_TOKEN=xxx # optional Gildata (恒生聚源) provider — commercial token via [email protected]; OHLCV requires market_quotes and explicit source="gildata"+# All nine Gildata features default to off. An existing token alone enables none on upgrade.+# Enable features individually (comma-separated). Free sources never fall back to Gildata.+# VIBE_TRADING_GILDATA_FEATURES= # choose from fin_query,stock_selection,symbol_search,shannon,market_quotes,fund_nav,macro_series,announcements,broker_reports# GILDATA_BASE_URL=xxx # optional endpoint override (defaults to the vendor's raw-api MCP endpoint)# GILDATA_SRV_TOOL_URL=xxx # optional override of the vendor's 标准版 NL research endpoint (powers get_cn_macro_series / get_cn_announcements / search_broker_reports)# TICKERALL_API_KEY=xxx # optional hosted MetaTrader 5 forex/metals feed — EXPLICIT source="tickerall" only, never an automatic fallback (no local terminal; https://tickerall.com)diff --git a/agent/SKILL.md b/agent/SKILL.mdindex 7f2a0bafc..744ab630a 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -1,7 +1,7 @@---name: vibe-tradingversion: 0.1.18-description: Professional finance research toolkit — backtesting (11 engines + benchmark comparison panel), factor analysis, Alpha Zoo (478 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 90 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 29 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, tickerall, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, nobitex, wallex, plus optional-key finnhub/alphavantage/tiingo/fmp/gildata).+description: Professional finance research toolkit — backtesting (11 engines + benchmark comparison panel), factor analysis, Alpha Zoo (478 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 89 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 28 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, tickerall, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, longbridge, nobitex, wallex, plus optional-key finnhub/alphavantage/tiingo/fmp/gildata).dependencies:python: ">=3.11"pip:@@ -23,7 +23,7 @@ mcp:# Vibe-Trading-Professional finance research toolkit with AI-powered backtesting (11 engines), multi-agent teams, 90 specialized skills, the **Alpha Zoo** (478 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.+Professional finance research toolkit with AI-powered backtesting (11 engines), multi-agent teams, 89 specialized skills, the **Alpha Zoo** (478 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.## Setup@@ -53,7 +53,7 @@ Add to your agent's MCP config:### API Key Requirements-Core research MCP tools work with zero API keys for HK/US/Canada/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (478 pre-built alphas), and all 90 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.+Core research MCP tools work with zero API keys for HK/US/Canada/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (478 pre-built alphas), and all 89 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.| Feature | Key needed | When ||---------|-----------|------|@@ -74,7 +74,7 @@ Feed a CSV broker export (同花顺 / 东财 / 富途 / generic), and the agent5. `scan_shadow_signals` — list today's symbols that match your shadow's entry cadence (research only).### Backtesting-Create and run quantitative strategies across 11 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, VietnamEquity, BrazilEquity, Crypto, ChinaFutures, GlobalFutures, Forex, cross-market Composite) plus an options portfolio engine, with 29 market-data sources (auto-detect + ordered fallback; the hosted forex `tickerall` source is explicit-only):+Create and run quantitative strategies across 11 engines (ChinaA, GlobalEquity, IndiaEquity, KoreaEquity, VietnamEquity, BrazilEquity, Crypto, ChinaFutures, GlobalFutures, Forex, cross-market Composite) plus an options portfolio engine, with 28 market-data sources (auto-detect + ordered fallback; the hosted forex `tickerall` source is explicit-only):- **HK/US equities** via yfinance / stooq / yahoo (free, no API key); optionally via **Longbridge** historical OHLCV (`longbridge`, requires the optional SDK and `LONGBRIDGE_APP_KEY` / `LONGBRIDGE_APP_SECRET` / `LONGBRIDGE_ACCESS_TOKEN`). To force it for a run, set `"source": "longbridge"` in `config.json`.- **Canada equities (TSX/TSXV)** via yahoo / yfinance using Yahoo's canonical `<TICKER>.TO` (TSX, e.g. `TD.TO`) or `<TICKER>.V` (TSXV, e.g. `PNG.V`) suffixes — free, no API key. The GlobalEquity engine uses CAD identity, whole-share orders, configurable Canadian commission/slippage, and the TSX/TSXV price-increment grid.- **India equities (NSE/BSE)** via yahoo / yfinance using `<SYMBOL>.NS` (NSE, e.g. `RELIANCE.NS`) or `<SCRIP>.BO` (BSE, e.g. `500325.BO`) — free, no API key. The `IndiaEquityEngine` models T+1 delivery, no overnight shorts (set `allow_short` for intraday), configurable circuit bands, 1-share lots, and the STT/stamp-duty/exchange/GST cost stack. Optionally back-fill from your live broker via the `india_broker` source (Shoonya/Dhan; requires broker login).@@ -86,7 +86,7 @@ Create and run quantitative strategies across 11 engines (ChinaA, GlobalEquity,- **Forex / metals with no local terminal** via the hosted **TickerAll** MetaTrader 5 feed (`source="tickerall"`, `TICKERALL_API_KEY` + `TICKERALL_ACCOUNT_ID`, read-only) — the same broker feed as the `mt5` loader but over a hosted API on any OS. **Explicit-only** (never an automatic fallback).- **HK & A-share equities** via Futu (broker login required, optional)- **Local CSV/parquet bars** via the `local` loader (offline, no network)-- **Premium cross-market data** via QVeris (optional API key)+- **Data partner: [Gildata](https://www.gildata.com/products/datamap)** — financial queries, stock screening, security search candidates and Shannon portfolio diagnosis each require a token and explicit opt-in.- **Premium US data** via optional-key finnhub / alphavantage / tiingo / fmp (graceful fallback to free sources)Factors: the Alpha101 and QLib158 zoos are tagged for the `equity_in` and `equity_kr` universes, so they compute on NSE/BSE and KRX bars (the GTJA191 zoo stays China-only). Live/paper India trading uses the Shoonya / Dhan connectors (paper + read-only live; live order placement is structurally disabled because those brokers expose no paper/live switch). Live/paper Korea equity trading uses the **KIS** connector (한국투자증권; genuine 모의투자 paper sandbox on a separate host/port from 실전투자 live, plus read-only live — no mandate-gated live-trade profile yet). Live/paper Korea crypto trading uses the **Upbit** connector (KRW markets; paper + read-only live — no runtime paper/live discriminator, so live order placement is structurally disabled, same as Shoonya/Dhan). Read-only Korea/US equity access is also available via the **Toss Securities** connector (토스증권) — no verified sandbox, so order placement always refuses, same as Trading 212.@@ -120,7 +120,7 @@ One-line cross-sectional IC / IR / alive-reversed-dead categorisation across fivEach alpha ships with `__alpha_meta__` (formula LaTeX + theme + universe + warmup + columns required), guarded by an AST purity gate + 300-row lookahead sentinel test. Use the `vibe-trading alpha {list,show,bench,compare,export-manifest}` CLI, the `/alpha/*` REST routes (browser at `/alpha-zoo`), or compose multi-factor signals via `ZooSignalEngine.from_zoo(...)`.-### Finance Skills (90)+### Finance Skills (89)Comprehensive knowledge base covering:- Technical analysis (candlestick, Elliott wave, Ichimoku, SMC, harmonic, chanlun)- Quantitative methods (factor research, ML strategy, pair trading, multi-factor)@@ -133,11 +133,11 @@ Comprehensive knowledge base covering:Use `load_skill(name)` to access full methodology docs with code templates.-## Available MCP Tools (84)+## Available MCP Tools (81)| Tool | Description | API Key ||------|-------------|---------|-| `list_skills` | List all 90 finance skills | None |+| `list_skills` | List all 89 finance skills | None || `load_skill` | Load full skill documentation | None || `start_research_goal` | Create an auditable research goal | None || `get_research_goal` | Read the current research goal | None |@@ -152,7 +152,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `analyze_options` | Black-Scholes price + Greeks | None || `analyze_options_payoff` | Multi-leg expiry payoff + spot/IV scenarios | None || `pattern_recognition` | Detect chart patterns (H&S, double top, etc.) | None |-| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 29 sources) | None* |+| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 28 sources) | None* || `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* |@@ -171,14 +171,11 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `screen_market` | Market screener with fundamental/technical filters | None* || `search_symbol` | Symbol / ticker search across markets | None || `get_macro_series` | FRED macroeconomic series | FRED_API_KEY |-| `get_fund_nav` | Chinese off-exchange fund NAV history | GILDATA_TOKEN |-| `get_cn_macro_series` | China macro/industry EDB series (NL query) | GILDATA_TOKEN |-| `get_cn_announcements` | A-share/HK/fund announcement search (NL query) | GILDATA_TOKEN |-| `search_broker_reports` | Broker research search over the Juyuan library (NL query) | GILDATA_TOKEN |+| `get_fund_nav` | Chinese off-exchange fund NAV history | GILDATA_TOKEN + fund_nav opt-in |+| `get_cn_macro_series` | China macro/industry EDB series (NL query) | GILDATA_TOKEN + macro_series opt-in |+| `get_cn_announcements` | A-share/HK/fund announcement search (NL query) | GILDATA_TOKEN + announcements opt-in |+| `search_broker_reports` | Broker research search over the Juyuan library (NL query) | GILDATA_TOKEN + broker_reports opt-in || `iwencai_search` | A-share natural-language research search | IWENCAI_KEY |-| `qveris_search` | Search QVeris premium data/tool marketplace (free discovery) | QVERIS_API_KEY + paid mode |-| `qveris_inspect` | Inspect QVeris tool schemas before executing (free) | QVERIS_API_KEY + paid mode |-| `qveris_execute` | Execute a QVeris capability; budget-bounded, may be billable | QVERIS_API_KEY + paid mode || `web_search` | Search the web via DuckDuckGo | None || `read_url` | Fetch web page as Markdown | None || `read_document` | Extract text from PDF/DOCX/XLSX/PPTX/images | None |@@ -230,7 +227,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.pip install vibe-trading-ai```-That's it — no API keys needed for HK/US/Canada/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 90 skills immediately.+That's it — no API keys needed for HK/US/Canada/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 89 skills immediately.## Loading Tools from External MCP Serversdiff --git a/agent/api_server.py b/agent/api_server.pyindex e3618940d..c0f3b5c9d 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -255,8 +255,6 @@ from src.api.channels_routes import register_channels_routes # noqa: E402register_channels_routes(app)from src.api.channels_config_routes import register_channels_config_routes # noqa: E402register_channels_config_routes(app)-from src.api.qveris_routes import qveris_router # noqa: E402 # QVERIS-INTEGRATION-app.include_router(qveris_router) # QVERIS-INTEGRATIONfrom src.api.channels_routes import ( # noqa: F401, E402ChannelPairingCommandRequest,diff --git a/agent/backtest/loaders/gildata_loader.py b/agent/backtest/loaders/gildata_loader.pyindex 4f33442fc..080e2aeb7 100644--- a/agent/backtest/loaders/gildata_loader.py+++ b/agent/backtest/loaders/gildata_loader.py@@ -52,6 +52,7 @@ import pandas as pdfrom backtest.loaders._http import resolve_min_interval, throttled_post_jsonfrom backtest.loaders.base import cached_loader_fetch, validate_date_range+from src.config.gildata_features import feature_availablefrom backtest.loaders.gildata_codes import _normalize_ref, resolve_vendor_codefrom backtest.loaders.registry import _A_SHARE_INDEX_CODE, register@@ -62,7 +63,6 @@ _BASE_URL_ENV = "GILDATA_BASE_URL"_DEFAULT_BASE_URL = "https://api.gildata.com/mcp-servers/aidata-assistant-srv-rawapi"# Tokens that must not count as "configured" (mirrors tushare's placeholder set).-GILDATA_TOKEN_PLACEHOLDERS = {"", "your-gildata-token"}# Shared throttle/session bucket for every Gildata request in this process._HOST_KEY = "gildata"@@ -336,8 +336,8 @@ class DataLoader:passdef is_available(self) -> bool:- """Available when ``GILDATA_TOKEN`` is set to a non-placeholder value."""- return _token() not in GILDATA_TOKEN_PLACEHOLDERS+ """Available for explicit quote requests after the user enables them."""+ return feature_available("market_quotes")def fetch(self,@@ -378,7 +378,7 @@ class DataLoader:return {}if not self.is_available():- logger.warning("gildata fetch skipped: %s not set", _TOKEN_ENV)+ logger.warning("Gildata quotes require a token and the market_quotes opt-in")return {}def _a_share_fetch(symbol: str) -> Callable[[], Optional[pd.DataFrame]]:diff --git a/agent/backtest/loaders/qveris_loader.py b/agent/backtest/loaders/qveris_loader.pydeleted file mode 100644index bb02ac70c..000000000--- a/agent/backtest/loaders/qveris_loader.py+++ /dev/null@@ -1,799 +0,0 @@-"""QVeris loader: explicit, key-gated OHLCV fetches through QVeris tools.--This loader is intentionally self-contained for the QVeris integration parcel:-it reads the shared ``~/.vibe-trading/qveris.json`` config schema, applies the-``QVERIS_API_KEY`` / ``QVERIS_BASE_URL`` environment overrides, and embeds the-small HTTP client it needs for ``POST /search``, ``POST /tools/execute``, and-truncated-result downloads.--QVeris is a paid-capability router, so it must only run when the user explicitly-requests ``source="qveris"``. The registry keeps it out of every auto fallback-chain.-"""--from __future__ import annotations--import json-import logging-import math-import os-import re-import time-from dataclasses import dataclass-from pathlib import Path-from typing import Any, Dict, Iterable, List, Optional--import pandas as pd-import requests--from backtest.engines._market_hooks import _detect_market-from backtest.loaders.base import (- NoAvailableSourceError,- cached_loader_fetch,- validate_date_range,- validate_ohlc,-)-from backtest.loaders.registry import market_has_corporate_actions, register--logger = logging.getLogger(__name__)--_CONFIG_PATH = Path.home() / ".vibe-trading" / "qveris.json"-_DEFAULT_BASE_URL = "https://qveris.ai/api/v1"-_API_KEY_ENV = "QVERIS_API_KEY"-_BASE_URL_ENV = "QVERIS_BASE_URL"-_MIN_INTERVAL_ENV = "VIBE_TRADING_QVERIS_MIN_INTERVAL"-_DEFAULT_MIN_INTERVAL_S = 0.5-_HTTP_TIMEOUT_S = 30.0-_MAX_RETRIES = 3-_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]-_DATE_KEYS = (- "trade_date",- "date",- "datetime",- "timestamp",- "time",- "period",-)-#: A quote bounds the bill only when it is a flat price per call: "24.2-#: credits", "1 credits/call", or a bare number. ``cn_financial_pro.-#: history_quotation.v1`` quoted "1 credits/result" and billed 9.66 credits for-#: one stock-year, 244 rows x 30 fields at 0.00132 credits a value (#1494), so-#: a quote priced per any other unit, or in a shape not listed here, reserves-#: nothing that caps the charge and prices as unknown.-_FLAT_QUOTE = re.compile(r"(\d+(?:\.\d+)?)\s*(?:credits?)?\s*(?:(?:/|per)\s*(call|request))?")--#: The four fields that must all be present for a record to become a bar.-_PRICE_QUARTET = ("open", "high", "low", "close")--#: Aliases for an unadjusted bar.-_FIELD_ALIASES = {- "open": ("open", "o", "1. open"),- "high": ("high", "h", "2. high"),- "low": ("low", "l", "3. low"),- "close": ("close", "c", "4. close"),- "volume": ("volume", "vol", "v", "5. volume", "6. volume"),-}--#: Volume names that make no adjustment claim, shared by both tables. The-#: family split exists to stop unadjusted and adjusted *price levels* sharing a-#: bar; volume is not a price level, so an adjusted bar must still report a-#: volume the payload calls ``volume`` (``6. volume`` is Alpha Vantage's label-#: for the adjusted series' volume) instead of silently reporting NaN. The-#: unadjusted tuple is referenced rather than copied so the two cannot drift and-#: the unadjusted path stays byte-identical.-_PLAIN_VOLUME_ALIASES = _FIELD_ALIASES["volume"]--#: Aliases for an adjusted bar, resolved as a complete alternate set rather-#: than field by field. ``adj_close`` used to sit in the unadjusted ``close``-#: aliases while it had no ``adj_open``/``adj_high``/``adj_low`` siblings,-#: which cut both ways (#1494): a record carrying only adjusted fields failed-#: the OHLC check on every row, so a billed call produced no bars, while a-#: record carrying unadjusted open/high/low with only ``adj_close`` was-#: accepted as one bar mixing unadjusted and adjusted price levels.-_ADJUSTED_FIELD_ALIASES = {- "open": ("adj_open", "adjusted_open"),- "high": ("adj_high", "adjusted_high"),- "low": ("adj_low", "adjusted_low"),- "close": ("adj_close", "adjusted_close"),- "volume": ("adj_volume", "adjusted_volume") + _PLAIN_VOLUME_ALIASES,-}---@dataclass(frozen=True)-class QVerisConfig:- """Resolved QVeris loader configuration."""-- enabled: bool- base_url: str- api_key: str- mode: str- budget_credits_per_session: float---def _load_config() -> QVerisConfig:- """Read QVeris config with environment overrides.-- Returns:- Resolved config. Missing or malformed config files fall back to the- disabled default; env vars only override matching fields and do not- implicitly enable the integration.- """- raw: dict[str, Any] = {- "enabled": False,- "base_url": _DEFAULT_BASE_URL,- "api_key": "",- "mode": "free",- "budget_credits_per_session": 50.0,- }- try:- if _CONFIG_PATH.is_file():- loaded = json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))- if isinstance(loaded, dict):- raw.update(loaded)- except Exception as exc: # noqa: BLE001 - config read failures mean unavailable- logger.warning("qveris config ignored: %s", exc)-- from src.config.accessor import get_env_config-- api_key = (get_env_config().data.qveris_api_key or str(raw.get("api_key") or "")).strip()- base_url = (get_env_config().data.qveris_base_url or str(raw.get("base_url") or _DEFAULT_BASE_URL)).strip()- try:- budget = float(raw.get("budget_credits_per_session", 50.0))- except (TypeError, ValueError):- budget = 50.0- if not math.isfinite(budget):- budget = 50.0- return QVerisConfig(- enabled=bool(raw.get("enabled")),- base_url=(base_url or _DEFAULT_BASE_URL).rstrip("/"),- api_key=api_key,- mode=_normalize_mode(str(raw.get("mode") or "free")),- budget_credits_per_session=max(budget, 0.0),- )---def _normalize_mode(mode: str) -> str:- """Normalize QVeris paid-route mode."""- return {"preview": "free", "allow_paid": "paid", "free": "free", "paid": "paid"}.get(mode.strip(), "free")---def _min_interval() -> float:- """Resolve the minimum interval between QVeris requests."""- raw = os.getenv(_MIN_INTERVAL_ENV) # noqa: env-gate — loader-specific rate limit- if raw is None or not raw.strip():- return _DEFAULT_MIN_INTERVAL_S- try:- value = float(raw)- except ValueError:- logger.warning(- "invalid %s=%r, using default %s",- _MIN_INTERVAL_ENV,- raw,- _DEFAULT_MIN_INTERVAL_S,- )- return _DEFAULT_MIN_INTERVAL_S- if value < 0:- logger.warning(- "negative %s=%r, using default %s",- _MIN_INTERVAL_ENV,- raw,- _DEFAULT_MIN_INTERVAL_S,- )- return _DEFAULT_MIN_INTERVAL_S- return value---class QVerisClient:- """Minimal QVeris HTTP client for search, execute, and full-result GET."""-- def __init__(self, config: QVerisConfig) -> None:- """Initialize a session-bound client.-- Args:- config: Resolved QVeris config containing base URL and API key.- """- self._config = config- self._session = requests.Session()- self._last_request_at = 0.0-- def search(self, query: str, *, limit: int = 20) -> dict[str, Any]:- """Call ``POST /search``.-- Args:- query: Natural-language capability query.- limit: Maximum result count.-- Returns:- Decoded response body.- """- return self._post_json("/search", {"query": query, "limit": limit})-- def execute(- self,- tool_id: str,- parameters: dict[str, Any],- *,- search_id: str | None = None,- ) -> dict[str, Any]:- """Call ``POST /tools/execute`` and hydrate truncated results.-- Args:- tool_id: QVeris tool identifier returned by search.- parameters: Provider parameters.- search_id: Optional search correlation id.-- Returns:- Decoded execute response, with ``result`` replaced by downloaded- full JSON when QVeris returned ``full_content_file_url``.- """- body: dict[str, Any] = {- "parameters": parameters,- "max_response_size": 20480,- }- if search_id:- body["search_id"] = search_id- payload = self._post_json(f"/tools/execute?tool_id={tool_id}", body)- if isinstance(payload, dict) and isinstance(payload.get("result"), dict):- full_url = payload["result"].get("full_content_file_url")- if isinstance(full_url, str) and full_url:- payload = dict(payload)- payload["result"] = self._get_json(full_url)- return payload-- def _post_json(self, path: str, body: dict[str, Any]) -> dict[str, Any]:- url = f"{self._config.base_url}{path}"- response = self._request("post", url, json=body, auth=True)- decoded = response.json()- return decoded if isinstance(decoded, dict) else {}-- def _get_json(self, url: str) -> Any:- response = self._request("get", url, auth=False)- try:- return response.json()- except ValueError:- return json.loads(response.text)-- def _request(self, method: str, url: str, *, auth: bool, **kwargs: Any) -> requests.Response:- headers = {"User-Agent": "Vibe-Trading/1.0"}- if auth:- headers["Authorization"] = f"Bearer {self._config.api_key}"-- for attempt in range(_MAX_RETRIES + 1):- self._wait()- response = self._session.request(- method,- url,- headers=headers,- timeout=_HTTP_TIMEOUT_S,- **kwargs,- )- if response.status_code != 429:- response.raise_for_status()- return response- if attempt == _MAX_RETRIES:- response.raise_for_status()- time.sleep(_retry_after_seconds(response))- raise AssertionError("unreachable: retry loop must return or raise")-- def _wait(self) -> None:- interval = _min_interval()- if interval <= 0:- return- now = time.monotonic()- sleep_for = self._last_request_at + interval - now- if sleep_for > 0:- time.sleep(sleep_for)- self._last_request_at = time.monotonic()---def _retry_after_seconds(response: requests.Response) -> float:- """Parse a Retry-After header, falling back to the default interval."""- raw = response.headers.get("Retry-After", "")- try:- value = float(raw)- except (TypeError, ValueError):- value = _min_interval()- return max(value, 0.0)---@register-class DataLoader:- """QVeris OHLCV loader, available only when explicitly configured."""-- name = "qveris"- markets = {"crypto", "forex", "macro"}- requires_auth = True-- def __init__(self) -> None:- """Initialize without network access."""- self._config = _load_config()-- def is_available(self) -> bool:- """Return whether paid QVeris routing is enabled and keyed."""- return self._config.enabled and bool(self._config.api_key) and self._config.mode == "paid"-- def fetch(- self,- codes: List[str],- start_date: str,- end_date: str,- *,- interval: str = "1D",- fields: Optional[List[str]] = None,- ) -> Dict[str, pd.DataFrame]:- """Fetch daily OHLCV history through selected QVeris capabilities.-- Args:- codes: Symbols to fetch.- start_date: Inclusive ``YYYY-MM-DD`` start date.- end_date: Inclusive ``YYYY-MM-DD`` end date.- interval: Bar interval. QVeris selection is optimized for daily- bars; non-daily values are passed through when a tool accepts an- interval-like parameter.- fields: Ignored; QVeris loader returns the standard OHLCV columns.-- Returns:- Mapping of input symbol to normalized OHLCV DataFrames.-- Raises:- ValueError: If ``start_date`` > ``end_date``.- NoAvailableSourceError: If a symbol belongs to a market with- corporate actions, whose price adjustment this loader cannot- establish (#1494). Nothing is fetched or billed.- """- del fields- validate_date_range(start_date, end_date)- # A market with splits and dividends would be served by whichever- # capability ranks first in search, and the ranking ignores adjustment:- # for 600519.SH the top pick was FMP's non_split_adjusted EOD, and- # mkt_bars_adjusted routed to a tool whose adj_close equalled the raw- # closes (#1494). No capability is pinned to a measured adjustment, so- # such a bar has no caliber anyone can state, and "unknown" stays out of- # every run-level caliber check. Refused before anything is billed.- refused = {code: _detect_market(code) for code in codes}- refused = {code: market for code, market in refused.items() if market_has_corporate_actions(market)}- if refused:- raise NoAvailableSourceError(- "source='qveris' does not serve markets with splits and dividends: it "- "picks a capability by search rank, which ignores price adjustment, so "- "these bars would reach the run at an adjustment nobody can state "- "(#1494). Refused: "- + ", ".join(f"{code} ({market})" for code, market in refused.items())- + ". Use a source with a measured price caliber for these symbols."- )- if not self.is_available():- logger.warning("qveris fetch skipped: disabled or %s not set", _API_KEY_ENV)- return {}-- client = QVerisClient(self._config)- budget_state = {"spent": 0.0}- result: Dict[str, pd.DataFrame] = {}- for code in codes:- try:- df = cached_loader_fetch(- source=self.name,- symbol=code,- timeframe=interval,- start_date=start_date,- end_date=end_date,- fields=None,- fetch=lambda code=code: self._fetch_one(- client,- code,- start_date,- end_date,- interval,- budget_state,- ),- )- if df is not None and not df.empty:- result[code] = df- except Exception as exc: # noqa: BLE001 - one symbol must not abort the batch- logger.warning("qveris failed for %s: %s", code, exc)- return result-- def _fetch_one(- self,- client: QVerisClient,- code: str,- start_date: str,- end_date: str,- interval: str,- budget_state: dict[str, float],- ) -> Optional[pd.DataFrame]:- search_payload = client.search(_search_query(code, interval))- candidates = _select_capabilities(search_payload.get("results"), interval)- search_id = _str_or_none(search_payload.get("search_id"))- for capability in candidates:- tool_id = str(capability.get("tool_id") or "").strip()- if not tool_id:- continue- quoted_cost = _expected_cost(capability.get("expected_cost"))- if not math.isfinite(quoted_cost):- logger.warning(- "QVeris capability %s skipped for %s: quote %r is not a flat "- "price per call, so no reservation bounds its bill",- tool_id,- code,- capability.get("expected_cost"),- )- continue- if budget_state["spent"] + quoted_cost > self._config.budget_credits_per_session:- logger.warning(- "QVeris paid capability skipped for %s: credit budget exceeded",- code,- )- continue- parameters = _build_parameters(capability, code, start_date, end_date, interval)- # Reserve the quoted cost before the request. If transport fails- # after the provider accepted it, later symbols still fail closed.- budget_state["spent"] += quoted_cost- execute_payload = client.execute(tool_id, parameters, search_id=search_id)- try:- actual_cost = float(execute_payload.get("cost"))- except (TypeError, ValueError):- actual_cost = quoted_cost- if math.isfinite(actual_cost) and actual_cost > quoted_cost:- budget_state["spent"] += actual_cost - quoted_cost- if execute_payload.get("success") is False:- logger.warning("QVeris execute failed for %s via %s", code, tool_id)- continue- frame = _result_to_frame(execute_payload.get("result"), start_date, end_date)- if frame is not None:- return frame- logger.warning("QVeris result for %s via %s had no parseable bars", code, tool_id)- return None---_MAX_CANDIDATES = 3---def _search_query(symbol: str, interval: str) -> str:- """Build a capability-search query for one symbol."""- return f"daily OHLCV historical market data for {symbol.strip().upper()} interval {interval}"---def _select_capabilities(results: Any, interval: str) -> list[dict[str, Any]]:- """Rank OHLCV-like capabilities, excluding wrong-granularity series."""- if not isinstance(results, list):- return []- wanted, unwanted = _granularity_tokens(interval)- candidates = []- for item in results:- if not isinstance(item, dict) or not _looks_ohlcv(item):- continue- text = _capability_text(item)- if any(token in text for token in unwanted):- continue- priority = 0 if any(token in text for token in wanted) else 1- candidates.append((priority, item))- ranked = sorted(candidates, key=lambda pair: (pair[0],) + _capability_rank(pair[1]))- return [item for _, item in ranked[:_MAX_CANDIDATES]]---def _capability_text(item: dict[str, Any]) -> str:- return " ".join(- str(item.get(key) or "").lower() for key in ("tool_id", "name", "description")- )---def _granularity_tokens(interval: str) -> tuple[tuple[str, ...], tuple[str, ...]]:- """Return (wanted, unwanted) capability-text tokens for a bar interval.-- ``1m``/``5m``/``15m``/``30m`` are case-sensitive minute tokens; ``1M`` is- month. Lowercasing first would collapse ``1m`` into an empty match and let- daily capabilities outrank minute ones.- """- token = interval.strip()- norm = token.lower()- intraday = ("intraday", "minute", "1min", "5min", "15min", "30min", "60min", "hourly")- if norm in ("", "1d", "d", "day", "daily"):- return ("daily", "eod", "end-of-day", "end of day"), ("monthly", "weekly") + intraday- # Case-sensitive: ``1M`` (month) must not be treated as ``1m`` (minute).- if token == "1M" or "month" in norm:- return ("monthly",), ("weekly",) + intraday- if token in {"1m", "5m", "15m", "30m"} or "min" in norm or norm in ("1h", "4h") or "hour" in norm:- return intraday, ("monthly", "weekly")- if "w" in norm or "week" in norm:- return ("weekly",), ("monthly",) + intraday- if "mo" in norm:- return ("monthly",), ("weekly",) + intraday- return (), ()---def _looks_ohlcv(item: dict[str, Any]) -> bool:- text_parts = [- item.get("name"),- item.get("description"),- item.get("provider_name"),- json.dumps(item.get("params") or "", default=str),- json.dumps(item.get("examples") or "", default=str),- ]- text = " ".join(str(part or "").lower() for part in text_parts)- has_price = any(token in text for token in ("ohlcv", "open", "high", "low", "close", "candle", "historical price"))- has_symbol = any(token in text for token in ("symbol", "ticker", "instrument", "code"))- return has_price and has_symbol---def _capability_rank(item: dict[str, Any]) -> tuple[float, float, str]:- success_rate = _success_rate(item.get("stats"))- cost = _expected_cost(item.get("expected_cost"))- return (-success_rate, cost, str(item.get("tool_id") or item.get("name") or ""))---def _success_rate(stats: Any) -> float:- if not isinstance(stats, dict):- return 0.0- value = stats.get("success_rate", 0.0)- try:- parsed = float(value)- except (TypeError, ValueError):- return 0.0- return parsed / 100.0 if parsed > 1.0 else parsed---def quoted_call_cost(value: Any) -> float | None:- """Return the credits one call can cost under ``value``, or None.-- Args:- value: A capability's ``expected_cost`` quote.-- Returns:- The flat per-call price, or None when the quote does not bound the- bill: absent, negative, priced per result/row/value, or in any shape- ``_FLAT_QUOTE`` does not describe.- """- if isinstance(value, bool) or value is None:- return None- if isinstance(value, (int, float)):- return float(value) if math.isfinite(value) and value >= 0 else None- match = _FLAT_QUOTE.fullmatch(str(value).strip().lower())- return float(match.group(1)) if match else None---def _expected_cost(value: Any) -> float:- cost = quoted_call_cost(value)- return float("inf") if cost is None else cost---def _build_parameters(- capability: dict[str, Any],- code: str,- start_date: str,- end_date: str,- interval: str,-) -> dict[str, Any]:- """Build an execute parameter object from examples plus known date keys."""- parameters = _sample_parameters(capability)- for param in capability.get("params") or []:- if not isinstance(param, dict):- continue- name = str(param.get("name") or "").strip()- if not name:- continue- lower = name.lower()- if _is_symbol_param(lower):- parameters[name] = code.strip().upper()- elif _is_start_param(lower):- parameters[name] = start_date- elif _is_end_param(lower):- parameters[name] = end_date- elif _is_interval_param(lower):- parameters[name] = _interval_value(param, interval)- return parameters---def _sample_parameters(capability: dict[str, Any]) -> dict[str, Any]:- examples = capability.get("examples")- if not isinstance(examples, dict):- return {}- sample = examples.get("sample_parameters")- return dict(sample) if isinstance(sample, dict) else {}---def _is_symbol_param(name: str) -> bool:- return any(token in name for token in ("symbol", "ticker", "instrument", "code"))---def _is_start_param(name: str) -> bool:- return any(token in name for token in ("start", "from", "begin")) and "end" not in name---def _is_end_param(name: str) -> bool:- normalized = name.replace("-", "_")- return normalized in {- "end",- "end_date",- "enddate",- "to",- "to_date",- "until",- "until_date",- }---def _is_interval_param(name: str) -> bool:- return any(token in name for token in ("interval", "timeframe", "resolution", "frequency"))---def _interval_value(param: dict[str, Any], interval: str) -> str:- enum = param.get("enum")- if isinstance(enum, list):- lowered = {str(value).lower(): value for value in enum}- for candidate in (interval, interval.lower(), "1d", "d", "daily"):- if candidate.lower() in lowered:- return str(lowered[candidate.lower()])- return "daily" if interval.upper() == "1D" else interval---def _response_field_set(records: list[dict[str, Any]]) -> dict[str, tuple[str, ...]] | None:- """Return the one alias table every usable record in a response supports.-- Choosing per record let one payload carry an unadjusted row and an- adjusted-only row, and the series then mixed the two price levels (#1527).- Records with no complete quartet are skipped as before; if the rest do not- share a family the response yields no bars rather than a mixed series.- """- complete = [- [table for table in (_FIELD_ALIASES, _ADJUSTED_FIELD_ALIASES) if _resolve_field_set_in(keys, table)]- for keys in ({str(key).lower() for key in record} for record in records)- ]- complete = [tables for tables in complete if tables]- for table in (_FIELD_ALIASES, _ADJUSTED_FIELD_ALIASES):- if complete and all(table in tables for tables in complete):- return table- if complete:- logger.warning("QVeris response mixes unadjusted and adjusted records; no bars built from it")- return None---def _resolve_field_set_in(keys: set[str], table: dict[str, tuple[str, ...]]) -> bool:- return all(any(alias in keys for alias in table[field]) for field in _PRICE_QUARTET)---def _result_to_frame(result: Any, start_date: str, end_date: str) -> Optional[pd.DataFrame]:- records = list(_iter_ohlcv_records(result))- table = _response_field_set(records)- if table is None:- return None- rows = [_normalize_record(record, table) for record in records]- cleaned = [row for row in rows if row is not None]- if not cleaned:- return None-- df = pd.DataFrame(cleaned)- df["trade_date"] = pd.to_datetime(df["trade_date"], errors="coerce").astype(- "datetime64[ns]"- )- for field in _OHLCV_COLUMNS:- if field not in df.columns:- df[field] = None- df[field] = pd.to_numeric(df[field], errors="coerce").astype(float)- df = df.dropna(subset=["trade_date", "open", "high", "low", "close"])- if df.empty:- return None-- df = df.set_index("trade_date").sort_index()- df = df[_OHLCV_COLUMNS]- start = pd.Timestamp(start_date)- end = pd.Timestamp(end_date)- df = df.loc[(df.index >= start) & (df.index <= end)]- df = validate_ohlc(df)- return None if df.empty else df---def _iter_ohlcv_records(payload: Any) -> Iterable[dict[str, Any]]:- """Yield dict-like OHLCV records from common QVeris/provider shapes."""- if isinstance(payload, list):- for item in payload:- yield from _iter_ohlcv_records(item)- return- if not isinstance(payload, dict):- return-- if _record_has_ohlc(payload):- yield payload-- date_keyed = _date_keyed_records(payload)- if date_keyed is not None:- yield from date_keyed- return-- yielded = False- for key in (- "data",- "results",- "result",- "historical",- "prices",- "items",- "rows",- "candles",- "values",- "time_series",- "Time Series (Daily)",- ):- if key in payload:- for record in _iter_ohlcv_records(payload[key]):- yielded = True- yield record- if yielded:- return- # Provider-specific series containers ("Weekly Adjusted Time Series",- # "Time Series (5min)", ...) — any nested dict of date-keyed records.- for value in payload.values():- if isinstance(value, dict):- date_keyed = _date_keyed_records(value)- if date_keyed:- yield from date_keyed---def _date_keyed_records(payload: dict[str, Any]) -> list[dict[str, Any]] | None:- rows: list[dict[str, Any]] = []- for key, value in payload.items():- if not isinstance(value, dict) or not _looks_like_date(key):- return None- row = dict(value)- row.setdefault("trade_date", key)- rows.append(row)- return rows if rows else None---def _looks_like_date(value: Any) -> bool:- if not isinstance(value, str):- return False- try:- pd.Timestamp(value)- except Exception:- return False- return True---def _resolve_field_set(keys: Iterable[str]) -> dict[str, tuple[str, ...]] | None:- """Return the alias table that supplies one complete price quartet.-- The unadjusted table wins when a record carries both sets, which is the- preference the previous single-table lookup had. ``None`` means neither- table is complete, so a bar is never assembled from a mix of unadjusted and- adjusted fields.- """- for table in (_FIELD_ALIASES, _ADJUSTED_FIELD_ALIASES):- if _resolve_field_set_in(set(keys), table):- return table- return None---def _record_has_ohlc(record: dict[str, Any]) -> bool:- return _resolve_field_set({str(key).lower() for key in record}) is not None---def _normalize_record(record: dict[str, Any], table: dict[str, tuple[str, ...]]) -> dict[str, Any] | None:- """Build one bar from ``record`` using the response's alias ``table``.-- An unadjusted bar never takes ``adj_volume``: split-adjusted volume is not- on the scale of unadjusted prices, so a missing unadjusted volume stays NaN.- """- lowered = {str(key).lower(): value for key, value in record.items()}- date = _first_value(lowered, _DATE_KEYS)- if date is None:- return None- row = {"trade_date": date}- for field in _OHLCV_COLUMNS:- row[field] = _first_value(lowered, table[field])- if any(row[field] is None for field in _PRICE_QUARTET):- return None- return row---def _first_value(mapping: dict[str, Any], keys: Iterable[str]) -> Any:- for key in keys:- if key in mapping:- return mapping[key]- return None---def _str_or_none(value: Any) -> str | None:- if value is None:- return None- text = str(value).strip()- return text or Nonediff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex 18c634c59..bd195b02b 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -55,7 +55,6 @@ VALID_SOURCES: set[str] = {"tiingo","fmp","gildata",- "qveris", # QVERIS-INTEGRATION"india_broker","pykrx","longbridge",@@ -118,7 +117,6 @@ def _ensure_registered() -> None:"backtest.loaders.tiingo_loader","backtest.loaders.fmp_loader","backtest.loaders.gildata_loader",- "backtest.loaders.qveris_loader", # QVERIS-INTEGRATION"backtest.loaders.india_broker_loader","backtest.loaders.pykrx_loader","backtest.loaders.longbridge",@@ -155,8 +153,8 @@ def _ensure_registered() -> None:# as if it were Toman — a caliber error of about six orders of magnitude, not a# missing-data error. An unreachable Iranian endpoint must be visible._NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset(- {"local", "qveris", "tickerall", "fmp", "nobitex", "wallex", "b3_cotahist"}-) # QVERIS-INTEGRATION+ {"local", "gildata", "tickerall", "fmp", "nobitex", "wallex", "b3_cotahist"}+)def is_no_network_fallback_source(source: str) -> bool:@@ -189,9 +187,6 @@ FALLBACK_CHAINS: dict[str, list[str]] = {"baostock","akshare","tushare",- # Key-gated commercial vendor (恒生聚源): trails the free sources so- # paid quota is only spent when the public endpoints cannot serve.- "gildata","local",],"us_equity": [@@ -220,9 +215,6 @@ FALLBACK_CHAINS: dict[str, list[str]] = {"yfinance","tushare","longbridge",- # Key-gated commercial vendor, same tail-of-chain rationale as the- # a_share chain (paid quota only spent when free sources cannot serve).- "gildata","local",],"india_equity": ["yahoo", "yfinance", "india_broker", "local"],@@ -256,7 +248,7 @@ FALLBACK_CHAINS: dict[str, list[str]] = {"forex": ["mt5", "akshare", "yfinance", "local"],# Yahoo index symbols (^SPX, ^NDX, ^FTSE, ^VIX, ...): served verbatim by# the public chart endpoint, same as the =F/=X conventions.- "index": ["yahoo", "yfinance", "gildata", "local"],+ "index": ["yahoo", "yfinance", "local"],}@@ -567,6 +559,10 @@ def refresh_source_order_overrides() -> None:for market, default in _DEFAULT_CHAINS.items():raw = snapshot[source_order_env_var(market)]order = parse_source_order(raw) if raw else []+ # Older settings had to include Gildata to save any custom order.+ # Preserve the remaining order without treating that as consent.+ if market in {"a_share", "hk_equity", "index"} and order.count("gildata") == 1:+ order.remove("gildata")if order and is_valid_source_order(market, order):FALLBACK_CHAINS[market] = order[:]_ACTIVE_SOURCE_ORDER_OVERRIDES[market] = order[:]@@ -663,6 +659,7 @@ def get_loader_cls_with_fallback(source: str) -> Type[Any]:"list at least one source.","tickerall": "Set TICKERALL_API_KEY and TICKERALL_ACCOUNT_ID.","fmp": "Set FMP_API_KEY.",+ "gildata": "Enable Gildata market quotes in Settings and configure GILDATA_TOKEN.","nobitex": "Nobitex's public endpoint was unreachable. It quotes in ""Toman (IRT) and has no substitute — check network access ""to apiv2.nobitex.ir.",diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.pyindex b2b21859f..81acba6ef 100644--- a/agent/backtest/metrics.py+++ b/agent/backtest/metrics.py@@ -39,7 +39,7 @@ _TRADING_DAYS = {"fmp": 252, "stooq": 252, "longbridge": 252,# resampling sources (local files / paid data — interval depends on source# data granularity; model as US equity session as a conservative default)- "local": 252, "qveris": 252,+ "local": 252,# Indian equity"india_broker": 252,# Korean equity (KRX)@@ -60,7 +60,7 @@ _BARS_PER_DAY = {# --- US/international equity (6.5h session) ---"1m": {"yfinance": 390, "yahoo": 390, "finnhub": 390, "alphavantage": 390,"tiingo": 390, "fmp": 390, "stooq": 390, "longbridge": 390,- "local": 390, "qveris": 390,+ "local": 390,# A-share equity (4.0h session)"tushare": 240, "gildata": 240, "akshare": 240, "baostock": 240, "tencent": 240,"eastmoney": 240, "sina": 240, "mootdx": 240, "futu": 240,@@ -78,7 +78,7 @@ _BARS_PER_DAY = {},"5m": {"yfinance": 78, "yahoo": 78, "finnhub": 78, "alphavantage": 78,"tiingo": 78, "fmp": 78, "stooq": 78, "longbridge": 78,- "local": 78, "qveris": 78,+ "local": 78,"tushare": 48, "gildata": 48, "akshare": 48, "baostock": 48, "tencent": 48,"eastmoney": 48, "sina": 48, "mootdx": 48, "futu": 48,"okx": 288, "ccxt": 288, "binance": 288,@@ -91,7 +91,7 @@ _BARS_PER_DAY = {},"15m": {"yfinance": 26, "yahoo": 26, "finnhub": 26, "alphavantage": 26,"tiingo": 26, "fmp": 26, "stooq": 26, "longbridge": 26,- "local": 26, "qveris": 26,+ "local": 26,"tushare": 16, "gildata": 16, "akshare": 16, "baostock": 16, "tencent": 16,"eastmoney": 16, "sina": 16, "mootdx": 16, "futu": 16,"okx": 96, "ccxt": 96, "binance": 96,@@ -104,7 +104,7 @@ _BARS_PER_DAY = {},"30m": {"yfinance": 13, "yahoo": 13, "finnhub": 13, "alphavantage": 13,"tiingo": 13, "fmp": 13, "stooq": 13, "longbridge": 13,- "local": 13, "qveris": 13,+ "local": 13,"tushare": 8, "gildata": 8, "akshare": 8, "baostock": 8, "tencent": 8,"eastmoney": 8, "sina": 8, "mootdx": 8, "futu": 8,"okx": 48, "ccxt": 48, "binance": 48,@@ -117,7 +117,7 @@ _BARS_PER_DAY = {},"1H": {"yfinance": 7, "yahoo": 7, "finnhub": 7, "alphavantage": 7,"tiingo": 7, "fmp": 7, "stooq": 7, "longbridge": 7,- "local": 7, "qveris": 7,+ "local": 7,"tushare": 4, "gildata": 4, "akshare": 4, "baostock": 4, "tencent": 4,"eastmoney": 4, "sina": 4, "mootdx": 4, "futu": 4,"okx": 24, "ccxt": 24, "binance": 24,@@ -130,7 +130,7 @@ _BARS_PER_DAY = {},"4H": {"yfinance": 2, "yahoo": 2, "finnhub": 2, "alphavantage": 2,"tiingo": 2, "fmp": 2, "stooq": 2, "longbridge": 2,- "local": 2, "qveris": 2,+ "local": 2,"tushare": 1, "gildata": 1, "akshare": 1, "baostock": 1, "tencent": 1,"eastmoney": 1, "sina": 1, "mootdx": 1, "futu": 1,"okx": 6, "ccxt": 6, "binance": 6,@@ -143,7 +143,7 @@ _BARS_PER_DAY = {},"1D": {"yfinance": 1, "yahoo": 1, "finnhub": 1, "alphavantage": 1,"tiingo": 1, "fmp": 1, "stooq": 1, "longbridge": 1,- "local": 1, "qveris": 1,+ "local": 1,"tushare": 1, "gildata": 1, "akshare": 1, "baostock": 1, "tencent": 1,"eastmoney": 1, "sina": 1, "mootdx": 1, "futu": 1,"okx": 1, "ccxt": 1, "binance": 1,diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 3adf371d2..3aeb94942 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -1915,6 +1915,9 @@ def _show_settings() -> None:runtime_table = Table.grid(expand=True)runtime_table.add_column(width=13, style="dim")runtime_table.add_column(ratio=1)+ from src.config.gildata_features import selected_features++ runtime_table.add_row("Gildata opt-ins", ", ".join(selected_features()) or "(none)")runtime_table.add_row("Temperature", str(_cfg.llm.langchain_temperature))runtime_table.add_row("Timeout", str(_cfg.llm.timeout_seconds) + "s")runtime_table.add_row("Retries", str(_cfg.llm.max_retries))@@ -3351,113 +3354,16 @@ def _dispatch_channels(args: argparse.Namespace) -> int:return cmd_channels_login(args.channel_name, force=args.force)console.print("[red]channels requires a subcommand.[/red] Try: vibe-trading channels status")return EXIT_USAGE_ERROR-# QVERIS-INTEGRATION-def _print_qveris_config(config) -> None: # QVERIS-INTEGRATION- """Render local QVeris config.""" # QVERIS-INTEGRATION- from src.tools.qveris_tool import SIGNUP_URL, INVITE_CODE, has_qveris_credentials, is_qveris_configured, mask_api_key, normalize_qveris_mode # QVERIS-INTEGRATION- table = Table(title="Data Routing", box=box.SIMPLE) # QVERIS-INTEGRATION- table.add_column("Field") # QVERIS-INTEGRATION- table.add_column("Value") # QVERIS-INTEGRATION- table.add_row("mode", normalize_qveris_mode(config.mode)) # QVERIS-INTEGRATION- table.add_row("free_route", "built-in public data") # QVERIS-INTEGRATION- table.add_row("premium_provider", "QVeris") # QVERIS-INTEGRATION- table.add_row("paid_active", "yes" if is_qveris_configured(config) else "no") # QVERIS-INTEGRATION- table.add_row("premium_key", "yes" if has_qveris_credentials(config) else "no") # QVERIS-INTEGRATION- table.add_row("base_url", config.base_url) # QVERIS-INTEGRATION- table.add_row("api_key", mask_api_key(config.api_key) or "(not set)") # QVERIS-INTEGRATION- table.add_row("budget/session", str(config.budget_credits_per_session)) # QVERIS-INTEGRATION- table.add_row("signup", SIGNUP_URL) # QVERIS-INTEGRATION- table.add_row("invite_code", INVITE_CODE) # QVERIS-INTEGRATION- console.print(table) # QVERIS-INTEGRATION-# QVERIS-INTEGRATION-def cmd_qveris_status() -> int: # QVERIS-INTEGRATION- """Show QVeris local config and live status when configured.""" # QVERIS-INTEGRATION- from src.tools.qveris_tool import QVerisClient, is_qveris_configured, load_qveris_config # QVERIS-INTEGRATION- config = load_qveris_config() # QVERIS-INTEGRATION- _print_qveris_config(config) # QVERIS-INTEGRATION- if not is_qveris_configured(config): # QVERIS-INTEGRATION- return EXIT_SUCCESS # QVERIS-INTEGRATION- try: # QVERIS-INTEGRATION- payload = QVerisClient(config).search("status", limit=1) # QVERIS-INTEGRATION- console.print(f"[green]QVeris reachable.[/green] remaining_credits={payload.get('remaining_credits')}") # QVERIS-INTEGRATION- return EXIT_SUCCESS # QVERIS-INTEGRATION- except Exception as exc: # noqa: BLE001 # QVERIS-INTEGRATION- console.print(f"[red]QVeris status failed:[/red] {exc}") # QVERIS-INTEGRATION- return EXIT_RUN_FAILED # QVERIS-INTEGRATION-# QVERIS-INTEGRATION-def cmd_qveris_enable(*, key: str | None = None, url: str | None = None) -> int: # QVERIS-INTEGRATION- """Enable QVeris if an API key is present or supplied.""" # QVERIS-INTEGRATION- from src.tools.qveris_tool import SIGNUP_URL, INVITE_CODE, QVerisConfig, _read_config_file, save_qveris_config # QVERIS-INTEGRATION- existing = _read_config_file() # QVERIS-INTEGRATION- api_key = (key or existing.api_key or "").strip() # QVERIS-INTEGRATION- if not api_key: # QVERIS-INTEGRATION- console.print("[yellow]QVeris API key is required to enable the integration.[/yellow]") # QVERIS-INTEGRATION- console.print(f"[dim]Sign up: {SIGNUP_URL} invite_code={INVITE_CODE}[/dim]") # QVERIS-INTEGRATION- return EXIT_USAGE_ERROR # QVERIS-INTEGRATION- base_url = (url or existing.base_url).strip().rstrip("/") # QVERIS-INTEGRATION- if not base_url.startswith(("http://", "https://")): # QVERIS-INTEGRATION- console.print("[red]--url must start with http:// or https://[/red]") # QVERIS-INTEGRATION- return EXIT_USAGE_ERROR # QVERIS-INTEGRATION- saved = save_qveris_config(QVerisConfig(True, base_url, api_key, "paid", existing.budget_credits_per_session)) # QVERIS-INTEGRATION- console.print("[green]QVeris paid route enabled.[/green]") # QVERIS-INTEGRATION- _print_qveris_config(saved) # QVERIS-INTEGRATION- return EXIT_SUCCESS # QVERIS-INTEGRATION-# QVERIS-INTEGRATION-def cmd_qveris_mode(- *,- mode: str,- budget: float | None = None,- key: str | None = None,- url: str | None = None,-) -> int: # QVERIS-INTEGRATION- """Switch QVeris between free and paid modes.""" # QVERIS-INTEGRATION- from src.tools.qveris_tool import QVerisConfig, _read_config_file, normalize_qveris_mode, save_qveris_config # QVERIS-INTEGRATION- existing = _read_config_file() # QVERIS-INTEGRATION- next_mode = normalize_qveris_mode(mode) # QVERIS-INTEGRATION- next_budget = existing.budget_credits_per_session if budget is None else max(float(budget), 0.0) # QVERIS-INTEGRATION- base_url = (url or existing.base_url).strip().rstrip("/") # QVERIS-INTEGRATION- if not base_url.startswith(("http://", "https://")): # QVERIS-INTEGRATION- console.print("[red]--url must start with http:// or https://[/red]") # QVERIS-INTEGRATION- return EXIT_USAGE_ERROR # QVERIS-INTEGRATION- api_key = (key or existing.api_key or "").strip() # QVERIS-INTEGRATION- saved = save_qveris_config(QVerisConfig(next_mode == "paid", base_url, api_key, next_mode, next_budget)) # QVERIS-INTEGRATION- console.print(f"[green]QVeris mode set to {next_mode}.[/green]") # QVERIS-INTEGRATION- _print_qveris_config(saved) # QVERIS-INTEGRATION- return EXIT_SUCCESS # QVERIS-INTEGRATION-# QVERIS-INTEGRATION-def cmd_qveris_disable() -> int: # QVERIS-INTEGRATION- """Disable QVeris without deleting the stored key.""" # QVERIS-INTEGRATION- from src.tools.qveris_tool import QVerisConfig, _read_config_file, save_qveris_config # QVERIS-INTEGRATION- existing = _read_config_file() # QVERIS-INTEGRATION- save_qveris_config(QVerisConfig(False, existing.base_url, existing.api_key, "free", existing.budget_credits_per_session)) # QVERIS-INTEGRATION- console.print("[green]QVeris disabled.[/green]") # QVERIS-INTEGRATION- return EXIT_SUCCESS # QVERIS-INTEGRATION-# QVERIS-INTEGRATION-def cmd_qveris_usage() -> int: # QVERIS-INTEGRATION- """Show recent QVeris usage events.""" # QVERIS-INTEGRATION- from src.tools.qveris_tool import QVerisClient, is_qveris_configured, load_qveris_config # QVERIS-INTEGRATION- config = load_qveris_config() # QVERIS-INTEGRATION- if not is_qveris_configured(config): # QVERIS-INTEGRATION- console.print("[yellow]QVeris is not configured.[/yellow]") # QVERIS-INTEGRATION- return EXIT_USAGE_ERROR # QVERIS-INTEGRATION- try: # QVERIS-INTEGRATION- payload = QVerisClient(config).usage_history(limit=10, page_size=10) # QVERIS-INTEGRATION- except Exception as exc: # noqa: BLE001 # QVERIS-INTEGRATION- console.print(f"[red]QVeris usage failed:[/red] {exc}") # QVERIS-INTEGRATION- return EXIT_RUN_FAILED # QVERIS-INTEGRATION- print(json.dumps(payload, indent=2, ensure_ascii=False)) # QVERIS-INTEGRATION- return EXIT_SUCCESS # QVERIS-INTEGRATION-def _dispatch_data(args: argparse.Namespace) -> int: # QVERIS-INTEGRATION- """Dispatch user-facing data-routing commands.""" # QVERIS-INTEGRATION- if args.data_command == "status": # QVERIS-INTEGRATION- return cmd_qveris_status() # QVERIS-INTEGRATION- if args.data_command == "mode": # QVERIS-INTEGRATION- return cmd_qveris_mode(mode=args.mode, budget=args.budget, key=args.key, url=args.url) # QVERIS-INTEGRATION- if args.data_command == "usage": # QVERIS-INTEGRATION- return cmd_qveris_usage() # QVERIS-INTEGRATION- console.print("[red]data requires a subcommand.[/red] Try: vibe-trading data status") # QVERIS-INTEGRATION- return EXIT_USAGE_ERROR # QVERIS-INTEGRATION-# QVERIS-INTEGRATION+def _dispatch_data(args: argparse.Namespace) -> int:+ """Show the optional data partner and the features selected for this process."""+ from src.config.gildata_features import selected_features++ _ensure_cli_env()+ console.print("Gildata: " + (", ".join(selected_features()) or "no optional research features selected"))+ console.print("Gildata: https://www.gildata.com/products/datamap")+ return EXIT_SUCCESS++def _live_server_config(broker: str):"""Resolve the protected MCP server config for ``broker``.@@ -5613,17 +5519,9 @@ def _build_parser() -> argparse.ArgumentParser:from cli.custom_providers import configure_parser as configure_custom_providersconfigure_custom_providers(provider_subparsers.add_parser("custom", help="Manage tested custom model endpoints"))- # QVERIS-INTEGRATION- data_parser = subparsers.add_parser("data", help="Manage data routing mode") # QVERIS-INTEGRATION- data_subparsers = data_parser.add_subparsers(dest="data_command") # QVERIS-INTEGRATION- data_subparsers.add_parser("status", help="Show active data routing mode") # QVERIS-INTEGRATION- data_mode = data_subparsers.add_parser("mode", help="Switch between free public data and paid data routing") # QVERIS-INTEGRATION- data_mode.add_argument("mode", choices=["free", "paid"], help="free uses built-in public data; paid enables premium data execution") # QVERIS-INTEGRATION- data_mode.add_argument("--budget", type=float, help="Paid-mode credit budget per session") # QVERIS-INTEGRATION- data_mode.add_argument("--key", help="Premium data API key") # QVERIS-INTEGRATION- data_mode.add_argument("--url", help="Premium data API base URL") # QVERIS-INTEGRATION- data_subparsers.add_parser("usage", help="Show recent paid data usage") # QVERIS-INTEGRATION- # QVERIS-INTEGRATION+ data_parser = subparsers.add_parser("data", help="Show research data partner settings")+ data_subparsers = data_parser.add_subparsers(dest="data_command", required=True)+ data_subparsers.add_parser("status", help="Show selected Gildata features")channels_parser = subparsers.add_parser("channels", help="Manage IM channel adapters")channels_subparsers = channels_parser.add_subparsers(dest="channels_command")channels_status = channels_subparsers.add_parser("status", help="Show IM channel status")@@ -6784,8 +6682,8 @@ def main(argv: list[str] | None = None) -> int:return EXIT_USAGE_ERRORif args.command == "channels":return _coerce_exit_code(_dispatch_channels(args))- if args.command == "data": # QVERIS-INTEGRATION- return _coerce_exit_code(_dispatch_data(args)) # QVERIS-INTEGRATION+ if args.command == "data":+ return _coerce_exit_code(_dispatch_data(args))if args.command == "run":return _handle_prompt_command(args.run_prompt,diff --git a/agent/cli/main.py b/agent/cli/main.pyindex fd71d8020..2f7aceb88 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -84,19 +84,23 @@ def _register_live_slash_commands() -> None:_register_live_slash_commands()-# QVERIS-INTEGRATION-def _register_data_slash_commands() -> None: # QVERIS-INTEGRATION- """Surface data routing mode in the shared slash registry.""" # QVERIS-INTEGRATION- from cli.commands import slash_router # QVERIS-INTEGRATION- if any(cmd.name == "data" for cmd in slash_router.SLASH_COMMANDS): # QVERIS-INTEGRATION- return # QVERIS-INTEGRATION- commands = list(slash_router.SLASH_COMMANDS) # QVERIS-INTEGRATION- quit_idx = next((i for i, c in enumerate(commands) if c.name == "quit"), len(commands)) # QVERIS-INTEGRATION- commands.insert(quit_idx, slash_router.Command("data", "Data routing mode", "cli.main")) # QVERIS-INTEGRATION- slash_router.SLASH_COMMANDS = tuple(commands) # QVERIS-INTEGRATION-# QVERIS-INTEGRATION-_register_data_slash_commands() # QVERIS-INTEGRATION-# QVERIS-INTEGRATION+++def _register_data_slash_commands() -> None:+ """Surface data partner settings in the shared slash registry."""+ from cli.commands import slash_router++ if any(cmd.name == "data" for cmd in slash_router.SLASH_COMMANDS):+ return+ commands = list(slash_router.SLASH_COMMANDS)+ quit_idx = next((i for i, c in enumerate(commands) if c.name == "quit"), len(commands))+ commands.insert(quit_idx, slash_router.Command("data", "Show data partner settings", "cli.main"))+ slash_router.SLASH_COMMANDS = tuple(commands)+++_register_data_slash_commands()++_AGENT_DIR = Path(__file__).resolve().parents[1]_ENV_PATH = Path.home() / ".vibe-trading" / ".env"_PROJECT_ENV_PATH = _AGENT_DIR / ".env"@@ -962,20 +966,24 @@ def _run_connector_command_from_repl(console: Any, args: list[str]) -> None:_dispatch_connector(parsed)except Exception as exc: # noqa: BLE001 — never let a connector command kill the loopconsole.print(f"[bold red]/connector failed:[/bold red] {exc}")-# QVERIS-INTEGRATION-def _run_data_command_from_repl(console: Any, args: list[str]) -> None: # QVERIS-INTEGRATION- """Run a ``/data ...`` subcommand from the REPL via the CLI dispatcher.""" # QVERIS-INTEGRATION- from cli._legacy import _build_parser, _dispatch_data # QVERIS-INTEGRATION- argv = ["data", *(args or ["status"])] # QVERIS-INTEGRATION- try: # QVERIS-INTEGRATION- parsed = _build_parser().parse_args(argv) # QVERIS-INTEGRATION- except SystemExit: # QVERIS-INTEGRATION- console.print("[dim]Usage: /data [status|mode free|mode paid|usage][/dim]") # QVERIS-INTEGRATION- return # QVERIS-INTEGRATION- try: # QVERIS-INTEGRATION- _dispatch_data(parsed) # QVERIS-INTEGRATION- except Exception as exc: # noqa: BLE001 # QVERIS-INTEGRATION- console.print(f"[bold red]/data failed:[/bold red] {exc}") # QVERIS-INTEGRATION+++def _run_data_command_from_repl(console: Any, args: list[str]) -> None:+ """Run a ``/data ...`` subcommand from the REPL via the CLI dispatcher."""+ from cli._legacy import _build_parser, _dispatch_data++ argv = ["data", *(args or ["status"])]+ try:+ parsed = _build_parser().parse_args(argv)+ except SystemExit:+ console.print("[dim]Usage: /data [status][/dim]")+ return+ try:+ _dispatch_data(parsed)+ except Exception as exc: # noqa: BLE001+ console.print(f"[bold red]/data failed:[/bold red] {exc}")++def _is_numeric_pick(text: str) -> Optional[int]:"""Return the chosen ordinal if ``text`` is a bare numeric pick, else None.@@ -1427,9 +1435,9 @@ def _interactive_loop(max_iter: int, resume_session_id: Optional[str] = None) ->if slash_name == "connector":_run_connector_command_from_repl(console, slash_tokens[1:])continue- if slash_name == "data": # QVERIS-INTEGRATION- _run_data_command_from_repl(console, slash_tokens[1:]) # QVERIS-INTEGRATION- continue # QVERIS-INTEGRATION+ if slash_name == "data":+ _run_data_command_from_repl(console, slash_tokens[1:])+ continuerc = _dispatch_slash(text, ctx)if rc == 2:breakdiff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex b79830393..64a16f0b1 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -6,7 +6,7 @@ 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 84 tools: skills, research goals, strategy discovery,+Surfaces 81 tools: skills, research goals, strategy discovery,backtest/factor/options/patternanalysis, 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 /@@ -14,8 +14,7 @@ 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),+screen_market / search_symbol / get_macro_series / iwencai_search),institutional-research and alternative data (get_institutional_holdings /etf_holdings / prediction_market / research_papers), read-only finance math andmarket analytics (quantlib_call / cashflow_performance / orderbook_depth /@@ -24,9 +23,7 @@ trading-connector reads, swarm orchestration, trade-journal and shadow-accountanalysis. Every exposed tool is read-only or research-only exceptrefresh_strategy_evidence, which writes ONLY the disposable facade-ownedstrategy-evidence cache from local run artifacts; no order-placing or-order-cancelling tool is ever surfaced via MCP. The QVeris tools additionally-require QVeris paid routing (QVERIS_API_KEY + paid mode), and qveris_execute-is billable research-data execution only — it never places orders.+order-cancelling tool is ever surfaced via MCP.Usage:python mcp_server.py # stdio transport (default)@@ -2052,6 +2049,7 @@ def get_market_data(- "akshare": A-shares, US, HK, futures, forex (free, e.g. 000001.SZ, AAPL.US)- "ccxt": crypto from 100+ exchanges (free, e.g. BTC/USDT)- "mt5": forex/metals from a local MetaTrader 5 terminal (Windows; e.g. EUR/USD, XAUUSD.FX)+ - "gildata": only on user request, with token and market quotes enabled; no fallback- "auto": auto-detect based on symbol format (with fallback)Args:@@ -2107,12 +2105,11 @@ def get_market_data(# Each wrapper delegates to the auto-discovered local registry, exactly like# factor_analysis / pattern_recognition above. The registry returns a clean# JSON error envelope when a key-gated tool (get_macro_series needs-# FRED_API_KEY, iwencai_search needs VIBE_TRADING_IWENCAI_KEY, the qveris_*-# tools need QVeris paid routing: QVERIS_API_KEY + paid mode) is absent — see+# FRED_API_KEY, iwencai_search needs VIBE_TRADING_IWENCAI_KEY) is absent — see# ``_execute_key_gated`` below, which honours that contract even though the# tool is excluded from the registry by ``check_available()``. Every tool below# is read-only or research-only data — no order/trading tool is ever surfaced-# via MCP (qveris_execute spends QVeris credits on data calls, never orders).+# via MCP.# ---------------------------------------------------------------------------@@ -2123,7 +2120,6 @@ def get_market_data(# contract above (a clean, env-var-named error). For these tools we therefore# fall through to the tool's own ``execute()`` — whose missing-key envelope# names the exact env var (``FRED_API_KEY`` / ``VIBE_TRADING_IWENCAI_KEY``),-# or the missing QVeris paid-routing setup (``QVERIS_API_KEY`` + paid mode).def _key_gated_tool_classes() -> dict[str, Any]:"""Return the {tool_name: tool_class} map for key-gated MCP tools.@@ -2141,11 +2137,6 @@ def _key_gated_tool_classes() -> dict[str, Any]:SearchBrokerReportsTool,)from src.tools.iwencai_tool import IWenCaiSearchTool- from src.tools.qveris_tool import (- QVerisExecuteTool,- QVerisInspectTool,- QVerisSearchTool,- )return {"get_macro_series": FredMacroTool,@@ -2154,25 +2145,16 @@ def _key_gated_tool_classes() -> dict[str, Any]:"get_cn_announcements": GetCnAnnouncementsTool,"search_broker_reports": SearchBrokerReportsTool,"iwencai_search": IWenCaiSearchTool,- "qveris_search": QVerisSearchTool,- "qveris_inspect": QVerisInspectTool,- "qveris_execute": QVerisExecuteTool,}def _execute_key_gated(name: str, params: dict[str, Any]) -> str:"""Run a key-gated MCP tool, preserving its env-var-named error.- Prefers the auto-discovered registry (present when the API key is set and,- for the qveris_* tools, paid mode is on). When the gating is absent the- tool is excluded from the registry, so we invoke its concrete ``execute()``- directly to surface the documented missing-key error that names the exact- env var — or the missing QVeris paid routing — never a generic "Tool not- found".+ If a credential is missing, use the tool's own actionable error response.Args:- name: MCP tool name (``get_macro_series``, ``iwencai_search``,- ``qveris_search``, ``qveris_inspect`` or ``qveris_execute``).+ name: Registered key-gated tool name.params: Keyword arguments forwarded to the tool.Returns:@@ -2589,8 +2571,7 @@ def get_fund_nav(NAV (复权净值) and the daily growth rate per fund, over an optional datewindow. Codes are bare 6-digit ('110022') or '.OF'-suffixed('110022.OF'). Exchange-listed ETF/LOF are OHLCV instruments — use- get_market_data for those. Requires the commercial GILDATA_TOKEN; without- it the tool returns a not-available error.+ get_market_data for those. Requires GILDATA_TOKEN and the fund_nav opt-in.Args:funds: Fund codes, e.g. ["110022", "000198.OF"].@@ -2615,7 +2596,7 @@ def get_cn_macro_series(query: str, limit: int = 50) -> str:GDP, CPI, PPI, PMI, money supply, rates, trade, 31 industry series andregional data — dated observations with unit and frequency, asked for innatural language. Complements get_macro_series (FRED, US/global).- Requires GILDATA_TOKEN; without it the tool returns a not-available error.+ Requires GILDATA_TOKEN and the macro_series opt-in.Args:query: Natural-language indicator request, e.g. "2024年中国月度CPI同比".@@ -2632,7 +2613,7 @@ def get_cn_announcements(query: str, limit: int = 50) -> str:Annual reports, earnings, dividends, buybacks, restructuring, inquiryletters — with title, publish date and a highlighted excerpt. For US- filings use get_sec_filings. Requires GILDATA_TOKEN.+ filings use get_sec_filings. Requires GILDATA_TOKEN and the announcements opt-in.Args:query: Natural-language announcement request, e.g. "贵州茅台2024年年度分红公告".@@ -2649,7 +2630,7 @@ def search_broker_reports(query: str, limit: int = 50) -> str:Title, broker, industry, rating and a highlighted excerpt of the argument— for company deep-dives, industry views and macro commentary. Coexists- with get_research_reports (eastmoney-backed). Requires GILDATA_TOKEN.+ with get_research_reports (eastmoney-backed). Requires GILDATA_TOKEN and the broker_reports opt-in.Args:query: Natural-language research request, e.g. "最近三个月白酒行业的券商研报观点".@@ -2678,100 +2659,6 @@ def iwencai_search(query: str, limit: int = 20) -> str:return _execute_key_gated("iwencai_search", {"query": query, "limit": limit})-def qveris_search(query: str, limit: int = 20, session_id: str | None = None) -> str:- """Search the QVeris premium data/tool marketplace for capabilities.-- Discovery is free. Returns candidate tools with ``tool_id``, ``provider``,- ``parameters``, ``expected_cost`` and ``stats.success_rate``; choose by- expected cost and success rate before any paid execute. Requires QVeris- paid routing (``QVERIS_API_KEY`` and paid mode via ``vibe-trading data- mode paid`` or Settings -> QVeris) — without it the tool returns a- not-available error.-- Args:- query: Capability search query, e.g. "US listed options chain implied- volatility Greeks AAPL".- limit: Maximum candidates to return.- session_id: Optional QVeris session id linking follow-up calls.- """- params: dict[str, Any] = {"query": query, "limit": limit}- if session_id:- params["session_id"] = session_id- return _execute_key_gated("qveris_search", params)---def qveris_inspect(- tool_ids: list[str],- search_id: str | None = None,- session_id: str | None = None,-) -> str:- """Inspect full parameter schemas of QVeris tools before executing them.-- Fetches the complete descriptors for one or more ``tool_ids`` returned by- ``qveris_search``. Inspection is free: verify required parameters, enum- values, date formats and output shape before a paid call. Requires QVeris- paid routing (``QVERIS_API_KEY`` and paid mode via ``vibe-trading data- mode paid`` or Settings -> QVeris) — without it the tool returns a- not-available error.-- Args:- tool_ids: QVeris tool ids taken from ``qveris_search`` results.- search_id: Optional search id from the ``qveris_search`` response.- session_id: Optional QVeris session id linking follow-up calls.- """- params: dict[str, Any] = {"tool_ids": tool_ids}- if search_id:- params["search_id"] = search_id- if session_id:- params["session_id"] = session_id- return _execute_key_gated("qveris_inspect", params)---def qveris_execute(- tool_id: str,- parameters: dict[str, Any],- search_id: str | None = None,- session_id: str | None = None,- model: str | None = None,- max_response_size: int = 20480,-) -> str:- """Execute one QVeris capability after discovery and inspection.-- Runs the ``tool_id`` selected via ``qveris_search`` / ``qveris_inspect``.- MAY BE BILLABLE — provider calls are charged by QVeris when billable- (failed or empty calls are not charged), and the tool enforces the local- per-session credit budget before sending the request; the result preserves- ``cost`` and ``remaining_credits``. Research/data execution only — it- never places orders. Requires QVeris paid routing (``QVERIS_API_KEY`` and- paid mode via ``vibe-trading data mode paid`` or Settings -> QVeris) —- without it the tool returns a not-available error.-- Args:- tool_id: QVeris tool id to execute.- parameters: Provider call parameters matching the inspected schema.- search_id: Optional search id from the ``qveris_search`` response.- session_id: Optional QVeris session id used for budget accounting.- model: Optional provider model override.- max_response_size: Provider response truncation budget (default- 20480; -1 disables truncation).- """- params: dict[str, Any] = {- "tool_id": tool_id,- "parameters": parameters,- "max_response_size": max_response_size,- }- if search_id:- params["search_id"] = search_id- if session_id:- params["session_id"] = session_id- if model:- params["model"] = model- return _execute_key_gated("qveris_execute", params)--# ---------------------------------------------------------------------------# Institutional-research & alternative-data tools (schema mirrored from source)#diff --git a/agent/src/api/qveris_routes.py b/agent/src/api/qveris_routes.pydeleted file mode 100644index 3a94d25cd..000000000--- a/agent/src/api/qveris_routes.py+++ /dev/null@@ -1,231 +0,0 @@-"""QVeris settings and status routes."""--from __future__ import annotations--import sys as _sys-from typing import Any, Literal--from fastapi import APIRouter, Depends, HTTPException, Request, Security-from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer-from pydantic import BaseModel, Field--from src.tools.qveris_tool import (- INVITE_CODE,- SIGNUP_URL,- DEFAULT_BASE_URL,- QVerisClient,- QVerisConfig,- _read_config_file,- has_qveris_credentials,- is_qveris_configured,- load_qveris_config,- mask_api_key,- normalize_qveris_mode,- save_qveris_config,-)--qveris_router = APIRouter()-_security = HTTPBearer(auto_error=False)---class QVerisConfigResponse(BaseModel):- """Redacted QVeris config response."""-- enabled: bool- base_url: str- api_key_masked: str- mode: Literal["free", "paid"]- budget_credits_per_session: float- configured: bool- signup_url: str- invite_code: str---class QVerisConfigUpdate(BaseModel):- """QVeris config update payload."""-- enabled: bool | None = None- base_url: str | None = None- api_key: str | None = None- mode: Literal["free", "paid"] | None = None- budget_credits_per_session: float | None = Field(default=None, ge=0)---class QVerisStatusResponse(BaseModel):- """QVeris runtime status response."""-- enabled: bool- ok: bool- error: str | None- remaining_credits: float | None- recent: list[dict[str, Any]]- signup_url: str- invite_code: str---def _host():- host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")- if host is None:- raise RuntimeError("api_server module is not loaded")- return host---async def _require_auth(- request: Request,- cred: HTTPAuthorizationCredentials | None = Security(_security),-) -> None:- """Delegate read auth to api_server.require_auth."""- await _host().require_auth(request, cred)---async def _require_settings_write_auth(- request: Request,- cred: HTTPAuthorizationCredentials | None = Security(_security),-) -> None:- """Delegate write auth to api_server.require_settings_write_auth."""- await _host().require_settings_write_auth(request, cred)---def _config_response(config: QVerisConfig) -> QVerisConfigResponse:- return QVerisConfigResponse(- enabled=config.enabled,- base_url=config.base_url,- api_key_masked=mask_api_key(config.api_key),- mode=normalize_qveris_mode(config.mode), # type: ignore[arg-type]- budget_credits_per_session=float(config.budget_credits_per_session),- configured=has_qveris_credentials(config),- signup_url=SIGNUP_URL,- invite_code=INVITE_CODE,- )---def _validate_base_url(base_url: str) -> str:- value = (base_url or DEFAULT_BASE_URL).strip().rstrip("/")- if not value.startswith(("http://", "https://")):- raise HTTPException(status_code=422, detail="base_url must be http(s)")- return value---def _events_from_usage(payload: dict[str, Any]) -> list[dict[str, Any]]:- data = payload.get("data")- if isinstance(data, dict):- events = data.get("events") or data.get("items") or data.get("data")- elif isinstance(data, list):- events = data- else:- events = payload.get("events") or payload.get("items") or []- if not isinstance(events, list):- return []- recent: list[dict[str, Any]] = []- for event in events[:10]:- if not isinstance(event, dict):- continue- recent.append(- {- "ts": str(- event.get("ts")- or event.get("created_at")- or event.get("timestamp")- or ""- ),- "tool_id": str(event.get("tool_id") or ""),- "cost": float(event.get("cost") or event.get("amount_credits") or 0.0),- "charge_outcome": str(event.get("charge_outcome") or ""),- }- )- return recent---@qveris_router.get(- "/qveris/config",- response_model=QVerisConfigResponse,- dependencies=[Depends(_require_auth)],-)-async def get_qveris_config() -> QVerisConfigResponse:- """Return redacted QVeris config."""- return _config_response(load_qveris_config())---@qveris_router.put(- "/qveris/config",- response_model=QVerisConfigResponse,- dependencies=[Depends(_require_settings_write_auth)],-)-async def put_qveris_config(update: QVerisConfigUpdate) -> QVerisConfigResponse:- """Persist QVeris config changes."""- existing = _read_config_file()- cfg = QVerisConfig(- enabled=existing.enabled,- base_url=existing.base_url,- api_key=existing.api_key,- mode=existing.mode,- budget_credits_per_session=existing.budget_credits_per_session,- )- if update.base_url is not None:- cfg.base_url = _validate_base_url(update.base_url)- if update.api_key:- cfg.api_key = update.api_key.strip()- if update.mode is not None:- cfg.mode = normalize_qveris_mode(update.mode)- cfg.enabled = cfg.mode == "paid"- elif update.enabled is not None:- cfg.enabled = bool(update.enabled)- cfg.mode = "paid" if cfg.enabled else "free"- if update.budget_credits_per_session is not None:- cfg.budget_credits_per_session = float(update.budget_credits_per_session)- save_qveris_config(cfg)- return _config_response(load_qveris_config())---@qveris_router.get(- "/qveris/status",- response_model=QVerisStatusResponse,- dependencies=[Depends(_require_auth)],-)-async def get_qveris_status() -> QVerisStatusResponse:- """Return QVeris availability, credits, and recent usage."""- cfg = load_qveris_config()- if not has_qveris_credentials(cfg):- return QVerisStatusResponse(- enabled=cfg.enabled,- ok=False,- error="QVeris is not configured",- remaining_credits=None,- recent=[],- signup_url=SIGNUP_URL,- invite_code=INVITE_CODE,- )- if not is_qveris_configured(cfg):- return QVerisStatusResponse(- enabled=cfg.enabled,- ok=False,- error="QVeris paid mode is off; free public data routing is active.",- remaining_credits=None,- recent=[],- signup_url=SIGNUP_URL,- invite_code=INVITE_CODE,- )- try:- client = QVerisClient(cfg)- search = client.search("status", limit=1)- usage = client.usage_history(limit=10, page_size=10)- remaining = search.get("remaining_credits")- return QVerisStatusResponse(- enabled=cfg.enabled,- ok=True,- error=None,- remaining_credits=float(remaining) if remaining is not None else None,- recent=_events_from_usage(usage),- signup_url=SIGNUP_URL,- invite_code=INVITE_CODE,- )- except Exception as exc: # noqa: BLE001 - status endpoint reports health.- return QVerisStatusResponse(- enabled=cfg.enabled,- ok=False,- error=str(exc),- remaining_credits=None,- recent=[],- signup_url=SIGNUP_URL,- invite_code=INVITE_CODE,- )diff --git a/agent/src/api/settings_routes.py b/agent/src/api/settings_routes.pyindex b9bc41b11..7740b0a53 100644--- a/agent/src/api/settings_routes.py+++ b/agent/src/api/settings_routes.py@@ -22,6 +22,8 @@ from pydantic import BaseModel, Fieldfrom src.config.accessor import get_env_value, reset_env_config+from src.config.gildata_features import FEATURES_ENV, GildataFeature, selected_features+logger = logging.getLogger(__name__)# Agent root (agent/) — resolved from this file's location (agent/src/api/).@@ -144,6 +146,7 @@ class DataSourceSettingsResponse(BaseModel):tushare_token_configured: booltushare_token_hint: Optional[str] = None+ gildata_features: list[GildataFeature] = Field(default_factory=list)gildata_token_configured: boolgildata_token_hint: Optional[str] = Nonebaostock_supported: bool@@ -159,6 +162,7 @@ class UpdateDataSourceSettingsRequest(BaseModel):tushare_token: Optional[str] = Noneclear_tushare_token: bool = Falsegildata_token: Optional[str] = None+ gildata_features: list[GildataFeature] | None = Noneclear_gildata_token: bool = Falsesource_orders: Optional[List[SourceOrderUpdate]] = None@@ -197,7 +201,7 @@ GILDATA_TOKEN_PLACEHOLDERS = {"", "your-gildata-token"}def _desktop_secure_credential_names() -> set[str]:"""Return secrets owned by the desktop host when secure storage is active."""- names = {"TUSHARE_TOKEN", "QVERIS_API_KEY", "GILDATA_TOKEN"}+ names = {"TUSHARE_TOKEN", "GILDATA_TOKEN"}names.update(provider.api_key_env for provider in LLM_PROVIDERS if provider.api_key_env)@@ -687,6 +691,7 @@ def _build_data_source_settings_response(tushare_token_hint=None,gildata_token_configured=gildata_configured,gildata_token_hint=None,+ gildata_features=selected_features(),baostock_supported=supported,baostock_installed=installed,baostock_message=baostock_message,@@ -1004,18 +1009,23 @@ def register_settings_routes(if value != current_values.get(env_var, ""):updates[env_var] = value+ if payload.gildata_features is not None:+ updates[FEATURES_ENV] = ",".join(dict.fromkeys(payload.gildata_features))+if updates:saved_values = _persist_settings_updates(updates)- token = updates.get("TUSHARE_TOKEN", "").strip()- if host_ref._is_configured_secret(token, TUSHARE_TOKEN_PLACEHOLDERS):- os.environ["TUSHARE_TOKEN"] = token- else:- os.environ.pop("TUSHARE_TOKEN", None)- gildata_token = updates.get("GILDATA_TOKEN", "").strip()- if host_ref._is_configured_secret(gildata_token, GILDATA_TOKEN_PLACEHOLDERS):- os.environ["GILDATA_TOKEN"] = gildata_token- else:- os.environ.pop("GILDATA_TOKEN", None)+ for key, placeholders in (+ ("TUSHARE_TOKEN", TUSHARE_TOKEN_PLACEHOLDERS),+ ("GILDATA_TOKEN", GILDATA_TOKEN_PLACEHOLDERS),+ ):+ if key in updates:+ token = updates[key].strip()+ if host_ref._is_configured_secret(token, placeholders):+ os.environ[key] = token+ else:+ os.environ.pop(key, None)+ if FEATURES_ENV in updates:+ os.environ[FEATURES_ENV] = updates[FEATURES_ENV]# Hot-apply source-order overrides in this process.for env_var, value in order_updates.items():if value:diff --git a/agent/src/api/shannon_routes.py b/agent/src/api/shannon_routes.pyindex 60ce08d00..4080146c1 100644--- a/agent/src/api/shannon_routes.py+++ b/agent/src/api/shannon_routes.py@@ -7,7 +7,7 @@ import mathfrom fastapi import Depends, FastAPI, HTTPExceptionfrom pydantic import BaseModel, ConfigDict, Field, model_validator-from src.config.accessor import get_env_config+from src.config.gildata_features import feature_availablefrom src.tools.gildata_srv import call_srv_arguments@@ -42,12 +42,12 @@ class Snapshot(BaseModel):def configured() -> bool:- return get_env_config().data.gildata_token.strip() not in {"", "your-gildata-token"}+ return feature_available("shannon")def invoke(arguments: dict) -> dict:if not configured():- raise HTTPException(503, "请先配置聚源Token / Configure GILDATA_TOKEN first")+ raise HTTPException(503, "Shannon diagnosis is disabled or unavailable")try:return call_srv_arguments("ShannonAnalyze", arguments)except Exception:diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex d5518255b..4100e9bb7 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -230,6 +230,7 @@ class DataConfig(_EnvBase):alphavantage_api_key: str = Field(alias="ALPHAVANTAGE_API_KEY", default="")tiingo_api_key: str = Field(alias="TIINGO_API_KEY", default="")fmp_api_key: str = Field(alias="FMP_API_KEY", default="")+ gildata_features: str = Field(alias="VIBE_TRADING_GILDATA_FEATURES", default="")gildata_token: str = Field(alias="GILDATA_TOKEN", default="")gildata_base_url: str = Field(alias="GILDATA_BASE_URL",@@ -278,8 +279,6 @@ class DataConfig(_EnvBase):vibe_trading_data_cache: EnvBool = Field(alias="VIBE_TRADING_DATA_CACHE", default=False)vibe_trading_data_cache_root: str = Field(alias="VIBE_TRADING_DATA_CACHE_ROOT", default="")aliyun_iqs_api_key: str = Field(alias="ALIYUN_IQS_API_KEY", default="")- qveris_api_key: str = Field(alias="QVERIS_API_KEY", default="")- qveris_base_url: str = Field(alias="QVERIS_BASE_URL", default="")tickerall_api_key: str = Field(alias="TICKERALL_API_KEY", default="")tickerall_account_id: str = Field(alias="TICKERALL_ACCOUNT_ID", default="")tickerall_base_url: str = Field(alias="TICKERALL_BASE_URL", default="")diff --git a/agent/src/config/gildata_features.py b/agent/src/config/gildata_features.pynew file mode 100644index 000000000..8f079a109--- /dev/null+++ b/agent/src/config/gildata_features.py@@ -0,0 +1,30 @@+"""Explicit opt-ins for the optional Gildata research integrations."""++from typing import Literal, get_args++from src.config.accessor import get_env_config++GildataFeature = Literal[+ "fin_query",+ "stock_selection",+ "symbol_search",+ "shannon",+ "market_quotes",+ "fund_nav",+ "macro_series",+ "announcements",+ "broker_reports",+]+FEATURES_ENV = "VIBE_TRADING_GILDATA_FEATURES"+++def selected_features() -> list[GildataFeature]:+ """Return recognized, individually selected features in settings order."""+ selected = {name.strip() for name in get_env_config().data.gildata_features.split(",")}+ return [name for name in get_args(GildataFeature) if name in selected]+++def feature_available(feature: GildataFeature) -> bool:+ """Check the current credential and opt-in before using a vendor capability."""+ data = get_env_config().data+ return data.gildata_token.strip() not in {"", "your-gildata-token"} and feature in selected_features()diff --git a/agent/src/core/runner.py b/agent/src/core/runner.pyindex 8df5b3dfc..3ebc5a296 100644--- a/agent/src/core/runner.py+++ b/agent/src/core/runner.py@@ -43,7 +43,7 @@ _SANDBOX_USER = "vibe-sandbox"# Path.home(); everything else in the real home (.env, sessions.db, memory/,# live/ mandate+audit ledger, shadow_*, dotfiles) stays unreadable to generated# strategy code — that broad read access was the VT-001 exposure.-_SANDBOX_HOME_REEXPOSE = ("cache", "data-bridge", "qveris.json")+_SANDBOX_HOME_REEXPOSE = ("cache", "data-bridge")# RLIMIT_AS caps *virtual* address space (mmap included). numpy/BLAS reserve# multi-GB virtual regions that are never resident, so a 2 GB cap spuriously# OOMs legitimate backtests; 4 GB keeps a DoS ceiling without false failures.@@ -183,7 +183,7 @@ def _prepare_sandbox_home(real_home: Path | None) -> Path:The generated strategy runs in the same subprocess as the data loaders, sothe ephemeral home re-exposes the narrow set of ``~/.vibe-trading`` paths the- loaders need (opt-in cache, local data-bridge config, qveris config) and+ loaders need (opt-in cache, local data-bridge config) andnothing else. Symlinks are used so the opt-in loader cache still persistsacross runs; ``shutil.rmtree`` later removes the links, never their targets."""diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 6b30020cc..b79d34591 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -299,7 +299,7 @@ def fetch_market_data(# sources: the override list IS the attempt order, so a user who put# tushare first actually starts there. Guards: explicit source# requests stay src-first; the fallback_chain_provider test hook wins;- # local:/qveris/tickerall/fmp keep their no-network entry point+ # local:/tickerall/fmp keep their no-network entry point# (explicit fmp must not silently return yahoo on Stable 403 — issue #1270).# Sources in _NO_NETWORK_FALLBACK_SOURCES never walk the chain.if src in _NO_NETWORK_FALLBACK_SOURCES:@@ -486,7 +486,7 @@ def fetch_market_data(continuesrc = detect_source(code) if source == "auto" else sourceif src in _NO_NETWORK_FALLBACK_SOURCES:- # Explicit local/tickerall/qveris requests must not silently+ # Explicit local/tickerall requests must not silently# fall through to a network loader (registry contract).continuemarket = _detect_market(code)diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.mdindex 8b2aacd60..7eddb69ee 100644--- a/agent/src/skills/data-routing/SKILL.md+++ b/agent/src/skills/data-routing/SKILL.md@@ -41,8 +41,7 @@ per-source skill.| alphavantage | US equities | Yes (`ALPHAVANTAGE_API_KEY`) | Unrestricted | data-routing || tiingo | US equities | Yes (`TIINGO_API_KEY`) | Unrestricted | data-routing || fmp | US equities | Yes (`FMP_API_KEY`) | Unrestricted | data-routing |-| gildata | A-shares (前复权 dailies), HK equities (raw), CN indices | Yes (`GILDATA_TOKEN` / Settings) | Gildata MCP API | data-routing |-| qveris | Global multi-asset (paid, credits) | Yes (`QVERIS_API_KEY` / Settings) | QVeris API | qveris <!-- QVERIS-INTEGRATION --> |+| gildata | A-shares (前复权 dailies), HK equities (raw), CN indices | Token + market quotes enabled in Settings; only when the user requests `source="gildata"`, no fallback | Gildata MCP API | data-routing |## Capability → Tool Routing@@ -69,12 +68,10 @@ is required only where listed (no key listed = free / no auth).| Market screen | `screen_market` | A-share | — || Symbol search | `search_symbol` | A-share, US, HK, Canada, crypto/index/FX | — || Macro / FRED series | `get_macro_series` | Macro (US/global) | `FRED_API_KEY` |-| OTC fund NAV (场外基金净值) | `get_fund_nav` | CN off-exchange funds | `GILDATA_TOKEN` |-| China macro / industry EDB (宏观行业) | `get_cn_macro_series` | CN macro/regional/industry | `GILDATA_TOKEN` |-| CN announcements (公告检索) | `get_cn_announcements` | A-share / HK / fund | `GILDATA_TOKEN` |-| Broker research (券商研报) | `search_broker_reports` | A-share / HK | `GILDATA_TOKEN` |-| Mixed financial/operating and market-data queries for one known security | `gildata_fin_query` | Vendor-supported securities | `GILDATA_TOKEN` |-| Stock screening / Top-N ranking with cross-period indicators in one query | `gildata_stock_selection` | Vendor-supported stocks | `GILDATA_TOKEN` |+| OTC fund NAV (场外基金净值) | `get_fund_nav` | CN off-exchange funds | `GILDATA_TOKEN` + `fund_nav` opt-in |+| China macro / industry EDB (宏观行业) | `get_cn_macro_series` | CN macro/regional/industry | `GILDATA_TOKEN` + `macro_series` opt-in |+| CN announcements (公告检索) | `get_cn_announcements` | A-share / HK / fund | `GILDATA_TOKEN` + `announcements` opt-in |+| Broker research (券商研报) | `search_broker_reports` | A-share / HK | `GILDATA_TOKEN` + `broker_reports` opt-in || iWenCai NL search (问财) | `iwencai_search` | A-share | `VIBE_TRADING_IWENCAI_KEY` |Notes:@@ -163,7 +160,7 @@ This discipline is what separates analysis from aggregation.### Gildata research and OTC funds-With a configured GILDATA_TOKEN, use the three srv-tool research tools for China+When the user has enabled the corresponding feature and configured a Gildata token, use its tool for Chinamacro observations, announcements and broker reports. Inspect the returned`api_names`; routing is vendor-selected. Rows retain vendor order and explicitlyreport truncation. Narrow the topic or date window to retrieve omitted records.diff --git a/agent/src/skills/mootdx/SKILL.md b/agent/src/skills/mootdx/SKILL.mdindex ba92515fe..3aa1c5ec2 100644--- a/agent/src/skills/mootdx/SKILL.md+++ b/agent/src/skills/mootdx/SKILL.md@@ -78,7 +78,7 @@ df_15m = client.bars(symbol="600519", frequency=1, offset=800)## Built-in Loader-`backtest/loaders/mootdx_loader.py` remains registered for explicit `source="mootdx"` calls. It is not in the automatic `a_share` fallback chain. The default chain is `tencent → eastmoney → baostock → akshare → tushare → gildata → local`, with unavailable loaders skipped. Tencent and AKShare ship in the base install; BaoStock requires the optional `vibe-trading-ai[ashare]` extra. Neither the base install nor that extra includes mootdx.+`backtest/loaders/mootdx_loader.py` remains registered for explicit `source="mootdx"` calls. It is not in the automatic `a_share` fallback chain. The default chain is `tencent → eastmoney → baostock → akshare → tushare → local`, with unavailable loaders skipped. Tencent and AKShare ship in the base install; BaoStock requires the optional `vibe-trading-ai[ashare]` extra. Neither the base install nor that extra includes mootdx.```pythonfrom backtest.runner import rundiff --git a/agent/src/skills/qveris/SKILL.md b/agent/src/skills/qveris/SKILL.mddeleted file mode 100644index 87aee1f42..000000000--- a/agent/src/skills/qveris/SKILL.md+++ /dev/null@@ -1,118 +0,0 @@-----name: qveris-category: data-source-description: Paid capability marketplace for global multi-asset data; use it when free Vibe-Trading sources lack coverage, depth, or provider quality, and keep free sources as the default for routine OHLCV.-----# QVeris--QVeris is a paid capability marketplace for global market, fundamental, macro,-derivatives, crypto, China/HK, news, filings, and alternative-data calls. Use it-when the built-in free sources cannot cover the requested dataset, when the user-explicitly asks for QVeris, or when a premium provider is needed for depth such-as options Greeks, analyst/calendar feeds, broad provider comparison, or paid-China/HK/global coverage. For ordinary OHLCV, keep `source: "auto"` on the free-loader chain unless the user explicitly selects `source: "qveris"`.--Signup link: [QVeris via Vibe-Trading](https://qveris.ai/?ref=Vyjjo5G_1cAHJA).-Invite code fallback: `Vyjjo5G_1cAHJA`.--## Workflow--### 1. Discover with `qveris_search`--Call `qveris_search` first. Search is free and returns candidate capabilities-with `tool_id`, provider, parameters, examples, `expected_cost`, billing rule,-categories, and `stats` such as `success_rate` and average execution time.--Good queries are concrete:--- `US listed options chain implied volatility Greeks AAPL`-- `Hong Kong market daily OHLCV financial statements`-- `FRED CPI Treasury yield curve macro series`-- `China A share northbound fund flow daily`--### 2. Inspect with `qveris_inspect`--Call `qveris_inspect` on one or more `tool_id` values before any paid call.-Inspect is free and returns the fuller parameter schema and sample parameters.-Use it to verify required parameters, enum values, date formats, and output-shape before execution.--### 3. Call with `qveris_execute`--Call `qveris_execute` only after the user has enabled QVeris and the tool has-been inspected. Pass the inspected `tool_id`, the exact `parameters`, and a-reasonable `max_response_size`. Use `session_id` and `search_id` when available-so usage can be reconciled later.--## Choosing a Capability--Prefer the candidate with the best combination of:--1. High `stats.success_rate`.-2. Low `expected_cost` for equivalent data.-3. Provider fit for the task: official or specialist sources before generic- mirrors when the figure matters.-4. Parameter clarity: required fields and examples should match the user's- requested asset, date range, and granularity.--Do not assume tools with similar names are interchangeable. The measured catalog-has very large quality variance inside the same category; design notes recorded-FMP tools ranging from near-zero to 100% success and some tradefeeds tools at-0%. Surface `success_rate` and `expected_cost` in the answer whenever the user is-choosing among paid options.--## Billing and Modes--- The default free route is Vibe-Trading's built-in public data stack; QVeris- tools are unavailable in `mode="free"`.-- Discover (`qveris_search`) and inspect (`qveris_inspect`) are free only after- the user explicitly enables the paid QVeris route.-- Execute (`qveris_execute`) is paid only when the provider call is billable.-- Failed calls, empty results, and parameter errors are not charged by the- QVeris contract; observed missing-parameter calls returned `success=false`,- `cost=0.0`, `status=not_charged`, and unchanged balance.-- `mode="free"` means the original free public-data path stays active and- QVeris is hidden from agent/tool/backtest routing.-- `mode="paid"` permits QVeris discovery, inspect, and execute calls, bounded by- `budget_credits_per_session`. Only a flat per-call quote (`24.2 credits`,- `1 credits/call`) can be reserved against that budget. A quote priced per- result, row or value is refused as `quote_not_bounded`, because its leading- number is not the bill: `1 credits/result` charged 9.66 credits for one- stock-year.-- `source: "qveris"` in a backtest or `get_market_data` serves crypto, forex,- futures and macro bars only. Stocks, ETFs and other markets with splits and- dividends are refused: the loader picks a capability by search rank, which- ignores price adjustment, so it could not say how the bars were adjusted.-- Never hide cost: every successful execute result should preserve `cost` and- `remaining_credits` for the user.--Configuration can come from `QVERIS_API_KEY` / `QVERIS_BASE_URL`, or from-Settings -> QVeris / `vibe-trading data mode paid`. If QVeris is disabled, in-free mode, or no API key is configured, the tools should be treated as-unavailable.--## Truncation--`qveris_execute` accepts `max_response_size` (`20480` default, `-1` means do not-ask QVeris to truncate). When a response is too large, QVeris returns a result-object containing a message, `truncated_content`, and `full_content_file_url`.-If the full JSON is required, fetch that signed URL and use the full payload.-If a summary is enough, cite that the response was truncated and work only from-`truncated_content`.--## Balance and Usage--Check balance and recent usage through:--- Web: Settings -> QVeris.-- CLI: `vibe-trading data status` or `vibe-trading data usage`.-- Agent/API tools: status is derived from free search/ledger/usage endpoints.--For reconciliation, prefer `execution_id`, `tool_id`, `charge_outcome`, `cost`,-and `remaining_credits` over text summaries.--## References--- [REST API reference](references/rest-api.md)-- [Coverage map](references/coverage.md)diff --git a/agent/src/skills/qveris/references/coverage.md b/agent/src/skills/qveris/references/coverage.mddeleted file mode 100644index afe12f504..000000000--- a/agent/src/skills/qveris/references/coverage.md+++ /dev/null@@ -1,64 +0,0 @@-# QVeris Coverage Map--This map condenses the 2026-07-07 Vibe-Trading design evidence. The measured-sample ran 20 finance-domain searches at `limit=50`; every search hit the-50-result cap. Deduplicated sample coverage was 841 tools across 63 providers.-QVeris also markets "10,000+ capabilities" across 15+ categories; cite that as-"10,000+ capabilities (per QVeris)".--## Provider Head List--Observed head providers and counts from the design sample:--| Provider | Sample count | Strong fit |-|----------|--------------|------------|-| FMP | 79 | US/global equities, fundamentals, calendars, ratios. |-| AlphaVantage | 75 | Equities, fundamentals, FX, macro-style time series. |-| TwelveData | 62 | Global market data and technical/time-series endpoints. |-| CoinGecko + CoinGecko Pro | 49 | Crypto spot, asset metadata, market data. |-| hangseng_polysource | 46 | Hong Kong market data. |-| cn_financial_pro | 41 | China financial data. |-| Census | 36 | Official US economic/demographic data. |-| Finnhub | 35 | Equities, news, filings, estimates, company data. |-| EODHD | 27 | End-of-day global equity data. |-| weather_gov | 27 | Weather data for commodity/event research. |-| ThetaData | 25 | US options chains, implied volatility, Greeks. |-| HKMA | 19 | Hong Kong monetary and macro data. |-| Deribit | 13 | Crypto derivatives. |-| Other observed providers | part of 63 total | cninfo, caidazi, FRED, US Treasury, SEC, Tiingo, Yahoo, Tradier, OKX, CoinMarketCap, and additional marketplace providers. |--The full 63-provider raw file is not committed in this repo. Do not invent a full-provider list from memory; use the observed head list above plus live search-results from `qveris_search`.--## Category Routing--| Category | Representative tools/providers | Typical cost range | Route to QVeris when | Prefer free Vibe-Trading sources when |-|----------|--------------------------------|--------------------|----------------------|---------------------------------------|-| US/global equities OHLCV | FMP, AlphaVantage, TwelveData, EODHD, Yahoo | 1-24.2 credits/call | The user asks for a paid provider, global breadth, or a source not covered by free loaders. | Routine OHLCV can use `source:"auto"` with yahoo/stooq/sina/eastmoney/yfinance/free fallbacks. |-| A-share and China market data | cn_financial_pro, cninfo, caidazi | 1-24.2 credits/call | Premium China fields, document-style data, or provider-specific coverage are needed. | A-share OHLCV and common flow/fundamental tools are covered by tencent/mootdx/eastmoney/akshare/tushare. |-| Hong Kong market data | hangseng_polysource, HKMA, Yahoo/FMP-style providers | 1-24.2 credits/call | HK-specific premium breadth or monetary data is required. | Routine HK OHLCV can use eastmoney/yahoo/futu/yfinance/akshare/local. |-| Fundamentals and financial statements | FMP, Finnhub, AlphaVantage, SEC, cn_financial_pro | 1-24.2 credits/call | Cross-provider comparison, premium vendor ratios, or non-US/non-China/HK coverage is needed. | US SEC facts and A/HK Eastmoney statements are available through built-in read-only tools. |-| SEC filings and institutional data | SEC, Finnhub, FMP | 1-24.2 credits/call | Marketplace convenience or 13F/filing enrichment is needed. | Official SEC filings/companyfacts should stay on built-in SEC tools when sufficient. |-| News and sentiment | Finnhub, FMP, AlphaVantage, web-search providers | 1-24.2 credits/call | Paid sentiment/news feeds or broad provider comparison are needed. | Basic stock news and web context can use built-in `get_stock_news` / `web_search`. |-| Earnings calendar and analyst estimates | Finnhub, FMP, AlphaVantage | 1-24.2 credits/call | The user needs estimates, surprises, or vendor calendars. | Avoid paid calls if the task only needs high-level narrative or public filings. |-| ETF holdings and fund data | FMP, AlphaVantage, market-data providers | 1-24.2 credits/call | Holdings/constituents are not in free tooling or need vendor consistency. | Basic OHLCV and many A-share/fund flows can use free loaders/tools. |-| Options chains, IV, Greeks | ThetaData, Tradier, Yahoo, FMP | 1-24.2 credits/call | Greeks, implied volatility surfaces, or specialist options data are required. | Basic US options chains can start with built-in `get_options_chain`. |-| FX and rates | AlphaVantage, TwelveData, US Treasury, FRED | 1-24.2 credits/call | Paid FX/rate granularity or provider-specific fields are needed. | Macro/FRED and basic FX can use built-in `get_macro_series`, tushare, or akshare when sufficient. |-| Crypto spot/derivatives/on-chain | CoinGecko Pro, Deribit, OKX, CoinMarketCap | 1-24.2 credits/call | CoinGecko Pro, derivatives, breadth, or paid metadata are needed. | Routine crypto OHLCV should use okx/ccxt/yfinance/local. |-| Commodities and weather | FMP-style commodity feeds, weather_gov | 1-24.2 credits/call | Weather-sensitive commodity/event analysis needs structured weather data. | Public web/document research is enough for qualitative context. |-| Macro official data | FRED, Census, US Treasury, HKMA | 1-24.2 credits/call | One key should access many official-style sources through one interface. | Built-in FRED macro is preferred when it covers the series and key is configured. |-| Corporate actions | FMP, AlphaVantage, EODHD | 1-24.2 credits/call | Dividends, splits, IPO, or vendor-adjusted history is missing in free sources. | Use free loaders for simple adjusted/unadjusted OHLCV where adequate. |-| Short interest and alternative data | Finnhub/FMP-style feeds, marketplace providers | 1-24.2 credits/call | The data class is absent from built-in tools. | Use built-in data only when it directly covers the requested metric. |--## Agent Policy--- Start with free Vibe-Trading sources for routine OHLCV and official/free tools.-- Use QVeris for paid breadth, specialist data, and provider comparison.-- Always inspect before execute.-- Rank paid candidates by `stats.success_rate`, `expected_cost`, provider fit,- and parameter clarity.-- Tell the user when a result is single-source or when provider quality varies.-- Failed, empty, and parameter-error executions are expected not to charge; keep- `execution_id`, `charge_outcome`, `reason_code`, `cost`, and- `remaining_credits` in the evidence trail.diff --git a/agent/src/skills/qveris/references/rest-api.md b/agent/src/skills/qveris/references/rest-api.mddeleted file mode 100644index 847e4f65e..000000000--- a/agent/src/skills/qveris/references/rest-api.md+++ /dev/null@@ -1,215 +0,0 @@-# QVeris REST API Reference--This reference is based on the frozen Vibe-Trading QVeris contract dated-2026-07-07. API authentication uses `Authorization: Bearer <QVERIS_API_KEY>`.-The default base endpoint is the QVeris API v1 base configured by-`QVERIS_BASE_URL`; Vibe-Trading's default is the production API v1 endpoint from-the frozen contract.--## Common Fields--| Field | Type | Meaning |-|-------|------|---------|-| `session_id` | string? | Optional caller session for usage grouping. |-| `search_id` | string? | Search correlation id returned by `/search`. |-| `remaining_credits` | number? | Account credits after the request or latest free lookup. |-| `error_message` | string? | Provider or API error text. Treat as user-facing diagnostic, not a stack trace. |--Errors may appear as HTTP errors or as HTTP 200 responses with-`success=false`, `error_message`, and an execution/billing outcome. Parse both.--## POST `/search` (Free)--Searches the marketplace for matching capabilities. Invalid keys return HTTP-401 with empty results.--### Request--| Field | Type | Required | Notes |-|-------|------|----------|-------|-| `query` | string | yes | Natural-language capability query. |-| `limit` | integer | no | 1-100, default 20. |-| `session_id` | string | no | Optional Vibe-Trading session id. |--### Response--| Field | Type | Notes |-|-------|------|-------|-| `query` | string | Echoed query. |-| `search_id` | string | Pass to inspect/execute for attribution. |-| `total` | integer | Total matched capabilities. |-| `results` | array | Capability summaries, see below. |-| `elapsed_time_ms` | number | Search latency. |-| `remaining_credits` | number? | Current balance if returned. |-| `error_message` | string? | Present on degraded/error response. |--### Result Object--| Field | Type | Notes |-|-------|------|-------|-| `tool_id` | string | Required for inspect/execute. |-| `name` | string | Capability display name. |-| `description` | string | Capability summary. |-| `provider_name` | string? | Provider/vendor name. |-| `params` | array | Parameter summaries with `name`, `type`, `required`, `description`, optional `enum`. |-| `examples.sample_parameters` | object? | Example request parameters. |-| `expected_cost` | string | Quoted expected credit cost; compare before execute. |-| `billing_rule` | object | Billing terms; preserve for user-visible cost quotes. |-| `stats` | object | Includes `avg_execution_time_ms`, `success_rate`, and provider stats when present. |-| `categories` | array | Category objects, usually with `slug`. |--## POST `/tools/by-ids` (Free)--Fetches full capability metadata by `tool_id`. Use this before paid execution.--### Request--| Field | Type | Required | Notes |-|-------|------|----------|-------|-| `tool_ids` | string[] | yes | One or more ids returned by search. |-| `search_id` | string | no | Original search correlation id. |-| `session_id` | string | no | Optional Vibe-Trading session id. |--### Response--The response uses the same `results` shape as `/search`, but with fuller-`params` and examples. Treat missing fields as absent, not fatal.--## POST `/tools/execute?tool_id={tool_id}` (Paid When Billable)--Executes one capability. Vibe-Trading must keep QVeris unavailable in `free`-mode and check session budget in `paid` mode before sending the request.--### Query--| Field | Type | Required | Notes |-|-------|------|----------|-------|-| `tool_id` | string | yes | Capability id from search/inspect. |--### Request Body--| Field | Type | Required | Notes |-|-------|------|----------|-------|-| `search_id` | string | no | Correlates execution to discovery. |-| `session_id` | string | no | Correlates execution to Vibe-Trading session. |-| `model` | string | no | Optional model hint accepted by QVeris. |-| `parameters` | object | yes | Exact parameters from inspected schema. |-| `max_response_size` | integer | no | Default 20480; `-1` requests no truncation. |--### Response--| Field | Type | Notes |-|-------|------|-------|-| `execution_id` | string | Use for usage reconciliation. |-| `result` | object | Provider payload or truncation envelope. |-| `success` | boolean | Provider/API success. |-| `error_message` | string? | Error when `success=false`. |-| `execution_time` | number? | Provider execution time. |-| `elapsed_time_ms` | number? | End-to-end latency. |-| `billing.summary` | string? | Human billing summary. |-| `billing.list_amount_credits` | number? | Listed credit amount. |-| `execution_outcome.outcome` | string? | Execution outcome label. |-| `execution_outcome.reason_code` | string? | Reason for charge or no-charge state. |-| `execution_outcome.provider_success` | boolean? | Whether upstream provider succeeded. |-| `execution_outcome.billable_success` | boolean? | Whether success is billable. |-| `execution_outcome.result_valid` | boolean? | Whether result passed QVeris validation. |-| `execution_outcome.status` | string? | Settlement status such as `not_charged`. |-| `cost` | number | Actual charged credits; observed parameter errors return `0.0`. |-| `remaining_credits` | number | Balance after settlement. |--### Truncation Envelope--When the provider payload exceeds `max_response_size`, `result` contains:--| Field | Type | Notes |-|-------|------|-------|-| `message` | string | Explains the response is too long. |-| `full_content_file_url` | string | Signed URL for the full JSON payload. |-| `truncated_content` | string/object | Partial payload for quick inspection. |--Fetch `full_content_file_url` only when the full result is necessary. Signed-URLs may expire and should not be persisted as durable evidence.--## GET `/auth/usage/history/v2` (Free)--Usage event history and summary endpoint. The response shape is intentionally-parsed leniently because QVeris may return events at the top level or under-`data`.--### Query Parameters--| Parameter | Type | Notes |-|-----------|------|-------|-| `execution_id` | string | Filter one execution. |-| `start_date`, `end_date` | string | Date range filters. |-| `kind` | string | Common values: `discover`, `call`, `model`. |-| `charge_outcome` | string | `charged`, `included`, `failed_not_charged`, `failed_charged_review`. |-| `summary` | boolean | `true` for aggregate summary. |-| `bucket` | string | Common value: `day`. |-| `limit` | integer | Max rows. |-| `page`, `page_size` | integer | Pagination. |--### Event Fields--| Field | Type | Notes |-|-------|------|-------|-| `id` | string | Usage event id. |-| `event_type` | string | Event category. |-| `session_id` | string? | Caller session. |-| `search_id` | string? | Search id. |-| `execution_id` | string? | Execution id. |-| `tool_id` | string? | Capability id. |-| `success` | boolean? | Request success. |-| `charge_outcome` | string? | Settlement result. |-| `duration_ms` | number? | Duration in milliseconds. |--## GET `/auth/credits/ledger` (Free)--Credit ledger endpoint for balance and audit.--### Query Parameters--| Parameter | Type | Notes |-|-----------|------|-------|-| `direction` | string | `consume`, `grant`, or `any`. |-| `entry_type` | string | Ledger entry type filter. |-| `summary` | boolean | `true` for aggregate summary. |-| `limit` | integer | Max rows. |-| `page`, `page_size` | integer | Pagination. |--### Item Fields--| Field | Type | Notes |-|-------|------|-------|-| `id` | string | Ledger entry id. |-| `entry_type` | string | Examples: `consume_tool_execute`, `grant_welcome_bonus`. |-| `amount_credits` | number | Negative means consumption; positive means grant. |-| `execution_id` | string? | Execution id for consumed credits. |-| `pre_settlement_bill` | object? | Bill details before settlement. |--## Charge Outcomes and Reason Codes--| Field/value | Meaning | Agent behavior |-|-------------|---------|----------------|-| `charge_outcome=charged` | Credits were consumed. | Report `cost` and `remaining_credits`. |-| `charge_outcome=included` | Included/free quota covered it. | Report no incremental charge if `cost=0`. |-| `charge_outcome=failed_not_charged` | Failure was not charged. | Surface error and suggest parameter/provider fix. |-| `charge_outcome=failed_charged_review` | Failure may need billing review. | Preserve `execution_id` and tell user to review usage. |-| `reason_code=missing_required_parameter` | Parameters invalid or missing. | Inspect schema, repair parameters, no charge expected. |-| `reason_code=empty_result` | Provider returned no usable data. | No charge expected; try different date/symbol/provider. |-| `reason_code=provider_error` | Upstream provider failed. | No charge expected; try alternate provider. |-| unknown `reason_code` | QVeris may add values. | Treat as opaque evidence; do not infer charge beyond `cost`. |--## 429 Rate Limits--Contracted nominal limits are search 120/min and execute 200/min, but measured-bursts around 20 requests in a short window can return 429. Clients must throttle-requests and retry 429 responses using headers.--| Header | Required handling |-|--------|-------------------|-| `Retry-After` | Sleep for the indicated seconds before retry. |-| `X-RateLimit-*` | If present, log only redacted/non-secret values and respect reset hints. |--Vibe-Trading clients should use a minimum request interval of 0.5 seconds and at-most 3 retries on 429.diff --git a/agent/src/tools/fund_nav_tool.py b/agent/src/tools/fund_nav_tool.pyindex dbad8cdc2..a74988e2e 100644--- a/agent/src/tools/fund_nav_tool.py+++ b/agent/src/tools/fund_nav_tool.py@@ -31,6 +31,7 @@ from backtest.loaders.gildata_codes import resolve_vendor_codefrom backtest.loaders.gildata_loader import _call_tool, _recall_candidatesfrom src.agent.tools import BaseToolfrom src.config.accessor import get_env_config+from src.config.gildata_features import feature_availablefrom src.config.limits import TOOL_RESULT_LIMITlogger = logging.getLogger(__name__)@@ -131,8 +132,8 @@ class GildataFundNavTool(BaseTool):@classmethoddef check_available(cls) -> bool:- """Available only when ``GILDATA_TOKEN`` is configured."""- return bool(get_env_config().data.gildata_token)+ """Require a token and explicit selection of this feature."""+ return feature_available("fund_nav")def execute(self, **kwargs: Any) -> str:"""Fetch NAV history for one or more funds and return a JSON envelope.@@ -147,8 +148,8 @@ class GildataFundNavTool(BaseTool):"count"}}}``; a failing fund carries ``{"ok": false, "error"}``and never aborts the rest of the batch."""- if not get_env_config().data.gildata_token:- return _error("GILDATA_TOKEN is not configured")+ if not self.check_available():+ return _error("Enable fund_nav in Gildata settings and configure GILDATA_TOKEN.")raw_codes = kwargs.get("funds")if isinstance(raw_codes, str):diff --git a/agent/src/tools/gildata_fin_query_tool.py b/agent/src/tools/gildata_fin_query_tool.pyindex c41f93580..6dad1a435 100644--- a/agent/src/tools/gildata_fin_query_tool.py+++ b/agent/src/tools/gildata_fin_query_tool.py@@ -8,10 +8,9 @@ from decimal import Decimal, InvalidOperationfrom typing import Anyfrom src.agent.tools import BaseTool-from src.config.accessor import get_env_config+from src.config.gildata_features import feature_availablefrom src.tools.gildata_srv import call_srv_tool_results-_PLACEHOLDER_TOKENS = {"", "your-gildata-token"}_QUOTE_LABELS = {"开盘价": "open", "今开盘": "open", "最高价": "high", "最低价": "low","收盘价": "close", "最新价": "price", "前收盘": "prev_close","前收盘价": "prev_close", "昨收": "prev_close"}@@ -124,11 +123,11 @@ class GildataFinQueryTool(BaseTool):@classmethoddef check_available(cls) -> bool:- return get_env_config().data.gildata_token.strip() not in _PLACEHOLDER_TOKENS+ return feature_available("fin_query")def execute(self, **kwargs: Any) -> str:if not self.check_available():- return json.dumps({"ok": False, "error_type": "not_configured", "error": "GILDATA_TOKEN is not configured"})+ return json.dumps({"ok": False, "error_type": "not_configured", "error": "Gildata feature is disabled or unavailable"})query = kwargs.get("query")if not isinstance(query, str) or not 1 <= len(query.strip()) <= 4000:return json.dumps({"ok": False, "error_type": "invalid_query",diff --git a/agent/src/tools/gildata_identity.py b/agent/src/tools/gildata_identity.pyindex 433af094b..daac0ea27 100644--- a/agent/src/tools/gildata_identity.py+++ b/agent/src/tools/gildata_identity.py@@ -2,11 +2,11 @@import refrom backtest.loaders.gildata_loader import _call_tool_results-from src.config.accessor import get_env_config+from src.config.gildata_features import feature_availabledef search_candidates(query: str, limit: int) -> tuple[list[dict], str | None]:- if get_env_config().data.gildata_token.strip() in {"", "your-gildata-token"}:+ if not feature_available("symbol_search"):return [], Nonedomains = {"StockDailyQuote": "a", "HKStockDailyQuotes": "hk", "USStockDailyQuotes": "us"}keyword = query[:-3] if query.upper().endswith(".US") else querydiff --git a/agent/src/tools/gildata_research_tools.py b/agent/src/tools/gildata_research_tools.pyindex 8152543ff..45254159b 100644--- a/agent/src/tools/gildata_research_tools.py+++ b/agent/src/tools/gildata_research_tools.py@@ -30,6 +30,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.config.accessor import get_env_config+from src.config.gildata_features import GildataFeature, feature_availablefrom src.config.limits import TOOL_RESULT_LIMITfrom src.tools._result_paging import fit_recordsfrom src.tools.gildata_srv import call_srv_tool@@ -90,16 +91,17 @@ def _clean_limit(kwargs: Any) -> int:class _GildataSrvToolBase(BaseTool):"""Shared plumbing for the srv-tool wrappers."""+ feature: GildataFeaturevendor_tool: str = ""@classmethoddef check_available(cls) -> bool:- """Available only when ``GILDATA_TOKEN`` is configured."""- return bool(get_env_config().data.gildata_token)+ """Require a token and explicit selection of this feature."""+ return feature_available(cls.feature)def execute(self, **kwargs: Any) -> str:- if not get_env_config().data.gildata_token:- return _error("GILDATA_TOKEN is not configured")+ if not self.check_available():+ return _error(f"Enable {self.feature} in Gildata settings and configure GILDATA_TOKEN.")query = _clean_query(kwargs)if query is None:return _error("'query' must contain 1 to 4000 characters")@@ -117,6 +119,7 @@ class GetCnMacroSeriesTool(_GildataSrvToolBase):"""China macro / regional / industry economic time series (EDB)."""name = "get_cn_macro_series"+ feature = "macro_series"vendor_tool = "MacroIndustryData"description = ("Fetch China macro / regional / industry economic indicator series "@@ -152,6 +155,7 @@ class GetCnAnnouncementsTool(_GildataSrvToolBase):"""A-share / HK / fund announcement retrieval with highlighted excerpts."""name = "get_cn_announcements"+ feature = "announcements"vendor_tool = "AnnouncementData"description = ("Search Chinese-market company announcements (公告): A-share, HK and "@@ -186,6 +190,7 @@ class SearchBrokerReportsTool(_GildataSrvToolBase):"""Broker research search over the Juyuan report library."""name = "search_broker_reports"+ feature = "broker_reports"vendor_tool = "FinancialResearchReport"description = ("Search sell-side broker research (券商研报) over the Juyuan library: "diff --git a/agent/src/tools/gildata_stock_selection_tool.py b/agent/src/tools/gildata_stock_selection_tool.pyindex d77d65894..3dadd3611 100644--- a/agent/src/tools/gildata_stock_selection_tool.py+++ b/agent/src/tools/gildata_stock_selection_tool.py@@ -5,7 +5,7 @@ import jsonfrom typing import Anyfrom src.agent.tools import BaseTool-from src.config.accessor import get_env_config+from src.config.gildata_features import feature_availablefrom src.tools.gildata_fin_query_tool import _normalize_tablefrom src.tools.gildata_srv import call_srv_tool_results@@ -17,7 +17,7 @@ class GildataStockSelectionTool(BaseTool):description = ("聚源智能选股:一次查询完成指定日期的股票筛选/TopN排名,并返回所选股票跨报告期的财务金额、估值或行情指标。 ""Example: 沪深300权重最高的10只成分股及2023、2024年全年营业收入. "- "Use gildata_fin_query for attribute/history queries without screening. "+ """Requires GILDATA_TOKEN; read-only.")parameters = {@@ -32,11 +32,11 @@ class GildataStockSelectionTool(BaseTool):@classmethoddef check_available(cls) -> bool:- return get_env_config().data.gildata_token.strip() not in {"", "your-gildata-token"}+ return feature_available("stock_selection")def execute(self, **kwargs: Any) -> str:if not self.check_available():- return json.dumps({"ok": False, "error_type": "not_configured", "error": "GILDATA_TOKEN is not configured"})+ return json.dumps({"ok": False, "error_type": "not_configured", "error": "Gildata feature is disabled or unavailable"})query, topk = kwargs.get("query"), kwargs.get("topk")if not isinstance(query, str) or not 1 <= len(query.strip()) <= 4000:return json.dumps({"ok": False, "error_type": "invalid_query", "error": "query must contain 1 to 4000 characters"})diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.pyindex 5c4c25ef6..8829b22df 100644--- a/agent/src/tools/market_data_tool.py+++ b/agent/src/tools/market_data_tool.py@@ -118,6 +118,8 @@ class MarketDataTool(BaseTool):"enum": _SOURCE_ENUM,"description": ("Data source. 'auto' detects from symbol format with fallback. "+ "Use 'gildata' only if the user asks for Gildata quotes; requires a token "+ "and the market quotes opt-in, with no fallback in either direction. ""Use 'longbridge' explicitly for US/HK OHLCV through the ""Longbridge OpenAPI (requires Longbridge credentials). ""Free, no key: yfinance/yahoo (US/HK/Canada equities; "@@ -128,7 +130,7 @@ class MarketDataTool(BaseTool):"bars for <CODE>.KS / <CODE>.KQ; needs the optional pykrx ""package, else Korea falls back to yahoo/yfinance). Key-gated ""REST: tushare (China A-shares), finnhub/alphavantage/tiingo/fmp "- "(US/global), qveris (premium marketplace). india_broker: "+ "(US/global). india_broker: ""read-only Shoonya/Dhan bars for .NS/.BO. mt5: forex/metals ""from a local MetaTrader 5 terminal (Windows; e.g. EUR/USD, ""XAUUSD.FX); tickerall: the same feed hosted, no terminal, "diff --git a/agent/src/tools/qveris_tool.py b/agent/src/tools/qveris_tool.pydeleted file mode 100644index cf15559a2..000000000--- a/agent/src/tools/qveris_tool.py+++ /dev/null@@ -1,682 +0,0 @@-"""QVeris discovery and execution tools."""--from __future__ import annotations--import json-import math-import os-import tempfile-import threading-import time-from collections.abc import Mapping-from dataclasses import asdict, dataclass-from pathlib import Path-from typing import Any--import httpx--from backtest.loaders.qveris_loader import quoted_call_cost-from src.agent.tools import BaseTool--SIGNUP_URL = "https://qveris.ai/?ref=Vyjjo5G_1cAHJA"-INVITE_CODE = "Vyjjo5G_1cAHJA"-DEFAULT_BASE_URL = "https://qveris.ai/api/v1"-QVERIS_CONFIG_PATH = Path.home() / ".vibe-trading" / "qveris.json"-VALID_MODES = {"free", "paid"}-_LEGACY_MODE_MAP = {- "preview": "free",- "allow_paid": "paid",- "free": "free",- "paid": "paid",-}--_SESSION_SPEND: dict[str, float] = {}-_SESSION_RESERVED: dict[str, float] = {}-_SESSION_BUDGET_LOCK = threading.Lock()---@dataclass-class QVerisConfig:- """QVeris local configuration."""-- enabled: bool = False- base_url: str = DEFAULT_BASE_URL- api_key: str = ""- mode: str = "free"- budget_credits_per_session: float = 50.0---def _read_config_file() -> QVerisConfig:- """Read the persisted QVeris config without env overrides."""- if not QVERIS_CONFIG_PATH.exists():- return QVerisConfig()- try:- raw = json.loads(QVERIS_CONFIG_PATH.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- return QVerisConfig()- cfg = QVerisConfig()- if isinstance(raw, dict):- cfg.enabled = bool(raw.get("enabled", cfg.enabled))- cfg.base_url = str(raw.get("base_url") or cfg.base_url)- cfg.api_key = str(raw.get("api_key") or "")- cfg.mode = normalize_qveris_mode(str(raw.get("mode") or cfg.mode))- try:- cfg.budget_credits_per_session = float(- raw.get("budget_credits_per_session", cfg.budget_credits_per_session)- )- except (TypeError, ValueError):- cfg.budget_credits_per_session = 50.0- if cfg.budget_credits_per_session < 0:- cfg.budget_credits_per_session = 0.0- return cfg---def load_qveris_config() -> QVerisConfig:- """Load QVeris config with environment overrides applied."""- from src.config.accessor import get_env_config-- cfg = _read_config_file()- env_key = get_env_config().data.qveris_api_key- env_url = get_env_config().data.qveris_base_url- if env_key:- cfg.api_key = env_key.strip()- if env_url:- cfg.base_url = env_url.strip() or DEFAULT_BASE_URL- return cfg---def save_qveris_config(config: QVerisConfig) -> QVerisConfig:- """Persist QVeris config with atomic replace and 0600 permissions.-- Args:- config: Configuration to persist.-- Returns:- The normalized configuration that was written.- """- cfg = QVerisConfig(- enabled=bool(config.enabled),- base_url=(config.base_url or DEFAULT_BASE_URL).rstrip("/"),- api_key=config.api_key or "",- mode=normalize_qveris_mode(config.mode),- budget_credits_per_session=max(float(config.budget_credits_per_session), 0.0),- )- QVERIS_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)- fd, tmp_name = tempfile.mkstemp(- prefix=".qveris.", suffix=".tmp", dir=str(QVERIS_CONFIG_PATH.parent)- )- tmp_path = Path(tmp_name)- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- json.dump(asdict(cfg), handle, ensure_ascii=False, indent=2)- handle.write("\n")- os.chmod(tmp_path, 0o600)- os.replace(tmp_path, QVERIS_CONFIG_PATH)- os.chmod(QVERIS_CONFIG_PATH, 0o600)- finally:- if tmp_path.exists():- tmp_path.unlink()- return cfg---def mask_api_key(api_key: str) -> str:- """Return a non-reversible display mask for an API key."""- key = (api_key or "").strip()- if not key:- return ""- if len(key) <= 7:- return "***"- return f"{key[:4]}…{key[-3:]}"---def normalize_qveris_mode(mode: str | None) -> str:- """Normalize user-facing QVeris mode names."""- return _LEGACY_MODE_MAP.get(str(mode or "").strip(), "free")---def has_qveris_credentials(config: QVerisConfig | None = None) -> bool:- """Return whether a QVeris API key is saved or provided."""- cfg = config or load_qveris_config()- return bool(cfg.api_key.strip())---def is_qveris_configured(config: QVerisConfig | None = None) -> bool:- """Return whether QVeris paid routing should be visible."""- cfg = config or load_qveris_config()- return has_qveris_credentials(cfg) and normalize_qveris_mode(cfg.mode) == "paid"---def _json_response(payload: dict[str, Any]) -> str:- """Serialize a tool response."""- return json.dumps(payload, ensure_ascii=False, default=str)---def _unconfigured_message(config: QVerisConfig | None = None) -> str:- """Build an actionable error message when QVeris routing is unavailable.-- Args:- config: Optional pre-loaded configuration; defaults to- :func:`load_qveris_config`.-- Returns:- Operator-facing error text. When no API key is saved it names- ``QVERIS_API_KEY`` and the paid-mode switch; when a key exists but- paid routing is off it points at the paid-mode toggle only.- """- cfg = config or load_qveris_config()- if not has_qveris_credentials(cfg):- return (- "QVeris is not configured; set QVERIS_API_KEY and enable paid mode "- "(`vibe-trading data mode paid` or Settings -> QVeris) to use QVeris tools"- )- return (- "QVeris paid mode is off; enable it with `vibe-trading data mode paid` "- "or Settings -> QVeris to use QVeris tools"- )---def _parse_expected_cost(value: Any) -> float | None:- """Return the flat per-call price a QVeris quote states, or None.-- The leading number of a quote is not a price when the quote is per result:- "1 credits/result" billed 9.66 credits for one stock-year (#1494). Shared- with the bar loader so the two budget gates read a quote the same way.- """- return quoted_call_cost(value)---def _quote_from_tool(tool: dict[str, Any] | None) -> dict[str, Any]:- """Project quote fields from a QVeris tool descriptor."""- tool = tool or {}- return {- "tool_id": tool.get("tool_id"),- "name": tool.get("name"),- "expected_cost": tool.get("expected_cost"),- "billing_rule": tool.get("billing_rule"),- "stats": tool.get("stats"),- }---class QVerisClient:- """Small synchronous client for the QVeris REST API."""-- def __init__(- self,- config: QVerisConfig | None = None,- *,- client: httpx.Client | None = None,- min_interval_seconds: float = 0.5,- max_429_retries: int = 3,- ) -> None:- """Initialize the client.-- Args:- config: Optional config; defaults to :func:`load_qveris_config`.- client: Injectable HTTP client for tests.- min_interval_seconds: Minimum spacing between requests.- max_429_retries: Maximum retries for HTTP 429 responses.- """- self.config = config or load_qveris_config()- self.base_url = self.config.base_url.rstrip("/")- self._client = client or httpx.Client(follow_redirects=True, timeout=60.0)- self._min_interval_seconds = max(float(min_interval_seconds), 0.0)- self._max_429_retries = max(int(max_429_retries), 0)- self._last_request_at = 0.0-- def _headers(self) -> dict[str, str]:- return {"Authorization": f"Bearer {self.config.api_key}"}-- def _wait_for_slot(self) -> None:- if self._min_interval_seconds <= 0:- return- elapsed = time.monotonic() - self._last_request_at- wait = self._min_interval_seconds - elapsed- if wait > 0:- time.sleep(wait)-- def _request(- self,- method: str,- path: str,- *,- json_body: dict[str, Any] | None = None,- params: dict[str, Any] | None = None,- auth: bool = True,- ) -> dict[str, Any]:- """Send a JSON request with spacing and 429 Retry-After handling."""- url = path if path.startswith(("http://", "https://")) else f"{self.base_url}{path}"- attempts = 0- while True:- self._wait_for_slot()- response = self._client.request(- method,- url,- json=json_body,- params=params,- headers=self._headers() if auth else None,- )- self._last_request_at = time.monotonic()- if response.status_code == 429 and attempts < self._max_429_retries:- attempts += 1- retry_after = response.headers.get("Retry-After", "1")- try:- delay = max(float(retry_after), 0.0)- except ValueError:- delay = 1.0- time.sleep(delay)- continue- response.raise_for_status()- if not response.content:- return {}- return response.json()-- def _download_full_content(self, url: str) -> Any:- payload = self._request("GET", url, auth=False)- return payload-- def _hydrate_truncated_result(self, payload: dict[str, Any]) -> dict[str, Any]:- result = payload.get("result")- if not isinstance(result, dict):- return payload- full_url = result.get("full_content_file_url")- if not isinstance(full_url, str) or not full_url:- return payload- try:- result["full_content"] = self._download_full_content(full_url)- result["full_content_downloaded"] = True- except Exception as exc: # noqa: BLE001 - preserve the paid response.- result["full_content_download_error"] = str(exc)- return payload-- def search(- self, query: str, *, limit: int = 20, session_id: str | None = None- ) -> dict[str, Any]:- """Call ``POST /search``."""- body: dict[str, Any] = {"query": query, "limit": min(max(int(limit), 1), 100)}- if session_id:- body["session_id"] = session_id- return self._request("POST", "/search", json_body=body)-- def inspect(- self,- tool_ids: list[str],- *,- search_id: str | None = None,- session_id: str | None = None,- ) -> dict[str, Any]:- """Call ``POST /tools/by-ids``."""- body: dict[str, Any] = {"tool_ids": tool_ids}- if search_id:- body["search_id"] = search_id- if session_id:- body["session_id"] = session_id- return self._request("POST", "/tools/by-ids", json_body=body)-- def execute(- self,- tool_id: str,- *,- parameters: dict[str, Any],- search_id: str | None = None,- session_id: str | None = None,- model: str | None = None,- max_response_size: int = 20480,- ) -> dict[str, Any]:- """Call ``POST /tools/execute`` and hydrate truncated results."""- body: dict[str, Any] = {- "parameters": parameters,- "max_response_size": max_response_size,- }- if search_id:- body["search_id"] = search_id- if session_id:- body["session_id"] = session_id- if model:- body["model"] = model- payload = self._request(- "POST",- "/tools/execute",- json_body=body,- params={"tool_id": tool_id},- )- return self._hydrate_truncated_result(payload)-- def usage_history(self, **params: Any) -> dict[str, Any]:- """Call ``GET /auth/usage/history/v2``."""- return self._request("GET", "/auth/usage/history/v2", params=params)-- def credits_ledger(self, **params: Any) -> dict[str, Any]:- """Call ``GET /auth/credits/ledger``."""- return self._request("GET", "/auth/credits/ledger", params=params)---def _positive_int(value: Any, field: str, default: int) -> int:- """Resolve an optional positive-integer option from tool kwargs.-- Args:- value: Raw argument value; ``None`` and ``""`` mean "not supplied".- field: Argument name, used in the error message.- default: Value to use when the argument was not supplied.-- Returns:- The requested integer, or ``default`` when the argument was absent.-- Raises:- ValueError: If the value is present but not a finite positive integer.- QVeris calls are billable, so an explicitly malformed option is- rejected instead of being replaced by a default.- """- if value is None or value == "":- return default- try:- number = float(value)- except (TypeError, ValueError, OverflowError):- raise ValueError(f"{field} must be a positive integer, got {value!r}") from None- if not math.isfinite(number) or number != int(number) or int(number) < 1:- raise ValueError(f"{field} must be a positive integer, got {value!r}")- return int(number)---class _QVerisBaseTool(BaseTool):- """Shared availability and client helpers for QVeris tools."""-- @classmethod- def check_available(cls) -> bool:- """Hide QVeris tools until explicitly enabled and keyed."""- return is_qveris_configured()-- def _client(self) -> QVerisClient:- return QVerisClient()---class QVerisSearchTool(_QVerisBaseTool):- """Discover QVeris capabilities."""-- name = "qveris_search"- description = (- "Search QVeris premium data/tool capabilities. Discover/inspect calls "- "are free; choose tools by expected_cost and stats.success_rate."- )- parameters = {- "type": "object",- "properties": {- "query": {"type": "string", "description": "Capability search query."},- "limit": {- "type": "integer",- "minimum": 1,- "maximum": 100,- "default": 20,- },- "session_id": {"type": "string"},- },- "required": ["query"],- }-- def execute(self, **kwargs: Any) -> str:- """Search QVeris capabilities after validating the request schema.-- A missing ``query`` is a schema-invalid request, not an empty search:- it is rejected rather than sent to the marketplace as ``""``.- """- if not is_qveris_configured():- return _json_response({"ok": False, "error": _unconfigured_message()})- query = kwargs.get("query")- if not isinstance(query, str) or not query.strip():- return _json_response(- {"ok": False, "error": "query is required (non-empty string)"}- )- try:- limit = _positive_int(kwargs.get("limit"), "limit", 20)- except ValueError as exc:- return _json_response({"ok": False, "error": str(exc)})- payload = self._client().search(- query.strip(),- limit=limit,- session_id=kwargs.get("session_id"),- )- return _json_response({"ok": True, **payload})---class QVerisInspectTool(_QVerisBaseTool):- """Inspect full QVeris tool parameter schemas."""-- name = "qveris_inspect"- description = "Inspect QVeris tools by id before executing a paid call."- parameters = {- "type": "object",- "properties": {- "tool_ids": {- "type": "array",- "items": {"type": "string"},- "description": "QVeris tool ids from qveris_search.",- },- "search_id": {"type": "string"},- "session_id": {"type": "string"},- },- "required": ["tool_ids"],- }-- def execute(self, **kwargs: Any) -> str:- if not is_qveris_configured():- return _json_response({"ok": False, "error": _unconfigured_message()})- payload = self._client().inspect(- list(kwargs["tool_ids"]),- search_id=kwargs.get("search_id"),- session_id=kwargs.get("session_id"),- )- return _json_response({"ok": True, **payload})---class QVerisExecuteTool(_QVerisBaseTool):- """Execute a selected QVeris capability behind paid-mode budget gates."""-- name = "qveris_execute"- description = (- "Execute a QVeris tool when paid QVeris routing is enabled. Enforces "- "the per-session credit budget before sending a billable request."- )- is_readonly = False- parameters = {- "type": "object",- "properties": {- "tool_id": {"type": "string"},- "parameters": {"type": "object"},- "search_id": {"type": "string"},- "session_id": {"type": "string"},- "model": {"type": "string"},- "max_response_size": {"type": "integer", "default": 20480},- "expected_cost": {- "description": "Optional quote copied from qveris_search/inspect.",- },- "billing_rule": {"type": "object"},- },- "required": ["tool_id", "parameters"],- }-- def _quote(- self, client: QVerisClient, tool_id: str, kwargs: dict[str, Any]- ) -> dict[str, Any]:- """Return the quote the budget reservation is computed from.-- A caller-supplied quote is a hint, never the authority. ``expected_cost``- and ``billing_rule`` are ordinary tool arguments, so they are written by- whatever drives the tool — an LLM on the agent path, an arbitrary client- over MCP. Previously either one short-circuited the server lookup and- was adopted verbatim, so ``expected_cost=0`` reserved nothing and every- call cleared the pre-check regardless of the real price.-- The server is consulted and the reservation takes the LARGER of the two- figures, so an honest caller is unaffected and an understating one- cannot buy a free pass. A non-positive cost is treated as "unknown"- rather than "free" unless the server itself attested it, because a- caller can always write zero.-- Args:- client: Marketplace client used for the authoritative lookup.- tool_id: Capability being priced.- kwargs: Raw tool arguments, possibly carrying a caller quote.-- Returns:- Quote dict whose ``expected_cost`` is the effective figure, plus- ``quote_source`` and ``server_attested`` for the audit trail.- """- supplied = _parse_expected_cost(kwargs.get("expected_cost"))- server_quote: dict[str, Any] = {}- server_cost: float | None = None- try:- inspected = client.inspect(- [tool_id],- search_id=kwargs.get("search_id"),- session_id=kwargs.get("session_id"),- )- except Exception: # noqa: BLE001 - an unreachable marketplace must not- inspected = None # crash the caller; it degrades to the hint below.- if isinstance(inspected, dict):- results = inspected.get("results")- first = results[0] if isinstance(results, list) and results else None- server_quote = _quote_from_tool(first)- server_cost = _parse_expected_cost(server_quote.get("expected_cost"))-- # A marketplace quote that is not a flat per-call price bounds nothing,- # and a caller hint must not stand in for it: a written number would- # then buy a call whose bill the budget cannot cap.- server_unbounded = server_quote.get("expected_cost") is not None and server_cost is None- candidates = [cost for cost in (supplied, server_cost) if cost is not None]- effective = None if server_unbounded else (max(candidates) if candidates else None)-- quote = dict(server_quote)- quote["tool_id"] = tool_id- quote["expected_cost"] = effective- quote["billing_rule"] = server_quote.get("billing_rule") or kwargs.get(- "billing_rule"- )- quote["server_attested"] = server_cost is not None- quote["caller_supplied_cost"] = supplied- if server_unbounded:- quote["quote_source"] = "server_quote_not_per_call"- elif server_cost is not None and supplied is not None and supplied < server_cost:- quote["quote_source"] = "server_overrode_lower_caller_quote"- elif server_cost is not None:- quote["quote_source"] = "server"- elif supplied is not None:- quote["quote_source"] = "caller_hint_unverified"- else:- quote["quote_source"] = "unavailable"- return quote-- def execute(self, **kwargs: Any) -> str:- """Execute a QVeris capability behind the per-session credit budget.-- The request schema is validated FIRST — before the quote lookup, before- the budget reservation, and before ``client.execute`` — because this- tool is not read-only and every call spends real credits. A missing- ``tool_id``/``parameters`` is a schema-invalid request, so it must never- be normalised into an empty-parameter call to the marketplace.- """- cfg = load_qveris_config()- if not is_qveris_configured(cfg):- return _json_response({"ok": False, "error": _unconfigured_message(cfg)})- raw_tool_id = kwargs.get("tool_id")- if not isinstance(raw_tool_id, str) or not raw_tool_id.strip():- return _json_response(- {"ok": False, "error": "tool_id is required (non-empty string)"}- )- if "parameters" not in kwargs or not isinstance(kwargs["parameters"], Mapping):- return _json_response(- {- "ok": False,- "error": "parameters is required and must be an object; refusing a billable call with an unvalidated request",- }- )- try:- max_response_size = _positive_int(- kwargs.get("max_response_size"), "max_response_size", 20480- )- except ValueError as exc:- return _json_response({"ok": False, "error": str(exc)})- parameters = dict(kwargs["parameters"])- client = self._client()- tool_id = raw_tool_id.strip()- quote = self._quote(client, tool_id, kwargs)- session_id = str(kwargs.get("session_id") or "default")- budget = max(float(cfg.budget_credits_per_session), 0.0)- expected = _parse_expected_cost(quote.get("expected_cost"))- with _SESSION_BUDGET_LOCK:- spent = _SESSION_SPEND.get(session_id, 0.0)- reserved = _SESSION_RESERVED.get(session_id, 0.0)- # A zero reservation is only trustworthy when the marketplace itself- # quoted it. A caller can always write zero, and that used to clear- # the pre-check while reserving nothing.- valid_quote = (- expected is not None- and math.isfinite(expected)- and (expected > 0.0 or (expected == 0.0 and quote.get("server_attested")))- )- if expected is None and (- quote.get("quote_source") == "server_quote_not_per_call"- or kwargs.get("expected_cost") is not None- ):- return _json_response(- {- "ok": False,- "status": "quote_not_bounded",- "error": "the quote is not a flat price per call, so the "- "session credit budget cannot bound this call's bill (#1494)",- "budget_credits_per_session": budget,- "quote": quote,- }- )- if (- not valid_quote- or spent >= budget- or spent + reserved + expected > budget- ):- return _json_response(- {- "ok": False,- "status": "budget_exceeded",- "spent_credits": spent,- "budget_credits_per_session": budget,- "quote": quote,- }- )- _SESSION_RESERVED[session_id] = reserved + expected-- try:- payload = client.execute(- tool_id,- parameters=parameters,- search_id=kwargs.get("search_id"),- session_id=kwargs.get("session_id"),- model=kwargs.get("model"),- max_response_size=max_response_size,- )- except Exception:- with _SESSION_BUDGET_LOCK:- remaining = _SESSION_RESERVED.get(session_id, 0.0) - expected- if remaining > 1e-12:- _SESSION_RESERVED[session_id] = remaining- else:- _SESSION_RESERVED.pop(session_id, None)- raise-- try:- cost = float(payload.get("cost"))- except (TypeError, ValueError):- cost = expected- if not math.isfinite(cost) or cost < 0.0:- cost = expected-- with _SESSION_BUDGET_LOCK:- remaining = _SESSION_RESERVED.get(session_id, 0.0) - expected- if remaining > 1e-12:- _SESSION_RESERVED[session_id] = remaining- else:- _SESSION_RESERVED.pop(session_id, None)- _SESSION_SPEND[session_id] = _SESSION_SPEND.get(session_id, 0.0) + cost- session_spent = _SESSION_SPEND[session_id]-- payload["cost"] = cost- payload["remaining_credits"] = payload.get("remaining_credits")- payload["session_spent_credits"] = session_spent- return _json_response({"ok": True, **payload})diff --git a/agent/tests/conftest.py b/agent/tests/conftest.pyindex 55916f6f9..7e67674b7 100644--- a/agent/tests/conftest.py+++ b/agent/tests/conftest.py@@ -28,7 +28,6 @@ if str(AGENT_DIR) not in sys.path:# i.e. during collection): loop.RUNS_DIR/SESSIONS_DIR, goal/session# _DB_PATH, helpers.ENV_PATH, memory MEMORY_BASE, skills USER_SKILLS_DIR,# strategy_store _DEFAULT_DB_PATH, swarm presets USER_PRESETS_DIR,-# qveris QVERIS_CONFIG_PATH.# * Runtime Path.home() call sites: redaction's internal-root anchors# (_internal_roots_for_cwd), alpha_bench report output (_default_output_dir),# autopilot run dirs, uploads shadow_reports.diff --git a/agent/tests/test_cli_data.py b/agent/tests/test_cli_data.pyindex d67f5d7dd..4c34d326a 100644--- a/agent/tests/test_cli_data.py+++ b/agent/tests/test_cli_data.py@@ -1,44 +1,9 @@-from __future__ import annotations--import pytest-from cli import _legacy-def test_data_parser_accepts_status_mode_and_usage() -> None:+def test_data_parser_accepts_status() -> None:parser = _legacy._build_parser()status = parser.parse_args(["data", "status"])assert status.command == "data"assert status.data_command == "status"-- free = parser.parse_args(["data", "mode", "free"])- assert free.command == "data"- assert free.data_command == "mode"- assert free.mode == "free"-- paid = parser.parse_args([- "data",- "mode",- "paid",- "--budget",- "30",- "--key",- "sk-test",- "--url",- "https://qveris.test/api/v1",- ])- assert paid.mode == "paid"- assert paid.budget == 30- assert paid.key == "sk-test"- assert paid.url == "https://qveris.test/api/v1"-- usage = parser.parse_args(["data", "usage"])- assert usage.data_command == "usage"---def test_qveris_is_not_a_top_level_user_command() -> None:- parser = _legacy._build_parser()-- with pytest.raises(SystemExit):- parser.parse_args(["qveris", "status"])diff --git a/agent/tests/test_correlation.py b/agent/tests/test_correlation.pyindex 3fd6bf6d8..7b8ab464c 100644--- a/agent/tests/test_correlation.py+++ b/agent/tests/test_correlation.py@@ -70,7 +70,7 @@ class TestInferMarket:# underlying asset is XAU / XAG / XPT / XPD (ISO 4217 metals); the# quote is USD. Engines (ForexEngine._METAL_SPECS) already handle the# correct pip / lot conventions; the classifier just has to land on- # ``forex`` so the forex fallback chain (mt5, tickerall, qveris,+ # ``forex`` so the forex fallback chain (mt5, tickerall,# yfinance) is engaged instead of the a_share chain.assert infer_market("XAUUSD") == "forex"assert infer_market("XAGUSD") == "forex"diff --git a/agent/tests/test_fund_nav_tool.py b/agent/tests/test_fund_nav_tool.pyindex 8c13a825d..7c6d54076 100644--- a/agent/tests/test_fund_nav_tool.py+++ b/agent/tests/test_fund_nav_tool.py@@ -11,10 +11,17 @@ from __future__ import annotationsimport jsonfrom typing import Any+import pytest+from src.tools import fund_nav_tool as fntfrom src.tools.fund_nav_tool import GildataFundNavTool[email protected](autouse=True)+def enable_test_features(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "fund_nav")++def _mcp_text(payload: dict[str, Any]) -> str:return json.dumps(payload, ensure_ascii=False)@@ -48,7 +55,7 @@ _NAV_ROWS = [class TestAvailability:- """check_available reflects only GILDATA_TOKEN."""+ """A selected NAV feature also requires a token."""def test_unavailable_without_token(self, monkeypatch):monkeypatch.delenv("GILDATA_TOKEN", raising=False)diff --git a/agent/tests/test_gildata_boundaries.py b/agent/tests/test_gildata_boundaries.pyindex 8c8e5cfe4..c800cc2b0 100644--- a/agent/tests/test_gildata_boundaries.py+++ b/agent/tests/test_gildata_boundaries.py@@ -60,6 +60,7 @@ def test_research_caps_whole_records_and_reports_omission():def test_nav_budget_keeps_complete_recent_records(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "fund_nav")monkeypatch.setenv("GILDATA_TOKEN", "test-token")monkeypatch.setattr(GildataFundNavTool, "_fetch_one", lambda *args: {"ok": True, "fund_name": "Fund", "rows": [{"date": f"row-{i}", "unit_nav": 1.12, "adjusted_nav": 2.34} for i in range(2000)], "count": 2000, "returned_by_vendor": 2000})text = GildataFundNavTool().execute(funds=["110022"])@@ -71,6 +72,7 @@ def test_nav_budget_keeps_complete_recent_records(monkeypatch):@pytest.mark.parametrize("window", [{"start_date": "yesterday"}, {"start_date": "2026-10-13", "end_date": "2026-10-12"}])def test_invalid_nav_window_fails_before_vendor_call(monkeypatch, window):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "fund_nav")monkeypatch.setenv("GILDATA_TOKEN", "test-token")monkeypatch.setattr(GildataFundNavTool, "_fetch_one", lambda *args: pytest.fail("invalid window reached vendor"))assert json.loads(GildataFundNavTool().execute(funds=["110022"], **window))["ok"] is False@@ -87,3 +89,41 @@ def test_macro_observations_ground_with_explicit_refs_without_widening_price_gatreturn ledger.validate_final_answer(f"Observed growth: {value}%.\n```figures\n{value}% | observed | Growth | macro_call::rows[0].value\n```")assert check("5.4").validassert not check("6.4").valid+++def test_old_token_and_individual_opt_ins_across_agent_and_mcp(monkeypatch):+ import asyncio++ import mcp_server+ from src.config.accessor import reset_env_config+ from src.tools import build_registry, gildata_research_tools++ features = {+ "fund_nav": ("get_fund_nav", {"funds": ["110022"]}),+ "macro_series": ("get_cn_macro_series", {"query": "GDP"}),+ "announcements": ("get_cn_announcements", {"query": "dividend"}),+ "broker_reports": ("search_broker_reports", {"query": "earnings"}),+ }++ def unexpected(*args, **kwargs):+ pytest.fail("Disabled feature reached vendor lookup")++ monkeypatch.setattr(GildataFundNavTool, "_fetch_one", unexpected)+ monkeypatch.setattr(gildata_research_tools, "call_srv_tool", unexpected)+ monkeypatch.setenv("GILDATA_TOKEN", "existing-token")+ key = "VIBE_TRADING_GILDATA_FEATURES"+ monkeypatch.setenv(key, ",".join(features))+ reset_env_config()+ retained = build_registry()+ assert all(retained.get(name) for name, _ in features.values())+ monkeypatch.setattr(mcp_server, "_registry", retained)+ for selected in ["", *features]:+ monkeypatch.setenv(key, selected)+ reset_env_config() # Settings PUT also refreshes the process config.+ fresh = build_registry()+ for feature, (name, params) in features.items():+ assert (fresh.get(name) is not None) == (feature == selected)+ if feature != selected:+ assert json.loads(retained.execute(name, params))["ok"] is False+ reply = asyncio.run(mcp_server.mcp.call_tool(name, params))+ assert json.loads(reply.content[0].text)["ok"] is Falsediff --git a/agent/tests/test_gildata_fin_query.py b/agent/tests/test_gildata_fin_query.pyindex 627ba3bdf..217b220fc 100644--- a/agent/tests/test_gildata_fin_query.py+++ b/agent/tests/test_gildata_fin_query.py@@ -24,6 +24,7 @@ def tables():@pytest.fixturedef vendor(monkeypatch, tables):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "fin_query")monkeypatch.setenv("GILDATA_TOKEN", "test-token")with patch.object(fq, "call_srv_tool_results", return_value=tables) as call:yield call@@ -166,6 +167,7 @@ def test_optional_tool_is_discovered(monkeypatch):def test_shared_transport_preserves_results_and_old_flattening(monkeypatch, tables):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "fin_query")monkeypatch.setenv("GILDATA_TOKEN", "test-token")raw = {"result": {"content": [{"type": "text", "text": json.dumps({"code": 0, "results": tables})}]}}with patch.object(gildata_srv, "throttled_post_json", return_value=raw) as post:diff --git a/agent/tests/test_gildata_identity.py b/agent/tests/test_gildata_identity.pyindex 6f170ad97..7d28b226e 100644--- a/agent/tests/test_gildata_identity.py+++ b/agent/tests/test_gildata_identity.py@@ -11,6 +11,7 @@ from src.tools import symbol_search_tool as ss@pytest.fixturedef recall(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "symbol_search")monkeypatch.setenv("GILDATA_TOKEN", "test-token")fn = Mock(return_value=[{"api_name": "StockDailyQuote", "candidates": [diff --git a/agent/tests/test_gildata_loader.py b/agent/tests/test_gildata_loader.pyindex 7e2df0465..c36e83894 100644--- a/agent/tests/test_gildata_loader.py+++ b/agent/tests/test_gildata_loader.py@@ -43,6 +43,11 @@ def _envelope(rows, *, inner_code=0):return {"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": json.dumps(inner)}]}}[email protected](autouse=True)+def enable_quotes(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "market_quotes")++class TestRegistration:"""Loader self-registers with the expected metadata."""@@ -64,7 +69,14 @@ class TestRegistration:class TestIsAvailable:- """Availability is gated purely on GILDATA_TOKEN presence."""+ """Market quotes require both a token and their own opt-in."""++ def test_saved_token_and_other_features_do_not_enable_quotes(self, monkeypatch):+ monkeypatch.setenv("GILDATA_TOKEN", "secret")+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "fin_query,stock_selection,symbol_search,shannon")+ monkeypatch.setattr(gl, "throttled_post_json", lambda *a, **kw: pytest.fail("unexpected vendor call"))+ assert not DataLoader().is_available()+ assert DataLoader().fetch(["600519.SH"], "2024-01-01", "2024-01-04") == {}def test_available_with_token(self, monkeypatch):monkeypatch.setenv("GILDATA_TOKEN", "secret")diff --git a/agent/tests/test_gildata_research_tools.py b/agent/tests/test_gildata_research_tools.pyindex 20946355a..080926bbf 100644--- a/agent/tests/test_gildata_research_tools.py+++ b/agent/tests/test_gildata_research_tools.py@@ -8,7 +8,7 @@ from __future__ import annotationsimport json-+import pytestfrom src.tools import gildata_research_tools as grtfrom src.tools.gildata_research_tools import (@@ -20,8 +20,13 @@ from src.tools.gildata_research_tools import (TOOLS = [GetCnMacroSeriesTool, GetCnAnnouncementsTool, SearchBrokerReportsTool][email protected](autouse=True)+def enable_test_features(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "macro_series,announcements,broker_reports")++class TestAvailabilityAndMetadata:- """All three wrappers gate on GILDATA_TOKEN and share plumbing."""+ """Selected features also require a token."""def test_unavailable_without_token(self, monkeypatch):monkeypatch.delenv("GILDATA_TOKEN", raising=False)diff --git a/agent/tests/test_gildata_stock_selection.py b/agent/tests/test_gildata_stock_selection.pyindex eec8e35db..26258fa7c 100644--- a/agent/tests/test_gildata_stock_selection.py+++ b/agent/tests/test_gildata_stock_selection.py@@ -12,6 +12,7 @@ from src.tools import gildata_srv@pytest.fixturedef vendor(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "stock_selection")monkeypatch.setenv("GILDATA_TOKEN", "test-token")call = Mock(return_value=[{"api_name": "智能选股",diff --git a/agent/tests/test_loader_contract.py b/agent/tests/test_loader_contract.pyindex 64bf0d6b7..3e65e9373 100644--- a/agent/tests/test_loader_contract.py+++ b/agent/tests/test_loader_contract.py@@ -34,7 +34,6 @@ CONTRACT_SUITES = {"nobitex": "test_nobitex_loader.py","okx": "test_okx_loader_bounded.py","pykrx": "test_pykrx_loader.py",- "qveris": "test_qveris_loader.py","sina": "test_sina_loader.py","stooq": "test_stooq_loader.py","tencent": "test_tencent_loader.py",diff --git a/agent/tests/test_local_source_routing.py b/agent/tests/test_local_source_routing.pyindex 43a33e5ae..c84546766 100644--- a/agent/tests/test_local_source_routing.py+++ b/agent/tests/test_local_source_routing.py@@ -233,7 +233,7 @@ class TestNoNetworkFallbackIsPerSymbolToo:# Every member of the set is pinned, not only ``local``: with the guard# narrowed to ``primary_source != "local"`` the suite stayed green while- # qveris / fmp / tickerall / nobitex / wallex kept filling gaps from the+ # fmp / tickerall / nobitex / wallex kept filling gaps from the# network. A source added to the set later is covered the moment it lands.@pytest.mark.parametrize("source", sorted(_NO_NETWORK_FALLBACK_SOURCES))def test_missing_symbol_raises_instead_of_reaching_the_network(diff --git a/agent/tests/test_market_data.py b/agent/tests/test_market_data.pyindex af82fb8c5..267bbbda0 100644--- a/agent/tests/test_market_data.py+++ b/agent/tests/test_market_data.py@@ -865,3 +865,27 @@ def test_fetch_auto_full_batch_never_touches_the_next_source() -> None:)assert stooq_calls == []assert "AAPL.US" in out and "NVDA.US" in out+[email protected]("symbol", ["600519.SH", "00700.HK", "000300.SH"])+def test_missing_market_quotes_never_cross_the_gildata_boundary(symbol, monkeypatch):+ from backtest.loaders.base import NoAvailableSourceError++ monkeypatch.setenv("GILDATA_TOKEN", "existing-token")+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "market_quotes")+ attempts = []++ def unavailable(name):+ attempts.append(name)+ raise NoAvailableSourceError(name)++ def query(source):+ return fetch_market_data(+ codes=[symbol], source=source, start_date="2024-01-01",+ end_date="2024-01-05", loader_resolver=unavailable, max_fallback_attempts=100,+ )++ assert query("auto")["_unresolved"] == [symbol]+ assert attempts and "gildata" not in attempts+ attempts.clear()+ assert query("gildata")["_unresolved"] == [symbol]+ assert attempts == ["gildata"]diff --git a/agent/tests/test_market_data_tool.py b/agent/tests/test_market_data_tool.pyindex 1cd0dccfc..5f02bbbe0 100644--- a/agent/tests/test_market_data_tool.py+++ b/agent/tests/test_market_data_tool.py@@ -375,7 +375,7 @@ def test_market_data_tool_accepts_every_registered_source():"""Every source in the loader registry must pass MarketDataTool validation.Regression (#1185): the source allow-list was a hardcoded subset that- rejected registered, documented sources (binance, local, futu, qveris,+ rejected registered, documented sources (binance, local, futu,india_broker, tickerall). The tool's enum must match VALID_SOURCES so thetool can never silently drop a loader the registry serves."""diff --git a/agent/tests/test_metrics.py b/agent/tests/test_metrics.pyindex 0bd0c1596..9be9d8649 100644--- a/agent/tests/test_metrics.py+++ b/agent/tests/test_metrics.py@@ -98,10 +98,6 @@ class TestBarsPerYear:# ── newly covered sources (#884) ──# resampling sources (local files / paid data, default to US equity session)- def test_resampling_qveris(self) -> None:- assert calc_bars_per_year("1D", "qveris") == 252- assert calc_bars_per_year("1m", "qveris") == 252 * 390- assert calc_bars_per_year("1H", "qveris") == 252 * 7def test_resampling_local(self) -> None:assert calc_bars_per_year("1D", "local") == 252diff --git a/agent/tests/test_offline_benchmark.py b/agent/tests/test_offline_benchmark.pyindex a81c95470..814cd9a22 100644--- a/agent/tests/test_offline_benchmark.py+++ b/agent/tests/test_offline_benchmark.py@@ -186,7 +186,7 @@ def test_inner_loader_frames_are_sanitised_like_the_snapshot() -> None:assert list(served[_BENCH].index) == [d for i, d in enumerate(_DATES) if i != 2][email protected]("source", ["local", "qveris", "tickerall", "fmp", "nobitex", "wallex"])[email protected]("source", ["local", "tickerall", "fmp", "nobitex", "wallex"])@pytest.mark.parametrize("loader_name", ["same", "yahoo"])def test_source_bound_benchmark_never_switches_provider(monkeypatch, source, loader_name):from backtest.benchmark import resolve_benchmarkdiff --git a/agent/tests/test_qveris_loader.py b/agent/tests/test_qveris_loader.pydeleted file mode 100644index 55e6a9715..000000000--- a/agent/tests/test_qveris_loader.py+++ /dev/null@@ -1,831 +0,0 @@-"""Tests for qveris_loader: config gating, mocked HTTP fetches, and registry safety.--All QVeris calls are mocked by replacing ``requests.Session`` inside the loader-module. No test reaches the live QVeris API or a signed full-content URL.-"""--from __future__ import annotations--import json-from typing import Any--import pandas as pd-import pytest--from backtest.loaders import qveris_loader as qv-from tests.loader_contract import assert_loader_contract-from backtest.loaders.base import NoAvailableSourceError-from backtest.loaders.registry import (- FALLBACK_CHAINS,- LOADER_REGISTRY,- get_loader_cls_with_fallback,-)---class _FakeResponse:- """Small response stub for the loader's embedded HTTP client."""-- def __init__(- self,- payload: Any,- *,- status_code: int = 200,- headers: dict[str, str] | None = None,- text: str | None = None,- ) -> None:- self._payload = payload- self.status_code = status_code- self.headers = headers or {}- self.text = text if text is not None else json.dumps(payload)-- def json(self) -> Any:- return self._payload-- def raise_for_status(self) -> None:- if self.status_code >= 400:- raise RuntimeError(f"HTTP {self.status_code}")---class _FakeSession:- """Queue-backed fake requests session."""-- def __init__(self, responses: list[_FakeResponse]) -> None:- self.responses = responses- self.calls: list[dict[str, Any]] = []-- def request(self, method: str, url: str, **kwargs: Any) -> _FakeResponse:- self.calls.append({"method": method, "url": url, "kwargs": kwargs})- assert self.responses, f"unexpected HTTP call: {method} {url}"- return self.responses.pop(0)--[email protected](autouse=True)-def _isolated_qveris_config(monkeypatch, tmp_path):- """Default every test to disabled QVeris with no cache or request sleep."""- monkeypatch.setattr(qv, "_CONFIG_PATH", tmp_path / "qveris.json")- monkeypatch.delenv("QVERIS_API_KEY", raising=False)- monkeypatch.delenv("QVERIS_BASE_URL", raising=False)- monkeypatch.setenv("VIBE_TRADING_DATA_CACHE", "0")- monkeypatch.setenv("VIBE_TRADING_QVERIS_MIN_INTERVAL", "0")---def _write_config(- path,- *,- enabled: bool = True,- api_key: str = "sk_test",- mode: str = "paid",- budget: float = 50.0,-) -> None:- path.write_text(- json.dumps(- {- "enabled": enabled,- "base_url": "https://qveris.test/api/v1",- "api_key": api_key,- "mode": mode,- "budget_credits_per_session": budget,- }- ),- encoding="utf-8",- )---def _capability(- tool_id: str = "tool_good",- *,- success_rate: float = 0.99,- expected_cost: str = "1.0 credits",-) -> dict[str, Any]:- return {- "tool_id": tool_id,- "name": "Daily OHLCV candles",- "description": "Historical open high low close volume by ticker symbol",- "expected_cost": expected_cost,- "stats": {"success_rate": success_rate},- "params": [- {"name": "symbol", "type": "string", "required": True},- {"name": "start_date", "type": "string", "required": True},- {"name": "end_date", "type": "string", "required": True},- {"name": "interval", "type": "string", "enum": ["daily", "1D"]},- ],- "examples": {"sample_parameters": {"adjusted": True}},- }---def _install_session(monkeypatch, responses: list[_FakeResponse]) -> _FakeSession:- session = _FakeSession(responses)- monkeypatch.setattr(qv.requests, "Session", lambda: session)- return session---class TestAvailability:- """Config and env override gating."""-- def test_missing_config_is_unavailable(self):- assert qv.DataLoader().is_available() is False-- def test_disabled_config_stays_unavailable_even_with_env_key(self, monkeypatch):- _write_config(qv._CONFIG_PATH, enabled=False, api_key="")- monkeypatch.setenv("QVERIS_API_KEY", "sk_env")- assert qv.DataLoader().is_available() is False-- def test_enabled_config_with_key_is_available(self):- _write_config(qv._CONFIG_PATH, enabled=True, api_key="sk_file")- assert qv.DataLoader().is_available() is True-- def test_env_key_overrides_empty_file_key(self, monkeypatch):- _write_config(qv._CONFIG_PATH, enabled=True, api_key="")- monkeypatch.setenv("QVERIS_API_KEY", "sk_env")- assert qv.DataLoader().is_available() is True-- def test_metadata(self):- assert qv.DataLoader.name == "qveris"- assert qv.DataLoader.requires_auth is True---class TestFetch:- """fetch() search-selects, executes, normalizes, and isolates empty symbols."""-- def test_returns_empty_without_availability_and_makes_no_http(self, monkeypatch):- session = _install_session(monkeypatch, [])- assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}- assert session.calls == []-- def test_free_mode_keeps_qveris_loader_unavailable(self, monkeypatch):- _write_config(qv._CONFIG_PATH, enabled=True, api_key="sk_test", mode="free")- session = _install_session(monkeypatch, [])-- assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}- assert session.calls == []-- def test_zero_budget_allows_search_but_blocks_paid_execute(self, monkeypatch):- _write_config(qv._CONFIG_PATH, budget=0.0)- session = _install_session(- monkeypatch,- [_FakeResponse({"search_id": "s_1", "results": [_capability()]})],- )-- result = qv.DataLoader().fetch(- ["BTC-USDT"], "2024-01-01", "2024-01-31"- )-- assert result == {}- assert len(session.calls) == 1- assert session.calls[0]["url"].endswith("/search")-- def test_budget_is_shared_across_symbols_in_one_fetch(self, monkeypatch):- _write_config(qv._CONFIG_PATH, budget=1.0)- rows = {- "data": [- {- "date": "2024-01-02",- "open": 100,- "high": 101,- "low": 99,- "close": 100,- "volume": 10,- }- ]- }- session = _install_session(- monkeypatch,- [- _FakeResponse({"search_id": "s_1", "results": [_capability()]}),- _FakeResponse({"success": True, "cost": 1.0, "result": rows}),- _FakeResponse({"search_id": "s_2", "results": [_capability()]}),- ],- )-- result = qv.DataLoader().fetch(- ["BTC-USDT", "ETH-USDT"], "2024-01-01", "2024-01-31"- )-- assert list(result) == ["BTC-USDT"]- execute_calls = [call for call in session.calls if "/tools/execute" in call["url"]]- assert len(execute_calls) == 1-- def test_search_execute_happy_path_selects_best_capability(self, monkeypatch):- _write_config(qv._CONFIG_PATH)- session = _install_session(- monkeypatch,- [- _FakeResponse(- {- "search_id": "s_123",- "results": [- _capability("expensive", success_rate=0.99, expected_cost="5 credits"),- _capability("cheap", success_rate=0.99, expected_cost="1 credits"),- _capability("weaker", success_rate=0.5, expected_cost="0.1 credits"),- ],- }- ),- _FakeResponse(- {- "success": True,- "result": {- "data": [- {- "date": "2024-01-02",- "open": "100",- "high": "112",- "low": "99",- "close": "110",- "volume": "1000",- }- ]- },- }- ),- ],- )-- out = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")-- assert list(out) == ["BTC-USDT"]- df = out["BTC-USDT"]- assert list(df.columns) == ["open", "high", "low", "close", "volume"]- assert df.index.name == "trade_date"- assert_loader_contract(df, context="canonical frame")- assert isinstance(df.index, pd.DatetimeIndex)- assert df.index.dtype == "datetime64[ns]"- assert df.loc["2024-01-02", "close"] == 110.0- assert df.loc["2024-01-02", "volume"] == 1000.0-- assert session.calls[0]["url"] == "https://qveris.test/api/v1/search"- assert session.calls[0]["kwargs"]["json"]["limit"] == 20- assert session.calls[1]["url"].endswith("/tools/execute?tool_id=cheap")- execute_body = session.calls[1]["kwargs"]["json"]- assert execute_body["search_id"] == "s_123"- assert execute_body["parameters"]["symbol"] == "BTC-USDT"- assert execute_body["parameters"]["start_date"] == "2024-01-01"- assert execute_body["parameters"]["end_date"] == "2024-01-31"- assert execute_body["parameters"]["adjusted"] is True-- def test_truncated_result_download_path(self, monkeypatch):- _write_config(qv._CONFIG_PATH)- session = _install_session(- monkeypatch,- [- _FakeResponse({"search_id": "s_1", "results": [_capability()]}),- _FakeResponse(- {- "success": True,- "result": {- "message": "too long",- "full_content_file_url": "https://oss.qveris.cn/full.json",- "truncated_content": "[]",- },- }- ),- _FakeResponse(- [- {- "date": "2024-01-02",- "open": 10,- "high": 12,- "low": 9,- "close": 11,- }- ]- ),- ],- )-- out = qv.DataLoader().fetch(["ETH-USDT"], "2024-01-01", "2024-01-31")-- assert list(out) == ["ETH-USDT"]- assert pd.isna(out["ETH-USDT"].loc["2024-01-02", "volume"])- assert session.calls[2]["method"] == "get"- assert session.calls[2]["url"] == "https://oss.qveris.cn/full.json"- assert "Authorization" not in session.calls[2]["kwargs"]["headers"]-- def test_search_no_ohlcv_result_omits_symbol(self, monkeypatch):- _write_config(qv._CONFIG_PATH)- session = _install_session(- monkeypatch,- [- _FakeResponse(- {- "search_id": "s_1",- "results": [- {- "tool_id": "news",- "name": "Company news",- "description": "Headlines by ticker symbol",- "expected_cost": "1",- "stats": {"success_rate": 1},- }- ],- }- )- ],- )-- assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}- assert len(session.calls) == 1-- def test_date_filtering_and_ohlc_validation(self, monkeypatch):- _write_config(qv._CONFIG_PATH)- session = _install_session(- monkeypatch,- [- _FakeResponse({"search_id": "s_1", "results": [_capability()]}),- _FakeResponse(- {- "success": True,- "result": {- "historical": [- {"date": "2023-12-29", "open": 1, "high": 1, "low": 1, "close": 1},- {"date": "2024-01-02", "open": 2, "high": 3, "low": 1, "close": 2.5},- {"date": "2024-01-03", "open": 5, "high": 4, "low": 1, "close": 4},- {"date": "2024-02-01", "open": 6, "high": 6, "low": 6, "close": 6},- ]- },- }- ),- ],- )-- df = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")["BTC-USDT"]-- assert [d.strftime("%Y-%m-%d") for d in df.index] == ["2024-01-02"]- assert df.loc["2024-01-02", "open"] == 2.0- assert len(session.calls) == 2-- def test_invalid_date_range_raises(self):- _write_config(qv._CONFIG_PATH)- with pytest.raises(ValueError):- qv.DataLoader().fetch(["BTC-USDT"], "2024-02-01", "2024-01-01")---class TestParameterMapping:- def test_does_not_treat_indicators_as_end_date(self):- capability = {- "params": [- {"name": "startdate", "type": "string"},- {"name": "enddate", "type": "string"},- {"name": "interval", "type": "string", "enum": ["D", "daily"]},- {"name": "cps", "type": "string"},- {"name": "indicators", "type": "string"},- {"name": "metadata_to", "type": "string"},- ],- "examples": {- "sample_parameters": {- "cps": "1",- "indicators": "close",- "metadata_to": "raw",- }- },- }-- parameters = qv._build_parameters(- capability,- "600519.SH",- "2019-01-02",- "2019-12-31",- "1D",- )-- assert parameters["startdate"] == "2019-01-02"- assert parameters["enddate"] == "2019-12-31"- assert parameters["interval"] == "D"- assert parameters["cps"] == "1"- assert parameters["indicators"] == "close"- assert parameters["metadata_to"] == "raw"---class TestHttpClient:- """429 backoff is local and mockable."""-- def test_429_retries_after_header(self, monkeypatch):- _write_config(qv._CONFIG_PATH)- session = _install_session(- monkeypatch,- [- _FakeResponse({}, status_code=429, headers={"Retry-After": "0"}),- _FakeResponse({"search_id": "s_1", "results": []}),- ],- )-- payload = qv.QVerisClient(qv._load_config()).search("daily OHLCV AAPL")-- assert payload == {"search_id": "s_1", "results": []}- assert len(session.calls) == 2---class TestCapabilitySelection:- """Granularity filtering and multi-candidate fallback (live-e2e regressions)."""-- def test_daily_request_excludes_monthly_and_intraday_series(self, monkeypatch):- """A monthly series with perfect stats must lose to a daily one."""- _write_config(qv._CONFIG_PATH)- monthly = _capability("alphavantage.time_series.monthly_adjusted.v1", success_rate=1.0)- monthly["name"] = "Monthly Adjusted Time Series"- intraday = _capability("alphavantage.time-series.intraday.v1", success_rate=1.0)- intraday["description"] = "Intraday open high low close by ticker symbol"- daily = _capability("tiingo.core.eod.v1", success_rate=0.5)- session = _install_session(- monkeypatch,- [- _FakeResponse(- {"search_id": "s_1", "results": [monthly, intraday, daily]}- ),- _FakeResponse(- {- "success": True,- "result": {- "data": [- {- "date": "2024-01-02",- "open": 1,- "high": 2,- "low": 0.5,- "close": 1.5,- "volume": 10,- }- ]- },- }- ),- ],- )-- data = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")-- assert "BTC-USDT" in data- execute_url = session.calls[1]["url"]- assert "tiingo.core.eod.v1" in execute_url-- def test_falls_back_to_second_candidate_when_first_result_unparseable(self, monkeypatch):- """An unparseable paid result must not silently drop the symbol."""- _write_config(qv._CONFIG_PATH)- first = _capability("daily_bad", success_rate=0.99)- second = _capability("daily_good", success_rate=0.90)- session = _install_session(- monkeypatch,- [- _FakeResponse({"search_id": "s_1", "results": [first, second]}),- _FakeResponse({"success": True, "result": {"unexpected": "shape"}}),- _FakeResponse(- {- "success": True,- "result": {- "data": [- {- "date": "2024-01-02",- "open": 1,- "high": 2,- "low": 0.5,- "close": 1.5,- "volume": 10,- }- ]- },- }- ),- ],- )-- data = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")-- assert "BTC-USDT" in data- assert "daily_bad" in session.calls[1]["url"]- assert "daily_good" in session.calls[2]["url"]-- def test_parses_provider_named_series_container(self, monkeypatch):- """AlphaVantage-style '<X> Time Series' containers must parse."""- _write_config(qv._CONFIG_PATH)- session = _install_session(- monkeypatch,- [- _FakeResponse({"search_id": "s_1", "results": [_capability()]}),- _FakeResponse(- {- "success": True,- "result": {- "Meta Data": {"1. Information": "Daily Prices"},- "Time Series (Daily Adjusted)": {- "2024-01-02": {- "1. open": "1.0",- "2. high": "2.0",- "3. low": "0.5",- "4. close": "1.5",- "5. volume": "10",- }- },- },- }- ),- ],- )-- data = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")-- assert "BTC-USDT" in data- assert float(data["BTC-USDT"]["close"].iloc[0]) == 1.5- assert len(session.calls) == 2---def test_auto_fallback_chains_do_not_contain_qveris():- """QVeris is explicit-only and must never be selected by source='auto'."""- assert "qveris" in LOADER_REGISTRY- assert all("qveris" not in chain for chain in FALLBACK_CHAINS.values())---def test_explicit_unavailable_qveris_does_not_fallback_to_network():- """An unavailable explicit qveris source raises instead of falling back."""- with pytest.raises(NoAvailableSourceError) as excinfo:- get_loader_cls_with_fallback("qveris")- assert "qveris" in str(excinfo.value).lower()---def test_adjusted_only_records_become_bars():- """A capability publishing only ``adj_*`` fields must still yield bars.-- ``qveris_finance.mkt_bars_adjusted`` returns ``adj_open``/``adj_high``/- ``adj_low``/``adj_close`` plus ``adj_factor`` and no unadjusted price- fields, so every row failed the OHLC check and a billed call produced "no- parseable bars" (#1494).- """- result = {- "data": [- {- "date": "2024-01-02",- "adj_open": 1.0,- "adj_high": 1.2,- "adj_low": 0.9,- "adj_close": 1.1,- "adj_volume": 100,- "adj_factor": 1.0,- },- {- "date": "2024-01-03",- "adj_open": 1.1,- "adj_high": 1.3,- "adj_low": 1.0,- "adj_close": 1.25,- "adj_volume": 120,- "adj_factor": 1.0,- },- ]- }-- frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")-- assert frame is not None- assert list(frame["close"]) == pytest.approx([1.1, 1.25])- assert list(frame["volume"]) == pytest.approx([100.0, 120.0])---def test_a_bar_never_mixes_unadjusted_and_adjusted_levels():- """Unadjusted open/high/low with only ``adj_close`` is not a bar.-- Accepting that record assembles raw price levels against an adjusted close- in a single bar, silently, under whatever caliber the source declares- (#1494).- """- result = {- "data": [- {- "date": "2024-01-02",- "open": 1.0,- "high": 1.2,- "low": 0.9,- "adj_close": 1.1,- }- ]- }-- assert qv._result_to_frame(result, "2024-01-01", "2024-01-05") is None---def test_unadjusted_fields_win_when_both_sets_are_present():- """A record carrying both sets keeps resolving to the unadjusted quartet."""- result = {- "data": [- {- "date": "2024-01-02",- "open": 1.0,- "high": 1.2,- "low": 0.9,- "close": 1.1,- "adj_open": 10.0,- "adj_high": 12.0,- "adj_low": 9.0,- "adj_close": 11.0,- }- ]- }-- frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")-- assert frame is not None- assert float(frame["close"].iloc[0]) == pytest.approx(1.1)--[email protected]("volume_key", ["volume", "vol", "v", "5. volume", "6. volume"])-def test_adjusted_bars_keep_volume_under_a_plain_volume_key(volume_key):- """Volume is not a price level, so an adjusted bar keeps a plain volume.-- Splitting the alias tables on price *levels* made the table a unit for every- column, so an adjusted-price record naming its volume ``volume`` — the most- natural key, and ``6. volume`` is how Alpha Vantage labels its adjusted- series — resolved a complete price quartet and then silently reported a NaN- volume. ``_result_to_frame`` only drops NaN price rows, so the NaN reached- the frame and the loader cache.- """- result = {- "data": [- {- "date": "2024-01-02",- "adj_open": 1.0,- "adj_high": 1.2,- "adj_low": 0.9,- "adj_close": 1.1,- volume_key: 100,- }- ]- }-- frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")-- assert frame is not None- assert float(frame["volume"].iloc[0]) == pytest.approx(100.0)---def test_adjusted_volume_wins_over_a_plain_volume_key():- """When the adjusted family names its own volume, that one still wins."""- result = {- "data": [- {- "date": "2024-01-02",- "adj_open": 1.0,- "adj_high": 1.2,- "adj_low": 0.9,- "adj_close": 1.1,- "adj_volume": 200,- "volume": 100,- }- ]- }-- frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")-- assert frame is not None- assert float(frame["volume"].iloc[0]) == pytest.approx(200.0)--def test_an_unadjusted_bar_does_not_take_the_adjusted_volume():- """Split-adjusted volume is not on the scale of unadjusted prices.-- With both price families present and only ``adj_volume`` named, the- unadjusted quartet wins (the documented preference) and its volume stays- NaN instead of borrowing the adjusted family's (#1527 follow-up).- """- result = {- "data": [- {- "date": "2024-01-02",- "open": 1.0,- "high": 1.2,- "low": 0.9,- "close": 1.1,- "adj_open": 2.0,- "adj_high": 2.2,- "adj_low": 1.9,- "adj_close": 2.1,- "adj_volume": 200,- }- ]- }-- frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")-- assert frame is not None- assert float(frame["close"].iloc[0]) == pytest.approx(1.1)- assert frame["volume"].isna().all()---def test_a_response_mixing_families_yields_no_bars():- """Per-record choice built one series from an unadjusted row and an- adjusted-only row: closes 11.0 then 1.1, two price levels in one series."""- result = {- "data": [- {"date": "2024-01-02", "open": 10.0, "high": 11.5, "low": 9.5, "close": 11.0, "volume": 5},- {"date": "2024-01-03", "adj_open": 1.0, "adj_high": 1.2, "adj_low": 0.9, "adj_close": 1.1},- ]- }-- assert qv._result_to_frame(result, "2024-01-01", "2024-01-05") is None---def test_a_response_whose_rows_carry_both_families_uses_the_unadjusted_one():- result = {- "data": [- {"date": d, "open": 10.0, "high": 11.0, "low": 9.0, "close": c,- "adj_open": 1.0, "adj_high": 1.1, "adj_low": 0.9, "adj_close": c / 10}- for d, c in (("2024-01-02", 10.5), ("2024-01-03", 10.7))- ]- }-- frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")-- assert list(frame["close"]) == pytest.approx([10.5, 10.7])---class TestMarketsWithCorporateActions:- """Search rank ignores adjustment, so those markets are refused (#1494)."""-- @pytest.mark.parametrize(- "code", ["600519.SH", "600519", "AAPL.US", "AAPL", "00700.HK", "RELIANCE.NS", "510300.SH"]- )- def test_refused_before_any_request(self, monkeypatch, code):- _write_config(qv._CONFIG_PATH)- session = _install_session(monkeypatch, [])-- with pytest.raises(NoAvailableSourceError, match="#1494") as excinfo:- qv.DataLoader().fetch([code], "2024-01-01", "2024-01-31")-- assert code in str(excinfo.value)- assert session.calls == []-- def test_one_refused_symbol_refuses_the_request(self, monkeypatch):- _write_config(qv._CONFIG_PATH)- session = _install_session(monkeypatch, [])-- with pytest.raises(NoAvailableSourceError) as excinfo:- qv.DataLoader().fetch(["BTC-USDT", "600519.SH"], "2024-01-01", "2024-01-31")-- assert "600519.SH (a_share)" in str(excinfo.value)- assert "BTC-USDT" not in str(excinfo.value)- assert session.calls == []-- @pytest.mark.parametrize("code", ["BTC-USDT", "EURUSD", "RB2410.SHFE", "^GSPC"])- def test_markets_with_nothing_to_adjust_still_search(self, monkeypatch, code):- _write_config(qv._CONFIG_PATH)- session = _install_session(monkeypatch, [_FakeResponse({"search_id": "s", "results": []})])-- assert qv.DataLoader().fetch([code], "2024-01-01", "2024-01-31") == {}- assert [call["url"] for call in session.calls] == ["https://qveris.test/api/v1/search"]---class TestQuotedCallCost:- """Only a flat per-call quote bounds a bill (#1494)."""-- @pytest.mark.parametrize(- ("quote", "cost"),- [- ("24.2 credits", 24.2),- ("1 credits/call", 1.0),- ("5 credits per call", 5.0),- ("0.5 credit", 0.5),- ("1", 1.0),- ("0 credits", 0.0),- (3, 3.0),- ],- )- def test_a_flat_quote_is_its_price(self, quote, cost):- assert qv.quoted_call_cost(quote) == cost-- @pytest.mark.parametrize(- "quote",- ["1 credits/result", "0.00132 credits/value", "1 credit per row", "1-24.2 credits/call", "-1", "free", None, True, float("nan")],- )- def test_any_other_quote_prices_as_unknown(self, quote):- assert qv.quoted_call_cost(quote) is None-- def test_a_per_result_quote_is_skipped_and_a_flat_one_runs(self, monkeypatch, caplog):- _write_config(qv._CONFIG_PATH)- rows = {"data": [{"date": "2024-01-02", "open": 1, "high": 2, "low": 1, "close": 2, "volume": 5}]}- session = _install_session(- monkeypatch,- [- _FakeResponse(- {- "search_id": "s",- "results": [- _capability("per_result", expected_cost="0.1 credits/result"),- _capability("flat", expected_cost="5 credits/call"),- ],- }- ),- _FakeResponse({"success": True, "cost": 5.0, "result": rows}),- ],- )-- out = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")-- assert list(out) == ["BTC-USDT"]- executed = [call["url"] for call in session.calls if "/tools/execute" in call["url"]]- assert executed == ["https://qveris.test/api/v1/tools/execute?tool_id=flat"]-- def test_a_lone_per_result_quote_bills_nothing(self, monkeypatch, caplog):- _write_config(qv._CONFIG_PATH)- session = _install_session(- monkeypatch,- [_FakeResponse({"search_id": "s", "results": [_capability("per_result", expected_cost="1 credits/result")]})],- )-- assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}- assert len(session.calls) == 1- assert "not a flat price per call" in caplog.textdiff --git a/agent/tests/test_qveris_mcp.py b/agent/tests/test_qveris_mcp.pydeleted file mode 100644index 7fe09ecb1..000000000--- a/agent/tests/test_qveris_mcp.py+++ /dev/null@@ -1,131 +0,0 @@-"""Contract tests for issue #964 — QVeris tools exposed over MCP.--The three QVeris agent tools (``qveris_search`` / ``qveris_inspect`` /-``qveris_execute``) must be registered on the FastMCP server and follow the-key-gated contract of ``get_macro_series`` / ``iwencai_search``: an-unconfigured install receives an actionable, setup-naming JSON envelope from-the tool's own ``execute()`` — never the registry's generic "Tool not found".--The cached ``mcp_server._registry`` bakes in ``check_available()`` results, so-every behavioral test resets it to ``None`` before and after the call to force-a rebuild against the monkeypatched config path.-"""--from __future__ import annotations--import asyncio-import json-import re-from pathlib import Path--import pytest--import mcp_server-from src.tools import qveris_tool as qt--# fastmcp wraps the tool; reach the raw callable.-_qveris_search = getattr(mcp_server.qveris_search, "fn", None) or getattr(- mcp_server.qveris_search, "__wrapped__", mcp_server.qveris_search-)-_qveris_inspect = getattr(mcp_server.qveris_inspect, "fn", None) or getattr(- mcp_server.qveris_inspect, "__wrapped__", mcp_server.qveris_inspect-)-_qveris_execute = getattr(mcp_server.qveris_execute, "fn", None) or getattr(- mcp_server.qveris_execute, "__wrapped__", mcp_server.qveris_execute-)--[email protected](autouse=True)-def qveris_config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- monkeypatch.setattr(qt, "QVERIS_CONFIG_PATH", tmp_path / "qveris.json")- monkeypatch.delenv("QVERIS_API_KEY", raising=False)- monkeypatch.delenv("QVERIS_BASE_URL", raising=False)- qt._SESSION_SPEND.clear()- getattr(qt, "_SESSION_RESERVED", {}).clear()- return tmp_path / "qveris.json"---def fresh_mcp_registry():- """Force mcp_server to rebuild its cached registry under the test config."""- mcp_server._registry = None- yield- mcp_server._registry = None---def test_mcp_server_registers_qveris_tools() -> None:- """All three qveris wrappers must be registered on the FastMCP instance."""- tools = asyncio.run(mcp_server.mcp.list_tools())- registered = {t.name for t in tools}-- expected = {"qveris_search", "qveris_inspect", "qveris_execute"}- missing = expected - registered- assert not missing, (- f"MCP server is missing qveris tools: {missing}. "- "Issue #964 requires all three QVeris tools on the MCP surface."- )- # Read the claim out of the docstring instead of hardcoding it a third- # time. A literal here is a number nobody updates: it was written as 55,- # shipped as 58, and the surface was 59 before these three landed. This- # asserts the docstring and the surface agree, whatever they say.- claimed = re.search(r"Surfaces (\d+) tools", mcp_server.__doc__ or "")- assert claimed, "mcp_server's module docstring no longer states a tool count"- assert len(tools) == int(claimed.group(1)), (- f"Module docstring says {claimed.group(1)} tools, surface has {len(tools)}."- )---def test_qveris_search_unconfigured_returns_actionable_error(- fresh_mcp_registry,-) -> None:- """Without QVeris routing the MCP call surfaces the setup hint, not 'Tool not found'."""- payload = json.loads(_qveris_search("US listed options chain implied volatility Greeks AAPL"))-- assert payload.get("ok") is False- assert payload.get("error") != "Tool 'qveris_search' not found"- assert "QVERIS_API_KEY" in payload.get("error", "")---def test_qveris_search_configured_paid_delegates(fresh_mcp_registry, monkeypatch: pytest.MonkeyPatch) -> None:- """A keyed paid-mode install delegates to the registered tool end to end."""- qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid"))- canned = {- "search_id": "srch_1",- "results": [- {- "tool_id": "tool_options_iv",- "name": "US options IV surface",- "provider": "options-data-co",- "expected_cost": "1 credit",- "stats": {"success_rate": 0.98},- }- ],- "remaining_credits": 99.0,- }-- class FakeClient:- def search(self, query, *, limit=20, session_id=None):- return canned-- monkeypatch.setattr(qt.QVerisSearchTool, "_client", lambda self: FakeClient())-- payload = json.loads(_qveris_search("options iv greeks", limit=5))-- assert payload["ok"] is True- assert payload["search_id"] == "srch_1"- assert payload["results"][0]["tool_id"] == "tool_options_iv"- assert payload["results"][0]["provider"] == "options-data-co"- assert payload["results"][0]["expected_cost"] == "1 credit"- assert payload["results"][0]["stats"] == {"success_rate": 0.98}- assert payload["remaining_credits"] == 99.0---def test_qveris_execute_unconfigured_returns_actionable_error(- fresh_mcp_registry,-) -> None:- """qveris_execute must also surface the actionable envelope, never 'Tool not found'."""- payload = json.loads(_qveris_execute(tool_id="tool_1", parameters={"x": 1}))-- assert payload.get("ok") is False- assert payload.get("error") != "Tool 'qveris_execute' not found"- assert "QVeris is not configured" in payload.get("error", "")diff --git a/agent/tests/test_qveris_minute_granularity_tokens.py b/agent/tests/test_qveris_minute_granularity_tokens.pydeleted file mode 100644index c79097c79..000000000--- a/agent/tests/test_qveris_minute_granularity_tokens.py+++ /dev/null@@ -1,47 +0,0 @@-"""QVeris must rank minute intervals as intraday, not fall through to daily."""--from __future__ import annotations--from backtest.loaders.qveris_loader import _granularity_tokens, _select_capabilities---def _sample_results() -> list[dict]:- return [- {- "tool_id": "daily-ohlcv",- "name": "Daily OHLCV historical",- "description": "end-of-day daily open high low close volume for symbol ticker",- "stats": {"success_rate": 0.99},- "expected_cost": 0.01,- },- {- "tool_id": "intraday-1min",- "name": "1min intraday candles",- "description": "minute bar ohlcv historical price for symbol ticker",- "stats": {"success_rate": 0.90},- "expected_cost": 0.02,- },- ]---def test_one_minute_tokens_are_intraday() -> None:- wanted, unwanted = _granularity_tokens("1m")- assert "minute" in wanted- assert "monthly" in unwanted---def test_five_minute_tokens_are_intraday() -> None:- wanted, _ = _granularity_tokens("5m")- assert "minute" in wanted---def test_month_token_stays_monthly_not_minute() -> None:- wanted, unwanted = _granularity_tokens("1M")- assert "monthly" in wanted- assert "minute" in unwanted---def test_one_minute_prefers_intraday_capability_over_daily() -> None:- selected = _select_capabilities(_sample_results(), "1m")- assert selected- assert selected[0]["tool_id"] == "intraday-1min"diff --git a/agent/tests/test_qveris_routes.py b/agent/tests/test_qveris_routes.pydeleted file mode 100644index f22dbaa61..000000000--- a/agent/tests/test_qveris_routes.py+++ /dev/null@@ -1,151 +0,0 @@-from __future__ import annotations--from pathlib import Path--import pytest-from fastapi.testclient import TestClient--import api_server-from src.api import qveris_routes-from src.tools import qveris_tool as qt---def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:- monkeypatch.setattr(qt, "QVERIS_CONFIG_PATH", tmp_path / "qveris.json")- monkeypatch.delenv("QVERIS_API_KEY", raising=False)- monkeypatch.delenv("QVERIS_BASE_URL", raising=False)- monkeypatch.delenv("API_AUTH_KEY", raising=False)- monkeypatch.setattr(api_server, "_API_KEY", "")- return TestClient(api_server.app, client=("127.0.0.1", 50000))---def test_get_config_returns_redacted_unconfigured_shape(client: TestClient):- response = client.get("/qveris/config")-- assert response.status_code == 200- body = response.json()- assert body == {- "enabled": False,- "base_url": qt.DEFAULT_BASE_URL,- "api_key_masked": "",- "mode": "free",- "budget_credits_per_session": 50.0,- "configured": False,- "signup_url": qt.SIGNUP_URL,- "invite_code": qt.INVITE_CODE,- }---def test_put_config_persists_and_never_returns_plain_key(client: TestClient):- response = client.put(- "/qveris/config",- json={- "enabled": True,- "base_url": "https://qveris.example/api",- "api_key": "sk-secret-8TI",- "mode": "paid",- "budget_credits_per_session": 7.5,- },- )-- assert response.status_code == 200- body = response.json()- assert body["enabled"] is True- assert body["configured"] is True- assert body["api_key_masked"] == "sk-s…8TI"- assert "sk-secret-8TI" not in response.text- assert qt.load_qveris_config().api_key == "sk-secret-8TI"---def test_put_config_rejects_bad_mode_and_bad_url(client: TestClient):- bad_mode = client.put("/qveris/config", json={"mode": "live"})- bad_url = client.put("/qveris/config", json={"base_url": "ftp://qveris.test"})-- assert bad_mode.status_code == 422- assert bad_url.status_code == 422---def test_put_config_empty_key_preserves_existing_key(client: TestClient):- qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-existing-abc"))-- response = client.put("/qveris/config", json={"api_key": "", "mode": "paid"})-- assert response.status_code == 200- assert qt.load_qveris_config().api_key == "sk-existing-abc"- assert response.json()["mode"] == "paid"---def test_status_unconfigured_is_fail_closed(client: TestClient):- response = client.get("/qveris/status")-- assert response.status_code == 200- body = response.json()- assert body["enabled"] is False- assert body["ok"] is False- assert body["remaining_credits"] is None- assert body["recent"] == []---def test_status_paid_mode_uses_qveris_search_and_usage_history(- client: TestClient, monkeypatch: pytest.MonkeyPatch-):- qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid"))-- class FakeClient:- def __init__(self, config):- self.config = config-- def search(self, query, *, limit):- assert query == "status"- assert limit == 1- return {"remaining_credits": 88.0}-- def usage_history(self, **params):- return {- "events": [- {- "ts": "2026-07-07T00:00:00Z",- "tool_id": "tool_1",- "cost": 1.5,- "charge_outcome": "charged",- }- ]- }-- monkeypatch.setattr(qveris_routes, "QVerisClient", FakeClient)-- response = client.get("/qveris/status")-- assert response.status_code == 200- body = response.json()- assert body["ok"] is True- assert body["remaining_credits"] == 88.0- assert body["recent"] == [- {- "ts": "2026-07-07T00:00:00Z",- "tool_id": "tool_1",- "cost": 1.5,- "charge_outcome": "charged",- }- ]---def test_status_free_mode_keeps_public_data_route_and_skips_qveris_call(- client: TestClient, monkeypatch: pytest.MonkeyPatch-):- qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="free"))-- class FakeClient:- def __init__(self, config): # pragma: no cover - must not instantiate- raise AssertionError("free mode must not contact QVeris")-- monkeypatch.setattr(qveris_routes, "QVerisClient", FakeClient)-- response = client.get("/qveris/status")-- assert response.status_code == 200- body = response.json()- assert body["ok"] is False- assert body["remaining_credits"] is None- assert body["recent"] == []diff --git a/agent/tests/test_qveris_tool.py b/agent/tests/test_qveris_tool.pydeleted file mode 100644index 2cf45e1d1..000000000--- a/agent/tests/test_qveris_tool.py+++ /dev/null@@ -1,488 +0,0 @@-from __future__ import annotations--import json-import os-import stat-import threading-from concurrent.futures import ThreadPoolExecutor-from pathlib import Path--import pytest--from src.tools import qveris_tool as qt--[email protected](autouse=True)-def qveris_config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- monkeypatch.setattr(qt, "QVERIS_CONFIG_PATH", tmp_path / "qveris.json")- monkeypatch.delenv("QVERIS_API_KEY", raising=False)- monkeypatch.delenv("QVERIS_BASE_URL", raising=False)- qt._SESSION_SPEND.clear()- getattr(qt, "_SESSION_RESERVED", {}).clear()- return tmp_path / "qveris.json"---class FakeResponse:- def __init__(self, status_code: int, payload: dict, headers: dict | None = None):- self.status_code = status_code- self._payload = payload- self.headers = headers or {}- self.content = json.dumps(payload).encode("utf-8")-- def raise_for_status(self) -> None:- if self.status_code >= 400:- raise RuntimeError(f"HTTP {self.status_code}")-- def json(self) -> dict:- return self._payload---class FakeHttpClient:- def __init__(self, responses: list[FakeResponse]):- self.responses = responses- self.calls: list[dict] = []-- def request(self, method, url, **kwargs):- self.calls.append({"method": method, "url": url, **kwargs})- return self.responses.pop(0)---def test_config_read_write_masks_key_and_uses_0600(qveris_config_path: Path):- saved = qt.save_qveris_config(- qt.QVerisConfig(- enabled=True,- base_url="https://example.test/api",- api_key="sk-test-8TI",- mode="paid",- budget_credits_per_session=12.5,- )- )-- assert saved.enabled is True- assert qt.load_qveris_config().api_key == "sk-test-8TI"- assert qt.mask_api_key("sk-test-8TI") == "sk-t…8TI"- if os.name == "posix":- assert stat.S_IMODE(qveris_config_path.stat().st_mode) == 0o600---def test_env_overrides_file_config(monkeypatch: pytest.MonkeyPatch):- qt.save_qveris_config(- qt.QVerisConfig(enabled=True, base_url="https://file.test", api_key="file-key")- )- monkeypatch.setenv("QVERIS_API_KEY", "env-key")- monkeypatch.setenv("QVERIS_BASE_URL", "https://env.test/api")-- cfg = qt.load_qveris_config()-- assert cfg.api_key == "env-key"- assert cfg.base_url == "https://env.test/api"---def test_free_mode_tools_are_hidden():- assert qt.QVerisSearchTool.check_available() is False-- qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="free"))-- assert qt.QVerisSearchTool.check_available() is False-- qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid"))-- assert qt.QVerisSearchTool.check_available() is True---def test_free_mode_execute_is_unavailable(monkeypatch: pytest.MonkeyPatch):- qt.save_qveris_config(- qt.QVerisConfig(enabled=True, api_key="sk-live", mode="free")- )-- class FakeClient:- def inspect(self, tool_ids, **kwargs):- return {- "results": [- {- "tool_id": tool_ids[0],- "expected_cost": "2 credits",- "billing_rule": {"kind": "call"},- }- ]- }-- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())-- payload = json.loads(- qt.QVerisExecuteTool().execute(tool_id="tool_1", parameters={"x": 1})- )-- assert payload == {- "ok": False,- "error": (- "QVeris paid mode is off; enable it with `vibe-trading data mode paid` "- "or Settings -> QVeris to use QVeris tools"- ),- }---def test_unconfigured_execute_names_missing_api_key():- payload = json.loads(qt.QVerisSearchTool().execute(query="options iv"))-- assert payload == {- "ok": False,- "error": (- "QVeris is not configured; set QVERIS_API_KEY and enable paid mode "- "(`vibe-trading data mode paid` or Settings -> QVeris) to use QVeris tools"- ),- }---def test_paid_mode_rejects_when_expected_cost_exceeds_budget(monkeypatch):- qt.save_qveris_config(- qt.QVerisConfig(- enabled=True,- api_key="sk-live",- mode="paid",- budget_credits_per_session=1.0,- )- )-- class FakeClient:- def execute(self, *args, **kwargs): # pragma: no cover - must not call- raise AssertionError("execute should be blocked by budget")-- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())-- payload = json.loads(- qt.QVerisExecuteTool().execute(- tool_id="tool_1",- parameters={},- session_id="s1",- expected_cost="2 credits",- )- )-- assert payload["status"] == "budget_exceeded"- assert payload["budget_credits_per_session"] == 1.0---def test_parallel_execute_reserves_shared_session_budget(monkeypatch):- qt.save_qveris_config(- qt.QVerisConfig(- enabled=True,- api_key="sk-live",- mode="paid",- budget_credits_per_session=1.0,- )- )- entered = threading.Event()- release = threading.Event()-- class FakeClient:- calls = 0- lock = threading.Lock()-- def execute(self, *args, **kwargs):- del args, kwargs- with self.lock:- type(self).calls += 1- call_number = type(self).calls- if call_number == 1:- entered.set()- assert release.wait(timeout=2)- return {"success": True, "cost": 0.75, "result": {}}-- client = FakeClient()- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)- tool = qt.QVerisExecuteTool()-- with ThreadPoolExecutor(max_workers=2) as pool:- first = pool.submit(- tool.execute,- tool_id="tool_1",- parameters={},- session_id="shared",- expected_cost="0.75 credits",- )- assert entered.wait(timeout=2)- second = pool.submit(- tool.execute,- tool_id="tool_2",- parameters={},- session_id="shared",- expected_cost="0.75 credits",- )- second_payload = json.loads(second.result(timeout=2))- release.set()- first_payload = json.loads(first.result(timeout=2))-- assert first_payload["ok"] is True- assert second_payload["status"] == "budget_exceeded"- assert FakeClient.calls == 1- assert qt._SESSION_SPEND["shared"] == pytest.approx(0.75)- assert qt._SESSION_RESERVED.get("shared", 0.0) == 0.0---def test_failed_execute_releases_credit_reservation(monkeypatch):- qt.save_qveris_config(- qt.QVerisConfig(- enabled=True,- api_key="sk-live",- mode="paid",- budget_credits_per_session=1.0,- )- )-- class FailOnceClient:- calls = 0-- def execute(self, *args, **kwargs):- del args, kwargs- type(self).calls += 1- if type(self).calls == 1:- raise RuntimeError("provider failed")- return {"success": True, "cost": 1.0, "result": {}}-- client = FailOnceClient()- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)- tool = qt.QVerisExecuteTool()- call = {- "tool_id": "tool_1",- "parameters": {},- "session_id": "retry",- "expected_cost": "1 credit",- }-- with pytest.raises(RuntimeError, match="provider failed"):- tool.execute(**call)-- assert qt._SESSION_RESERVED.get("retry", 0.0) == 0.0- payload = json.loads(tool.execute(**call))- assert payload["ok"] is True- assert payload["session_spent_credits"] == pytest.approx(1.0)---def test_429_retries_after_retry_after(monkeypatch: pytest.MonkeyPatch):- sleeps: list[float] = []- monkeypatch.setattr(qt.time, "sleep", lambda value: sleeps.append(value))- fake = FakeHttpClient(- [- FakeResponse(429, {"error": "rate"}, headers={"Retry-After": "0"}),- FakeResponse(200, {"results": [], "remaining_credits": 9}),- ]- )- client = qt.QVerisClient(- qt.QVerisConfig(enabled=True, api_key="sk-live"),- client=fake,- min_interval_seconds=0,- )-- payload = client.search("aapl", limit=1)-- assert payload["remaining_credits"] == 9- assert len(fake.calls) == 2- assert sleeps == [0.0]---def test_execute_hydrates_truncated_full_content():- fake = FakeHttpClient(- [- FakeResponse(- 200,- {- "success": True,- "cost": 1.0,- "result": {- "message": "too long",- "full_content_file_url": "https://oss.qveris.cn/file.json",- },- },- ),- FakeResponse(200, {"rows": [{"close": 1.23}]}),- ]- )- client = qt.QVerisClient(- qt.QVerisConfig(enabled=True, api_key="sk-live"),- client=fake,- min_interval_seconds=0,- )-- payload = client.execute("tool_1", parameters={}, max_response_size=10)-- assert payload["result"]["full_content"] == {"rows": [{"close": 1.23}]}- assert payload["result"]["full_content_downloaded"] is True- assert fake.calls[1]["headers"] is None---def test_zero_expected_cost_from_the_caller_cannot_clear_the_budget_gate(monkeypatch):- """A caller-written quote of 0 must not reserve nothing and sail through.-- ``expected_cost`` is an ordinary tool argument, so it is written by an LLM- on the agent path and by an arbitrary client over MCP. It used to- short-circuit the marketplace lookup and be adopted verbatim, so 0 cleared- the pre-check with a zero reservation whatever the real price was.- """- qt.save_qveris_config(- qt.QVerisConfig(- enabled=True,- api_key="sk-live",- mode="paid",- budget_credits_per_session=1.0,- )- )-- class FakeClient:- def inspect(self, *args, **kwargs):- del args, kwargs- return {"results": [{"tool_id": "tool_1", "expected_cost": "5 credits"}]}-- def execute(self, *args, **kwargs): # pragma: no cover - must not run- raise AssertionError("execute must be blocked by the budget gate")-- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())-- payload = json.loads(- qt.QVerisExecuteTool().execute(- tool_id="tool_1",- parameters={},- session_id="attack",- expected_cost=0.0,- )- )-- assert payload["status"] == "budget_exceeded"- assert payload["quote"]["expected_cost"] == 5.0- assert payload["quote"]["quote_source"] == "server_overrode_lower_caller_quote"- assert qt._SESSION_SPEND.get("attack", 0.0) == 0.0---def test_an_unverifiable_zero_quote_fails_closed(monkeypatch):- """With no server quote to corroborate it, 0 means unknown, not free."""- qt.save_qveris_config(- qt.QVerisConfig(- enabled=True,- api_key="sk-live",- mode="paid",- budget_credits_per_session=1.0,- )- )-- class FakeClient:- def inspect(self, *args, **kwargs):- del args, kwargs- raise RuntimeError("marketplace unreachable")-- def execute(self, *args, **kwargs): # pragma: no cover - must not run- raise AssertionError("execute must be blocked by the budget gate")-- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())-- payload = json.loads(- qt.QVerisExecuteTool().execute(- tool_id="tool_1", parameters={}, session_id="offline", expected_cost=0- )- )-- assert payload["status"] == "budget_exceeded"---def test_an_honest_caller_quote_is_still_honoured(monkeypatch):- """The caller hint keeps working when it is not understating the price."""- qt.save_qveris_config(- qt.QVerisConfig(- enabled=True,- api_key="sk-live",- mode="paid",- budget_credits_per_session=10.0,- )- )-- class FakeClient:- def inspect(self, *args, **kwargs):- del args, kwargs- return {"results": [{"tool_id": "tool_1", "expected_cost": "1 credit"}]}-- def execute(self, *args, **kwargs):- del args, kwargs- return {"success": True, "cost": 1.0, "result": {}}-- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())-- payload = json.loads(- qt.QVerisExecuteTool().execute(- tool_id="tool_1", parameters={}, session_id="honest", expected_cost="2 credits"- )- )-- assert payload["ok"] is True- assert qt._SESSION_SPEND["honest"] == pytest.approx(1.0)---def _paid(budget: float) -> None:- qt.save_qveris_config(- qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid", budget_credits_per_session=budget)- )---class _QuotedClient:- def __init__(self, quote):- self.quote = quote- self.executed = 0-- def inspect(self, *args, **kwargs):- del args, kwargs- return {"results": [{"tool_id": "tool_1", "expected_cost": self.quote}]}-- def execute(self, *args, **kwargs):- del args, kwargs- self.executed += 1- return {"success": True, "cost": 1.0, "result": {}}---def test_a_per_result_server_quote_is_refused_whatever_the_caller_writes(monkeypatch):- """ "1 credits/result" billed 9.66 credits for one stock-year (#1494): its- leading number is not a price, and a caller-written flat quote must not- stand in for it."""- _paid(50.0)- client = _QuotedClient("1 credits/result")- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)-- for hint in (None, "2 credits"):- kwargs = {"tool_id": "tool_1", "parameters": {}, "session_id": "per_result"}- if hint is not None:- kwargs["expected_cost"] = hint- payload = json.loads(qt.QVerisExecuteTool().execute(**kwargs))- assert payload["status"] == "quote_not_bounded"- assert payload["quote"]["quote_source"] == "server_quote_not_per_call"-- assert client.executed == 0- assert qt._SESSION_SPEND.get("per_result", 0.0) == 0.0---def test_a_per_result_caller_quote_without_a_server_quote_is_refused(monkeypatch):- _paid(50.0)-- class _Offline(_QuotedClient):- def inspect(self, *args, **kwargs):- raise RuntimeError("marketplace unreachable")-- client = _Offline(None)- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)-- payload = json.loads(- qt.QVerisExecuteTool().execute(- tool_id="tool_1", parameters={}, session_id="s", expected_cost="1 credits/result"- )- )-- assert payload["status"] == "quote_not_bounded"- assert client.executed == 0---def test_a_flat_per_call_server_quote_still_runs(monkeypatch):- _paid(50.0)- client = _QuotedClient("24.2 credits/call")- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)-- payload = json.loads(qt.QVerisExecuteTool().execute(tool_id="tool_1", parameters={}, session_id="flat"))-- assert payload["ok"] is True- assert client.executed == 1- assert qt._SESSION_SPEND["flat"] == pytest.approx(1.0)diff --git a/agent/tests/test_readme_counts.py b/agent/tests/test_readme_counts.pyindex 31349ca2d..a17c69a95 100644--- a/agent/tests/test_readme_counts.py+++ b/agent/tests/test_readme_counts.py@@ -291,7 +291,7 @@ def test_repo_tree_states_the_real_mcp_count(name: str) -> None:# Environment variables that make a credential-gated tool register. The# repository-tree line has always carried the keyless registry size (the count a# fresh install sees), so those gates are closed while measuring it.-_CREDENTIAL_GATES = ("GILDATA_TOKEN", "FRED_API_KEY", "VIBE_TRADING_IWENCAI_KEY", "QVERIS_API_KEY", "VIBE_TW_STOCK_DB")+_CREDENTIAL_GATES = ("GILDATA_TOKEN", "FRED_API_KEY", "VIBE_TRADING_IWENCAI_KEY", "VIBE_TW_STOCK_DB")@functools.lru_cache(maxsize=1)diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.pyindex 6e1688420..0f3f62cf2 100644--- a/agent/tests/test_registry.py+++ b/agent/tests/test_registry.py@@ -258,7 +258,6 @@ class TestFallbackChains:"baostock","akshare","tushare",- "gildata","local",]assert FALLBACK_CHAINS["us_equity"] == [@@ -284,7 +283,6 @@ class TestFallbackChains:"yfinance","tushare","longbridge",- "gildata","local",]diff --git a/agent/tests/test_runner_env.py b/agent/tests/test_runner_env.pyindex 3b07bf9c4..38e8a41e5 100644--- a/agent/tests/test_runner_env.py+++ b/agent/tests/test_runner_env.py@@ -165,14 +165,12 @@ def test_prepare_sandbox_home_reexposes_only_loader_paths(tmp_path: Path) -> Non(vt / "cache").mkdir(parents=True)(vt / "memory").mkdir(parents=True)(vt / ".env").write_text("SECRET=1", encoding="utf-8")- (vt / "qveris.json").write_text("{}", encoding="utf-8")sandbox = _prepare_sandbox_home(real_home)try:dst_vt = sandbox / ".vibe-trading"# Loader-owned paths re-exposed (symlinked)...assert (dst_vt / "cache").exists()- assert (dst_vt / "qveris.json").exists()# ...persistent secrets/state are NOT.assert not (dst_vt / "memory").exists()assert not (dst_vt / ".env").exists()@@ -238,7 +236,6 @@ def test_prepare_sandbox_home_copy_fallback_when_symlink_privileges_missing(vt = real_home / ".vibe-trading"(vt / "cache").mkdir(parents=True)(vt / "data-bridge").mkdir(parents=True)- (vt / "qveris.json").write_text("{}", encoding="utf-8")def _deny_symlink(*args, **kwargs):raise OSError(1314, "A required privilege is not held by the client")@@ -251,7 +248,6 @@ def test_prepare_sandbox_home_copy_fallback_when_symlink_privileges_missing(# Symlinks were impossible, yet the loader paths are still present...assert (dst_vt / "cache").is_dir()assert (dst_vt / "data-bridge").is_dir()- assert (dst_vt / "qveris.json").is_file()# ...and the persistent secrets/state are still NOT re-exposed.assert not (dst_vt / ".env").exists()assert not (dst_vt / "memory").exists()diff --git a/agent/tests/test_settings_api.py b/agent/tests/test_settings_api.pyindex b463d7ac5..1a89d3b1a 100644--- a/agent/tests/test_settings_api.py+++ b/agent/tests/test_settings_api.py@@ -715,7 +715,7 @@ def test_update_source_orders_persists_and_hot_applies("market": "a_share","order": ["tushare", "tencent", "eastmoney",- "baostock", "akshare", "gildata", "local",+ "baostock", "akshare", "local",],},],@@ -754,7 +754,7 @@ def test_update_source_orders_reset_clears_override("market": "a_share","order": ["tushare", "tencent", "eastmoney",- "baostock", "akshare", "gildata", "local",+ "baostock", "akshare", "local",],},],@@ -939,3 +939,50 @@ def test_codex_model_discovery_uses_fixed_oauth_catalog_not_form_url(assert response.json()["model_labels"]["openai-codex/gpt-6-sol"] == "GPT-6 Sol"assert response.json()["effort_levels"]["openai-codex/gpt-6-sol"] == ["low", "medium", "ultra"]assert response.json()["default_effort_levels"]["openai-codex/gpt-6-sol"] == "medium"+++def test_gildata_upgrade_and_feature_isolation(client, monkeypatch, tmp_path):+ """An old token grants none of the four capabilities until individually enabled."""+ from src.config.gildata_features import FEATURES_ENV+ from src.tools import gildata_identity+ from src.tools.gildata_fin_query_tool import GildataFinQueryTool+ from src.tools.gildata_stock_selection_tool import GildataStockSelectionTool+ from src.tools import gildata_srv+ from unittest.mock import Mock++ monkeypatch.delenv(FEATURES_ENV, raising=False)+ monkeypatch.setenv("GILDATA_TOKEN", "old-token")+ (tmp_path / ".env").write_text("GILDATA_TOKEN=old-token\n")+ vendor = Mock(return_value=[])+ monkeypatch.setattr(gildata_identity, "_call_tool_results", vendor)+ monkeypatch.setattr(gildata_srv, "_call_srv", vendor)+ url = "/settings/data-sources"+ assert client.get(url).json()["gildata_features"] == []+ from backtest.loaders.gildata_loader import DataLoader++ retained_tool = GildataFinQueryTool()+ for index, feature in enumerate([None, "symbol_search", "fin_query", "stock_selection", "shannon", "market_quotes", None]):+ if index:+ selected = [feature] if feature else []+ response = client.put(url, json={"gildata_features": selected})+ assert response.status_code == 200+ assert response.json()["gildata_features"] == selected+ assert f"{FEATURES_ENV}={feature or ''}\n" in (tmp_path / ".env").read_text()+ assert DataLoader().is_available() == (feature == "market_quotes")+ assert retained_tool.check_available() == (feature == "fin_query")+ assert GildataStockSelectionTool.check_available() == (feature == "stock_selection")+ before = vendor.call_count+ gildata_identity.search_candidates("AAPL", 5)+ assert vendor.call_count == before + (feature == "symbol_search")+ assert client.get("/api/shannon/status").json()["configured"] == (feature == "shannon")+ if feature != "shannon":+ assert client.get("/api/shannon/catalog").status_code == 503+ assert client.post("/api/shannon/diagnosis", json={+ "holdings": [{"code": "600000.SH"}]+ }).status_code == 503+ if feature != "fin_query":+ assert '"ok": false' in retained_tool.execute(query="revenue")+ if feature != "stock_selection":+ assert '"ok": false' in GildataStockSelectionTool().execute(query="top stocks")+ assert vendor.call_count == before + (feature == "symbol_search")+ assert client.put(url, json={"gildata_features": ["*"]}).status_code == 422diff --git a/agent/tests/test_shannon_routes.py b/agent/tests/test_shannon_routes.pyindex 1195ae042..309b6430b 100644--- a/agent/tests/test_shannon_routes.py+++ b/agent/tests/test_shannon_routes.py@@ -23,6 +23,7 @@ def diagnosis():@pytest.fixturedef client(monkeypatch, diagnosis):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "shannon")monkeypatch.setenv("GILDATA_TOKEN", "test-token")vendor = Mock(return_value=diagnosis)monkeypatch.setattr(sr, "call_srv_arguments", vendor)@@ -121,6 +122,7 @@ def test_routes_keep_authentication():@pytest.mark.parametrize("status", ["completed", "queued", "running"])def test_transport_preserves_status_and_rejects_rpc_errors(monkeypatch, status):+ monkeypatch.setenv("VIBE_TRADING_GILDATA_FEATURES", "shannon")monkeypatch.setenv("GILDATA_TOKEN", "test-token")payload = {"status": status, "job_id": "job-123", "data": {}, "meta": {"as_of": "2026-10-28"}}outer = {"result": {"content": [{"type": "text", "text": json.dumps(payload)}]}}diff --git a/agent/tests/test_source_order_overrides.py b/agent/tests/test_source_order_overrides.pyindex c995add25..3f8378ec2 100644--- a/agent/tests/test_source_order_overrides.py+++ b/agent/tests/test_source_order_overrides.py@@ -191,7 +191,7 @@ def test_empty_string_resets_to_default("tushare,tencent,eastmoney,baostock,akshare,gildata,local",)refresh_source_order_overrides()- assert registry.FALLBACK_CHAINS["a_share"][0] == "tushare"+ assert registry.FALLBACK_CHAINS["a_share"] == ["tushare", "tencent", "eastmoney", "baostock", "akshare", "local"]monkeypatch.setenv("MARKET_DATA_ORDER_A_SHARE", "")refresh_source_order_overrides()diff --git a/agent/tests/test_strategy_discovery_mcp.py b/agent/tests/test_strategy_discovery_mcp.pyindex 57a40f743..4f0468f93 100644--- a/agent/tests/test_strategy_discovery_mcp.py+++ b/agent/tests/test_strategy_discovery_mcp.py@@ -7,7 +7,7 @@ on the FastMCP server and each wrapper must delegate tofound" path when the facade layer can answer, and never a crash when theregistry is missing or broken (actionable JSON instead).-Follows the ``test_qveris_mcp.py`` fixture pattern: a fresh/monkeypatched+Uses a fresh/monkeypatched``mcp_server._registry`` per test. No network: delegation is verified againstrecording fake registries; the real store/facade are never constructed."""diff --git a/agent/tests/test_tools_type_value_safety.py b/agent/tests/test_tools_type_value_safety.pyindex eeb113ed3..4c98b9354 100644--- a/agent/tests/test_tools_type_value_safety.py+++ b/agent/tests/test_tools_type_value_safety.py@@ -21,7 +21,6 @@ from typing import Anyimport pytest-from src.tools import qveris_tool as qtfrom src.tools import shadow_account_tool as satfrom src.tools.alpha_zoo_tool import run_alpha_zoofrom src.tools.block_trades_tool import _clamp_days as block_trades_clamp_days@@ -182,130 +181,6 @@ def test_place_order_still_forwards_valid_arguments(monkeypatch: pytest.MonkeyPaassert seen["port"] == 7497-# ── QVeris: not read-only, spends real credits ────────────────────────────────---def paid_qveris(tmp_path, monkeypatch: pytest.MonkeyPatch):- """Configure paid-mode QVeris against a tmp config file (never the real key)."""- monkeypatch.setattr(qt, "QVERIS_CONFIG_PATH", tmp_path / "qveris.json")- monkeypatch.delenv("QVERIS_API_KEY", raising=False)- monkeypatch.delenv("QVERIS_BASE_URL", raising=False)- qt._SESSION_SPEND.clear()- qt._SESSION_RESERVED.clear()- qt.save_qveris_config(- qt.QVerisConfig(enabled=True, api_key="sk-test", mode="paid", budget_credits_per_session=50.0)- )- yield- qt._SESSION_SPEND.clear()- qt._SESSION_RESERVED.clear()---def _forbid_qveris_client(monkeypatch: pytest.MonkeyPatch) -> None:- """Make any QVeris client construction an outright test failure."""-- def fail(self: Any) -> Any:- raise AssertionError("no QVeris client may be built for an invalid request")-- monkeypatch.setattr(qt.QVerisSearchTool, "_client", fail)- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", fail)--[email protected]("kwargs", [{}, {"query": None}, {"query": " "}, {"query": 5}])-def test_qveris_search_rejects_missing_query(- paid_qveris: None, monkeypatch: pytest.MonkeyPatch, kwargs: dict[str, Any]-) -> None:- """A missing query must not be sent to the marketplace as an empty search."""- _forbid_qveris_client(monkeypatch)-- payload = json.loads(qt.QVerisSearchTool().execute(**kwargs))-- assert payload["ok"] is False- assert "query is required" in payload["error"]--[email protected]("bad_limit", [float("inf"), float("nan"), "many", 0, -3, 2.5, {}])-def test_qveris_search_rejects_malformed_limit(- paid_qveris: None, monkeypatch: pytest.MonkeyPatch, bad_limit: Any-) -> None:- """An explicitly malformed limit errors instead of quietly becoming 20."""- _forbid_qveris_client(monkeypatch)-- payload = json.loads(qt.QVerisSearchTool().execute(query="btc", limit=bad_limit))-- assert payload["ok"] is False- assert "limit must be a positive integer" in payload["error"]---def test_qveris_search_forwards_valid_request(paid_qveris: None, monkeypatch: pytest.MonkeyPatch) -> None:- """A well-formed search still reaches the client with a defaulted limit."""- seen: dict[str, Any] = {}-- class FakeClient:- def search(self, query: str, **kwargs: Any) -> dict[str, Any]:- seen.update({"query": query, **kwargs})- return {"results": []}-- monkeypatch.setattr(qt.QVerisSearchTool, "_client", lambda self: FakeClient())-- payload = json.loads(qt.QVerisSearchTool().execute(query=" btc "))-- assert payload["ok"] is True- assert seen["query"] == "btc"- assert seen["limit"] == 20--- ("kwargs", "expected"),- [- ({"tool_id": "t1"}, "parameters is required"),- ({"tool_id": "t1", "parameters": None}, "parameters is required"),- ({"tool_id": "t1", "parameters": "{}"}, "parameters is required"),- ({"tool_id": "t1", "parameters": []}, "parameters is required"),- ({"parameters": {"x": 1}}, "tool_id is required"),- ({"tool_id": "", "parameters": {"x": 1}}, "tool_id is required"),- ({"tool_id": "t1", "parameters": {}, "max_response_size": float("inf")}, "max_response_size"),- ({"tool_id": "t1", "parameters": {}, "max_response_size": "big"}, "max_response_size"),- ],-)-def test_qveris_execute_never_bills_an_invalid_request(- paid_qveris: None, monkeypatch: pytest.MonkeyPatch, kwargs: dict[str, Any], expected: str-) -> None:- """A schema-invalid billable call is refused before quote/budget/execute."""- _forbid_qveris_client(monkeypatch)-- payload = json.loads(qt.QVerisExecuteTool().execute(**kwargs))-- assert payload["ok"] is False- assert expected in payload["error"]- assert qt._SESSION_RESERVED == {}- assert qt._SESSION_SPEND == {}---def test_qveris_execute_accepts_a_genuinely_empty_parameters_object(- paid_qveris: None, monkeypatch: pytest.MonkeyPatch-) -> None:- """`parameters={}` is a valid supplied value — only a MISSING field is refused."""- seen: dict[str, Any] = {}-- class FakeClient:- def execute(self, tool_id: str, **kwargs: Any) -> dict[str, Any]:- seen.update({"tool_id": tool_id, **kwargs})- return {"success": True, "cost": 1.0, "result": {}}-- monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: FakeClient())-- payload = json.loads(- qt.QVerisExecuteTool().execute(- tool_id="tool_1", parameters={}, session_id="s1", expected_cost="1 credit"- )- )-- assert payload["ok"] is True- assert seen["parameters"] == {}- assert seen["max_response_size"] == 20480--# ── report_audit extract options ──────────────────────────────────────────────diff --git a/desktop/electron/THREAT_MODEL.md b/desktop/electron/THREAT_MODEL.mdindex a1a42d23f..525383148 100644--- a/desktop/electron/THREAT_MODEL.md+++ b/desktop/electron/THREAT_MODEL.md@@ -20,7 +20,7 @@ or default-enabled updater exists.- Local Vibe-Trading sessions, reports, configuration, and research data.- Any credentials already present in the environment inherited by the Pythonprocess.-- LLM, Tushare, and QVeris credentials managed by the desktop host.+- LLM, Tushare, and Gildata credentials managed by the desktop host.- The integrity of the executable selected as the backend.- The ability to invoke authenticated local API routes.- Future update publisher policy, release digest metadata, and the integrity of@@ -168,7 +168,7 @@ therefore security-significant.- The on-disk JSON file contains only Base64-encoded ciphertext and the list ofconfigured names.- Writes use a same-directory temporary file followed by rename.-- Existing supported values in `~/.vibe-trading/.env` and QVeris configuration+- Existing supported values in `~/.vibe-trading/.env`are migrated once; the corresponding plaintext field is removed after theencrypted store has been persisted.- Decrypted values are injected only into the owned backend child environment.diff --git a/desktop/electron/WINDOWS_PACKAGING.md b/desktop/electron/WINDOWS_PACKAGING.mdindex ebcfd421b..b9118e617 100644--- a/desktop/electron/WINDOWS_PACKAGING.md+++ b/desktop/electron/WINDOWS_PACKAGING.md@@ -7,7 +7,7 @@ This layer is stacked on the desktop lifecycle shell and adds only:- the existing production frontend and the upstream hash-locked base Pythondependencies;- the verified native DLL subset required for WeasyPrint PDF output;-- Electron `safeStorage` for LLM, Tushare, and QVeris credentials.+- Electron `safeStorage` for LLM, Tushare, and Gildata credentials.## Deliberate exclusions@@ -96,8 +96,7 @@ Electron `safeStorage` uses the operating-system encryption facility for thecurrent user. Decrypted values are injected only into the child backendenvironment and are not returned to the renderer.-On first startup, supported secrets in `~/.vibe-trading/.env` and the QVeris-API key in `~/.vibe-trading/qveris.json` are migrated into encrypted storage.+On first startup, supported secrets in `~/.vibe-trading/.env` are migrated into encrypted storage.The plaintext fields are then removed. Backend settings writes in desktopsecure mode explicitly blank known credential fields instead of writing theinjected values back to dotenv.diff --git a/desktop/electron/scripts/smoke-credentials.cjs b/desktop/electron/scripts/smoke-credentials.cjsindex e14ac090c..c5d2fb235 100644--- a/desktop/electron/scripts/smoke-credentials.cjs+++ b/desktop/electron/scripts/smoke-credentials.cjs@@ -28,19 +28,12 @@ async function run() {"MODELSCOPE_API_KEY=desktop-smoke-modelscope-secret","TUSHARE_TOKEN='desktop-smoke-tushare-secret'","ANTHROPIC_API_KEY=sk-xxx",+ "GILDATA_TOKEN=desktop-smoke-gildata-secret","NON_SECRET_SETTING=preserved","",].join("\n"),"utf8",);- await fs.writeFile(- path.join(configDirectory, "qveris.json"),- `${JSON.stringify({- api_key: "desktop-smoke-qveris-secret",- enabled: true,- }, null, 2)}\n`,- "utf8",- );const store = new SecureCredentialStore({ homeDirectory, userDataDirectory });await store.initialize();@@ -52,21 +45,21 @@ async function run() {"desktop-smoke-modelscope-secret",);assert.equal(initialEnvironment.TUSHARE_TOKEN, "desktop-smoke-tushare-secret");- assert.equal(initialEnvironment.QVERIS_API_KEY, "desktop-smoke-qveris-secret");+ assert.equal(initialEnvironment.GILDATA_TOKEN, "desktop-smoke-gildata-secret");assert.equal(initialEnvironment.ANTHROPIC_API_KEY, undefined);const status = store.status();assert.deepEqual(status.configured, [+ "GILDATA_TOKEN","MODELSCOPE_API_KEY","OPENAI_API_KEY",- "QVERIS_API_KEY","TUSHARE_TOKEN",]);assert.deepEqual(status.migrated, ["OPENAI_API_KEY","MODELSCOPE_API_KEY","TUSHARE_TOKEN",- "QVERIS_API_KEY",+ "GILDATA_TOKEN",]);const encryptedFile = await fs.readFile(@@ -87,10 +80,7 @@ async function run() {assert.ok(!migratedDotenv.includes("desktop-smoke-modelscope-secret"));assert.ok(!migratedDotenv.includes("desktop-smoke-tushare-secret"));- const migratedQveris = JSON.parse(- await fs.readFile(path.join(configDirectory, "qveris.json"), "utf8"),- );- assert.deepEqual(migratedQveris, { enabled: true });+ assert.ok(!migratedDotenv.includes("desktop-smoke-gildata-secret"));const reloadedStore = new SecureCredentialStore({ homeDirectory, userDataDirectory });await reloadedStore.initialize();diff --git a/desktop/electron/src/secure-credentials.ts b/desktop/electron/src/secure-credentials.tsindex acf2792be..7d735349b 100644--- a/desktop/electron/src/secure-credentials.ts+++ b/desktop/electron/src/secure-credentials.ts@@ -29,7 +29,7 @@ const ENV_CREDENTIALS = new Set(["SPARK_API_KEY","ZAI_API_KEY","TUSHARE_TOKEN",- "QVERIS_API_KEY",+ "GILDATA_TOKEN",]);const PLACEHOLDER_VALUES = new Set([@@ -40,6 +40,7 @@ const PLACEHOLDER_VALUES = new Set(["xxx","gsk_xxx","your-tushare-token",+ "your-gildata-token",]);export type CredentialStatus = {@@ -87,11 +88,6 @@ export class SecureCredentialStore {}await this.load();await this.migrateDotenv(path.join(this.homeDirectory, ".vibe-trading", ".env"));- await this.migrateJsonField(- path.join(this.homeDirectory, ".vibe-trading", "qveris.json"),- "api_key",- "QVERIS_API_KEY",- );}status(): CredentialStatus {@@ -195,28 +191,6 @@ export class SecureCredentialStore {}}- private async migrateJsonField(- filePath: string,- field: string,- credential: string,- ): Promise<void> {- try {- const parsed = JSON.parse(await fs.readFile(filePath, "utf8")) as Record<string, unknown>;- const value = typeof parsed[field] === "string" ? parsed[field].trim() : "";- if (!value) return;- if (!this.values[credential]) {- this.values[credential] = safeStorage.encryptString(value).toString("base64");- this.migrated.push(credential);- await this.persist();- }- delete parsed[field];- await atomicTextWrite(filePath, `${JSON.stringify(parsed, null, 2)}\n`);- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !(error instanceof SyntaxError)) {- throw error;- }- }- }}function unquote(value: string): string {diff --git a/frontend/src/components/settings/QVerisSettings.tsx b/frontend/src/components/settings/QVerisSettings.tsxdeleted file mode 100644index f4e55c237..000000000--- a/frontend/src/components/settings/QVerisSettings.tsx+++ /dev/null@@ -1,357 +0,0 @@-import { useEffect, useId, useState, type FormEvent } from "react";-import { ExternalLink, KeyRound, Loader2, Save, SearchCheck } from "lucide-react";-import { useTranslation } from "react-i18next";-import { toast } from "sonner";-import { authHeaders } from "@/lib/apiAuth";--type QVerisMode = "free" | "paid";--interface QVerisConfig {- enabled: boolean;- base_url: string;- api_key_masked: string;- mode: QVerisMode;- budget_credits_per_session: number;- configured: boolean;- signup_url: string;- invite_code: string;-}--interface QVerisStatus {- enabled: boolean;- ok: boolean;- error: string | null;- remaining_credits: number | null;- recent: Array<{- ts: string;- tool_id: string;- cost: number;- charge_outcome: string;- }>;- signup_url: string;- invite_code: string;-}--interface QVerisForm {- enabled: boolean;- base_url: string;- api_key: string;- mode: QVerisMode;- budget_credits_per_session: number;-}--const DEFAULT_BASE_URL = "https://qveris.ai/api/v1";-const fieldClass =- "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-60";-const labelClass = "text-sm font-medium";-const hintClass = "text-xs text-muted-foreground";--async function requestJson<T>(path: string, options?: RequestInit): Promise<T> {- const { headers, ...rest } = options ?? {};- const mergedHeaders: Record<string, string> = { "Content-Type": "application/json", ...authHeaders() };- if (headers) {- new Headers(headers).forEach((value, key) => {- mergedHeaders[key] = value;- });- }-- const response = await fetch(path, { ...rest, headers: mergedHeaders });- if (!response.ok) {- let message = `HTTP ${response.status}`;- try {- const body = await response.json();- message = body.detail || body.message || message;- } catch { /* ignore */ }- throw new Error(message);- }- return response.json() as Promise<T>;-}--function formFromConfig(config: QVerisConfig): QVerisForm {- return {- enabled: config.enabled && config.mode === "paid",- base_url: config.base_url || DEFAULT_BASE_URL,- api_key: "",- mode: config.mode,- budget_credits_per_session: config.budget_credits_per_session,- };-}--export function QVerisSettings() {- const { t } = useTranslation();- const idPrefix = useId();- const [config, setConfig] = useState<QVerisConfig | null>(null);- const [status, setStatus] = useState<QVerisStatus | null>(null);- const [form, setForm] = useState<QVerisForm>({- enabled: false,- base_url: DEFAULT_BASE_URL,- api_key: "",- mode: "free",- budget_credits_per_session: 50,- });- const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string | null>(null);-- const load = async () => {- setLoading(true);- setError(null);- try {- const [nextConfig, nextStatus] = await Promise.all([- requestJson<QVerisConfig>("/qveris/config"),- requestJson<QVerisStatus>("/qveris/status"),- ]);- setConfig(nextConfig);- setForm(formFromConfig(nextConfig));- setStatus(nextStatus);- } catch (loadError) {- setError(loadError instanceof Error ? loadError.message : t("qveris.testFailed"));- } finally {- setLoading(false);- }- };-- useEffect(() => {- let alive = true;- setLoading(true);- setError(null);-- Promise.all([- requestJson<QVerisConfig>("/qveris/config"),- requestJson<QVerisStatus>("/qveris/status"),- ])- .then(([nextConfig, nextStatus]) => {- if (!alive) return;- setConfig(nextConfig);- setForm(formFromConfig(nextConfig));- setStatus(nextStatus);- })- .catch((loadError) => {- if (!alive) return;- setError(loadError instanceof Error ? loadError.message : t("qveris.testFailed"));- })- .finally(() => {- if (alive) setLoading(false);- });-- return () => {- alive = false;- };- }, [t]);-- const submit = async (event: FormEvent) => {- event.preventDefault();- setSaving(true);- setError(null);- try {- const payload: {- enabled: boolean;- base_url: string;- mode: QVerisMode;- budget_credits_per_session: number;- api_key?: string;- } = {- enabled: form.mode === "paid" && form.enabled,- base_url: form.base_url.trim(),- mode: form.mode,- budget_credits_per_session: Number(form.budget_credits_per_session) || 0,- };- const trimmedApiKey = form.api_key.trim();- if (trimmedApiKey && !window.vibeDesktop) payload.api_key = trimmedApiKey;-- const nextConfig = await requestJson<QVerisConfig>("/qveris/config", {- method: "PUT",- body: JSON.stringify(payload),- });- if (trimmedApiKey && window.vibeDesktop) {- await window.vibeDesktop.setCredential("QVERIS_API_KEY", trimmedApiKey);- }- setConfig(nextConfig);- setForm(formFromConfig(nextConfig));- toast.success(t("qveris.saved"));- if (trimmedApiKey && window.vibeDesktop) {- toast.info(t("settings.desktopCredentialRestarting"));- await window.vibeDesktop.restartBackend();- return;- }- await load();- } catch (saveError) {- const message = saveError instanceof Error ? saveError.message : t("qveris.testFailed");- setError(message);- } finally {- setSaving(false);- }- };-- const recent = status?.recent ?? [];- const signupUrl = config?.signup_url || "";- const inviteCode = config?.invite_code || status?.invite_code || "";- const apiKeyPlaceholder = config?.api_key_masked || t("qveris.apiKeyPlaceholder");-- return (- <section className="rounded-lg border bg-card p-5 shadow-sm">- <div className="mb-5 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">- <div className="space-y-1">- <div className="flex items-center gap-2">- <SearchCheck className="h-4 w-4 text-primary" />- <h2 className="text-base font-semibold">{t("qveris.title")}</h2>- </div>- <p className="max-w-3xl text-sm text-muted-foreground">{t("qveris.subtitle")}</p>- </div>- <a- href={signupUrl || undefined}- target="_blank"- rel="noreferrer"- aria-disabled={!signupUrl}- className={`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-2 text-sm transition ${- signupUrl- ? "text-muted-foreground hover:bg-muted hover:text-foreground"- : "pointer-events-none text-muted-foreground opacity-60"- }`}- >- <ExternalLink className="h-4 w-4" />- {t("qveris.signupCta")}- </a>- </div>-- {error ? (- <div className="mb-4 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">- <span className="font-medium">{t("qveris.testFailed")}: </span>- <span>{error}</span>- </div>- ) : null}-- <form onSubmit={submit} className="grid gap-5 lg:grid-cols-[minmax(0,1.1fr)_minmax(280px,0.9fr)]">- <div className="grid gap-4">- <label className="flex items-center justify-between gap-3 rounded-md border bg-muted/20 px-3 py-2">- <span className={labelClass}>{t("qveris.enabled")}</span>- <input- type="checkbox"- checked={form.enabled}- onChange={(event) => {- const enabled = event.target.checked;- setForm({ ...form, enabled, mode: enabled ? "paid" : "free" });- }}- className="h-4 w-4 accent-primary"- disabled={loading}- />- </label>-- <label className="grid gap-2" htmlFor={`${idPrefix}-base-url`}>- <span className={labelClass}>{t("qveris.baseUrl")}</span>- <input- id={`${idPrefix}-base-url`}- value={form.base_url}- onChange={(event) => setForm({ ...form, base_url: event.target.value })}- className={fieldClass}- placeholder={DEFAULT_BASE_URL}- disabled={loading}- />- </label>-- <label className="grid gap-2" htmlFor={`${idPrefix}-api-key`}>- <span className={labelClass}>{t("qveris.apiKey")}</span>- <div className="relative">- <KeyRound className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />- <input- id={`${idPrefix}-api-key`}- type="password"- value={form.api_key}- onChange={(event) => setForm({ ...form, api_key: event.target.value })}- className={`${fieldClass} pl-9`}- placeholder={apiKeyPlaceholder}- autoComplete="current-password"- disabled={loading}- />- </div>- <span className={hintClass}>{t("qveris.apiKeyPlaceholder")}</span>- </label>-- <div className="grid gap-4 md:grid-cols-2">- <label className="grid gap-2" htmlFor={`${idPrefix}-mode`}>- <span className={labelClass}>{t("qveris.mode")}</span>- <select- id={`${idPrefix}-mode`}- value={form.mode}- onChange={(event) => {- const mode = event.target.value as QVerisMode;- setForm({ ...form, mode, enabled: mode === "paid" });- }}- className={fieldClass}- disabled={loading}- >- <option value="free">{t("qveris.modeFree")}</option>- <option value="paid">{t("qveris.modePaid")}</option>- </select>- </label>-- <label className="grid gap-2" htmlFor={`${idPrefix}-budget`}>- <span className={labelClass}>{t("qveris.budget")}</span>- <input- id={`${idPrefix}-budget`}- type="number"- min={0}- step={1}- value={form.budget_credits_per_session}- onChange={(event) => setForm({ ...form, budget_credits_per_session: Number(event.target.value) })}- className={fieldClass}- disabled={loading}- />- <span className={hintClass}>{t("qveris.budgetHint")}</span>- </label>- </div>-- <button- type="submit"- disabled={loading || saving}- className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70"- >- {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}- {t("qveris.save")}- </button>- </div>-- <div className="grid gap-4">- <div className="rounded-md border bg-muted/20 p-4">- <div className="mb-3 flex items-center justify-between gap-3">- <span className="text-sm font-medium">{t("qveris.balance")}</span>- {loading ? <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" /> : null}- </div>- <div className="text-2xl font-semibold">- {status?.remaining_credits ?? t("qveris.notConfigured")}- </div>- {status?.error ? <p className="mt-2 text-xs text-destructive">{status.error}</p> : null}- </div>-- <div className="rounded-md border bg-muted/20 p-4">- <div className="mb-3 text-sm font-medium">{t("qveris.recentUsage")}</div>- {recent.length ? (- <div className="space-y-2">- {recent.map((item) => (- <div key={`${item.ts}-${item.tool_id}`} className="rounded-md border bg-background px-3 py-2 text-xs">- <div className="flex items-center justify-between gap-3">- <span className="font-medium">{item.tool_id}</span>- <span className="text-muted-foreground">{item.cost}</span>- </div>- <div className="mt-1 flex items-center justify-between gap-3 text-muted-foreground">- <span>{item.ts}</span>- <span>{item.charge_outcome}</span>- </div>- </div>- ))}- </div>- ) : (- <p className="text-sm text-muted-foreground">{t("qveris.noUsage")}</p>- )}- </div>-- <div className="rounded-md border bg-muted/20 p-4">- <div className="mb-2 text-sm font-medium">{t("qveris.signupHint")}</div>- <div className="text-xs text-muted-foreground">{t("qveris.inviteCode")}</div>- <div className="mt-1 break-all font-mono text-sm">{inviteCode || t("qveris.notConfigured")}</div>- </div>- </div>- </form>- </section>- );-}diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 1b67d0366..b7f9d278d 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "شريك البيانات · Gildata",+ "website": "الوصول إلى MCP والتسجيل",+ "features": "ميزات Gildata الاختيارية",+ "optInHelp": "الميزات التسع معطلة افتراضيًا. وجود رمز وصول محفوظ لا يفعّل أي ميزة، حتى بعد الترقية. حتى عند تفعيل الأسعار، لا يُستخدم Gildata إلا عند اختياره صراحةً. لا تتحول المصادر المجانية إليه تلقائيًا عند تعذّر جلب البيانات.",+ "fund_nav": "صافي قيمة أصول الصناديق",+ "macro_series": "مؤشرات الاقتصاد الكلي الصيني",+ "announcements": "إعلانات الشركات والصناديق",+ "broker_reports": "تقارير أبحاث الوساطة",+ "market_quotes": "أسعار السوق (عند طلب Gildata صراحةً فقط)",+ "fin_query": "الاستعلامات المالية المجمّعة",+ "stock_selection": "فرز الأسهم",+ "symbol_search": "تضمين Gildata في البحث عن الأوراق المالية",+ "shannon": "تشخيص المحفظة (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1153,29 +1168,6 @@"tushareTokenDesc": "يُستخدم لبيانات الأسهم الصينية (فئة A) والعقود الآجلة والصناديق والاقتصاد الكلي. إذا لم يُضبط، يتراجع المشروع إلى AKShare حيثما توفر.","gildataTokenDesc": "بيانات Gildata الاختيارية: أسعار يومية معدّلة لأسهم الصين A، وأسعار خام لأسهم هونغ كونغ والمؤشرات، وصافي قيمة أصول الصناديق غير المتداولة في البورصة، وأدوات الاقتصاد الكلي والإعلانات والأبحاث الصينية."},- "qveris": {- "title": "سوق أدوات QVeris",- "subtitle": "أبقِ البيانات العامة المجانية كخيار افتراضي، وفعّل تنفيذ QVeris المدفوع عند الحاجة فقط.",- "enabled": "تفعيل مسار QVeris المدفوع",- "baseUrl": "عنوان URL الأساسي",- "apiKey": "مفتاح API",- "apiKeyPlaceholder": "اتركه فارغًا للاحتفاظ بالمفتاح الحالي",- "mode": "الوضع",- "modeFree": "البيانات العامة المجانية فقط",- "modePaid": "تفعيل QVeris المدفوع",- "budget": "رصيد Credits لكل جلسة",- "budgetHint": "يتوقف التنفيذ المدفوع عند بلوغ ميزانية هذه الجلسة.",- "balance": "Credits المتبقية",- "recentUsage": "الاستخدام الأخير",- "noUsage": "لا يوجد استخدام حديث",- "signupCta": "فتح التسجيل",- "signupHint": "استخدم رمز الدعوة هذا عند إنشاء حساب QVeris.",- "inviteCode": "رمز الدعوة",- "save": "حفظ إعدادات QVeris",- "saved": "تم حفظ إعدادات QVeris",- "testFailed": "فشل طلب QVeris",- "notConfigured": "غير مكوّن"- },"agent": {"reasoningStrength": "جهد الاستدلال","unknownProvider": "مزوّد غير معروف",@@ -2092,9 +2084,6 @@"pattern": "اكتشاف أنماط المخطط","portfolio_risk_xray": "فحص مخاطر المحفظة بعمق","propose_mandate_profiles": "اقتراح تفويضات التداول",- "qveris_execute": "تنفيذ إجراء QVeris",- "qveris_inspect": "فحص إجراء QVeris",- "qveris_search": "البحث في QVeris","read_document": "قراءة مستند","read_file": "قراءة ملف","read_url": "قراءة صفحة ويب",diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.jsonindex f6387bbe2..43f54237b 100644--- a/frontend/src/i18n/locales/de.json+++ b/frontend/src/i18n/locales/de.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "Datenpartner · Gildata",+ "website": "MCP-Zugang und Registrierung",+ "features": "Optionale Gildata-Funktionen",+ "optInHelp": "Alle neun Funktionen sind standardmäßig ausgeschaltet. Ein gespeichertes Token aktiviert auch nach einem Update keine davon. Selbst bei aktivierten Kursdaten wird Gildata nur auf ausdrückliche Auswahl genutzt. Liefern kostenlose Quellen keine Daten, wird Gildata nicht automatisch abgefragt.",+ "fund_nav": "Nettoinventarwerte von Fonds",+ "macro_series": "Chinesische Konjunkturindikatoren",+ "announcements": "Unternehmens- und Fondsmitteilungen",+ "broker_reports": "Analystenberichte von Brokern",+ "market_quotes": "Marktdaten (nur bei ausdrücklicher Auswahl von Gildata)",+ "fin_query": "Kombinierte Finanzabfragen",+ "stock_selection": "Aktienfilter",+ "symbol_search": "Gildata in die Wertpapiersuche einbeziehen",+ "shannon": "Portfoliodiagnose (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1159,29 +1174,6 @@"tushareTokenDesc": "Verwendet für China-A-Aktien, Futures, Fonds und Makrodaten. Falls nicht gesetzt, greift das Projekt auf AKShare zurück, sofern verfügbar.","gildataTokenDesc": "Optionale Gildata-Daten: bereinigte Tageskurse chinesischer A-Aktien, unbereinigte Hongkong- und Indexkurse, Nettoinventarwerte nicht börsengehandelter Fonds sowie chinesische Makro-, Mitteilungs- und Research-Tools."},- "qveris": {- "title": "QVeris-Tool-Marktplatz",- "subtitle": "Behalten Sie kostenlose öffentliche Daten als Standard, oder aktivieren Sie kostenpflichtige QVeris-Ausführung für spezielle Datenwerkzeuge.",- "enabled": "Kostenpflichtige QVeris-Route aktivieren",- "baseUrl": "Basis-URL",- "apiKey": "API-Schlüssel",- "apiKeyPlaceholder": "Leer lassen, um den aktuellen Schlüssel beizubehalten",- "mode": "Modus",- "modeFree": "Nur kostenlose öffentliche Daten",- "modePaid": "Kostenpflichtiges QVeris aktiviert",- "budget": "Budget-Kreditpunkte pro Sitzung",- "budgetHint": "Die kostenpflichtige Ausführung stoppt, wenn das Sitzungsbudget erreicht ist.",- "balance": "Verbleibende Kreditpunkte",- "recentUsage": "Letzte Nutzung",- "noUsage": "Keine letzte Nutzung",- "signupCta": "Registrierung öffnen",- "signupHint": "Verwenden Sie diesen Einladungscode bei der Erstellung Ihres QVeris-Kontos.",- "inviteCode": "Einladungscode",- "save": "QVeris-Einstellungen speichern",- "saved": "QVeris-Einstellungen gespeichert",- "testFailed": "QVeris-Anfrage fehlgeschlagen",- "notConfigured": "Nicht konfiguriert"- },"agent": {"reasoningStrength": "Reasoning-Aufwand","unknownProvider": "Unbekannter Anbieter",@@ -2092,9 +2084,6 @@"pattern": "Chart-Muster erkennen","portfolio_risk_xray": "Portfolio-Risiko durchleuchten","propose_mandate_profiles": "Trading-Mandate vorschlagen",- "qveris_execute": "QVeris-Aktion ausführen",- "qveris_inspect": "QVeris-Aktion inspizieren",- "qveris_search": "QVeris durchsuchen","read_document": "Dokument lesen","read_file": "Datei lesen","read_url": "Webseite lesen",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 842a50c2e..34c68913c 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "Data partner · Gildata",+ "website": "MCP access and registration",+ "features": "Optional Gildata features",+ "optInHelp": "All nine features are off by default. A saved token alone enables none of them, including after an upgrade. Even with market quotes enabled, Gildata is used only when explicitly selected. Free sources never fall back to Gildata.",+ "fund_nav": "Fund NAV history",+ "macro_series": "China macro indicators",+ "announcements": "Company and fund announcements",+ "broker_reports": "Broker research reports",+ "market_quotes": "Market quotes (explicit Gildata requests only)",+ "fin_query": "Combined financial queries",+ "stock_selection": "Stock screening",+ "symbol_search": "Include Gildata in symbol searches",+ "shannon": "Portfolio diagnosis (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1159,29 +1174,6 @@"tushareTokenDesc": "Used for China A-share, futures, fund, and macro data. If unset, the project falls back to AKShare where available.","gildataTokenDesc": "Optional Gildata data: adjusted A-share daily bars, raw HK/index bars, OTC fund NAVs, and China macro, announcement and research tools."},- "qveris": {- "title": "QVeris Tool Marketplace",- "subtitle": "Keep free public data as the default, or enable paid QVeris execution for specialized data tools.",- "enabled": "Enable paid QVeris route",- "baseUrl": "Base URL",- "apiKey": "API key",- "apiKeyPlaceholder": "Leave blank to keep the current key",- "mode": "Mode",- "modeFree": "Free public data only",- "modePaid": "Paid QVeris enabled",- "budget": "Budget credits per session",- "budgetHint": "Paid execution stops when this session budget is reached.",- "balance": "Remaining credits",- "recentUsage": "Recent usage",- "noUsage": "No recent usage",- "signupCta": "Open signup",- "signupHint": "Use this invitation code when creating your QVeris account.",- "inviteCode": "Invitation code",- "save": "Save QVeris settings",- "saved": "QVeris settings saved",- "testFailed": "QVeris request failed",- "notConfigured": "Not configured"- },"agent": {"reasoningStrength": "Reasoning Effort","unknownProvider": "Unknown provider",@@ -2092,9 +2084,6 @@"pattern": "Detect chart patterns","portfolio_risk_xray": "X-ray portfolio risk","propose_mandate_profiles": "Propose trading mandates",- "qveris_execute": "Execute QVeris action",- "qveris_inspect": "Inspect QVeris action",- "qveris_search": "Search QVeris","read_document": "Read document","read_file": "Read file","read_url": "Read webpage",diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.jsonindex eb43e679d..d22779786 100644--- a/frontend/src/i18n/locales/es.json+++ b/frontend/src/i18n/locales/es.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "Socio de datos · Gildata",+ "website": "Acceso MCP y registro",+ "features": "Funciones opcionales de Gildata",+ "optInHelp": "Las nueve funciones están desactivadas por defecto. Guardar un token no activa ninguna, tampoco al actualizar. Incluso con las cotizaciones activadas, Gildata solo se usa si se selecciona expresamente. Si una fuente gratuita falla, no se recurre a Gildata.",+ "fund_nav": "Valor liquidativo de fondos",+ "macro_series": "Indicadores macroeconómicos de China",+ "announcements": "Anuncios de empresas y fondos",+ "broker_reports": "Informes de análisis de intermediarios",+ "market_quotes": "Cotizaciones (solo al seleccionar Gildata expresamente)",+ "fin_query": "Consultas financieras combinadas",+ "stock_selection": "Selección de acciones",+ "symbol_search": "Incluir Gildata en la búsqueda de valores",+ "shannon": "Diagnóstico de cartera (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1159,29 +1174,6 @@"tushareTokenDesc": "Usado para datos de acciones A, futuros, fondos y macro de China. Si no se configura, el proyecto recurre a AKShare cuando está disponible.","gildataTokenDesc": "Datos opcionales de Gildata: precios diarios ajustados de acciones A, precios sin ajustar de Hong Kong e índices, valores liquidativos de fondos no cotizados y herramientas de macroeconomía, anuncios y análisis de China."},- "qveris": {- "title": "Mercado de herramientas QVeris",- "subtitle": "Mantén los datos públicos gratuitos como predeterminados, o habilita la ejecución paga de QVeris para herramientas de datos especializadas.",- "enabled": "Habilitar ruta paga de QVeris",- "baseUrl": "URL base",- "apiKey": "Clave de API",- "apiKeyPlaceholder": "Déjalo en blanco para conservar la clave actual",- "mode": "Modo",- "modeFree": "Solo datos públicos gratuitos",- "modePaid": "QVeris paga habilitado",- "budget": "Créditos de presupuesto por sesión",- "budgetHint": "La ejecución paga se detiene al alcanzar este presupuesto de sesión.",- "balance": "Créditos restantes",- "recentUsage": "Uso reciente",- "noUsage": "Sin uso reciente",- "signupCta": "Abrir registro",- "signupHint": "Usa este código de invitación al crear tu cuenta de QVeris.",- "inviteCode": "Código de invitación",- "save": "Guardar configuración de QVeris",- "saved": "Configuración de QVeris guardada",- "testFailed": "La solicitud a QVeris falló",- "notConfigured": "No configurado"- },"agent": {"reasoningStrength": "Esfuerzo de razonamiento","unknownProvider": "Proveedor desconocido",@@ -2092,9 +2084,6 @@"pattern": "Detectar patrones de gráfico","portfolio_risk_xray": "Radiografiar riesgo del portafolio","propose_mandate_profiles": "Proponer mandatos de trading",- "qveris_execute": "Ejecutar acción de QVeris",- "qveris_inspect": "Inspeccionar acción de QVeris",- "qveris_search": "Buscar en QVeris","read_document": "Leer documento","read_file": "Leer archivo","read_url": "Leer página web",diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.jsonindex a7e6d06bf..83c0922c2 100644--- a/frontend/src/i18n/locales/fa.json+++ b/frontend/src/i18n/locales/fa.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "شریک داده · Gildata",+ "website": "دسترسی به MCP و ثبتنام",+ "features": "قابلیتهای اختیاری Gildata",+ "optInHelp": "هر نه قابلیت بهطور پیشفرض غیرفعالاند. ذخیره بودن توکن حتی پس از بهروزرسانی هیچ قابلیتی را فعال نمیکند. حتی با فعال بودن قیمتهای بازار، فقط با انتخاب صریح Gildata از آن استفاده میشود. اگر منابع رایگان دادهای ندهند، سامانه خودکار به Gildata رجوع نمیکند.",+ "fund_nav": "خالص ارزش دارایی صندوقها",+ "macro_series": "شاخصهای اقتصاد کلان چین",+ "announcements": "اطلاعیههای شرکتها و صندوقها",+ "broker_reports": "گزارشهای پژوهشی کارگزاریها",+ "market_quotes": "قیمتهای بازار (فقط با انتخاب صریح Gildata)",+ "fin_query": "پرسوجوی ترکیبی دادههای مالی",+ "stock_selection": "غربالگری سهام",+ "symbol_search": "استفاده از Gildata در جستوجوی نمادها",+ "shannon": "ارزیابی سبد سهام (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1159,29 +1174,6 @@"tushareTokenDesc": "برای داده سهام A، آینده، صندوق و کلان چین استفاده میشود. اگر تنظیم نشود، در صورت وجود، پروژه به AKShare برمیگردد.","gildataTokenDesc": "داده اختیاری Gildata: قیمت روزانه تعدیلشده سهام A چین، قیمت خام سهام هنگکنگ و شاخصها، خالص ارزش دارایی صندوقهای خارج از بورس، و ابزارهای اقتصاد کلان، اطلاعیه و پژوهش چین."},- "qveris": {- "title": "بازار ابزار QVeris",- "subtitle": "داده عمومی رایگان را پیشفرض نگه دارید، یا اجرای پولی QVeris را برای ابزارهای داده تخصصی فعال کنید.",- "enabled": "فعالسازی مسیر پولی QVeris",- "baseUrl": "URL پایه",- "apiKey": "کلید API",- "apiKeyPlaceholder": "برای حفظ کلید فعلی خالی بگذارید",- "mode": "حالت",- "modeFree": "فقط داده عمومی رایگان",- "modePaid": "اجرای پولی QVeris فعال",- "budget": "اعتبار بودجه هر نشست",- "budgetHint": "اجرای پولی با رسیدن به بودجه این نشست متوقف میشود.",- "balance": "اعتبار باقیمانده",- "recentUsage": "مصرف اخیر",- "noUsage": "مصرف اخیری وجود ندارد",- "signupCta": "ثبتنام",- "signupHint": "هنگام ساخت حساب QVeris از این کد دعوت استفاده کنید.",- "inviteCode": "کد دعوت",- "save": "ذخیره تنظیمات QVeris",- "saved": "تنظیمات QVeris ذخیره شد",- "testFailed": "درخواست QVeris ناموفق بود",- "notConfigured": "پیکربندی نشده"- },"agent": {"reasoningStrength": "عمق استدلال","unknownProvider": "ارائهدهنده ناشناخته",@@ -2092,9 +2084,6 @@"pattern": "تشخیص الگوهای چارت","portfolio_risk_xray": "اشعه ریسک پورتفولیو","propose_mandate_profiles": "پیشنهاد ماندیتهای معاملاتی",- "qveris_execute": "اجرای کنش QVeris",- "qveris_inspect": "بازرسی کنش QVeris",- "qveris_search": "جستجوی QVeris","read_document": "خواندن سند","read_file": "خواندن فایل","read_url": "خواندن صفحه وب",diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.jsonindex 8c3b74ed6..35eeabece 100644--- a/frontend/src/i18n/locales/id.json+++ b/frontend/src/i18n/locales/id.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "Mitra data · Gildata",+ "website": "Akses MCP dan pendaftaran",+ "features": "Fitur opsional Gildata",+ "optInHelp": "Kesembilan fitur nonaktif secara bawaan. Token yang tersimpan tidak mengaktifkan fitur apa pun, termasuk setelah pembaruan. Meski fitur harga pasar aktif, Gildata hanya digunakan jika dipilih secara eksplisit. Jika sumber gratis gagal, sistem tidak beralih ke Gildata.",+ "fund_nav": "Nilai aktiva bersih reksa dana",+ "macro_series": "Indikator makroekonomi Tiongkok",+ "announcements": "Pengumuman perusahaan dan reksa dana",+ "broker_reports": "Laporan riset broker",+ "market_quotes": "Harga pasar (hanya jika Gildata dipilih secara eksplisit)",+ "fin_query": "Kueri keuangan gabungan",+ "stock_selection": "Penyaringan saham",+ "symbol_search": "Sertakan Gildata dalam pencarian efek",+ "shannon": "Diagnosis portofolio (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1159,29 +1174,6 @@"tushareTokenDesc": "Digunakan untuk data A-share China, futures, fund, dan makro. Jika tidak diatur, proyek akan menggunakan AKShare sebagai fallback jika tersedia.","gildataTokenDesc": "Data Gildata opsional: harga harian saham A yang disesuaikan, harga mentah saham Hong Kong/indeks, NAB reksa dana di luar bursa, serta alat makroekonomi, pengumuman, dan riset Tiongkok."},- "qveris": {- "title": "Marketplace Tool QVeris",- "subtitle": "Gunakan data publik gratis sebagai pilihan bawaan, atau aktifkan eksekusi QVeris berbayar untuk tool data khusus.",- "enabled": "Aktifkan rute QVeris berbayar",- "baseUrl": "URL Dasar",- "apiKey": "API key",- "apiKeyPlaceholder": "Biarkan kosong untuk mempertahankan key saat ini",- "mode": "Mode",- "modeFree": "Hanya data publik gratis",- "modePaid": "QVeris berbayar diaktifkan",- "budget": "Anggaran kredit per sesi",- "budgetHint": "Eksekusi berbayar berhenti saat anggaran sesi ini tercapai.",- "balance": "Sisa kredit",- "recentUsage": "Penggunaan terbaru",- "noUsage": "Belum ada penggunaan terbaru",- "signupCta": "Buka pendaftaran",- "signupHint": "Gunakan kode undangan ini saat membuat akun QVeris.",- "inviteCode": "Kode undangan",- "save": "Simpan pengaturan QVeris",- "saved": "Pengaturan QVeris tersimpan",- "testFailed": "Permintaan QVeris gagal",- "notConfigured": "Belum dikonfigurasi"- },"agent": {"reasoningStrength": "Tingkat Reasoning","unknownProvider": "Provider tidak diketahui",@@ -2092,9 +2084,6 @@"pattern": "Deteksi pola chart","portfolio_risk_xray": "X-ray risiko portofolio","propose_mandate_profiles": "Usulkan mandat trading",- "qveris_execute": "Jalankan aksi QVeris",- "qveris_inspect": "Periksa aksi QVeris",- "qveris_search": "Cari QVeris","read_document": "Baca dokumen","read_file": "Baca file","read_url": "Baca halaman web",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 9c16ef195..b853448e2 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "データパートナー · Gildata",+ "website": "MCPの利用と登録",+ "features": "Gildataのオプション機能",+ "optInHelp": "9つの機能はすべて初期設定で無効です。アップグレード前にトークンを保存していても、使う機能を個別に有効にしてください。相場データを有効にしても、Gildataを明示した場合のみ利用します。無料ソースで取得できない場合の自動切り替えはありません。",+ "fund_nav": "投資信託の基準価額",+ "macro_series": "中国のマクロ経済指標",+ "announcements": "企業・ファンドの公告",+ "broker_reports": "証券会社の調査レポート",+ "market_quotes": "相場データ(Gildataを明示した場合のみ)",+ "fin_query": "財務・市場データの一括照会",+ "stock_selection": "銘柄スクリーニング",+ "symbol_search": "銘柄検索にGildataの候補を含める",+ "shannon": "保有銘柄の診断(Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1153,29 +1168,6 @@"tushareTokenDesc": "中国A株・先物・ファンド・マクロデータに使用します。未設定の場合、利用可能なところではAKShareにフォールバックします。","gildataTokenDesc": "任意の Gildata データ:A株の調整済み日足、香港株・指数の未調整価格、店頭投資信託の基準価額、中国のマクロ経済・公告・調査レポートツール。"},- "qveris": {- "title": "QVeris ツールマーケットプレイス",- "subtitle": "無料の公開データを既定のまま使い、必要なときだけ QVeris の有料実行を有効にします。",- "enabled": "QVeris 有料ルートを有効化",- "baseUrl": "ベース URL",- "apiKey": "API キー",- "apiKeyPlaceholder": "空欄で現在のキーを保持",- "mode": "モード",- "modeFree": "無料公開データのみ",- "modePaid": "QVeris 有料を有効化",- "budget": "セッションごとの予算 Credits",- "budgetHint": "このセッション予算に達すると有料実行を停止します。",- "balance": "残り Credits",- "recentUsage": "最近の使用量",- "noUsage": "最近の使用量はありません",- "signupCta": "登録を開く",- "signupHint": "QVeris アカウント作成時にこの招待コードを使用してください。",- "inviteCode": "招待コード",- "save": "QVeris 設定を保存",- "saved": "QVeris 設定を保存しました",- "testFailed": "QVeris リクエストに失敗しました",- "notConfigured": "未設定"- },"agent": {"reasoningStrength": "推論強度","unknownProvider": "不明なプロバイダー",@@ -2092,9 +2084,6 @@"pattern": "チャートパターンを検出","portfolio_risk_xray": "ポートフォリオリスクを精査","propose_mandate_profiles": "取引マンデートを提案",- "qveris_execute": "QVeris アクションを実行",- "qveris_inspect": "QVeris アクションを確認",- "qveris_search": "QVeris を検索","read_document": "ドキュメントを読む","read_file": "ファイルを読む","read_url": "Web ページを読む",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 3095ecd0d..a60098564 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "데이터 파트너 · Gildata",+ "website": "MCP 이용 및 가입",+ "features": "Gildata 선택 기능",+ "optInHelp": "아홉 가지 기능은 기본적으로 모두 꺼져 있습니다. 업그레이드 전에 토큰을 저장했어도 사용할 기능을 개별적으로 켜야 합니다. 시세 기능을 켜도 Gildata를 직접 지정할 때만 사용합니다. 무료 소스에서 데이터를 찾지 못해도 자동으로 전환되지 않습니다.",+ "fund_nav": "펀드 기준가",+ "macro_series": "중국 거시경제 지표",+ "announcements": "기업 및 펀드 공시",+ "broker_reports": "증권사 리서치 보고서",+ "market_quotes": "시세 (Gildata를 직접 지정한 경우만)",+ "fin_query": "재무·시장 데이터 통합 조회",+ "stock_selection": "종목 선별",+ "symbol_search": "종목 검색에 Gildata 후보 포함",+ "shannon": "포트폴리오 진단 (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1153,29 +1168,6 @@"tushareTokenDesc": "중국 A주·선물·펀드·거시 데이터에 사용됩니다. 설정하지 않으면 가능한 경우 AKShare로 대체됩니다.","gildataTokenDesc": "선택적 Gildata 데이터: A주 수정 일봉, 홍콩 주식·지수의 원시 시세, 장외 펀드 순자산가치, 중국 거시경제·공시·리서치 도구."},- "qveris": {- "title": "QVeris 도구 마켓플레이스",- "subtitle": "무료 공개 데이터 경로를 기본으로 두고, 필요할 때만 QVeris 유료 실행을 켭니다.",- "enabled": "QVeris 유료 경로 활성화",- "baseUrl": "기본 URL",- "apiKey": "API 키",- "apiKeyPlaceholder": "비우면 현재 키 유지",- "mode": "모드",- "modeFree": "무료 공개 데이터만 사용",- "modePaid": "QVeris 유료 활성화",- "budget": "세션당 예산 Credits",- "budgetHint": "이 세션 예산에 도달하면 유료 실행을 중지합니다.",- "balance": "남은 Credits",- "recentUsage": "최근 사용량",- "noUsage": "최근 사용량 없음",- "signupCta": "가입 열기",- "signupHint": "QVeris 계정을 만들 때 이 초대 코드를 사용하세요.",- "inviteCode": "초대 코드",- "save": "QVeris 설정 저장",- "saved": "QVeris 설정이 저장되었습니다",- "testFailed": "QVeris 요청 실패",- "notConfigured": "구성되지 않음"- },"agent": {"reasoningStrength": "추론 강도","unknownProvider": "알 수 없는 제공자",@@ -2092,9 +2084,6 @@"pattern": "차트 패턴 감지","portfolio_risk_xray": "포트폴리오 위험 정밀 분석","propose_mandate_profiles": "거래 운용 권한 제안",- "qveris_execute": "QVeris 작업 실행",- "qveris_inspect": "QVeris 작업 점검",- "qveris_search": "QVeris 검색","read_document": "문서 읽기","read_file": "파일 읽기","read_url": "웹페이지 읽기",diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.jsonindex 7044b3f63..533a6cff1 100644--- a/frontend/src/i18n/locales/pt-BR.json+++ b/frontend/src/i18n/locales/pt-BR.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "Parceiro de dados · Gildata",+ "website": "Acesso ao MCP e cadastro",+ "features": "Recursos opcionais da Gildata",+ "optInHelp": "Os nove recursos vêm desativados. Um token já salvo não ativa nenhum deles, mesmo após uma atualização. Mesmo com as cotações ativadas, o Gildata só é usado quando selecionado explicitamente. Se as fontes gratuitas falharem, o sistema não recorre ao Gildata.",+ "fund_nav": "Valor patrimonial das cotas de fundos",+ "macro_series": "Indicadores macroeconômicos da China",+ "announcements": "Comunicados de empresas e fundos",+ "broker_reports": "Relatórios de análise de corretoras",+ "market_quotes": "Cotações (somente ao selecionar Gildata explicitamente)",+ "fin_query": "Consultas financeiras combinadas",+ "stock_selection": "Triagem de ações",+ "symbol_search": "Incluir a Gildata na busca de ativos",+ "shannon": "Diagnóstico de carteira (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1159,29 +1174,6 @@"tushareTokenDesc": "Usado para ações A da China, futuros, fundos e dados macro. Se não for definido, o projeto volta para o AKShare, quando disponível.","gildataTokenDesc": "Dados opcionais da Gildata: preços diários ajustados de ações A, preços brutos de Hong Kong e índices, valores patrimoniais de fundos não negociados em bolsa e ferramentas de macroeconomia, comunicados e pesquisa da China."},- "qveris": {- "title": "Mercado de ferramentas QVeris",- "subtitle": "Mantenha os dados públicos gratuitos como padrão ou ative a execução paga do QVeris para ferramentas de dados especializadas.",- "enabled": "Habilitar rota QVeris paga",- "baseUrl": "URL base",- "apiKey": "Chave de API",- "apiKeyPlaceholder": "Deixe em branco para manter a chave atual",- "mode": "Modo",- "modeFree": "Somente dados públicos gratuitos",- "modePaid": "QVeris pago ativado",- "budget": "Créditos de orçamento por sessão",- "budgetHint": "A execução paga é interrompida quando o orçamento da sessão é atingido.",- "balance": "Créditos restantes",- "recentUsage": "Uso recente",- "noUsage": "Nenhum uso recente",- "signupCta": "Abrir inscrição",- "signupHint": "Use este código de convite ao criar sua conta QVeris.",- "inviteCode": "Código de convite",- "save": "Salvar configurações do QVeris",- "saved": "Configurações do QVeris salvas",- "testFailed": "Falha na solicitação QVeris",- "notConfigured": "Não configurado"- },"agent": {"reasoningStrength": "Esforço de raciocínio","unknownProvider": "Provedor desconhecido",@@ -2092,9 +2084,6 @@"pattern": "Detectar padrões gráficos","portfolio_risk_xray": "Risco do portfólio de raios X","propose_mandate_profiles": "Propor mandatos comerciais",- "qveris_execute": "Executar ação QVeris",- "qveris_inspect": "Inspecione a ação do QVeris",- "qveris_search": "Pesquisar QVeris","read_document": "Ler documento","read_file": "Ler arquivo","read_url": "Ler página da web",diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.jsonindex d378f3114..02bfae210 100644--- a/frontend/src/i18n/locales/tr.json+++ b/frontend/src/i18n/locales/tr.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "Veri ortağı · Gildata",+ "website": "MCP erişimi ve kayıt",+ "features": "İsteğe bağlı Gildata özellikleri",+ "optInHelp": "Dokuz özelliğin tümü varsayılan olarak kapalıdır. Kayıtlı bir token, güncellemeden sonra da hiçbir özelliği kendiliğinden açmaz. Piyasa fiyatları açık olsa bile Gildata yalnızca açıkça seçildiğinde kullanılır. Ücretsiz kaynaklar veri sağlamazsa Gildata’ya otomatik geçiş yapılmaz.",+ "fund_nav": "Fonların net varlık değerleri",+ "macro_series": "Çin makroekonomik göstergeleri",+ "announcements": "Şirket ve fon duyuruları",+ "broker_reports": "Aracı kurum araştırma raporları",+ "market_quotes": "Piyasa fiyatları (yalnızca Gildata açıkça seçildiğinde)",+ "fin_query": "Birleşik finansal sorgular",+ "stock_selection": "Hisse tarama",+ "symbol_search": "Menkul kıymet aramalarına Gildata sonuçlarını ekle",+ "shannon": "Portföy analizi (Shannon)"+ },"app": {"version": "v0.1.18"},@@ -1121,29 +1136,6 @@"reasoningEffortXhigh": "Çok yüksek","reasoningEffortReset": "Seçilen model {{level}} düzeyini desteklemiyor; sağlayıcı varsayılanına sıfırlandı."},- "qveris": {- "title": "QVeris araç pazarı",- "subtitle": "Ücretsiz açık veriyi varsayılan tutun veya özel veri araçları için ücretli QVeris kullanımını etkinleştirin.",- "enabled": "Ücretli QVeris yolunu etkinleştir",- "baseUrl": "Temel URL",- "apiKey": "API anahtarı",- "apiKeyPlaceholder": "Mevcut anahtarı korumak için boş bırakın",- "mode": "Mod",- "modeFree": "Yalnızca ücretsiz açık veri",- "modePaid": "Ücretli QVeris etkin",- "budget": "Oturum başına kredi bütçesi",- "budgetHint": "Bu oturum bütçesine ulaşıldığında ücretli işlemler durur.",- "balance": "Kalan kredi",- "recentUsage": "Son kullanım",- "noUsage": "Yakın zamanda kullanım yok",- "signupCta": "Kayıt sayfasını aç",- "signupHint": "QVeris hesabınızı oluştururken bu davet kodunu kullanın.",- "inviteCode": "Davet kodu",- "save": "QVeris ayarlarını kaydet",- "saved": "QVeris ayarları kaydedildi",- "testFailed": "QVeris isteği başarısız",- "notConfigured": "Yapılandırılmadı"- },"agent": {"reasoningStrength": "Akıl yürütme düzeyi","unknownProvider": "Bilinmeyen sağlayıcı",@@ -2054,9 +2046,6 @@"pattern": "Grafik formasyonlarını tespit et","portfolio_risk_xray": "Portföy riskini incele","propose_mandate_profiles": "İşlem yetkisi öner",- "qveris_execute": "QVeris işlemini yürüt",- "qveris_inspect": "QVeris işlemini incele",- "qveris_search": "QVeris’te ara","read_document": "Belgeyi oku","read_file": "Dosyayı oku","read_url": "Web sayfasını oku",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 8b7dfda6a..0fb8245cf 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -1,4 +1,19 @@{+ "gildata": {+ "partner": "数据合作方 · 恒生聚源",+ "website": "MCP 服务与个人注册",+ "features": "聚源可选功能",+ "optInHelp": "九项功能默认全部关闭。即使升级前已保存 Token,也要逐项手动开启。开启行情后,只有明确指定聚源才会使用;免费源查不到时不会自动转用聚源。",+ "fund_nav": "场外基金净值",+ "macro_series": "中国宏观指标",+ "announcements": "公司和基金公告",+ "broker_reports": "券商研报",+ "market_quotes": "聚源行情(仅在指定聚源时使用)",+ "fin_query": "综合问数",+ "stock_selection": "智能选股",+ "symbol_search": "证券搜索时查询聚源候选",+ "shannon": "持仓诊断(香农)"+ },"app": {"version": "v0.1.18"},@@ -1153,29 +1168,6 @@"tushareTokenDesc": "用于中国 A 股、期货、基金和宏观数据。没填的话会自动改用 AKShare 的免费数据。","gildataTokenDesc": "可选的海量数据:A 股复权日线、港股及指数原始行情、场外基金净值,以及中国宏观、公告和研报工具。"},- "qveris": {- "title": "QVeris 工具市场",- "subtitle": "默认继续使用免费公开数据;需要专业付费数据时再启用 QVeris。",- "enabled": "启用 QVeris 付费通道",- "baseUrl": "基础 URL",- "apiKey": "API 密钥",- "apiKeyPlaceholder": "留空以保留当前密钥",- "mode": "模式",- "modeFree": "仅使用免费公开数据",- "modePaid": "启用 QVeris 付费",- "budget": "每会话预算 Credits",- "budgetHint": "达到本会话预算后将停止付费执行。",- "balance": "剩余 Credits",- "recentUsage": "近期用量",- "noUsage": "暂无近期用量",- "signupCta": "打开注册",- "signupHint": "创建 QVeris 账户时使用此邀请码。",- "inviteCode": "邀请码",- "save": "保存 QVeris 设置",- "saved": "QVeris 设置已保存",- "testFailed": "QVeris 请求失败",- "notConfigured": "未配置"- },"agent": {"reasoningStrength": "推理强度","unknownProvider": "未知提供商",@@ -2092,9 +2084,6 @@"pattern": "识别图表形态","portfolio_risk_xray": "透视组合风险","propose_mandate_profiles": "推荐交易授权",- "qveris_execute": "执行QVeris操作",- "qveris_inspect": "检查QVeris操作",- "qveris_search": "搜索QVeris","read_document": "读取文档","read_file": "读取文件","read_url": "读取网页",diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 78c4a1381..78748adac 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1081,7 +1081,21 @@ export interface SourceOrderUpdate {order?: string[] | null;}+export const gildataFeatures = [+ "fin_query",+ "stock_selection",+ "symbol_search",+ "shannon",+ "market_quotes",+ "fund_nav",+ "macro_series",+ "announcements",+ "broker_reports",+] as const;+export type GildataFeature = typeof gildataFeatures[number];+export interface DataSourceSettings {+ gildata_features?: GildataFeature[];tushare_token_configured: boolean;tushare_token_hint?: string | null;gildata_token_configured: boolean;@@ -1094,6 +1108,7 @@ export interface DataSourceSettings {}export interface UpdateDataSourceSettingsRequest {+ gildata_features?: GildataFeature[];tushare_token?: string;clear_tushare_token?: boolean;gildata_token?: string;diff --git a/frontend/src/pages/Correlation.tsx b/frontend/src/pages/Correlation.tsxindex 03bd44988..4fa16e578 100644--- a/frontend/src/pages/Correlation.tsx+++ b/frontend/src/pages/Correlation.tsx@@ -5,16 +5,37 @@ import { CorrelationMatrix } from "@/components/charts/CorrelationMatrix";import { RegimeTimeline } from "@/components/charts/RegimeTimeline";import { api, type CorrelationAnalysisResponse } from "@/lib/api";import { useAnalysisState } from "@/hooks/useAnalysisState";+import { shannon } from "@/lib/shannon";import { ShannonPortfolio } from "@/components/charts/ShannonPortfolio";const WINDOWS = [30, 60, 90, 180, 365] as const;export function Correlation() {const [tab, setTab] = useState("correlation");+ const [available, setAvailable] = useState(false);+ useEffect(() => {+ let controller: AbortController;+ function refresh() {+ controller?.abort();+ const signal = (controller = new AbortController()).signal;+ shannon.status(signal).then(status => update(status.configured)).catch(() => update(false));+ function update(enabled: boolean) {+ if (signal.aborted) return;+ setAvailable(enabled);+ if (!enabled) setTab("correlation");+ }+ }+ refresh();+ window.addEventListener("focus", refresh);+ return () => {+ controller.abort();+ window.removeEventListener("focus", refresh);+ };+ }, []);return <>- <div className="mx-auto flex max-w-5xl gap-2 px-6 pt-6" role="tablist" aria-label={i18n.language.startsWith("zh") ? "分析类型" : "Analysis type"}>- {[["correlation", i18n.t("correlation.title")], ["shannon", i18n.language.startsWith("zh") ? "持仓诊断(香农)" : "Portfolio diagnosis (Shannon)"]].map(([key, label]) => <button key={key} role="tab" aria-selected={tab === key} onClick={() => setTab(key)} className={`rounded-lg border px-4 py-2 text-sm ${tab === key ? "bg-primary text-primary-foreground" : "hover:bg-muted"}`}>{label}</button>)}- </div>+ {available && <div className="mx-auto flex max-w-5xl gap-2 px-6 pt-6" role="tablist" aria-label={i18n.t("correlation.title")}>+ {[["correlation", i18n.t("correlation.title")], ["shannon", i18n.t("gildata.shannon")]].map(([key, label]) => <button key={key} role="tab" aria-selected={tab === key} onClick={() => setTab(key)} className={`rounded-lg border px-4 py-2 text-sm ${tab === key ? "bg-primary text-primary-foreground" : "hover:bg-muted"}`}>{label}</button>)}+ </div>}<div hidden={tab !== "correlation"}><CorrelationAnalysis /></div>{tab === "shannon" && <div className="mx-auto max-w-5xl p-6"><ShannonPortfolio /></div>}</>;diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsxindex 0ff7246c5..380eed819 100644--- a/frontend/src/pages/Settings.tsx+++ b/frontend/src/pages/Settings.tsx@@ -5,9 +5,8 @@ import { toast } from "sonner";import { ChannelSettings } from "@/components/settings/ChannelSettings";import { CustomProviderManager } from "@/components/settings/CustomProviderManager";import { ModelPicker } from "@/components/settings/ModelPicker";-import { QVerisSettings } from "@/components/settings/QVerisSettings"; // QVERIS-INTEGRATIONimport { SourcePrioritySettings } from "@/components/settings/SourcePrioritySettings";-import { api, isAuthRequiredError, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";+import { api, gildataFeatures, type GildataFeature, isAuthRequiredError, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";import { getApiAuthKey, setApiAuthKey } from "@/lib/apiAuth";import { effortLabelKey } from "@/lib/reasoningEffort";@@ -55,6 +54,7 @@ export function Settings() {const [clearApiKey, setClearApiKey] = useState(false);const [tushareToken, setTushareToken] = useState("");const [clearTushareToken, setClearTushareToken] = useState(false);+ const [features, setFeatures] = useState<GildataFeature[]>([]);const [gildataToken, setGildataToken] = useState("");const [clearGildataToken, setClearGildataToken] = useState(false);const [loading, setLoading] = useState(true);@@ -93,6 +93,7 @@ export function Settings() {if (dataSourceResult.status === "fulfilled") {setDataSettings(dataSourceResult.value);+ setFeatures(dataSourceResult.value.gildata_features ?? []);} else {const message = dataSourceResult.reason instanceof Error? dataSourceResult.reason.message@@ -270,6 +271,7 @@ export function Settings() {const updated = await api.updateDataSourceSettings({tushare_token: isDesktop ? undefined : tushareToken.trim() || undefined,clear_tushare_token: isDesktop ? false : clearTushareToken,+ gildata_features: features,gildata_token: isDesktop ? undefined : gildataToken.trim() || undefined,clear_gildata_token: isDesktop ? false : clearGildataToken,});@@ -291,7 +293,7 @@ export function Settings() {setGildataToken("");setClearGildataToken(false);toast.success(t("settings.dataSourceSettingsSaved"));- if (desktop && (tushareToken.trim() || clearTushareToken)) {+ if (desktop && (tushareToken.trim() || clearTushareToken || gildataToken.trim() || clearGildataToken)) {toast.info(t("settings.desktopCredentialRestarting"));await desktop.restartBackend();}@@ -339,6 +341,16 @@ export function Settings() {</form>);+ const partnerSection = (+ <section className="rounded-lg border bg-card p-5">+ <h2 className="text-lg font-semibold">{t("gildata.partner")}</h2>+ <div className="mt-2 flex flex-wrap gap-4 text-sm text-primary underline">+ <a href="https://www.gildata.com/products/datamap" target="_blank" rel="noreferrer">{t("gildata.website")}</a>+ {dataSettings && <a href="#gildata-settings">{t("gildata.features")}</a>}+ </div>+ </section>+ );+if (loading || !form || !settings || !dataSettings) {return (<div className="mx-auto max-w-5xl space-y-6 p-6">@@ -347,8 +359,7 @@ export function Settings() {<p className="max-w-3xl text-sm text-muted-foreground">{t("settings.subtitle")}</p></div>{!isDesktop && localApiAccessSection}- {/* QVERIS-INTEGRATION */}- <QVerisSettings />+ {partnerSection}<div className="flex min-h-32 items-center justify-center rounded-lg border bg-card p-5 text-sm text-muted-foreground">{settingsLoadError ? (<div className="text-center">@@ -393,8 +404,7 @@ export function Settings() {{!isDesktop && localApiAccessSection}- {/* QVERIS-INTEGRATION */}- <QVerisSettings />+ {partnerSection}<ChannelSettings />@@ -403,7 +413,7 @@ export function Settings() {<p className="max-w-3xl text-sm text-muted-foreground">{t("settings.llmSettingsDesc")}</p></div>- {/* Column ratio matches the QVeris and data-source sections so the+ {/* Column ratio matches the data-source section so thecard seams align down the page. */}<form onSubmit={submit} className="grid gap-5 lg:grid-cols-[minmax(0,1.1fr)_minmax(280px,0.9fr)]"><section className="rounded-lg border bg-card p-5 shadow-sm">@@ -691,7 +701,7 @@ export function Settings() {<div className="flex items-start justify-between gap-3"><span className={hintClass}>{t("settings.gildataTokenDesc", {- defaultValue: "Optional Gildata (Hundsun Juyuan) A-share feed. When set, it joins the tail of the A-share fallback chain.",+ defaultValue: "Optional Gildata data credentials.",})}</span><label className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground">@@ -709,6 +719,16 @@ export function Settings() {</div></label>+ <fieldset id="gildata-settings" disabled={dataSaving} className="grid gap-2 rounded-md border p-3">+ <legend className="px-1 text-sm font-medium">{t("gildata.features")}</legend>+ <p className="text-sm text-muted-foreground">{t("gildata.optInHelp")}</p>+ {gildataFeatures.map(feature => <label key={feature} className="flex items-center gap-2 text-sm">+ <input type="checkbox" checked={features.includes(feature)}+ onChange={event => setFeatures(event.target.checked+ ? [...features, feature] : features.filter(item => item !== feature))} />+ {t(`gildata.${feature}`)}+ </label>)}+ </fieldset><div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground"><span className="font-medium text-foreground">{t("settings.saved")}: </span><span className="break-all font-mono">{dataSettings.env_path}</span>diff --git a/frontend/src/pages/__tests__/Correlation.test.tsx b/frontend/src/pages/__tests__/Correlation.test.tsxindex 16cebbc6f..1ff3991d9 100644--- a/frontend/src/pages/__tests__/Correlation.test.tsx+++ b/frontend/src/pages/__tests__/Correlation.test.tsx@@ -1,4 +1,6 @@import { act, fireEvent, render, screen } from "@testing-library/react";+import { shannon } from "@/lib/shannon";+vi.mock("@/lib/shannon", () => ({ shannon: { status: vi.fn() } }));import { Correlation } from "../Correlation";import { clearAnalysisState } from "@/hooks/useAnalysisState";import type { CorrelationAnalysisResponse } from "@/lib/api";@@ -15,7 +17,7 @@ function response(label: string): CorrelationAnalysisResponse {return { correlation: { labels: [label], matrix: [[1]] }, regime: null, errors: {},coverage: { requested: [label], missing: [], observations: 30, first_date: "2026-01-01", last_date: "2026-02-12", diagnostics: {} } };}-beforeEach(() => { clearAnalysisState("correlation"); apiMock.getCorrelationAnalysis.mockReset(); });+beforeEach(() => { vi.mocked(shannon.status).mockResolvedValue({configured: false}); clearAnalysisState("correlation"); apiMock.getCorrelationAnalysis.mockReset(); });it("marks old results and rejects a late response after editing the query", async () => {apiMock.getCorrelationAnalysis.mockResolvedValueOnce(response("OLD"));@@ -53,6 +55,7 @@ it("rejects duplicate assets and accepts Chinese delimiters", () => {});it("keeps correlation as default and retains its result across diagnosis tab switches", async () => {+ vi.mocked(shannon.status).mockResolvedValue({configured: true});apiMock.getCorrelationAnalysis.mockResolvedValue(response("RETAINED"));render(<Correlation />);expect(screen.queryByText("Shannon diagnosis panel")).not.toBeInTheDocument();@@ -65,3 +68,11 @@ it("keeps correlation as default and retains its result across diagnosis tab swiexpect(screen.getByTestId("correlation-result")).toBeVisible();expect(apiMock.getCorrelationAnalysis).toHaveBeenCalledTimes(1);});++it("hides the diagnosis tab while the capability is unavailable", async () => {+ apiMock.getCorrelationAnalysis.mockResolvedValue(response("FREE"));+ render(<Correlation />);+ fireEvent.click(screen.getByRole("button", { name: "Compute" }));+ expect(await screen.findByTestId("correlation-result")).toHaveTextContent("FREE");+ expect(screen.queryByRole("tab", { name: /Shannon/ })).not.toBeInTheDocument();+});diff --git a/frontend/src/pages/__tests__/SettingsClaudeCliModels.test.tsx b/frontend/src/pages/__tests__/SettingsClaudeCliModels.test.tsxindex 2eab283d9..fb8f2f3c5 100644--- a/frontend/src/pages/__tests__/SettingsClaudeCliModels.test.tsx+++ b/frontend/src/pages/__tests__/SettingsClaudeCliModels.test.tsx@@ -24,7 +24,6 @@ vi.mock("@/lib/apiAuth", () => ({}));vi.mock("@/components/settings/ChannelSettings", () => ({ ChannelSettings: () => null }));-vi.mock("@/components/settings/QVerisSettings", () => ({ QVerisSettings: () => null }));vi.mock("@/components/settings/SourcePrioritySettings", () => ({SourcePrioritySettings: () => null,}));@@ -233,3 +232,18 @@ describe("Settings with Codex OAuth discovery", () => {expect(input).toHaveValue("openai-codex/manual-model");});});++it("saves only the explicitly selected Gildata feature for an existing token", async () => {+ const saved = { gildata_token_configured: true, gildata_features: [] };+ apiMock.getLLMSettings.mockResolvedValue(llmSettings());+ apiMock.getDataSourceSettings.mockResolvedValue(saved);+ apiMock.updateDataSourceSettings.mockResolvedValue({ ...saved, gildata_features: ["fin_query"] });+ render(<Settings />);+ const query = await screen.findByRole("checkbox", { name: "Combined financial queries" });+ expect(query).not.toBeChecked();+ fireEvent.click(query);+ fireEvent.click(screen.getByRole("button", { name: /save data source settings/i }));+ await waitFor(() => expect(apiMock.updateDataSourceSettings).toHaveBeenCalledWith(+ expect.objectContaining({ gildata_features: ["fin_query"] }),+ ));+});diff --git a/frontend/src/pages/__tests__/SettingsQVeris.test.tsx b/frontend/src/pages/__tests__/SettingsQVeris.test.tsxdeleted file mode 100644index 029b9d669..000000000--- a/frontend/src/pages/__tests__/SettingsQVeris.test.tsx+++ /dev/null@@ -1,277 +0,0 @@-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-import i18n from "@/i18n";-import { QVerisSettings } from "@/components/settings/QVerisSettings";-import { Settings } from "../Settings";--const apiMock = vi.hoisted(() => ({- getLLMSettings: vi.fn(),- getDataSourceSettings: vi.fn(),- getChannelStatus: vi.fn(),- getChannelsConfig: vi.fn(),- startChannels: vi.fn(),- stopChannels: vi.fn(),- updateLLMSettings: vi.fn(),- updateDataSourceSettings: vi.fn(),- listCustomProviders: vi.fn().mockResolvedValue({status: "ok", providers: []}),-}));--vi.mock("@/lib/api", async () => {- const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");- return {- ...actual,- api: apiMock,- isAuthRequiredError: vi.fn(() => false),- };-});--vi.mock("@/lib/apiAuth", () => ({- authHeaders: vi.fn(() => ({ Authorization: "Bearer local-test-key" })),- getApiAuthKey: vi.fn(() => "local-test-key"),- setApiAuthKey: vi.fn(),-}));--vi.mock("sonner", () => ({- toast: {- success: vi.fn(),- info: vi.fn(),- error: vi.fn(),- },-}));--function llmSettings() {- return {- provider: "openrouter",- model_name: "deepseek/deepseek-v3.2",- base_url: "https://openrouter.ai/api/v1",- api_key_env: "OPENROUTER_API_KEY",- api_key_configured: false,- api_key_required: true,- temperature: 0.1,- timeout_seconds: 120,- max_retries: 2,- reasoning_effort: "",- sse_timeout_seconds: 300,- env_path: "agent/.env",- providers: [- {- name: "openrouter",- label: "OpenRouter",- api_key_env: "OPENROUTER_API_KEY",- base_url_env: "OPENROUTER_BASE_URL",- default_model: "deepseek/deepseek-v3.2",- default_base_url: "https://openrouter.ai/api/v1",- api_key_required: true,- auth_type: "api_key",- },- ],- };-}--function dataSourceSettings() {- return {- tushare_token_configured: false,- baostock_supported: true,- baostock_installed: true,- baostock_message: "BaoStock available",- env_path: "agent/.env",- };-}--function channelStatus() {- return {- running: false,- inbound_queue: 0,- outbound_queue: 0,- session_count: 0,- channels: {},- };-}--function qverisConfig(overrides = {}) {- return {- enabled: true,- base_url: "https://qveris.ai/api/v1",- api_key_masked: "sk-...8TI",- mode: "paid",- budget_credits_per_session: 50,- configured: true,- signup_url: "https://qveris.ai/?ref=from-api",- invite_code: "INVITE-FROM-API",- ...overrides,- };-}--function qverisStatus(overrides = {}) {- return {- enabled: true,- ok: true,- error: null,- remaining_credits: 123.45,- recent: [- {- ts: "2026-07-07T01:02:03Z",- tool_id: "sec_filings",- cost: 1.25,- charge_outcome: "charged",- },- ],- signup_url: "https://qveris.ai/?ref=status",- invite_code: "INVITE-FROM-STATUS",- ...overrides,- };-}--function jsonResponse(body: unknown, status = 200) {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });-}--function mockQVerisFetch(config = qverisConfig(), status = qverisStatus()) {- const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {- const path = String(input);- if (path === "/qveris/config" && init?.method === "PUT") {- const payload = JSON.parse(String(init.body || "{}"));- return jsonResponse({ ...config, ...payload, api_key_masked: payload.api_key ? "sk-...NEW" : config.api_key_masked });- }- if (path === "/qveris/config") return jsonResponse(config);- if (path === "/qveris/status") return jsonResponse(status);- return jsonResponse({ detail: `Unexpected path: ${path}` }, 404);- });- vi.stubGlobal("fetch", fetchMock);- return fetchMock;-}--describe("Settings QVeris card", () => {- beforeEach(async () => {- await i18n.changeLanguage("en");- window.localStorage.clear();- apiMock.getLLMSettings.mockResolvedValue(llmSettings());- apiMock.getDataSourceSettings.mockResolvedValue(dataSourceSettings());- apiMock.getChannelStatus.mockResolvedValue(channelStatus());- apiMock.getChannelsConfig.mockResolvedValue({- config_path: "agent/agent.json",- writable: true,- runtime_running: false,- channels: {},- });- apiMock.startChannels.mockResolvedValue(channelStatus());- apiMock.stopChannels.mockResolvedValue(channelStatus());- });-- afterEach(() => {- cleanup();- delete window.vibeDesktop;- vi.unstubAllGlobals();- });-- it("renders inside Settings and shows loaded config, balance, and recent usage", async () => {- mockQVerisFetch();-- render(<Settings />);-- expect(await screen.findByText("QVeris Tool Marketplace")).toBeInTheDocument();- expect(await screen.findByDisplayValue("https://qveris.ai/api/v1")).toBeInTheDocument();- expect(screen.getByPlaceholderText("sk-...8TI")).toBeInTheDocument();- expect(screen.getByText("123.45")).toBeInTheDocument();- expect(screen.getByText("sec_filings")).toBeInTheDocument();- });-- it("sends the configured PUT payload when saving with a new API key", async () => {- const fetchMock = mockQVerisFetch(qverisConfig({ enabled: false, mode: "free" }), qverisStatus({ recent: [] }));- render(<QVerisSettings />);-- // The base-URL input shows its default value before the config GET resolves,- // so wait for the save button to leave its loading-disabled state instead.- await waitFor(() => expect(screen.getByRole("button", { name: "Save QVeris settings" })).toBeEnabled());- fireEvent.click(screen.getByLabelText("Enable paid QVeris route"));- fireEvent.change(screen.getByLabelText("Base URL"), { target: { value: "https://example.test/qveris" } });- fireEvent.change(screen.getByPlaceholderText("sk-...8TI"), { target: { value: "sk-new-key" } });- fireEvent.change(screen.getByLabelText("Mode"), { target: { value: "paid" } });- fireEvent.change(screen.getByDisplayValue("50"), { target: { value: "80" } });- fireEvent.click(screen.getByRole("button", { name: "Save QVeris settings" }));-- await waitFor(() => expect(fetchMock).toHaveBeenCalledWith("/qveris/config", expect.objectContaining({ method: "PUT" })));- const putCall = fetchMock.mock.calls.find(([path, init]) => String(path) === "/qveris/config" && init?.method === "PUT");- expect(JSON.parse(String(putCall?.[1]?.body))).toEqual({- enabled: true,- base_url: "https://example.test/qveris",- mode: "paid",- budget_credits_per_session: 80,- api_key: "sk-new-key",- });- });-- it("does not overwrite the saved API key when the key field is left blank", async () => {- const fetchMock = mockQVerisFetch();- render(<QVerisSettings />);-- // The base-URL input shows its default value before the config GET resolves,- // so wait for the save button to leave its loading-disabled state instead.- await waitFor(() => expect(screen.getByRole("button", { name: "Save QVeris settings" })).toBeEnabled());- fireEvent.click(screen.getByRole("button", { name: "Save QVeris settings" }));-- await waitFor(() => expect(fetchMock).toHaveBeenCalledWith("/qveris/config", expect.objectContaining({ method: "PUT" })));- const putCall = fetchMock.mock.calls.find(([path, init]) => String(path) === "/qveris/config" && init?.method === "PUT");- expect(JSON.parse(String(putCall?.[1]?.body))).not.toHaveProperty("api_key");- });-- it("stores a desktop API key through safe storage and restarts the backend", async () => {- const setCredential = vi.fn().mockResolvedValue({- available: true,- configured: ["QVERIS_API_KEY"],- migrated: [],- });- const restartBackend = vi.fn().mockResolvedValue(true);- window.vibeDesktop = {- isDesktop: true,- getCredentialStatus: vi.fn(),- setCredential,- restartBackend,- };- const fetchMock = mockQVerisFetch();- render(<QVerisSettings />);-- await waitFor(() =>- expect(screen.getByRole("button", { name: "Save QVeris settings" })).toBeEnabled(),- );- fireEvent.change(screen.getByPlaceholderText("sk-...8TI"), {- target: { value: "sk-desktop-key" },- });- fireEvent.click(screen.getByRole("button", { name: "Save QVeris settings" }));-- await waitFor(() =>- expect(setCredential).toHaveBeenCalledWith("QVERIS_API_KEY", "sk-desktop-key"),- );- const putCall = fetchMock.mock.calls.find(- ([path, init]) => String(path) === "/qveris/config" && init?.method === "PUT",- );- expect(JSON.parse(String(putCall?.[1]?.body))).not.toHaveProperty("api_key");- expect(restartBackend).toHaveBeenCalledTimes(1);- });-- it("uses the signup href from the config response and renders the empty usage state", async () => {- mockQVerisFetch(qverisConfig({ signup_url: "https://qveris.ai/?ref=config-response" }), qverisStatus({ recent: [] }));- render(<QVerisSettings />);-- const signup = await screen.findByRole("link", { name: "Open signup" });- expect(signup).toHaveAttribute("href", "https://qveris.ai/?ref=config-response");- expect(screen.getByText("INVITE-FROM-API")).toBeInTheDocument();- expect(screen.getByText("No recent usage")).toBeInTheDocument();- });-- it("renders QVeris copy in English and Chinese through i18n", async () => {- mockQVerisFetch(undefined, qverisStatus({ recent: [] }));- const { unmount } = render(<QVerisSettings />);- expect(await screen.findByText("QVeris Tool Marketplace")).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Save QVeris settings" })).toBeInTheDocument();- unmount();-- await i18n.changeLanguage("zh-CN");- mockQVerisFetch(undefined, qverisStatus({ recent: [] }));- render(<QVerisSettings />);- expect(await screen.findByText("QVeris 工具市场")).toBeInTheDocument();- expect(screen.getByRole("button", { name: "保存 QVeris 设置" })).toBeInTheDocument();- });-});diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 793d9b09a..a6f52db12 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -8,7 +8,6 @@ const PROXY_PATHS = ["/sessions","/swarm/presets","/swarm/runs",- "/qveris","/settings/llm","/settings/data-sources","/settings/custom-providers",diff --git a/wiki/docs/content.en.js b/wiki/docs/content.en.jsindex f0a16eb1b..5c138267a 100644--- a/wiki/docs/content.en.js+++ b/wiki/docs/content.en.js@@ -33,9 +33,9 @@ export const DOCS_STRUCTURE = [title: "What is in 0.1.16",body: `<ul>- <li><strong>29 market-data sources</strong> behind one call, with a fallback chain per market. Most markets need no API key.</li>+ <li><strong>28 market-data sources</strong> behind one call, with a fallback chain per market. Most markets need no API key.</li><li><strong>11 backtest engines</strong>: China A-shares, global equities, India, Korea, Vietnam, crypto, China futures, global futures, forex, a composite engine for cross-market portfolios, and an options portfolio engine.</li>- <li><strong>90 finance skills</strong> in 9 categories, and <strong>30 swarm presets</strong> for committee-style research.</li>+ <li><strong>89 finance skills</strong> in 9 categories, and <strong>30 swarm presets</strong> for committee-style research.</li><li><strong>Alpha Zoo</strong>: 478 alphas you can benchmark on your own universe with one command.</li><li><strong>82 MCP tools</strong> for other agents.</li><li><strong>19 broker connectors</strong>, read-only by default, plus a read-only multi-broker portfolio page.</li>@@ -188,7 +188,7 @@ DEEPSEEK_BASE_URL=https://api.deepseek.com/v1</code></pre><li><code>TUSHARE_TOKEN</code> — richer A-share, fund and macro data.</li><li><code>GILDATA_TOKEN</code> — Hundsun Juyuan commercial A-share feed.</li><li>Finnhub, Alpha Vantage, Tiingo and FMP keys — extra US sources.</li>- <li>QVeris — a paid marketplace, used only when you ask for it; switch with <code>vibe-trading data mode</code>.</li>+ <li>Data partner: Gildata. Each Gildata feature requires a token and a separate opt-in in Settings.</li></ul><p>See <a data-doc-link="tools/data-sources">Data sources</a> for which source serves which market.</p>`@@ -569,7 +569,7 @@ vibe-trading --swarm-retry RUN_ID --swarm-resume # keep finished tasks</code><id: "tools/data-sources",title: "Data sources",description: "Which source serves which market, symbol formats, and how to pick a source.",- lead: "One get_market_data call reaches 29 sources. With source auto, each symbol is routed by its market and walks that market's fallback chain, with the sources least likely to block you first.",+ lead: "One get_market_data call reaches 28 sources. With source auto, each symbol is routed by its market and walks that market's fallback chain, with the sources least likely to block you first.",sections: [{id: "providers",@@ -578,7 +578,7 @@ vibe-trading --swarm-retry RUN_ID --swarm-resume # keep finished tasks</code><<table><thead><tr><th>Market</th><th>Chain, in order</th></tr></thead><tbody>- <tr><td>China A-shares</td><td>tencent, eastmoney, baostock, akshare, tushare, gildata, local</td></tr>+ <tr><td>China A-shares</td><td>tencent, eastmoney, baostock, akshare, tushare, local</td></tr><tr><td>US equities</td><td>yahoo, stooq, sina, eastmoney, yfinance, tiingo, fmp, finnhub, alphavantage, longbridge, akshare, local</td></tr><tr><td>Hong Kong</td><td>tencent, eastmoney, yahoo, futu, akshare, yfinance, tushare, longbridge, local</td></tr><tr><td>India</td><td>yahoo, yfinance, india_broker, local</td></tr>@@ -591,7 +591,7 @@ vibe-trading --swarm-retry RUN_ID --swarm-resume # keep finished tasks</code><<tr><td>Macro</td><td>akshare, tushare, local</td></tr></tbody></table>- <p>These sources are used only when you name them: <code>qveris</code> (paid marketplace), <code>tickerall</code> (hosted MT5 feed), and <code>nobitex</code> / <code>wallex</code> (Iranian Toman pairs). Set <code>MARKET_DATA_ORDER_<MARKET></code>, for example <code>MARKET_DATA_ORDER_US_EQUITY</code>, to reorder a chain.</p>+ <p>These sources are used only when you name them: <code>gildata</code> (requires market quotes enabled), <code>tickerall</code> (hosted MT5 feed), and <code>nobitex</code> / <code>wallex</code> (Iranian Toman pairs). Set <code>MARKET_DATA_ORDER_<MARKET></code>, for example <code>MARKET_DATA_ORDER_US_EQUITY</code>, to reorder a chain.</p><p>The base install includes Tencent's standard-library HTTP loader and AKShare. BaoStock is an optional token-free TCP source for daily A-share bars: install it with <code>pip install --upgrade "vibe-trading-ai[ashare]"</code>, or use <code>uv tool install --force --python 3.12 "vibe-trading-ai[ashare]"</code> for a uv tool installation that previously used only the base package. Missing optional SDKs are skipped during automatic fallback.</p><p>For uv tool users, <code>--force</code> rebuilds the existing tool environment. Keep previously used extras when adding <code>ashare</code>, for example <code>"vibe-trading-ai[ashare,deepseek]"</code>, and repeat any existing <code>--with</code> arguments to retain those additional dependencies.</p><p>The legacy <code>mootdx</code> loader is also explicit-only: it has been retired from automatic fallback and is not included in the base install or the <code>ashare</code> extra. Installing its SDK does not guarantee compatibility with the TDX server protocol. Prefer <code>source: "auto"</code> or an available alternative such as <code>tencent</code> or <code>baostock</code> when an Eastmoney-backed request is throttled. Startup preflight covers selected services, not every optional loader, and an installed SDK does not prove remote-service availability.</p>@@ -674,7 +674,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, anid: "library",title: "Library",body: `- <p>90 skills in 9 categories:</p>+ <p>89 skills in 9 categories:</p><table><thead><tr><th>Category</th><th>Skills</th></tr></thead><tbody>diff --git a/wiki/docs/content.zh.js b/wiki/docs/content.zh.jsindex 028357b37..014f9324b 100644--- a/wiki/docs/content.zh.js+++ b/wiki/docs/content.zh.js@@ -32,9 +32,9 @@ export const DOCS_STRUCTURE = [title: "0.1.16 包含什么",body: `<ul>- <li><strong>29 个行情数据源</strong>,一次调用即可,每个市场各有一条回退链。多数市场不需要任何 API key。</li>+ <li><strong>28 个行情数据源</strong>,一次调用即可,每个市场各有一条回退链。多数市场不需要任何 API key。</li><li><strong>11 个回测引擎</strong>:A 股、全球股票、印度、韩国、越南、加密货币、国内期货、海外期货、外汇,一个用于跨市场组合的复合引擎,以及一个期权组合引擎。</li>- <li><strong>90 个金融技能</strong>,分 9 类;<strong>30 个多智能体团队预设</strong>,用于投委会式研究。</li>+ <li><strong>89 个金融技能</strong>,分 9 类;<strong>30 个多智能体团队预设</strong>,用于投委会式研究。</li><li><strong>Alpha Zoo</strong>:478 个现成因子,一条命令即可在你的股票池上评测。</li><li><strong>82 个 MCP 工具</strong>,供其他智能体调用。</li><li><strong>19 个券商连接器</strong>,默认只读;另有只读的多券商持仓页。</li>@@ -187,7 +187,7 @@ DEEPSEEK_BASE_URL=https://api.deepseek.com/v1</code></pre><li><code>TUSHARE_TOKEN</code>——更丰富的 A 股、基金和宏观数据。</li><li><code>GILDATA_TOKEN</code>——恒生聚源商业 A 股数据。</li><li>Finnhub、Alpha Vantage、Tiingo、FMP 的 key——额外的美股数据源。</li>- <li>QVeris——付费数据市场,只在你明确要求时使用;用 <code>vibe-trading data mode</code> 切换。</li>+ <li>数据合作方:聚源。每项聚源功能均需 Token,并在设置中单独开启,默认全关。</li></ul><p>哪个数据源服务哪个市场,见 <a data-doc-link="tools/data-sources">数据源</a>。</p>`@@ -568,7 +568,7 @@ vibe-trading --swarm-retry RUN_ID --swarm-resume # 保留已完成的任务</cid: "tools/data-sources",title: "数据源",description: "哪个数据源服务哪个市场、代码格式、如何指定数据源。",- lead: "一次 get_market_data 调用可以用到 29 个数据源。source 设为 auto 时,每个代码按所属市场路由,沿该市场的回退链依次尝试,最不容易封禁你的数据源排在最前。",+ lead: "一次 get_market_data 调用可以用到 28 个数据源。source 设为 auto 时,每个代码按所属市场路由,沿该市场的回退链依次尝试,最不容易封禁你的数据源排在最前。",sections: [{id: "providers",@@ -577,7 +577,7 @@ vibe-trading --swarm-retry RUN_ID --swarm-resume # 保留已完成的任务</c<table><thead><tr><th>市场</th><th>回退顺序</th></tr></thead><tbody>- <tr><td>A 股</td><td>tencent、eastmoney、baostock、akshare、tushare、gildata、local</td></tr>+ <tr><td>A 股</td><td>tencent、eastmoney、baostock、akshare、tushare、local</td></tr><tr><td>美股</td><td>yahoo、stooq、sina、eastmoney、yfinance、tiingo、fmp、finnhub、alphavantage、longbridge、akshare、local</td></tr><tr><td>港股</td><td>tencent、eastmoney、yahoo、futu、akshare、yfinance、tushare、longbridge、local</td></tr><tr><td>印度</td><td>yahoo、yfinance、india_broker、local</td></tr>@@ -590,7 +590,7 @@ vibe-trading --swarm-retry RUN_ID --swarm-resume # 保留已完成的任务</c<tr><td>宏观</td><td>akshare、tushare、local</td></tr></tbody></table>- <p>以下数据源只在你点名时使用:<code>qveris</code>(付费数据市场)、<code>tickerall</code>(托管的 MT5 行情)、<code>nobitex</code> / <code>wallex</code>(伊朗托曼计价交易对)。设置 <code>MARKET_DATA_ORDER_<MARKET></code>(例如 <code>MARKET_DATA_ORDER_US_EQUITY</code>)可以调整某条链的顺序。</p>+ <p>以下数据源只在你点名时使用:<code>gildata</code>(需先启用聚源行情)、<code>tickerall</code>(托管的 MT5 行情)、<code>nobitex</code> / <code>wallex</code>(伊朗托曼计价交易对)。设置 <code>MARKET_DATA_ORDER_<MARKET></code>(例如 <code>MARKET_DATA_ORDER_US_EQUITY</code>)可以调整某条链的顺序。</p><p>基础安装包含使用标准库 HTTP 的腾讯行情加载器和 AKShare。BaoStock 是可选的免 token TCP 日线数据源,可用 <code>pip install --upgrade "vibe-trading-ai[ashare]"</code> 安装;原先只安装基础包的 uv tool 用户可运行 <code>uv tool install --force --python 3.12 "vibe-trading-ai[ashare]"</code>。自动回退会跳过缺少可选 SDK 的加载器。</p><p>uv tool 的 <code>--force</code> 会重建现有工具环境。添加 <code>ashare</code> 时须保留原先使用的其他 extra(例如 <code>"vibe-trading-ai[ashare,deepseek]"</code>),并在命令中重复原有的 <code>--with</code> 参数,以保留这些附加依赖。</p><p>旧版 <code>mootdx</code> 加载器也仅供显式指定:它已退出自动回退链,基础安装和 <code>ashare</code> extra 都不包含它。安装 SDK 并不能保证与 TDX 服务器协议兼容。东方财富相关请求遇到限流时,可使用 <code>source: "auto"</code>,或选择可用的 <code>tencent</code>、<code>baostock</code> 等替代源。启动预检只覆盖部分服务,不会列出所有可选加载器;SDK 已安装也不代表远端服务当前可用。</p>@@ -673,7 +673,7 @@ vibe-trading run -p "分析我的交易行为,提炼我的影子策略,并id: "library",title: "技能库",body: `- <p>共 90 个技能,分 9 类:</p>+ <p>共 89 个技能,分 9 类:</p><table><thead><tr><th>类别</th><th>数量</th></tr></thead><tbody>