Content
# IBKR TWS MCP Server 📈
A high-performance, robust [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server providing a seamless AI integration layer for **Interactive Brokers (IBKR) TWS & IB Gateway**.
This package exposes your trading account, positions, real-time market data, and quantitative scanners directly to LLMs (like Claude Desktop) with incredibly low latency thanks to its persistent-connection architecture.
## ✨ Core Features
* **⚡ Persistent Connection Pooling**: Employs a single global active session (Client ID=1) preventing TWS rate limits, Socket crashes, and cutting tool invocation latency from `~3000ms` down to `~50ms`.
* **🧠 Agent-Optimized**: Type-hinted properties and descriptive schemas allowing LLMs to naturally understand market states and errors.
* **🛡️ Thread-Safe**: Fully compatible with the concurrency models of FastMCP and synchronous `ib_insync` polling.
* **🧰 Comprehensive Toolset**:
* **行情 (Market Data)**: Real-time price snapshots (`live/delayed/historic` cascade) and contract searching (`search_contract`).
* **历史 (Historical)**: Candle stick historical data.
* **账户 (Account)**: PnL summaries, Net Liquidation tracking, and Holdings overview.
* **资讯 (News)**: Breaking news headlines for specific tickers and the full article viewer.
* **扫描仪 (Scanners)**: Real-time dynamic market scanners (Top gainers, most active, etc.).
* **基本面 (Fundamentals)**: Get structural company data (`ReportSnapshot`, `ReportRatios`, `RESC`, etc.).
* **🛡️ Robustness**: Connection health checks (`check_connection`), manual `reconnect` tool, and a status resource (`ibkr://status`).
* **🧪 Testing Ready**: Built-in **Prompts** (templates) for Stock Analysis, Portfolio Review, and Market Scanning, accessible via the MCP Inspector or Claude's prompt menu.
## 🛠 Prerequisites
1. **Python >= 3.12**
2. **Interactive Brokers TWS** or **IB Gateway** running locally.
3. In TWS/Gateway, navigate to **Settings > API > Settings**:
* Enable **"Enable ActiveX and Socket Clients"**
* Check your API Port (defaults to `7496` for TWS Live, `7497` for TWS Paper, `4001` for Gateway Live, `4002` for Gateway Paper).
*This project expects the port `4002` by default but it can be overridden.*
## 📦 Installation & Setup
We recommend using [uv](https://github.com/astral-sh/uv) for fast, reliable package management.
```bash
# 1. Clone the repository
git clone <your-repo-url>
cd ibkr-tws-mcp
# 2. Setup environment and install dependencies
uv sync
```
## 🚀 Usage
### Environment Variables
Configure your gateway using exactly these environment variables if they differ from the defaults:
```env
IBKR_HOST=127.0.0.1
IBKR_PORT=4002
```
### 1. Test via MCP Inspector (Web UI)
Test out the functionality in a web playground:
```bash
npx -y @modelcontextprotocol/inspector uv run python -m ibkr_mcp
```
### 2. Add to Claude Desktop (or other MCP Clients)
Add this to your `claude_desktop_config.json` (usually located at `~/Library/Application Support/Claude/claude_desktop_config.json` on Mac).
```json
{
"mcpServers": {
"ibkr": {
"command": "uv",
"args": [
"--directory",
"/Users/<your-user>/path/to/ibkr-tws-mcp",
"run",
"python",
"-m",
"ibkr_mcp"
],
"env": {
"IBKR_HOST": "127.0.0.1",
"IBKR_PORT": "4002"
}
}
}
}
```
### 3. CLI Testing & Debugging
The repository includes a standalone client CLI that allows you to test IBKR connectivity and fetch data without starting the full MCP server.
```bash
# General Syntax
uv run ibkr_mcp/client.py --port 4002 <command> [args]
# 1. 💰 Market Price snapshot (Live/Delayed/Historic)
uv run ibkr_mcp/client.py --port 4002 price --symbol AAPL
# 2. 📈 Historical Bars (Last 1 Month daily)
uv run ibkr_mcp/client.py --port 4002 history --symbol TSLA --duration "1 M" --bar-size "1 day"
# 3. 💼 List current account positions
uv run ibkr_mcp/client.py --port 4002 positions
# 4. 🏦 Get account PnL and Net Liquidation status
uv run ibkr_mcp/client.py --port 4002 pnl
# 5. 🗞️ News for currently held positions
uv run ibkr_mcp/client.py --port 4002 positions-news --limit 3
# 6. 📰 News headlines for a specific symbol
uv run ibkr_mcp/client.py --port 4002 news --symbol NVDA --limit 5
# 7. 📖 Fetch full article body (using Code and ID from 'news' results)
uv run ibkr_mcp/client.py --port 4002 article --provider BRFG --id 1234567
# 8. 🔍 Run a Dynamic Market Scanner
uv run ibkr_mcp/client.py --port 4002 scan --code TOP_PERC_GAIN --instrument STK
# 9. 📊 Get Fundamental Company Data (XML)
uv run ibkr_mcp/client.py --port 4002 fundamentals --symbol AAPL --type ReportSnapshot
```
## 🛠️ Troubleshooting & Debugging
Connecting to IBKR can be tricky due to TWS settings and network configs. Here is how to debug issues:
### 1. Unified Logging
The server and CLI both output detailed logs to **stderr**.
* **Enable Debug Logs**: Set the environment variable `IBKR_LOG_LEVEL=DEBUG`.
* **In Claude Desktop**: You can view these logs by checking the Claude logs directly (usually at `~/Library/Logs/Claude/mcp.log` on macOS).
### 2. Standalone CLI Testing
Before integrating with Claude, always test your connection using the built-in CLI:
```bash
# Test connection and fetch a price with debug logs enabled
IBKR_LOG_LEVEL=DEBUG uv run ibkr_mcp/client.py --port 4002 price --symbol AAPL
```
### 3. TWS API Settings
If you get "Connection Refused":
* Ensure **TWS/Gateway** is running.
* Go to **Settings > API > Settings** in TWS.
* Verify **"Enable ActiveX and Socket Clients"** is checked.
* Verify your **Port** matches your `IBKR_PORT` (default 4002 for Paper, 7496 for Live).
* Ensure **"Allow connections from localhost only"** is checked (or add your IP to trusted IPs).
### 4. Interactive Debugging (Inspector)
Use the MCP Inspector to see the JSON-RPC traffic and test tools in a sandbox:
```bash
npx -y @modelcontextprotocol/inspector uv run python -m ibkr_mcp
```
### 5. Multi-Client Conflicts
IBKR allows only one connection per `Client ID`. This server uses `client_id=1` by default. If you have another application (like a TradingView bridge or custom script) using ID 1, this server will fail to connect.
---
*Built via [FastMCP](https://github.com/FastMCP/FastMCP) and [ib_insync](https://github.com/erdewit/ib_insync).*
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
valuecell
Valuecell is a Python project for efficient data management.
hexstrike-ai
HexStrike AI is an AI-powered MCP cybersecurity automation platform with 150+ tools.
AP2
AP2 provides code samples and demos for the Agent Payments Protocol.
YC-Killer
YC-Killer is an AI agents library by Singularity Research, open-sourcing...
tradingview-mcp
TradingView MCP Server offers real-time market analysis for crypto and stocks.
tradingview-mcp
AI-assisted TradingView chart analysis — connect Claude Code to your...