🚀 Interactive Brokers API Project
This project offers an interface to the Interactive Brokers API using the Model Context Protocol (MCP). It's designed to provide a modern and flexible way to interact with IB's services, leveraging the Web API for better long - term stability and support.
🚀 Quick Start
Prerequisites
- Docker Desktop installed on your machine.
- An Interactive Brokers account.
Steps
- Clone the repository and set up the environment:
git clone https://github.com/rcontesti/IB_MCP.git
cd IB_MCP
cp.env.example.env
docker compose up --build -d
- Authenticate with your IB account:
After the image is up and running, navigate to
https://{GATEWAY_BASE_URL}:{GATEWAY_PORT} (e.g., https://localhost:5055/) to login. You can also find the login path in the logs of the API gateway container. If successful, you'll be redirected to a URL that reads: "Client login succeeds".
- Configure VS Code:
Add the MCP server config file to your VS Code
settings.json. Given the following environment parameters:MCP_SERVER_HOST=0.0.0.0
MCP_SERVER_PORT=5002
MCP_SERVER_PATH=/mcp
MCP_TRANSPORT_PROTOCOL=streamable - http
The VS Code MCP server snippet in settings.json would be:{
...
},
"chat.mcp.discovery.enabled": true,
"mcp": {
"inputs": [],
"servers": {
"time": {
"command": "docker",
"args": ["run", "-i", "--rm", "mcp/time"]
},
"ib - web": {
"type": "http",
"url": "http://localhost:5002/mcp/",
}
}
},
"workbench.colorTheme": "Tomorrow Night Blue"
}
Alternatively, create a .vscode/mcp.json file at the root of your project with the following content:{
"servers": {
"ib - mcp - server": {
"type": "http",
"url": "http://localhost:5002/mcp/"
}
},
"inputs": []
}
Check [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp - servers) for more information.
- Start the MCP in Copilot
✨ Features
- Built on IB Web API: This project uses the official Interactive Brokers Web API, avoiding third - party dependencies and ensuring long - term stability.
- Dockerized Setup: All components are containerized, making it easy to deploy and manage.
- MCP Integration: Provides an interface using the Model Context Protocol (MCP).
📦 Installation
Docker Desktop Setup
See a quick walkthrough in YOUTUBE
- Clone the repo, set env variables and build the images
git clone https://github.com/rcontesti/IB_MCP.git
cd IB_MCP
cp.env.example.env
docker compose up --build -d
- Auth with your IB account and credentials
After the image is up and running, navigate to
https://{GATEWAY_BASE_URL}:{GATEWAY_PORT} (e.g., https://localhost:5055/) to login. You can find the login path in the logs of the API gateway container. If successful, you'll be redirected to a URL that reads: "Client login succeeds".
- Add the MCP server config file to your VS Code
settings.json
Given the environment parameters:MCP_SERVER_HOST=0.0.0.0
MCP_SERVER_PORT=5002
MCP_SERVER_PATH=/mcp
MCP_TRANSPORT_PROTOCOL=streamable - http
The VS Code MCP server snippet in settings.json would be:{
...
},
"chat.mcp.discovery.enabled": true,
"mcp": {
"inputs": [],
"servers": {
"time": {
"command": "docker",
"args": ["run", "-i", "--rm", "mcp/time"]
},
"ib - web": {
"type": "http",
"url": "http://localhost:5002/mcp/",
}
}
},
"workbench.colorTheme": "Tomorrow Night Blue"
}
Alternatively, create a .vscode/mcp.json file at the root of your project with the following content:{
"servers": {
"ib - mcp - server": {
"type": "http",
"url": "http://localhost:5002/mcp/"
}
},
"inputs": []
}
Check [Use MCP servers in VS Code (Preview)](https://code.visualstudio.com/docs/copilot/chat/mcp - servers) for more details.
- Start the MCP in Copilot
Limitations of Multi - Container Setup
- Users must log in through the browser on the same machine as Client Portal Gateway for authentication.
- All API Endpoint calls must be made on the same machine where the Client Portal Gateway was authenticated.
- None of the endpoints beginning with /gw/api, /oauth, or /oauth2 are supported for use in the Client Portal Gateway.
Session Management
The additional /iserver/auth/ssodh/init endpoint is used to reopen a brokerage session with the backend, through which you can access the protected /iserver endpoints. Sessions will time out after approximately 6 minutes without sending new requests or maintaining the /tickle endpoint at least every 5 minutes. To prevent session timeout, call the /tickle endpoint regularly, preferably every minute. If the brokerage session has timed out but the session is still connected to the IBKR backend, the response to /auth/status returns ‘connected’:true and ‘authenticated’:false. Calling the /iserver/auth/ssodh/init endpoint will initialize a new brokerage session.
💻 Usage Examples
Basic Usage
git clone https://github.com/rcontesti/IB_MCP.git
cd IB_MCP
cp.env.example.env
docker compose up --build -d
Advanced Usage
{
"servers": {
"ib - mcp - server": {
"type": "http",
"url": "http://localhost:5002/mcp/"
}
},
"inputs": []
}
📚 Documentation
TWS vs WEB comparison
TWS API (Trader Workstation API)
The legacy, powerful API. It's extremely powerful, fast, and feature - rich, but it's also more complex and requires you to run the TWS desktop software or the IB Gateway on a machine continuously.
Web API (Client Portal API)
The modern, developer - friendly RESTful API. It's much easier to use, works over standard HTTPS, and is standalone (no desktop software needed). However, it is less performant and has fewer features than the TWS API.
Comparison Table
| Feature |
TWS API |
Web API (Client Portal API) |
| Technology |
TCP/IP Socket, Proprietary binary protocol |
RESTful, HTTPS, JSON format |
| Dependency |
Requires TWS or IB Gateway to be running |
Standalone (does not require TWS/Gateway) |
| Ease of Use |
Steep learning curve, complex |
Much easier, standard for web developers |
| Performance |
Very high speed, low latency. Ideal for high - frequency data and fast order execution. |
Slower due to HTTPS overhead. Not for HFT. |
| Functionality |
Extremely comprehensive. Access to virtually every feature in TWS, including complex order types, combos, algos, etc. |
More limited. Covers core trading, portfolio, and market data, but lacks the most advanced features. |
| Data Streaming |
Robust, high - frequency streaming for market data, account updates, etc. |
Supports streaming via a WebSocket connection (/ws). |
| Historical Data |
Very deep and extensive access to historical data. |
Good access, but can be more limited in scope and request frequency. |
| Authentication |
Connects directly to an authenticated TWS/Gateway session. |
Modern OAuth - based authentication. More secure for web apps but requires a more complex initial setup. |
| Ideal Use Cases |
Algorithmic trading, custom trading desktops, high - frequency strategies, complex options analysis. |
Web dashboards, mobile apps, portfolio analysis tools, simple trading bots, reporting. |
| Community/Libraries |
Very mature. Many third - party libraries in Python, Java, C#, C++, etc. |
Newer, but growing. Easy to use with any language that can make HTTP requests. |
Which One Should You Choose?
Choose the TWS API if:
- You are building a serious, automated algorithmic trading system.
- Your strategy is latency - sensitive.
- You need to place complex order types like options spreads, combos, or use IBKR's built - in algos.
- You are building a custom, feature - rich desktop trading application.
- You are comfortable with the operational overhead of running the IB Gateway 24/7.
Choose the Web API (Client Portal API) if:
- You are building a web dashboard or mobile app to monitor your portfolio.
- You want to build a simple trading bot for executing basic orders (e.g., "buy 100 shares of AAPL when it hits $150").
- You are building a reporting or analytics tool.
- Development speed and ease of use are more important than raw performance or access to every single feature.
- You cannot or do not want to run a dedicated TWS/Gateway instance.
🔧 Technical Details
Architecture
The project consists of 4 main components:
- api_gateway: Runs the Interactive Brokers Client Portal Gateway in a Docker container to enable secure access to the IB REST API.
- ticker_service: Maintains the Interactive Brokers session by periodically calling the
/tickle endpoint to prevent session timeouts. This service runs in a Docker container.
- routers_generator: Based on official documentation, it automatically creates FastAPI routers and saves them in the routers directory.
- mcp_server: An MCP server built with FastMCP that interacts with the API gateway by adding the previously generated routers. This service also runs in a Docker container.
📦 Interactive Brokers Client Portal Gateway Docker Container
This Docker container sets up and runs the Interactive Brokers (IB) Client Portal Gateway, which is required for applications to connect via the IB REST API.
🔧 What This Container Does
- Base Image: Uses
eclipse - temurin:21 (Java 21) for compatibility with the IB Gateway.
- Installs Dependencies: Installs
unzip for extracting the gateway archive.
- Downloads Gateway: Fetches the latest version of the Client Portal Gateway from the official Interactive Brokers source and unzips it.
- Configuration:
- Copies a custom
conf.yaml into the expected path (gateway/root/conf.yaml) to configure the gateway.
- Adds a custom
run_gateway.sh script as the container entrypoint.
- Port Exposure: Exposes port
5055 (default port used by the gateway). Override as needed in .env.
- Startup Command: Runs the gateway using the configuration file.
📦 Interactive Brokers Routers Generator Docker Container [WIP]
Routers are currently manually developed as the official Open Api Json file fails validations. See [Future Work](#future - work) and [Endpoints Status](#endpoints - status)
📦 IB MCP Server Docker Container
This Docker container sets up and runs the Interactive Brokers (IB) Model Context Protocol (MCP) Server, which provides an interface for interacting with the IB API gateway.
🔧 What This Container Does
- Base Image: Uses
ghcr.io/astral - sh/uv:python3.11 - bookworm - slim for a lightweight Python 3.11 environment with uv.
- Installs Dependencies: Installs
curl for system dependencies and uses uv sync to install Python dependencies from pyproject.toml.
- Configuration: Copies the
pyproject.toml and the entire mcp_server directory into the container. Sets PYTHONPATH to /app and UV_CACHE_DIR to /tmp/uv - cache.
- Port Exposure: Exposes the port specified by the
MCP_SERVER_PORT environment variable (e.g., 5002).
- Startup Command: Runs the FastAPI server using
uv run -- python /app/mcp_server/fastapi_server.py.
Endpoints Status
Endpoints are currently manually built. 👉 See the full list of API Endpoints Staus
Future Work
- Automatically generate endpoints: Currently, the [IB REST API (2.16.0) OpenAPI specification](https://api.ibkr.com/gw/api/v3/api - docs) fails validation, with 351 errors. Automated router generation is not feasible at this time, and routers are being built manually.
- Add OAuth: Incorporate OAuth authentication for enhanced security.
References
- [IB WEB API Reference](https://www.interactivebrokers.com/campus/ibkr - api - page/webapi - ref/)
- [IB WEB API openapi docs](https://api.ibkr.com/gw/api/v3/api - docs) Outdated!
- [IB WEB API Reference page](https://www.interactivebrokers.com/campus/ibkr - api - page/cpapi - v1/#introduction)
- FAST MCP
- FAST MCP Documentation
- FAST MCP openapi integration
- ibeam
- [fastapi - codegen](https://github.com/koxudaxi/fastapi - code - generator)
- [openapi spec validator repo](https://github.com/python - openapi/openapi - spec - validator)
- [openapi spec validator docs](https://openapi - spec - validator.readthedocs.io/en/latest/python.html)
Contributing
We welcome contributions to this project! If you'd like to contribute, please follow these guidelines:
- Fork the repository and create your branch from
main.
- Report bugs by opening an issue with a clear description and steps to reproduce.
- Suggest features by opening an issue to discuss your ideas.
- Submit pull requests for bug fixes, new features, or improvements. Please ensure your code adheres to the existing style, includes relevant tests, and has clear commit messages.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.