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>
  1. Install:
    pip install ib_async
  2. Start IB Gateway on port 7497 (paper) or 7496 (live)
  3. Connect:
    ib = IB(); await ib.connectAsync('127.0.0.1', 7497, clientId=1)
  4. Query:
    positions = ib.positions()
    /
    summary = await ib.accountSummaryAsync()
    </quick_start>
<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>
  1. 安装:
    pip install ib_async
  2. 启动IB Gateway,端口7497(模拟交易)或7496(实盘交易)
  3. 连接:
    ib = IB(); await ib.connectAsync('127.0.0.1', 7497, clientId=1)
  4. 查询:
    positions = ib.positions()
    /
    summary = await ib.accountSummaryAsync()
    </quick_start>
<success_criteria>
  • 已建立API连接并完成认证
  • 已获取所有关联账户的投资组合持仓和余额数据
  • 写入操作已遵循IRA限制
  • 凭证已安全存储(绝不硬编码) </success_criteria>

Quick Decision: Which API?

快速决策:选择哪种API?

CriterionTWS API (Recommended)Client Portal REST API
Best forAutomated trading, portfolio mgmtWeb dashboards, light usage
AuthLocal login via TWS/IB GatewayOAuth 2.0 JWT
PerformanceAsync, low latency, high throughputREST, slower
Data qualityTick-by-tick availableLevel 1 only
Multi-accountAll accounts simultaneouslyPer-request
InfrastructureLocal Java app (port 7496/7497)HTTPS REST calls
Python libraryib_async (recommended)requests + OAuth
CostFreeFree
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
    reqLinkedAccounts()
    to enumerate account IDs
  • 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会话可访问所有关联账户
  • 使用
    reqLinkedAccounts()
    枚举账户ID
  • 下单时指定账户ID
  • 市场数据订阅费用在所有关联账户中仅收取一次
  • 每个用户名仅允许一个活跃会话 —— 在其他地方登录会关闭当前会话

IRA-Specific Restrictions (Critical)

IRA特定限制(关键)

RestrictionImpact
No short selling
placeOrder()
will reject short orders
No margin borrowingCash-only (no debit balances)
No foreign currency borrowingMust execute FX trade first
Futures margin 2x higherPosition sizing affected
MLPs/UBTI prohibitedFilter these from IRA order flow
Withdrawals USD onlyInformational
限制内容影响
禁止卖空
placeOrder()
会拒绝卖空订单
禁止保证金借款仅现金账户(无借方余额)
禁止外币借款必须先执行外汇交易
期货保证金要求翻倍影响仓位规模
禁止MLP/UBTI需从IRA订单流中过滤这些资产
仅允许美元提款信息提示

Core API Operations

核心API操作

Read Operations (Safe — use for all account types)

读取操作(安全 —— 适用于所有账户类型)

python
undefined
python
undefined

Key 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
undefined
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
undefined

Write 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 orders
python
placeOrder(account_id, contract, order)  # Place order on specific account
cancelOrder(order_id)                     # Cancel pending order
reqGlobalCancel()                         # Cancel all open orders

Client 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 candles
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 candles

Python Library: ib_async

Python库:ib_async

Install:
pip install ib_async
Why 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):
  • ib_insync
    — Legacy, stable but unmaintained since early 2024
  • ibapi
    — Official IBKR library, cumbersome event loop
安装
pip install ib_async
为什么选择ib_async而非其他库
  • ib_insync的现代继任者(原作者项目的延续)
  • 原生支持asyncio
  • 内部实现IBKR二进制协议(无需官方ibapi)
  • 持续维护(GitHub: ib-api-reloaded/ib_async)
替代方案(仅当ib_async无法满足需求时使用):
  • ib_insync
    —— 旧版,稳定但自2024年初起未维护
  • ibapi
    —— 官方IBKR库,事件循环使用繁琐

Reference: Connection Pattern

参考:连接模式

See
reference/connection-patterns.md
for:
  • 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
reference/trading-patterns.md
for:
  • 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

