A sophisticated multi-agent financial trading system that integrates Interactive Brokers (IBKR) API with Python analytics, web search capabilities, and intelligent routing. The system provides specialized agents for different aspects of financial analysis and trading.
- Multi-Agent Architecture: Specialized agents for different financial tasks
- IBKR Integration: Direct connection to Interactive Brokers for real-time data and trading
- Python Analytics: Execute Python code for quantitative analysis and visualizations
- Web Search: Access to market news and research via Brave Search
- Intelligent Routing: Automatic selection of the best agent for your queries
- Financial Analyst - Market analysis, stock performance, volatility assessment
- Portfolio Manager - Portfolio optimization, rebalancing, performance reports
- Trading Advisor - Trading recommendations, entry/exit points, risk management
- Python Analyst - Quantitative analysis, backtesting, custom calculations
- Router - Automatically selects the best agent for your query
Download and Install IB Gateway or TWS:
- Visit Interactive Brokers
- Download either:
- IB Gateway (recommended for API access) - lightweight, API-focused
- Trader Workstation (TWS) - full trading platform
Configure API Access:
- Launch IB Gateway or TWS
- Log in with your IBKR credentials
- Go to Configure → Settings → API → Settings
- Enable "Enable ActiveX and Socket Clients"
- Add
127.0.0.1to trusted IP addresses - Set socket port:
- IB Gateway:
4001(live) or4002(paper) - TWS:
7497(paper) or7496(live)
- IB Gateway:
- Important: For testing, use paper trading account
Paper Trading Account:
- Create a paper trading account at IBKR Paper Trading
- This allows testing without real money
Install UV (Python Package Manager):
# Install UV
curl -LsSf https://astral.sh/uv/install.sh | sh
# Restart terminal or source your shell profile
source ~/.bashrc # or ~/.zshrcCreate Project Directory:
mkdir ibkr-trading-agent
cd ibkr-trading-agentCreate the following files in your project directory:
fs_agent.py- Main agent applicationibkr_fast_mcp_server.py- IBKR MCP serverbrave_mcp_server.py- Brave search MCP serverfastagent.config.yaml- Configuration filerequirements.txt- Python dependencies
Create requirements.txt:
fast-agent-mcp
fastmcp
ibapi
pydantic
pydantic-settings
aiohttp
requests
anthropicInstall with UV:
# Create virtual environment and install dependencies
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv pip install -r requirements.txt
# Install additional MCP tools
uvx install mcp-python-interpreter# Install Deno
curl -fsSL https://deno.land/x/install/install.sh | sh
# Add to PATH (add to ~/.bashrc or ~/.zshrc)
export PATH="$HOME/.deno/bin:$PATH"Create fastagent.config.yaml:
# MCP Capabilities
capabilities:
elicitation: {}
# Global API Key (replace with your Anthropic API key)
api_key: "your-anthropic-api-key-here"
mcp:
servers:
ibkr:
command: "uv"
args: ["run", "fastmcp", "run", "ibkr_fast_mcp_server.py"]
elicitation:
mode: "auto_cancel"
brave_search:
command: "uv"
args: ["run", "fastmcp", "run", "brave_mcp_server.py"]
elicitation:
mode: "auto_cancel"
mcp-python-interpreter:
command: "uvx"
args: [
"mcp-python-interpreter",
"--dir",
"/your/working/directory", # Replace with your path
"--python-path",
"/your/working/directory/.venv/bin/python" # Replace with your path
]
env:
MCP_ALLOW_SYSTEM_ACCESS: "0"
elicitation:
mode: "auto_cancel"
# Models
models:
default:
provider: "anthropic"
model: "claude-sonnet-4-20250514"
# Providers
providers:
anthropic:
base_url: "https://api.anthropic.com"
# Global settings
settings:
default_temperature: 0.7
max_retries: 3
mcp_timeout: 30
debug: false
human_input_timeout: 300Get API Keys:
- Anthropic API Key: Get from Anthropic Console
- Brave Search API Key: Get from Brave Search API
Set up environment (optional - can be in config file):
export ANTHROPIC_API_KEY="your-anthropic-key"
export BRAVE_API_KEY="your-brave-search-key"- Launch IB Gateway or TWS
- Log in with your account credentials
- Ensure API settings are configured (see Prerequisites)
- Keep the application running
# Activate virtual environment
source .venv/bin/activate
# Run the agent
uv run fs_agent.py interactiveThe system starts with an intelligent router that automatically selects the best agent for your queries. Simply type your questions:
Example Queries:
Analyze AAPL stock performance and create Python visualizations
What's my current portfolio performance?
Should I buy Tesla stock right now?
Create a Python backtest for a momentum strategy
Get the latest news about the semiconductor sector
Calculate the Sharpe ratio for my current positions
Manual Agent Selection: If you want to use specific agents:
@financial_analyst analyze MSFT trends
@python_analyst create a correlation matrix
@trading_advisor recommend entry points for QQQ
@portfolio_manager rebalance suggestions
Error: "Failed to connect to IBKR"
- Ensure IB Gateway/TWS is running and logged in
- Check API settings are enabled
- Verify ports: 4001 (Gateway) or 7497 (TWS Paper)
- Confirm 127.0.0.1 is in trusted IPs
Market Data Issues:
- Ensure you have market data subscriptions
- Paper trading has limited real-time data
- Some data may be delayed
Module Import Errors:
# Reinstall dependencies
uv pip install --force-reinstall -r requirements.txtMCP Server Errors:
# Check MCP tools installation
uvx list
uvx install mcp-python-interpreterIf you get "prompt too long" errors:
- The router resets context automatically
- Restart the agent to clear accumulated context
- Use specific agents for complex tasks instead of router
ibkr-trading-agent/
├── fs_agent.py # Main agent application
├── ibkr_fast_mcp_server.py # IBKR MCP server
├── brave_mcp_server.py # Brave search server
├── fastagent.config.yaml # Configuration
├── requirements.txt # Dependencies
├── .venv/ # Virtual environment
└── README.md # This file
- Use paper trading accounts for testing
- Never commit API keys to version control
- Keep IB Gateway/TWS updated
- Monitor your positions and orders
- The system can execute real trades if using live accounts
- Anthropic: Varies by plan
- IBKR: ~50 requests per second
- Brave Search: Varies by plan
For issues:
- Check IBKR connection and API settings
- Verify all dependencies are installed
- Check the logs for specific error messages
- Ensure API keys are valid and have sufficient credits
This project is for educational and personal use. Ensure compliance with:
- Interactive Brokers API terms
- Anthropic API terms
- Brave Search API terms
Disclaimer: This software is for educational purposes. Trading involves risk. Always verify trades and use appropriate risk management.