Metadata-Version: 2.4
Name: iflow-mcp_gaochx_ibkr-mcp-server
Version: 0.1.0
Summary: Interactive Brokers MCP Server for account management, trading operations, and market data
Project-URL: Homepage, https://github.com/yourusername/ibkr-mcp-server
Project-URL: Repository, https://github.com/yourusername/ibkr-mcp-server
Project-URL: Issues, https://github.com/yourusername/ibkr-mcp-server/issues
Author-email: Your Name <your.email@example.com>
License: MIT License
        
        Copyright (c) 2024 IBKR MCP Server
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE. 
License-File: LICENSE
Keywords: api,interactive-brokers,mcp,trading
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Requires-Python: >=3.8
Requires-Dist: asyncio-mqtt>=0.13.0
Requires-Dist: fastmcp>=0.2.0
Requires-Dist: httpx>=0.24.0
Requires-Dist: ib-insync>=0.9.86
Requires-Dist: loguru>=0.7.0
Requires-Dist: mcp>=1.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: rich>=13.0.0
Requires-Dist: typer>=0.9.0
Requires-Dist: uvloop>=0.17.0; sys_platform != 'win32'
Provides-Extra: dev
Requires-Dist: black>=23.0.0; extra == 'dev'
Requires-Dist: flake8>=6.0.0; extra == 'dev'
Requires-Dist: isort>=5.12.0; extra == 'dev'
Requires-Dist: mypy>=1.5.0; extra == 'dev'
Requires-Dist: pre-commit>=3.0.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# IBKR MCP Server

An Interactive Brokers (IBKR) MCP server implementation based on FastMCP 2.0 and MCP StreamableHTTP, providing account management, trading operations, and market data query functionality.

## Features

- 🔗 **Connection Management**: Stable connection with IBKR TWS/Gateway
- 📊 **Account Information**: Query account summary, positions, and balances
- 💹 **Trading Operations**: Place orders, cancel orders, query order status
- 📈 **Market Data**: Real-time and historical market data retrieval
- 🛡️ **Type Safety**: Data validation using Pydantic
- ⚡ **Async Architecture**: High-performance asynchronous I/O operations
- 📝 **Rich Logging**: Structured logging
- 🔧 **Flexible Configuration**: Support for environment variables and configuration files

## Installation

### Install from Source

```bash
git clone https://github.com/yourusername/ibkr-mcp-server.git
cd ibkr-mcp-server

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install the package
pip install -e .
```

### Development Setup

```bash
# Install development dependencies
pip install -e ".[dev]"

# Setup pre-commit hooks
pre-commit install
```

## Quick Start

### 1. Configure Environment

Create a `.env` file in the project root:

```env
# MCP Server Settings
MCP__HOST=0.0.0.0
MCP__PORT=8080

# IBKR Connection Settings
IBKR__HOST=127.0.0.1
IBKR__PORT=4002
IBKR__CLIENT_ID=1
IBKR__READONLY=false

# Logging Settings
LOGGING__LEVEL=INFO
```

### 2. Test Connection

```bash
# Test IBKR connection
python -m ibkr_mcp_server.cli test --host 127.0.0.1 --port 4002
```

### 3. Start Server

```bash
# Start server
python -m ibkr_mcp_server.cli serve

# Or with custom parameters
python -m ibkr_mcp_server.cli serve --host 0.0.0.0 --port 8080
```

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `MCP__HOST` | `0.0.0.0` | MCP server listen address |
| `MCP__PORT` | `8080` | MCP server port |
| `IBKR__HOST` | `127.0.0.1` | IBKR TWS/Gateway address |
| `IBKR__PORT` | `4002` | IBKR TWS/Gateway port |
| `IBKR__CLIENT_ID` | `1` | IBKR client ID |
| `IBKR__READONLY` | `false` | Read-only mode |
| `LOGGING__LEVEL` | `INFO` | Logging level |

### IBKR Port Configuration

| Platform | Demo Port | Live Port |
|----------|-----------|-----------|
| TWS | 4002 | 7496 |
| Gateway | 4002 | 4001 |

## MCP Tools

The server provides 9 MCP tools:

### Account Management

- `get_account_summary`: Get account summary information
- `get_positions`: Get position information

### Trading Operations

