IB Analytics MCP Server
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@IB Analytics MCP Servershow me my portfolio performance for the last quarter"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
IB Analytics
Interactive Brokers portfolio analytics library with AI-powered investment analysis and development automation.
Overview
IB Analytics enables systematic analysis of trading performance across multiple IB accounts with type-safe, modular, and extensible architecture.
For Investors (Modes 1 & 2):
95% faster investment strategy generation (6-8 hours → 15-20 minutes)
Parallel market analysis of all holdings simultaneously
Consolidated multi-account view with accurate portfolio metrics
Professional options strategies with specific strikes, Greeks, and Max Pain
Tax-optimized execution plans across multiple accounts
Multi-timeframe technical analysis with entry/exit signals
For Developers (Mode 3):
90% faster issue resolution (80 minutes → 8 minutes via
/resolve-gh-issue)Automated quality gates (black, ruff, mypy, pytest)
Complete TDD workflow (tests → code → PR automation)
11 specialized AI agents + 21 slash commands
Task | Manual | Automated | Savings |
Investment Strategy | 6-8 hours | 15-20 min | 95% |
Stock Analysis | 1-2 hours | 2-3 min | 97% |
Options Strategy | 45-60 min | 3-5 min | 93% |
Portfolio Analysis | 3-4 hours | 5 min | 95% |
GitHub Issue → PR | 80 min | 8 min | 90% |
Related MCP server: Interactive Brokers MCP Server
Installation
# Install with uv (recommended)
uv pip install -e .
# Install with MCP server support
uv pip install -e ".[mcp]"
# Install with development dependencies
uv pip install -e ".[dev]"
# Install all optional dependencies
uv pip install -e ".[dev,mcp,visualization,reporting]"Quick Start
1. Configuration
Create a .env file with your IB Flex Query credentials:
QUERY_ID=your_query_id
TOKEN=your_token_hereNote: To analyze multiple accounts, configure them in your IB Flex Query settings. A single query can return data for multiple accounts.
2. Fetch Data
# Fetch data
ib-sec-fetch --start-date 2025-01-01 --end-date 2025-10-05
# Split by account (if query contains multiple accounts)
ib-sec-fetch --split-accounts --start-date 2025-01-01 --end-date 2025-10-053. Run Analysis
# Run comprehensive analysis
ib-sec-analyze --account U1234567
# Run specific analyzer
ib-sec-analyze --account U1234567 --analyzer performance
# Analyze all accounts
ib-sec-analyze --all-accounts4. Generate Reports
Use ib-sec-analyze with its --output option to produce reports.
Docker Usage
The repository ships two independent Docker setups:
Setup | Location | Purpose |
MCP server | repository root | Runs IB Analytics itself in a hardened container (analysis & MCP server) |
CP Gateway |
| Runs IBKR's Client Portal Gateway, required for live trading |
Run the MCP server in an isolated container with security hardening (non-root user, read-only filesystem, resource limits):
docker compose up # or: docker build -t ib-sec-mcp . && docker run -e QUERY_ID=... -e TOKEN=... ib-sec-mcpSee docs/docker.md for full setup of both containers, docker-compose configuration, and troubleshooting.
Programmatic Usage
from ib_sec_mcp import FlexQueryClient, Portfolio
from ib_sec_mcp.analyzers import PerformanceAnalyzer, TaxAnalyzer
from datetime import date
# Initialize client
client = FlexQueryClient(query_id="your_query_id", token="your_token_here")
# Fetch data
data = client.fetch_statement(
start_date=date(2025, 1, 1),
end_date=date(2025, 10, 5)
)
# Create portfolio
portfolio = Portfolio.from_flex_data(data)
# Run analysis
perf_analyzer = PerformanceAnalyzer(portfolio)
results = perf_analyzer.analyze()
# Generate report
from ib_sec_mcp.reports import ConsoleReport
report = ConsoleReport(results)
report.render()Project Structure
ib-sec/
├── ib_sec_mcp/ # Main library
│ ├── api/ # Flex Query API client
│ ├── core/ # Core business logic
│ ├── models/ # Pydantic data models
│ ├── analyzers/ # Analysis modules
│ ├── reports/ # Report generators
│ └── utils/ # Utilities
├── tests/ # Test suite
└── data/ # Data directory
├── raw/ # Raw CSV/XML data
└── processed/ # Processed dataArchitecture
Layer Structure
┌─────────────────────────────────────┐
│ CLI Layer (typer + rich) │
├─────────────────────────────────────┤
│ Reports Layer (console/html) │
├─────────────────────────────────────┤
│ Analyzers Layer (7 analyzers) │
├─────────────────────────────────────┤
│ Core Logic (parser/calc/agg) │
├─────────────────────────────────────┤
│ Models Layer (Pydantic v2) │
├─────────────────────────────────────┤
│ API Layer (sync + async) │
└─────────────────────────────────────┘See docs/architecture.md for design patterns, data flow diagrams, layer responsibilities, and new feature decision guide.
Available Analyzers
PerformanceAnalyzer: Overall trading performance metrics
TaxAnalyzer: Tax liability calculations (OID, capital gains)
CostAnalyzer: Commission and cost efficiency analysis
RiskAnalyzer: Interest rate and market risk scenarios
BondAnalyzer: Bond-specific analytics (YTM, duration, etc.)
SectorAnalyzer: Sector allocation and concentration (HHI) analysis
FXExposureAnalyzer: Currency exposure and FX sensitivity analysis
Investment Analysis Tools (MCP)
51 MCP tools for stock, options, and portfolio analysis via Yahoo Finance and IB
portfolio data — plus 8 optional live-trading tools (CP Gateway, disabled by default)
for a total of 59 when IB_ENABLE_LIVE_TRADING is enabled (see
Live Trading (CP Gateway)).
Category | Tools | Representative Tools |
Portfolio analysis & metrics | 10 |
|
Composable data access | 6 |
|
Stock & market data | 11 |
|
Options analysis | 5 |
|
Position history & snapshots | 5 |
|
Rebalancing, sector & FX | 4 |
|
ETF swap calculators | 2 |
|
Limit orders & daily monitoring | 8 |
|
Live trading (CP Gateway) ⚠️ | 8 |
|
Full reference (all arguments, return values, examples): docs/mcp-tools-reference.md
Usage Examples in Claude Desktop
Once you've set up the MCP server in Claude Desktop, you can use natural language:
"Show me detailed information for AAPL including all fundamental metrics"
"Compare my portfolio performance against the S&P 500 over the last year"
"What's the correlation between positions in my portfolio? Are they well diversified?"
"Analyze market sentiment for NVDA - should I buy now or wait?"
"What's the composite sentiment for SPY across news, options, and technicals?"
"Create a comprehensive investment plan for my portfolio"Usage Modes
IB Analytics supports three distinct usage modes optimized for different user types:
Mode | Target | Characteristics |
1: Claude Desktop | Investors, analysts | Natural language queries, zero coding, complete analysis from single question |
2: Claude Code + MCP | Data scientists | Direct tool composition, fine-grained data access, custom analysis workflows |
3: Claude Code + Repo | Developers | Sub-agents, slash commands, GitHub integration, TDD workflow automation |
Mode 3 example:
/resolve-gh-issue 42
# Automated: Issue analysis → Tests → Implementation → Quality checks → PR
# Result: 80 minutes → 8 minutes (90% time savings)Detailed architecture, workflow examples, and implementation guide: CLAUDE.md
See .claude/README.md for all 11 sub-agents and 21 slash commands.
Feature Comparison
Feature | Mode 1: Desktop | Mode 2: MCP | Mode 3: Repository |
Investment Analysis | ✅ Natural language | ✅ Composable tools | ✅ Advanced automation |
Multi-Account Support | ✅ Automatic | ✅ Manual selection | ✅ Consolidated analysis |
Market Analysis | ✅ Basic | ✅ Detailed | ✅ Parallel + Advanced |
Options Strategies | ✅ Basic | ✅ Detailed | ✅ Professional-grade |
Tax Optimization | ✅ Recommendations | ✅ Custom analysis | ✅ Multi-account optimization |
Development Tools | ❌ | ❌ | ✅ 11 AI specialists |
GitHub Integration | ❌ | ❌ | ✅ Issue → PR automation |
Quality Gates | ❌ | ❌ | ✅ Automated enforcement |
Time to Analysis | 2 minutes | 15 minutes | 15-20 minutes (comprehensive) |
Time to Implementation | N/A | N/A | 8 minutes (vs 80 manual) |
Learning Curve | None | Low | Medium |
Customization | Low | High | Very High |
Recommendation:
Start with Mode 1 if you're an investor looking for quick insights
Use Mode 2 if you need custom analysis or programmatic access
Adopt Mode 3 if you're developing features or need advanced automation
Position History & Time-Series Analysis
IB Analytics automatically stores daily position snapshots in SQLite (data/processed/positions.db) for historical analysis and time-series tracking.
Features: Automatic sync on data fetch, multi-account support, 5 MCP tools for querying history.
Tool | Description |
| Time series for a symbol over a date range |
| All positions on a specific date |
| Portfolio changes between two dates |
| Min/max/average statistics over time |
| List all dates with snapshot data |
Full schema, indexes, and migration procedures: docs/database-schema.md
MCP Server Integration
IB Analytics provides a Model Context Protocol (MCP) server for integration with Claude Desktop and Claude Code.
Features
51 Tools (+8 optional live-trading tools = 59 when
IB_ENABLE_LIVE_TRADINGis enabled): portfolio analysis, market data, risk/tax/cost analytics, rebalancing, dividend/sector/FX analysis, position history, limit orders, and daily monitoring9 Resources: Portfolio data, account info, trades, positions, and strategy context via URI patterns
5 Prompts: Pre-configured analysis templates for common workflows
Setup Options
Option 1: Git リポジトリから直接実行(推奨・クローン不要)
インストール不要。設定ファイルに追記するだけで使用できます。
Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"ib-sec-mcp": {
"command": "uvx",
"args": [
"--from",
"ib-sec-mcp[mcp] @ git+https://github.com/knishioka/ib-sec-mcp",
"ib-sec-mcp"
],
"env": {
"QUERY_ID": "your_query_id",
"TOKEN": "your_token"
}
}
}
}Claude Code (プロジェクトの .mcp.json):
{
"mcpServers": {
"ib-sec-mcp": {
"type": "stdio",
"command": "uvx",
"args": [
"--from",
"ib-sec-mcp[mcp] @ git+https://github.com/knishioka/ib-sec-mcp",
"ib-sec-mcp"
],
"env": {
"QUERY_ID": "${QUERY_ID}",
"TOKEN": "${TOKEN}"
}
}
}
}Note:
[mcp]extra の指定が必須です(fastmcp,scipy,pyyamlが含まれます)。
キャッシュ: 初回のみ依存関係をダウンロード(
~/.cache/uv)。2回目以降は即座に起動します。最新版を取得したい場合はuvx --refreshオプションを使用してください。
Option 2: ローカルリポジトリから実行(開発者向け)
リポジトリをクローンして開発する場合:
git clone https://github.com/knishioka/ib-sec-mcp.git
cd ib-sec-mcp
cp .mcp.json.example .mcp.json # パスを編集.mcp.json:
{
"mcpServers": {
"ib-sec-mcp": {
"type": "stdio",
"command": "uv",
"args": ["--directory", "/path/to/ib-sec-mcp", "run", "ib-sec-mcp"],
"env": {
"QUERY_ID": "${QUERY_ID}",
"TOKEN": "${TOKEN}"
}
}
}
}Prerequisites
uv インストール済み:
brew install uvまたはcurl -LsSf https://astral.sh/uv/install.sh | shIB Flex Query の
QUERY_IDとTOKEN(IB ポータルで取得)
See MCP Tools Reference for complete documentation of all 51 tools (59 with live trading), 9 resources, and 5 prompts.
See .claude/CLAUDE.md for development guide and usage patterns.
Live Trading (CP Gateway)
Beyond read-only analysis, IB Analytics can place and manage live orders through the
IBKR Client Portal Web API. This requires the local Client Portal Gateway (CP
Gateway) — IBKR's authenticated proxy for the /v1/api/... endpoints — and the
live-trading tools are disabled by default.
⚠️ Live trading moves real money. Read the Live Trading Gate safety guards below before enabling anything. Start with paper trading and keep
IB_ORDER_DRY_RUNon until you have verified the full flow.
Prerequisites
A funded or paper IBKR account with Client Portal Web API access enabled
Docker + Docker Compose (to run the gateway)
The MCP server started with the live-trading gate enabled (see step 2)
1. Start the CP Gateway
The gateway is packaged under docker/cp-gateway/:
cd docker/cp-gateway
docker compose up -d --build # host 5001 → container 5000 (HTTPS)
# Then open https://localhost:5001/ in your browser to authenticateFull setup, authentication, and troubleshooting:
docker/cp-gateway/README.md and the
Docker Usage section.
2. Enable the live-trading tools
The 8 CP Gateway tools (place_order, modify_order, cancel_order,
cancel_all_orders, get_live_orders, get_live_account_balance,
get_live_positions, check_gateway_status) are only registered with the MCP server
when the gate is explicitly enabled:
export IB_ENABLE_LIVE_TRADING=1 # accepts 1 / true / yes (default: off)
export IB_GATEWAY_URL=https://localhost:5001 # match the Docker host port (default: 5000)
ib-sec-mcpGateway URL:
CPClientdefaultsIB_GATEWAY_URLtohttps://localhost:5000, but thedocker/cp-gateway/compose file publishes the gateway on host port 5001. ExportIB_GATEWAY_URL=https://localhost:5001(as shown) so the live-trading tools reach the gateway; otherwise they report it as unavailable. If you run the gateway directly on5000(no Docker port remap), the default is correct and this export is unnecessary.
When the flag is off, these tools are not advertised to MCP clients at all. See the
Live Trading Gate table for the full set of safety guards
(IB_READ_ONLY, IB_ORDER_DRY_RUN, per-order and daily amount limits).
Daily Monitoring & Scheduled Tasks
IB Analytics supports unattended, scheduled portfolio monitoring. The sync_daily_snapshot
MCP tool persists a daily snapshot to the SQLite position history (with pipeline health
monitored via the read-only get_sync_status tool), and the
/daily-check slash command runs a complete
hands-off monitoring pass (snapshot sync, price check, limit-order proximity, consolidated
portfolio review) in under 3 minutes — designed for Claude Desktop scheduled tasks.
See docs/scheduled-tasks.md for the full setup, the 3-layer memory system, and recommended morning/evening schedules.
Documentation
Document | Description |
Data flow diagrams, layer responsibilities, and new feature decision guide | |
Calculation formulas (YTM, duration, Sharpe, Sortino, phantom income) | |
SQLite position history schema, indexes, and migration procedures | |
Complete reference for all 51 tools (59 with live trading), 9 resources, and 5 prompts | |
Docker and docker-compose setup | |
Common errors and solutions | |
ETF calculation accuracy strategy | |
Claude Desktop scheduled task setup (daily monitoring) |
Development
# Install development dependencies
uv pip install -e ".[dev]"
# Run tests
uv run pytest
# Run tests with coverage
uv run pytest --cov=ib_sec_mcp --cov-report=html
# Code formatting with Ruff
uv run ruff format ib_sec_mcp tests
# Linting with Ruff
uv run ruff check --fix ib_sec_mcp tests
# Type checking with mypy
uv run mypy ib_sec_mcp
# Run all pre-commit hooks manually
uv run pre-commit run --all-filesRequirements
Python 3.12+
Interactive Brokers account with Flex Query access
Dependencies
requests (2.32.5+): HTTP client for API calls
pandas (2.2.3+): Data analysis and manipulation
pydantic (2.10.0+): Data validation and settings management
httpx (0.27.0+): Async HTTP client for parallel requests
rich (13.7.0+): Beautiful console output
typer (0.12.0+): CLI framework
yfinance (0.2.40+): Yahoo Finance data integration
fastmcp (2.0.0+): Model Context Protocol server framework
Security
MCP Server Security
Error Masking: Internal error details are masked from clients (configurable with
IB_DEBUG=1)Input Validation: All inputs are validated before processing
File Path Protection: Path traversal attacks are prevented
File Size Limits: Maximum file size: 10MB
Timeout Protection: All operations have timeout limits
Retry Logic: Automatic retry for transient errors (max 3 attempts)
Live Trading Gate
CP Gateway live-trading and order-management tools (place_order, modify_order,
cancel_order, cancel_all_orders, get_live_orders, get_live_account_balance,
get_live_positions, check_gateway_status) are disabled by default. They are only
registered with the MCP server when IB_ENABLE_LIVE_TRADING is explicitly enabled:
export IB_ENABLE_LIVE_TRADING=1 # accepts 1 / true / yes
ib-sec-mcpWhen the flag is off, these 8 tools are not advertised to MCP clients at all. The local
limit_orders tools (add_limit_order, update_limit_order, get_pending_orders,
check_order_proximity, get_order_history, sync_limit_orders) remain available in both
states. This registration gate is purely additive — once enabled, the existing per-call
guards still apply as a second line of defense:
Variable | Default | Effect |
| off | Registers the 8 CP Gateway live-trading tools |
| off | Blocks all order placement/modification/cancellation |
| on | Simulates orders without submitting (set |
|
| Per-order amount limit |
|
| Cumulative daily order amount limit |
Debug Mode
export IB_DEBUG=1
ib-sec-mcpWarning: Never enable debug mode in production as it exposes internal error details.
Credentials Security
Never commit
.envfiles to version controlStore credentials in environment variables or secure secret management systems
Regularly rotate API tokens
Command Selection Guide
For an interactive decision flowchart and full command reference table, see .claude/README.md.
Quick reference:
Investors:
/investment-strategy→/analyze-symbol SYMBOL→/options-strategy SYMBOLDevelopers:
/resolve-gh-issue N→/quality-check→/test
Troubleshooting
For a comprehensive troubleshooting guide with detailed error cases, prevention tips, and the full exception hierarchy, see docs/troubleshooting.md.
Testing
uv run pytest
uv run pytest --cov=ib_sec_mcp --cov-report=htmlMCP Server Testing
# Start server in debug mode
IB_DEBUG=1 ib-sec-mcpPerformance Optimization
If experiencing slow performance:
Reduce date ranges: Fetch smaller time periods
Use file caching: Reuse previously fetched data
Limit technical indicators: Only request needed indicators
License
MIT
Author
Kenichiro Nishioka
Support
For issues and questions, please check the IB Flex Query documentation.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/knishioka/ib-sec-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server