Skip to content

About

Automated stock trading bot

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

๐Ÿค– Enhanced AI Trading Bot with Interactive Brokers Integration

๐Ÿ“‹ Project Overview

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.

๐Ÿง  Three-Layer AI Architecture:

  1. Traditional ML: Random Forest + Gradient Boosting (Fast, Reliable Pattern Recognition)
  2. Deep Learning: LSTM Neural Networks (Advanced Temporal Pattern Analysis)
  3. Large Language Models: Market Sentiment & Context Analysis (Optional)

๐Ÿ”ฅ Key Features:

  • โœ… 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

๐Ÿš€ Quick Start Guide

Prerequisites:

  1. Python 3.8+ installed
  2. Interactive Brokers account with paper trading enabled
  3. TWS or IB Gateway downloaded and configured

Step 1: Installation

# Clone or download the repository
cd your-trading-bot-directory

# Install dependencies
pip install -r requirements.txt

Step 2: IBKR Setup

  1. Download TWS/IB Gateway from Interactive Brokers
  2. Login to your paper trading account (account starts with "DU")
  3. Enable API: Configure โ†’ API โ†’ Settings
    • โœ… Enable ActiveX and Socket Clients
    • โœ… Socket port: 7497 (paper trading)
    • โœ… Add 127.0.0.1 to Trusted IPs
  4. Apply settings and keep TWS/Gateway running

Step 3: Test Connection

# Test your IBKR connection
python test_ibkr_connection.py

Expected 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!

Step 4: Choose Your Interface

Option A: Web Dashboard (Recommended)

python app.py
# Open browser to: http://localhost:5000

Option B: IBKR Bot (Terminal)

python ibkr_bot.py

Option C: Launcher Menu

python ibkr_launcher.py
# Interactive menu with all options

๐Ÿ“ File Structure

trading-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

๐ŸŽฏ Recommended Workflow

For IBKR Paper Trading (Recommended):

  1. Test Connection First:

    python test_ibkr_connection.py
  2. Start Web Dashboard:

    python app.py
    # Dashboard: http://localhost:5000
  3. In Web Dashboard:

    • Click "Train Models" (takes 10-15 minutes)
    • Click "Start Bot" once training completes
    • Monitor performance in real-time

For Yahoo Finance Simulation:

  1. Run Original Bot:

    python bot.py
  2. Or Web Dashboard:

    python app.py
    # Uses Yahoo Finance data with paper trading simulation

๐ŸŽ›๏ธ Configuration Options

Conservative Setup (Recommended for Beginners):

# 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
)

Balanced Setup (Default):

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
)

Aggressive Setup (Advanced Users):

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
)

๐Ÿ“Š Web Dashboard Features

Access at http://localhost:5000 when running python app.py:

Real-Time Monitoring:

  • ๐Ÿ“ˆ 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

Control Panel:

  • โ–ถ๏ธ 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

๐Ÿค– AI Model Details

1. Traditional Machine Learning

  • 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.)

2. Deep Learning (LSTM)

  • 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

3. Large Language Models (Optional)

  • Local LLM: Ollama integration for market sentiment
  • Cloud LLM: Claude API for advanced market analysis
  • Features: News sentiment, market context, qualitative factors

Ensemble Approach:

The bot combines all three model types using confidence-weighted averaging for final trading decisions.


โšก Performance & Expectations

Realistic Performance Targets:

  • 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)

Your $1000 Goal Timeline:

  • 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.


๐Ÿ›ก๏ธ Risk Management Features

Built-in Safety Systems:

  • 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

Continuous Monitoring:

  • 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

๐Ÿ”„ Continuous Learning System

After-Hours Learning (4:30 PM - 9:30 AM):

  1. Performance Analysis: Analyze today's trades and outcomes
  2. Model Updates: Retrain underperforming models
  3. Strategy Optimization: Adjust parameters based on results
  4. Next Day Preparation: Generate predictions for tomorrow

Weekly Deep Learning (Sundays):

  1. Comprehensive Retraining: Update all models with latest data
  2. Performance Review: Analyze weekly trading metrics
  3. Parameter Adjustment: Optimize risk management settings
  4. Model Validation: Ensure model accuracy and reliability

๐Ÿšจ Important Warnings & Best Practices

Before Live Trading:

  • โš ๏ธ 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

Market Data Limitations:

  • 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)

System Requirements:

  • Stable Internet: Critical for real-time trading
  • Always-On Computer: Bot needs to run during market hours
  • Backup Power: UPS recommended for reliability

๐Ÿ”ง Troubleshooting

Common Issues:

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 IPs

2. "No managed accounts found":

# Restart TWS/Gateway
# Check login credentials
# Verify paper trading account is active

3. "No market data":

# Normal during after-hours/weekends
# Check market data permissions
# Verify IBKR account has data subscriptions

4. Web dashboard won't load:

pip install Flask plotly
python app.py
# Open: http://localhost:5000

Getting Help:


๐ŸŽฏ Next Steps

  1. โœ… Install Dependencies: pip install -r requirements.txt
  2. โœ… Setup IBKR: Configure TWS/Gateway with API enabled
  3. โœ… Test Connection: python test_ibkr_connection.py
  4. โœ… Start Dashboard: python app.py โ†’ http://localhost:5000
  5. โœ… Train Models: Click "Train Models" in web dashboard (15 min)
  6. โœ… Start Trading: Click "Start Bot" and monitor performance
  7. โœ… Monitor Daily: Check positions and performance regularly

Recommended Learning Path:

  1. Week 1: Setup and paper trading with basic models
  2. Week 2: Monitor performance and understand AI predictions
  3. Week 3: Experiment with different risk parameters
  4. Week 4: Add LLM integration for enhanced analysis
  5. Month 2+: Consider small live trading amounts if performance is good

๐Ÿ“ˆ Advanced Features

LLM Integration Setup (Optional):

# 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"

Multiple Model Training:

# 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
"

Custom Strategy Development:

  • Modify create_features() to add custom indicators
  • Adjust trading_routine() for different trading strategies
  • Update risk_management_check() for custom risk rules

๐Ÿ† Success Metrics

Key Performance Indicators:

  • Sharpe Ratio > 1.0: Risk-adjusted returns
  • Maximum Drawdown < 15%: Risk management effectiveness
  • Win Rate > 55%: Prediction accuracy
  • Consistent Daily Performance: Steady growth pattern

Monthly Review Checklist:

  • 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! ๐Ÿš€

About

Automated stock trading bot

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages