ib-mcp


Nameib-mcp JSON
Version 0.2.6 PyPI version JSON
download
home_pagehttps://github.com/Hellek1/ib-mcp
SummaryModel Context Protocol (MCP) server exposing Interactive Brokers data via ib_async + FastMCP
upload_time2025-08-27 13:19:46
maintainerNone
docs_urlNone
authorDavid Hellekalek
requires_python<4.0,>=3.12
licenseBSD-3-Clause
keywords interactive-brokers ib ibapi tws asyncio mcp fastmcp llm
VCS
bugtrack_url
requirements ib_async fastmcp defusedxml
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # IB Async MCP Server

[![CI](https://github.com/Hellek1/ib-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/Hellek1/ib-mcp/actions/workflows/ci.yml)

Lightweight Model Context Protocol (MCP) server exposing read-only Interactive Brokers data (contracts, historical data, fundamentals, news, portfolio, account) via the asynchronous [`ib_async`](https://ib-api-reloaded.github.io/ib_async/) library and [`FastMCP`](https://github.com/modelcontextprotocol/fastmcp). Ideal for feeding financial data into LLM workflows and autonomous agents while keeping trading disabled.

## Overview

This directory contains an MCP (Model Context Protocol) server that wraps the ib_async library to allow LLMs to interact with Interactive Brokers data.

## Features

The MCP server provides the following tools for LLM interaction:

### 1. Contract Lookup and Conversion
- **lookup_contract**: Look up contract details by ticker symbol and optional exchange/currency
- **ticker_to_conid**: Convert ticker symbol to contract ID (conid)

### 2. Market Data
- **get_historical_data**: Retrieve historical market data with configurable duration, bar size, and data type

### 3. News
- **get_news**: Retrieve current news articles for a contract
- **get_historical_news**: Retrieve historical news articles within a date range

### 4. Fundamental Data
- **get_fundamental_data**: Retrieve fundamental data including financial summaries, ownership, financial statements, and more

### 5. Portfolio and Account Information
- **get_portfolio**: Retrieve portfolio positions and details
- **get_account_summary**: Retrieve account summary information
- **get_positions**: Retrieve current positions

## Prerequisites

1. **Interactive Brokers Account**: You need an active IB account
2. **IB Gateway or TWS**: Download and install either:
   - [IB Gateway (Stable)](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) - Recommended for API-only use
   - [IB Gateway (Latest)](https://www.interactivebrokers.com/en/trading/ibgateway-latest.php) - Latest features
   - [Trader Workstation (TWS)](https://www.interactivebrokers.com/en/trading/tws.php) - Full trading platform

3. **API Configuration**:
   - Enable API access in TWS/Gateway: `Configure → API → Settings` and check "Enable ActiveX and Socket Clients"
   - Set appropriate port (default: 7497 for TWS, 4001 for Gateway)
   - Add `127.0.0.1` to trusted IPs if connecting locally

## Installation

### From source (development)
```bash
git clone https://github.com/Hellek1/ib-mcp.git
cd ib-mcp
pip install poetry
poetry install
```

## Usage

### Running the MCP Server

```bash
# Using default settings (TWS on localhost:7497)
poetry run ib-mcp-server

# Custom IB Gateway connection
poetry run ib-mcp-server --host 127.0.0.1 --port 4001 --client-id 1

# Help with all options
poetry run ib-mcp-server --help
```

### Command Line Options

- `--host`: IB Gateway/TWS host (default: 127.0.0.1)
- `--port`: IB Gateway/TWS port (default: 7497 for TWS, use 4001 for Gateway)
- `--client-id`: Unique client ID for the connection (default: 1)

You can also use environment variables instead of flags:

- `IB_HOST`
- `IB_PORT`
- `IB_CLIENT_ID`

Flags override environment variables if both are provided.

## Docker

### Build

```bash
docker build -t ib-mcp .
```

### Run (connect to TWS running on host)

On macOS/Windows Docker Desktop you can reach host via `host.docker.internal` (already the default):

```bash
docker run --rm -it \
   -e IB_HOST=host.docker.internal \
   -e IB_PORT=7497 \
   -e IB_CLIENT_ID=1 \
   ghcr.io/hellek1/ib-mcp
```

On Linux you may need to add `--add-host host.docker.internal:host-gateway` and ensure the TWS/Gateway port is accessible:

```bash
docker run --rm -it \
   --add-host host.docker.internal:host-gateway \
   -e IB_HOST=host.docker.internal \
   -e IB_PORT=7497 \
   ghcr.io/hellek1/ib-mcp
```

Override arguments directly if preferred:

```bash
docker run --rm -it ghcr.io/hellek1/ib-mcp --host host.docker.internal --port 4001 --client-id 2
```


### MCP Client Integration

The server communicates via stdio using the MCP protocol. It can be integrated with MCP-compatible tools and LLM applications.

Example MCP client configuration (e.g. Claude Desktop) using Docker:
```json
{
   "mcpServers": {
      "ib-async": {
         "command": "docker",
         "args": [
            "run",
            "--rm",
            "--add-host","host.docker.internal:host-gateway",
            "-e","IB_HOST=host.docker.internal",
            "-e","IB_PORT=7497",
            "-e","IB_CLIENT_ID=1",
            "ghcr.io/hellek1/ib-mcp:latest"
         ]
      }
   }
}
```

Notes:
1. Remove the `--add-host` line on macOS/Windows Docker Desktop (it's only needed on Linux).

## Available Tools

### Contract Lookup
```
lookup_contract(symbol, sec_type="STK", exchange="SMART", currency="USD")
ticker_to_conid(symbol, sec_type="STK", exchange="SMART", currency="USD")
```

### Market Data
```
get_historical_data(symbol, duration="1 M", bar_size="1 day", data_type="TRADES", exchange="SMART", currency="USD")
```

### News
```
get_news(symbol, provider_codes="", exchange="SMART", currency="USD")
get_historical_news(symbol, start_date, end_date, provider_codes="", max_count=10, exchange="SMART", currency="USD")
```

### Fundamentals
```
get_fundamental_data(symbol, report_type="ReportsFinSummary", exchange="SMART", currency="USD")
```

Available report types:
- `ReportsFinSummary`: Financial summary
- `ReportsOwnership`: Ownership information
- `ReportsFinStatements`: Financial statements
- `RESC`: Research reports
- `CalendarReport`: Calendar events

### Portfolio & Account
```
get_portfolio(account="")
get_account_summary(account="")
get_positions(account="")
```

## Example Usage

Once connected to an LLM through MCP, you can ask questions like:

- "Look up the contract details for AAPL"
- "Get the last month of daily historical data for TSLA"
- "What are the recent news articles for Microsoft?"
- "Show me the financial summary for Google"
- "What positions do I currently have in my portfolio?"

## Data Formats

### XML to Markdown Conversion

The server automatically converts XML-formatted fundamental data to markdown for better readability in LLM interactions.

### Error Handling

The server includes comprehensive error handling and will provide meaningful error messages when:
- IB connection fails
- Invalid symbols are requested
- Market data is not available
- Authentication issues occur

## Troubleshooting

### Connection Issues

1. **"Cannot connect to Interactive Brokers"**
   - Ensure TWS/Gateway is running
   - Check that API is enabled in settings
   - Verify port numbers match (7497 for TWS, 4001 for Gateway)
   - Check firewall settings

2. **"No contract found"**
   - Verify symbol spelling
   - Try different exchanges (NYSE, NASDAQ vs SMART)
   - Check if security type is correct

3. **"No market data"**
   - Ensure you have appropriate market data subscriptions
   - Check if markets are open for real-time data
   - Try delayed data mode if real-time is not available

### Performance Tips

1. Use specific exchanges when possible instead of "SMART" routing
2. Limit historical data requests to reasonable time ranges
3. Cache contract IDs for frequently accessed symbols

## Security Considerations

- The MCP server operates in read-only mode - no order placement capabilities
- Credentials are handled by the IB Gateway/TWS application
- The server only accesses data you have permission to view in your IB account

## Contributing

1. Fork & branch: `feat/xyz`
2. Install dev deps: `poetry install`
3. Activate pre-commit: `pre-commit install`
4. Run tests: `poetry run pytest -q`
5. Open a PR with a concise description.

### Release (maintainers)
```bash
poetry version patch  # or minor / major
poetry build
poetry publish --username __token__ --password <pypi-token>
git tag v$(poetry version -s)
git push --tags
```

## Support & References

- IB API functionality: [ib_async docs](https://ib-api-reloaded.github.io/ib_async/)
- MCP protocol: [MCP spec](https://spec.modelcontextprotocol.io/)
- Interactive Brokers: [IB API docs](https://ibkrcampus.com/ibkr-api-page/twsapi-doc/)

---

Licensed under the BSD 3-Clause License. Contributions welcome.


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Hellek1/ib-mcp",
    "name": "ib-mcp",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.12",
    "maintainer_email": null,
    "keywords": "interactive-brokers, ib, ibapi, tws, asyncio, mcp, fastmcp, llm",
    "author": "David Hellekalek",
    "author_email": "hellekalek@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/54/eb/94c72f9d08d3da5a81e274599d26b53ed2e7c3776f1d70cf9078892a8144/ib_mcp-0.2.6.tar.gz",
    "platform": null,
    "description": "# IB Async MCP Server\n\n[![CI](https://github.com/Hellek1/ib-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/Hellek1/ib-mcp/actions/workflows/ci.yml)\n\nLightweight Model Context Protocol (MCP) server exposing read-only Interactive Brokers data (contracts, historical data, fundamentals, news, portfolio, account) via the asynchronous [`ib_async`](https://ib-api-reloaded.github.io/ib_async/) library and [`FastMCP`](https://github.com/modelcontextprotocol/fastmcp). Ideal for feeding financial data into LLM workflows and autonomous agents while keeping trading disabled.\n\n## Overview\n\nThis directory contains an MCP (Model Context Protocol) server that wraps the ib_async library to allow LLMs to interact with Interactive Brokers data.\n\n## Features\n\nThe MCP server provides the following tools for LLM interaction:\n\n### 1. Contract Lookup and Conversion\n- **lookup_contract**: Look up contract details by ticker symbol and optional exchange/currency\n- **ticker_to_conid**: Convert ticker symbol to contract ID (conid)\n\n### 2. Market Data\n- **get_historical_data**: Retrieve historical market data with configurable duration, bar size, and data type\n\n### 3. News\n- **get_news**: Retrieve current news articles for a contract\n- **get_historical_news**: Retrieve historical news articles within a date range\n\n### 4. Fundamental Data\n- **get_fundamental_data**: Retrieve fundamental data including financial summaries, ownership, financial statements, and more\n\n### 5. Portfolio and Account Information\n- **get_portfolio**: Retrieve portfolio positions and details\n- **get_account_summary**: Retrieve account summary information\n- **get_positions**: Retrieve current positions\n\n## Prerequisites\n\n1. **Interactive Brokers Account**: You need an active IB account\n2. **IB Gateway or TWS**: Download and install either:\n   - [IB Gateway (Stable)](https://www.interactivebrokers.com/en/trading/ibgateway-stable.php) - Recommended for API-only use\n   - [IB Gateway (Latest)](https://www.interactivebrokers.com/en/trading/ibgateway-latest.php) - Latest features\n   - [Trader Workstation (TWS)](https://www.interactivebrokers.com/en/trading/tws.php) - Full trading platform\n\n3. **API Configuration**:\n   - Enable API access in TWS/Gateway: `Configure \u2192 API \u2192 Settings` and check \"Enable ActiveX and Socket Clients\"\n   - Set appropriate port (default: 7497 for TWS, 4001 for Gateway)\n   - Add `127.0.0.1` to trusted IPs if connecting locally\n\n## Installation\n\n### From source (development)\n```bash\ngit clone https://github.com/Hellek1/ib-mcp.git\ncd ib-mcp\npip install poetry\npoetry install\n```\n\n## Usage\n\n### Running the MCP Server\n\n```bash\n# Using default settings (TWS on localhost:7497)\npoetry run ib-mcp-server\n\n# Custom IB Gateway connection\npoetry run ib-mcp-server --host 127.0.0.1 --port 4001 --client-id 1\n\n# Help with all options\npoetry run ib-mcp-server --help\n```\n\n### Command Line Options\n\n- `--host`: IB Gateway/TWS host (default: 127.0.0.1)\n- `--port`: IB Gateway/TWS port (default: 7497 for TWS, use 4001 for Gateway)\n- `--client-id`: Unique client ID for the connection (default: 1)\n\nYou can also use environment variables instead of flags:\n\n- `IB_HOST`\n- `IB_PORT`\n- `IB_CLIENT_ID`\n\nFlags override environment variables if both are provided.\n\n## Docker\n\n### Build\n\n```bash\ndocker build -t ib-mcp .\n```\n\n### Run (connect to TWS running on host)\n\nOn macOS/Windows Docker Desktop you can reach host via `host.docker.internal` (already the default):\n\n```bash\ndocker run --rm -it \\\n   -e IB_HOST=host.docker.internal \\\n   -e IB_PORT=7497 \\\n   -e IB_CLIENT_ID=1 \\\n   ghcr.io/hellek1/ib-mcp\n```\n\nOn Linux you may need to add `--add-host host.docker.internal:host-gateway` and ensure the TWS/Gateway port is accessible:\n\n```bash\ndocker run --rm -it \\\n   --add-host host.docker.internal:host-gateway \\\n   -e IB_HOST=host.docker.internal \\\n   -e IB_PORT=7497 \\\n   ghcr.io/hellek1/ib-mcp\n```\n\nOverride arguments directly if preferred:\n\n```bash\ndocker run --rm -it ghcr.io/hellek1/ib-mcp --host host.docker.internal --port 4001 --client-id 2\n```\n\n\n### MCP Client Integration\n\nThe server communicates via stdio using the MCP protocol. It can be integrated with MCP-compatible tools and LLM applications.\n\nExample MCP client configuration (e.g. Claude Desktop) using Docker:\n```json\n{\n   \"mcpServers\": {\n      \"ib-async\": {\n         \"command\": \"docker\",\n         \"args\": [\n            \"run\",\n            \"--rm\",\n            \"--add-host\",\"host.docker.internal:host-gateway\",\n            \"-e\",\"IB_HOST=host.docker.internal\",\n            \"-e\",\"IB_PORT=7497\",\n            \"-e\",\"IB_CLIENT_ID=1\",\n            \"ghcr.io/hellek1/ib-mcp:latest\"\n         ]\n      }\n   }\n}\n```\n\nNotes:\n1. Remove the `--add-host` line on macOS/Windows Docker Desktop (it's only needed on Linux).\n\n## Available Tools\n\n### Contract Lookup\n```\nlookup_contract(symbol, sec_type=\"STK\", exchange=\"SMART\", currency=\"USD\")\nticker_to_conid(symbol, sec_type=\"STK\", exchange=\"SMART\", currency=\"USD\")\n```\n\n### Market Data\n```\nget_historical_data(symbol, duration=\"1 M\", bar_size=\"1 day\", data_type=\"TRADES\", exchange=\"SMART\", currency=\"USD\")\n```\n\n### News\n```\nget_news(symbol, provider_codes=\"\", exchange=\"SMART\", currency=\"USD\")\nget_historical_news(symbol, start_date, end_date, provider_codes=\"\", max_count=10, exchange=\"SMART\", currency=\"USD\")\n```\n\n### Fundamentals\n```\nget_fundamental_data(symbol, report_type=\"ReportsFinSummary\", exchange=\"SMART\", currency=\"USD\")\n```\n\nAvailable report types:\n- `ReportsFinSummary`: Financial summary\n- `ReportsOwnership`: Ownership information\n- `ReportsFinStatements`: Financial statements\n- `RESC`: Research reports\n- `CalendarReport`: Calendar events\n\n### Portfolio & Account\n```\nget_portfolio(account=\"\")\nget_account_summary(account=\"\")\nget_positions(account=\"\")\n```\n\n## Example Usage\n\nOnce connected to an LLM through MCP, you can ask questions like:\n\n- \"Look up the contract details for AAPL\"\n- \"Get the last month of daily historical data for TSLA\"\n- \"What are the recent news articles for Microsoft?\"\n- \"Show me the financial summary for Google\"\n- \"What positions do I currently have in my portfolio?\"\n\n## Data Formats\n\n### XML to Markdown Conversion\n\nThe server automatically converts XML-formatted fundamental data to markdown for better readability in LLM interactions.\n\n### Error Handling\n\nThe server includes comprehensive error handling and will provide meaningful error messages when:\n- IB connection fails\n- Invalid symbols are requested\n- Market data is not available\n- Authentication issues occur\n\n## Troubleshooting\n\n### Connection Issues\n\n1. **\"Cannot connect to Interactive Brokers\"**\n   - Ensure TWS/Gateway is running\n   - Check that API is enabled in settings\n   - Verify port numbers match (7497 for TWS, 4001 for Gateway)\n   - Check firewall settings\n\n2. **\"No contract found\"**\n   - Verify symbol spelling\n   - Try different exchanges (NYSE, NASDAQ vs SMART)\n   - Check if security type is correct\n\n3. **\"No market data\"**\n   - Ensure you have appropriate market data subscriptions\n   - Check if markets are open for real-time data\n   - Try delayed data mode if real-time is not available\n\n### Performance Tips\n\n1. Use specific exchanges when possible instead of \"SMART\" routing\n2. Limit historical data requests to reasonable time ranges\n3. Cache contract IDs for frequently accessed symbols\n\n## Security Considerations\n\n- The MCP server operates in read-only mode - no order placement capabilities\n- Credentials are handled by the IB Gateway/TWS application\n- The server only accesses data you have permission to view in your IB account\n\n## Contributing\n\n1. Fork & branch: `feat/xyz`\n2. Install dev deps: `poetry install`\n3. Activate pre-commit: `pre-commit install`\n4. Run tests: `poetry run pytest -q`\n5. Open a PR with a concise description.\n\n### Release (maintainers)\n```bash\npoetry version patch  # or minor / major\npoetry build\npoetry publish --username __token__ --password <pypi-token>\ngit tag v$(poetry version -s)\ngit push --tags\n```\n\n## Support & References\n\n- IB API functionality: [ib_async docs](https://ib-api-reloaded.github.io/ib_async/)\n- MCP protocol: [MCP spec](https://spec.modelcontextprotocol.io/)\n- Interactive Brokers: [IB API docs](https://ibkrcampus.com/ibkr-api-page/twsapi-doc/)\n\n---\n\nLicensed under the BSD 3-Clause License. Contributions welcome.\n\n",
    "bugtrack_url": null,
    "license": "BSD-3-Clause",
    "summary": "Model Context Protocol (MCP) server exposing Interactive Brokers data via ib_async + FastMCP",
    "version": "0.2.6",
    "project_urls": {
        "Documentation": "https://github.com/Hellek1/ib-mcp#readme",
        "Homepage": "https://github.com/Hellek1/ib-mcp",
        "Repository": "https://github.com/Hellek1/ib-mcp"
    },
    "split_keywords": [
        "interactive-brokers",
        " ib",
        " ibapi",
        " tws",
        " asyncio",
        " mcp",
        " fastmcp",
        " llm"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "bcebd1c5fbc5630691c18af18308420fce9408a4f0ce7f61d4a4fed509c6cb0f",
                "md5": "12ae23a45c1fde26d563d2dbf1fb73d5",
                "sha256": "fc8c51401971f47c383daeaeb5d164b2e75b3190a4ad5398790d11d3fb751741"
            },
            "downloads": -1,
            "filename": "ib_mcp-0.2.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "12ae23a45c1fde26d563d2dbf1fb73d5",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.12",
            "size": 12134,
            "upload_time": "2025-08-27T13:19:45",
            "upload_time_iso_8601": "2025-08-27T13:19:45.990378Z",
            "url": "https://files.pythonhosted.org/packages/bc/eb/d1c5fbc5630691c18af18308420fce9408a4f0ce7f61d4a4fed509c6cb0f/ib_mcp-0.2.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "54eb94c72f9d08d3da5a81e274599d26b53ed2e7c3776f1d70cf9078892a8144",
                "md5": "42939acd32909ac626e15070eda29860",
                "sha256": "6567eae307c4f9f061313c1dc511df2bd699aa553915e42943b02c3be2c65c63"
            },
            "downloads": -1,
            "filename": "ib_mcp-0.2.6.tar.gz",
            "has_sig": false,
            "md5_digest": "42939acd32909ac626e15070eda29860",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.12",
            "size": 14474,
            "upload_time": "2025-08-27T13:19:46",
            "upload_time_iso_8601": "2025-08-27T13:19:46.972868Z",
            "url": "https://files.pythonhosted.org/packages/54/eb/94c72f9d08d3da5a81e274599d26b53ed2e7c3776f1d70cf9078892a8144/ib_mcp-0.2.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-27 13:19:46",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Hellek1",
    "github_project": "ib-mcp",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "ib_async",
            "specs": [
                [
                    ">=",
                    "2.0.1"
                ]
            ]
        },
        {
            "name": "fastmcp",
            "specs": [
                [
                    ">=",
                    "2.11.0"
                ]
            ]
        },
        {
            "name": "defusedxml",
            "specs": [
                [
                    ">=",
                    "0.7.1"
                ]
            ]
        }
    ],
    "lcname": "ib-mcp"
}
        
Elapsed time: 1.21425s