IBKR 技能
概述
此技能透過 ib_insync 與 Interactive Brokers Trader Workstation (TWS) 和 IB Gateway 整合,透過以下方式公開可操作的 IBKR 工作流程:
- 統一的 Python CLI:
scripts/ibkr_cli.py - Bash CLI 包裝腳本:
scripts/ibkr.sh - 相容性別名:
scripts/openclaw.sh - 向後相容的腳本進入點:
scripts/get_account_info.pyscripts/get_historical_data.pyscripts/place_order.py
先決條件
- 已啟用 API 權限的 Interactive Brokers 帳戶。
- 執行中的 TWS 或 IB Gateway,且已啟用 API。
- 建議使用 Python 3.9+。
- 已安裝
ib_insync:
pip install ib_insync
連線配置
所有 CLI 均支援透過標誌或環境變數覆寫連線設定。
環境變數:
IBKR_HOST(預設127.0.0.1)IBKR_PORT(預設7497)IBKR_CLIENT_ID(預設1)IBKR_ACCOUNT(可選)
範例:
IBKR_PORT=4002 IBKR_CLIENT_ID=14 ./scripts/ibkr.sh account-summary
python3 scripts/ibkr_cli.py positions --host 127.0.0.1 --port 7496 --account DU123456
Bash CLI
./scripts/ibkr.sh <command> [args]
支援的命令:
account(帳戶摘要 + 持倉)account-summarypositionsportfoliopnlquotehistoricalplace-ordercancel-orderopen-ordersexecutionscontract-detailsscanner
./scripts/openclaw.sh 是同一個 CLI 介面的別名。
Python CLI
python3 scripts/ibkr_cli.py <command> [args]
帳戶服務
python3 scripts/ibkr_cli.py account-summary --json
python3 scripts/ibkr_cli.py positions --account DU123456
python3 scripts/ibkr_cli.py portfolio --json
python3 scripts/ibkr_cli.py pnl --account DU123456 --wait 2
市場數據服務
python3 scripts/ibkr_cli.py quote --symbol AAPL --sec-type STK --market-data-type 3
python3 scripts/ibkr_cli.py historical --symbol EURUSD --sec-type CASH --duration "30 D" --bar-size "1 hour"
注意事項:
- 歷史資料請求支援透過標誌使用完整的 IB 格式值,包括包含空白的 token,例如
"30 D"。 - 對於
CASH,除非明確覆寫,否則預設的whatToShow為MIDPOINT。
合約發現
python3 scripts/ibkr_cli.py contract-details --symbol ES --sec-type FUT --expiry 202606
交易與訂單生命週期
python3 scripts/ibkr_cli.py place-order --symbol AAPL --sec-type STK --action BUY --quantity 10 --order-type MKT
python3 scripts/ibkr_cli.py place-order --symbol AAPL --sec-type STK --action SELL --quantity 10 --order-type LMT --limit-price 250 --tif GTC
python3 scripts/ibkr_cli.py open-orders
python3 scripts/ibkr_cli.py cancel-order --order-id 12345
python3 scripts/ibkr_cli.py executions --json
CLI 中支援的訂單類型:
MKTLMTSTPSTP LMT
place-order 會等待狀態更新,並顯示下單過程中收集到的 API 錯誤。
掃描器服務
python3 scripts/ibkr_cli.py scanner --instrument STK --location-code STK.US.MAJOR --scan-code TOP_PERC_GAIN --rows 25
相容性腳本
舊版腳本仍受支援,並已委派給統一的 CLI:
get_account_info.pyget_historical_data.py(舊版位置參數模式仍可使用)place_order.py(舊版位置參數模式仍可使用)
錯誤處理
CLI 在以下情況下會返回非零退出碼:
- 匯入/依賴項失敗
- 連線失敗
- 合約驗證失敗
- 無效參數
- 找不到要取消的未成交訂單
參考資料
請參閱 references/api_reference.md 以獲取 IBKR 和 ib_insync 的文件連結。