IBKR + OpenClaw Integration
Connect OpenClaw to your Interactive Brokers account for live portfolio monitoring, real-time quotes, technical analysis, and automated Telegram alerts.
Features
- - Live account data — NAV, cash, P&L, buying power
- Positions — all holdings with avg cost and exchange
- Real-time quotes — delayed or live market data
- Historical K-lines — daily OHLCV data for technical analysis
- Technical indicators — RSI, MACD, Bollinger Bands, ATR, MA (via ib_async)
- Read-only safe — API configured for read-only access
Prerequisites
- - Interactive Brokers account (live or paper)
- IBKR Mobile app (for 2FA approval)
- Docker & Docker Compose installed on your server
- Python 3.9+ with
ib_async and INLINECODE1
Setup Guide
Step 1: Install Docker
CODEBLOCK0
Step 2: Clone IB Gateway Docker
The IB Gateway runs in a Docker container based on gnzsnz/ib-gateway-docker.
CODEBLOCK1
Step 3: Configure Environment
Create a .env file in the ib-gateway-docker directory:
CODEBLOCK2
Important: Find your TWOFA_DEVICE name in your IBKR web portal under:
Settings → Security → Second Factor Authentication → Devices
Step 4: Start the Container
CODEBLOCK3
Check logs:
CODEBLOCK4
Step 5: Approve 2FA
The Gateway will prompt for 2FA. Approve the notification on your IBKR Mobile app.
Once connected, the API is available on:
- - Port 4001 → Paper trading API
- Port 4002 → Live trading API (read-only if configured)
Step 6: Install Python Dependencies
CODEBLOCK5
Step 7: Test the Connection
CODEBLOCK6
Expected output:
CODEBLOCK7
CLI Usage
ibkr_client.py — Account, Positions & Quotes
CODEBLOCK8
Getting Historical Data (Python)
CODEBLOCK9
API Port Reference
| Port | Mode | Description |
|---|
| 4001 | Paper | Paper trading API |
| 4002 |
Live | Live trading API |
| 5900 | VNC | Remote desktop (if VNC enabled) |
Troubleshooting
2FA not arriving
- - Check IBKR Mobile app is logged in with the correct username
- Verify
TWOFA_DEVICE matches your device name in IBKR web portal - Check phone notification settings for IBKR app
Connection timeout
- - Ensure the container is running: INLINECODE6
- Check logs: INLINECODE7
- The Gateway restarts daily at 23:45 SGT (configured via
AUTO_RESTART_TIME)
Read-only errors
- -
READ_ONLY_API=yes prevents trading but allows all read queries - Some ib_async features auto-request write access — ignore those errors
- Account summary and positions work fine in read-only mode
Container won't start
- - Check
.env file has correct credentials - Ensure ports 4001, 4002, 5900 are not in use: INLINECODE11
- Try recreating: INLINECODE12
Security Notes
- -
.env contains your IBKR password in plain text — keep it secure - INLINECODE14 prevents accidental trades
- VNC is bound to
127.0.0.1 (localhost only) by default - The container auto-restarts daily to maintain connection
Architecture
CODEBLOCK10
Credits
IBKR + OpenClaw 集成
将OpenClaw连接到您的盈透证券账户,实现实时投资组合监控、实时报价、技术分析和自动Telegram提醒。
功能特性
- - 实时账户数据 — 净资产值、现金、盈亏、购买力
- 持仓信息 — 所有持仓及其平均成本和交易所
- 实时报价 — 延迟或实时市场数据
- 历史K线 — 用于技术分析的每日OHLCV数据
- 技术指标 — RSI、MACD、布林带、ATR、移动平均线(通过ib_async实现)
- 只读安全 — API配置为只读访问
前提条件
- - 盈透证券账户(实盘或模拟)
- IBKR手机应用(用于双因素认证)
- 服务器上安装Docker和Docker Compose
- Python 3.9+,并安装ib_async和pandas
设置指南
步骤1:安装Docker
bash
curl -fsSL https://get.docker.com | sh
docker --version
docker compose version
步骤2:克隆IB网关Docker
IB网关运行在基于gnzsnz/ib-gateway-docker的Docker容器中。
bash
cd ~/.openclaw/workspace
git clone https://github.com/gnzsnz/ib-gateway-docker.git
cd ib-gateway-docker
步骤3:配置环境变量
在ib-gateway-docker目录中创建.env文件:
env
IBKR账户
TWS
USERID=yourusername
TWS
PASSWORD=yourpassword
交易模式:live或paper
TRADING_MODE=live
只读API(推荐用于监控)
READ
ONLYAPI=yes
API设置
TWS
ACCEPTINCOMING=auto
TWS
MASTERCLIENT_ID=1
双因素认证设备名称(在IBKR网页门户中查找 → 设置 → 安全)
TWOFA_DEVICE=IB Key
双因素认证超时
TWOFA
TIMEOUTACTION=exit
时区
TIME_ZONE=Asia/Singapore
TZ=Asia/Singapore
VNC密码(可选,用于远程桌面)
VNC
SERVERPASSWORD=your_password
自动重启(每日维护)
AUTO
RESTARTTIME=23:45
重启间保存设置
SAVE
TWSSETTINGS=yes
重要提示: 在IBKR网页门户中查找您的TWOFA_DEVICE名称:
设置 → 安全 → 双因素认证 → 设备
步骤4:启动容器
bash
docker compose up -d
查看日志:
bash
docker logs algo-trader-ib-gateway-1 --tail 20
步骤5:批准双因素认证
网关将提示进行双因素认证。在您的IBKR手机应用上批准通知。
连接成功后,API可通过以下端口访问:
- - 端口4001 → 模拟交易API
- 端口4002 → 实盘交易API(如果配置为只读)
步骤6:安装Python依赖
bash
pip install ib_async pandas
步骤7:测试连接
bash
python3 ~/.openclaw/workspace/skills/ibkr-openclaw/scripts/ibkr_client.py summary --port 4001
预期输出:
Account: [DU1234567]
BuyingPower.............. 500,000.00
NetLiquidation........... 125,000.00
TotalCashValue........... 25,000.00
StockMarketValue......... 100,000.00
FuturesPNL............... -500.00
UnrealizedPnL............ 3,200.00
CLI使用说明
ibkr_client.py — 账户、持仓和报价
bash
账户摘要
python3 scripts/ibkr_client.py summary --port 4001
所有持仓
python3 scripts/ibkr_client.py positions --port 4001
快速净资产值
python3 scripts/ibkr_client.py nav --port 4001
股票报价
python3 scripts/ibkr_client.py quote 2800 --exchange SEHK --currency HKD --port 4001
获取历史数据(Python)
python
from ib_async import IB, Stock
ib = IB()
ib.connect(127.0.0.1, 4001, clientId=1, readonly=True)
contract = Stock(2800, SEHK, HKD, primaryExchange=SEHK)
qualified = ib.qualifyContracts(contract)
bars = ib.reqHistoricalData(
qualified[0], , 6 M, 1 day, TRADES, True, 1
)
for bar in bars[-5:]:
print(f{bar.date} O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume})
ib.disconnect()
API端口参考
实盘 | 实盘交易API |
| 5900 | VNC | 远程桌面(如果启用VNC) |
故障排除
双因素认证未收到
- - 检查IBKR手机应用是否使用正确的用户名登录
- 验证TWOFA_DEVICE与IBKR网页门户中的设备名称匹配
- 检查手机通知设置中IBKR应用的通知权限
连接超时
- - 确保容器正在运行:docker ps
- 检查日志:docker logs algo-trader-ib-gateway-1 --tail 20
- 网关每天新加坡时间23:45自动重启(通过AUTORESTARTTIME配置)
只读错误
- - READONLYAPI=yes禁止交易但允许所有读取查询
- 某些ib_async功能会自动请求写入权限 — 忽略这些错误
- 账户摘要和持仓信息在只读模式下正常工作
容器无法启动
- - 检查.env文件中的凭证是否正确
- 确保端口4001、4002、5900未被占用:netstat -tlnp | grep 400
- 尝试重新创建:docker compose up -d --force-recreate
安全说明
- - .env文件包含明文密码 — 请妥善保管
- READONLYAPI=yes防止意外交易
- VNC默认绑定到127.0.0.1(仅本地访问)
- 容器每天自动重启以保持连接
架构
┌─────────────┐ ┌──────────────────┐ ┌─────────────┐
│ OpenClaw │────►│ ibkr_client.py │────►│ IB网关 │
│ 代理 │ │ (ib_async) │ │ (Docker) │
└─────────────┘ └──────────────────┘ └──────┬──────┘
│
┌──────▼──────┐
│ IBKR服务器 │
│ (实时数据) │
└─────────────┘
致谢