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 格式值,包括像
"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 文档链接。