- `place_order`: Place an order
- `cancel_order`: Cancel an order
- `get_open_orders`: Get open orders

### Market Data

- `get_market_data`: Get real-time market data
- `get_historical_data`: Get historical data

### Connection Management

- `connection_status`: Check connection status
- `reconnect`: Reconnect to IBKR

## Usage Examples

### Place Order

```json
{
    "tool": "place_order",
    "arguments": {
        "contract": {
            "symbol": "AAPL",
            "sec_type": "STK",
            "exchange": "SMART",
            "currency": "USD"
        },
        "order": {
            "action": "BUY",
            "total_quantity": 100,
            "order_type": "LMT",
            "lmt_price": 150.0
        }
    }
}
```

### Get Positions

```json
{
    "tool": "get_positions",
    "arguments": {}
}
```

### Get Historical Data

```json
{
    "tool": "get_historical_data",
    "arguments": {
        "contract": {
            "symbol": "AAPL",
            "sec_type": "STK",
            "exchange": "SMART",
            "currency": "USD"
        },
        "duration": "1 D",
        "bar_size": "1 min"
    }
}
```

## Architecture

```
┌─────────────────────┐
│   MCP Client        │
│ (Claude Desktop,    │
│  Custom Client)     │
└─────────┬───────────┘
          │ HTTP/WebSocket
┌─────────┴───────────┐
│   FastMCP Server    │
│ (MCP Protocol Layer)│
├─────────────────────┤
│   IBKR MCP Server   │
│ (Business Logic)    │
├─────────────────────┤
│   IBKR Client       │
│ (API Wrapper)       │
└─────────┬───────────┘
          │ TWS API
┌─────────┴───────────┐
│   TWS/Gateway       │
│ (IBKR Platform)     │
└─────────────────────┘
```

## Development

### Project Structure

```
src/ibkr_mcp_server/
├── __init__.py          # Package initialization
├── server.py            # MCP server implementation
├── client.py            # IBKR client wrapper
├── models.py            # Data models
├── config.py            # Configuration management
├── exceptions.py        # Exception definitions
└── cli.py              # Command line interface
```

### Code Standards

- Use `black` for code formatting
- Use `isort` for import sorting
- Use `flake8` for code linting
- Use `mypy` for type checking

### Testing

```bash
# Run tests
pytest

# Generate coverage report
pytest --cov=src --cov-report=html
```

## Deployment

### Docker Deployment

```bash
# Build image
docker build -t ibkr-mcp-server .

# Run container
docker run -p 8080:8080 --env-file .env ibkr-mcp-server
```

### Docker Compose

```bash
# Start services
docker-compose up -d

# View logs
docker-compose logs -f
```

## Integration with Claude Desktop

Add to your Claude Desktop MCP configuration:

```json
{
  "mcpServers": {
    "ibkr": {
      "command": "python",
      "args": ["-m", "ibkr_mcp_server.cli", "serve"],
      "env": {
        "IBKR__HOST": "127.0.0.1",
        "IBKR__PORT": "4002",
        "IBKR__CLIENT_ID": "1"
      }
    }
  }
}
```

## Important Notes

1. **TWS/Gateway**: Ensure IBKR TWS or Gateway is running with API connection enabled
2. **Port Configuration**: Make sure TWS/Gateway API port matches your configuration
3. **Permissions**: Ensure your account has appropriate trading permissions
4. **Risk Management**: Please implement proper risk controls in production environments
5. **Market Data**: Some market data may require subscriptions

## Troubleshooting

### Common Issues

1. **Connection Failed**: Check if TWS/Gateway is running and API is enabled
2. **Client ID Conflict**: Use different client IDs for multiple connections
3. **Port Issues**: Verify the correct port for your TWS/Gateway setup
4. **Market Data Errors**: Ensure you have proper market data subscriptions

### Logging

Enable debug logging for troubleshooting:

```bash
LOGGING__LEVEL=DEBUG python -m ibkr_mcp_server.cli serve
```

## License

MIT License - see [LICENSE](LICENSE) file for details

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## Support

If you encounter any issues, please file an [Issue](https://github.com/yourusername/ibkr-mcp-server/issues).

---

**中文文档**: [README_zh_CN.md](README_zh_CN.md) 