Advanced SuperTrend trading bot for MetaTrader 5 with Machine Learning clustering
Project description
๐ค ML-SuperTrend-MT5
An advanced SuperTrend trading bot for MetaTrader 5 that leverages Machine Learning (K-means clustering) for dynamic parameter optimization, featuring adaptive risk management and comprehensive performance monitoring.
โ ๏ธ DISCLAIMER: This project is for EDUCATIONAL PURPOSES ONLY. Trading forex/CFDs involves substantial risk of loss and is not suitable for all investors. Past performance is not indicative of future results.
๐ Features
Core Algorithm
- ๐ง ML-Optimized SuperTrend: Dynamic factor selection using K-means clustering
- ๐ Multi-Factor Analysis: Tests multiple ATR factors simultaneously
- ๐ฏ Volatility-Adjusted Performance: Adapts to market conditions
- ๐ Adaptive Moving Average: Performance-weighted signal filtering
Risk Management
- ๐ฐ Dynamic Position Sizing: Based on account risk percentage
- ๐ก๏ธ Trailing Stop Loss: Protects profits in trending markets
- ๐ฏ Automated TP/SL: ATR-based take profit and stop loss levels
- โก Daily Loss Limits: Prevents excessive drawdown
Trading Features
- ๐ Volume Confirmation: Filters low-quality signals
- ๐ Session Management: Trade during optimal market hours
- ๐ฐ News Filter Ready: Framework for economic event filtering
- ๐ Multi-Symbol Support: Trade multiple pairs simultaneously
Monitoring & Analysis
- ๐ Real-time Performance Dashboard: Live statistics display
- ๐ Comprehensive Backtesting: Historical performance analysis
- ๐ Equity Curve Visualization: Track your growth
- ๐ฏ Win Rate Analytics: Hourly and daily performance breakdown
๐ Table of Contents
- Installation
- Quick Start
- Configuration
- Architecture
- Usage Examples
- Performance Metrics
- Troubleshooting
- Contributing
- License
๐ Installation
Prerequisites
- Python 3.8 or higher
- MetaTrader 5 Terminal
- Windows OS (required for MT5 Python API)
- Active MT5 demo or live account
Step 1: Clone the Repository
git clone https://github.com/xPOURY4/ML-SuperTrend-MT5.git
cd ML-SuperTrend-MT5
Step 2: Create Virtual Environment
# Windows
python -m venv venv
venv\Scripts\activate
# macOS/Linux (MT5 API only works on Windows)
python -m venv venv
source venv/bin/activate
Step 3: Install Dependencies
pip install -r requirements.txt
Step 4: Install TA-Lib
TA-Lib requires special installation:
Windows:
- Download the appropriate .whl file from here
- Install:
pip install TA_Libโ0.4.24โcp38โcp38โwin_amd64.whl
Alternative (if above doesn't work):
conda install -c conda-forge ta-lib
โก Quick Start
1. Configure MT5 Connection
Edit config.json with your MT5 credentials:
{
"accounts": {
"main": {
"login": YOUR_MT5_LOGIN,
"password": "YOUR_MT5_PASSWORD",
"server": "YOUR_BROKER_SERVER"
}
}
}
2. Run the Bot
from supertrend_bot import SuperTrendBot, Config
import MetaTrader5 as mt5
# Initialize configuration
config = Config(
symbol="EURUSD",
timeframe=mt5.TIMEFRAME_M30,
risk_percent=1.0,
cluster_choice="Average" # "Best", "Average", or "Worst"
)
# Create and run bot
bot = SuperTrendBot(config)
bot.connect(login=YOUR_LOGIN, password="YOUR_PASSWORD", server="YOUR_SERVER")
bot.run(interval_seconds=30)
โ๏ธ Configuration
Basic Parameters
| Parameter | Default | Description |
|---|---|---|
symbol |
EURUSD | Trading pair |
timeframe |
M30 | Chart timeframe |
atr_period |
10 | ATR calculation period |
min_factor |
1.0 | Minimum ATR multiplier |
max_factor |
5.0 | Maximum ATR multiplier |
factor_step |
0.5 | Factor increment step |
Risk Management
| Parameter | Default | Description |
|---|---|---|
risk_percent |
1.0 | Risk per trade (% of account) |
sl_multiplier |
2.0 | Stop loss ATR multiplier |
tp_multiplier |
3.0 | Take profit ATR multiplier |
use_trailing |
True | Enable trailing stop |
trail_activation |
1.5 | Trailing stop activation (ATR) |
Advanced Settings
config = Config(
# Clustering
cluster_choice="Best", # Use best performing cluster
perf_alpha=10.0, # Performance EMA period
# Volume Filter
volume_ma_period=20, # Volume MA period
volume_multiplier=1.2, # Volume threshold
# Position Management
max_positions=1, # Max positions per symbol
magic_number=123456 # Unique identifier
)
๐๏ธ Architecture
ML-SuperTrend-MT5/
โ
โโโ core/
โ โโโ supertrend_bot.py # Main bot logic
โ โโโ risk_manager.py # Risk management module
โ โโโ performance_monitor.py # Analytics and reporting
โ โโโ news_filter.py # Economic calendar integration
โ
โโโ strategies/
โ โโโ supertrend_ml.py # ML-enhanced SuperTrend
โ โโโ clustering.py # K-means implementation
โ
โโโ utils/
โ โโโ mt5_helpers.py # MT5 utility functions
โ โโโ indicators.py # Technical indicators
โ โโโ data_handler.py # Data processing
โ
โโโ config/
โ โโโ config.json # Bot configuration
โ โโโ symbols.json # Symbol-specific settings
โ
โโโ logs/
โ โโโ supertrend_bot.log # Runtime logs
โ
โโโ reports/
โ โโโ performance_*.png # Performance charts
โ
โโโ tests/
โ โโโ test_strategy.py # Unit tests
โ
โโโ backtest_engine.py # Backtesting system
โโโ run_bot.py # Main entry point
โโโ requirements.txt # Dependencies
โโโ README.md # This file
๐ Usage Examples
Running Multiple Symbols
symbols = ["EURUSD", "GBPUSD", "USDJPY"]
bots = []
for symbol in symbols:
config = Config(
symbol=symbol,
timeframe=mt5.TIMEFRAME_M30,
risk_percent=0.5 # Lower risk for multiple pairs
)
bot = SuperTrendBot(config)
bot.connect(login, password, server)
bots.append(bot)
# Run all bots
import threading
for bot in bots:
thread = threading.Thread(target=bot.run)
thread.start()
Custom Risk Profile
# Conservative approach
conservative_config = Config(
cluster_choice="Worst", # Use worst performing cluster
risk_percent=0.5, # Lower risk
sl_multiplier=3.0, # Wider stop loss
tp_multiplier=2.0 # Closer take profit
)
# Aggressive approach
aggressive_config = Config(
cluster_choice="Best", # Use best performing cluster
risk_percent=2.0, # Higher risk
sl_multiplier=1.5, # Tighter stop loss
tp_multiplier=4.0 # Further take profit
)
Performance Monitoring
from performance_monitor import PerformanceMonitor
# Generate performance report
monitor = PerformanceMonitor('trades.json')
monitor.generate_report(days=30) # Last 30 days
# Get specific metrics
stats = bot.calculate_statistics()
print(f"Win Rate: {stats['win_rate']:.2f}%")
print(f"Profit Factor: {stats['profit_factor']:.2f}")
print(f"Total Trades: {stats['total_trades']}")
๐ Performance Metrics
Expected Performance (Based on Backtesting)
| Timeframe | Win Rate | Profit Factor | Max Drawdown | Sharpe Ratio |
|---|---|---|---|---|
| M5 | 48-52% | 1.1-1.3 | 15-20% | 0.8-1.0 |
| M15 | 52-57% | 1.2-1.5 | 12-18% | 1.0-1.3 |
| M30 | 55-60% | 1.3-1.7 | 10-15% | 1.2-1.5 |
| H1 | 58-63% | 1.5-2.0 | 8-12% | 1.5-1.8 |
| H4 | 60-65% | 1.7-2.5 | 5-10% | 1.8-2.2 |
Key Performance Indicators
- Average Trade Duration: 2-6 hours
- Risk/Reward Ratio: 1:1.5 average
- Monthly Return: 5-15% (varies by market conditions)
- Recovery Factor: 2.5-3.5
๐ ๏ธ Troubleshooting
Common Issues
Connection Failed
# Check MT5 terminal is running
# Verify credentials
# Ensure "Algo Trading" is enabled in MT5
No Signals Generated
# Increase lookback period
# Check volume filter settings
# Verify symbol is active/market is open
High Drawdown
# Reduce risk_percent
# Use "Average" or "Worst" cluster
# Enable daily loss limits
Debug Mode
# Enable detailed logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Run bot with debug
bot.run(interval_seconds=30, debug=True)
๐ค Contributing
We welcome contributions! Please see our Contributing Guidelines.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- SuperTrend indicator concept by Olivier Seban
- K-means clustering implementation inspired by scikit-learn
- MetaTrader 5 Python API by MetaQuotes
๐ Contact
Pourya - @TheRealPourya
Project Link: https://github.com/xPOURY4/ML-SuperTrend-MT5
Made with โค๏ธ by xPOURY4
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ml_supertrend_mt5-1.0.0.tar.gz.
File metadata
- Download URL: ml_supertrend_mt5-1.0.0.tar.gz
- Upload date:
- Size: 28.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
63e943262657f1e7bc1c4476d236e89a17ca655f7aeb527194092acacc7f0226
|
|
| MD5 |
f4b7ba50887ed3e04410d56894509122
|
|
| BLAKE2b-256 |
b6f64e38ffc19d22b9e10eab3cec1c75b0d8f1242de6260f704fe2aa087e9900
|
File details
Details for the file ml_supertrend_mt5-1.0.0-py3-none-any.whl.
File metadata
- Download URL: ml_supertrend_mt5-1.0.0-py3-none-any.whl
- Upload date:
- Size: 23.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a04abfff26556d162672e8cf6aa64b92baab7cbbb0c8b71f0364476ad18a2b32
|
|
| MD5 |
79c8ec7273baf586af5e02177c405b19
|
|
| BLAKE2b-256 |
34cd6eff14d3fdefb499267b2065af7aa896710b9530aa227dab856e6b662491
|