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.
- ✅ 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
- 🔐 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
- Python 3.8+ installed
- MetaTrader 5 desktop application installed (Download here)
- XM Broker Demo Account (Sign up here)
- 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.
cd C:\Users\Sameer\Desktop\Trading_botpython -m venv venv
.\venv\Scripts\activatepip install -r requirements.txtThis will install:
- MetaTrader5
- google-generativeai
- streamlit
- pandas-ta
- plotly
- And more...
Your Gemini API key is already configured in the .env file:
GEMINI_API_KEY=AIzaSyD2Gf1BV8BKonie-ElmUYZrre86cyqZUlcOptional: Add Telegram bot credentials for alerts (leave empty if not using):
TELEGRAM_BOT_TOKEN=your_telegram_token
TELEGRAM_CHAT_ID=your_chat_id-
Install MetaTrader 5 on your Windows machine
-
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
-
Enable Algo Trading:
- In MT5, click Tools → Options → Expert Advisors
- Check "Allow automated trading"
- Check "Allow DLL imports"
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']streamlit run app.py- Dashboard opens at
http://localhost:8501 - Login with:
- Email:
admin@mail.com - Password:
Password@9850
- Email:
Open a new terminal in the project folder:
python bot.pyYou'll be prompted for:
- MT5 Login
- MT5 Password
- MT5 Server (e.g., "XMGlobal-Demo")
The bot will:
- Connect to MT5
- Initialize Gemini AI
- Start the 15-minute trading loop
- Analyze EURUSD and XAUUSD
- Execute trades when signals are strong
python bot.pyTrades will be logged to trading_bot.db database.
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
- 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
Gemini AI analyzes:
- Current price vs SMA (trend direction)
- RSI levels (overbought > 70, oversold < 30)
- Bollinger Band position (support/resistance)
- Confluence of signals
- 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
- ✅ Never commit
.envfile to version control - ✅ Use demo account for testing
- ✅ Keep API keys secret
- ✅ Monitor trades regularly
- ✅ Start with minimal lot sizes (0.01)
- ✅ Test on historical data before live trading
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
Solution:
- Verify API key in
.envfile - Check your API quota at Google AI Studio
- Ensure internet connection is stable
Solution:
- Ensure symbols are available in your MT5 account
- Try logging into MT5 manually first
- Check symbol spelling (e.g., "EURUSD" not "EUR/USD")
Solution:
- Make sure MT5 is running
- Click "Refresh Dashboard" button
- Restart Streamlit:
streamlit run app.py
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)
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
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
If you encounter issues:
- Check the Troubleshooting section above
- Review MT5 connection settings
- Verify all dependencies are installed
- Check Python version (3.8+)
This project is for educational purposes. Use at your own risk.
- MetaTrader 5: Trading platform
- Google Gemini: AI-powered signals
- Streamlit: Dashboard framework
- pandas-ta: Technical analysis library
# 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!