Skip to content

sameer-dev-stack/Trade-bot-AI-Scalper

Repository files navigation

🤖 AI Forex Trading Bot

A complete, production-ready AI-powered Forex trading bot that uses MetaTrader 5 for broker connectivity, Gemini AI for intelligent trading signals, and Streamlit for a professional monitoring dashboard.

Python MT5 Gemini Streamlit


✨ Features

🔧 Backend Trading Bot (bot.py)

  • MT5 Integration: Connects to XM broker (or any MT5-compatible broker)
  • 🤖 Gemini AI Signals: Uses Google's Gemini 3 AI for intelligent trade decisions
  • 📊 Technical Analysis: RSI(14), SMA(20), Bollinger Bands
  • 💾 SQLite Database: Logs all trades with timestamps, profit/loss, and reasoning
  • 🛡️ Risk Management:
    • Max 1% account risk per trade
    • 10-pip stop-loss, 20-pip take-profit
    • Maximum 1 open trade at a time
  • 24/7 Operation: Runs in infinite loop with 15-minute intervals
  • 🛑 Graceful Shutdown: Proper error handling and signal management

💻 Frontend Dashboard (app.py)

  • 🔐 Authentication: Secure login (admin@mail.com / Password@9850)
  • 📈 Real-time Charts: Live candlestick charts with indicators (Plotly)
  • 📊 Account Metrics: Balance, P/L, win rate, drawdown
  • 📜 Trade History: Complete trade log with profit calculations
  • 🎮 Bot Controls: Start/Stop bot, manual trade override
  • ✏️ Prompt Editor: Edit Gemini AI prompt in real-time
  • 📱 Telegram Alerts: Integration ready (optional)
  • 🎨 Dark Theme: Premium UI with gradient effects

📋 Prerequisites

  1. Python 3.8+ installed
  2. MetaTrader 5 desktop application installed (Download here)
  3. XM Broker Demo Account (Sign up here)
  4. Gemini API Key (Get free key)

⚠️ IMPORTANT: Always test with a DEMO account first! Never use real money until you're confident with the system.


🚀 Installation

Step 1: Clone or Download Project

cd C:\Users\Sameer\Desktop\Trading_bot

Step 2: Create Virtual Environment (Recommended)

python -m venv venv
.\venv\Scripts\activate

Step 3: Install Dependencies

pip install -r requirements.txt

This will install:

  • MetaTrader5
  • google-generativeai
  • streamlit
  • pandas-ta
  • plotly
  • And more...

Step 4: Configure Environment Variables

Your Gemini API key is already configured in the .env file:

GEMINI_API_KEY=AIzaSyD2Gf1BV8BKonie-ElmUYZrre86cyqZUlc

Optional: Add Telegram bot credentials for alerts (leave empty if not using):

TELEGRAM_BOT_TOKEN=your_telegram_token
TELEGRAM_CHAT_ID=your_chat_id

⚙️ Configuration

MT5 Setup

  1. Install MetaTrader 5 on your Windows machine

  2. Create a Demo Account with XM broker:

    • Open MT5
    • File → Open an Account → Search for "XM"
    • Select "XMGlobal-Demo" or "XMGlobal-Demo 3"
    • Fill in your details and create account
    • Save your credentials: Login, Password, Server
  3. Enable Algo Trading:

    • In MT5, click Tools → Options → Expert Advisors
    • Check "Allow automated trading"
    • Check "Allow DLL imports"

Trading Parameters

Edit config.py to customize:

# Risk Management
MAX_RISK_PERCENT = 1.0  # 1% per trade
LOT_SIZE = 0.01  # 0.01 lots
STOP_LOSS_PIPS = 10
TAKE_PROFIT_PIPS = 20

# Trading Loop
LOOP_INTERVAL_MINUTES = 15  # Check every 15 min

# Symbols
SYMBOLS = ['EURUSD', 'XAUUSD']

🎯 Usage

Option 1: Run Dashboard + Bot (Recommended)

Step 1: Start the Streamlit Dashboard

streamlit run app.py
  • Dashboard opens at http://localhost:8501
  • Login with:
    • Email: admin@mail.com
    • Password: Password@9850

Step 2: Start the Trading Bot

Open a new terminal in the project folder:

python bot.py

You'll be prompted for:

  • MT5 Login
  • MT5 Password
  • MT5 Server (e.g., "XMGlobal-Demo")

The bot will:

  1. Connect to MT5
  2. Initialize Gemini AI
  3. Start the 15-minute trading loop
  4. Analyze EURUSD and XAUUSD
  5. Execute trades when signals are strong

Option 2: Run Bot Only