基础设施要求

  1. IB Gateway (lightweight) or TWS (full UI) running locally
  2. Java 8+ installed
  3. API enabled in TWS/Gateway settings
  4. Ports: 7496 (live) / 7497 (paper trading)
  5. Credentials: Stored in OS credential manager (never hardcode)
  1. IB Gateway(轻量版)或TWS(完整UI)本地运行
  2. 已安装Java 8+
  3. 在TWS/Gateway设置中启用API
  4. 端口:7496(实盘)/ 7497(模拟交易)
  5. 凭证:存储在操作系统凭证管理器中(绝不硬编码)

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

成本结构

ItemCost
API accessFree
Market data$5-50/month per exchange subscription
Trading commissionsStandard 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
    ~/.claude.json
    (user scope)
  • 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工具

ToolPurposeAccount Types
get_portfolio
Positions + P&LAll accounts
get_account_summary
Balances, margin, buying powerAll accounts
switch_account
Toggle Roth IRA / Personal / THKMulti-account
get_market_data
Real-time quotesN/A
get_historical_data
Historical OHLCVN/A
place_order
Orders with safety checksAll (IRA restrictions enforced)
check_shortable_shares
Short availabilityPersonal/Business only
get_margin_requirements
Margin needs per securityPersonal/Business only
get_borrow_rates
Borrow costs for shortsPersonal/Business only
short_selling_analysis
Full short analysis packagePersonal/Business only
get_connection_status
IB Gateway health checkN/A
工具用途适用账户类型
get_portfolio
持仓 + 盈亏所有账户
get_account_summary
余额、保证金、购买力所有账户
switch_account
切换罗斯IRA / 个人 / THK账户多账户
get_market_data
实时报价N/A
get_historical_data
历史OHLCV数据N/A
place_order
带安全检查的下单所有账户(强制执行IRA限制)
check_shortable_shares
可卖空股票数量仅个人/企业账户
get_margin_requirements
每只证券的保证金需求仅个人/企业账户
get_borrow_rates
卖空借款成本仅个人/企业账户
short_selling_analysis
完整卖空分析包仅个人/企业账户
get_connection_status
IB Gateway健康检查N/A

To Activate

激活步骤

  1. Start IB Gateway → port 7497 (paper) or 7496 (live)
  2. Enable API: Config → API → Settings → "ActiveX and Socket Clients"
  3. Add 127.0.0.1 to Trusted IPs
  4. Restart Claude Code / Claude Desktop
  1. 启动IB Gateway → 端口7497(模拟)或7496(实盘)
  2. 启用API:配置 → API → 设置 → "ActiveX和Socket客户端"
  3. 将127.0.0.1添加到可信IP列表
  4. 重启Claude Code / Claude Desktop

Other Community MCP Servers

其他社区MCP服务器

  • code-rabi/interactive-brokers-mcp
    — Client Portal REST API
  • xiao81/IBKR-MCP-Server
    — TWS API focused
  • Hellek1/ib-mcp
    — Read-only via ib_async (safest)
  • code-rabi/interactive-brokers-mcp
    —— Client Portal REST API
  • xiao81/IBKR-MCP-Server
    —— 专注TWS API
  • Hellek1/ib-mcp
    —— 通过ib_async实现只读访问(最安全)

Multi-Broker Aggregation

多经纪商聚合

For unified view across IBKR + Robinhood:
  • SnapTrade MCP (
    dangelov/mcp-snaptrade
    ) — Read-only aggregator, 15+ brokerages, OAuth-based (safe)
  • Alpaca MCP (official) — Alternative broker with production-ready MCP
  • Manual CSV import from Robinhood as fallback (ToS-safe)
See
reference/multi-broker-strategy.md
for aggregation patterns.
如需统一查看IBKR + Robinhood账户:
  • SnapTrade MCP (
    dangelov/mcp-snaptrade
    ) —— 只读聚合器,支持15+经纪商,基于OAuth(安全)
  • Alpaca MCP(官方)—— 替代经纪商,生产就绪MCP
  • 备选方案:从Robinhood手动导入CSV(符合ToS)
详见
reference/multi-broker-strategy.md
中的聚合模式。