This is a sophisticated AI-powered trading bot that combines multiple machine learning models with real-time Interactive Brokers integration. The bot features continuous learning, web-based monitoring, and comprehensive risk management.
- Traditional ML: Random Forest + Gradient Boosting (Fast, Reliable Pattern Recognition)
- Deep Learning: LSTM Neural Networks (Advanced Temporal Pattern Analysis)
- Large Language Models: Market Sentiment & Context Analysis (Optional)
- โ Real-time IBKR Integration - Connect to Interactive Brokers for live data and trading
- โ Paper Trading Support - Safe testing with IBKR paper trading accounts
- โ Web Dashboard - Real-time monitoring and control interface
- โ Multi-Model AI - Ensemble predictions from multiple AI models
- โ Continuous Learning - Models retrain after market hours
- โ Risk Management - Built-in stop-loss, position sizing, and daily limits
- โ 30+ Technical Indicators - Comprehensive feature engineering
- โ Backtesting - Historical performance validation
- Python 3.8+ installed
- Interactive Brokers account with paper trading enabled
- TWS or IB Gateway downloaded and configured
# Clone or download the repository
cd your-trading-bot-directory
# Install dependencies
pip install -r requirements.txt- Download TWS/IB Gateway from Interactive Brokers
- Login to your paper trading account (account starts with "DU")
- Enable API: Configure โ API โ Settings
- โ Enable ActiveX and Socket Clients
- โ Socket port: 7497 (paper trading)
- โ Add 127.0.0.1 to Trusted IPs
- Apply settings and keep TWS/Gateway running
# Test your IBKR connection
python test_ibkr_connection.pyExpected Output:
โ
Connected to IBKR successfully!
๐ Connected to account: ['DU1234567']
โ
Paper Trading Mode Active
๐ฐ Account Summary:
NetLiquidation: $1,000,000.00
TotalCashValue: $1,000,000.00
BuyingPower: $4,000,000.00
โ
IBKR Setup Test Completed!
Option A: Web Dashboard (Recommended)
python app.py
# Open browser to: http://localhost:5000Option B: IBKR Bot (Terminal)
python ibkr_bot.pyOption C: Launcher Menu
python ibkr_launcher.py
# Interactive menu with all optionstrading-bot/
โโโ README.md # This file
โโโ requirements.txt # Python dependencies
โโโ setup.py # Setup and installation script
โ
โโโ ๐ค Core Bot Files
โโโ bot.py # Original bot (Yahoo Finance + Paper Trading)
โโโ ibkr_bot.py # IBKR-enhanced bot (REAL-TIME DATA)
โโโ app.py # Flask web dashboard
โ
โโโ ๐ง Utility Scripts
โโโ test_ibkr_connection.py # IBKR connection tester
โโโ ibkr_launcher.py # Interactive launcher menu
โ
โโโ ๐จ Web Interface
โโโ templates/
โ โโโ dashboard.html # Web dashboard UI
โ
โโโ ๐ Generated Directories
โโโ models/ # Trained AI models
โโโ logs/ # Application logs
โโโ data/ # Historical data cache
-
Test Connection First:
python test_ibkr_connection.py
-
Start Web Dashboard:
python app.py # Dashboard: http://localhost:5000 -
In Web Dashboard:
- Click "Train Models" (takes 10-15 minutes)
- Click "Start Bot" once training completes
- Monitor performance in real-time
-
Run Original Bot:
python bot.py
-
Or Web Dashboard:
python app.py # Uses Yahoo Finance data with paper trading simulation
# In ibkr_bot.py or bot.py
bot = IBKRTradingBot(
initial_capital=1000,
max_position_size=0.05, # 5% max per trade
stop_loss=0.015, # 1.5% stop loss
take_profit=0.025, # 2.5% take profit
min_confidence=0.75, # Higher confidence threshold
max_daily_trades=2 # Max 2 trades per day
)bot = IBKRTradingBot(
initial_capital=1000,
max_position_size=0.1, # 10% max per trade
stop_loss=0.02, # 2% stop loss
take_profit=0.03, # 3% take profit
min_confidence=0.6, # Standard confidence
max_daily_trades=3 # Max 3 trades per day
)bot = IBKRTradingBot(
initial_capital=1000,
max_position_size=0.15, # 15% max per trade
stop_loss=0.025, # 2.5% stop loss
take_profit=0.04, # 4% take profit
min_confidence=0.5, # Lower confidence threshold
max_daily_trades=5 # Max 5 trades per day
)Access at http://localhost:5000 when running python app.py:
- ๐ Live Performance Charts - P&L and win rate tracking
- ๐ฎ AI Predictions - Current model predictions for all stocks
- ๐ผ Position Management - View and close positions
- ๐ Trade History - Complete trade log with P&L
- ๐ง Model Performance - Training accuracy and metrics
โถ๏ธ Start/Stop Bot - Real-time bot control- ๐ง Train Models - Retrain AI models with latest data
- ๐ Run Backtests - Historical performance testing
- โ๏ธ Real-time Status - Connection and account monitoring
- Random Forest: Pattern recognition and feature importance
- Gradient Boosting: Sequential learning and error correction
- Training Data: 5 years of historical stock data
- Features: 30+ technical indicators (RSI, MACD, Bollinger Bands, etc.)
- Architecture: 3-layer LSTM with dropout and batch normalization
- Lookback: 60-day time series sequences
- Purpose: Capture complex temporal patterns
- Training: Automatic early stopping and learning rate reduction
- Local LLM: Ollama integration for market sentiment
- Cloud LLM: Claude API for advanced market analysis
- Features: News sentiment, market context, qualitative factors
The bot combines all three model types using confidence-weighted averaging for final trading decisions.
- Annual Return: 15-30% (excellent performance)
- Monthly Return: 1-3% (sustainable growth)
- Daily Return: 0.1-0.5% average (realistic expectation)
- Win Rate: 55-65% (professional level)
- Sharpe Ratio: 1.0-2.0 (risk-adjusted returns)
- Max Drawdown: <15% (risk management)
- 3 months: $1000 โ $1150 (15% return) โ Realistic
- 6 months: $1000 โ $1300 (30% return) โ Good Performance
- 12 months: $1000 โ $2000 (100% return)
โ ๏ธ Very Ambitious
Note: The bot's 5% daily return goal is unrealistic. Professional traders achieve 15-30% annually.
- Position Sizing: Maximum 10% of portfolio per trade
- Stop Loss: Automatic 2% stop loss on all positions
- Take Profit: Automatic 3% profit taking
- Daily Limits: Maximum 3 trades per day
- Loss Protection: Stop trading if daily loss > 5%
- Account Verification: Confirms paper trading mode
- Real-time Position Tracking: Monitor all open positions
- Performance Analysis: Daily performance evaluation
- Model Retraining: Weekly model updates with new data
- Risk Alerts: Automatic warnings for unusual behavior
- Performance Analysis: Analyze today's trades and outcomes
- Model Updates: Retrain underperforming models
- Strategy Optimization: Adjust parameters based on results
- Next Day Preparation: Generate predictions for tomorrow
- Comprehensive Retraining: Update all models with latest data
- Performance Review: Analyze weekly trading metrics
- Parameter Adjustment: Optimize risk management settings
- Model Validation: Ensure model accuracy and reliability
โ ๏ธ Paper trade for 30+ days minimumโ ๏ธ Start with small amounts ($100-200, not $1000)โ ๏ธ Monitor closely for first weekโ ๏ธ Understand all risk management featuresโ ๏ธ Keep TWS/Gateway running during market hours
- Yahoo Finance: 15-20 minute delay (good for testing)
- IBKR: Real-time or minimal delay (professional trading)
- Market Hours: Bot works during market hours (9:30 AM - 4:00 PM ET)
- Stable Internet: Critical for real-time trading
- Always-On Computer: Bot needs to run during market hours
- Backup Power: UPS recommended for reliability
1. IBKR Connection Failed:
# Check TWS/Gateway is running
# Verify API settings: Configure โ API โ Settings
# Confirm port 7497 for paper trading
# Add 127.0.0.1 to Trusted IPs2. "No managed accounts found":
# Restart TWS/Gateway
# Check login credentials
# Verify paper trading account is active3. "No market data":
# Normal during after-hours/weekends
# Check market data permissions
# Verify IBKR account has data subscriptions4. Web dashboard won't load:
pip install Flask plotly
python app.py
# Open: http://localhost:5000- IBKR API Documentation: https://interactivebrokers.github.io/tws-api/
- ib_insync Documentation: https://ib-insync.readthedocs.io/
- Check logs: Look in
logs/directory for detailed error messages
- โ
Install Dependencies:
pip install -r requirements.txt - โ Setup IBKR: Configure TWS/Gateway with API enabled
- โ
Test Connection:
python test_ibkr_connection.py - โ
Start Dashboard:
python app.pyโ http://localhost:5000 - โ Train Models: Click "Train Models" in web dashboard (15 min)
- โ Start Trading: Click "Start Bot" and monitor performance
- โ Monitor Daily: Check positions and performance regularly
- Week 1: Setup and paper trading with basic models
- Week 2: Monitor performance and understand AI predictions
- Week 3: Experiment with different risk parameters
- Week 4: Add LLM integration for enhanced analysis
- Month 2+: Consider small live trading amounts if performance is good
# Install Ollama for local LLM
curl -fsSL https://ollama.ai/install.sh | sh
ollama pull llama2
ollama serve
# Or use Claude API (set environment variable)
export ANTHROPIC_API_KEY="your_api_key_here"# Train all models for all symbols
python -c "
from ibkr_bot import IBKRTradingBot
bot = IBKRTradingBot()
bot.train_all_models() # Traditional ML + LSTM for all 8 stocks
"- Modify
create_features()to add custom indicators - Adjust
trading_routine()for different trading strategies - Update
risk_management_check()for custom risk rules
- Sharpe Ratio > 1.0: Risk-adjusted returns
- Maximum Drawdown < 15%: Risk management effectiveness
- Win Rate > 55%: Prediction accuracy
- Consistent Daily Performance: Steady growth pattern
- Analyze monthly P&L and win rate
- Review model prediction accuracy
- Assess risk management effectiveness
- Update training data with latest market conditions
- Optimize parameters based on performance
Remember: This is a sophisticated trading system. Start conservative, understand the technology, and never risk more than you can afford to lose. The AI learns and improves over time, so patience and careful monitoring are key to success! ๐