Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(trading): add 6 SDK broker connectors with paper+live order placement

Haozhe Wu8563d5e78b27
diff --git a/README.md b/README.md
index d5206c117..05fb13146 100644
--- a/README.md
+++ b/README.md
@@ -46,12 +46,13 @@
## 📰 News
+- **2026-06-02** 🔌 **Six new broker connectors (Tiger / Longbridge / Alpaca / OKX / Binance / Futu)**: The connector-first trading layer gains a direct-SDK transport alongside IBKR (local) and Robinhood (MCP). Each connector exposes read-only account / positions / orders / quote / history **plus paper-account order placement** — test your strategies across these broker paper accounts. Five of them (Tiger, Alpaca, OKX, Binance, Futu) also support **bounded, mandate-gated order placement** behind the same safety model as Robinhood: a user-committed mandate (symbol universe / order size / exposure / leverage / daily cap), a filesystem kill switch, a fail-closed pre-trade gate, and a full audit ledger. **Longbridge is paper + read-only only** (its API exposes no runtime paper/live discriminator). Every paper/live distinction is a structural per-broker guard — account-id format, host separation, demo flag, or trade environment. New `trading_place_order` / `trading_cancel_order` tools; HK and A-share asset classes added to the mandate universe. Experimental / use at your own risk.
- **2026-06-01** 🚀 **v0.1.9 released** (`pip install -U vibe-trading-ai`): Rolls up everything since 0.1.8. Connector-first broker profiles (IBKR local read-only TWS / IB Gateway + Robinhood Agentic Trading behind OAuth, a committed mandate, order guard, audit ledger, and instant halt). Research Goal runtime across CLI / REST / MCP / Web. A swarm pass — live reconcile + MCP keepalive, operator-configured worker MCP tools, a strict alpha-bench random control, and a new `retry_run` to relaunch failed/stale runs (**36 MCP tools** now). The `agent/cli/` package refactor with a refreshed terminal UI, the `mootdx` no-token A-share loader, and a robustness pass across backtest / agent loop / sessions. `--version` now always matches the installed package, fixing the 0.1.8 drift ([#156](https://github.com/HKUDS/Vibe-Trading/issues/156)).
- **2026-05-31** 🔌 **Connector-first broker architecture (IBKR + Robinhood)**: Trading access now starts from a selectable connector profile instead of separate broker/live entry points. `vibe-trading connector list/use/check/account/positions/orders/quote/history` and the MCP `trading_*` tools share the same selected profile, where paper/live is an attribute of the connector. IBKR can be used immediately through a local read-only TWS / IB Gateway profile, while the official IBKR remote MCP path is seeded as an OAuth `mcp.read` probe until stable read tool names are available. Robinhood Agentic Trading remains the bounded live MCP connector behind OAuth, a committed mandate, order guard, audit ledger, and instant halt.
-- **2026-05-30** 🧰 **Robustness pass — backtest, agent loop, sessions**: LLM-generated signal engines now pass pre-flight interface validation before instantiation, catching circular self-imports, a missing `generate()`, non-defaulted `__init__` args, and wrong return types with actionable JSON errors instead of raw tracebacks ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149)); a follow-up routes source-level AST validation errors through the same clean JSON envelope. The agent loop no longer burns all 50 iterations into a `failed` status with no output — it mirrors the swarm worker's wrap-up nudge at 80% of the iteration budget and drops tool definitions on the last iteration to force a final text answer ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)), guarded to fire only mid-run so it never displaces research-goal context. Session message writes now `flush + fsync` each append so expensive AI responses survive a mid-write crash, and the read path skips corrupted JSONL lines (logging the first 200 chars for recovery) instead of 500-ing the whole `/messages` endpoint ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). The Web composer also fixes IME Enter handling so a composition-confirming Enter no longer submits mid-word ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).
<details>
<summary>Earlier news</summary>
+- **2026-05-30** 🧰 **Robustness pass — backtest, agent loop, sessions**: LLM-generated signal engines now pass pre-flight interface validation before instantiation, catching circular self-imports, a missing `generate()`, non-defaulted `__init__` args, and wrong return types with actionable JSON errors instead of raw tracebacks ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149)); a follow-up routes source-level AST validation errors through the same clean JSON envelope. The agent loop no longer burns all 50 iterations into a `failed` status with no output — it mirrors the swarm worker's wrap-up nudge at 80% of the iteration budget and drops tool definitions on the last iteration to force a final text answer ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)), guarded to fire only mid-run so it never displaces research-goal context. Session message writes now `flush + fsync` each append so expensive AI responses survive a mid-write crash, and the read path skips corrupted JSONL lines (logging the first 200 chars for recovery) instead of 500-ing the whole `/messages` endpoint ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). The Web composer also fixes IME Enter handling so a composition-confirming Enter no longer submits mid-word ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).
- **2026-05-29** 🔐 **Robinhood Agentic Trading support (opt-in, bounded autonomy)**: Adds support for Robinhood Agentic Trading (remote MCP, OAuth). Off and read-only by default; the agent acts only inside a user-committed mandate (symbols / order size / exposure / leverage / daily cap), with a filesystem-level instant kill switch, preemptive flatten, mandate auto-expiry, a full audit ledger, and a persistent autonomous runner. No custody, no venue — the broker holds funds and executes; we only relay intent. Experimental / use at your own risk.
- **2026-05-28** 🧪 **Swarm safety + strict alpha gate + worker MCP**: Swarm DAG blocks downstream tasks when upstream fails ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). New `run_bench_strict()` adds a same-universe random control + OOS split to catch factors that just track market beta ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), thanks @Soli22de). Swarm workers can call operator-configured external MCP servers, with trust boundary pinned ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), thanks @shadowinlife).
- **2026-05-27** 📊 **mootdx A-share data source + output polish**: New `mootdx` loader speaks the native 通达信 TCP protocol for A-share OHLCV (no auth, no IP rate-limit, daily + intraday with 25-page walk-back pagination), slotting between tushare and akshare in the fallback chain ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). CCXT loader now reads `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` so Binance/OKX public data works from restricted networks ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), thanks @ruok808). Final-answer rendering also dropped the ugly full-width `---` horizontal separators on CLI and Web: the system prompt now nudges the agent toward markdown tables and `##` headings, the CLI renderer strips standalone HRs as defense-in-depth, and the chat bubble hides any `<hr>` that slips through ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), thanks @sdwxm188).
diff --git a/README_ar.md b/README_ar.md
index 77d561917..51d4437e8 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -46,12 +46,13 @@
## 📰 الأخبار
+- **2026-06-02** 🔌 **ستة connectors وسطاء جديدة (Tiger / Longbridge / Alpaca / OKX / Binance / Futu)**: تكتسب طبقة التداول التي تعتمد أولاً على connectors ناقلاً مباشراً عبر SDK إلى جانب IBKR (محلي) وRobinhood (MCP). يكشف كل connector عن حساب / مراكز / أوامر / quote / تاريخ للقراءة فقط، بالإضافة إلى وضع أوامر على حساب PAPER — اختبر استراتيجياتك عبر حسابات paper الخاصة بهؤلاء الوسطاء. كما يدعم خمسة منها (Tiger وAlpaca وOKX وBinance وFutu) وضع أوامر محدوداً ومحكوماً بـ mandate خلف نفس نموذج السلامة المطبّق على Robinhood: mandate يلتزم به المستخدم (نطاق الرموز / حجم الأمر / التعرّض / الرافعة / الحد اليومي)، وkill switch على مستوى الملفات، وبوّابة استباقية قبل التداول تُغلَق عند الفشل، وسجل تدقيق كامل. أما Longbridge فهو للقراءة فقط + paper حصراً (لا تكشف واجهته عن مميِّز زمن تشغيل بين paper وlive). كل تمييز بين paper وlive هو حارس بنيوي خاص بكل وسيط. أدوات جديدة `trading_place_order` / `trading_cancel_order`؛ وأُضيفت فئتا الأصول HK وأسهم A إلى universe الخاص بـ mandate. تجريبي / الاستخدام على مسؤوليتك.
- **2026-06-01** 🚀 **إصدار v0.1.9** (`pip install -U vibe-trading-ai`): يجمع كل ما استُجد منذ 0.1.8. ملفات وسطاء تعتمد أولاً على connectors (IBKR محلي للقراءة فقط من TWS / IB Gateway + Robinhood Agentic Trading خلف OAuth وmandate مُلتزم وorder guard وسجل تدقيق وhalt فوري). زمن تشغيل Research Goal عبر CLI / REST / MCP / Web. تحديث swarm — reconcile حيّ + إبقاء MCP حياً، وأدوات MCP لعمّال swarm يضبطها المشغّل، وتحكم عشوائي صارم في alpha-bench، و`retry_run` جديد لإعادة تشغيل runs الفاشلة/القديمة (الآن **36 أداة MCP**). إعادة هيكلة حزمة `agent/cli/` مع واجهة طرفية محدّثة، ومحمّل `mootdx` لأسهم A بدون توكن، وجولة متانة عبر backtest / agent loop / sessions. أصبح `--version` يطابق دائماً الحزمة المثبّتة، مصلحاً انحراف 0.1.8 ([#156](https://github.com/HKUDS/Vibe-Trading/issues/156)).
- **2026-05-31** 🔌 **بنية وسطاء تعتمد أولاً على connectors (IBKR + Robinhood)**: يبدأ الوصول إلى التداول الآن من connector profile قابل للاختيار، لا من مداخل منفصلة للوسيط أو live. أوامر `vibe-trading connector list/use/check/account/positions/orders/quote/history` وأدوات MCP `trading_*` تشترك في نفس profile المحدد، حيث تكون paper/live مجرد خاصية ضمن connector. يمكن استخدام IBKR فوراً عبر profile محلي للقراءة فقط من TWS / IB Gateway، بينما يُزرع مسار MCP الرسمي البعيد لـ IBKR كتحقق OAuth بنطاق `mcp.read` إلى أن تتوفر أسماء أدوات قراءة مستقرة. يظل Robinhood Agentic Trading هو connector MCP حيّاً ومحدوداً خلف OAuth وmandate مُلتزم وorder guard وسجل تدقيق وhalt فوري.
-- **2026-05-30** 🧰 **جولة متانة — backtest وagent loop وsession**: تمرّ الآن signal engines المولّدة بواسطة LLM بتحقق مسبق من الواجهة قبل الإنشاء، فتلتقط مبكراً الأخطاء الشائعة مثل self-import الدائري، وغياب `generate()`، ووسائط `__init__` بلا قيم افتراضية، ونوع الإرجاع الخاطئ، وتُرجِع أخطاء JSON قابلة للتنفيذ بدل traceback خام ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149))؛ ومتابعةٌ لاحقة توجّه أخطاء تحقق AST على مستوى المصدر عبر نفس مغلّف JSON النظيف. لم يعد agent loop يستنزف الخمسين تكراراً ليصل إلى حالة `failed` بلا أي مخرجات — فهو يحاكي أسلوب swarm worker المُجرَّب: يحقن wrap-up nudge عند 80% من ميزانية التكرار ويُسقط تعريفات الأدوات في التكرار الأخير لفرض إجابة نصية ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148))، مع حارس يجعله يُطلَق في المنتصف فقط كي لا يزيح سياق research-goal. كتابة رسائل الجلسة تجري الآن `flush + fsync` بعد كل append حتى تنجو ردود الـ AI الباهظة من تعطّل أثناء الكتابة، ويتخطّى مسار القراءة أسطر JSONL التالفة (مع تسجيل أول 200 حرف للاسترداد) بدل إعطاء 500 لنقطة `/messages` كاملة ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). كما أصلح محرّر الإدخال في الويب معالجة Enter مع IME بحيث لا يؤدي Enter لتأكيد التركيب إلى إرسال في منتصف الكلمة ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).
<details>
<summary>أخبار سابقة</summary>
+- **2026-05-30** 🧰 **جولة متانة — backtest وagent loop وsession**: تمرّ الآن signal engines المولّدة بواسطة LLM بتحقق مسبق من الواجهة قبل الإنشاء، فتلتقط مبكراً الأخطاء الشائعة مثل self-import الدائري، وغياب `generate()`، ووسائط `__init__` بلا قيم افتراضية، ونوع الإرجاع الخاطئ، وتُرجِع أخطاء JSON قابلة للتنفيذ بدل traceback خام ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149))؛ ومتابعةٌ لاحقة توجّه أخطاء تحقق AST على مستوى المصدر عبر نفس مغلّف JSON النظيف. لم يعد agent loop يستنزف الخمسين تكراراً ليصل إلى حالة `failed` بلا أي مخرجات — فهو يحاكي أسلوب swarm worker المُجرَّب: يحقن wrap-up nudge عند 80% من ميزانية التكرار ويُسقط تعريفات الأدوات في التكرار الأخير لفرض إجابة نصية ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148))، مع حارس يجعله يُطلَق في المنتصف فقط كي لا يزيح سياق research-goal. كتابة رسائل الجلسة تجري الآن `flush + fsync` بعد كل append حتى تنجو ردود الـ AI الباهظة من تعطّل أثناء الكتابة، ويتخطّى مسار القراءة أسطر JSONL التالفة (مع تسجيل أول 200 حرف للاسترداد) بدل إعطاء 500 لنقطة `/messages` كاملة ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). كما أصلح محرّر الإدخال في الويب معالجة Enter مع IME بحيث لا يؤدي Enter لتأكيد التركيب إلى إرسال في منتصف الكلمة ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).
- **2026-05-29** 🔐 **دعم Robinhood Agentic Trading (اختياري، استقلالية محدودة)**: أُضيف دعم Robinhood Agentic Trading (MCP عن بُعد، OAuth). مُعطَّل وللقراءة فقط افتراضياً؛ ويتداول الوكيل تلقائياً فقط ضمن mandate يلتزم به المستخدم (الرموز / حجم الأمر / التعرّض / الرافعة / الحد اليومي)، مع kill switch فوري على مستوى الملفات، وتصفية استباقية للمراكز، وانتهاء صلاحية تلقائي لـ mandate، وسجل تدقيق كامل، و runner مستقل دائم. لا حفظ للأموال ولا تشغيل لمنصة تداول — الوسيط يحتفظ بالأموال وينفّذ، ونحن ننقل النية فقط. تجريبي / الاستخدام على مسؤوليتك.
- **2026-05-28** 🧪 **سلامة Swarm + بوّابة alpha صارمة + MCP لعمّال swarm**: يحجب Swarm DAG الآن المهام المتفرعة عندما تفشل المهمة الأعلى ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). دالة `run_bench_strict()` الجديدة تضيف فوق بوّابة IC تحكماً عشوائياً بنفس universe + قسمة train/test OOS لاصطياد العوامل التي تتبع beta السوق فقط ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143)، شكراً @Soli22de). يستطيع عمّال Swarm الآن استدعاء أدوات من خوادم MCP خارجية يضبطها المشغل، مع تثبيت حدود الثقة باختبارات مخصصة ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142)، شكراً @shadowinlife).
- **2026-05-27** 📊 **مصدر بيانات A-share عبر mootdx + تحسين الإخراج**: محمّل `mootdx` الجديد يتحدث بروتوكول 通达信 TCP الأصلي لبيانات OHLCV لأسهم A (بدون مصادقة، بدون قيود معدل لكل IP، يومي + intraday مع pagination تراجع بـ 25 صفحة)، ويُدرج بين tushare وakshare في سلسلة fallback ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). محمّل CCXT يقرأ الآن `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` ليعمل جلب بيانات Binance/OKX العامة من الشبكات المقيدة ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126)، شكراً @ruok808). عرض الإجابة النهائية أزال أيضاً فواصل `---` الأفقية القبيحة بعرض كامل على CLI وWeb: يحث system prompt الآن agent على استخدام جداول markdown وعناوين `##`، يجرّد CLI renderer أسطر HR المستقلة كدفاع متعمق، ويخفي chat bubble أي `<hr>` ينفذ عبر ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139)، شكراً @sdwxm188).
diff --git a/README_ja.md b/README_ja.md
index af5f81974..4e20bd5ac 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -46,12 +46,13 @@
## 📰 ニュース
+- **2026-06-02** 🔌 **6 つの新しいブローカー connector(Tiger / Longbridge / Alpaca / OKX / Binance / Futu)**: connector-first の取引レイヤーに、IBKR(ローカル)と Robinhood(MCP)に加えて直接 SDK トランスポートが加わりました。各 connector は読み取り専用の account / positions / orders / quote / history に加え、ペーパー口座での発注を公開します——これらのブローカーのペーパー口座で戦略を検証できます。Tiger / Alpaca / OKX / Binance / Futu の 5 つは、Robinhood と同じ安全モデルの背後で、有界かつ mandate でゲートされた発注にも対応します: ユーザーがコミットした mandate(銘柄ユニバース/注文サイズ/エクスポージャー/レバレッジ/日次上限)、ファイルレベルの kill switch、fail-closed の発注前ゲート、完全な監査台帳。Longbridge はペーパー + 読み取り専用のみです(API がランタイムでのペーパー/live 判別子を公開しないため)。すべてのペーパー/live の区別はブローカー単位の構造的ガードです。新しい `trading_place_order` / `trading_cancel_order` ツールを追加し、mandate ユニバースに香港株と A 株のアセットクラスを追加しました。実験的 / 自己責任でご利用ください。
- **2026-06-01** 🚀 **v0.1.9 リリース**(`pip install -U vibe-trading-ai`): 0.1.8 以降のすべてをまとめました。Connector-first ブローカー profile(IBKR ローカル読み取り専用 TWS / IB Gateway + OAuth・コミット済み mandate・order guard・audit ledger・instant halt の背後にある Robinhood Agentic Trading)。CLI / REST / MCP / Web を貫く Research Goal ランタイム。swarm 強化——live reconcile + MCP keepalive、operator 設定の worker MCP ツール、厳格 alpha-bench ランダムコントロール、失敗/stale run を再実行する新 `retry_run`(現在 **36 MCP tools**)。`agent/cli/` パッケージ refactor + 刷新したターミナル UI、`mootdx` トークン不要の A 株 loader、backtest / agent loop / session の堅牢性 pass。`--version` は常にインストール済みパッケージと一致し、0.1.8 のドリフトを修正([#156](https://github.com/HKUDS/Vibe-Trading/issues/156))。
- **2026-05-31** 🔌 **Connector-first ブローカーアーキテクチャ(IBKR + Robinhood)**: 取引アクセスは、個別のブローカー入口や live 入口ではなく、選択可能な connector profile から始まるようになりました。`vibe-trading connector list/use/check/account/positions/orders/quote/history` と MCP の `trading_*` ツールは同じ選択済み profile を共有し、paper/live は connector 配下の属性として扱われます。IBKR はローカル読み取り専用 TWS / IB Gateway profile ですぐ使え、公式 IBKR リモート MCP は安定した read tool 名が公開されるまで OAuth `mcp.read` probe として seed されています。Robinhood Agentic Trading は引き続き、OAuth、コミット済み mandate、order guard、audit ledger、instant halt の背後にある bounded live MCP connector です。
-- **2026-05-30** 🧰 **堅牢性パス — backtest、agent loop、session**: LLM 生成の signal engine は、インスタンス化の前にインターフェース事前検証を通すようになりました。循環 self-import、`generate()` の欠落、デフォルト値のない `__init__` 引数、誤った戻り値型といった典型ミスを早期に捕捉し、生の traceback ではなく実行可能な JSON エラーで返します ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149))。続くフォローアップで、ソースレベルの AST 検証エラーも同じクリーンな JSON エンベロープに乗せました。agent loop は 50 反復を使い切って出力のない `failed` 状態に陥らなくなりました——swarm worker の実績ある方式に倣い、反復予算の 80% で wrap-up nudge を注入し、最後の反復で tool 定義を外してテキスト回答を強制します ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148))。途中でのみ発火するようガードしてあり、research-goal の文脈を押しのけることはありません。session のメッセージ書き込みは append ごとに `flush + fsync` するようになり、高価な AI 応答が書き込み途中のクラッシュでも残ります。読み取り側は壊れた JSONL 行をスキップし(復旧用に先頭 200 文字をログ)、`/messages` エンドポイント全体を 500 にしません ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147))。Web の入力欄は IME の Enter 処理も修正し、変換確定の Enter で語の途中送信が起きないようにしました ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146))。
<details>
<summary>過去のニュース</summary>
+- **2026-05-30** 🧰 **堅牢性パス — backtest、agent loop、session**: LLM 生成の signal engine は、インスタンス化の前にインターフェース事前検証を通すようになりました。循環 self-import、`generate()` の欠落、デフォルト値のない `__init__` 引数、誤った戻り値型といった典型ミスを早期に捕捉し、生の traceback ではなく実行可能な JSON エラーで返します ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149))。続くフォローアップで、ソースレベルの AST 検証エラーも同じクリーンな JSON エンベロープに乗せました。agent loop は 50 反復を使い切って出力のない `failed` 状態に陥らなくなりました——swarm worker の実績ある方式に倣い、反復予算の 80% で wrap-up nudge を注入し、最後の反復で tool 定義を外してテキスト回答を強制します ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148))。途中でのみ発火するようガードしてあり、research-goal の文脈を押しのけることはありません。session のメッセージ書き込みは append ごとに `flush + fsync` するようになり、高価な AI 応答が書き込み途中のクラッシュでも残ります。読み取り側は壊れた JSONL 行をスキップし(復旧用に先頭 200 文字をログ)、`/messages` エンドポイント全体を 500 にしません ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147))。Web の入力欄は IME の Enter 処理も修正し、変換確定の Enter で語の途中送信が起きないようにしました ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146))。
- **2026-05-29** 🔐 **Robinhood Agentic Trading 対応(オプトイン・有界自律)**: Robinhood Agentic Trading に対応しました(リモート MCP、OAuth)。デフォルトでは無効かつ読み取り専用。エージェントはユーザーがコミットした mandate(銘柄/注文サイズ/エクスポージャー/レバレッジ/日次上限)の範囲内でのみ自律取引し、ファイルレベルの即時 kill switch、先制的なポジション手仕舞い、mandate の自動失効、完全な監査台帳、永続的な自律 runner を備えます。資金の保管なし・取引所運営なし——資金の保有と執行はブローカーが行い、こちらは意図を中継するだけです。実験的 / 自己責任でご利用ください。
- **2026-05-28** 🧪 **Swarm の安全性 + 厳格 alpha gate + worker 側 MCP**: Swarm DAG は上流タスクが失敗したとき下流タスクをブロックするようになりました ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新規 `run_bench_strict()` は IC gate に同 universe のランダムコントロール + train/test OOS 分割を追加し、市場 beta を追っているだけの偽 factor を捕捉します ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de さんに感謝)。Swarm worker は operator が設定した外部 MCP server からツールを呼べるようになり、信頼境界は専用テストで固定されています ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife さんに感謝)。
- **2026-05-27** 📊 **mootdx A 株データソース + 出力スタイル**: 新規 `mootdx` loader はネイティブ 通达信 TCP プロトコルで A 株 OHLCV を取得します(認証不要、IP 速度制限なし、日足 + 分足の 25 ページ walk-back ページング)。fallback chain では tushare と akshare の間に配置されます ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107))。CCXT loader は `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY` を読み込み、制限されたネットワークから Binance/OKX の公開データを取得できるようになりました ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), @ruok808 さんに感謝)。最終回答のレンダリングからは CLI と Web の見苦しい全幅 `---` セパレータを削除しました: system prompt は markdown table と `##` heading を促し、CLI renderer は単独 HR を defense-in-depth として除去し、chat bubble はすり抜けた `<hr>` を隠します ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), @sdwxm188 さんに感謝)。
diff --git a/README_ko.md b/README_ko.md
index 898d2c2c7..ba7b8c86e 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -46,12 +46,13 @@
## 📰 뉴스
+- **2026-06-02** 🔌 **새 브로커 connector 6종(Tiger / Longbridge / Alpaca / OKX / Binance / Futu)**: connector-first 거래 레이어에 IBKR(로컬)·Robinhood(MCP)와 나란히 direct-SDK transport가 추가되었습니다. 각 connector는 읽기 전용 account / positions / orders / quote / history에 더해 페이퍼 계좌 주문 제출을 노출하므로, 이 브로커 페이퍼 계좌들에서 전략을 검증할 수 있습니다. 그중 5종(Tiger, Alpaca, OKX, Binance, Futu)은 Robinhood와 동일한 안전 모델 뒤에서 mandate로 게이트되는 bounded 주문 제출도 지원합니다 — 사용자가 커밋한 mandate(종목 universe / 주문 규모 / 익스포저 / 레버리지 / 일일 한도), 파일 수준 kill switch, fail-closed 사전 거래 게이트, 완전한 감사 원장. Longbridge는 페이퍼 + 읽기 전용 전용입니다(API가 런타임 paper/live 구분자를 노출하지 않음). 모든 paper/live 구분은 브로커별 구조적 가드입니다. 새 `trading_place_order` / `trading_cancel_order` 도구가 추가되었고, HK·A주 asset class가 mandate universe에 들어왔습니다. 실험적 / 사용에 따른 책임은 본인에게 있습니다.
- **2026-06-01** 🚀 **v0.1.9 출시**(`pip install -U vibe-trading-ai`): 0.1.8 이후 모든 것을 롤업했습니다. Connector-first 브로커 profile(IBKR 로컬 읽기 전용 TWS / IB Gateway + OAuth·커밋된 mandate·order guard·audit ledger·instant halt 뒤의 Robinhood Agentic Trading). CLI / REST / MCP / Web을 아우르는 Research Goal 런타임. swarm 패스 — live reconcile + MCP keepalive, operator가 설정한 worker MCP 도구, 엄격 alpha-bench 랜덤 컨트롤, 실패/오래된 run을 다시 실행하는 새 `retry_run`(이제 **36개 MCP tools**). `agent/cli/` 패키지 리팩토링 + 새 터미널 UI, `mootdx` 무토큰 A주 loader, backtest / agent loop / session 견고성 패스. `--version`은 이제 항상 설치된 패키지와 일치하여 0.1.8 드리프트를 수정합니다([#156](https://github.com/HKUDS/Vibe-Trading/issues/156)).
- **2026-05-31** 🔌 **Connector-first 브로커 아키텍처(IBKR + Robinhood)**: 거래 접근은 이제 별도의 브로커/live 진입점이 아니라 선택 가능한 connector profile에서 시작합니다. `vibe-trading connector list/use/check/account/positions/orders/quote/history`와 MCP `trading_*` 도구는 동일한 선택 profile을 공유하며, paper/live는 connector의 속성으로 다룹니다. IBKR은 로컬 읽기 전용 TWS / IB Gateway profile로 즉시 사용할 수 있고, 공식 IBKR 원격 MCP 경로는 안정적인 read tool 이름이 제공될 때까지 OAuth `mcp.read` probe로 seed되어 있습니다. Robinhood Agentic Trading은 계속 OAuth, 커밋된 mandate, order guard, audit ledger, instant halt 뒤에 있는 bounded live MCP connector입니다.
-- **2026-05-30** 🧰 **견고성 패스 — backtest, agent loop, session**: LLM이 생성한 signal engine은 이제 인스턴스화 전에 인터페이스 사전 검증을 거칩니다. 순환 self-import, 누락된 `generate()`, 기본값 없는 `__init__` 인자, 잘못된 반환 타입 같은 흔한 실수를 조기에 잡아 원시 traceback 대신 실행 가능한 JSON 오류로 반환합니다 ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149)). 후속 작업으로 소스 수준 AST 검증 오류도 동일한 깔끔한 JSON 봉투에 실었습니다. agent loop는 더 이상 50회 반복을 모두 소진하고 출력 없는 `failed` 상태로 끝나지 않습니다 — swarm worker의 검증된 방식을 따라 반복 예산의 80%에서 wrap-up nudge를 주입하고 마지막 반복에서 tool 정의를 제거해 텍스트 답변을 강제합니다 ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)). 중간에만 발동하도록 가드되어 research-goal 컨텍스트를 밀어내지 않습니다. session 메시지 쓰기는 이제 append마다 `flush + fsync`하여 비싼 AI 응답이 쓰기 도중 크래시에도 살아남고, 읽기 경로는 손상된 JSONL 줄을 건너뛰며(복구용으로 앞 200자 로깅) `/messages` 엔드포인트 전체를 500으로 만들지 않습니다 ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). Web 입력창은 IME Enter 처리도 수정해 조합 확정 Enter가 단어 도중에 전송되지 않도록 했습니다 ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).
<details>
<summary>이전 뉴스</summary>
+- **2026-05-30** 🧰 **견고성 패스 — backtest, agent loop, session**: LLM이 생성한 signal engine은 이제 인스턴스화 전에 인터페이스 사전 검증을 거칩니다. 순환 self-import, 누락된 `generate()`, 기본값 없는 `__init__` 인자, 잘못된 반환 타입 같은 흔한 실수를 조기에 잡아 원시 traceback 대신 실행 가능한 JSON 오류로 반환합니다 ([#149](https://github.com/HKUDS/Vibe-Trading/pull/149)). 후속 작업으로 소스 수준 AST 검증 오류도 동일한 깔끔한 JSON 봉투에 실었습니다. agent loop는 더 이상 50회 반복을 모두 소진하고 출력 없는 `failed` 상태로 끝나지 않습니다 — swarm worker의 검증된 방식을 따라 반복 예산의 80%에서 wrap-up nudge를 주입하고 마지막 반복에서 tool 정의를 제거해 텍스트 답변을 강제합니다 ([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)). 중간에만 발동하도록 가드되어 research-goal 컨텍스트를 밀어내지 않습니다. session 메시지 쓰기는 이제 append마다 `flush + fsync`하여 비싼 AI 응답이 쓰기 도중 크래시에도 살아남고, 읽기 경로는 손상된 JSONL 줄을 건너뛰며(복구용으로 앞 200자 로깅) `/messages` 엔드포인트 전체를 500으로 만들지 않습니다 ([#147](https://github.com/HKUDS/Vibe-Trading/pull/147)). Web 입력창은 IME Enter 처리도 수정해 조합 확정 Enter가 단어 도중에 전송되지 않도록 했습니다 ([#146](https://github.com/HKUDS/Vibe-Trading/pull/146)).
- **2026-05-29** 🔐 **Robinhood Agentic Trading 지원(옵트인, 제한된 자율성)**: Robinhood Agentic Trading을 지원합니다(원격 MCP, OAuth). 기본적으로 비활성·읽기 전용이며, 에이전트는 사용자가 커밋한 mandate(종목/주문 규모/익스포저/레버리지/일일 한도) 범위 안에서만 자율 거래합니다. 파일 수준의 즉시 kill switch, 선제적 포지션 청산, mandate 자동 만료, 완전한 감사 원장, 영속 자율 runner를 갖췄습니다. 수탁 없음·거래소 없음 — 자금 보유와 체결은 브로커가 하고, 우리는 의도만 중계합니다. 실험적 / 사용에 따른 책임은 본인에게 있습니다.
- **2026-05-28** 🧪 **Swarm 안전성 + 엄격 alpha 게이트 + worker MCP**: Swarm DAG가 상위 태스크 실패 시 하위 태스크를 차단합니다 ([#145](https://github.com/HKUDS/Vibe-Trading/pull/145)). 새 `run_bench_strict()`는 IC 게이트 위에 동일 universe 랜덤 컨트롤 + 학습/테스트 OOS 분할을 추가해 시장 beta만 따라가는 가짜 factor를 잡아냅니다 ([#143](https://github.com/HKUDS/Vibe-Trading/pull/143), @Soli22de 감사). Swarm worker는 이제 operator가 설정한 외부 MCP server를 호출할 수 있으며 신뢰 경계는 전용 테스트로 고정되어 있습니다 ([#142](https://github.com/HKUDS/Vibe-Trading/pull/142), @shadowinlife 감사).
- **2026-05-27** 📊 **mootdx A주 데이터 소스 + 출력 정리**: 새 `mootdx` loader는 네이티브 通达信 TCP 프로토콜로 A주 OHLCV를 가져옵니다(인증 불필요, IP 속도 제한 없음, 일봉 + 분봉의 25 페이지 walk-back 페이지네이션). fallback chain에서 tushare와 akshare 사이에 위치합니다 ([#107](https://github.com/HKUDS/Vibe-Trading/issues/107)). CCXT loader는 이제 `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY`를 읽어 제한된 네트워크에서 Binance/OKX 공개 데이터를 가져올 수 있습니다 ([#126](https://github.com/HKUDS/Vibe-Trading/pull/126), @ruok808 감사). 최종 답변 렌더링에서도 CLI와 Web의 보기 흉한 전체 너비 `---` 구분자를 제거했습니다: system prompt는 markdown 테이블과 `##` 헤딩 사용을 유도하고, CLI 렌더러는 독립 HR을 defense-in-depth로 제거하며, 채팅 버블은 빠져나온 `<hr>`을 숨깁니다 ([#139](https://github.com/HKUDS/Vibe-Trading/issues/139), @sdwxm188 감사).
diff --git a/README_zh.md b/README_zh.md
index 32ac56ee6..d3ec28a4d 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -46,12 +46,13 @@
## 📰 News
+- **2026-06-02** 🔌 **六个新券商 connector(老虎 / 长桥 / Alpaca / OKX / 币安 / 富途)**:connector-first 交易层在 IBKR(本地)和 Robinhood(MCP)之外,新增一条直连 SDK 传输。每个 connector 都暴露只读的账户 / 持仓 / 订单 / 行情 / 历史,外加模拟账户下单——把你的策略放到这些券商的模拟盘上跑。其中五个(老虎、Alpaca、OKX、币安、富途)还支持在用户提交的 mandate(标的/单量/敞口/杠杆/每日笔数)约束下的有界下单,沿用与 Robinhood 同一套安全模型:用户提交的 mandate、文件级即时 kill switch、fail-closed 的下单前门禁,以及完整审计账本。长桥仅支持模拟盘 + 只读(其 API 不暴露运行时的模拟/正式判别标识)。每一处模拟/正式的区分都是按券商落实的结构性守卫——账户 id 格式、host 隔离、demo 标志或 trade environment。新增 `trading_place_order` / `trading_cancel_order` 工具;mandate universe 也补上了港股和 A 股资产类别。实验性 / 风险自负。
- **2026-06-01** 🚀 **v0.1.9 发布**(`pip install -U vibe-trading-ai`):汇总 0.1.8 以来的全部更新。Connector-first 券商 profile(IBKR 本地只读 TWS / IB Gateway + Robinhood Agentic Trading,受 OAuth、已提交 mandate、order guard、审计账本和即时 halt 约束)。Research Goal 运行时贯通 CLI / REST / MCP / Web。一轮 swarm 升级——实时 reconcile + MCP keepalive、operator 配置的 worker MCP 工具、严格 alpha-bench 随机控制,以及新增 `retry_run` 重跑失败/过期 run(现 **36 个 MCP 工具**)。`agent/cli/` 包重构 + 刷新的终端 UI、`mootdx` 免 token A 股 loader,以及 backtest / agent loop / session 的健壮性增强。`--version` 现在始终与已安装版本一致,修复 0.1.8 漂移([#156](https://github.com/HKUDS/Vibe-Trading/issues/156))。
- **2026-05-31** 🔌 **Connector-first 券商架构(IBKR + Robinhood)**:交易接入现在从可选择的 connector profile 开始,不再拆成分散的券商入口和 live 入口。`vibe-trading connector list/use/check/account/positions/orders/quote/history` 与 MCP `trading_*` 工具共享同一个选中的 profile;paper/live 只是该 connector 下的属性。IBKR 可立即通过本地只读 TWS / IB Gateway profile 使用;官方 IBKR 远程 MCP 先作为 OAuth `mcp.read` 探测种子,等待稳定 read 工具名后再映射。Robinhood Agentic Trading 仍是有界 live MCP connector,必须经过 OAuth、已提交 mandate、order guard、审计账本和即时 halt。
-- **2026-05-30** 🧰 **健壮性专项 — backtest、agent loop、session**:LLM 生成的 signal engine 现在会在实例化前先过接口预检,提前抓出循环 self-import、缺失 `generate()`、`__init__` 参数没有默认值、返回类型错误等常见问题,并给出可操作的 JSON 报错而非原始 traceback([#149](https://github.com/HKUDS/Vibe-Trading/pull/149));后续一并把源码级 AST 校验的报错也走同一套干净的 JSON 信封。agent loop 不再把 50 次迭代全烧光后留下一个没有任何输出的 `failed` 状态——它复用 swarm worker 已验证的做法:在迭代预算 80% 处注入 wrap-up nudge,并在最后一次迭代丢掉 tool 定义以强制产出文本答案([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)),且只在中途触发,绝不挤掉 research-goal 上下文。session 消息写入现在每次 append 后 `flush + fsync`,让昂贵的 AI 回复能在写到一半崩溃时存活;读取端则跳过损坏的 JSONL 行(记录前 200 字符以便人工恢复),而不是让整个 `/messages` 端点 500([#147](https://github.com/HKUDS/Vibe-Trading/pull/147))。Web 输入框也修了 IME 回车处理,让中日韩输入法的确认上屏回车不再误触发提交([#146](https://github.com/HKUDS/Vibe-Trading/pull/146))。
<details>
<summary>更早的更新</summary>
+- **2026-05-30** 🧰 **健壮性专项 — backtest、agent loop、session**:LLM 生成的 signal engine 现在会在实例化前先过接口预检,提前抓出循环 self-import、缺失 `generate()`、`__init__` 参数没有默认值、返回类型错误等常见问题,并给出可操作的 JSON 报错而非原始 traceback([#149](https://github.com/HKUDS/Vibe-Trading/pull/149));后续一并把源码级 AST 校验的报错也走同一套干净的 JSON 信封。agent loop 不再把 50 次迭代全烧光后留下一个没有任何输出的 `failed` 状态——它复用 swarm worker 已验证的做法:在迭代预算 80% 处注入 wrap-up nudge,并在最后一次迭代丢掉 tool 定义以强制产出文本答案([#148](https://github.com/HKUDS/Vibe-Trading/pull/148)),且只在中途触发,绝不挤掉 research-goal 上下文。session 消息写入现在每次 append 后 `flush + fsync`,让昂贵的 AI 回复能在写到一半崩溃时存活;读取端则跳过损坏的 JSONL 行(记录前 200 字符以便人工恢复),而不是让整个 `/messages` 端点 500([#147](https://github.com/HKUDS/Vibe-Trading/pull/147))。Web 输入框也修了 IME 回车处理,让中日韩输入法的确认上屏回车不再误触发提交([#146](https://github.com/HKUDS/Vibe-Trading/pull/146))。
- **2026-05-29** 🔐 **支持 Robinhood Agentic Trading(可选开启、有界自主)**:新增对 Robinhood Agentic Trading 的支持(远程 MCP,OAuth)。默认关闭且只读;仅在用户提交的 mandate(标的/单量/敞口/杠杆/每日笔数)内自主交易,配文件级即时 kill switch、抢占式平仓、mandate 自动过期、完整审计账本,以及一个持久自主 runner。无托管、无场所——券商持有资金并执行,我们只中继意图。实验性 / 风险自负。
- **2026-05-28** 🧪 **Swarm 安全 + 严格 alpha 门 + worker 端 MCP**:Swarm DAG 在上游任务失败时阻断下游任务([#145](https://github.com/HKUDS/Vibe-Trading/pull/145))。新增 `run_bench_strict()` 在 IC 门之上加入同 universe 随机控制 + 训练/测试 OOS 切分,识别只是跟随市场 beta 的伪因子([#143](https://github.com/HKUDS/Vibe-Trading/pull/143),感谢 @Soli22de)。Swarm worker 现在可以调用 operator 配置的外部 MCP server,信任边界由专项测试固定([#142](https://github.com/HKUDS/Vibe-Trading/pull/142),感谢 @shadowinlife)。
- **2026-05-27** 📊 **mootdx A 股数据源 + 输出排版**:新增 `mootdx` loader,走原生通达信 TCP 协议拉 A 股 OHLCV(无需 token,无 IP 速率限制,日线 + 分钟线 25 页 walk-back 分页),在 fallback chain 中位于 tushare 和 akshare 之间([#107](https://github.com/HKUDS/Vibe-Trading/issues/107))。CCXT loader 现在会读取 `HTTP_PROXY/HTTPS_PROXY/ALL_PROXY`,使 Binance/OKX 公开数据可在受限网络下拉取([#126](https://github.com/HKUDS/Vibe-Trading/pull/126),感谢 @ruok808)。最终回答的渲染也去掉了 CLI 和 Web 上丑陋的全宽 `---` 分隔符:系统提示鼓励 agent 用 markdown 表格和 `##` 标题,CLI 渲染端兜底 strip 孤立 HR,前端 chat 气泡隐藏任何漏过去的 `<hr>`([#139](https://github.com/HKUDS/Vibe-Trading/issues/139),感谢 @sdwxm188)。
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 408dbc709..5d9524fd4 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -3640,6 +3640,8 @@ def cmd_connector_history(
bar_size: str = "1 day",
what_to_show: str = "TRADES",
use_rth: bool = True,
+ period: str = "1d",
+ limit: int = 90,
) -> int:
"""Print historical bars from a connector profile."""
from src.trading.service import get_history
@@ -3659,6 +3661,8 @@ def cmd_connector_history(
bar_size=bar_size,
what_to_show=what_to_show,
use_rth=use_rth,
+ period=period,
+ limit=limit,
)
except Exception as exc: # noqa: BLE001
console.print(f"[red]Connector history failed:[/red] {exc}")
@@ -3852,6 +3856,8 @@ def _dispatch_connector(args: argparse.Namespace) -> int:
bar_size=args.bar_size,
what_to_show=args.what_to_show,
use_rth=not args.no_rth,
+ period=args.period,
+ limit=args.bar_limit,
)
if sub == "authorize":
return cmd_connector_authorize(args.profile)
@@ -4025,10 +4031,12 @@ def _build_parser() -> argparse.ArgumentParser:
_add_connector_profile_arg(connector_history)
_add_connector_local(connector_history)
_add_connector_contract(connector_history)
- connector_history.add_argument("--duration", default="30 D")
- connector_history.add_argument("--bar-size", dest="bar_size", default="1 day")
+ connector_history.add_argument("--duration", default="30 D", help="IBKR (local_tws) duration string")
+ connector_history.add_argument("--bar-size", dest="bar_size", default="1 day", help="IBKR (local_tws) bar size")
connector_history.add_argument("--what-to-show", dest="what_to_show", default="TRADES")
connector_history.add_argument("--no-rth", action="store_true", help="Include outside-regular-hours data when available")
+ connector_history.add_argument("--period", default="1d", help="Bar interval for SDK connectors: 1m/5m/15m/30m/1h/4h/1d/1w/1M")
+ connector_history.add_argument("--limit", dest="bar_limit", type=int, default=90, help="Number of bars for SDK connectors")
for name, help_text in (
("start", "Start the selected live connector runner"),
diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.py
index 8a6ca85ac..489274b0f 100644
--- a/agent/src/tools/trading_connector_tool.py
+++ b/agent/src/tools/trading_connector_tool.py
@@ -17,12 +17,14 @@ from src.trading.profiles import (
save_selected_profile_id,
)
from src.trading.service import (
+ cancel_order,
check_connection,
get_account,
get_history,
get_open_orders,
get_positions,
get_quote,
+ place_order,
)
@@ -43,6 +45,12 @@ def _int_or_none(value: Any) -> int | None:
return int(value)
+def _num_or_none(value: Any) -> float | None:
+ if value in (None, ""):
+ return None
+ return float(value)
+
+
TRADING_COMMON_PARAMETERS = {
"connection": {
"type": "string",
@@ -260,10 +268,16 @@ class TradingHistoryTool(BaseTool):
"type": "object",
"properties": {
**TradingQuoteTool.parameters["properties"],
- "duration": {"type": "string", "default": "30 D"},
- "bar_size": {"type": "string", "default": "1 day"},
+ "duration": {"type": "string", "default": "30 D", "description": "IBKR (local_tws) duration string."},
+ "bar_size": {"type": "string", "default": "1 day", "description": "IBKR (local_tws) bar size."},
"what_to_show": {"type": "string", "default": "TRADES"},
"use_rth": {"type": "boolean", "default": True},
+ "period": {
+ "type": "string",
+ "default": "1d",
+ "description": "Bar interval for SDK connectors (broker_sdk): 1m/5m/15m/30m/1h/4h/1d/1w/1M.",
+ },
+ "limit": {"type": "integer", "default": 90, "description": "Number of bars for SDK connectors."},
},
"required": ["symbol"],
}
@@ -284,6 +298,93 @@ class TradingHistoryTool(BaseTool):
bar_size=str(kwargs.get("bar_size") or "1 day"),
what_to_show=str(kwargs.get("what_to_show") or "TRADES"),
use_rth=bool(kwargs.get("use_rth", True)),
+ period=str(kwargs.get("period") or "1d"),
+ limit=int(kwargs.get("limit") or 90),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingPlaceOrderTool(BaseTool):
+ """Place an order through a trading connector profile.
+
+ Paper profiles place against the broker's sandbox account. Live profiles
+ route through the bounded-autonomy mandate gate (mandate + kill switch +
+ fail-closed pre-trade checks + audit) before any order reaches the broker.
+ Not read-only; not repeatable (an order must never be silently re-issued).
+ """
+
+ name = "trading_place_order"
+ description = (
+ "Place an order through the selected trading connector profile. Paper "
+ "profiles trade a sandbox account; live profiles are gated by the user's "
+ "mandate and kill switch. side is 'buy' or 'sell'; give exactly one of "
+ "quantity (units) or notional (account-currency amount)."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TRADING_COMMON_PARAMETERS,
+ "symbol": {"type": "string", "description": "Symbol, e.g. AAPL, BTC-USDT, 700.HK, HK.00700."},
+ "side": {"type": "string", "enum": ["buy", "sell"]},
+ "quantity": {"type": "number", "description": "Order size in units/shares/contracts. Exactly one of quantity/notional."},
+ "notional": {"type": "number", "description": "Order size as an account-currency amount. Exactly one of quantity/notional."},
+ "order_type": {"type": "string", "enum": ["market", "limit"], "default": "market"},
+ "limit_price": {"type": "number", "description": "Required for limit orders."},
+ "time_in_force": {"type": "string", "enum": ["day", "gtc"], "default": "day"},
+ },
+ "required": ["symbol", "side"],
+ }
+ repeatable = False
+ is_readonly = False
+
+ def execute(self, **kwargs: Any) -> str:
+ """Place an order via the connector profile."""
+ try:
+ return _json_result(
+ place_order(
+ str(kwargs["symbol"]),
+ _connection(kwargs.get("connection")),
+ side=str(kwargs.get("side") or ""),
+ quantity=_num_or_none(kwargs.get("quantity")),
+ notional=_num_or_none(kwargs.get("notional")),
+ order_type=str(kwargs.get("order_type") or "market"),
+ limit_price=_num_or_none(kwargs.get("limit_price")),
+ time_in_force=str(kwargs.get("time_in_force") or "day"),
+ **_overrides(kwargs),
+ )
+ )
+ except Exception as exc: # noqa: BLE001
+ return _json_result({"status": "error", "error": str(exc)})
+
+
+class TradingCancelOrderTool(BaseTool):
+ """Cancel an order through a trading connector profile (risk-reducing)."""
+
+ name = "trading_cancel_order"
+ description = "Cancel an open order on the selected trading connector profile by order id."
+ parameters = {
+ "type": "object",
+ "properties": {
+ **TRADING_COMMON_PARAMETERS,
+ "order_id": {"type": "string", "description": "Broker order id to cancel."},
+ "symbol": {"type": "string", "description": "Symbol (required by some brokers, e.g. OKX/Binance)."},
+ },
+ "required": ["order_id"],
+ }
+ repeatable = False
+ is_readonly = False
+
+ def execute(self, **kwargs: Any) -> str:
+ """Cancel an order via the connector profile."""
+ try:
+ return _json_result(
+ cancel_order(
+ str(kwargs["order_id"]),
+ _connection(kwargs.get("connection")),
+ symbol=_connection(kwargs.get("symbol")),
**_overrides(kwargs),
)
)
diff --git a/agent/src/trading/connectors/alpaca/__init__.py b/agent/src/trading/connectors/alpaca/__init__.py
new file mode 100644
index 000000000..dcb84b272
--- /dev/null
+++ b/agent/src/trading/connectors/alpaca/__init__.py
@@ -0,0 +1,13 @@
+"""Alpaca trading connector.
+
+Read-only account/market access in Layer A via the official ``alpaca-py`` SDK
+(``TradingClient`` + ``StockHistoricalDataClient`` over REST). A ``broker_sdk``
+transport.
+
+Paper-vs-live separation is structural: paper and live use DIFFERENT API keys
+and DIFFERENT hosts (``paper-api.alpaca.markets`` vs ``api.alpaca.markets``), so
+a paper key physically cannot reach the live host. The account response carries
+no paper/live field, so the configured ``paper`` flag (and thus the host) is the
+authoritative discriminator; it is recorded on every payload and never flipped
+implicitly.
+"""
diff --git a/agent/src/trading/connectors/alpaca/classification.py b/agent/src/trading/connectors/alpaca/classification.py
new file mode 100644
index 000000000..f6f12b536
--- /dev/null
+++ b/agent/src/trading/connectors/alpaca/classification.py
@@ -0,0 +1,25 @@
+"""Curated read/write classification for Alpaca SDK operations.
+
+Keys are the connector's own operation names. Order-mutating SDK calls are
+pinned WRITE so the live gate never treats them as plain reads; anything
+unlisted and not a known read is treated as WRITE (fail-closed) by the gate.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Alpaca SDK operation read/write catalog.
+ALPACA_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "get_account": ToolClass.READ,
+ "get_all_positions": ToolClass.READ,
+ "get_open_position": ToolClass.READ,
+ "get_orders": ToolClass.READ,
+ "get_stock_latest_quote": ToolClass.READ,
+ "get_stock_bars": ToolClass.READ,
+ # WRITE
+ "submit_order": ToolClass.WRITE,
+ "cancel_order_by_id": ToolClass.WRITE,
+ "cancel_orders": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/alpaca/profiles.py b/agent/src/trading/connectors/alpaca/profiles.py
new file mode 100644
index 000000000..a6a66720a
--- /dev/null
+++ b/agent/src/trading/connectors/alpaca/profiles.py
@@ -0,0 +1,71 @@
+"""Built-in Alpaca connector profiles.
+
+Layer A ships read-only paper and live profiles; the trade profiles add order
+placement. Paper and live use different key pairs and different hosts, so they
+are distinct profiles. The live-trade profile carries an
+``orders.place.requires_mandate`` capability — placement on live funds is only
+authorized once the caller has a mandate in place; this connector layer just
+records the capability.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+ALPACA_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="alpaca-paper-sdk",
+ connector="alpaca",
+ label="Alpaca Paper · alpaca-py",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper", "feed": "iex"},
+ notes=(
+ "Reads an Alpaca paper account (paper-api.alpaca.markets) via alpaca-py. "
+ "Paper keys cannot reach the live host."
+ ),
+ ),
+ TradingProfile(
+ id="alpaca-live-sdk-readonly",
+ connector="alpaca",
+ label="Alpaca Live · alpaca-py Read-Only",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly", "feed": "iex"},
+ notes="Reads an Alpaca live account only (api.alpaca.markets). Order placement is not exposed in this profile.",
+ ),
+ TradingProfile(
+ id="alpaca-paper-trade",
+ connector="alpaca",
+ label="Alpaca Paper · alpaca-py Trade",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper", "feed": "iex"},
+ notes=(
+ "Reads and places orders on an Alpaca paper account "
+ "(paper-api.alpaca.markets) via alpaca-py. Paper keys cannot reach "
+ "the live host, so no real funds are ever at risk."
+ ),
+ ),
+ TradingProfile(
+ id="alpaca-live-trade",
+ connector="alpaca",
+ label="Alpaca Live · alpaca-py Trade",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place.requires_mandate",),
+ readonly=False,
+ config={"profile": "live", "feed": "iex"},
+ notes=(
+ "Reads and places orders on an Alpaca live account "
+ "(api.alpaca.markets). Placement on live funds requires an "
+ "authorized mandate; the caller enforces it."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/alpaca/sdk.py b/agent/src/trading/connectors/alpaca/sdk.py
new file mode 100644
index 000000000..92e57ad59
--- /dev/null
+++ b/agent/src/trading/connectors/alpaca/sdk.py
@@ -0,0 +1,623 @@
+"""Read-only Alpaca connector via the official ``alpaca-py`` SDK.
+
+Wraps ``TradingClient`` (account/positions/orders) and
+``StockHistoricalDataClient`` (quote/bars) for the five read operations. No
+order-placement method is exposed here.
+
+Paper-vs-live is structural: ``profile == "paper"`` constructs the client with
+``paper=True`` (host ``paper-api.alpaca.markets``) using the paper key pair; a
+live profile uses ``paper=False`` (host ``api.alpaca.markets``) with the live
+key pair. A paper key cannot reach the live host, so the configured profile —
+recorded as ``paper`` in every payload — is the authoritative discriminator.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "alpaca.json"
+
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+PAPER_HOST = "https://paper-api.alpaca.markets"
+LIVE_HOST = "https://api.alpaca.markets"
+
+
+class AlpacaDependencyError(RuntimeError):
+ """Raised when the optional ``alpaca-py`` package is not installed."""
+
+
+class AlpacaConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+@dataclass(frozen=True)
+class AlpacaConfig:
+ """Alpaca connector connection settings.
+
+ Args:
+ api_key: Alpaca API key id (paper and live use different keys).
+ secret_key: Alpaca API secret key.
+ profile: ``paper``, ``live-readonly`` or ``live``.
+ feed: Market-data feed, ``iex`` (free) or ``sip`` (paid).
+ timeout: Network timeout in seconds.
+ readonly: Always true for this layer; order methods are not exposed.
+ """
+
+ api_key: str = ""
+ secret_key: str = ""
+ profile: str = "paper"
+ feed: str = "iex"
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "AlpacaConfig":
+ """Build a config from a JSON-like mapping, normalizing the profile."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise AlpacaConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ feed = str(payload.get("feed") or "iex").strip().lower()
+ if feed not in ("iex", "sip"):
+ raise AlpacaConfigError("feed must be 'iex' or 'sip'")
+ return cls(
+ api_key=str(payload.get("api_key") or "").strip(),
+ secret_key=str(payload.get("secret_key") or "").strip(),
+ profile=profile,
+ feed=feed,
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ api_key: str | None = None,
+ secret_key: str | None = None,
+ profile: str | None = None,
+ feed: str | None = None,
+ ) -> "AlpacaConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if api_key is not None:
+ payload["api_key"] = api_key
+ if secret_key is not None:
+ payload["secret_key"] = secret_key
+ if profile is not None:
+ payload["profile"] = profile
+ if feed is not None:
+ payload["feed"] = feed
+ return AlpacaConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+ @property
+ def is_paper(self) -> bool:
+ """Return whether this profile targets the paper host/key."""
+ return self.environment == "paper"
+
+ @property
+ def host(self) -> str:
+ """Return the REST host this profile connects to."""
+ return PAPER_HOST if self.is_paper else LIVE_HOST
+
+
+_OVERRIDE_KEYS = ("api_key", "secret_key", "profile", "feed")
+
+
+def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "AlpacaConfig":
+ """Resolve config: saved file ← profile defaults ← CLI overrides."""
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = AlpacaConfig.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def config_path() -> Path:
+ """Return the user-level Alpaca config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> AlpacaConfig:
+ """Load Alpaca settings from ``~/.vibe-trading/alpaca.json``."""
+ path = config_path()
+ if not path.exists():
+ return AlpacaConfig()
+ try:
+ return AlpacaConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise AlpacaConfigError(f"invalid Alpaca config at {path}: {exc}") from exc
+
+
+def save_config(config: AlpacaConfig) -> Path:
+ """Persist Alpaca settings with owner-only permissions."""
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def alpaca_available() -> bool:
+ """Return whether the optional ``alpaca-py`` SDK can be imported."""
+ try:
+ _require_alpaca()
+ return True
+ except AlpacaDependencyError:
+ return False
+
+
+def check_status(config: AlpacaConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness and config completeness without mutating broker state."""
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "alpaca-py", "installed": alpaca_available()},
+ "paper_guard": "host_separated",
+ "host": cfg.host,
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Alpaca connector not configured: missing {', '.join(missing)}."
+ return report
+
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install alpaca-py`."
+ return report
+
+ try:
+ snapshot = get_account_snapshot(cfg)
+ except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ report["account"] = {
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "account_number": snapshot.get("account", {}).get("account_number"),
+ }
+ return report
+
+
+def get_account_snapshot(config: AlpacaConfig | None = None) -> dict[str, Any]:
+ """Fetch account summary for the configured account."""
+ cfg = config or load_config()
+ client = _trading_client(cfg)
+ account = client.get_account()
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "host": cfg.host,
+ "account": {
+ "account_number": _obj_get(account, "account_number"),
+ "status": str(_obj_get(account, "status", "")),
+ "currency": _obj_get(account, "currency"),
+ "cash": _obj_get(account, "cash"),
+ "equity": _obj_get(account, "equity"),
+ "buying_power": _obj_get(account, "buying_power"),
+ "portfolio_value": _obj_get(account, "portfolio_value"),
+ "pattern_day_trader": _obj_get(account, "pattern_day_trader"),
+ "trading_blocked": _obj_get(account, "trading_blocked"),
+ },
+ }
+
+
+def get_positions(config: AlpacaConfig | None = None) -> dict[str, Any]:
+ """Fetch current positions for the configured account."""
+ cfg = config or load_config()
+ client = _trading_client(cfg)
+ positions = client.get_all_positions()
+ rows = [_position_to_dict(item) for item in _as_iter(positions)]
+ return {"status": "ok", "profile": cfg.profile, "is_paper": cfg.is_paper, "positions": rows}
+
+
+def get_open_orders(config: AlpacaConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:
+ """Fetch open orders and, optionally, recently filled orders."""
+ cfg = config or load_config()
+ client = _trading_client(cfg)
+ _require_alpaca()
+ from alpaca.trading.requests import GetOrdersRequest # type: ignore
+ from alpaca.trading.enums import QueryOrderStatus # type: ignore
+
+ open_req = GetOrdersRequest(status=QueryOrderStatus.OPEN)
+ open_orders = client.get_orders(filter=open_req)
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "open_orders": [_order_to_dict(item) for item in _as_iter(open_orders)],
+ }
+ if include_executions:
+ closed_req = GetOrdersRequest(status=QueryOrderStatus.CLOSED)
+ closed = client.get_orders(filter=closed_req)
+ result["executions"] = [_order_to_dict(item) for item in _as_iter(closed) if _obj_get(item, "filled_qty")]
+ return result
+
+
+def get_quote(symbol: str, *, config: AlpacaConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch a latest quote snapshot for ``symbol``."""
+ cfg = config or load_config()
+ client = _data_client(cfg)
+ from alpaca.data.requests import StockLatestQuoteRequest # type: ignore
+
+ clean = symbol.strip().upper()
+ req = StockLatestQuoteRequest(symbol_or_symbols=clean, feed=_data_feed(cfg))
+ quotes = client.get_stock_latest_quote(req)
+ quote = quotes.get(clean) if isinstance(quotes, Mapping) else _obj_get(quotes, clean)
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "quote": {
+ "bid": _obj_get(quote, "bid_price"),
+ "ask": _obj_get(quote, "ask_price"),
+ "bid_size": _obj_get(quote, "bid_size"),
+ "ask_size": _obj_get(quote, "ask_size"),
+ "time": str(_obj_get(quote, "timestamp", "")),
+ },
+ }
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: AlpacaConfig | None = None,
+ period: str = "1d",
+ limit: int = 90,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical bars for ``symbol`` (``period`` is a canonical token)."""
+ cfg = config or load_config()
+ client = _data_client(cfg)
+ from alpaca.data.requests import StockBarsRequest # type: ignore
+ from alpaca.data.timeframe import TimeFrame, TimeFrameUnit # type: ignore
+
+ clean = symbol.strip().upper()
+ timeframe = _timeframe(period, TimeFrame, TimeFrameUnit)
+ req = StockBarsRequest(symbol_or_symbols=clean, timeframe=timeframe, limit=int(limit), feed=_data_feed(cfg))
+ bars = client.get_stock_bars(req)
+ rows = bars.data.get(clean, []) if hasattr(bars, "data") else _as_iter(bars)
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "period": period,
+ "bars": [_bar_to_dict(item) for item in _as_iter(rows)],
+ }
+
+
+def place_order(
+ config: AlpacaConfig | None = None,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | None = None,
+ notional: float | None = None,
+ order_type: str = "market",
+ limit_price: float | None = None,
+ time_in_force: str = "day",
+) -> dict[str, Any]:
+ """Submit an order to the configured Alpaca account.
+
+ Paper-vs-live is structural: ``_trading_client`` builds the client with
+ ``paper=cfg.is_paper`` so a paper profile reaches the paper host and a live
+ profile reaches the live host. This connector only executes against the
+ account in ``config``; deciding whether the order is authorized (mandate,
+ kill switch, user opt-in) is the caller's responsibility.
+
+ Args:
+ config: Connector config; falls back to the saved config when ``None``.
+ symbol: Equity symbol (case-insensitive, whitespace tolerated).
+ side: ``buy`` or ``sell``.
+ quantity: Share quantity; mutually exclusive with ``notional``.
+ notional: Dollar amount (fractional); mutually exclusive with ``quantity``.
+ order_type: ``market`` or ``limit``.
+ limit_price: Required when ``order_type`` is ``limit``.
+ time_in_force: ``day`` or ``gtc``.
+
+ Returns:
+ On success ``{"status": "ok", "order_id", "symbol", "side", "profile",
+ "is_paper", "order_type", "time_in_force", "quantity", "notional",
+ "limit_price", "order_status", "filled_qty"}``. On invalid input or
+ submission failure ``{"status": "error", "error": <message>}`` — this
+ function fails closed and never raises for caller-controlled mistakes.
+ """
+ cfg = config or load_config()
+
+ clean_symbol = str(symbol or "").strip().upper()
+ if not clean_symbol:
+ return {"status": "error", "error": "symbol is required"}
+
+ side_token = str(side or "").strip().lower()
+ if side_token not in ("buy", "sell"):
+ return {"status": "error", "error": "side must be 'buy' or 'sell'"}
+
+ type_token = str(order_type or "").strip().lower()
+ if type_token not in ("market", "limit"):
+ return {"status": "error", "error": "order_type must be 'market' or 'limit'"}
+
+ tif_token = str(time_in_force or "").strip().lower()
+ if tif_token not in ("day", "gtc"):
+ return {"status": "error", "error": "time_in_force must be 'day' or 'gtc'"}
+
+ has_qty = quantity is not None
+ has_notional = notional is not None
+ if has_qty == has_notional:
+ return {"status": "error", "error": "provide exactly one of quantity or notional"}
+
+ qty_value: float | None = None
+ notional_value: float | None = None
+ try:
+ if has_qty:
+ qty_value = float(quantity) # type: ignore[arg-type]
+ if qty_value <= 0:
+ return {"status": "error", "error": "quantity must be positive"}
+ else:
+ notional_value = float(notional) # type: ignore[arg-type]
+ if notional_value <= 0:
+ return {"status": "error", "error": "notional must be positive"}
+ except (TypeError, ValueError):
+ return {"status": "error", "error": "quantity/notional must be numeric"}
+
+ limit_value: float | None = None
+ if type_token == "limit":
+ if limit_price is None:
+ return {"status": "error", "error": "limit order requires limit_price"}
+ try:
+ limit_value = float(limit_price)
+ except (TypeError, ValueError):
+ return {"status": "error", "error": "limit_price must be numeric"}
+ if limit_value <= 0:
+ return {"status": "error", "error": "limit_price must be positive"}
+
+ try:
+ client = _trading_client(cfg)
+ from alpaca.trading.enums import OrderSide, TimeInForce # type: ignore
+ from alpaca.trading.requests import ( # type: ignore
+ LimitOrderRequest,
+ MarketOrderRequest,
+ )
+
+ order_side = OrderSide.BUY if side_token == "buy" else OrderSide.SELL
+ tif = TimeInForce.DAY if tif_token == "day" else TimeInForce.GTC
+ amount = {"qty": qty_value} if has_qty else {"notional": notional_value}
+
+ if type_token == "limit":
+ req = LimitOrderRequest(
+ symbol=clean_symbol,
+ side=order_side,
+ time_in_force=tif,
+ limit_price=limit_value,
+ **amount,
+ )
+ else:
+ req = MarketOrderRequest(
+ symbol=clean_symbol,
+ side=order_side,
+ time_in_force=tif,
+ **amount,
+ )
+
+ order = client.submit_order(order_data=req)
+ except AlpacaDependencyError as exc:
+ return {"status": "error", "error": str(exc)}
+ except Exception as exc: # noqa: BLE001 - submission errors are reported, not raised
+ return {"status": "error", "error": str(exc)}
+
+ return {
+ "status": "ok",
+ "order_id": str(_obj_get(order, "id", "")),
+ "symbol": clean_symbol,
+ "side": side_token,
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "order_type": type_token,
+ "time_in_force": tif_token,
+ "quantity": qty_value,
+ "notional": notional_value,
+ "limit_price": limit_value,
+ "order_status": str(_obj_get(order, "status", "")),
+ "filled_qty": _obj_get(order, "filled_qty"),
+ }
+
+
+def cancel_order(
+ config: AlpacaConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel an open order on the configured Alpaca account.
+
+ Args:
+ config: Connector config; falls back to the saved config when ``None``.
+ order_id: Alpaca order id to cancel.
+ symbol: Optional symbol, echoed back for caller bookkeeping only;
+ Alpaca cancels purely by id.
+
+ Returns:
+ On success ``{"status": "ok", "order_id", "symbol", "side", "profile",
+ "is_paper", "cancelled"}``. On invalid input or cancel failure
+ ``{"status": "error", "error": <message>}`` — fails closed, never raises.
+ """
+ cfg = config or load_config()
+
+ clean_id = str(order_id or "").strip()
+ if not clean_id:
+ return {"status": "error", "error": "order_id is required"}
+
+ try:
+ client = _trading_client(cfg)
+ client.cancel_order_by_id(clean_id)
+ except AlpacaDependencyError as exc:
+ return {"status": "error", "error": str(exc)}
+ except Exception as exc: # noqa: BLE001 - cancel errors are reported, not raised
+ return {"status": "error", "error": str(exc)}
+
+ return {
+ "status": "ok",
+ "order_id": clean_id,
+ "symbol": symbol.strip().upper() if isinstance(symbol, str) and symbol.strip() else None,
+ "side": None,
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "cancelled": True,
+ }
+
+
+def _timeframe(period: str, time_frame_cls: Any, unit_cls: Any) -> Any:
+ """Map a canonical period token to an Alpaca ``TimeFrame``.
+
+ Case-sensitive: ``1m`` is one minute, ``1M`` is one month.
+ """
+ token = period.strip()
+ minute_amounts = {"1m": 1, "5m": 5, "15m": 15, "30m": 30}
+ if token in minute_amounts:
+ return time_frame_cls(minute_amounts[token], unit_cls.Minute)
+ if token in ("1h", "4h"):
+ return time_frame_cls(1 if token == "1h" else 4, unit_cls.Hour)
+ if token == "1w":
+ return time_frame_cls(1, unit_cls.Week)
+ if token == "1M":
+ return time_frame_cls(1, unit_cls.Month)
+ return time_frame_cls.Day
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _require_alpaca() -> ModuleType:
+ try:
+ import alpaca # type: ignore
+ except ModuleNotFoundError as exc:
+ raise AlpacaDependencyError("alpaca-py is not installed; run `pip install alpaca-py`.") from exc
+ return alpaca
+
+
+def _trading_client(cfg: AlpacaConfig):
+ _require_alpaca()
+ from alpaca.trading.client import TradingClient # type: ignore
+
+ return TradingClient(cfg.api_key, cfg.secret_key, paper=cfg.is_paper)
+
+
+def _data_client(cfg: AlpacaConfig):
+ _require_alpaca()
+ from alpaca.data.historical import StockHistoricalDataClient # type: ignore
+
+ return StockHistoricalDataClient(cfg.api_key, cfg.secret_key)
+
+
+def _data_feed(cfg: AlpacaConfig):
+ """Map the configured ``feed`` string to the Alpaca ``DataFeed`` enum."""
+ _require_alpaca()
+ from alpaca.data.enums import DataFeed # type: ignore
+
+ return DataFeed.SIP if cfg.feed == "sip" else DataFeed.IEX
+
+
+def _missing_fields(cfg: AlpacaConfig) -> list[str]:
+ missing = []
+ if not cfg.api_key:
+ missing.append("api_key")
+ if not cfg.secret_key:
+ missing.append("secret_key")
+ return missing
+
+
+def _public_config(cfg: AlpacaConfig) -> dict[str, Any]:
+ """Config snapshot with secrets redacted."""
+ data = asdict(cfg)
+ if data.get("secret_key"):
+ data["secret_key"] = "***redacted***"
+ if data.get("api_key"):
+ data["api_key"] = data["api_key"][:4] + "***"
+ data["host"] = cfg.host
+ return data
+
+
+# ---------------------------------------------------------------------------
+# Defensive field extraction
+# ---------------------------------------------------------------------------
+
+
+def _as_iter(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
+ if obj is None:
+ return default
+ if isinstance(obj, Mapping):
+ return obj.get(name, default)
+ return getattr(obj, name, default)
+
+
+def _position_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _obj_get(item, "symbol"),
+ "side": str(_obj_get(item, "side", "")),
+ "quantity": _obj_get(item, "qty"),
+ "average_cost": _obj_get(item, "avg_entry_price"),
+ "market_value": _obj_get(item, "market_value"),
+ "current_price": _obj_get(item, "current_price"),
+ "unrealized_pnl": _obj_get(item, "unrealized_pl"),
+ "cost_basis": _obj_get(item, "cost_basis"),
+ }
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": str(_obj_get(item, "id", "")),
+ "symbol": _obj_get(item, "symbol"),
+ "side": str(_obj_get(item, "side", "")),
+ "order_type": str(_obj_get(item, "order_type", "") or _obj_get(item, "type", "")),
+ "quantity": _obj_get(item, "qty"),
+ "notional": _obj_get(item, "notional"),
+ "filled_qty": _obj_get(item, "filled_qty"),
+ "filled_avg_price": _obj_get(item, "filled_avg_price"),
+ "limit_price": _obj_get(item, "limit_price"),
+ "status": str(_obj_get(item, "status", "")),
+ "submitted_at": str(_obj_get(item, "submitted_at", "")),
+ }
+
+
+def _bar_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "time": str(_obj_get(item, "timestamp", "")),
+ "open": _obj_get(item, "open"),
+ "high": _obj_get(item, "high"),
+ "low": _obj_get(item, "low"),
+ "close": _obj_get(item, "close"),
+ "volume": _obj_get(item, "volume"),
+ }
diff --git a/agent/src/trading/connectors/binance/__init__.py b/agent/src/trading/connectors/binance/__init__.py
new file mode 100644
index 000000000..c30b25270
--- /dev/null
+++ b/agent/src/trading/connectors/binance/__init__.py
@@ -0,0 +1,15 @@
+"""Binance (spot) trading connector.
+
+Read-only account/market access in Layer A via the ``ccxt`` library's unified
+``binance`` exchange client (REST). A ``broker_sdk`` transport. Order placement
+is not exposed here — writes are introduced in a later layer behind the paper
+guard and, for live, the mandate gate.
+
+Paper-vs-live separation is structural: the testnet (paper) and live mainnet use
+DIFFERENT API keys and DIFFERENT hosts (``testnet.binance.vision`` vs
+``api.binance.com``), so a testnet key physically cannot reach the live host. The
+configured ``profile`` selects the host (via ``set_sandbox_mode``) and is the
+authoritative discriminator; it is recorded on every payload and never flipped
+implicitly. Binance spot has no positions — holdings are non-zero balances, so
+``get_positions`` shapes the non-zero balances from ``fetch_balance`` as rows.
+"""
diff --git a/agent/src/trading/connectors/binance/classification.py b/agent/src/trading/connectors/binance/classification.py
new file mode 100644
index 000000000..b41770c78
--- /dev/null
+++ b/agent/src/trading/connectors/binance/classification.py
@@ -0,0 +1,24 @@
+"""Curated read/write classification for Binance (ccxt) spot operations.
+
+Keys are the ccxt unified method names this connector uses. Order-mutating ccxt
+calls are pinned WRITE so the live gate never treats them as plain reads;
+anything unlisted and not a known read is treated as WRITE (fail-closed) by the
+gate.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Binance (ccxt) spot operation read/write catalog.
+BINANCE_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "fetch_balance": ToolClass.READ,
+ "fetch_open_orders": ToolClass.READ,
+ "fetch_my_trades": ToolClass.READ,
+ "fetch_ticker": ToolClass.READ,
+ "fetch_ohlcv": ToolClass.READ,
+ # WRITE
+ "create_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/binance/profiles.py b/agent/src/trading/connectors/binance/profiles.py
new file mode 100644
index 000000000..571556c40
--- /dev/null
+++ b/agent/src/trading/connectors/binance/profiles.py
@@ -0,0 +1,70 @@
+"""Built-in Binance (spot) connector profiles.
+
+Read-only paper (testnet) and live profiles plus order-placing paper and live
+profiles. Paper and live use different key pairs and different hosts, so they
+are distinct profiles. The order-placing live profile carries an
+``orders.place.requires_mandate`` capability — the higher trading layer must
+gate it behind the user's mandate before any order reaches the connector.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+BINANCE_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="binance-paper-sdk",
+ connector="binance",
+ label="Binance Spot Testnet · ccxt",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads a Binance spot testnet account (testnet.binance.vision) via ccxt. "
+ "Testnet keys cannot reach the live host."
+ ),
+ ),
+ TradingProfile(
+ id="binance-live-sdk-readonly",
+ connector="binance",
+ label="Binance Spot Live · ccxt Read-Only",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes="Reads a Binance spot live account only (api.binance.com). Order placement is not exposed in this profile.",
+ ),
+ TradingProfile(
+ id="binance-paper-trade",
+ connector="binance",
+ label="Binance Spot Testnet · ccxt Trading",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper"},
+ notes=(
+ "Places and cancels orders on a Binance spot testnet account "
+ "(testnet.binance.vision) via ccxt. Testnet keys cannot reach the live host, "
+ "so no order from this profile can touch real funds."
+ ),
+ ),
+ TradingProfile(
+ id="binance-live-trade",
+ connector="binance",
+ label="Binance Spot Live · ccxt Trading",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place.requires_mandate",),
+ readonly=False,
+ config={"profile": "live"},
+ notes=(
+ "Places and cancels orders on a Binance spot live account (api.binance.com) "
+ "via ccxt. Live order placement must be gated by the user's mandate; the "
+ "orders.place.requires_mandate capability signals that requirement upstream."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/binance/sdk.py b/agent/src/trading/connectors/binance/sdk.py
new file mode 100644
index 000000000..61153ca14
--- /dev/null
+++ b/agent/src/trading/connectors/binance/sdk.py
@@ -0,0 +1,772 @@
+"""Read-only Binance (spot) connector via the ``ccxt`` unified exchange client.
+
+Wraps ccxt's ``binance`` exchange for the five read operations the trading layer
+exposes (account / positions / orders / quote / history). No order-placement
+method is exposed here — writes are introduced in a later layer behind the paper
+guard and, for live, the mandate gate.
+
+Paper-vs-live is structural: ``profile == "paper"`` builds the client with
+``set_sandbox_mode(True)`` (host ``testnet.binance.vision``) using the testnet
+key pair; a live profile uses ``set_sandbox_mode(False)`` (host
+``api.binance.com``) with the live key pair. A testnet key cannot reach the live
+host, so the configured host — recorded as ``host`` / ``paper_guard`` in every
+payload — is the authoritative discriminator. There is no paper/live field in
+any response; the host is the guard.
+
+Note: the testnet host may migrate (``testnet.binance.vision`` historically vs
+``demo-api.binance.com``), so ``testnet_host`` is config-overridable.
+
+Note: Binance spot has NO positions — holdings are simply non-zero balances. So
+``get_positions`` derives position-shaped rows from the non-zero ``total``
+balances returned by ``fetch_balance``.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+from urllib.parse import urlparse
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "binance.json"
+
+#: Profiles this connector understands and their default account environment.
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+DEFAULT_TESTNET_HOST = "https://testnet.binance.vision"
+LIVE_HOST = "https://api.binance.com"
+
+#: Common quote assets, longest-first, used to split a slashless symbol.
+_QUOTE_ASSETS = ("USDT", "USDC", "BUSD", "TUSD", "FDUSD", "BTC", "ETH", "BNB")
+
+
+class BinanceDependencyError(RuntimeError):
+ """Raised when the optional ``ccxt`` package is not installed."""
+
+
+class BinanceConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+def normalize_symbol(symbol: str) -> str:
+ """Normalize a symbol to ccxt unified ``BASE/QUOTE`` format.
+
+ Accepts ``BTC/USDT`` (passed through, uppercased), ``BTC-USDT`` (hyphen
+ rewritten to slash), or a slashless ``BTCUSDT`` (split before a known quote
+ asset). If the slashless form has no recognized quote suffix, the uppercased
+ input is returned unchanged.
+
+ Args:
+ symbol: The raw symbol string from a caller.
+
+ Returns:
+ A ccxt unified symbol such as ``BTC/USDT``.
+ """
+ clean = (symbol or "").strip().upper().replace("-", "/")
+ if "/" in clean:
+ return clean
+ for quote in _QUOTE_ASSETS:
+ if clean.endswith(quote) and len(clean) > len(quote):
+ return f"{clean[: -len(quote)]}/{quote}"
+ return clean
+
+
+@dataclass(frozen=True)
+class BinanceConfig:
+ """Binance (spot) connector connection settings.
+
+ Args:
+ api_key: Binance API key (testnet and live use different keys).
+ api_secret: Binance API secret.
+ profile: ``paper``, ``live-readonly`` or ``live``.
+ testnet_host: Testnet REST host (overridable; may migrate upstream).
+ timeout: Network timeout in seconds.
+ readonly: Always true for this layer; order methods are not exposed.
+ """
+
+ api_key: str = ""
+ api_secret: str = ""
+ profile: str = "paper"
+ testnet_host: str = DEFAULT_TESTNET_HOST
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "BinanceConfig":
+ """Build a config from a JSON-like mapping, normalizing the profile."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise BinanceConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ api_key=str(payload.get("api_key") or "").strip(),
+ api_secret=str(payload.get("api_secret") or "").strip(),
+ profile=profile,
+ testnet_host=str(payload.get("testnet_host") or DEFAULT_TESTNET_HOST).strip(),
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ api_key: str | None = None,
+ api_secret: str | None = None,
+ profile: str | None = None,
+ testnet_host: str | None = None,
+ ) -> "BinanceConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if api_key is not None:
+ payload["api_key"] = api_key
+ if api_secret is not None:
+ payload["api_secret"] = api_secret
+ if profile is not None:
+ payload["profile"] = profile
+ if testnet_host is not None:
+ payload["testnet_host"] = testnet_host
+ return BinanceConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+ @property
+ def is_testnet(self) -> bool:
+ """Return whether this profile targets the testnet host/key."""
+ return self.environment == "paper"
+
+ @property
+ def host(self) -> str:
+ """Return the REST host this profile connects to."""
+ return self.testnet_host if self.is_testnet else LIVE_HOST
+
+
+_OVERRIDE_KEYS = ("api_key", "api_secret", "profile", "testnet_host")
+
+
+def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "BinanceConfig":
+ """Resolve the effective config: saved file ← profile defaults ← CLI overrides.
+
+ Credentials (``api_key`` / ``api_secret``) come from the saved
+ ``~/.vibe-trading/binance.json``; the selected connector profile supplies the
+ ``profile`` intent; CLI/tool overrides win last.
+
+ Args:
+ profile_config: The connector profile's ``config`` dict.
+ overrides: Per-call overrides (only known config keys are applied).
+
+ Returns:
+ A normalized :class:`BinanceConfig`.
+ """
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = BinanceConfig.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def config_path() -> Path:
+ """Return the user-level Binance config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> BinanceConfig:
+ """Load Binance settings from ``~/.vibe-trading/binance.json``."""
+ path = config_path()
+ if not path.exists():
+ return BinanceConfig()
+ try:
+ return BinanceConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise BinanceConfigError(f"invalid Binance config at {path}: {exc}") from exc
+
+
+def save_config(config: BinanceConfig) -> Path:
+ """Persist Binance settings with owner-only permissions."""
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def ccxt_available() -> bool:
+ """Return whether the optional ``ccxt`` library can be imported."""
+ try:
+ _require_ccxt()
+ return True
+ except BinanceDependencyError:
+ return False
+
+
+def check_status(config: BinanceConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness, config completeness, and host separation.
+
+ Returns a JSON-serializable health report. Does not place or mutate any
+ broker state. The host-allowlist guard asserts that the client's resolved
+ host is the testnet host for a paper profile, or ``api.binance.com`` for a
+ live profile, so a key/host mismatch fails closed before any read.
+ """
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "ccxt", "installed": ccxt_available()},
+ "paper_guard": "host_separated",
+ "host": cfg.host,
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Binance connector not configured: missing {', '.join(missing)}."
+ return report
+
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install ccxt`."
+ return report
+
+ try:
+ _assert_host(cfg)
+ except BinanceConfigError as exc:
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ try:
+ snapshot = get_account_snapshot(cfg)
+ except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ report["account"] = {
+ "profile": cfg.profile,
+ "is_testnet": cfg.is_testnet,
+ "balances": len(snapshot.get("balances", [])),
+ }
+ return report
+
+
+def get_account_snapshot(config: BinanceConfig | None = None) -> dict[str, Any]:
+ """Fetch the spot account balance for the configured account.
+
+ Returns the non-zero balances (each with ``free`` / ``used`` / ``total``)
+ from ccxt's unified ``fetch_balance``.
+ """
+ cfg = config or load_config()
+ _assert_host(cfg)
+ ex = _exchange(cfg)
+ balance = ex.fetch_balance()
+ rows = _nonzero_balances(balance)
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_testnet": cfg.is_testnet,
+ "host": cfg.host,
+ "paper_guard": "host_separated",
+ "balances": rows,
+ }
+
+
+def get_positions(config: BinanceConfig | None = None) -> dict[str, Any]:
+ """Fetch holdings shaped as positions for the configured account.
+
+ Binance spot has no positions; holdings are the non-zero balances. Each row
+ is ``{symbol, quantity, free, used}`` where ``symbol`` is the asset code and
+ ``quantity`` is the total balance.
+ """
+ cfg = config or load_config()
+ _assert_host(cfg)
+ ex = _exchange(cfg)
+ balance = ex.fetch_balance()
+ rows = [
+ {
+ "symbol": _obj_get(row, "asset"),
+ "quantity": _obj_get(row, "total"),
+ "free": _obj_get(row, "free"),
+ "used": _obj_get(row, "used"),
+ }
+ for row in _nonzero_balances(balance)
+ ]
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_testnet": cfg.is_testnet,
+ "paper_guard": "host_separated",
+ "positions": rows,
+ }
+
+
+def get_open_orders(config: BinanceConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:
+ """Fetch open orders and, optionally, recent personal trades.
+
+ ``fetch_open_orders`` is called without a symbol to retrieve all open
+ orders; some Binance setups require a symbol, so the call is wrapped and a
+ note is returned on failure rather than failing the whole call. When
+ ``include_executions`` is set, ``fetch_my_trades`` typically REQUIRES a
+ symbol, so it is also wrapped and degrades to an empty list with a note.
+ """
+ cfg = config or load_config()
+ _assert_host(cfg)
+ ex = _exchange(cfg)
+ symbol_required = _symbol_required_errors()
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_testnet": cfg.is_testnet,
+ "paper_guard": "host_separated",
+ }
+ # Only the "this call needs a symbol" family degrades to a note; auth /
+ # network / rate-limit errors must propagate so the caller sees a real
+ # failure instead of a misleading status:ok with an empty list.
+ try:
+ open_orders = ex.fetch_open_orders()
+ result["open_orders"] = [_order_to_dict(item) for item in _as_iter(open_orders)]
+ except symbol_required as exc:
+ result["open_orders"] = []
+ result["open_orders_note"] = f"fetch_open_orders without a symbol failed: {exc}"
+ if include_executions:
+ try:
+ trades = ex.fetch_my_trades()
+ result["executions"] = [_trade_to_dict(item) for item in _as_iter(trades)]
+ except symbol_required as exc:
+ result["executions"] = []
+ result["executions_note"] = f"fetch_my_trades without a symbol failed: {exc}"
+ return result
+
+
+def get_quote(symbol: str, *, config: BinanceConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch a latest ticker snapshot for ``symbol`` (ccxt unified format)."""
+ cfg = config or load_config()
+ _assert_host(cfg)
+ ex = _exchange(cfg)
+ clean = normalize_symbol(symbol)
+ ticker = ex.fetch_ticker(clean)
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "quote": {
+ "bid": _obj_get(ticker, "bid"),
+ "ask": _obj_get(ticker, "ask"),
+ "last": _obj_get(ticker, "last"),
+ "high": _obj_get(ticker, "high"),
+ "low": _obj_get(ticker, "low"),
+ "volume": _obj_get(ticker, "baseVolume"),
+ "time": str(_obj_get(ticker, "timestamp", "")),
+ },
+ }
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: BinanceConfig | None = None,
+ period: str = "1d",
+ limit: int = 90,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV bars for ``symbol`` (ccxt unified format)."""
+ cfg = config or load_config()
+ _assert_host(cfg)
+ ex = _exchange(cfg)
+ clean = normalize_symbol(symbol)
+ bars = ex.fetch_ohlcv(clean, timeframe=period, limit=int(limit))
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "period": period,
+ "bars": [_ohlcv_to_dict(item) for item in _as_iter(bars)],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Order placement (write path; guarded by host separation + profile readonly)
+# ---------------------------------------------------------------------------
+
+#: ccxt ``timeInForce`` values Binance spot accepts for limit orders. Binance
+#: has no DAY policy; the unified ``"day"`` intent maps to GTC, which is the
+#: Binance default and the closest equivalent.
+_TIME_IN_FORCE_MAP = {
+ "day": "GTC",
+ "gtc": "GTC",
+ "ioc": "IOC",
+ "fok": "FOK",
+}
+
+
+def place_order(
+ config: BinanceConfig | None = None,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | None = None,
+ notional: float | None = None,
+ order_type: str = "market",
+ limit_price: float | None = None,
+ time_in_force: str = "day",
+) -> dict[str, Any]:
+ """Place a spot order on Binance via ccxt's unified ``create_order``.
+
+ The configured profile's host (testnet vs live) is the authoritative
+ paper/live discriminator and is asserted before anything is submitted, so a
+ testnet key can never reach the live host. The connector simply executes the
+ intent the caller has already authorized; mandate/limit enforcement lives in
+ a higher layer.
+
+ Either ``quantity`` (base-asset amount) or ``notional`` (quote-asset spend)
+ must be given, never both. ``notional`` is only supported for market orders:
+ ccxt's binance adapter forwards ``params={"quoteOrderQty": notional}`` so
+ Binance sizes the order in the quote asset (e.g. spend 50 USDT of BTC).
+ Limit orders require ``quantity`` and ``limit_price``.
+
+ Args:
+ config: Connector config; falls back to the saved config when ``None``.
+ symbol: Trading pair in any accepted form (normalized to ``BASE/QUOTE``).
+ side: ``"buy"`` or ``"sell"``.
+ quantity: Base-asset amount. Mutually exclusive with ``notional``.
+ notional: Quote-asset spend (market orders only). Mutually exclusive
+ with ``quantity``.
+ order_type: ``"market"`` or ``"limit"``.
+ limit_price: Required when ``order_type`` is ``"limit"``.
+ time_in_force: Limit-order policy; ``"day"`` maps to Binance GTC.
+
+ Returns:
+ On success: ``{"status": "ok", "order_id": str, "symbol", "side",
+ "profile", "order_type", "status", "filled", "amount", "price"}``. On
+ any validation or execution failure: ``{"status": "error", "error":
+ str}`` (fail-closed; nothing is submitted on a validation error).
+ """
+ cfg = config or load_config()
+
+ side_clean = str(side or "").strip().lower()
+ if side_clean not in ("buy", "sell"):
+ return {"status": "error", "error": "side must be 'buy' or 'sell'."}
+
+ type_clean = str(order_type or "").strip().lower()
+ if type_clean not in ("market", "limit"):
+ return {"status": "error", "error": "order_type must be 'market' or 'limit'."}
+
+ qty_given = quantity is not None
+ notional_given = notional is not None
+ if qty_given == notional_given:
+ return {"status": "error", "error": "provide exactly one of 'quantity' or 'notional'."}
+
+ qty_value = _to_float(quantity) if qty_given else None
+ notional_value = _to_float(notional) if notional_given else None
+ if qty_given and (qty_value is None or qty_value <= 0):
+ return {"status": "error", "error": "quantity must be a positive number."}
+ if notional_given and (notional_value is None or notional_value <= 0):
+ return {"status": "error", "error": "notional must be a positive number."}
+
+ if type_clean == "limit":
+ if notional_given:
+ return {"status": "error", "error": "limit orders require 'quantity', not 'notional'."}
+ price_value = _to_float(limit_price)
+ if price_value is None or price_value <= 0:
+ return {"status": "error", "error": "limit orders require a positive 'limit_price'."}
+ else:
+ price_value = None
+
+ # The connector merely executes against whatever environment the profile
+ # selects; readonly/mandate gating is enforced upstream (service + profile
+ # capabilities), not inside the connector. The host separation asserted next
+ # is the one structural guard that cannot be bypassed here.
+ try:
+ _assert_host(cfg)
+ except BinanceConfigError as exc:
+ return {"status": "error", "error": str(exc)}
+
+ clean_symbol = normalize_symbol(symbol)
+ if not clean_symbol or "/" not in clean_symbol:
+ return {"status": "error", "error": f"could not resolve a valid trading pair from symbol '{symbol}'."}
+
+ params: dict[str, Any] = {}
+ if type_clean == "limit":
+ tif = _TIME_IN_FORCE_MAP.get(str(time_in_force or "").strip().lower())
+ if tif is None:
+ return {"status": "error", "error": "time_in_force must be one of 'day', 'gtc', 'ioc', 'fok'."}
+ params["timeInForce"] = tif
+ amount: float | None = qty_value
+ price: float | None = price_value
+ elif notional_given:
+ # ccxt's binance adapter reads ``quoteOrderQty`` from params and sizes the
+ # order in the quote asset; ``amount`` carries the same notional so callers
+ # that inspect the unified amount see a sensible value.
+ params["quoteOrderQty"] = notional_value
+ amount = notional_value
+ price = None
+ else:
+ amount = qty_value
+ price = None
+
+ try:
+ ex = _exchange(cfg)
+ order = ex.create_order(clean_symbol, type_clean, side_clean, amount, price, params)
+ except Exception as exc: # noqa: BLE001 - surface any ccxt/auth/network error as fail-closed
+ return {"status": "error", "error": str(exc)}
+
+ return {
+ "status": "ok",
+ "order_id": str(_obj_get(order, "id", "")),
+ "symbol": _obj_get(order, "symbol", clean_symbol),
+ "side": str(_obj_get(order, "side", side_clean)),
+ "profile": cfg.profile,
+ "is_testnet": cfg.is_testnet,
+ "paper_guard": "host_separated",
+ "order_type": str(_obj_get(order, "type", type_clean)),
+ "order_status": str(_obj_get(order, "status", "")),
+ "filled": _obj_get(order, "filled"),
+ "amount": _obj_get(order, "amount"),
+ "price": _obj_get(order, "price"),
+ }
+
+
+def cancel_order(
+ config: BinanceConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel an open order by id. Binance REQUIRES the order's symbol.
+
+ Args:
+ config: Connector config; falls back to the saved config when ``None``.
+ order_id: The exchange order id to cancel.
+ symbol: The order's trading pair. Binance cannot cancel without it.
+
+ Returns:
+ On success: ``{"status": "ok", "order_id", "symbol", "side", "profile",
+ "order_status"}``. On any validation or execution failure:
+ ``{"status": "error", "error": str}`` (fail-closed).
+ """
+ cfg = config or load_config()
+
+ order_id_clean = str(order_id or "").strip()
+ if not order_id_clean:
+ return {"status": "error", "error": "order_id is required to cancel an order."}
+ if symbol is None or not str(symbol).strip():
+ return {"status": "error", "error": "Binance cancel requires symbol."}
+
+ try:
+ _assert_host(cfg)
+ except BinanceConfigError as exc:
+ return {"status": "error", "error": str(exc)}
+
+ clean_symbol = normalize_symbol(symbol)
+ if not clean_symbol or "/" not in clean_symbol:
+ return {"status": "error", "error": f"could not resolve a valid trading pair from symbol '{symbol}'."}
+
+ try:
+ ex = _exchange(cfg)
+ order = ex.cancel_order(order_id_clean, clean_symbol)
+ except Exception as exc: # noqa: BLE001 - surface any ccxt/auth/network error as fail-closed
+ return {"status": "error", "error": str(exc)}
+
+ return {
+ "status": "ok",
+ "order_id": str(_obj_get(order, "id", order_id_clean)),
+ "symbol": _obj_get(order, "symbol", clean_symbol),
+ "side": str(_obj_get(order, "side", "")),
+ "profile": cfg.profile,
+ "is_testnet": cfg.is_testnet,
+ "paper_guard": "host_separated",
+ "order_status": str(_obj_get(order, "status", "")),
+ }
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _require_ccxt() -> ModuleType:
+ try:
+ import ccxt # type: ignore
+ except ModuleNotFoundError as exc:
+ raise BinanceDependencyError("ccxt is not installed; run `pip install ccxt`.") from exc
+ return ccxt
+
+
+def _symbol_required_errors() -> tuple[type[BaseException], ...]:
+ """ccxt exception classes that mean "this call needs a symbol" (degrade-only).
+
+ Auth/network/rate-limit errors are deliberately excluded so they propagate
+ rather than being masked as a status:ok note.
+ """
+ ccxt = _require_ccxt()
+ names = ("ArgumentsRequired", "BadSymbol", "NotSupported")
+ classes = tuple(getattr(ccxt, n) for n in names if hasattr(ccxt, n))
+ return classes or (ValueError,)
+
+
+def _exchange(cfg: BinanceConfig):
+ """Build a ccxt ``binance`` client bound to the configured environment."""
+ ccxt = _require_ccxt()
+ ex = ccxt.binance(
+ {
+ "apiKey": cfg.api_key,
+ "secret": cfg.api_secret,
+ "enableRateLimit": True,
+ "timeout": int(cfg.timeout * 1000),
+ }
+ )
+ ex.set_sandbox_mode(cfg.is_testnet)
+ return ex
+
+
+def _assert_host(cfg: BinanceConfig) -> None:
+ """Fail closed when the resolved host does not match the declared environment.
+
+ The host is the authoritative discriminator: testnet keys cannot reach the
+ live host. A live profile must resolve to ``api.binance.com``; a paper
+ profile must resolve to the configured testnet host.
+ """
+ host = (urlparse(cfg.host).hostname or cfg.host or "").lower()
+ if cfg.is_testnet:
+ expected = (urlparse(cfg.testnet_host).hostname or cfg.testnet_host or "").lower()
+ if host != expected:
+ raise BinanceConfigError(
+ f"Configured profile is paper, but the resolved host '{host}' is not the testnet host '{expected}'."
+ )
+ return
+ expected = urlparse(LIVE_HOST).hostname or LIVE_HOST
+ if host != expected:
+ raise BinanceConfigError(
+ f"Configured profile is live, but the resolved host '{host}' is not the live host '{expected}'."
+ )
+
+
+def _missing_fields(cfg: BinanceConfig) -> list[str]:
+ missing = []
+ if not cfg.api_key:
+ missing.append("api_key")
+ if not cfg.api_secret:
+ missing.append("api_secret")
+ return missing
+
+
+def _public_config(cfg: BinanceConfig) -> dict[str, Any]:
+ """Config snapshot with secrets redacted."""
+ data = asdict(cfg)
+ if data.get("api_secret"):
+ data["api_secret"] = "***redacted***"
+ if data.get("api_key"):
+ data["api_key"] = data["api_key"][:4] + "***"
+ data["host"] = cfg.host
+ return data
+
+
+# ---------------------------------------------------------------------------
+# Defensive field extraction (ccxt returns dicts; stay defensive anyway)
+# ---------------------------------------------------------------------------
+
+
+def _as_iter(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
+ if obj is None:
+ return default
+ if isinstance(obj, Mapping):
+ return obj.get(name, default)
+ return getattr(obj, name, default)
+
+
+def _to_float(value: Any) -> float | None:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _nonzero_balances(balance: Any) -> list[dict[str, Any]]:
+ """Extract non-zero per-asset balances from a ccxt ``fetch_balance`` result.
+
+ ccxt returns a dict keyed by asset (each ``{free, used, total}``) plus
+ aggregate ``total`` / ``free`` / ``used`` maps and metadata keys (``info``,
+ ``timestamp``, ``datetime``, ``free``, ``used``, ``total``). We iterate the
+ per-asset sub-dicts and keep those with a non-zero total.
+ """
+ rows: list[dict[str, Any]] = []
+ if not isinstance(balance, Mapping):
+ return rows
+ skip = {"info", "timestamp", "datetime", "free", "used", "total"}
+ for asset, detail in balance.items():
+ if asset in skip or not isinstance(detail, Mapping):
+ continue
+ total = _to_float(detail.get("total"))
+ if not total:
+ continue
+ rows.append(
+ {
+ "asset": asset,
+ "free": _to_float(detail.get("free")),
+ "used": _to_float(detail.get("used")),
+ "total": total,
+ }
+ )
+ return rows
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": str(_obj_get(item, "id", "")),
+ "symbol": _obj_get(item, "symbol"),
+ "side": str(_obj_get(item, "side", "")),
+ "order_type": str(_obj_get(item, "type", "")),
+ "price": _obj_get(item, "price"),
+ "quantity": _obj_get(item, "amount"),
+ "filled": _obj_get(item, "filled"),
+ "remaining": _obj_get(item, "remaining"),
+ "status": str(_obj_get(item, "status", "")),
+ "time": str(_obj_get(item, "timestamp", "")),
+ }
+
+
+def _trade_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "trade_id": str(_obj_get(item, "id", "")),
+ "order_id": str(_obj_get(item, "order", "")),
+ "symbol": _obj_get(item, "symbol"),
+ "side": str(_obj_get(item, "side", "")),
+ "price": _obj_get(item, "price"),
+ "quantity": _obj_get(item, "amount"),
+ "cost": _obj_get(item, "cost"),
+ "time": str(_obj_get(item, "timestamp", "")),
+ }
+
+
+def _ohlcv_to_dict(item: Any) -> dict[str, Any]:
+ """Shape a ccxt OHLCV row (``[ts, o, h, l, c, v]``) into a named dict."""
+ row = list(item) if isinstance(item, (list, tuple)) else []
+ row += [None] * (6 - len(row))
+ return {
+ "time": str(row[0] if row[0] is not None else ""),
+ "open": row[1],
+ "high": row[2],
+ "low": row[3],
+ "close": row[4],
+ "volume": row[5],
+ }
diff --git a/agent/src/trading/connectors/futu/__init__.py b/agent/src/trading/connectors/futu/__init__.py
new file mode 100644
index 000000000..959ca177c
--- /dev/null
+++ b/agent/src/trading/connectors/futu/__init__.py
@@ -0,0 +1,52 @@
+"""Futu (moomoo) trading connector.
+
+Read-only account/market access in Layer A via the official ``futu-api`` Python
+SDK talking to a user-owned LOCAL OpenD gateway (default ``127.0.0.1:11111``).
+Like the IBKR connector, this is a local-gateway transport: OpenD runs on the
+operator's machine, holds the Futu login, and the SDK speaks to it over a local
+socket. Vibe-Trading never sees Futu credentials and exposes no order-placement
+method (no ``place_order``, no ``unlock_trade``) in this layer; order placement
+(paper, then mandate-gated live) is layered on top later.
+
+Paper-vs-live separation is the documented Futu discriminator: every account row
+from ``get_acc_list()`` carries a ``trd_env`` field (``SIMULATE`` for paper,
+``REAL`` for live). The connector resolves the account whose ``trd_env`` matches
+the selected profile and fails closed if a configured ``acc_id`` does not match,
+so a live account can never be driven under a paper profile by mistake.
+"""
+
+from src.trading.connectors.futu.sdk import (
+ FutuConfig,
+ FutuConfigError,
+ FutuDependencyError,
+ FutuProfileMismatchError,
+ build_config,
+ check_status,
+ config_path,
+ futu_available,
+ get_account_snapshot,
+ get_historical_bars,
+ get_open_orders,
+ get_positions,
+ get_quote,
+ load_config,
+ save_config,
+)
+
+__all__ = [
+ "FutuConfig",
+ "FutuConfigError",
+ "FutuDependencyError",
+ "FutuProfileMismatchError",
+ "build_config",
+ "check_status",
+ "config_path",
+ "futu_available",
+ "get_account_snapshot",
+ "get_historical_bars",
+ "get_open_orders",
+ "get_positions",
+ "get_quote",
+ "load_config",
+ "save_config",
+]
diff --git a/agent/src/trading/connectors/futu/classification.py b/agent/src/trading/connectors/futu/classification.py
new file mode 100644
index 000000000..fae4fe5a6
--- /dev/null
+++ b/agent/src/trading/connectors/futu/classification.py
@@ -0,0 +1,31 @@
+"""Curated read/write classification for Futu (futu-api) SDK operations.
+
+The trading layer classifies each connector operation as READ or WRITE so the
+live gate can keep writes behind the mandate. Futu is a direct local-SDK
+connector (the SDK talks to a local OpenD gateway, not a remote MCP server), so
+the keys here are the SDK's own method names rather than remote MCP tool names.
+Anything not listed and not a known read resolves to WRITE (fail-closed) when
+the live gate consults this map.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Futu SDK operation read/write catalog. Read operations mirror the connector's
+#: public read functions; write operations are the order-mutating / trade-unlock
+#: SDK calls, pinned WRITE so the live gate never treats them as plain reads.
+FUTU_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "accinfo_query": ToolClass.READ,
+ "position_list_query": ToolClass.READ,
+ "order_list_query": ToolClass.READ,
+ "deal_list_query": ToolClass.READ,
+ "get_market_snapshot": ToolClass.READ,
+ "request_history_kline": ToolClass.READ,
+ "get_acc_list": ToolClass.READ,
+ # WRITE
+ "place_order": ToolClass.WRITE,
+ "modify_order": ToolClass.WRITE,
+ "unlock_trade": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/futu/profiles.py b/agent/src/trading/connectors/futu/profiles.py
new file mode 100644
index 000000000..d09cf2968
--- /dev/null
+++ b/agent/src/trading/connectors/futu/profiles.py
@@ -0,0 +1,80 @@
+"""Built-in Futu (moomoo) connector profiles.
+
+Read-only paper and live profiles sit alongside order-placing paper and live
+profiles. All four reach the same local OpenD gateway; the profile chooses the
+trade environment (``SIMULATE`` vs ``REAL``) and the account is resolved by its
+``trd_env`` at runtime. The order-placing live profile gates on the mandate
+("orders.place.requires_mandate") and requires an OpenD trade-password unlock.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+FUTU_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="futu-paper-sdk",
+ connector="futu",
+ label="Futu Paper · futu-api",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper", "filter_trdmarket": "HK"},
+ notes=(
+ "Reads a Futu paper (SIMULATE) account via futu-api through a local OpenD "
+ "gateway (default 127.0.0.1:11111). OpenD must be running and logged in. "
+ "The account is resolved by trd_env=SIMULATE; a live account cannot be "
+ "driven under this profile."
+ ),
+ ),
+ TradingProfile(
+ id="futu-live-sdk-readonly",
+ connector="futu",
+ label="Futu Live · futu-api Read-Only",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly", "filter_trdmarket": "HK"},
+ notes=(
+ "Reads a Futu live (REAL) account only, via futu-api through a local OpenD "
+ "gateway (default 127.0.0.1:11111). OpenD must be running and logged in. "
+ "Order placement is not exposed in this profile."
+ ),
+ ),
+ TradingProfile(
+ id="futu-paper-trade",
+ connector="futu",
+ label="Futu Paper · futu-api Trading",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper", "filter_trdmarket": "HK"},
+ notes=(
+ "Places orders on a Futu paper (SIMULATE) account via futu-api through a "
+ "local OpenD gateway (default 127.0.0.1:11111). OpenD must be running and "
+ "logged in. The account is resolved by trd_env=SIMULATE; a live account "
+ "cannot be driven under this profile. Paper accounts are never unlocked, so "
+ "no trade password is required."
+ ),
+ ),
+ TradingProfile(
+ id="futu-live-trade",
+ connector="futu",
+ label="Futu Live · futu-api Trading",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place.requires_mandate",),
+ readonly=False,
+ config={"profile": "live", "filter_trdmarket": "HK"},
+ notes=(
+ "Places orders on a Futu live (REAL) account via futu-api through a local "
+ "OpenD gateway (default 127.0.0.1:11111). OpenD must be running and logged "
+ "in. Live order placement gates on the user mandate and requires unlocking "
+ "the trade context with FUTU_TRADE_PWD_MD5 (the MD5 of the Futu trade "
+ "password); without it, orders fail closed."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/futu/sdk.py b/agent/src/trading/connectors/futu/sdk.py
new file mode 100644
index 000000000..0c22cdf95
--- /dev/null
+++ b/agent/src/trading/connectors/futu/sdk.py
@@ -0,0 +1,911 @@
+"""Read-only Futu (moomoo) connector via the official ``futu-api`` SDK.
+
+This module wraps Futu's ``OpenSecTradeContext`` / ``OpenQuoteContext`` for the
+five read operations the trading layer exposes (account / positions / orders /
+quote / history). It holds no order-placement method and never calls
+``unlock_trade`` — writes are introduced in a later layer behind the paper guard
+and, for live, the mandate gate.
+
+Architecture is a LOCAL OpenD gateway (default ``127.0.0.1:11111``), exactly
+like IBKR's local TWS / IB Gateway: OpenD runs on the operator's machine, holds
+the Futu login, and the SDK speaks to it over a local socket. Vibe-Trading never
+sees Futu credentials. A TCP-port-open probe runs before every connect so a
+missing gateway degrades to a clean error instead of an SDK stack trace.
+
+Paper-vs-live identity guard (the documented Futu discriminator): every account
+row from ``OpenSecTradeContext.get_acc_list()`` carries a ``trd_env`` field
+(``SIMULATE`` for paper, ``REAL`` for live). The connector resolves the account
+whose ``trd_env`` matches the selected profile's environment; if a non-zero
+``acc_id`` is configured, that row's ``trd_env`` must match the profile or the
+guard fails closed. This pins ``paper_guard="trd_env_acc_list"``.
+
+Futu SDK calls return ``(ret_code, data)`` tuples (and ``request_history_kline``
+returns a 3-tuple ``(ret, df, page_key)``); ``data`` is typically a pandas
+DataFrame which we convert with ``to_dict("records")`` before field mapping.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import socket
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "futu.json"
+
+#: Default local OpenD gateway endpoint.
+DEFAULT_HOST = "127.0.0.1"
+DEFAULT_PORT = 11111
+
+#: Profiles this connector understands and their default account environment.
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+#: Maps the connector environment to the Futu ``TrdEnv`` enum member name.
+_ENV_TO_TRD_ENV = {
+ "paper": "SIMULATE",
+ "live": "REAL",
+}
+
+
+class FutuDependencyError(RuntimeError):
+ """Raised when the optional ``futu-api`` package is not installed."""
+
+
+class FutuConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+class FutuProfileMismatchError(RuntimeError):
+ """Raised when a profile's account does not match its declared environment."""
+
+
+@dataclass(frozen=True)
+class FutuConfig:
+ """Futu connector connection settings.
+
+ Args:
+ host: Local host where the OpenD gateway listens.
+ port: OpenD socket port (default 11111).
+ profile: ``paper``, ``live-readonly`` or ``live``.
+ security_firm: Futu security firm, e.g. ``FUTUSECURITIES``.
+ filter_trdmarket: Trade market filter for the trade context, e.g. ``HK``.
+ acc_id: Account id; ``0`` means resolve by ``trd_env``.
+ timeout: Network/connect timeout in seconds.
+ readonly: Always true for this layer; order methods are not exposed.
+ """
+
+ host: str = DEFAULT_HOST
+ port: int = DEFAULT_PORT
+ profile: str = "paper"
+ security_firm: str = "FUTUSECURITIES"
+ filter_trdmarket: str = "HK"
+ acc_id: int = 0
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "FutuConfig":
+ """Build a config from a JSON-like mapping, normalizing the profile.
+
+ Args:
+ data: Mapping with any subset of config fields.
+
+ Returns:
+ A normalized :class:`FutuConfig`.
+
+ Raises:
+ FutuConfigError: If the profile is not a recognized value.
+ """
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise FutuConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ host=str(payload.get("host") or DEFAULT_HOST).strip(),
+ port=int(payload.get("port") or DEFAULT_PORT),
+ profile=profile,
+ security_firm=str(payload.get("security_firm") or "FUTUSECURITIES").strip().upper(),
+ filter_trdmarket=str(payload.get("filter_trdmarket") or "HK").strip().upper(),
+ acc_id=int(payload.get("acc_id") or 0),
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ host: str | None = None,
+ port: int | None = None,
+ profile: str | None = None,
+ security_firm: str | None = None,
+ filter_trdmarket: str | None = None,
+ acc_id: int | None = None,
+ ) -> "FutuConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if host is not None:
+ payload["host"] = host
+ if port is not None:
+ payload["port"] = port
+ if profile is not None:
+ payload["profile"] = profile
+ if security_firm is not None:
+ payload["security_firm"] = security_firm
+ if filter_trdmarket is not None:
+ payload["filter_trdmarket"] = filter_trdmarket
+ if acc_id is not None:
+ payload["acc_id"] = acc_id
+ return FutuConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+ @property
+ def trd_env_name(self) -> str:
+ """Return the Futu ``TrdEnv`` member name (``SIMULATE`` or ``REAL``)."""
+ return _ENV_TO_TRD_ENV.get(self.environment, "SIMULATE")
+
+
+_OVERRIDE_KEYS = ("host", "port", "profile", "security_firm", "filter_trdmarket", "acc_id")
+
+
+def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "FutuConfig":
+ """Resolve the effective config: saved file ← profile defaults ← CLI overrides.
+
+ Gateway endpoint and account settings come from the saved
+ ``~/.vibe-trading/futu.json``; the selected connector profile supplies the
+ ``profile`` / ``filter_trdmarket`` intent; CLI/tool overrides win last.
+
+ Args:
+ profile_config: The connector profile's ``config`` dict.
+ overrides: Per-call overrides (only known config keys are applied).
+
+ Returns:
+ A normalized :class:`FutuConfig`.
+ """
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = FutuConfig.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def config_path() -> Path:
+ """Return the user-level Futu config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> FutuConfig:
+ """Load Futu settings from ``~/.vibe-trading/futu.json``."""
+ path = config_path()
+ if not path.exists():
+ return FutuConfig()
+ try:
+ return FutuConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise FutuConfigError(f"invalid Futu config at {path}: {exc}") from exc
+
+
+def save_config(config: FutuConfig) -> Path:
+ """Persist Futu settings with owner-only permissions."""
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def futu_available() -> bool:
+ """Return whether the optional ``futu-api`` SDK can be imported."""
+ try:
+ _require_futu()
+ return True
+ except FutuDependencyError:
+ return False
+
+
+def check_status(config: FutuConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness, gateway reachability, and account identity.
+
+ Returns a JSON-serializable health report that degrades cleanly when the
+ OpenD gateway is not running or ``futu-api`` is not installed. Does not place
+ or mutate any broker state.
+
+ Args:
+ config: Optional target config; loaded from disk when omitted.
+
+ Returns:
+ A health report dict.
+ """
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "futu-api", "installed": futu_available()},
+ "paper_guard": "trd_env_acc_list",
+ "trd_env": cfg.trd_env_name,
+ }
+
+ gateway_open = tcp_port_open(cfg.host, cfg.port)
+ report["gateway"] = {"host": cfg.host, "port": cfg.port, "open": gateway_open}
+ if not gateway_open:
+ report["status"] = "error"
+ report["error"] = (
+ f"No Futu OpenD gateway is listening at {cfg.host}:{cfg.port}. "
+ "Start OpenD, log in, and confirm the API port."
+ )
+ return report
+
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install futu-api`."
+ return report
+
+ try:
+ snapshot = get_account_snapshot(cfg)
+ except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ report["account"] = {
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": snapshot.get("acc_id"),
+ }
+ return report
+
+
+def get_account_snapshot(config: FutuConfig | None = None) -> dict[str, Any]:
+ """Fetch account funds/assets for the resolved account."""
+ cfg = config or load_config()
+ trade_ctx = _trade_ctx(cfg)
+ try:
+ acc_id = _resolve_acc_id(cfg, trade_ctx)
+ trd_env = _trd_env_enum(cfg)
+ rows = _records(_unwrap(trade_ctx.accinfo_query(trd_env=trd_env, acc_id=acc_id)))
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": acc_id,
+ "assets": [_account_to_dict(row) for row in rows],
+ }
+ finally:
+ _close(trade_ctx)
+
+
+def get_positions(config: FutuConfig | None = None) -> dict[str, Any]:
+ """Fetch current positions for the resolved account."""
+ cfg = config or load_config()
+ trade_ctx = _trade_ctx(cfg)
+ try:
+ acc_id = _resolve_acc_id(cfg, trade_ctx)
+ trd_env = _trd_env_enum(cfg)
+ rows = _records(_unwrap(trade_ctx.position_list_query(trd_env=trd_env, acc_id=acc_id)))
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": acc_id,
+ "positions": [_position_to_dict(row) for row in rows],
+ }
+ finally:
+ _close(trade_ctx)
+
+
+def get_open_orders(config: FutuConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:
+ """Fetch open orders and, optionally, recent fills (deals)."""
+ cfg = config or load_config()
+ trade_ctx = _trade_ctx(cfg)
+ try:
+ acc_id = _resolve_acc_id(cfg, trade_ctx)
+ trd_env = _trd_env_enum(cfg)
+ orders = _records(_unwrap(trade_ctx.order_list_query(trd_env=trd_env, acc_id=acc_id)))
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": acc_id,
+ "open_orders": [_order_to_dict(row) for row in orders],
+ }
+ if include_executions:
+ deals = _records(_unwrap(trade_ctx.deal_list_query(trd_env=trd_env, acc_id=acc_id)))
+ result["executions"] = [_deal_to_dict(row) for row in deals]
+ return result
+ finally:
+ _close(trade_ctx)
+
+
+def get_quote(symbol: str, *, config: FutuConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch a market-snapshot quote for ``symbol`` (e.g. ``HK.00700``)."""
+ cfg = config or load_config()
+ quote_ctx = _quote_ctx(cfg)
+ try:
+ code = symbol.strip().upper()
+ rows = _records(_unwrap(quote_ctx.get_market_snapshot([code])))
+ payload = _quote_to_dict(rows[0]) if rows else {}
+ return {"status": "ok", "symbol": code, "quote": payload}
+ finally:
+ _close(quote_ctx)
+
+
+#: Canonical period token → Futu ``KLType`` attribute name.
+_KLTYPE_MAP = {
+ "1m": "K_1M", "5m": "K_5M", "15m": "K_15M", "30m": "K_30M",
+ "1h": "K_60M", "4h": "K_60M", "1d": "K_DAY", "1w": "K_WEEK", "1M": "K_MON",
+}
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: FutuConfig | None = None,
+ period: str = "1d",
+ limit: int = 90,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical K-line bars for ``symbol`` (e.g. ``US.AAPL``)."""
+ cfg = config or load_config()
+ futu = _require_futu()
+ ktype_name = _KLTYPE_MAP.get(period.strip(), "K_DAY")
+ ktype = getattr(futu.KLType, ktype_name, getattr(futu.KLType, "K_DAY"))
+ quote_ctx = _quote_ctx(cfg)
+ try:
+ code = symbol.strip().upper()
+ rows = _records(_unwrap(quote_ctx.request_history_kline(code, ktype=ktype, max_count=int(limit))))
+ return {
+ "status": "ok",
+ "symbol": code,
+ "period": period,
+ "bars": [_bar_to_dict(row) for row in rows],
+ }
+ finally:
+ _close(quote_ctx)
+
+
+# ---------------------------------------------------------------------------
+# Order placement (paper SIMULATE + live REAL, fail-closed)
+# ---------------------------------------------------------------------------
+
+#: Env var holding the MD5 of the Futu trade password (required to unlock live).
+LIVE_TRADE_PWD_ENV = "FUTU_TRADE_PWD_MD5"
+
+#: side token → Futu ``TrdSide`` enum member name.
+_SIDE_TO_TRD_SIDE = {"buy": "BUY", "sell": "SELL"}
+
+
+def place_order(
+ config: FutuConfig | None = None,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | int | None = None,
+ notional: float | None = None,
+ order_type: str = "market",
+ limit_price: float | None = None,
+ time_in_force: str = "day",
+) -> dict[str, Any]:
+ """Place a Futu order through the local OpenD gateway.
+
+ Resolves the account by ``trd_env`` (paper = SIMULATE, live = REAL), unlocks
+ the trade context for live profiles only, then submits a market or limit
+ order. Fails closed: every error path returns ``{"status": "error", ...}``
+ instead of raising. Futu has no notional-based order path, so a notional-only
+ request is rejected.
+
+ Args:
+ config: Effective connector config; loaded from disk when omitted.
+ symbol: Futu instrument code, e.g. ``HK.00700`` / ``US.AAPL`` (passed
+ through uppercased).
+ side: ``buy`` or ``sell``.
+ quantity: Share quantity (required; coerced to ``int``).
+ notional: Cash amount. Unsupported by Futu — present only to satisfy the
+ shared contract; supplying it without ``quantity`` is an error.
+ order_type: ``market`` or ``limit``. ``limit`` requires ``limit_price``.
+ limit_price: Limit price; required when ``order_type`` is ``limit``.
+ time_in_force: Accepted for contract parity; Futu's ``place_order`` does
+ not take a TIF on this path, so it is echoed back only.
+
+ Returns:
+ On success ``{"status": "ok", "order_id", "symbol", "side", "profile",
+ ...}``; on any failure ``{"status": "error", "error": ...}``.
+ """
+ cfg = config or load_config()
+
+ side_key = str(side or "").strip().lower()
+ if side_key not in _SIDE_TO_TRD_SIDE:
+ return _order_error(cfg, "side must be 'buy' or 'sell'")
+
+ order_kind = str(order_type or "").strip().lower()
+ if order_kind not in ("market", "limit"):
+ return _order_error(cfg, "order_type must be 'market' or 'limit'")
+
+ if quantity is None:
+ if notional is not None:
+ return _order_error(
+ cfg, "Futu requires an explicit quantity; notional-based orders are not supported"
+ )
+ return _order_error(cfg, "quantity is required")
+
+ try:
+ qty_int = int(quantity)
+ except (TypeError, ValueError):
+ return _order_error(cfg, "quantity must be a whole number of shares")
+ if qty_int <= 0:
+ return _order_error(cfg, "quantity must be a positive whole number of shares")
+
+ price = 0.0
+ if order_kind == "limit":
+ if limit_price is None:
+ return _order_error(cfg, "limit_price is required for a limit order")
+ try:
+ price = float(limit_price)
+ except (TypeError, ValueError):
+ return _order_error(cfg, "limit_price must be a number")
+ if price <= 0:
+ return _order_error(cfg, "limit_price must be a positive number")
+
+ code = str(symbol or "").strip().upper()
+ if not code:
+ return _order_error(cfg, "symbol is required")
+
+ try:
+ futu = _require_futu()
+ except FutuDependencyError as exc:
+ return _order_error(cfg, str(exc))
+
+ try:
+ trade_ctx = _trade_ctx(cfg)
+ except (FutuConfigError, FutuDependencyError) as exc:
+ return _order_error(cfg, str(exc))
+
+ try:
+ acc_id = _resolve_acc_id(cfg, trade_ctx)
+ trd_env = _trd_env_enum(cfg)
+
+ unlock_error = _unlock_if_live(cfg, trade_ctx, futu)
+ if unlock_error is not None:
+ return _order_error(cfg, unlock_error)
+
+ trd_side = getattr(futu.TrdSide, _SIDE_TO_TRD_SIDE[side_key])
+ ftu_order_type = (
+ futu.OrderType.MARKET if order_kind == "market" else futu.OrderType.NORMAL
+ )
+ ret, data = trade_ctx.place_order(
+ price=price,
+ qty=qty_int,
+ code=code,
+ trd_side=trd_side,
+ order_type=ftu_order_type,
+ trd_env=trd_env,
+ acc_id=acc_id,
+ )
+ if ret != getattr(futu, "RET_OK", 0):
+ return _order_error(cfg, f"Futu place_order rejected the order: {data}")
+
+ rows = _records(data)
+ order_id = str(_first(rows[0], ("order_id",), "")) if rows else ""
+ if not order_id:
+ return _order_error(cfg, f"Futu accepted the order but returned no order_id: {data}")
+
+ return {
+ "status": "ok",
+ "order_id": order_id,
+ "symbol": code,
+ "side": side_key,
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": acc_id,
+ "order_type": order_kind,
+ "quantity": qty_int,
+ "limit_price": price if order_kind == "limit" else None,
+ "time_in_force": str(time_in_force or "day"),
+ }
+ except FutuProfileMismatchError as exc:
+ return _order_error(cfg, str(exc))
+ except Exception as exc: # noqa: BLE001 - order path must fail closed
+ return _order_error(cfg, str(exc))
+ finally:
+ _close(trade_ctx)
+
+
+def cancel_order(
+ config: FutuConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel a Futu order through the local OpenD gateway.
+
+ Resolves the account by ``trd_env`` and unlocks for live profiles only, then
+ issues ``modify_order(ModifyOrderOp.CANCEL, ...)``. Fails closed: every error
+ path returns ``{"status": "error", ...}``.
+
+ Args:
+ config: Effective connector config; loaded from disk when omitted.
+ order_id: The Futu order id to cancel.
+ symbol: Optional instrument code; echoed back for caller context (Futu
+ cancels by ``order_id`` and does not require the symbol).
+
+ Returns:
+ On success ``{"status": "ok", "order_id", "symbol", "profile", ...}``;
+ on any failure ``{"status": "error", "error": ...}``.
+ """
+ cfg = config or load_config()
+
+ oid = str(order_id or "").strip()
+ if not oid:
+ return _order_error(cfg, "order_id is required")
+
+ code = str(symbol or "").strip().upper() or None
+
+ try:
+ futu = _require_futu()
+ except FutuDependencyError as exc:
+ return _order_error(cfg, str(exc))
+
+ try:
+ trade_ctx = _trade_ctx(cfg)
+ except (FutuConfigError, FutuDependencyError) as exc:
+ return _order_error(cfg, str(exc))
+
+ try:
+ acc_id = _resolve_acc_id(cfg, trade_ctx)
+ trd_env = _trd_env_enum(cfg)
+
+ unlock_error = _unlock_if_live(cfg, trade_ctx, futu)
+ if unlock_error is not None:
+ return _order_error(cfg, unlock_error)
+
+ ret, data = trade_ctx.modify_order(
+ futu.ModifyOrderOp.CANCEL,
+ oid,
+ 0,
+ 0,
+ trd_env=trd_env,
+ acc_id=acc_id,
+ )
+ if ret != getattr(futu, "RET_OK", 0):
+ return _order_error(cfg, f"Futu cancel rejected: {data}")
+
+ return {
+ "status": "ok",
+ "order_id": oid,
+ "symbol": code,
+ "profile": cfg.profile,
+ "trd_env": cfg.trd_env_name,
+ "acc_id": acc_id,
+ }
+ except FutuProfileMismatchError as exc:
+ return _order_error(cfg, str(exc))
+ except Exception as exc: # noqa: BLE001 - cancel path must fail closed
+ return _order_error(cfg, str(exc))
+ finally:
+ _close(trade_ctx)
+
+
+def _unlock_if_live(cfg: FutuConfig, trade_ctx: Any, futu: ModuleType) -> str | None:
+ """Unlock the trade context for live profiles; paper (SIMULATE) is a no-op.
+
+ Live trading requires the MD5 of the Futu trade password, read from the
+ :data:`LIVE_TRADE_PWD_ENV` environment variable. Paper accounts must never be
+ unlocked.
+
+ Args:
+ cfg: Effective connector config.
+ trade_ctx: An open ``OpenSecTradeContext``.
+ futu: The imported ``futu`` module.
+
+ Returns:
+ ``None`` on success (or when no unlock is needed); an error message
+ string when the live unlock cannot be completed.
+ """
+ if cfg.environment != "live":
+ return None
+ pwd_md5 = os.environ.get(LIVE_TRADE_PWD_ENV, "").strip()
+ if not pwd_md5:
+ return f"live order requires {LIVE_TRADE_PWD_ENV}"
+ ret, data = trade_ctx.unlock_trade(password_md5=pwd_md5, is_unlock=True)
+ if ret != getattr(futu, "RET_OK", 0):
+ return f"Futu unlock_trade failed: {data}"
+ return None
+
+
+def _order_error(cfg: FutuConfig, message: str) -> dict[str, Any]:
+ """Build a fail-closed order error envelope tagged with the profile."""
+ return {"status": "error", "error": message, "profile": cfg.profile}
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _require_futu() -> ModuleType:
+ try:
+ import futu # type: ignore
+ except ModuleNotFoundError as exc:
+ raise FutuDependencyError("futu-api is not installed; run `pip install futu-api`.") from exc
+ return futu
+
+
+def tcp_port_open(host: str, port: int, timeout: float = 0.5) -> bool:
+ """Return whether a TCP socket accepts connections."""
+ try:
+ with socket.create_connection((host, int(port)), timeout=timeout):
+ return True
+ except OSError:
+ return False
+
+
+def _assert_gateway(cfg: FutuConfig) -> None:
+ """Fail with a clean error when the local OpenD gateway is unreachable."""
+ if not tcp_port_open(cfg.host, cfg.port):
+ raise FutuConfigError(
+ f"No Futu OpenD gateway is listening at {cfg.host}:{cfg.port}. "
+ "Start OpenD, log in, and confirm the API port."
+ )
+
+
+def _trade_ctx(cfg: FutuConfig):
+ """Open an ``OpenSecTradeContext`` against the local OpenD gateway."""
+ _assert_gateway(cfg)
+ futu = _require_futu()
+ trd_market = getattr(futu.TrdMarket, cfg.filter_trdmarket, getattr(futu.TrdMarket, "HK"))
+ security_firm = getattr(futu.SecurityFirm, cfg.security_firm, getattr(futu.SecurityFirm, "FUTUSECURITIES"))
+ try:
+ return futu.OpenSecTradeContext(
+ filter_trdmarket=trd_market,
+ host=cfg.host,
+ port=cfg.port,
+ security_firm=security_firm,
+ )
+ except TypeError:
+ return futu.OpenSecTradeContext(host=cfg.host, port=cfg.port)
+
+
+def _quote_ctx(cfg: FutuConfig):
+ """Open an ``OpenQuoteContext`` against the local OpenD gateway."""
+ _assert_gateway(cfg)
+ futu = _require_futu()
+ return futu.OpenQuoteContext(host=cfg.host, port=cfg.port)
+
+
+def _trd_env_enum(cfg: FutuConfig):
+ """Return the ``TrdEnv`` enum value for this profile's environment."""
+ futu = _require_futu()
+ return getattr(futu.TrdEnv, cfg.trd_env_name, futu.TrdEnv.SIMULATE)
+
+
+def _resolve_acc_id(cfg: FutuConfig, trade_ctx: Any) -> int:
+ """Resolve and guard the account id by its ``trd_env``.
+
+ Calls ``get_acc_list()``, keeps rows whose ``trd_env`` matches the profile,
+ and either confirms the configured ``acc_id`` (failing closed on mismatch) or
+ selects the first matching account when ``acc_id`` is ``0``.
+
+ Args:
+ cfg: Effective connector config.
+ trade_ctx: An open ``OpenSecTradeContext``.
+
+ Returns:
+ The resolved Futu account id.
+
+ Raises:
+ FutuProfileMismatchError: If the configured account's ``trd_env`` does
+ not match the profile, or no account matches the profile env.
+ """
+ rows = _records(_unwrap(trade_ctx.get_acc_list()))
+ want = cfg.trd_env_name
+ matching = [row for row in rows if _trd_env_of(row) == want]
+
+ if cfg.acc_id:
+ target = next((row for row in rows if _acc_id_of(row) == cfg.acc_id), None)
+ if target is None:
+ raise FutuProfileMismatchError(
+ f"Configured acc_id {cfg.acc_id} was not found in the OpenD account list."
+ )
+ if _trd_env_of(target) != want:
+ raise FutuProfileMismatchError(
+ f"Configured acc_id {cfg.acc_id} has trd_env {_trd_env_of(target)!r}, "
+ f"but profile {cfg.profile!r} requires {want!r}. "
+ "Select a profile that matches this account's environment."
+ )
+ return cfg.acc_id
+
+ if not matching:
+ raise FutuProfileMismatchError(
+ f"No Futu account with trd_env {want!r} was found for profile {cfg.profile!r}. "
+ "Confirm OpenD is logged into the expected account."
+ )
+ return _acc_id_of(matching[0])
+
+
+def _close(ctx: Any) -> None:
+ """Close an OpenD context, swallowing teardown errors."""
+ try:
+ ctx.close()
+ except Exception: # noqa: BLE001 - teardown must not mask the primary result
+ pass
+
+
+def _public_config(cfg: FutuConfig) -> dict[str, Any]:
+ """Config snapshot with no secret material (local endpoint only)."""
+ return asdict(cfg)
+
+
+# ---------------------------------------------------------------------------
+# Defensive (ret_code, data) handling + DataFrame field extraction
+# ---------------------------------------------------------------------------
+
+
+def _unwrap(result: Any) -> Any:
+ """Return the data payload from a Futu ``(ret_code, data[, page_key])`` tuple.
+
+ Futu read calls return ``(ret_code, data)``; ``request_history_kline``
+ returns a 3-tuple ``(ret, df, page_key)``. On a non-``RET_OK`` return code we
+ yield ``None`` so the caller degrades to an empty record set rather than
+ surfacing a raw SDK error string.
+
+ Args:
+ result: The raw value returned by an SDK read call.
+
+ Returns:
+ The data payload (typically a pandas DataFrame), or ``None`` on error.
+ """
+ if not isinstance(result, (list, tuple)) or len(result) < 2:
+ return result
+ ret_code, data = result[0], result[1]
+ futu = _require_futu()
+ if ret_code != getattr(futu, "RET_OK", 0):
+ return None
+ return data
+
+
+def _records(data: Any) -> list[dict[str, Any]]:
+ """Normalize a Futu data payload to a list of row dicts.
+
+ Handles a pandas DataFrame (via ``to_dict('records')``), an existing list of
+ dicts, a single mapping, or ``None``.
+
+ Args:
+ data: The payload returned by :func:`_unwrap`.
+
+ Returns:
+ A list of plain row dicts (possibly empty).
+ """
+ if data is None:
+ return []
+ to_dict = getattr(data, "to_dict", None)
+ if callable(to_dict) and hasattr(data, "columns"):
+ try:
+ return list(to_dict("records"))
+ except Exception: # noqa: BLE001 - fall through to generic handling
+ pass
+ if isinstance(data, Mapping):
+ return [dict(data)]
+ if isinstance(data, (list, tuple)):
+ return [dict(item) if isinstance(item, Mapping) else {"value": item} for item in data]
+ return []
+
+
+def _row_get(row: Mapping[str, Any], name: str, default: Any = None) -> Any:
+ if not isinstance(row, Mapping):
+ return default
+ return row.get(name, default)
+
+
+def _first(row: Mapping[str, Any], names: tuple[str, ...], default: Any = None) -> Any:
+ for name in names:
+ value = _row_get(row, name, None)
+ if value is not None:
+ return value
+ return default
+
+
+def _trd_env_of(row: Mapping[str, Any]) -> str:
+ return str(_first(row, ("trd_env", "trdEnv"), "")).upper()
+
+
+def _acc_id_of(row: Mapping[str, Any]) -> int:
+ try:
+ return int(_first(row, ("acc_id", "accId"), 0) or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _account_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ "power": _first(row, ("power",)),
+ "total_assets": _first(row, ("total_assets",)),
+ "cash": _first(row, ("cash",)),
+ "market_val": _first(row, ("market_val",)),
+ "available_funds": _first(row, ("available_funds",)),
+ "securities_assets": _first(row, ("securities_assets",)),
+ }
+
+
+def _position_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ "code": _first(row, ("code",)),
+ "qty": _first(row, ("qty",)),
+ "can_sell_qty": _first(row, ("can_sell_qty",)),
+ "cost_price": _first(row, ("cost_price",)),
+ "market_val": _first(row, ("market_val",)),
+ "pl_ratio": _first(row, ("pl_ratio",)),
+ "pl_val": _first(row, ("pl_val",)),
+ "position_side": str(_first(row, ("position_side",), "")),
+ }
+
+
+def _order_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ "order_id": _first(row, ("order_id",)),
+ "code": _first(row, ("code",)),
+ "stock_name": _first(row, ("stock_name",)),
+ "trd_side": str(_first(row, ("trd_side",), "")),
+ "order_type": str(_first(row, ("order_type",), "")),
+ "order_status": str(_first(row, ("order_status",), "")),
+ "qty": _first(row, ("qty",)),
+ "price": _first(row, ("price",)),
+ "dealt_qty": _first(row, ("dealt_qty",)),
+ "dealt_avg_price": _first(row, ("dealt_avg_price",)),
+ "create_time": str(_first(row, ("create_time",), "")),
+ }
+
+
+def _deal_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ "deal_id": _first(row, ("deal_id",)),
+ "order_id": _first(row, ("order_id",)),
+ "code": _first(row, ("code",)),
+ "qty": _first(row, ("qty",)),
+ "price": _first(row, ("price",)),
+ "trd_side": str(_first(row, ("trd_side",), "")),
+ "create_time": str(_first(row, ("create_time",), "")),
+ }
+
+
+def _quote_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ "code": _first(row, ("code",)),
+ "last": _first(row, ("last_price",)),
+ "open": _first(row, ("open_price",)),
+ "high": _first(row, ("high_price",)),
+ "low": _first(row, ("low_price",)),
+ "prev_close": _first(row, ("prev_close_price",)),
+ "volume": _first(row, ("volume",)),
+ "ask": _first(row, ("ask_price",)),
+ "bid": _first(row, ("bid_price",)),
+ "time": str(_first(row, ("update_time",), "")),
+ }
+
+
+def _bar_to_dict(row: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ "code": _first(row, ("code",)),
+ "time": str(_first(row, ("time_key",), "")),
+ "open": _first(row, ("open",)),
+ "close": _first(row, ("close",)),
+ "high": _first(row, ("high",)),
+ "low": _first(row, ("low",)),
+ "volume": _first(row, ("volume",)),
+ "turnover": _first(row, ("turnover",)),
+ }
diff --git a/agent/src/trading/connectors/longbridge/__init__.py b/agent/src/trading/connectors/longbridge/__init__.py
new file mode 100644
index 000000000..57ff77ee8
--- /dev/null
+++ b/agent/src/trading/connectors/longbridge/__init__.py
@@ -0,0 +1,13 @@
+"""Longbridge (LongPort OpenAPI) trading connector.
+
+Read-only account/market access in Layer A via the official ``longbridge``
+Python SDK (``TradeContext`` / ``QuoteContext`` over REST). A ``broker_sdk``
+transport, like Tiger.
+
+Safety note: Longbridge exposes no runtime field that distinguishes a paper
+account from a live one — paper and live share the same host and App Key and
+differ only by which Access Token is loaded. The paper/live distinction here is
+therefore operator-declared in config and cannot be self-verified from any API
+response. Order placement on this connector stays gated on resolving a reliable
+runtime discriminator first.
+"""
diff --git a/agent/src/trading/connectors/longbridge/classification.py b/agent/src/trading/connectors/longbridge/classification.py
new file mode 100644
index 000000000..75cf83f11
--- /dev/null
+++ b/agent/src/trading/connectors/longbridge/classification.py
@@ -0,0 +1,29 @@
+"""Curated read/write classification for Longbridge SDK operations.
+
+Keys are the connector's own operation names (Longbridge is a direct-SDK
+connector, not MCP). Order-mutating SDK calls are pinned WRITE so the live gate
+never treats them as plain reads; anything unlisted and not a known read is
+treated as WRITE (fail-closed) by the gate.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Longbridge SDK operation read/write catalog.
+LONGBRIDGE_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "account_balance": ToolClass.READ,
+ "stock_positions": ToolClass.READ,
+ "today_orders": ToolClass.READ,
+ "history_orders": ToolClass.READ,
+ "today_executions": ToolClass.READ,
+ "history_executions": ToolClass.READ,
+ "quote": ToolClass.READ,
+ "depth": ToolClass.READ,
+ "candlesticks": ToolClass.READ,
+ # WRITE
+ "submit_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+ "replace_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/longbridge/profiles.py b/agent/src/trading/connectors/longbridge/profiles.py
new file mode 100644
index 000000000..3a2d999f4
--- /dev/null
+++ b/agent/src/trading/connectors/longbridge/profiles.py
@@ -0,0 +1,55 @@
+"""Built-in Longbridge connector profiles.
+
+Layer A ships read-only paper and live profiles. Because Longbridge exposes no
+runtime paper/live discriminator, the paper profile's environment is
+operator-declared (config-trust) and order placement is not exposed here.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+LONGBRIDGE_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="longbridge-paper-sdk",
+ connector="longbridge",
+ label="Longbridge Paper · LongPort OpenAPI",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper", "region": "global"},
+ notes=(
+ "Reads a Longbridge paper account via the official longbridge SDK. "
+ "Paper vs live is operator-declared (the API exposes no runtime "
+ "discriminator); load the paper Access Token for this profile."
+ ),
+ ),
+ TradingProfile(
+ id="longbridge-paper-trade",
+ connector="longbridge",
+ label="Longbridge Paper · LongPort OpenAPI Trade",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper", "region": "global"},
+ notes=(
+ "Places PAPER orders against a Longbridge paper account via the "
+ "official longbridge SDK. Paper-only by design: Longbridge exposes "
+ "no runtime paper/live discriminator, so live order placement is "
+ "not supported. Load the paper Access Token for this profile."
+ ),
+ ),
+ TradingProfile(
+ id="longbridge-live-sdk-readonly",
+ connector="longbridge",
+ label="Longbridge Live · LongPort OpenAPI Read-Only",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly", "region": "global"},
+ notes="Reads a Longbridge live account only. Order placement is not exposed in this profile.",
+ ),
+)
diff --git a/agent/src/trading/connectors/longbridge/sdk.py b/agent/src/trading/connectors/longbridge/sdk.py
new file mode 100644
index 000000000..3ffaeaf1d
--- /dev/null
+++ b/agent/src/trading/connectors/longbridge/sdk.py
@@ -0,0 +1,753 @@
+"""Read-only Longbridge (LongPort OpenAPI) connector via the official SDK.
+
+Wraps ``TradeContext`` / ``QuoteContext`` for the five read operations the
+trading layer exposes (account / positions / orders / quote / history). No
+order-placement method is exposed here.
+
+Auth is static-key (App Key + App Secret + Access Token). The SDK was renamed
+from ``longport`` to ``longbridge``; this module imports whichever is installed.
+
+Paper-vs-live identity guard: **none is possible from the API** — Longbridge
+exposes no response field, account prefix, or host that distinguishes paper from
+live (they differ only by the loaded Access Token). The configured ``profile``
+label is therefore trust-based and recorded in every payload as
+``paper_guard="config_declared"`` so callers never mistake it for a verified
+environment.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "longbridge.json"
+
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+#: Region → HTTP host (used only for display/diagnostics; the SDK selects the
+#: host from the same region setting). Paper and live share these hosts.
+REGION_HOSTS = {
+ "global": "openapi.longbridge.com",
+ "cn": "openapi.longbridge.cn",
+}
+
+
+class LongbridgeDependencyError(RuntimeError):
+ """Raised when neither ``longbridge`` nor ``longport`` SDK is installed."""
+
+
+class LongbridgeConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+@dataclass(frozen=True)
+class LongbridgeConfig:
+ """Longbridge connector connection settings.
+
+ Args:
+ app_key: LongPort App Key.
+ app_secret: LongPort App Secret.
+ access_token: LongPort Access Token (selects paper vs live account).
+ profile: ``paper``, ``live-readonly`` or ``live`` (operator-declared).
+ region: ``global`` or ``cn`` (host region; not a paper/live signal).
+ timeout: Network timeout in seconds.
+ readonly: Always true for this layer; order methods are not exposed.
+ """
+
+ app_key: str = ""
+ app_secret: str = ""
+ access_token: str = ""
+ profile: str = "paper"
+ region: str = "global"
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "LongbridgeConfig":
+ """Build a config from a JSON-like mapping, normalizing the profile."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise LongbridgeConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ region = str(payload.get("region") or "global").strip().lower()
+ if region not in REGION_HOSTS:
+ raise LongbridgeConfigError("region must be 'global' or 'cn'")
+ return cls(
+ app_key=str(payload.get("app_key") or "").strip(),
+ app_secret=str(payload.get("app_secret") or "").strip(),
+ access_token=str(payload.get("access_token") or "").strip(),
+ profile=profile,
+ region=region,
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ app_key: str | None = None,
+ app_secret: str | None = None,
+ access_token: str | None = None,
+ profile: str | None = None,
+ region: str | None = None,
+ ) -> "LongbridgeConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if app_key is not None:
+ payload["app_key"] = app_key
+ if app_secret is not None:
+ payload["app_secret"] = app_secret
+ if access_token is not None:
+ payload["access_token"] = access_token
+ if profile is not None:
+ payload["profile"] = profile
+ if region is not None:
+ payload["region"] = region
+ return LongbridgeConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+
+_OVERRIDE_KEYS = ("app_key", "app_secret", "access_token", "profile", "region")
+
+
+def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "LongbridgeConfig":
+ """Resolve the effective config: saved file ← profile defaults ← CLI overrides.
+
+ Credentials (``app_key`` / ``app_secret`` / ``access_token``) come from the
+ saved ``~/.vibe-trading/longbridge.json``; the selected connector profile
+ supplies the ``profile`` / ``region`` intent; CLI/tool overrides win last.
+
+ Args:
+ profile_config: The connector profile's ``config`` dict.
+ overrides: Per-call overrides (only known config keys are applied).
+
+ Returns:
+ A normalized :class:`LongbridgeConfig`.
+ """
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = LongbridgeConfig.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def config_path() -> Path:
+ """Return the user-level Longbridge config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> LongbridgeConfig:
+ """Load Longbridge settings from ``~/.vibe-trading/longbridge.json``."""
+ path = config_path()
+ if not path.exists():
+ return LongbridgeConfig()
+ try:
+ return LongbridgeConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise LongbridgeConfigError(f"invalid Longbridge config at {path}: {exc}") from exc
+
+
+def save_config(config: LongbridgeConfig) -> Path:
+ """Persist Longbridge settings with owner-only permissions."""
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def longbridge_available() -> bool:
+ """Return whether the optional Longbridge SDK can be imported."""
+ try:
+ _require_openapi()
+ return True
+ except LongbridgeDependencyError:
+ return False
+
+
+def check_status(config: LongbridgeConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness and config completeness without mutating broker state."""
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "longbridge", "installed": longbridge_available()},
+ "paper_guard": "config_declared",
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Longbridge connector not configured: missing {', '.join(missing)}."
+ return report
+
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install longbridge`."
+ return report
+
+ try:
+ snapshot = get_account_snapshot(cfg)
+ except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ report["account"] = {
+ "profile": cfg.profile,
+ "region": cfg.region,
+ "balances_currency": [row.get("currency") for row in snapshot.get("balances", [])],
+ }
+ return report
+
+
+def get_account_snapshot(config: LongbridgeConfig | None = None) -> dict[str, Any]:
+ """Fetch account balances for the configured account."""
+ cfg = config or load_config()
+ trade = _trade_context(cfg)
+ balances = _call(trade, "account_balance")
+ rows = [_balance_to_dict(item) for item in _as_iter(balances)]
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "paper_guard": "config_declared",
+ "balances": rows,
+ }
+
+
+def get_positions(config: LongbridgeConfig | None = None) -> dict[str, Any]:
+ """Fetch current stock positions for the configured account."""
+ cfg = config or load_config()
+ trade = _trade_context(cfg)
+ response = _call(trade, "stock_positions")
+ rows = [_position_to_dict(item) for item in _iter_positions(response)]
+ return {"status": "ok", "profile": cfg.profile, "paper_guard": "config_declared", "positions": rows}
+
+
+#: Longbridge OrderStatus values that mean the order is no longer live (bare
+#: member names). Used to filter ``today_orders`` (which returns ALL of today's
+#: orders) down to the genuinely-open ones, so ``open_orders`` matches the other
+#: connectors' meaning. Matching is normalized so it works whether the SDK
+#: stringifies a status as ``Filled``, ``FilledStatus`` or ``OrderStatus.Filled``.
+#: ``PartialFilled`` is deliberately NOT terminal (still open).
+_TERMINAL_ORDER_STATUSES = frozenset(
+ {"filled", "canceled", "cancelled", "rejected", "expired", "partialwithdrawal"}
+)
+
+
+def _normalize_status(value: Any) -> str:
+ """Normalize a status to a bare lower-case member name for comparison."""
+ text = str(value or "").strip().lower()
+ text = text.rsplit(".", 1)[-1] # drop an ``orderstatus.`` prefix
+ if text.endswith("status"):
+ text = text[: -len("status")] # drop a ``...Status`` suffix
+ return text
+
+
+def _is_open_order(row: dict[str, Any]) -> bool:
+ """Return whether a mapped order row is still live (not in a terminal state)."""
+ return _normalize_status(row.get("status")) not in _TERMINAL_ORDER_STATUSES
+
+
+def get_open_orders(config: LongbridgeConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:
+ """Fetch today's still-open orders and, optionally, today's executions.
+
+ Longbridge's ``today_orders`` returns ALL of today's orders (including
+ filled/cancelled). We filter to non-terminal statuses so ``open_orders``
+ means the same thing here as in the other connectors.
+ """
+ cfg = config or load_config()
+ trade = _trade_context(cfg)
+ orders = _call(trade, "today_orders")
+ mapped = [_order_to_dict(item) for item in _as_iter(orders)]
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "paper_guard": "config_declared",
+ "open_orders": [row for row in mapped if _is_open_order(row)],
+ }
+ if include_executions:
+ execs = _safe_call(trade, "today_executions")
+ result["executions"] = [_execution_to_dict(item) for item in _as_iter(execs)]
+ return result
+
+
+def get_quote(symbol: str, *, config: LongbridgeConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch a quote snapshot for ``symbol`` (top-of-book bid/ask via depth)."""
+ cfg = config or load_config()
+ quote_ctx = _quote_context(cfg)
+ clean = symbol.strip().upper()
+ quotes = _call(quote_ctx, "quote", [clean])
+ rows = [_quote_to_dict(item) for item in _as_iter(quotes)]
+ payload = rows[0] if rows else {}
+ depth = _safe_call(quote_ctx, "depth", clean)
+ bid, ask = _top_of_book(depth)
+ if bid is not None:
+ payload["bid"] = bid
+ if ask is not None:
+ payload["ask"] = ask
+ return {"status": "ok", "symbol": clean, "quote": payload}
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: LongbridgeConfig | None = None,
+ period: str = "1d",
+ limit: int = 90,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV candlesticks for ``symbol`` (``period`` canonical)."""
+ cfg = config or load_config()
+ quote_ctx = _quote_context(cfg)
+ clean = symbol.strip().upper()
+ period_enum, adjust_enum = _candlestick_enums(period)
+ bars = _call(quote_ctx, "candlesticks", clean, period_enum, int(limit), adjust_enum)
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "period": period,
+ "bars": [_bar_to_dict(item) for item in _as_iter(bars)],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Order placement — PAPER ONLY (no runtime paper/live discriminator exists)
+# ---------------------------------------------------------------------------
+
+#: Message used by both order entry points when the config is not a paper
+#: profile. Longbridge exposes no API field that distinguishes paper from live,
+#: so we structurally refuse anything that is not the declared paper profile —
+#: this connector can never place a live order by design.
+_PAPER_ONLY_ERROR = (
+ "Longbridge order placement is paper-only (no runtime paper/live "
+ "discriminator); live orders are not supported."
+)
+
+_SIDE_MAP = {"buy": "Buy", "sell": "Sell"}
+_ORDER_TYPE_MAP = {"market": "MO", "limit": "LO"}
+_TIF_MAP = {"day": "Day"}
+
+
+def place_order(
+ config: LongbridgeConfig,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | None = None,
+ notional: float | None = None,
+ order_type: str = "market",
+ limit_price: float | None = None,
+ time_in_force: str = "day",
+) -> dict[str, Any]:
+ """Place a PAPER-ONLY stock order via the Longbridge ``TradeContext``.
+
+ Longbridge exposes no runtime paper/live discriminator (paper vs live is
+ only the loaded Access Token), so this connector is structurally capped at
+ paper: the very first check refuses any config whose ``environment`` is not
+ ``paper``. There is therefore no live order path here, by design.
+
+ The order is submitted against whatever account the loaded paper Access
+ Token points at. The connector only executes; authorization (mandate gate,
+ kill switch) is the caller's responsibility.
+
+ Args:
+ config: Resolved :class:`LongbridgeConfig`. Must be a paper profile.
+ symbol: Longbridge symbol, e.g. ``700.HK`` or ``AAPL.US`` (passed
+ through uppercased).
+ side: ``buy`` or ``sell`` (case-insensitive).
+ quantity: Order size in shares. Longbridge requires an explicit share
+ quantity; provide this (not ``notional``).
+ notional: Unsupported — Longbridge has no notional order path, so a
+ notional-only request fails closed with a clear error.
+ order_type: ``market`` or ``limit`` (a ``limit`` order requires
+ ``limit_price``).
+ limit_price: Limit price; required for and only used by limit orders.
+ time_in_force: Only ``day`` is supported.
+
+ Returns:
+ ``{"status": "ok", "order_id": str, "symbol", "side", "profile", ...}``
+ on success, otherwise ``{"status": "error", "error": str}``. Never
+ raises: every failure mode is reported in the envelope.
+ """
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ if config.environment != "paper":
+ return {"status": "error", "error": _PAPER_ONLY_ERROR}
+
+ # ---- input validation (fail closed before touching the SDK) ----
+ side_key = str(side or "").strip().lower()
+ side_attr = _SIDE_MAP.get(side_key)
+ if side_attr is None:
+ return {"status": "error", "error": "side must be 'buy' or 'sell'"}
+
+ if (quantity is None) == (notional is None):
+ return {"status": "error", "error": "provide exactly one of quantity or notional"}
+ if notional is not None:
+ return {"status": "error", "error": "Longbridge requires quantity (shares), not notional"}
+
+ try:
+ qty = float(quantity)
+ except (TypeError, ValueError):
+ return {"status": "error", "error": "quantity must be a number"}
+ if qty <= 0:
+ return {"status": "error", "error": "quantity must be positive"}
+
+ type_key = str(order_type or "").strip().lower()
+ type_attr = _ORDER_TYPE_MAP.get(type_key)
+ if type_attr is None:
+ return {"status": "error", "error": "order_type must be 'market' or 'limit'"}
+
+ px: float | None = None
+ if type_key == "limit":
+ if limit_price is None:
+ return {"status": "error", "error": "limit order requires limit_price"}
+ try:
+ px = float(limit_price)
+ except (TypeError, ValueError):
+ return {"status": "error", "error": "limit_price must be a number"}
+ if px <= 0:
+ return {"status": "error", "error": "limit_price must be positive"}
+
+ tif_key = str(time_in_force or "").strip().lower()
+ tif_attr = _TIF_MAP.get(tif_key)
+ if tif_attr is None:
+ return {"status": "error", "error": "time_in_force must be 'day'"}
+
+ clean_symbol = str(symbol or "").strip().upper()
+ if not clean_symbol:
+ return {"status": "error", "error": "symbol is required"}
+
+ # ---- resolve SDK enums + build + submit ----
+ try:
+ from decimal import Decimal
+
+ openapi = _require_openapi()
+ order_type_enum = getattr(getattr(openapi, "OrderType"), type_attr)
+ order_side_enum = getattr(getattr(openapi, "OrderSide"), side_attr)
+ tif_enum = getattr(getattr(openapi, "TimeInForceType"), tif_attr)
+
+ kwargs: dict[str, Any] = {
+ "symbol": clean_symbol,
+ "order_type": order_type_enum,
+ "side": order_side_enum,
+ "submitted_quantity": Decimal(str(qty)),
+ "time_in_force": tif_enum,
+ }
+ if type_key == "limit":
+ kwargs["submitted_price"] = Decimal(str(px))
+
+ trade = _trade_context(config)
+ response = _call(trade, "submit_order", **kwargs)
+ order_id = _obj_get(response, "order_id", None)
+ except Exception as exc: # noqa: BLE001 - fail closed, never raise to caller
+ return {"status": "error", "error": str(exc)}
+
+ if order_id is None:
+ return {"status": "error", "error": "Longbridge did not return an order id"}
+
+ return {
+ "status": "ok",
+ "order_id": str(order_id),
+ "symbol": clean_symbol,
+ "side": side_key,
+ "profile": config.profile,
+ "paper_guard": "config_declared",
+ "order_type": type_key,
+ "quantity": qty,
+ "limit_price": px,
+ "time_in_force": tif_key,
+ }
+
+
+def cancel_order(config: LongbridgeConfig, order_id: Any, *, symbol: str | None = None) -> dict[str, Any]:
+ """Cancel a PAPER-ONLY order via the Longbridge ``TradeContext``.
+
+ Like :func:`place_order`, the very first check refuses any config whose
+ ``environment`` is not ``paper`` — this connector never cancels a live
+ order. Longbridge cancels by order id; ``symbol`` is echoed back only for
+ caller convenience. Never raises: every failure is returned in the envelope.
+
+ Args:
+ config: Resolved :class:`LongbridgeConfig`. Must be a paper profile.
+ order_id: The order id returned by :func:`place_order`.
+ symbol: Optional symbol, echoed back; Longbridge cancels by id and does
+ not require it.
+
+ Returns:
+ ``{"status": "ok", "order_id": str, "profile", ...}`` on success,
+ otherwise ``{"status": "error", "error": str}``.
+ """
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ if config.environment != "paper":
+ return {"status": "error", "error": _PAPER_ONLY_ERROR}
+
+ if order_id is None or str(order_id).strip() == "":
+ return {"status": "error", "error": "order_id is required"}
+
+ clean_id = str(order_id).strip()
+ try:
+ trade = _trade_context(config)
+ _call(trade, "cancel_order", clean_id)
+ except Exception as exc: # noqa: BLE001 - fail closed, never raise to caller
+ return {"status": "error", "error": str(exc)}
+
+ result: dict[str, Any] = {
+ "status": "ok",
+ "order_id": clean_id,
+ "profile": config.profile,
+ "paper_guard": "config_declared",
+ }
+ if symbol is not None:
+ result["symbol"] = str(symbol).strip().upper()
+ return result
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing — import either the renamed ``longbridge`` or legacy ``longport``
+# ---------------------------------------------------------------------------
+
+
+def _require_openapi() -> ModuleType:
+ """Return the ``openapi`` submodule from whichever SDK package is installed."""
+ for package in ("longbridge", "longport"):
+ try:
+ module = __import__(f"{package}.openapi", fromlist=["openapi"])
+ return module
+ except ModuleNotFoundError:
+ continue
+ raise LongbridgeDependencyError(
+ "Longbridge SDK is not installed; run `pip install longbridge`."
+ )
+
+
+def _build_config(cfg: LongbridgeConfig):
+ openapi = _require_openapi()
+ config_cls = getattr(openapi, "Config")
+ # SDK exposes both a keyword constructor and a ``from_apikey`` factory across
+ # versions; try the direct constructor, fall back to the factory.
+ try:
+ return config_cls(
+ app_key=cfg.app_key,
+ app_secret=cfg.app_secret,
+ access_token=cfg.access_token,
+ )
+ except TypeError:
+ return config_cls.from_apikey(cfg.app_key, cfg.app_secret, cfg.access_token)
+
+
+def _trade_context(cfg: LongbridgeConfig):
+ openapi = _require_openapi()
+ return getattr(openapi, "TradeContext")(_build_config(cfg))
+
+
+def _quote_context(cfg: LongbridgeConfig):
+ openapi = _require_openapi()
+ return getattr(openapi, "QuoteContext")(_build_config(cfg))
+
+
+def _candlestick_enums(period: str):
+ """Map a period string to the SDK ``Period`` and ``AdjustType`` enums."""
+ openapi = _require_openapi()
+ period_cls = getattr(openapi, "Period")
+ adjust_cls = getattr(openapi, "AdjustType")
+ period_map = {
+ "1m": "Min_1",
+ "5m": "Min_5",
+ "15m": "Min_15",
+ "30m": "Min_30",
+ "1h": "Min_60",
+ "4h": "Min_60",
+ "1d": "Day",
+ "1w": "Week",
+ "1M": "Month",
+ }
+ attr = period_map.get(period.strip(), "Day")
+ period_enum = getattr(period_cls, attr, getattr(period_cls, "Day"))
+ adjust_enum = getattr(adjust_cls, "NoAdjust", getattr(adjust_cls, "ForwardAdjust", None))
+ return period_enum, adjust_enum
+
+
+def _missing_fields(cfg: LongbridgeConfig) -> list[str]:
+ missing = []
+ if not cfg.app_key:
+ missing.append("app_key")
+ if not cfg.app_secret:
+ missing.append("app_secret")
+ if not cfg.access_token:
+ missing.append("access_token")
+ return missing
+
+
+def _public_config(cfg: LongbridgeConfig) -> dict[str, Any]:
+ """Config snapshot with secrets redacted."""
+ data = asdict(cfg)
+ for secret in ("app_secret", "access_token"):
+ if data.get(secret):
+ data[secret] = "***redacted***"
+ if data.get("app_key"):
+ data["app_key"] = data["app_key"][:4] + "***"
+ data["host"] = REGION_HOSTS.get(cfg.region)
+ return data
+
+
+# ---------------------------------------------------------------------------
+# Defensive field extraction
+# ---------------------------------------------------------------------------
+
+
+def _as_iter(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
+ if obj is None:
+ return default
+ if isinstance(obj, Mapping):
+ return obj.get(name, default)
+ return getattr(obj, name, default)
+
+
+def _first(obj: Any, names: tuple[str, ...], default: Any = None) -> Any:
+ for name in names:
+ value = _obj_get(obj, name, None)
+ if value is not None:
+ return value
+ return default
+
+
+def _iter_positions(response: Any) -> list[Any]:
+ """Flatten ``stock_positions`` channels into a flat position list."""
+ channels = _obj_get(response, "channels")
+ if channels is None:
+ return _as_iter(response)
+ rows: list[Any] = []
+ for channel in _as_iter(channels):
+ rows.extend(_as_iter(_obj_get(channel, "positions")))
+ return rows
+
+
+def _top_of_book(depth: Any) -> tuple[Any, Any]:
+ """Extract best bid/ask price from a depth response."""
+ if depth is None:
+ return None, None
+ asks = _as_iter(_obj_get(depth, "asks") or _obj_get(depth, "ask"))
+ bids = _as_iter(_obj_get(depth, "bids") or _obj_get(depth, "bid"))
+ bid = _first(bids[0], ("price",)) if bids else None
+ ask = _first(asks[0], ("price",)) if asks else None
+ return bid, ask
+
+
+def _balance_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "currency": _first(item, ("currency",)),
+ "total_cash": _first(item, ("total_cash",)),
+ "net_assets": _first(item, ("net_assets",)),
+ "buy_power": _first(item, ("buy_power",)),
+ "init_margin": _first(item, ("init_margin",)),
+ "maintenance_margin": _first(item, ("maintenance_margin",)),
+ }
+
+
+def _position_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _first(item, ("symbol",)),
+ "symbol_name": _first(item, ("symbol_name",)),
+ "quantity": _first(item, ("quantity",)),
+ "available_quantity": _first(item, ("available_quantity",)),
+ "cost_price": _first(item, ("cost_price",)),
+ "currency": _first(item, ("currency",)),
+ "market": str(_first(item, ("market",), "")),
+ }
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": _first(item, ("order_id",)),
+ "symbol": _first(item, ("symbol",)),
+ "stock_name": _first(item, ("stock_name",)),
+ "side": str(_first(item, ("side",), "")),
+ "order_type": str(_first(item, ("order_type",), "")),
+ "quantity": _first(item, ("quantity",)),
+ "executed_quantity": _first(item, ("executed_quantity",)),
+ "price": _first(item, ("price",)),
+ "executed_price": _first(item, ("executed_price",)),
+ "status": str(_first(item, ("status",), "")),
+ "currency": _first(item, ("currency",)),
+ "submitted_at": str(_first(item, ("submitted_at",), "")),
+ }
+
+
+def _execution_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": _first(item, ("order_id",)),
+ "trade_id": _first(item, ("trade_id",)),
+ "symbol": _first(item, ("symbol",)),
+ "quantity": _first(item, ("quantity",)),
+ "price": _first(item, ("price",)),
+ "trade_done_at": str(_first(item, ("trade_done_at",), "")),
+ }
+
+
+def _quote_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _first(item, ("symbol",)),
+ "last": _first(item, ("last_done",)),
+ "open": _first(item, ("open",)),
+ "high": _first(item, ("high",)),
+ "low": _first(item, ("low",)),
+ "prev_close": _first(item, ("prev_close",)),
+ "volume": _first(item, ("volume",)),
+ "turnover": _first(item, ("turnover",)),
+ "time": str(_first(item, ("timestamp",), "")),
+ }
+
+
+def _bar_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "time": str(_first(item, ("timestamp",), "")),
+ "open": _first(item, ("open",)),
+ "high": _first(item, ("high",)),
+ "low": _first(item, ("low",)),
+ "close": _first(item, ("close",)),
+ "volume": _first(item, ("volume",)),
+ "turnover": _first(item, ("turnover",)),
+ }
+
+
+def _call(obj: Any, name: str, *args: Any, **kwargs: Any) -> Any:
+ fn = getattr(obj, name, None)
+ if fn is None:
+ raise LongbridgeConfigError(f"Longbridge SDK has no method '{name}'")
+ return fn(*args, **kwargs)
+
+
+def _safe_call(obj: Any, name: str, *args: Any) -> Any:
+ fn = getattr(obj, name, None)
+ if fn is None:
+ return None
+ try:
+ return fn(*args)
+ except Exception: # noqa: BLE001 - optional read, degrade quietly
+ return None
diff --git a/agent/src/trading/connectors/okx/__init__.py b/agent/src/trading/connectors/okx/__init__.py
new file mode 100644
index 000000000..33f906265
--- /dev/null
+++ b/agent/src/trading/connectors/okx/__init__.py
@@ -0,0 +1,15 @@
+"""OKX trading connector.
+
+Read-only account/market access in Layer A via the optional ``python-okx`` SDK
+(``AccountAPI`` + ``TradeAPI`` + ``MarketAPI`` over REST). A ``broker_sdk``
+transport. Order placement (paper and mandate-gated live) is layered on top in
+later phases; no place/cancel method is exposed here.
+
+Paper-vs-live separation is namespace + header based: OKX demo (paper) keys live
+in a separate key namespace and the ``x-simulated-trading`` header (driven by the
+SDK ``flag`` argument — ``"1"`` demo, ``"0"`` live) selects the environment. OKX
+returns NO response field echoing demo/live, so there is no hard self-verifying
+guard; the discriminator is the configured ``flag`` plus best-effort UID pinning
+(``expected_uid``). The selected profile (and thus the flag) is recorded as
+``paper`` on every payload and never flipped implicitly.
+"""
diff --git a/agent/src/trading/connectors/okx/classification.py b/agent/src/trading/connectors/okx/classification.py
new file mode 100644
index 000000000..909007310
--- /dev/null
+++ b/agent/src/trading/connectors/okx/classification.py
@@ -0,0 +1,29 @@
+"""Curated read/write classification for OKX SDK operations.
+
+The trading layer classifies each connector operation as READ or WRITE so the
+live gate can keep writes behind the mandate. OKX is a direct-SDK connector (not
+MCP), so the keys here are the OKX SDK method names rather than remote MCP tool
+names. Anything not listed and not a known read resolves to WRITE (fail-closed)
+when the live gate consults this map.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: OKX SDK operation read/write catalog. Read operations mirror the connector's
+#: public read functions; write operations are the order-mutating SDK calls,
+#: pinned WRITE so the live gate never treats them as plain reads.
+OKX_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "get_account_balance": ToolClass.READ,
+ "get_positions": ToolClass.READ,
+ "get_order_list": ToolClass.READ,
+ "get_fills": ToolClass.READ,
+ "get_ticker": ToolClass.READ,
+ "get_candlesticks": ToolClass.READ,
+ # WRITE
+ "place_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+ "amend_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/okx/profiles.py b/agent/src/trading/connectors/okx/profiles.py
new file mode 100644
index 000000000..8e3485027
--- /dev/null
+++ b/agent/src/trading/connectors/okx/profiles.py
@@ -0,0 +1,70 @@
+"""Built-in OKX connector profiles.
+
+Layer A ships read-only paper (demo) and live profiles. OKX demo keys live in a
+separate key namespace from live keys and select the environment via the SDK
+``flag`` (``"1"`` demo, ``"0"`` live), so they are distinct profiles. The
+order-placing profiles (``okx-paper-trade`` / ``okx-live-trade``) add the
+``orders.place`` capability; the live one is gated behind a mandate.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+OKX_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="okx-paper-sdk",
+ connector="okx",
+ label="OKX Demo · python-okx",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads an OKX demo (paper) account via python-okx with the simulated-"
+ "trading flag set. Demo keys are a separate namespace and cannot reach "
+ "the live environment."
+ ),
+ ),
+ TradingProfile(
+ id="okx-live-sdk-readonly",
+ connector="okx",
+ label="OKX Live · python-okx Read-Only",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes="Reads an OKX live account only. Order placement is not exposed in this profile.",
+ ),
+ TradingProfile(
+ id="okx-paper-trade",
+ connector="okx",
+ label="OKX Demo · python-okx Trading",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper"},
+ notes=(
+ "Places orders on an OKX demo (paper) account via python-okx with the "
+ "simulated-trading flag set. Demo keys are a separate namespace and "
+ "cannot reach the live environment."
+ ),
+ ),
+ TradingProfile(
+ id="okx-live-trade",
+ connector="okx",
+ label="OKX Live · python-okx Trading",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place.requires_mandate",),
+ readonly=False,
+ config={"profile": "live"},
+ notes=(
+ "Places orders on an OKX live account via python-okx. Live order "
+ "placement is gated behind a user-defined mandate and kill switch."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/okx/sdk.py b/agent/src/trading/connectors/okx/sdk.py
new file mode 100644
index 000000000..89350b52b
--- /dev/null
+++ b/agent/src/trading/connectors/okx/sdk.py
@@ -0,0 +1,781 @@
+"""Read-only OKX connector via the optional ``python-okx`` SDK.
+
+Wraps ``AccountAPI`` (account/positions), ``TradeAPI`` (orders/fills) and
+``MarketAPI`` (quote/candles) for the five read operations. No order-placement
+method is exposed here.
+
+Paper-vs-live is selected by the SDK ``flag`` (``"1"`` demo/paper sets the
+``x-simulated-trading`` header, ``"0"`` live) and reinforced by OKX's separate
+demo key namespace. OKX returns NO field echoing demo/live, so there is no hard
+self-verifying guard: the discriminator is the configured flag plus best-effort
+UID pinning. When ``expected_uid`` is set, :func:`check_status` calls the account
+config endpoint and asserts the returned ``uid`` matches, reporting any mismatch
+as an error. The guard marker recorded on every payload is
+``header_flag+uid_pin``. The selected profile is recorded as ``paper`` on every
+payload and never flipped implicitly.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "okx.json"
+
+#: Profiles this connector understands and their default account environment.
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+DEFAULT_HOST = "https://www.okx.com"
+
+#: SDK ``flag`` per environment: ``"1"`` demo/paper, ``"0"`` live.
+_ENVIRONMENT_FLAGS = {"paper": "1", "live": "0"}
+
+
+class OKXDependencyError(RuntimeError):
+ """Raised when the optional ``python-okx`` package is not installed."""
+
+
+class OKXConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+@dataclass(frozen=True)
+class OKXConfig:
+ """OKX connector connection settings.
+
+ Args:
+ api_key: OKX API key (demo and live use different keys).
+ api_secret: OKX API secret key.
+ passphrase: OKX API passphrase set at key creation.
+ profile: ``paper``, ``live-readonly`` or ``live``.
+ host: REST host (default ``https://www.okx.com``).
+ expected_uid: Optional account UID to pin in ``check_status``.
+ timeout: Network timeout in seconds.
+ readonly: Always true for this layer; order methods are not exposed.
+ """
+
+ api_key: str = ""
+ api_secret: str = ""
+ passphrase: str = ""
+ profile: str = "paper"
+ host: str = DEFAULT_HOST
+ expected_uid: str = ""
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "OKXConfig":
+ """Build a config from a JSON-like mapping, normalizing the profile."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise OKXConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ api_key=str(payload.get("api_key") or "").strip(),
+ api_secret=str(payload.get("api_secret") or "").strip(),
+ passphrase=str(payload.get("passphrase") or "").strip(),
+ profile=profile,
+ host=str(payload.get("host") or DEFAULT_HOST).strip(),
+ expected_uid=str(payload.get("expected_uid") or "").strip(),
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ api_key: str | None = None,
+ api_secret: str | None = None,
+ passphrase: str | None = None,
+ profile: str | None = None,
+ host: str | None = None,
+ expected_uid: str | None = None,
+ ) -> "OKXConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if api_key is not None:
+ payload["api_key"] = api_key
+ if api_secret is not None:
+ payload["api_secret"] = api_secret
+ if passphrase is not None:
+ payload["passphrase"] = passphrase
+ if profile is not None:
+ payload["profile"] = profile
+ if host is not None:
+ payload["host"] = host
+ if expected_uid is not None:
+ payload["expected_uid"] = expected_uid
+ return OKXConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+ @property
+ def flag(self) -> str:
+ """Return the OKX SDK flag (``"1"`` demo/paper, ``"0"`` live)."""
+ return _ENVIRONMENT_FLAGS.get(self.environment, "1")
+
+ @property
+ def is_demo(self) -> bool:
+ """Return whether this profile targets the OKX demo (paper) environment."""
+ return self.flag == "1"
+
+
+_OVERRIDE_KEYS = ("api_key", "api_secret", "passphrase", "profile", "host", "expected_uid")
+
+
+def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "OKXConfig":
+ """Resolve config: saved file ← profile defaults ← CLI overrides."""
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = OKXConfig.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def config_path() -> Path:
+ """Return the user-level OKX config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> OKXConfig:
+ """Load OKX settings from ``~/.vibe-trading/okx.json``."""
+ path = config_path()
+ if not path.exists():
+ return OKXConfig()
+ try:
+ return OKXConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise OKXConfigError(f"invalid OKX config at {path}: {exc}") from exc
+
+
+def save_config(config: OKXConfig) -> Path:
+ """Persist OKX settings with owner-only permissions."""
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def okx_available() -> bool:
+ """Return whether the optional ``python-okx`` SDK can be imported."""
+ try:
+ _require_okx()
+ return True
+ except OKXDependencyError:
+ return False
+
+
+def check_status(config: OKXConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness, config completeness, and account identity.
+
+ Returns a JSON-serializable health report. Does not place or mutate any
+ broker state. When ``expected_uid`` is set, the account config endpoint is
+ queried (best effort) and a UID mismatch is reported as an error.
+ """
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "python-okx", "installed": okx_available()},
+ "paper_guard": "header_flag+uid_pin",
+ "flag": cfg.flag,
+ }
+
+ if cfg.flag not in ("0", "1"):
+ report["status"] = "error"
+ report["error"] = f"invalid OKX flag {cfg.flag!r}; expected '0' (live) or '1' (demo)."
+ return report
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"OKX connector not configured: missing {', '.join(missing)}."
+ return report
+
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install python-okx`."
+ return report
+
+ try:
+ snapshot = get_account_snapshot(cfg)
+ except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ uid = None
+ if cfg.expected_uid:
+ try:
+ account = _account_client(cfg)
+ resp = _safe_call(account, "get_account_config")
+ rows = _extract_data(resp)
+ uid = _first(rows[0], ("uid",)) if rows else None
+ if uid is not None and str(uid) != cfg.expected_uid:
+ report["status"] = "error"
+ report["error"] = f"UID mismatch: expected {cfg.expected_uid}, broker returned {uid}."
+ return report
+ except Exception as exc: # noqa: BLE001 - uid pinning is best effort
+ report["uid_check"] = {"ok": False, "error": str(exc)}
+
+ report["account"] = {
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "uid": str(uid) if uid is not None else None,
+ "total_equity": snapshot.get("account", {}).get("total_equity"),
+ }
+ return report
+
+
+def get_account_snapshot(config: OKXConfig | None = None) -> dict[str, Any]:
+ """Fetch account balance for the configured account."""
+ cfg = config or load_config()
+ account = _account_client(cfg)
+ resp = _safe_call(account, "get_account_balance")
+ rows = _extract_data(resp)
+ summary = rows[0] if rows else {}
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": "header_flag+uid_pin",
+ "account": {
+ "total_equity": _first(summary, ("totalEq",)),
+ "details": [_balance_detail_to_dict(item) for item in _as_iter(_obj_get(summary, "details"))],
+ },
+ }
+
+
+def get_positions(config: OKXConfig | None = None) -> dict[str, Any]:
+ """Fetch current positions for the configured account."""
+ cfg = config or load_config()
+ account = _account_client(cfg)
+ resp = _safe_call(account, "get_positions")
+ rows = [_position_to_dict(item) for item in _extract_data(resp)]
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": "header_flag+uid_pin",
+ "positions": rows,
+ }
+
+
+def get_open_orders(config: OKXConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:
+ """Fetch open orders and, optionally, recent fills."""
+ cfg = config or load_config()
+ trade = _trade_client(cfg)
+ resp = _safe_call(trade, "get_order_list")
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": "header_flag+uid_pin",
+ "open_orders": [_order_to_dict(item) for item in _extract_data(resp)],
+ }
+ if include_executions:
+ fills = _safe_call(trade, "get_fills")
+ result["executions"] = [_fill_to_dict(item) for item in _extract_data(fills)]
+ return result
+
+
+def get_quote(symbol: str, *, config: OKXConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch a top-of-book ticker snapshot for ``symbol``."""
+ cfg = config or load_config()
+ market = _market_client(cfg)
+ clean = symbol.strip().upper()
+ resp = _safe_call(market, "get_ticker", instId=clean)
+ rows = _extract_data(resp)
+ payload = _quote_to_dict(rows[0]) if rows else {}
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": "header_flag+uid_pin",
+ "symbol": clean,
+ "quote": payload,
+ }
+
+
+#: Canonical period token → OKX ``bar`` parameter.
+_BAR_MAP = {
+ "1m": "1m", "5m": "5m", "15m": "15m", "30m": "30m",
+ "1h": "1H", "4h": "4H", "1d": "1D", "1w": "1W", "1M": "1M",
+}
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: OKXConfig | None = None,
+ period: str = "1d",
+ limit: int = 90,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV candlesticks for ``symbol`` (``period`` canonical)."""
+ cfg = config or load_config()
+ market = _market_client(cfg)
+ clean = symbol.strip().upper()
+ bar = _BAR_MAP.get(period.strip(), "1D")
+ resp = _safe_call(market, "get_candlesticks", instId=clean, bar=bar, limit=str(int(limit)))
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": "header_flag+uid_pin",
+ "symbol": clean,
+ "period": period,
+ "bar": bar,
+ "bars": [_candle_to_dict(item) for item in _extract_data(resp)],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Order placement
+# ---------------------------------------------------------------------------
+
+
+def place_order(
+ config: OKXConfig | None = None,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | str | None = None,
+ notional: float | str | None = None,
+ order_type: str = "market",
+ limit_price: float | str | None = None,
+ time_in_force: str = "day",
+) -> dict[str, Any]:
+ """Place a spot order on the configured OKX account.
+
+ The demo-vs-live target is selected entirely by the configured profile flag
+ (``"1"`` demo, ``"0"`` live); this connector merely executes against whatever
+ environment the flag selects.
+
+ Args:
+ config: Resolved connector config; loaded from disk when ``None``.
+ symbol: Instrument id, e.g. ``"BTC-USDT"`` (uppercased before sending).
+ side: ``"buy"`` or ``"sell"``.
+ quantity: Base-currency size. Exactly one of ``quantity``/``notional``.
+ notional: Quote-currency amount (market orders only). Exactly one of
+ ``quantity``/``notional``.
+ order_type: ``"market"`` or ``"limit"``. Limit orders require
+ ``limit_price`` and must be sized with ``quantity``.
+ limit_price: Limit price (required and only used for limit orders).
+ time_in_force: Accepted for interface symmetry; OKX spot ``cash`` orders
+ do not take a standalone TIF field, so this is recorded but not sent.
+
+ Returns:
+ On success ``{"status": "ok", "order_id", "symbol", "side", "profile",
+ ...}``. On any validation or broker error a fail-closed
+ ``{"status": "error", "error": ...}`` payload (no order is sent unless
+ every precondition passes).
+ """
+ cfg = config or load_config()
+
+ clean_side = str(side or "").strip().lower()
+ if clean_side not in ("buy", "sell"):
+ return _order_error(cfg, "side must be 'buy' or 'sell'", symbol=symbol, side=side)
+
+ clean_type = str(order_type or "").strip().lower()
+ if clean_type not in ("market", "limit"):
+ return _order_error(cfg, "order_type must be 'market' or 'limit'", symbol=symbol, side=clean_side)
+
+ clean_symbol = str(symbol or "").strip().upper()
+ if not clean_symbol:
+ return _order_error(cfg, "symbol is required", symbol=symbol, side=clean_side)
+
+ has_qty = quantity is not None
+ has_notional = notional is not None
+ if has_qty == has_notional:
+ return _order_error(
+ cfg, "exactly one of quantity or notional is required", symbol=clean_symbol, side=clean_side
+ )
+
+ # Limit orders are priced and always sized in base currency.
+ if clean_type == "limit":
+ if limit_price is None:
+ return _order_error(cfg, "limit order requires limit_price", symbol=clean_symbol, side=clean_side)
+ if not has_qty:
+ return _order_error(
+ cfg, "limit order must be sized with quantity (base size)", symbol=clean_symbol, side=clean_side
+ )
+
+ missing = _missing_fields(cfg)
+ if missing:
+ return _order_error(
+ cfg, f"OKX connector not configured: missing {', '.join(missing)}.", symbol=clean_symbol, side=clean_side
+ )
+
+ # Build the OKX request. Spot trading uses tdMode="cash".
+ params: dict[str, Any] = {
+ "instId": clean_symbol,
+ "tdMode": "cash",
+ "side": clean_side,
+ "ordType": clean_type,
+ }
+ if has_qty:
+ params["sz"] = str(quantity)
+ else:
+ # Market order sized by quote-currency notional: OKX expects the quote
+ # amount in ``sz`` plus ``tgtCcy="quote_ccy"`` so it is not mistaken for
+ # a base-currency size. (notional is only reachable for market orders
+ # here: limit orders reject above unless quantity is supplied.)
+ params["sz"] = str(notional)
+ params["tgtCcy"] = "quote_ccy"
+ if clean_type == "limit":
+ params["px"] = str(limit_price)
+
+ try:
+ trade = _trade_client(cfg)
+ # Call the SDK directly (NOT via _safe_call): a write must fail closed on
+ # any signature drift, never silently re-invoke with stripped arguments.
+ resp = trade.place_order(**params)
+ except OKXDependencyError as exc:
+ return _order_error(cfg, str(exc), symbol=clean_symbol, side=clean_side)
+ except Exception as exc: # noqa: BLE001 - broker/network failures fail closed
+ return _order_error(cfg, str(exc), symbol=clean_symbol, side=clean_side)
+
+ return _order_result(
+ cfg,
+ resp,
+ symbol=clean_symbol,
+ side=clean_side,
+ order_type=clean_type,
+ time_in_force=str(time_in_force or "").strip().lower(),
+ )
+
+
+def cancel_order(
+ config: OKXConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel a resting order on the configured OKX account.
+
+ Args:
+ config: Resolved connector config; loaded from disk when ``None``.
+ order_id: OKX order id (``ordId``) to cancel.
+ symbol: Instrument id of the order. OKX requires ``instId`` to cancel,
+ so this is mandatory; ``None`` fails closed.
+
+ Returns:
+ On success ``{"status": "ok", "order_id", "symbol", "profile", ...}``.
+ On any validation or broker error a fail-closed
+ ``{"status": "error", "error": ...}`` payload.
+ """
+ cfg = config or load_config()
+
+ clean_id = str(order_id or "").strip()
+ if not clean_id:
+ return _order_error(cfg, "OKX cancel requires order_id", symbol=symbol)
+
+ clean_symbol = str(symbol or "").strip().upper()
+ if not clean_symbol:
+ return _order_error(cfg, "OKX cancel requires symbol", order_id=clean_id)
+
+ missing = _missing_fields(cfg)
+ if missing:
+ return _order_error(
+ cfg, f"OKX connector not configured: missing {', '.join(missing)}.", symbol=clean_symbol, order_id=clean_id
+ )
+
+ try:
+ trade = _trade_client(cfg)
+ # Direct SDK call (not _safe_call): writes must fail closed, not retry stripped.
+ resp = trade.cancel_order(instId=clean_symbol, ordId=clean_id)
+ except OKXDependencyError as exc:
+ return _order_error(cfg, str(exc), symbol=clean_symbol, order_id=clean_id)
+ except Exception as exc: # noqa: BLE001 - broker/network failures fail closed
+ return _order_error(cfg, str(exc), symbol=clean_symbol, order_id=clean_id)
+
+ return _order_result(cfg, resp, symbol=clean_symbol, action="cancel", requested_order_id=clean_id)
+
+
+def _order_error(cfg: OKXConfig, message: str, **extra: Any) -> dict[str, Any]:
+ """Build a fail-closed error payload carrying profile/guard context."""
+ payload: dict[str, Any] = {
+ "status": "error",
+ "error": message,
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": "header_flag+uid_pin",
+ }
+ for key, value in extra.items():
+ if value is not None:
+ payload[key] = value
+ return payload
+
+
+def _order_result(cfg: OKXConfig, resp: Any, *, symbol: str, **extra: Any) -> dict[str, Any]:
+ """Interpret an OKX order/cancel response, failing closed on any non-zero code.
+
+ Success requires both the outer ``code == "0"`` and the first data row's
+ ``sCode == "0"``; otherwise the row's ``sMsg`` (or a generic message) is
+ surfaced as an error.
+ """
+ rows = _extract_data(resp)
+ if not rows:
+ message = _resp_message(resp) or "OKX returned no order data"
+ return _order_error(cfg, message, symbol=symbol, **extra)
+
+ row = rows[0]
+ s_code = str(_first(row, ("sCode",)) or "")
+ if s_code != "0":
+ message = str(_first(row, ("sMsg",)) or _resp_message(resp) or f"OKX rejected order (sCode={s_code or '?'})")
+ return _order_error(cfg, message, symbol=symbol, **extra)
+
+ order_id = str(_first(row, ("ordId",)) or "")
+ result: dict[str, Any] = {
+ "status": "ok",
+ "order_id": order_id,
+ "symbol": symbol,
+ "profile": cfg.profile,
+ "is_demo": cfg.is_demo,
+ "paper_guard": "header_flag+uid_pin",
+ "client_order_id": _first(row, ("clOrdId",)),
+ }
+ for key, value in extra.items():
+ result[key] = value
+ return result
+
+
+def _resp_message(resp: Any) -> str:
+ """Pull a top-level OKX error message (``msg``) when present."""
+ if isinstance(resp, Mapping):
+ return str(resp.get("msg") or "")
+ return ""
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _require_okx() -> ModuleType:
+ try:
+ import okx # type: ignore
+ except ModuleNotFoundError as exc:
+ raise OKXDependencyError("python-okx is not installed; run `pip install python-okx`.") from exc
+ return okx
+
+
+def _account_client(cfg: OKXConfig):
+ _require_okx()
+ from okx.Account import AccountAPI # type: ignore
+
+ return AccountAPI(cfg.api_key, cfg.api_secret, cfg.passphrase, False, cfg.flag, domain=cfg.host)
+
+
+def _trade_client(cfg: OKXConfig):
+ _require_okx()
+ from okx.Trade import TradeAPI # type: ignore
+
+ return TradeAPI(cfg.api_key, cfg.api_secret, cfg.passphrase, False, cfg.flag, domain=cfg.host)
+
+
+def _market_client(cfg: OKXConfig):
+ _require_okx()
+ from okx.MarketData import MarketAPI # type: ignore
+
+ return MarketAPI(cfg.api_key, cfg.api_secret, cfg.passphrase, False, cfg.flag, domain=cfg.host)
+
+
+def _missing_fields(cfg: OKXConfig) -> list[str]:
+ missing = []
+ if not cfg.api_key:
+ missing.append("api_key")
+ if not cfg.api_secret:
+ missing.append("api_secret")
+ if not cfg.passphrase:
+ missing.append("passphrase")
+ return missing
+
+
+def _public_config(cfg: OKXConfig) -> dict[str, Any]:
+ """Config snapshot with secrets redacted."""
+ data = asdict(cfg)
+ if data.get("api_secret"):
+ data["api_secret"] = "***redacted***"
+ if data.get("passphrase"):
+ data["passphrase"] = "***redacted***"
+ if data.get("api_key"):
+ data["api_key"] = data["api_key"][:4] + "***"
+ data["flag"] = cfg.flag
+ data["is_demo"] = cfg.is_demo
+ return data
+
+
+# ---------------------------------------------------------------------------
+# Defensive field extraction (python-okx returns ``{"code":"0","data":[...]}``)
+# ---------------------------------------------------------------------------
+
+
+def _as_iter(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
+ if obj is None:
+ return default
+ if isinstance(obj, Mapping):
+ return obj.get(name, default)
+ return getattr(obj, name, default)
+
+
+def _first(obj: Any, names: tuple[str, ...], default: Any = None) -> Any:
+ for name in names:
+ value = _obj_get(obj, name, None)
+ if value is not None:
+ return value
+ return default
+
+
+def _extract_data(resp: Any) -> list[Any]:
+ """Return the ``data`` list from an OKX response, or ``[]`` defensively.
+
+ python-okx returns a dict shaped ``{"code": "0", "data": [...]}`` on success.
+ Anything else (a non-zero code, a non-dict, a missing/non-list ``data``) is
+ treated as empty rather than raising, matching the reference connectors'
+ defensive extraction posture.
+ """
+ if isinstance(resp, Mapping):
+ if str(resp.get("code")) != "0":
+ return []
+ data = resp.get("data")
+ return list(data) if isinstance(data, (list, tuple)) else []
+ return _as_iter(resp)
+
+
+def _balance_detail_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "currency": _first(item, ("ccy",)),
+ "equity": _first(item, ("eq",)),
+ "available": _first(item, ("availBal",)),
+ "cash_balance": _first(item, ("cashBal",)),
+ "frozen": _first(item, ("frozenBal",)),
+ }
+
+
+def _position_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _first(item, ("instId",)),
+ "side": str(_first(item, ("posSide",)) or ""),
+ "quantity": _first(item, ("pos",)),
+ "average_cost": _first(item, ("avgPx",)),
+ "unrealized_pnl": _first(item, ("upl",)),
+ "margin_mode": _first(item, ("mgnMode",)),
+ "leverage": _first(item, ("lever",)),
+ }
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _first(item, ("instId",)),
+ "order_id": str(_first(item, ("ordId",)) or ""),
+ "client_order_id": _first(item, ("clOrdId",)),
+ "price": _first(item, ("px",)),
+ "quantity": _first(item, ("sz",)),
+ "order_type": _first(item, ("ordType",)),
+ "side": str(_first(item, ("side",)) or ""),
+ "status": str(_first(item, ("state",)) or ""),
+ "filled_qty": _first(item, ("fillSz",)),
+ "avg_fill_price": _first(item, ("avgPx",)),
+ "acc_filled_qty": _first(item, ("accFillSz",)),
+ }
+
+
+def _fill_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _first(item, ("instId",)),
+ "order_id": str(_first(item, ("ordId",)) or ""),
+ "trade_id": str(_first(item, ("tradeId",)) or ""),
+ "fill_price": _first(item, ("fillPx",)),
+ "fill_qty": _first(item, ("fillSz",)),
+ "side": str(_first(item, ("side",)) or ""),
+ "fee": _first(item, ("fee",)),
+ "time": str(_first(item, ("ts",)) or ""),
+ }
+
+
+def _quote_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "last": _first(item, ("last",)),
+ "ask": _first(item, ("askPx",)),
+ "ask_size": _first(item, ("askSz",)),
+ "bid": _first(item, ("bidPx",)),
+ "bid_size": _first(item, ("bidSz",)),
+ "open_24h": _first(item, ("open24h",)),
+ "high_24h": _first(item, ("high24h",)),
+ "low_24h": _first(item, ("low24h",)),
+ "volume_24h": _first(item, ("vol24h",)),
+ "time": str(_first(item, ("ts",)) or ""),
+ }
+
+
+def _candle_to_dict(item: Any) -> dict[str, Any]:
+ """Map an OKX candle array ``[ts,o,h,l,c,vol,volCcy,volCcyQuote,confirm]``.
+
+ OKX candlesticks come back as positional arrays rather than dicts, so this
+ indexes defensively and tolerates short rows.
+ """
+ row = list(item) if isinstance(item, (list, tuple)) else []
+
+ def at(idx: int) -> Any:
+ return row[idx] if idx < len(row) else None
+
+ # ``confirm`` is always the LAST element across OKX's 7- and 9-field candle
+ # shapes; read it positionally from the tail rather than a fixed index.
+ return {
+ "time": str(at(0) or ""),
+ "open": at(1),
+ "high": at(2),
+ "low": at(3),
+ "close": at(4),
+ "volume": at(5),
+ "volume_ccy": at(6),
+ "confirm": row[-1] if row else None,
+ }
+
+
+def _safe_call(obj: Any, name: str, *args: Any, **kwargs: Any) -> Any:
+ """Call ``obj.name(*args, **kwargs)`` if it exists, retrying without kwargs.
+
+ python-okx signatures vary across versions (some read methods accept extra
+ keyword filters, some do not). We try the richer call first and fall back to
+ the no-arg form so a signature drift degrades to a usable call instead of an
+ error.
+ """
+ fn = getattr(obj, name, None)
+ if fn is None:
+ return None
+ try:
+ return fn(*args, **kwargs)
+ except TypeError:
+ try:
+ return fn(*args)
+ except TypeError:
+ return fn()
diff --git a/agent/src/trading/connectors/tiger/__init__.py b/agent/src/trading/connectors/tiger/__init__.py
new file mode 100644
index 000000000..ed9c24c38
--- /dev/null
+++ b/agent/src/trading/connectors/tiger/__init__.py
@@ -0,0 +1,7 @@
+"""Tiger Brokers (TigerOpen) trading connector.
+
+Read-only account/market access in Layer A. Order placement (paper and
+mandate-gated live) is layered on top in later phases. The connector talks to
+Tiger's official ``tigeropen`` Python SDK directly (RSA-signed REST), so it is a
+``broker_sdk`` transport rather than a local socket or remote MCP server.
+"""
diff --git a/agent/src/trading/connectors/tiger/classification.py b/agent/src/trading/connectors/tiger/classification.py
new file mode 100644
index 000000000..b260ed36c
--- /dev/null
+++ b/agent/src/trading/connectors/tiger/classification.py
@@ -0,0 +1,31 @@
+"""Curated read/write classification for Tiger Brokers SDK operations.
+
+The trading layer classifies each connector operation as READ or WRITE so the
+live gate can keep writes behind the mandate. Tiger is a direct-SDK connector
+(not MCP), so the keys here are the connector's own operation names rather than
+remote MCP tool names. Anything not listed and not a known read resolves to
+WRITE (fail-closed) when the live gate consults this map.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Tiger SDK operation read/write catalog. Read operations mirror the connector's
+#: public read functions; write operations are the order-mutating SDK calls,
+#: pinned WRITE so the live gate never treats them as plain reads.
+TIGER_TOOL_CLASS: dict[str, ToolClass] = {
+ # READ
+ "get_account": ToolClass.READ,
+ "get_assets": ToolClass.READ,
+ "get_positions": ToolClass.READ,
+ "get_open_orders": ToolClass.READ,
+ "get_orders": ToolClass.READ,
+ "get_filled_orders": ToolClass.READ,
+ "get_stock_briefs": ToolClass.READ,
+ "get_bars": ToolClass.READ,
+ # WRITE
+ "place_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+ "modify_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/tiger/profiles.py b/agent/src/trading/connectors/tiger/profiles.py
new file mode 100644
index 000000000..0ff0b4187
--- /dev/null
+++ b/agent/src/trading/connectors/tiger/profiles.py
@@ -0,0 +1,74 @@
+"""Built-in Tiger Brokers connector profiles.
+
+Layer A ships read-only paper and live profiles. Layer B/C adds two
+order-placing profiles: a paper-execution profile (sandbox orders) and a
+mandate-gated live profile. Read-only profiles stay ``readonly=True``; the
+trade profiles set ``readonly=False`` and add the relevant ``orders.place``
+capability.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+TIGER_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="tiger-paper-sdk",
+ connector="tiger",
+ label="Tiger Paper · TigerOpen",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads a Tiger paper account via the official tigeropen SDK. The paper "
+ "profile fails closed unless the account number is a 17-digit Tiger "
+ "paper account."
+ ),
+ ),
+ TradingProfile(
+ id="tiger-live-sdk-readonly",
+ connector="tiger",
+ label="Tiger Live · TigerOpen Read-Only",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes="Reads a Tiger live account only. Order placement is not exposed in this profile.",
+ ),
+ TradingProfile(
+ id="tiger-paper-trade",
+ connector="tiger",
+ label="Tiger Paper · TigerOpen Trade",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper"},
+ notes=(
+ "Places orders against a Tiger paper (sandbox) account via the "
+ "official tigeropen SDK. Fails closed unless the account number is a "
+ "17-digit Tiger paper account. Paper accounts do not support GTC, so "
+ "time-in-force is forced to DAY; notional orders are unsupported "
+ "(quantity in units only)."
+ ),
+ ),
+ TradingProfile(
+ id="tiger-live-trade",
+ connector="tiger",
+ label="Tiger Live · TigerOpen Trade",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place.requires_mandate",),
+ readonly=False,
+ config={"profile": "live"},
+ notes=(
+ "Places orders against a Tiger live account. Live orders go through "
+ "the mandate gate (symbol allowlist, max order size, exposure and "
+ "leverage limits, daily trade cap) before reaching the broker; "
+ "quantity in units only, no notional path for stocks."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/tiger/sdk.py b/agent/src/trading/connectors/tiger/sdk.py
new file mode 100644
index 000000000..9d6e250d7
--- /dev/null
+++ b/agent/src/trading/connectors/tiger/sdk.py
@@ -0,0 +1,739 @@
+"""Read-only Tiger Brokers (TigerOpen) connector via the official ``tigeropen`` SDK.
+
+This module wraps Tiger's ``QuoteClient`` / ``TradeClient`` for the five read
+operations the trading layer exposes (account / positions / orders / quote /
+history). It holds no order-placement method — writes are introduced in a later
+layer behind the paper guard and, for live, the mandate gate.
+
+Auth is RSA-signed static-key (``tiger_id`` + a local PKCS#1 private key +
+account number); no OAuth, no token refresh. Credentials never leave the user's
+machine: the private key is read from a local path the operator configures.
+
+Paper-vs-live identity guard (the documented Tiger discriminator): a paper
+account number is 17 digits, all numeric (e.g. ``20191106192858300``); a
+standard/prime account is 5–10 digits; a global account starts with ``U``. The
+``paper`` profile fails closed unless the configured account matches the
+17-digit paper format, so a live account can never be driven under a paper
+profile by mistake.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "tiger.json"
+
+#: Profiles this connector understands and their default account environment.
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+#: A Tiger paper account number is exactly 17 numeric digits.
+_PAPER_ACCOUNT_RE = re.compile(r"^\d{17}$")
+
+
+class TigerDependencyError(RuntimeError):
+ """Raised when the optional ``tigeropen`` package is not installed."""
+
+
+class TigerConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+class TigerProfileMismatchError(RuntimeError):
+ """Raised when a profile's account does not match its declared environment."""
+
+
+def is_paper_account(account: str | None) -> bool:
+ """Return whether an account number is a Tiger paper account (17 digits)."""
+ return bool(account) and bool(_PAPER_ACCOUNT_RE.match(account.strip()))
+
+
+@dataclass(frozen=True)
+class TigerConfig:
+ """Tiger connector connection settings.
+
+ Args:
+ tiger_id: Developer ``tiger_id`` issued by the Tiger open platform.
+ private_key_path: Path to the local PKCS#1 RSA private key (PEM).
+ account: Tiger account number. A 17-digit number is a paper account.
+ profile: ``paper``, ``live-readonly`` or ``live``.
+ timeout: Network timeout in seconds.
+ readonly: Always true for this layer; order methods are not exposed.
+ """
+
+ tiger_id: str = ""
+ private_key_path: str = ""
+ account: str = ""
+ profile: str = "paper"
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "TigerConfig":
+ """Build a config from a JSON-like mapping, normalizing the profile."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "paper").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise TigerConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ return cls(
+ tiger_id=str(payload.get("tiger_id") or "").strip(),
+ private_key_path=str(payload.get("private_key_path") or "").strip(),
+ account=str(payload.get("account") or "").strip(),
+ profile=profile,
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ tiger_id: str | None = None,
+ private_key_path: str | None = None,
+ account: str | None = None,
+ profile: str | None = None,
+ ) -> "TigerConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if tiger_id is not None:
+ payload["tiger_id"] = tiger_id
+ if private_key_path is not None:
+ payload["private_key_path"] = private_key_path
+ if account is not None:
+ payload["account"] = account
+ if profile is not None:
+ payload["profile"] = profile
+ return TigerConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
+
+
+_OVERRIDE_KEYS = ("tiger_id", "private_key_path", "account", "profile")
+
+
+def build_config(profile_config: Mapping[str, Any] | None = None, overrides: Mapping[str, Any] | None = None) -> "TigerConfig":
+ """Resolve the effective config: saved file ← profile defaults ← CLI overrides.
+
+ Credentials (``tiger_id`` / ``private_key_path`` / ``account``) come from the
+ saved ``~/.vibe-trading/tiger.json``; the selected connector profile supplies
+ the ``profile`` intent; CLI/tool overrides win last.
+
+ Args:
+ profile_config: The connector profile's ``config`` dict.
+ overrides: Per-call overrides (only known config keys are applied).
+
+ Returns:
+ A normalized :class:`TigerConfig`.
+ """
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = TigerConfig.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
+def config_path() -> Path:
+ """Return the user-level Tiger config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> TigerConfig:
+ """Load Tiger settings from ``~/.vibe-trading/tiger.json``."""
+ path = config_path()
+ if not path.exists():
+ return TigerConfig()
+ try:
+ return TigerConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise TigerConfigError(f"invalid Tiger config at {path}: {exc}") from exc
+
+
+def save_config(config: TigerConfig) -> Path:
+ """Persist Tiger settings with owner-only permissions."""
+ path = config_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return path
+
+
+def tigeropen_available() -> bool:
+ """Return whether the optional ``tigeropen`` SDK can be imported."""
+ try:
+ _require_tigeropen()
+ return True
+ except TigerDependencyError:
+ return False
+
+
+def check_status(config: TigerConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness, config completeness, and account identity.
+
+ Returns a JSON-serializable health report. Does not place or mutate any
+ broker state.
+ """
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "tigeropen", "installed": tigeropen_available()},
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Tiger connector not configured: missing {', '.join(missing)}."
+ return report
+
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install tigeropen`."
+ return report
+
+ try:
+ _assert_profile(cfg)
+ except (TigerProfileMismatchError, TigerConfigError) as exc:
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ try:
+ snapshot = get_account_snapshot(cfg)
+ except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ report["account"] = {
+ "account": cfg.account,
+ "is_paper": is_paper_account(cfg.account),
+ "profile": cfg.profile,
+ "assets_currency": [row.get("currency") for row in snapshot.get("assets", [])],
+ }
+ return report
+
+
+def get_account_snapshot(config: TigerConfig | None = None) -> dict[str, Any]:
+ """Fetch account assets / balance for the configured account."""
+ cfg = config or load_config()
+ _assert_profile(cfg)
+ trade = _trade_client(cfg)
+ assets = _safe_call(trade, "get_assets", account=cfg.account) or _safe_call(trade, "get_assets")
+ rows = [_asset_to_dict(item) for item in _as_iter(assets)]
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "account": cfg.account,
+ "is_paper": is_paper_account(cfg.account),
+ "assets": rows,
+ }
+
+
+def get_positions(config: TigerConfig | None = None) -> dict[str, Any]:
+ """Fetch current positions for the configured account."""
+ cfg = config or load_config()
+ _assert_profile(cfg)
+ trade = _trade_client(cfg)
+ positions = _safe_call(trade, "get_positions", account=cfg.account) or _safe_call(trade, "get_positions")
+ rows = [_position_to_dict(item) for item in _as_iter(positions)]
+ return {"status": "ok", "profile": cfg.profile, "account": cfg.account, "positions": rows}
+
+
+def get_open_orders(config: TigerConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:
+ """Fetch open orders and, optionally, recently filled orders."""
+ cfg = config or load_config()
+ _assert_profile(cfg)
+ trade = _trade_client(cfg)
+ open_orders = _safe_call(trade, "get_open_orders", account=cfg.account) or _safe_call(trade, "get_open_orders")
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "account": cfg.account,
+ "open_orders": [_order_to_dict(item) for item in _as_iter(open_orders)],
+ }
+ if include_executions:
+ filled = _safe_call(trade, "get_filled_orders", account=cfg.account) or _safe_call(trade, "get_filled_orders")
+ result["executions"] = [_order_to_dict(item) for item in _as_iter(filled)]
+ return result
+
+
+def get_quote(symbol: str, *, config: TigerConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch a top-of-book quote snapshot for ``symbol``."""
+ cfg = config or load_config()
+ _assert_profile(cfg)
+ quote = _quote_client(cfg)
+ clean = symbol.strip().upper()
+ briefs = _safe_call(quote, "get_stock_briefs", [clean])
+ rows = [_quote_to_dict(item) for item in _as_iter(briefs)]
+ payload = rows[0] if rows else {}
+ return {"status": "ok", "symbol": clean, "quote": payload}
+
+
+#: Canonical period token → Tiger ``get_bars`` period string.
+_PERIOD_MAP = {
+ "1m": "1min", "5m": "5min", "15m": "15min", "30m": "30min",
+ "1h": "60min", "4h": "60min", "1d": "day", "1w": "week", "1M": "month",
+}
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: TigerConfig | None = None,
+ period: str = "1d",
+ limit: int = 90,
+ **_: Any,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV bars for ``symbol`` (``period`` is a canonical token)."""
+ cfg = config or load_config()
+ _assert_profile(cfg)
+ quote = _quote_client(cfg)
+ clean = symbol.strip().upper()
+ # Case-sensitive: ``1m`` (minute) must not collide with ``1M`` (month).
+ tiger_period = _PERIOD_MAP.get(period.strip(), "day")
+ bars = _safe_call(quote, "get_bars", [clean], period=tiger_period, limit=int(limit))
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "period": period,
+ "bars": [_bar_to_dict(item) for item in _as_iter(bars)],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Order placement (Layer B/C) — fails closed, never raises
+# ---------------------------------------------------------------------------
+
+#: Accepted ``side`` tokens → Tiger ``action`` (uppercase).
+_ACTION_MAP = {"buy": "BUY", "sell": "SELL"}
+
+#: Accepted ``time_in_force`` tokens → Tiger TIF string.
+_TIF_MAP = {"day": "DAY", "gtc": "GTC"}
+
+
+def place_order(
+ config: TigerConfig,
+ *,
+ symbol: str,
+ side: str,
+ quantity: float | None = None,
+ notional: float | None = None,
+ order_type: str = "market",
+ limit_price: float | None = None,
+ time_in_force: str = "day",
+) -> dict[str, Any]:
+ """Place a stock order against the account in ``config``.
+
+ This executes a REAL order against whatever account ``config`` points at: a
+ paper config drives the Tiger paper (sandbox) account, a live config drives
+ the live account. The connector only executes; authorization (mandate gate,
+ kill switch) is the caller's responsibility. ``_assert_profile`` runs first
+ so a live account can never be driven under a paper profile by mistake.
+
+ Args:
+ config: Resolved :class:`TigerConfig`. Its ``profile`` selects the
+ account environment (paper account = sandbox order).
+ symbol: Stock symbol, e.g. ``AAPL``.
+ side: ``buy`` or ``sell`` (case-insensitive).
+ quantity: Order size in units. Provide exactly one of ``quantity`` or
+ ``notional``.
+ notional: Notional amount. Tiger has no notional path for stocks, so a
+ notional-only request fails closed with a clear error.
+ order_type: ``market`` or ``limit`` (a ``limit`` order requires
+ ``limit_price``).
+ limit_price: Limit price; required for and only used by limit orders.
+ time_in_force: ``day`` or ``gtc``. Paper accounts do not support GTC, so
+ it is forced to DAY when ``config`` is a paper profile.
+
+ Returns:
+ ``{"status": "ok", "order_id": str, "symbol", "side", "profile", ...}``
+ on success, otherwise ``{"status": "error", "error": str}``. Never
+ raises: all failure modes are reported in the envelope.
+ """
+ # ---- input validation (fail closed before touching the SDK) ----
+ side_key = str(side or "").strip().lower()
+ action = _ACTION_MAP.get(side_key)
+ if action is None:
+ return {"status": "error", "error": "side must be 'buy' or 'sell'"}
+
+ if (quantity is None) == (notional is None):
+ return {"status": "error", "error": "provide exactly one of quantity or notional"}
+ if notional is not None:
+ return {"status": "error", "error": "Tiger requires quantity (units), not notional"}
+
+ try:
+ qty = float(quantity)
+ except (TypeError, ValueError):
+ return {"status": "error", "error": "quantity must be a number"}
+ if qty <= 0:
+ return {"status": "error", "error": "quantity must be positive"}
+
+ type_key = str(order_type or "").strip().lower()
+ if type_key not in ("market", "limit"):
+ return {"status": "error", "error": "order_type must be 'market' or 'limit'"}
+
+ px: float | None = None
+ if type_key == "limit":
+ if limit_price is None:
+ return {"status": "error", "error": "limit order requires limit_price"}
+ try:
+ px = float(limit_price)
+ except (TypeError, ValueError):
+ return {"status": "error", "error": "limit_price must be a number"}
+ if px <= 0:
+ return {"status": "error", "error": "limit_price must be positive"}
+
+ tif_key = str(time_in_force or "").strip().lower()
+ tif = _TIF_MAP.get(tif_key)
+ if tif is None:
+ return {"status": "error", "error": "time_in_force must be 'day' or 'gtc'"}
+
+ clean_symbol = str(symbol or "").strip().upper()
+ if not clean_symbol:
+ return {"status": "error", "error": "symbol is required"}
+
+ # ---- profile / environment guard ----
+ try:
+ _assert_profile(config)
+ except (TigerProfileMismatchError, TigerConfigError) as exc:
+ return {"status": "error", "error": str(exc)}
+
+ # Paper accounts do not support GTC; force DAY rather than failing the order.
+ paper = is_paper_account(config.account)
+ if paper and tif == "GTC":
+ tif = "DAY"
+
+ # ---- build + submit ----
+ try:
+ from tigeropen.common.util.contract_utils import stock_contract # type: ignore
+ from tigeropen.common.util.order_utils import limit_order, market_order # type: ignore
+ except ModuleNotFoundError as exc:
+ return {"status": "error", "error": f"tigeropen is not installed; run `pip install tigeropen` ({exc})"}
+
+ try:
+ trade = _trade_client(config)
+ contract = stock_contract(symbol=clean_symbol, currency="USD")
+ if type_key == "limit":
+ order = limit_order(
+ account=config.account,
+ contract=contract,
+ action=action,
+ quantity=qty,
+ limit_price=px,
+ time_in_force=tif,
+ )
+ else:
+ order = market_order(
+ account=config.account,
+ contract=contract,
+ action=action,
+ quantity=qty,
+ time_in_force=tif,
+ )
+ # ``place_order`` mutates ``order.id`` with the global id and returns it;
+ # read both defensively in case the SDK only does one.
+ returned = trade.place_order(order)
+ order_id = _obj_get(order, "id", None)
+ if order_id is None:
+ order_id = returned
+ except Exception as exc: # noqa: BLE001 - fail closed, never raise to caller
+ return {"status": "error", "error": str(exc)}
+
+ if order_id is None:
+ return {"status": "error", "error": "Tiger did not return an order id"}
+
+ # Best-effort rejection check: tigeropen mutates the order object with a
+ # status/reason. A rejected order can still come back with an id, so don't
+ # report success when the broker flagged it rejected.
+ order_status = str(_obj_get(order, "status", "") or "")
+ reason = _obj_get(order, "reason", None)
+ if order_status.strip().lower() in ("rejected", "inactive") or (reason and str(reason).strip()):
+ return {
+ "status": "error",
+ "error": f"Tiger rejected order: {reason or order_status}",
+ "order_id": str(order_id),
+ "symbol": clean_symbol,
+ }
+
+ return {
+ "status": "ok",
+ "order_id": str(order_id),
+ "symbol": clean_symbol,
+ "side": side_key,
+ "profile": config.profile,
+ "account": config.account,
+ "is_paper": paper,
+ "order_type": type_key,
+ "quantity": qty,
+ "limit_price": px,
+ "time_in_force": tif,
+ }
+
+
+def cancel_order(config: TigerConfig, order_id: Any, *, symbol: str | None = None) -> dict[str, Any]:
+ """Cancel a previously placed order on the account in ``config``.
+
+ Runs ``_assert_profile`` first so the cancel targets the intended account
+ environment. Like :func:`place_order`, this never raises: every failure is
+ returned in the envelope.
+
+ Args:
+ config: Resolved :class:`TigerConfig` selecting the account.
+ order_id: The global order id returned by :func:`place_order`.
+ symbol: Optional symbol, echoed back for caller convenience; Tiger
+ cancels by id and does not require it.
+
+ Returns:
+ ``{"status": "ok", "order_id": str, "profile", ...}`` on success,
+ otherwise ``{"status": "error", "error": str}``.
+ """
+ if order_id is None or str(order_id).strip() == "":
+ return {"status": "error", "error": "order_id is required"}
+
+ try:
+ _assert_profile(config)
+ except (TigerProfileMismatchError, TigerConfigError) as exc:
+ return {"status": "error", "error": str(exc)}
+
+ try:
+ oid: Any = int(order_id)
+ except (TypeError, ValueError):
+ oid = order_id
+
+ try:
+ trade = _trade_client(config)
+ # SDK accepts ``id=``; older builds use ``order_id=`` — try the canonical
+ # keyword first and fall back so a signature drift still cancels.
+ try:
+ trade.cancel_order(id=oid)
+ except TypeError:
+ trade.cancel_order(order_id=oid)
+ except Exception as exc: # noqa: BLE001 - fail closed, never raise to caller
+ return {"status": "error", "error": str(exc)}
+
+ result: dict[str, Any] = {
+ "status": "ok",
+ "order_id": str(order_id),
+ "profile": config.profile,
+ "account": config.account,
+ }
+ if symbol:
+ result["symbol"] = str(symbol).strip().upper()
+ return result
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _require_tigeropen() -> ModuleType:
+ try:
+ import tigeropen # type: ignore
+ except ModuleNotFoundError as exc:
+ raise TigerDependencyError("tigeropen is not installed; run `pip install tigeropen`.") from exc
+ return tigeropen
+
+
+def _client_config(cfg: TigerConfig):
+ """Build a ``TigerOpenClientConfig`` from connector settings."""
+ _require_tigeropen()
+ from tigeropen.common.util.signature_utils import read_private_key # type: ignore
+ from tigeropen.tiger_open_config import TigerOpenClientConfig # type: ignore
+
+ key_path = Path(cfg.private_key_path).expanduser()
+ if not key_path.exists():
+ raise TigerConfigError(f"Tiger private key not found at {key_path}")
+ client_config = TigerOpenClientConfig()
+ client_config.private_key = read_private_key(str(key_path))
+ client_config.tiger_id = cfg.tiger_id
+ client_config.account = cfg.account
+ try:
+ client_config.timeout = cfg.timeout
+ except Exception: # noqa: BLE001 - older SDKs may not expose timeout
+ pass
+ return client_config
+
+
+def _trade_client(cfg: TigerConfig):
+ _require_tigeropen()
+ from tigeropen.trade.trade_client import TradeClient # type: ignore
+
+ return TradeClient(_client_config(cfg))
+
+
+def _quote_client(cfg: TigerConfig):
+ _require_tigeropen()
+ from tigeropen.quote.quote_client import QuoteClient # type: ignore
+
+ return QuoteClient(_client_config(cfg))
+
+
+def _assert_profile(cfg: TigerConfig) -> None:
+ """Fail closed when the account does not match the declared environment."""
+ account = (cfg.account or "").strip()
+ if not account:
+ raise TigerConfigError("Tiger account number is not configured")
+ paper = is_paper_account(account)
+ if cfg.environment == "paper" and not paper:
+ raise TigerProfileMismatchError(
+ "Configured profile is paper, but the account number is not a 17-digit Tiger paper account. "
+ "Use a live profile only if you intend live-account access."
+ )
+ if cfg.environment == "live" and paper:
+ raise TigerProfileMismatchError(
+ "Configured profile is live, but the account number is a 17-digit Tiger paper account. "
+ "Select a paper profile for paper accounts."
+ )
+
+
+def _missing_fields(cfg: TigerConfig) -> list[str]:
+ missing = []
+ if not cfg.tiger_id:
+ missing.append("tiger_id")
+ if not cfg.private_key_path:
+ missing.append("private_key_path")
+ if not cfg.account:
+ missing.append("account")
+ return missing
+
+
+def _public_config(cfg: TigerConfig) -> dict[str, Any]:
+ """Config snapshot with credential material masked (key path only, never contents)."""
+ data = asdict(cfg)
+ if data.get("tiger_id"):
+ data["tiger_id"] = data["tiger_id"][:4] + "***"
+ return data
+
+
+# ---------------------------------------------------------------------------
+# Defensive field extraction (SDK returns objects or dicts depending on version)
+# ---------------------------------------------------------------------------
+
+
+def _as_iter(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
+ if obj is None:
+ return default
+ if isinstance(obj, Mapping):
+ return obj.get(name, default)
+ return getattr(obj, name, default)
+
+
+def _first(obj: Any, names: tuple[str, ...], default: Any = None) -> Any:
+ for name in names:
+ value = _obj_get(obj, name, None)
+ if value is not None:
+ return value
+ return default
+
+
+def _asset_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "currency": _first(item, ("currency",)),
+ "cash": _first(item, ("cash", "cash_balance")),
+ "net_liquidation": _first(item, ("net_liquidation", "net_liquidation_value")),
+ "buying_power": _first(item, ("buying_power",)),
+ "equity_with_loan": _first(item, ("equity_with_loan", "equity_with_loan_value")),
+ "unrealized_pnl": _first(item, ("unrealized_pnl", "unrealized_pl")),
+ }
+
+
+def _position_to_dict(item: Any) -> dict[str, Any]:
+ contract = _obj_get(item, "contract")
+ return {
+ "symbol": _first(contract, ("symbol",)) or _first(item, ("symbol",)),
+ "currency": _first(contract, ("currency",)) or _first(item, ("currency",)),
+ "sec_type": _first(contract, ("sec_type", "secType")),
+ "quantity": _first(item, ("quantity", "position_qty", "position")),
+ "average_cost": _first(item, ("average_cost", "avg_cost")),
+ "market_value": _first(item, ("market_value",)),
+ "unrealized_pnl": _first(item, ("unrealized_pnl", "unrealized_pl")),
+ }
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ contract = _obj_get(item, "contract")
+ return {
+ "order_id": _first(item, ("id", "order_id")),
+ "symbol": _first(contract, ("symbol",)) or _first(item, ("symbol",)),
+ "action": _first(item, ("action",)),
+ "order_type": _first(item, ("order_type", "type")),
+ "quantity": _first(item, ("quantity",)),
+ "filled": _first(item, ("filled",)),
+ "remaining": _first(item, ("remaining",)),
+ "avg_fill_price": _first(item, ("avg_fill_price",)),
+ "limit_price": _first(item, ("limit_price",)),
+ "status": str(_first(item, ("status",)) or ""),
+ "currency": _first(contract, ("currency",)),
+ }
+
+
+def _quote_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _first(item, ("symbol",)),
+ "last": _first(item, ("latest_price", "last_price", "latest")),
+ "bid": _first(item, ("bid_price", "bid")),
+ "ask": _first(item, ("ask_price", "ask")),
+ "open": _first(item, ("open",)),
+ "high": _first(item, ("high",)),
+ "low": _first(item, ("low",)),
+ "prev_close": _first(item, ("pre_close", "prev_close")),
+ "volume": _first(item, ("volume",)),
+ "time": str(_first(item, ("latest_time", "time"), "")),
+ }
+
+
+def _bar_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "time": str(_first(item, ("time", "date"), "")),
+ "open": _first(item, ("open",)),
+ "high": _first(item, ("high",)),
+ "low": _first(item, ("low",)),
+ "close": _first(item, ("close",)),
+ "volume": _first(item, ("volume",)),
+ }
+
+
+def _safe_call(obj: Any, name: str, *args: Any, **kwargs: Any) -> Any:
+ """Call ``obj.name(*args, **kwargs)`` if it exists, retrying without kwargs.
+
+ Tiger SDK signatures vary across versions (some read methods take an
+ ``account`` kwarg, some bind it from the client config). We try the richer
+ call first and fall back to the no-arg form so a signature drift degrades to
+ a usable call instead of an error.
+ """
+ fn = getattr(obj, name, None)
+ if fn is None:
+ return None
+ try:
+ return fn(*args, **kwargs)
+ except TypeError:
+ try:
+ return fn(*args)
+ except TypeError:
+ return fn()
diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.py
index 2fd98141d..bbc3c3508 100644
--- a/agent/src/trading/profiles.py
+++ b/agent/src/trading/profiles.py
@@ -6,8 +6,14 @@ import json
from pathlib import Path
from src.config.paths import get_runtime_root
+from src.trading.connectors.alpaca.profiles import ALPACA_PROFILES
+from src.trading.connectors.binance.profiles import BINANCE_PROFILES
+from src.trading.connectors.futu.profiles import FUTU_PROFILES
from src.trading.connectors.ibkr.profiles import IBKR_PROFILES
+from src.trading.connectors.longbridge.profiles import LONGBRIDGE_PROFILES
+from src.trading.connectors.okx.profiles import OKX_PROFILES
from src.trading.connectors.robinhood.profiles import ROBINHOOD_PROFILES
+from src.trading.connectors.tiger.profiles import TIGER_PROFILES
from src.trading.types import TradingProfile
CONFIG_FILENAME = "trading-connections.json"
@@ -16,6 +22,12 @@ DEFAULT_PROFILE_ID = "ibkr-paper-local"
BUILTIN_PROFILES: tuple[TradingProfile, ...] = (
*IBKR_PROFILES,
*ROBINHOOD_PROFILES,
+ *TIGER_PROFILES,
+ *LONGBRIDGE_PROFILES,
+ *ALPACA_PROFILES,
+ *OKX_PROFILES,
+ *BINANCE_PROFILES,
+ *FUTU_PROFILES,
)
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index a1430bb80..90c7f9907 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -9,6 +9,29 @@ from src.trading.types import TradingProfile
RUNNER_CAPABILITY = "runner.manage.requires_mandate"
+#: Direct-SDK connectors (``broker_sdk`` transport) → their connector module.
+#: Each module exposes a uniform read interface (``build_config``, ``check_status``,
+#: ``get_account_snapshot``, ``get_positions``, ``get_open_orders``, ``get_quote``,
+#: ``get_historical_bars``).
+_SDK_CONNECTOR_MODULES = {
+ "tiger": "src.trading.connectors.tiger.sdk",
+ "longbridge": "src.trading.connectors.longbridge.sdk",
+ "alpaca": "src.trading.connectors.alpaca.sdk",
+ "okx": "src.trading.connectors.okx.sdk",
+ "binance": "src.trading.connectors.binance.sdk",
+ "futu": "src.trading.connectors.futu.sdk",
+}
+
+
+def _sdk_module(connector: str):
+ """Import the SDK connector module for a ``broker_sdk`` connector key."""
+ import importlib
+
+ path = _SDK_CONNECTOR_MODULES.get(connector)
+ if path is None:
+ raise ValueError(f"no SDK connector module for '{connector}'")
+ return importlib.import_module(path)
+
def check_connection(profile_id: str | None = None, **overrides: Any) -> dict[str, Any]:
"""Check a connector profile without mutating broker state."""
@@ -24,6 +47,15 @@ def check_connection(profile_id: str | None = None, **overrides: Any) -> dict[st
report["transport"] = profile.transport
return report
+ if profile.transport == "broker_sdk":
+ module = _sdk_module(profile.connector)
+ report = module.check_status(module.build_config(profile.config, overrides))
+ report["profile_id"] = profile.id
+ report["connector"] = profile.connector
+ report["environment"] = profile.environment
+ report["transport"] = profile.transport
+ return report
+
return _remote_status(profile)
@@ -34,6 +66,9 @@ def get_account(profile_id: str | None = None, **overrides: Any) -> dict[str, An
from src.trading.connectors.ibkr.local import get_account_snapshot
return _with_profile(profile, get_account_snapshot(_ibkr_config(profile, overrides)))
+ if profile.transport == "broker_sdk":
+ module = _sdk_module(profile.connector)
+ return _with_profile(profile, module.get_account_snapshot(module.build_config(profile.config, overrides)))
return _call_remote(profile, "account", {})
@@ -44,6 +79,9 @@ def get_positions(profile_id: str | None = None, **overrides: Any) -> dict[str,
from src.trading.connectors.ibkr.local import get_positions as _get_positions
return _with_profile(profile, _get_positions(_ibkr_config(profile, overrides)))
+ if profile.transport == "broker_sdk":
+ module = _sdk_module(profile.connector)
+ return _with_profile(profile, module.get_positions(module.build_config(profile.config, overrides)))
return _call_remote(profile, "positions", {})
@@ -62,6 +100,12 @@ def get_open_orders(
profile,
_get_open_orders(_ibkr_config(profile, overrides), include_executions=include_executions),
)
+ if profile.transport == "broker_sdk":
+ module = _sdk_module(profile.connector)
+ return _with_profile(
+ profile,
+ module.get_open_orders(module.build_config(profile.config, overrides), include_executions=include_executions),
+ )
return _call_remote(profile, "orders", {})
@@ -89,6 +133,9 @@ def get_quote(
sec_type=sec_type,
),
)
+ if profile.transport == "broker_sdk":
+ module = _sdk_module(profile.connector)
+ return _with_profile(profile, module.get_quote(symbol, config=module.build_config(profile.config, overrides)))
return _call_remote(profile, "quote", {"symbols": [symbol], "symbol": symbol})
@@ -103,9 +150,17 @@ def get_history(
bar_size: str = "1 day",
what_to_show: str = "TRADES",
use_rth: bool = True,
+ period: str = "1d",
+ limit: int = 90,
**overrides: Any,
) -> dict[str, Any]:
- """Read historical bars for a connector profile."""
+ """Read historical bars for a connector profile.
+
+ ``duration``/``bar_size``/``what_to_show``/``use_rth`` are the IBKR
+ (``local_tws``) vocabulary. ``period`` (e.g. ``1m``/``5m``/``1h``/``1d``)
+ and ``limit`` are the generic vocabulary every ``broker_sdk`` connector
+ understands and maps to its own SDK tokens.
+ """
profile = profile_by_id(profile_id)
if profile.transport == "local_tws":
from src.trading.connectors.ibkr.local import get_historical_bars
@@ -124,9 +179,177 @@ def get_history(
use_rth=use_rth,
),
)
+ if profile.transport == "broker_sdk":
+ module = _sdk_module(profile.connector)
+ return _with_profile(
+ profile,
+ module.get_historical_bars(
+ symbol,
+ config=module.build_config(profile.config, overrides),
+ period=period,
+ limit=limit,
+ ),
+ )
return _unsupported(profile, "history.read")
+#: Connector → (instrument type, fixed asset class | None). ``None`` asset class
+#: means "infer from the symbol's market" (multi-market equity connectors).
+_CONNECTOR_INSTRUMENT = {
+ "okx": ("crypto", "crypto"),
+ "binance": ("crypto", "crypto"),
+ "alpaca": ("equity", "us_equity"),
+ "tiger": ("equity", None),
+ "longbridge": ("equity", None),
+ "futu": ("equity", None),
+}
+
+
+def _order_classification(connector: str, symbol: str):
+ """Return ``(InstrumentType, AssetClass | None)`` for an order's mandate gate.
+
+ Crypto connectors are unambiguous; multi-market equity connectors infer the
+ asset class from the symbol's market tag (``.HK``/``HK.`` → HK, ``.US``/``US.``
+ → US, ``.SH``/``.SZ``/``CN.`` → A-share). When the market cannot be inferred
+ the asset class is ``None`` and the gate falls back to the US default — which
+ only ever DENIES (never silently widens) when the user's mandate permits a
+ non-US class, so the unknown case is fail-safe.
+ """
+ from src.live.mandate.model import AssetClass, InstrumentType
+
+ instrument_name, asset_name = _CONNECTOR_INSTRUMENT.get(connector, ("equity", None))
+ instrument = InstrumentType(instrument_name)
+ if asset_name is not None:
+ return instrument, AssetClass(asset_name)
+
+ token = (symbol or "").strip().upper()
+ if token.startswith("HK.") or token.endswith(".HK"):
+ return instrument, AssetClass.HK_EQUITY
+ if token.startswith("US.") or token.endswith(".US"):
+ return instrument, AssetClass.US_EQUITY
+ if token.startswith(("CN.", "SH.", "SZ.")) or token.endswith((".SH", ".SS", ".SZ")):
+ return instrument, AssetClass.CN_EQUITY
+ return instrument, None
+
+
+def place_order(
+ symbol: str,
+ profile_id: str | None = None,
+ *,
+ side: str,
+ quantity: float | None = None,
+ notional: float | None = None,
+ order_type: str = "market",
+ limit_price: float | None = None,
+ time_in_force: str = "day",
+ session_id: str = "",
+ **overrides: Any,
+) -> dict[str, Any]:
+ """Place an order via a connector profile.
+
+ Paper profiles place directly against the broker's sandbox account. Live
+ profiles route through the direct-SDK mandate gate (mandate + kill switch +
+ fail-closed pre-trade checks + audit) before any order reaches the broker.
+ Only ``broker_sdk`` connectors are supported here; Robinhood keeps its MCP
+ gate and IBKR stays read-only.
+ """
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "orders.place")
+
+ module = _sdk_module(profile.connector)
+ config = module.build_config(profile.config, overrides)
+ place_kwargs = {
+ "symbol": symbol,
+ "side": side,
+ "quantity": quantity,
+ "notional": notional,
+ "order_type": order_type,
+ "limit_price": limit_price,
+ "time_in_force": time_in_force,
+ }
+
+ if profile.environment == "paper":
+ return _with_profile(profile, module.place_order(config, **place_kwargs))
+
+ # Live: pre-trade mandate gate.
+ from src.live.enforcement import OrderIntent
+ from src.live.sdk_order_gate import execute_live_order
+
+ instrument_type, asset_class = _order_classification(profile.connector, symbol)
+ intent = OrderIntent(
+ symbol=str(symbol or "").strip().upper(),
+ side=str(side or "").strip().lower(),
+ notional_usd=float(notional) if notional is not None else None,
+ quantity=float(quantity) if quantity is not None else None,
+ instrument_type=instrument_type,
+ asset_class=asset_class,
+ )
+ result = execute_live_order(
+ broker=profile.connector,
+ connector_module=module,
+ config=config,
+ intent=intent,
+ place_kwargs=place_kwargs,
+ session_id=session_id,
+ )
+ return _with_profile(profile, result)
+
+
+def cancel_order(
+ order_id: str,
+ profile_id: str | None = None,
+ *,
+ symbol: str | None = None,
+ session_id: str = "",
+ **overrides: Any,
+) -> dict[str, Any]:
+ """Cancel an order via a connector profile.
+
+ Cancelling is risk-reducing, so it is not blocked by the mandate or the kill
+ switch (a halt should still let the user cancel resting orders). But a live
+ cancel IS a live action, so it is written to the audit ledger — every live
+ action must be logged (Red Lines).
+ """
+ profile = profile_by_id(profile_id)
+ if profile.transport != "broker_sdk":
+ return _unsupported(profile, "orders.cancel")
+ module = _sdk_module(profile.connector)
+ config = module.build_config(profile.config, overrides)
+ result = module.cancel_order(config, order_id, symbol=symbol)
+ if profile.environment == "live":
+ _audit_live_cancel(profile, order_id, symbol, result, session_id)
+ return _with_profile(profile, result)
+
+
+def _audit_live_cancel(profile, order_id, symbol, result, session_id) -> None:
+ """Write a live-action audit record for a live order cancellation (best-effort)."""
+ try:
+ from src.live.audit import LiveActionEvent, write_live_action
+
+ ok = isinstance(result, dict) and str(result.get("status", "")).lower() == "ok"
+ event = LiveActionEvent(
+ kind="order_cancelled",
+ session_id=session_id,
+ outcome="accepted" if ok else "error",
+ server=profile.connector,
+ remote_tool="cancel_order",
+ intent_normalized=f"cancel {order_id} {symbol or ''}".strip(),
+ mandate_snapshot_ref=None,
+ consent_record_ref=None,
+ broker_request={"order_id": order_id, "symbol": symbol},
+ broker_response=result if isinstance(result, dict) else {"raw": result},
+ gate_decision={"allowed": True, "decision": "cancel"},
+ error=None if ok else (result.get("error") if isinstance(result, dict) else "cancel failed"),
+ )
+ try:
+ write_live_action(event, event_callback=None, trace_writer=None)
+ except TypeError:
+ write_live_action(event)
+ except Exception: # noqa: BLE001 - auditing must never block a cancel
+ pass
+
+
def profile_supports_live_runner(profile: TradingProfile) -> bool:
"""Return whether a profile can run the managed live runner."""
return (
diff --git a/agent/src/trading/types.py b/agent/src/trading/types.py
index dd0219767..d9c57db94 100644
--- a/agent/src/trading/types.py
+++ b/agent/src/trading/types.py
@@ -6,7 +6,7 @@ from dataclasses import asdict, dataclass, field
from typing import Any, Literal
Environment = Literal["paper", "live"]
-Transport = Literal["local_tws", "remote_mcp"]
+Transport = Literal["local_tws", "remote_mcp", "broker_sdk"]
READ_CAPABILITIES = (
"account.read",