ibkr-api-skill
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<objective>
Build and manage Interactive Brokers (IBKR) integrations for portfolio queries, trade execution, and multi-account management across Roth IRA, personal brokerage, and business accounts using TWS API (ib_async) or Client Portal REST API.
</objective>
<quick_start>
- Install:
pip install ib_async - Start IB Gateway on port 7497 (paper) or 7496 (live)
- Connect:
ib = IB(); await ib.connectAsync('127.0.0.1', 7497, clientId=1) - Query: /
positions = ib.positions()</quick_start>summary = await ib.accountSummaryAsync()
<success_criteria>
- API connection established and authenticated
- Portfolio positions and balances retrieved across all linked accounts
- IRA restrictions enforced on write operations
- Credentials stored securely (never hardcoded) </success_criteria>
<objective>
构建并管理Interactive Brokers (IBKR)集成,通过TWS API(ib_async)或Client Portal REST API实现投资组合查询、交易执行以及罗斯IRA、个人经纪账户和企业账户的多账户管理。
</objective>
<quick_start>
- 安装:
pip install ib_async - 启动IB Gateway,端口7497(模拟交易)或7496(实盘交易)
- 连接:
ib = IB(); await ib.connectAsync('127.0.0.1', 7497, clientId=1) - 查询:/
positions = ib.positions()</quick_start>summary = await ib.accountSummaryAsync()
<success_criteria>
- 已建立API连接并完成认证
- 已获取所有关联账户的投资组合持仓和余额数据
- 写入操作已遵循IRA限制
- 凭证已安全存储(绝不硬编码) </success_criteria>
Quick Decision: Which API?
快速决策:选择哪种API?
| Criterion | TWS API (Recommended) | Client Portal REST API |
|---|---|---|
| Best for | Automated trading, portfolio mgmt | Web dashboards, light usage |
| Auth | Local login via TWS/IB Gateway | OAuth 2.0 JWT |
| Performance | Async, low latency, high throughput | REST, slower |
| Data quality | Tick-by-tick available | Level 1 only |
| Multi-account | All accounts simultaneously | Per-request |
| Infrastructure | Local Java app (port 7496/7497) | HTTPS REST calls |
| Python library | ib_async (recommended) | requests + OAuth |
| Cost | Free | Free |
Default recommendation: TWS API via ib_async library for all programmatic work.
| 评判标准 | TWS API(推荐) | Client Portal REST API |
|---|---|---|
| 最适用场景 | 自动化交易、投资组合管理 | Web仪表板、轻量使用场景 |
| 认证方式 | 通过TWS/IB Gateway本地登录 | OAuth 2.0 JWT |
| 性能 | 异步、低延迟、高吞吐量 | REST、速度较慢 |
| 数据质量 | 支持逐笔数据 | 仅Level 1数据 |
| 多账户支持 | 同时访问所有账户 | 每次请求指定单个账户 |
| 基础设施 | 本地Java应用(端口7496/7497) | HTTPS REST调用 |
| Python库 | ib_async(推荐) | requests + OAuth |
| 成本 | 免费 | 免费 |
默认推荐:所有程序化工作均通过ib_async库使用TWS API。
Account Architecture
账户架构
Tim's setup: Roth IRA + Personal Brokerage + THK Enterprises (future business account)
- All linked under single IBKR username/password
- Single API session accesses all linked accounts
- Use to enumerate account IDs
reqLinkedAccounts() - Specify account ID per order placement
- Market data subscriptions charged once across all linked accounts
- One active session per username — connecting elsewhere closes current session
蒂姆的配置:罗斯IRA + 个人经纪账户 + THK Enterprises(未来企业账户)
- 所有账户关联到同一个IBKR用户名/密码下
- 单个API会话可访问所有关联账户
- 使用枚举账户ID
reqLinkedAccounts() - 下单时指定账户ID
- 市场数据订阅费用在所有关联账户中仅收取一次
- 每个用户名仅允许一个活跃会话 —— 在其他地方登录会关闭当前会话
IRA-Specific Restrictions (Critical)
IRA特定限制(关键)
| Restriction | Impact |
|---|---|
| No short selling | |
| No margin borrowing | Cash-only (no debit balances) |
| No foreign currency borrowing | Must execute FX trade first |
| Futures margin 2x higher | Position sizing affected |
| MLPs/UBTI prohibited | Filter these from IRA order flow |
| Withdrawals USD only | Informational |
| 限制内容 | 影响 |
|---|---|
| 禁止卖空 | |
| 禁止保证金借款 | 仅现金账户(无借方余额) |
| 禁止外币借款 | 必须先执行外汇交易 |
| 期货保证金要求翻倍 | 影响仓位规模 |
| 禁止MLP/UBTI | 需从IRA订单流中过滤这些资产 |
| 仅允许美元提款 | 信息提示 |
Core API Operations
核心API操作
Read Operations (Safe — use for all account types)
读取操作(安全 —— 适用于所有账户类型)
python
undefinedpython
undefinedKey TWS API functions for portfolio queries
Key TWS API functions for portfolio queries
reqLinkedAccounts() # List all account IDs
reqAccountSummary() # Balances, buying power, equity (all accounts)
reqPositions() # Current positions (up to 50 sub-accounts)
reqPositionsMulti() # Per-account positions (>50 sub-accounts)
reqAccountUpdates() # Stream account + position data (single account)
reqMktData() # Real-time Level 1 market data
reqHistoricalData() # Historical price data
undefinedreqLinkedAccounts() # List all account IDs
reqAccountSummary() # Balances, buying power, equity (all accounts)
reqPositions() # Current positions (up to 50 sub-accounts)
reqPositionsMulti() # Per-account positions (>50 sub-accounts)
reqAccountUpdates() # Stream account + position data (single account)
reqMktData() # Real-time Level 1 market data
reqHistoricalData() # Historical price data
undefinedWrite Operations (Use with caution — respect IRA restrictions)
写入操作(谨慎使用 —— 遵守IRA限制)
python
placeOrder(account_id, contract, order) # Place order on specific account
cancelOrder(order_id) # Cancel pending order
reqGlobalCancel() # Cancel all open orderspython
placeOrder(account_id, contract, order) # Place order on specific account
cancelOrder(order_id) # Cancel pending order
reqGlobalCancel() # Cancel all open ordersClient Portal REST Endpoints (Alternative)
Client Portal REST端点(替代方案)
GET /iserver/accounts # List accounts
GET /iserver/account/{id}/positions # Positions
GET /iserver/account/{id}/summary # Balances
POST /iserver/account/{id}/orders # Place order
GET /market/candle # Historical candlesGET /iserver/accounts # List accounts
GET /iserver/account/{id}/positions # Positions
GET /iserver/account/{id}/summary # Balances
POST /iserver/account/{id}/orders # Place order
GET /market/candle # Historical candlesPython Library: ib_async
Python库:ib_async
Install:
pip install ib_asyncWhy ib_async over alternatives:
- Modern successor to ib_insync (original creator's project continued)
- Native asyncio support
- Implements IBKR binary protocol internally (no need for official ibapi)
- Active maintenance (GitHub: ib-api-reloaded/ib_async)
Alternatives (use only if ib_async doesn't meet needs):
- — Legacy, stable but unmaintained since early 2024
ib_insync - — Official IBKR library, cumbersome event loop
ibapi
安装:
pip install ib_async为什么选择ib_async而非其他库:
- ib_insync的现代继任者(原作者项目的延续)
- 原生支持asyncio
- 内部实现IBKR二进制协议(无需官方ibapi)
- 持续维护(GitHub: ib-api-reloaded/ib_async)
替代方案(仅当ib_async无法满足需求时使用):
- —— 旧版,稳定但自2024年初起未维护
ib_insync - —— 官方IBKR库,事件循环使用繁琐
ibapi
Reference: Connection Pattern
参考:连接模式
See for:
reference/connection-patterns.md- IB Gateway setup and configuration
- Connection/reconnection handling
- Session timeout management (6-min ping for CP API)
- Multi-account query patterns
- Error handling and rate limit management
详见:
reference/connection-patterns.md- IB Gateway设置与配置
- 连接/重连处理
- 会话超时管理(CP API需6分钟心跳)
- 多账户查询模式
- 错误处理与速率限制管理
Reference: Trading Patterns
参考:交易模式
See for:
reference/trading-patterns.md- Order types (market, limit, stop, bracket, IB algos)
- IRA-safe order validation
- Multi-account order routing
- Position sizing with account-type awareness
- Greeks-aware options order flow
详见:
reference/trading-patterns.md- 订单类型(市价、限价、止损、括号单、IB算法单)
- IRA安全订单验证
- 多账户订单路由
- 考虑账户类型的仓位规模计算
- Greeks感知的期权订单流
Infrastructure Requirements
基础设施要求
- IB Gateway (lightweight) or TWS (full UI) running locally
- Java 8+ installed
- API enabled in TWS/Gateway settings
- Ports: 7496 (live) / 7497 (paper trading)
- Credentials: Stored in OS credential manager (never hardcode)
- IB Gateway(轻量版)或TWS(完整UI)本地运行
- 已安装Java 8+
- 在TWS/Gateway设置中启用API
- 端口:7496(实盘)/ 7497(模拟交易)
- 凭证:存储在操作系统凭证管理器中(绝不硬编码)
Security Best Practices
安全最佳实践
- Run IB Gateway on localhost only (no internet exposure)
- Use read-only login for portfolio queries when trading not needed
- Store credentials in macOS Keychain / Linux secret-service
- Implement session timeout handling
- Validate market data subscriptions before placing orders
- Log all order attempts with account ID + timestamp
- 仅在本地主机运行IB Gateway(不暴露到互联网)
- 当无需交易时,使用只读登录进行投资组合查询
- 将凭证存储在macOS钥匙串/Linux秘密服务中
- 实现会话超时处理
- 下单前验证市场数据订阅状态
- 记录所有订单尝试,包含账户ID + 时间戳
Cost Structure
成本结构
| Item | Cost |
|---|---|
| API access | Free |
| Market data | $5-50/month per exchange subscription |
| Trading commissions | Standard IBKR rates (varies by asset) |
| Account minimums | $500 per account |
| Estimated total | ~$1,500 aggregate minimum; $15-50/month data |
| 项目 | 成本 |
|---|---|
| API访问 | 免费 |
| 市场数据 | 每个交易所订阅每月5-50美元 |
| 交易佣金 | 标准IBKR费率(因资产类型而异) |
| 账户最低存款 | 每个账户500美元 |
| 预估总成本 | 合计最低约1500美元;每月数据费用15-50美元 |
Integration with Trading-Signals Skill
与交易信号技能集成
This skill complements the :
trading-signals-skill- trading-signals → generates signals, confluence scores, regime detection
- ibkr-api → executes trades, queries positions, manages accounts
- Pipeline: Signal generation → Position sizing → IRA validation → Order execution
本技能与互补:
trading-signals-skill- trading-signals → 生成信号、汇合度评分、趋势检测
- ibkr-api → 执行交易、查询持仓、管理账户
- 流程:信号生成 → 仓位规模计算 → IRA验证 → 订单执行
IBKR MCP Server (Installed)
IBKR MCP服务器(已安装)
ArjunDivecha/ibkr-mcp-server is installed and configured:
- Location:
~/Desktop/tk_projects/ibkr-mcp-server/ - Claude Code: Added to (user scope)
~/.claude.json - Claude Desktop: Added to
claude_desktop_config.json - Mode: Paper trading (port 7497), live trading disabled
- Safety: Order cap 1,000 shares, confirmation required
ArjunDivecha/ibkr-mcp-server已安装并配置:
- 位置:
~/Desktop/tk_projects/ibkr-mcp-server/ - Claude Code:已添加到(用户范围)
~/.claude.json - Claude Desktop:已添加到
claude_desktop_config.json - 模式:模拟交易(端口7497),实盘交易已禁用
- 安全设置:订单上限1000股,需确认
Available MCP Tools
可用MCP工具
| Tool | Purpose | Account Types |
|---|---|---|
| Positions + P&L | All accounts |
| Balances, margin, buying power | All accounts |
| Toggle Roth IRA / Personal / THK | Multi-account |
| Real-time quotes | N/A |
| Historical OHLCV | N/A |
| Orders with safety checks | All (IRA restrictions enforced) |
| Short availability | Personal/Business only |
| Margin needs per security | Personal/Business only |
| Borrow costs for shorts | Personal/Business only |
| Full short analysis package | Personal/Business only |
| IB Gateway health check | N/A |
| 工具 | 用途 | 适用账户类型 |
|---|---|---|
| 持仓 + 盈亏 | 所有账户 |
| 余额、保证金、购买力 | 所有账户 |
| 切换罗斯IRA / 个人 / THK账户 | 多账户 |
| 实时报价 | N/A |
| 历史OHLCV数据 | N/A |
| 带安全检查的下单 | 所有账户(强制执行IRA限制) |
| 可卖空股票数量 | 仅个人/企业账户 |
| 每只证券的保证金需求 | 仅个人/企业账户 |
| 卖空借款成本 | 仅个人/企业账户 |
| 完整卖空分析包 | 仅个人/企业账户 |
| IB Gateway健康检查 | N/A |
To Activate
激活步骤
- Start IB Gateway → port 7497 (paper) or 7496 (live)
- Enable API: Config → API → Settings → "ActiveX and Socket Clients"
- Add 127.0.0.1 to Trusted IPs
- Restart Claude Code / Claude Desktop
- 启动IB Gateway → 端口7497(模拟)或7496(实盘)
- 启用API:配置 → API → 设置 → "ActiveX和Socket客户端"
- 将127.0.0.1添加到可信IP列表
- 重启Claude Code / Claude Desktop
Other Community MCP Servers
其他社区MCP服务器
- — Client Portal REST API
code-rabi/interactive-brokers-mcp - — TWS API focused
xiao81/IBKR-MCP-Server - — Read-only via ib_async (safest)
Hellek1/ib-mcp
- —— Client Portal REST API
code-rabi/interactive-brokers-mcp - —— 专注TWS API
xiao81/IBKR-MCP-Server - —— 通过ib_async实现只读访问(最安全)
Hellek1/ib-mcp
Multi-Broker Aggregation
多经纪商聚合
For unified view across IBKR + Robinhood:
- SnapTrade MCP () — Read-only aggregator, 15+ brokerages, OAuth-based (safe)
dangelov/mcp-snaptrade - Alpaca MCP (official) — Alternative broker with production-ready MCP
- Manual CSV import from Robinhood as fallback (ToS-safe)
See for aggregation patterns.
reference/multi-broker-strategy.md如需统一查看IBKR + Robinhood账户:
- SnapTrade MCP () —— 只读聚合器,支持15+经纪商,基于OAuth(安全)
dangelov/mcp-snaptrade - Alpaca MCP(官方)—— 替代经纪商,生产就绪MCP
- 备选方案:从Robinhood手动导入CSV(符合ToS)
详见中的聚合模式。
reference/multi-broker-strategy.md