"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Fix causal option pricing, channel refresh state, and market routing
Haozhe Wu1c16c02c2078
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 21b0686e5..aa237fbc6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,25 +13,32 @@ This project adheres to [Semantic Versioning](https://semver.org/).reset in all nine languages. Reset reasons redact URL userinfo and old/newsecret values; a best-effort notice goes to the changed channel's last chat.Signal refreshes its writable nested policies, not its computed allowlist.+ Refresh changes only declared live fields and preserves connection state+ resolved during login, including WeChat's authenticated server address.- Strip URL credentials even with malformed ports or multiple `@` characters(#1742; #1741). Saving or testing an echoed configuration preserves the storedURL credentials; explicit edits and clear flags remain effective (#1744; #1743).Enable and connection-test failures also redact credentials, including raisedSDK exceptions, and leave saved configuration unchanged.-- Recognize known slash-USD crypto pairs before forex (#1748), normalize+- Recognize known slash-USD crypto pairs before forex in both correlation and+ shared Agent/MCP market-data routing, while keeping precious metals on the+ forex chain (#1740, #1748). Normalizesuffixed Hong Kong aliases for duplicate detection (#1746; #1745), and treatunusable persisted cache metadata as a recoverable cache miss (#1747).Five-digit display aliases share an identity with their four-digit spelling;distinct currency counters stay separate. Missing cache index metadata is amiss too, with valid entries still reused after repair.- Options drawdown includes the initial-cash high-water mark (#1750; #1749).- Pricing volatility receives the run's annualization factor, including the- cross-market convention (#1753). Bootstrap and walk-forward validation use+ Pricing volatility receives the run's annualization factor; cross-market+ pricing estimates each bar's frequency from elapsed return intervals known+ at that time, including subdaily intervals. Extending a run cannot change+ earlier option prices (#1753). Bootstrap and walk-forward validation useonly observed adjacent equity returns across missing data (#1754).A walk-forward window without observed endpoints or any adjacent returnsreports an error instead of a fabricated zero score or an incomplete aggregate.- Cash-flow ingestion refuses ambiguous single-dot amounts unless the decimal- separator is supplied (#1739). American waterfalls reject a bare `as_of`+ separator is supplied, while accepting unambiguous scientific notation in+ cash-flow and entity-panel files (#1739). American waterfalls reject a bare `as_of`date rather than silently ignoring it; per-deal dates remain supported (#1732).- Retire mootdx from the default A-share chain and public canary (#1730; #1729),with explicit-source access retained. Old source-order overrides containingdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex fdbfa7f98..82a175227 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -199,6 +199,9 @@ configuration with no per-channel frontend code.`self.config`. Such edits are revalidated and applied without reconnecting;connection settings and enable transitions still reload the adapter. Acomputed field is not writable (Signal's policies live under `dm`/`group`).+ Refresh copies only declared live fields into the current validated config,+ preserving connection state resolved during login (such as WeChat's server+ address). Do not replace the entire runtime config with the stored section.The Web UI reports the apply outcome. A failed hot swap that requires a fullreset returns a bounded, sanitized reason and sends a best-effort notice tothe changed channel's last outbound chat.diff --git a/README.md b/README.mdindex 2594666db..d97daffa7 100644--- a/README.md+++ b/README.md@@ -52,7 +52,7 @@> ⚠️ **Security warning:** The X account `VibeTrading_HKU`, Virtuals project `101845`, and token contract `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` are not official Vibe-Trading assets. We have never launched or endorsed any token or memecoin. Do not buy, connect a wallet, or sign anything. [Details](SECURITY.md#official-channels--impersonation).-- **2026-10-09** 🛠️ **Channel updates and backtest correctness**: Channel settings preserve embedded credentials and apply live-read edits without reconnecting; Web results explain resets in all nine languages ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). Options pricing and drawdown use consistent annualization and starting capital; validation excludes missing equity returns. Crypto/HK identity and cache recovery are corrected, and mootdx leaves the default A-share chain. See [CHANGELOG](CHANGELOG.md) for all thirteen PRs.+- **2026-10-09** 🛠️ **Channel updates and backtest correctness**: Channel settings preserve embedded URL credentials and authenticated WeChat endpoints during in-place updates, with save/reset feedback in all nine languages ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). Cross-market option volatility uses only timestamps known at each bar; drawdown includes starting capital. Crypto/precious-metal routing, HK duplicate detection, cache recovery, scientific-notation amounts and missing-equity validation are corrected. mootdx leaves the default A-share chain. See [CHANGELOG](CHANGELOG.md) for all thirteen PRs.- **2026-10-08** 🔐 **Protected PDF reports and clearer broker reads**: Scheduled Email PDFs support optional AES-256 password protection across Web, CLI playbooks and agent confirmations; the password stays in private channel configuration ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS queries all three venue buckets, refreshes an explicitly expired token once, and reports incomplete reads as errors ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). Derived formulas keep their arithmetic after descriptive labels while evidence checks remain enforced ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).diff --git a/README_ar.md b/README_ar.mdindex c5ce9b925..83574454d 100644--- a/README_ar.md+++ b/README_ar.md@@ -52,7 +52,7 @@> ⚠️ **تحذير أمني:** حساب X باسم `VibeTrading_HKU`، ومشروع Virtuals رقم `101845`، وعقد التوكن `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` كلّها غير رسمية ولا تتبع Vibe-Trading. لم نُطلق أو نؤيد مطلقًا أي توكن أو عملة ميم. لا تشترِ هذا التوكن، ولا تربط محفظتك، ولا توقّع أي شيء. [التفاصيل](SECURITY.md#official-channels--impersonation).-- **2026-10-09** 🛠️ **إعدادات القنوات ودقة الاختبارات التاريخية**: تُحفظ بيانات الاعتماد المضمّنة في الروابط وتُطبّق الإعدادات المقروءة مباشرة دون إعادة الاتصال. تعرض الواجهة نتائج الحفظ وإعادة التشغيل بتسع لغات ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)، [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)، [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). صُححت سنوية تقلب الخيارات والتراجع من رأس المال الأولي، ولا تُنشأ عوائد وهمية من قيم مفقودة. تحسّن التعرف على العملات الرقمية وأسهم هونغ كونغ واستعادة الذاكرة المؤقتة، وأُزيل mootdx من سلسلة أسهم A الافتراضية. تفاصيل طلبات الدمج الثلاثة عشر في [CHANGELOG](CHANGELOG.md).+- **2026-10-09** 🛠️ **إعدادات القنوات ودقة الاختبارات التاريخية**: تحافظ تحديثات الإعدادات دون إعادة الاتصال على بيانات اعتماد الروابط وعنوان خادم WeChat الناتج عن المصادقة، وتعرض الواجهة نتائج الحفظ وإعادة التشغيل بتسع لغات ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)، [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)، [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). يعتمد تقلب الخيارات عبر الأسواق على التوقيتات المعروفة عند كل شمعة فقط، ويشمل التراجع رأس المال الأولي. صُححت مسارات بيانات العملات الرقمية والمعادن الثمينة، وكشف تكرار أسهم هونغ كونغ، واستعادة الذاكرة المؤقتة، والمبالغ بالصيغة العلمية، والتحقق من قيم حقوق الملكية المفقودة. أُزيل mootdx من سلسلة أسهم A الافتراضية. تفاصيل طلبات الدمج الثلاثة عشر في [CHANGELOG](CHANGELOG.md).- **2026-10-08** 🔐 **حماية تقارير PDF وتصحيح قراءات الوسيط**: تدعم تقارير البريد المجدولة حماية اختيارية بكلمة مرور عبر AES-256 في الويب وCLI وتأكيدات الوكيل؛ تُحفظ كلمة المرور في إعدادات القناة الخاصة فقط ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). يستعلم KIS عن مسارات التداول الثلاثة ويجدد الرمز المنتهي صراحةً مرة واحدة ويرفض القراءة غير المكتملة ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). تُحفظ الصيغة الحسابية بعد الوصف مع استمرار التحقق من الأدلة ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).diff --git a/README_es.md b/README_es.mdindex 7d85c783f..e7b05fe51 100644--- a/README_es.md+++ b/README_es.md@@ -52,7 +52,7 @@> ⚠️ **Advertencia de seguridad:** la cuenta de X `VibeTrading_HKU`, el proyecto de Virtuals `101845` y el contrato de token `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` no son activos oficiales de Vibe-Trading. Nunca hemos lanzado ni respaldado ningún token o memecoin. No compres, conectes una wallet ni firmes nada. [Detalles](SECURITY.md#official-channels--impersonation).-- **2026-10-09** 🛠️ **Configuración de canales y correcciones de backtests**: Se conservan las credenciales de las URL y los ajustes consultados en cada mensaje se aplican sin reconectar. La web explica guardados y reinicios en nueve idiomas ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). Corregimos la anualización de opciones y la caída desde el capital inicial; la validación no inventa rendimientos para valores ausentes. Mejoran la identificación de criptoactivos/acciones de Hong Kong y la recuperación de caché; mootdx sale de la cadena predeterminada de acciones A. Los trece PR están en [CHANGELOG](CHANGELOG.md).+- **2026-10-09** 🛠️ **Configuración de canales y correcciones de backtests**: Las actualizaciones sin reconexión conservan las credenciales de las URL y la dirección del servidor autenticado de WeChat; la web explica guardados y reinicios en nueve idiomas ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). La volatilidad de opciones entre mercados usa solo marcas temporales conocidas en cada barra; la caída máxima incluye el capital inicial. Corregimos las rutas de criptoactivos y metales preciosos, los duplicados de Hong Kong, la recuperación de caché, los importes en notación científica y la validación de valores ausentes. mootdx sale de la cadena predeterminada de acciones A. Los trece PR están en [CHANGELOG](CHANGELOG.md).- **2026-10-08** 🔐 **Informes PDF protegidos y lecturas del bróker corregidas**: Los PDF de correo programado admiten protección AES-256 opcional en Web, CLI y confirmaciones del agente; la contraseña permanece en la configuración privada del canal ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS consulta las tres rutas, renueva una sola vez un token explícitamente caducado y rechaza lecturas incompletas ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). Las fórmulas conservan la expresión tras las etiquetas descriptivas y mantienen la verificación de evidencias ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).diff --git a/README_id.md b/README_id.mdindex 08a3be7de..7e4811b07 100644--- a/README_id.md+++ b/README_id.md@@ -53,7 +53,7 @@> ⚠️ **Peringatan keamanan:** Akun X `VibeTrading_HKU`, proyek Virtuals `101845`, dan kontrak token `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` bukan aset resmi Vibe-Trading. Kami tidak pernah meluncurkan atau mendukung token maupun memecoin apa pun. Jangan membeli, menghubungkan wallet, atau menandatangani apa pun. [Detail](SECURITY.md#official-channels--impersonation).-- **2026-10-09** 🛠️ **Pengaturan kanal dan perbaikan backtest**: Kredensial dalam URL tetap tersimpan, dan pengaturan yang dibaca setiap pesan diterapkan tanpa menyambungkan ulang. Hasil penyimpanan dan mulai ulang dijelaskan dalam sembilan bahasa ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). Annualisasi opsi dan penurunan dari modal awal diperbaiki; validasi tidak menciptakan imbal hasil dari nilai yang hilang. Identifikasi kripto/saham Hong Kong dan pemulihan cache diperbaiki, sementara mootdx dikeluarkan dari rantai A-share bawaan. Lihat ketiga belas PR di [CHANGELOG](CHANGELOG.md).+- **2026-10-09** 🛠️ **Pengaturan kanal dan perbaikan backtest**: Pembaruan tanpa menyambungkan ulang mempertahankan kredensial URL dan alamat server WeChat hasil autentikasi; web menjelaskan hasil penyimpanan dan mulai ulang dalam sembilan bahasa ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). Volatilitas opsi lintas pasar hanya memakai waktu yang sudah diketahui pada setiap bar; drawdown mencakup modal awal. Perbaikan meliputi rute data kripto/logam mulia, duplikat saham Hong Kong, pemulihan cache, nominal notasi ilmiah, dan validasi nilai ekuitas yang hilang. mootdx dikeluarkan dari rantai saham A bawaan. Ketiga belas PR tercantum dalam [CHANGELOG](CHANGELOG.md).- **2026-10-08** 🔐 **Laporan PDF terlindungi dan pembacaan broker diperbaiki**: PDF Email terjadwal mendukung perlindungan AES-256 opsional melalui Web, CLI, dan konfirmasi agen; kata sandi hanya disimpan dalam konfigurasi privat kanal ([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS menanyakan ketiga jalur perdagangan, memperbarui token yang secara eksplisit kedaluwarsa satu kali, dan menolak pembacaan yang tidak lengkap ([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). Rumus turunan tetap utuh setelah label deskriptif dengan pemeriksaan bukti tetap berlaku ([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).diff --git a/README_ja.md b/README_ja.mdindex 8d2f16568..0a7502222 100644--- a/README_ja.md+++ b/README_ja.md@@ -52,7 +52,7 @@> ⚠️ **セキュリティ警告:** Xアカウント `VibeTrading_HKU`、Virtualsプロジェクト `101845`、およびトークンコントラクト `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` は、いずれもVibe-Trading公式のものではありません。Vibe-Tradingはこれまで、いかなるトークンやミームコインも発行・公認していません。購入、ウォレットの接続、署名は行わないでください。[詳細](SECURITY.md#official-channels--impersonation)-- **2026-10-09** 🛠️ **チャンネル設定とバックテストの修正**:URL 内の認証情報を保持し、接続に影響しない設定は再接続せず反映。保存・再起動の結果を Web で9言語表示します([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)、[#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)、[#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744))。オプション価格の年率換算と初期資金からのドローダウンを修正し、欠損資産額から架空のリターンを作りません。暗号資産・香港株の識別とキャッシュ復旧を改善し、mootdx を標準の A 株取得経路から外しました。全13件は [CHANGELOG](CHANGELOG.md)。+- **2026-10-09** 🛠️ **チャンネル設定とバックテストの修正**:再接続なしの設定更新で URL 内の認証情報と WeChat 認証後のサーバーアドレスを保持し、保存・再起動の結果を Web で9言語表示します([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)、[#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)、[#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744))。複数市場のオプション価格に使うボラティリティは各時点までのタイムスタンプだけで計算し、ドローダウンには初期資金を反映。暗号資産・貴金属のデータ取得経路、香港株の重複判定、キャッシュ復旧、科学表記の金額、欠損資産額の検証を修正しました。mootdx は標準の A 株取得経路から外れます。全13件は [CHANGELOG](CHANGELOG.md)。- **2026-10-08** 🔐 **PDF レポートのパスワード保護とブローカー読み取り修正**:定期メール PDF に AES-256 保護を選択でき、Web、CLI、エージェント確認画面に反映されます。パスワードは非公開のチャネル設定だけに保存します([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709))。KIS は三つの取引経路を照会し、明示的なトークン失効を一度だけ再取得、不完全な読み取りはエラーにします([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726))。説明ラベルの後の導出式を保持し、証拠検証を維持します([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728))。diff --git a/README_ko.md b/README_ko.mdindex 319caef30..8b1240df6 100644--- a/README_ko.md+++ b/README_ko.md@@ -52,7 +52,7 @@> ⚠️ **보안 경고:** X 계정 `VibeTrading_HKU`, Virtuals 프로젝트 `101845`, 토큰 컨트랙트 `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4`는 모두 Vibe-Trading 공식과 무관합니다. Vibe-Trading은 어떠한 토큰이나 밈코인도 발행하거나 공식적으로 지지한 적이 없습니다. 해당 토큰을 구매하거나 지갑을 연결하거나 어떠한 서명도 하지 마세요. [자세히 보기](SECURITY.md#official-channels--impersonation).-- **2026-10-09** 🛠️ **채널 설정 및 백테스트 수정**: URL에 포함된 인증 정보를 보존하고 연결에 영향을 주지 않는 설정은 재연결 없이 적용합니다. 저장·재시작 결과를 웹에서 9개 언어로 표시합니다 ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). 옵션 가격의 연율화와 초기 자금을 반영한 낙폭을 수정하고, 누락된 자산 값에서 수익률을 만들어 내지 않습니다. 암호화폐·홍콩 주식 식별과 캐시 복구를 개선하고 기본 A주 경로에서 mootdx를 제외했습니다. 13개 PR은 [CHANGELOG](CHANGELOG.md)를 참조하세요.+- **2026-10-09** 🛠️ **채널 설정 및 백테스트 수정**: 재연결 없는 설정 업데이트에서 URL 인증 정보와 WeChat 인증 후 서버 주소를 보존하며, 저장·재시작 결과를 웹에서 9개 언어로 표시합니다 ([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737), [#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742), [#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744)). 여러 시장의 옵션 변동성은 각 시점까지 알려진 타임스탬프만 사용하고, 낙폭은 초기 자금을 반영합니다. 암호화폐·귀금속 데이터 경로, 홍콩 주식 중복 판별, 캐시 복구, 과학적 표기 금액 및 누락된 자산 값 검증을 수정했습니다. 기본 A주 경로에서 mootdx를 제외했습니다. 13개 PR은 [CHANGELOG](CHANGELOG.md)를 참조하세요.- **2026-10-08** 🔐 **PDF 보고서 비밀번호 보호와 증권사 조회 수정**: 예약 이메일 PDF에 AES-256 보호를 선택할 수 있으며 Web, CLI 및 에이전트 확인에 반영됩니다. 비밀번호는 비공개 채널 설정에만 저장합니다([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709)). KIS는 세 거래 경로를 조회하고 명시적으로 만료된 토큰을 한 번만 갱신하며 불완전한 조회는 오류로 처리합니다([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726)). 설명 뒤의 전체 파생 수식을 보존하고 증거 검증을 유지합니다([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728)).diff --git a/README_zh.md b/README_zh.mdindex 24a7a940b..70af20f37 100644--- a/README_zh.md+++ b/README_zh.md@@ -52,7 +52,7 @@> ⚠️ **安全警告:** X 账号 `VibeTrading_HKU`、Virtuals 项目 `101845` 及代币合约 `0x640BDBF77b6447E8b7DB7894cED84BD1c40571f4` 均非 Vibe-Trading 官方。我们从未发行或背书任何代币或 meme 币。请勿购买、连接钱包或签名。[详细说明](SECURITY.md#official-channels--impersonation)。-- **2026-10-09** 🛠️ **渠道设置与回测修正**:渠道设置保留 URL 内嵌凭证,允许名单等实时读取的配置可不中断连接地更新;Web 以九种语言说明保存和重启结果([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)、[#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)、[#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744))。期权定价年化与运行口径一致,回撤纳入初始资金,验证不再为缺失净值制造收益。修正加密货币/港股识别和缓存恢复,mootdx 移出默认 A 股链。全部十三项 PR 见 [CHANGELOG](CHANGELOG.md)。+- **2026-10-09** 🛠️ **渠道设置与回测修正**:原地更新渠道设置时保留 URL 内嵌凭证和微信认证后的服务地址,Web 以九种语言说明保存与重启结果([#1737](https://github.com/HKUDS/Vibe-Trading/pull/1737)、[#1742](https://github.com/HKUDS/Vibe-Trading/pull/1742)、[#1744](https://github.com/HKUDS/Vibe-Trading/pull/1744))。跨市场期权波动率仅使用截至当前时点的时间戳,回撤纳入初始资金。修正加密货币/贵金属数据源路由、港股重复识别、缓存恢复、科学计数金额解析及缺失净值验证;mootdx 移出默认 A 股链。全部十三项 PR 见 [CHANGELOG](CHANGELOG.md)。- **2026-10-08** 🔐 **PDF 报告密码保护与券商读取修复**:定时邮件 PDF 可选 AES-256 密码保护,覆盖 Web、CLI 模板和 Agent 确认入口;密码只保存在渠道私有配置中([#1709](https://github.com/HKUDS/Vibe-Trading/pull/1709))。KIS 读取三个交易场所的订单,明确过期的 token 只刷新一次,不完整的读取返回错误([#1726](https://github.com/HKUDS/Vibe-Trading/pull/1726))。派生公式保留说明标签之后的完整算式,证据核验规则保持不变([#1728](https://github.com/HKUDS/Vibe-Trading/pull/1728))。diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.pyindex b599bfa7e..b6748b669 100644--- a/agent/backtest/correlation.py+++ b/agent/backtest/correlation.py@@ -39,6 +39,11 @@ def infer_market(code: str) -> str:code_upper = code.strip().upper()if canonical_fx_pair(code_upper):return "forex"+ # The shared classifier distinguishes known crypto/USD pairs from metals+ # and FX. Resolve those before the permissive crypto spelling fallback.+ detected = _detect_market(code_upper)+ if detected != "a_share":+ return detectedcrypto_suffixes = ("USDT", "BTC", "ETH", "BNB", "SOL", "ADA", "DOGE")if ("/" in code_upper@@ -52,9 +57,6 @@ def infer_market(code: str) -> str:)):return "crypto"- detected = _detect_market(code_upper)- if detected != "a_share":- return detectedif code_upper.endswith(".HK"):return "hk_equity"if code_upper.endswith((".SH", ".SZ", ".BJ")):diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.pyindex 456fa2c06..f016c872a 100644--- a/agent/backtest/engines/options_portfolio.py+++ b/agent/backtest/engines/options_portfolio.py@@ -51,18 +51,23 @@ def historical_volatility((the leading warm-up and NaN gaps). Backfilling the first computedwindow here would price bars before it with information from thewindow's own end (#1293).- bars_per_year: Bars per elapsed calendar year on this series' own- cadence. ``None`` is the cross-market convention the runner passes- (#1239) and resolves through ``effective_bars_per_year`` from the- observed span, exactly as the metrics do -- so a leg is priced and- graded on one cadence instead of two. Crypto venues serve 365 daily- bars and okx hourly bars 8760, neither of which is 252.+ bars_per_year: Known annual bar count, or ``None`` for a cross-market+ run. With ``None``, estimate each bar's cadence from return+ intervals observed up to that bar, using elapsed seconds so+ intraday bars retain their frequency. Future timestamps must not+ affect historical prices; end-of-run metric annualisation is a+ separate calculation.Returns:Annualised historical volatility Series."""if bars_per_year is None:- bars_per_year = effective_bars_per_year(close.index)+ # An expanding mean of elapsed return intervals is causal, including+ # weekends and market closures already observed. Count intervals, not+ # prices: n prices contain n - 1 returns. Preserve fractional days.+ spacing = pd.Series(close.index, index=close.index).diff().dt.total_seconds()+ mean_spacing = spacing.expanding().mean()+ bars_per_year = pd.Timedelta(days=365.25).total_seconds() / mean_spacing.where(mean_spacing > 0)log_ret = np.log(close / close.shift(1))hv = log_ret.rolling(window=window).std() * np.sqrt(bars_per_year)return hv.fillna(default_iv)@@ -249,10 +254,9 @@ def run_options_backtest(print(json.dumps({"error": "No data fetched"}))sys.exit(1)- # Compute implied volatility (approximated by historical volatility) on the- # cadence this run is annualised on, so legs are priced and graded alike.- # Each code resolves a None from its own span: a cross-market basket has no- # single factor, which is why the runner passes None at all.+ # Each cross-market underlying estimates its cadence using only timestamps+ # known at each bar. Reporting metrics may inspect the whole finished run;+ # the volatility used to price historical trades may not.iv_map: Dict[str, pd.Series] = {}for code, df in data_map.items():iv_map[code] = historical_volatility(diff --git a/agent/src/channels/base.py b/agent/src/channels/base.pyindex 0a822265a..dd13a6b35 100644--- a/agent/src/channels/base.py+++ b/agent/src/channels/base.py@@ -89,19 +89,30 @@ class BaseChannel(ABC):return {"ok": False, "code": "unsupported"}def refresh_config(self, section: dict[str, Any]) -> bool:- """Swap in *section* without reconnecting; False if validation fails.+ """Refresh declared live fields; preserve runtime connection state.- Re-validates via the same path ``__init__`` used (the config model's- ``model_validate``, else a dict copy). Only ``hot_reload_noop_keys``- reach here, so live reads see new values while the connection stays up;- on error the old config is kept and the caller does a full reload.+ Validate the stored section, then copy only ``hot_reload_noop_keys``+ into the current config. Login may have resolved connection fields+ that are absent from storage, such as Weixin's authenticated base URL.+ On validation failure keep the old config and request a full reload."""try:model_cls = type(self.config)if hasattr(model_cls, "model_validate"):- self.config = model_cls.model_validate(section)+ computed = set(model_cls.model_computed_fields)+ fresh = model_cls.model_validate(section).model_dump(by_alias=True, exclude=computed)+ current = self.config.model_dump(by_alias=True, exclude=computed)+ current.update({key: fresh[key] for key in self.hot_reload_noop_keys if key in fresh})+ self.config = model_cls.model_validate(current)else:- self.config = dict(section)+ fresh = {**self.default_config(), **section}+ current = dict(self.config)+ for key in self.hot_reload_noop_keys:+ if key in fresh:+ current[key] = fresh[key]+ else:+ current.pop(key, None)+ self.config = currentexcept Exception: # noqa: BLE001 - a rejected section must not strand the adapterlogger.debug("refresh_config rejected section for %s", self.name, exc_info=True)return Falsediff --git a/agent/src/entities/ingest.py b/agent/src/entities/ingest.pyindex bc08435dd..10af9ed30 100644--- a/agent/src/entities/ingest.py+++ b/agent/src/entities/ingest.py@@ -174,7 +174,8 @@ def _to_plain_number(text: str, decimal_separator: str | None) -> str:f"{text.replace(',', '.')} (comma is the decimal separator); pass ""decimal_separator='.' or decimal_separator=',' to say which")- if has_dot and text.count(".") == 1 and len(text.rpartition(".")[2]) == 3:+ dot_tail = text.rpartition(".")[2]+ if has_dot and text.count(".") == 1 and len(dot_tail) == 3 and dot_tail.isdigit():# A lone dot followed by anything other than exactly three digits can# only be a decimal point -- European grouping never uses a group of# that width. Three digits is where it turns genuinely ambiguous.diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 99a9c7296..dad25ff78 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -66,13 +66,17 @@ _SOURCE_PATTERNS = [def detect_source(code: str) -> str:"""Infer the best loader source for a normalized symbol."""- for pattern, source in _SOURCE_PATTERNS:- if pattern.match(code):- return sourcefrom backtest.engines._market_hooks import _detect_marketfrom backtest.loaders.registry import FALLBACK_CHAINS- market = _detect_market(code)+ market = _detect_market(code.strip().upper())+ for pattern, source in _SOURCE_PATTERNS:+ if pattern.match(code):+ # XXX/USD also matches known crypto bases. Keep the shared market+ # classification authoritative over this broad forex-source rule.+ if source == "mt5" and market == "crypto":+ continue+ return sourceif market == "a_share":return "tushare" # Keep the documented fallback for unknown symbols.chain = FALLBACK_CHAINS.get(market, [])diff --git a/agent/tests/test_analysis_reliability.py b/agent/tests/test_analysis_reliability.pyindex f43c47678..e0689f5cb 100644--- a/agent/tests/test_analysis_reliability.py+++ b/agent/tests/test_analysis_reliability.py@@ -146,6 +146,23 @@ def test_readiness_snapshots_and_single_asset_validation():alpha_routes.ALPHA_BENCH_JOBS.pop(job_id, None)[email protected]("token,ready", [("", False), (" \t\n", False), ("synthetic-token", True)])+def test_alpha_readiness_requires_a_nonblank_tushare_token(monkeypatch, token, ready):+ from src.config import accessor++ config = accessor.get_env_config()+ config = config.model_copy(update={"data": config.data.model_copy(update={"tushare_token": token})})+ monkeypatch.setattr(accessor, "get_env_config", lambda: config)+ find_spec = alpha_routes.importlib.util.find_spec+ monkeypatch.setattr(+ alpha_routes.importlib.util, "find_spec",+ lambda name: object() if name == "tushare" else find_spec(name),+ )+ client = TestClient(api_server.app, client=("127.0.0.1", 50000))+ status = client.get("/alpha/readiness").json()["universes"]["csi300"]+ assert status == {"ready": ready, "reason": "tushare_ready" if ready else "tushare_token_missing"}++def test_lost_submission_response_reuses_job_and_refuses_changed_parameters(monkeypatch):client = TestClient(api_server.app, client=("127.0.0.1", 50000))job_id = "a" * 32diff --git a/agent/tests/test_channel_noop_refresh.py b/agent/tests/test_channel_noop_refresh.pyindex 0e7e2edb5..2430be00e 100644--- a/agent/tests/test_channel_noop_refresh.py+++ b/agent/tests/test_channel_noop_refresh.py@@ -15,6 +15,7 @@ from pathlib import Pathfrom typing import Anyimport pytest+import httpxfrom fastapi.testclient import TestClientimport api_server@@ -24,6 +25,7 @@ from src.channels.base import BaseChannelfrom src.channels.bus.queue import MessageBusfrom src.channels.feishu import FeishuChannel, FeishuConfigfrom src.channels.manager import ChannelManager+from src.channels.weixin import WeixinChannelCLIENT_ID = "ding-client-id-1234567890"STORED_SECRET = "stored-secret-abcdefghij"@@ -341,3 +343,56 @@ def test_signal_policy_put_refreshes_without_counting_computed_fields(tmp_path,assert response.json()["applied"] == "refreshed"assert manager.reload_calls == []assert channel.is_allowed("bob") and not channel.is_allowed("alice")+++def test_weixin_refresh_preserves_the_authenticated_endpoint(tmp_path, monkeypatch):+ monkeypatch.setenv('VIBE_TRADING_HOME', str(tmp_path))+ section = {'enabled': True, 'state_dir': str(tmp_path), 'allow_from': ['alice']}+ (tmp_path / 'account.json').write_text(json.dumps({+ 'token': 'synthetic-only-token', 'base_url': 'https://region.example.test',+ }))+ channel = WeixinChannel(section, MessageBus())+ assert channel._load_state()+ manager = ChannelManager({}, channel.bus)+ manager.channels['weixin'] = channel+ seen = []++ def reply(request):+ seen.append(request.url.host)+ return httpx.Response(200, json={'ok': True})++ async def scenario():+ async with httpx.AsyncClient(transport=httpx.MockTransport(reply)) as client:+ channel._client = client+ await channel._api_get('ilink/bot/getupdates')+ assert await manager.refresh_channel_config('weixin', dict(section, allow_from=['bob']))+ assert channel.config.allow_from == ['bob']+ await channel._api_get('ilink/bot/getupdates')++ asyncio.run(scenario())+ assert seen == ['region.example.test', 'region.example.test']++[email protected]("allow_from", [["bob"], []])+def test_weixin_full_form_preserves_login_state_and_can_clear_allowlist(tmp_path, monkeypatch, allow_from):+ section = {"enabled": True, "state_dir": str(tmp_path), "allow_from": ["alice"]}+ (tmp_path / "account.json").write_text(json.dumps({+ "token": "synthetic-only-token", "base_url": "https://region.example.test",+ }))+ channel = WeixinChannel(section, MessageBus())+ assert channel._load_state()+ manager = ChannelManager({}, channel.bus)+ manager.channels["weixin"] = channel+ client = _client(+ tmp_path, monkeypatch, channels={"weixin": section},+ runtime=_FakeRuntime(running=True, manager=manager),+ )+ values = client.get("/channels/config").json()["channels"]["weixin"]["values"]+ response = client.put("/channels/config/weixin", json={"config": dict(values, allow_from=allow_from)})+ assert response.status_code == 200, response.text+ assert response.json()["applied"] == "refreshed"+ assert manager.channels["weixin"] is channel+ assert channel.config.allow_from == allow_from+ assert channel.config.base_url == "https://region.example.test"+ channel._save_state()+ assert json.loads((tmp_path / "account.json").read_text())["base_url"] == "https://region.example.test"diff --git a/agent/tests/test_entities_spine.py b/agent/tests/test_entities_spine.pyindex a9855cac9..3849f3e60 100644--- a/agent/tests/test_entities_spine.py+++ b/agent/tests/test_entities_spine.py@@ -15,7 +15,7 @@ from src.entities.cashflow import ()from src.entities.ingest import CashFlowIngestError, load_cashflowsfrom src.entities.cashflow import FxRate, FxRateTable, MissingExchangeRateError, translate_cashflows-from src.entities.ingest import EntityPanel, PanelIngestError, PanelObservation, load_panel+from src.entities.ingest import PanelIngestError, PanelObservation, load_panelfrom src.entities.models import (Bond,Entity,@@ -1075,3 +1075,23 @@ def test_panel_path_does_not_touch_the_bar_price_panel_gate():# 1W / 1M are bar sizes the runner builds from daily bars (#1479); this# path still adds no interval of its own.assert _VALID_INTERVALS == {"1m", "5m", "15m", "30m", "1H", "4H", "1D", "1W", "1M"}++[email protected]('amount,expected', [+ ('1.2e3', 1200.), ('1.2E3', 1200.), ('1.23e3', 1230.),+ ('1.234e3', 1234.), ('1.2e-3', 0.0012), ('-1.2e3', -1200.),+])+def test_unambiguous_scientific_amount_is_accepted(tmp_path, amount, expected):+ path = tmp_path / 'flows.csv'+ kind = 'capital_call' if expected < 0 else 'coupon'+ path.write_text(f'date,amount,kind,currency\n2024-03-31,{amount},{kind},USD\n')+ assert load_cashflows(path)[0].amount == pytest.approx(expected)++[email protected]("value", ["1.2e3", "1.2E3", "1.234e3"])+def test_panel_scientific_amount_uses_the_same_parser(tmp_path, value):+ path = _write_csv(+ tmp_path, "panel.csv",+ f"entity,date,metric,value,currency,unit\nFUNDA,2024-01-01,nav,{value},USD,USD\n",+ )+ assert list(load_panel(path))[0].value == pytest.approx(float(value))diff --git a/agent/tests/test_equity_crypto_suffix_regressions.py b/agent/tests/test_equity_crypto_suffix_regressions.pyindex 6a49844ef..37a5f293e 100644--- a/agent/tests/test_equity_crypto_suffix_regressions.py+++ b/agent/tests/test_equity_crypto_suffix_regressions.py@@ -1,6 +1,8 @@import pandas as pdimport pytestfrom backtest.correlation import infer_market, _fetch_price_series+from backtest.loaders import registry+from src.market_data import fetch_market_data@pytest.mark.parametrize("symbol", ["ABNB", "ABNB.US", "SOL", "SOL.US"])@@ -104,3 +106,64 @@ def test_correlation_slash_crypto_uses_crypto_chain(monkeypatch):assert list(rows) == ["ETH/USD"]assert rows["ETH/USD"]["close"].tolist() == [100, 110]assert seen == ["ETH/USD"]+++def _routing_frame():+ return pd.DataFrame(+ {'open': [100., 101.], 'high': [101., 102.], 'low': [99., 100.],+ 'close': [100., 101.], 'volume': [1., 1.]},+ index=pd.date_range('2025-01-01', periods=2, name='date'),+ )++[email protected]('symbol', ['XAU/USD', 'XAG/USD', 'XPT/USD', 'XPD/USD'])+def test_precious_metals_keep_the_forex_loader(symbol, monkeypatch):+ calls = []++ class Forex:+ def is_available(self):+ return True++ def fetch(self, codes, **kwargs):+ calls.append('forex')+ return {code: _routing_frame() for code in codes}++ class Crypto:+ def is_available(self):+ return True++ def fetch(self, codes, **kwargs):+ calls.append('crypto')+ return {}++ monkeypatch.setattr(registry, '_ensure_registered', lambda: None)+ monkeypatch.setattr(registry, 'get_source_order_override', lambda market: None)+ monkeypatch.setattr(registry, 'FALLBACK_CHAINS', {'forex': ['fx'], 'crypto': ['coin']})+ monkeypatch.setattr(registry, 'LOADER_REGISTRY', {'fx': Forex, 'coin': Crypto})+ rows = _fetch_price_series([symbol], '2025-01-01', '2025-01-02')+ assert calls == ['forex']+ assert symbol in rows++[email protected]('symbol', ['BTC/USD', 'ETH/USD', 'BNB/USD', 'SOL/USD', 'ADA/USD', 'DOGE/USD'])+def test_market_data_auto_reaches_crypto_chain(symbol, monkeypatch):+ calls = []+ monkeypatch.setattr(registry, 'refresh_source_order_overrides', lambda: None)+ monkeypatch.setattr(registry, 'get_source_order_override', lambda market: None)+ monkeypatch.setattr(registry, 'FALLBACK_CHAINS', {'forex': ['mt5'], 'crypto': ['okx']})++ def resolve(source):+ class Loader:+ name = source++ def fetch(self, codes, *args, **kwargs):+ calls.append(source)+ return {code: _routing_frame() for code in codes} if source == 'okx' else {}+ return Loader++ result = fetch_market_data(+ codes=[symbol], start_date='2025-01-01', end_date='2025-01-02',+ loader_resolver=resolve,+ )+ assert calls == ['okx']+ assert result[symbol]diff --git a/agent/tests/test_options_hv_bars_per_year.py b/agent/tests/test_options_hv_bars_per_year.pyindex 28681a365..487d647b0 100644--- a/agent/tests/test_options_hv_bars_per_year.py+++ b/agent/tests/test_options_hv_bars_per_year.py@@ -1,24 +1,8 @@-"""Regression: the vol that prices option legs must annualise on the run's cadence.--``run_options_backtest`` already receives the runner-resolved ``bars_per_year``-and forwards it to ``_calc_options_metrics``, where ``None`` is resolved through-``backtest.metrics.effective_bars_per_year`` -- the shared span-derived factor-whose own docstring promises that "the Sharpe, the annualised volatility, and-the validation Sharpe in a single run card are annualised identically".--``historical_volatility`` is that annualised volatility for the options engine:-it produces the per-bar vol every leg is opened, marked and greeked at. It-annualised at a hardcoded ``np.sqrt(252)`` and its call site never forwarded the-factor the run already knew, so a venue that does not trade 252 bars a year-priced its legs on one cadence and reported its metrics on another. Every crypto-source maps to 365 daily bars, and okx hourly bars to 8760, so an at-the-money-30-day call was marked roughly 16% too cheap on a daily crypto run and far worse-intraday -- silently, into ``trades.csv``, ``greeks.csv``, ``equity.csv``,-``metrics.csv`` and the ``backtest_summary`` tool result.--Same convention as ``8afa3879`` ("fix(portfolio): annualize weekly and monthly-risk bars correctly"), which resolved the risk x-ray's hardcoded 252 through-``calc_bars_per_year``; this is the options engine's copy of that bug.+"""Options pricing uses the supplied cadence or a causal per-bar estimate.++Cross-market pricing may use timestamps known at the current bar only.+Finished-run reporting metrics may use their full span, but reusing that span+to price earlier trades creates lookahead."""from __future__ import annotations@@ -76,16 +60,10 @@ def test_hv_defaults_to_252_so_daily_equity_runs_are_unchanged() -> None:)-def test_hv_none_resolves_from_the_observed_span() -> None:- """``None`` means cross-market: measure the cadence, as the metrics do.-- The runner passes ``bars_per_year=None`` for a basket that spans markets- (#1239). Restated here from the documented convention rather than by- calling the helper, so the test pins the convention and not the code.- """+def test_hv_none_resolves_daily_return_cadence_causally() -> None:+ """Daily return intervals annualise to calendar days, without future bars."""close = _alternating_close()- span_days = (close.index[-1] - close.index[0]).days- expected_factor = int(len(close) / (span_days / 365.25))+ expected_factor = 365.25assert expected_factor != 252, "fixture must exercise a non-default factor"hv = historical_volatility(close, default_iv=DEFAULT_IV, bars_per_year=None)@@ -93,6 +71,26 @@ def test_hv_none_resolves_from_the_observed_span() -> None:pd.testing.assert_series_equal(hv, _annualised_hv(close, expected_factor))[email protected]("frequency,yearly", [("1min", 365.25 * 1440), ("1h", 365.25 * 24), ("7D", 365.25 / 7)])+def test_cross_market_hv_preserves_elapsed_subday_and_weekly_intervals(frequency, yearly):+ close = _alternating_close()+ close.index = pd.date_range("2024-01-01", periods=len(close), freq=frequency)+ pd.testing.assert_series_equal(+ historical_volatility(close, bars_per_year=None), _annualised_hv(close, yearly),+ )++[email protected]("frequency", ["D", "B", "1h", "1min"])+def test_future_cadence_changes_cannot_change_past_volatility(frequency):+ close = _alternating_close()+ past_dates = pd.date_range("2024-01-01", periods=45, freq=frequency)+ future_dates = pd.date_range(past_dates[-1] + pd.Timedelta(days=10), periods=15, freq="7D")+ close.index = past_dates.append(future_dates)+ past = historical_volatility(close.iloc[:45], bars_per_year=None)+ extended = historical_volatility(close, bars_per_year=None).iloc[:45]+ pd.testing.assert_series_equal(past, extended)++class _SingleCodeLoader:"""Serves one deterministic daily series, ignoring the requested window."""@@ -198,17 +196,50 @@ def test_options_backtest_prices_the_leg_on_the_run_cadence(tmp_path: Path) -> Nassert (expected - stale) / expected == pytest.approx(0.16, abs=0.01)-def test_options_backtest_cross_market_none_prices_on_the_observed_span(+def test_options_backtest_cross_market_none_prices_on_causal_cadence(tmp_path: Path,) -> None:"""``bars_per_year=None`` must reach pricing too, not just the metrics."""close = _alternating_close()fill_bar = close.index[41]- span_days = (close.index[-1] - close.index[0]).days- factor = int(len(close) / (span_days / 365.25))+ factor = 365.25price, strike, spot = _run_one_call(tmp_path, bars_per_year=None)sigma = float(_annualised_hv(close, factor).at[fill_bar])expected = bs_price(spot, strike, 30 / 365.0, 0.05, sigma, "call")assert price == pytest.approx(expected, abs=1e-4)+++def _run_call_prefix(path, count, bars_per_year):+ dates = pd.date_range('2026-01-01', periods=80)+ values = 100 * np.exp(np.cumsum(np.where(np.arange(80) % 2, 0.02, -0.015)))+ close = pd.Series(values[:count], index=dates[:count])++ class Loader:+ def fetch(self, codes, *args, **kwargs):+ return {code: pd.DataFrame({'open': close, 'close': close}) for code in codes}++ class Signals:+ def generate(self, data):+ return [{+ 'date': str(dates[40].date()), 'action': 'open', 'underlying': 'BTC-USDT',+ 'legs': [{'type': 'call', 'strike': float(values[41]),+ 'expiry': str((dates[41] + pd.Timedelta(days=30)).date()), 'qty': 1}],+ }]++ run_options_backtest(+ {'codes': ['BTC-USDT', 'AAPL.US'], 'source': 'auto', 'engine': 'options',+ 'start_date': str(dates[0].date()), 'end_date': str(dates[count-1].date()),+ 'initial_cash': 1_000_000., 'options_config': {'margin_enabled': False}},+ Loader(), Signals(), path, bars_per_year=bars_per_year,+ )+ trades = pd.read_csv(path / 'artifacts' / 'trades.csv')+ return float(trades[trades['side'] == 'buy'].iloc[0]['price'])++[email protected]('factor', [None, 365], ids=['cross-market', 'fixed-cadence-control'])+def test_future_bars_do_not_reprice_a_past_option_fill(tmp_path, factor):+ prefix = _run_call_prefix(tmp_path / 'prefix', 45, factor)+ extended = _run_call_prefix(tmp_path / 'extended', 80, factor)+ assert extended == pytest.approx(prefix, abs=1e-10)