python bot.py

Trades will be logged to trading_bot.db database.


📊 How It Works

Trading Logic Flow

1. Every 15 minutes:
   ├── Fetch H1 candle data from MT5 (100 bars)
   ├── Calculate Technical Indicators:
   │   ├── RSI (14-period)
   │   ├── SMA (20-period)
   │   └── Bollinger Bands (20, 2)
   ├── Send data to Gemini AI with prompt:
   │   "EURUSD price X, RSI Y, SMA Z... BUY/SELL/HOLD?"
   ├── Parse AI response (ACTION + REASON)
   ├── Check signal strength (STRONG/MODERATE/WEAK)
   └── Execute trade if:
       ├── Action = BUY or SELL
       ├── Strength = STRONG
       └── No existing open trades

Risk Management

  • Position Sizing: Fixed 0.01 lots per trade
  • Stop Loss: Automatically placed 10 pips below/above entry
  • Take Profit: Automatically placed 20 pips above/below entry
  • Max Risk: 1% of account balance
  • Max Positions: Only 1 trade open at a time

AI Decision Making

Gemini AI analyzes:

  • Current price vs SMA (trend direction)
  • RSI levels (overbought > 70, oversold < 30)
  • Bollinger Band position (support/resistance)
  • Confluence of signals

📸 Dashboard Screenshots

Login Page

Login

Main Dashboard

  • Top Row: Balance, P/L, Win Rate, Total Trades
  • Charts Section: Interactive candlestick charts with RSI/SMA/BB
  • Trade History: Searchable table with profit highlighting
  • Controls: Start/Stop bot, manual trades, settings

🔒 Security Best Practices

  1. Never commit .env file to version control
  2. Use demo account for testing
  3. Keep API keys secret
  4. Monitor trades regularly
  5. Start with minimal lot sizes (0.01)
  6. Test on historical data before live trading

🐛 Troubleshooting

Issue: "MT5 initialization failed"

Solution:

  • Ensure MetaTrader 5 is installed
  • Make sure MT5 is running (doesn't need to be logged in)
  • Check you're using the correct server name

Issue: "Gemini API error"

Solution:

  • Verify API key in .env file
  • Check your API quota at Google AI Studio
  • Ensure internet connection is stable

Issue: "No data for symbol"

Solution:

  • Ensure symbols are available in your MT5 account
  • Try logging into MT5 manually first
  • Check symbol spelling (e.g., "EURUSD" not "EUR/USD")

Issue: Dashboard shows "N/A" for balance

Solution:

  • Make sure MT5 is running
  • Click "Refresh Dashboard" button
  • Restart Streamlit: streamlit run app.py

📁 Project Structure

Trading_bot/
├── bot.py                  # Main trading bot
├── app.py                  # Streamlit dashboard
├── config.py              # Configuration settings
├── database.py            # SQLite operations
├── indicators.py          # Technical analysis
├── requirements.txt       # Python dependencies
├── .env                   # Environment variables (your API keys)
├── .env.example          # Template for .env
├── .gitignore            # Git ignore patterns
├── README.md             # This file
└── trading_bot.db        # SQLite database (created automatically)

🎓 Educational Purpose

This bot is designed for educational and research purposes. Forex trading involves substantial risk:

  • 📉 You can lose more than your initial investment
  • 🎓 Use this to learn about algorithmic trading
  • 🧪 Always test on demo accounts first
  • 💰 Never invest money you can't afford to lose

🚀 Future Enhancements

Potential improvements:

  • Backtesting engine with historical data
  • Multiple strategy support
  • Advanced position sizing (Kelly Criterion)
  • News sentiment analysis
  • Multi-timeframe analysis
  • Email notifications
  • Trade export to CSV/Excel
  • Machine learning model integration

📞 Support

If you encounter issues:

  1. Check the Troubleshooting section above
  2. Review MT5 connection settings
  3. Verify all dependencies are installed
  4. Check Python version (3.8+)

📜 License

This project is for educational purposes. Use at your own risk.


🙏 Acknowledgments

  • MetaTrader 5: Trading platform
  • Google Gemini: AI-powered signals
  • Streamlit: Dashboard framework
  • pandas-ta: Technical analysis library

⚡ Quick Start Summary

# 1. Install dependencies
pip install -r requirements.txt

# 2. Start dashboard (Terminal 1)
streamlit run app.py

# 3. Start bot (Terminal 2)
python bot.py

# 4. Login to dashboard
# Email: admin@mail.com
# Password: Password@9850

# 5. Monitor trades!

Happy Trading! 📈💰

Remember: Demo first, real later!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages