A professional-grade, modular algorithmic trading system for MetaTrader 5, specifically designed for Gold (XAUUSD) scalping strategies.
- Modular Design: Clean separation of concerns with dedicated engines
- Professional Grade: Production-ready code with comprehensive error handling
- Zero-Division Protection: Robust mathematical calculations with safety checks
- Advanced Risk Management: Multi-layered risk controls and position sizing
- Configuration-Driven: All parameters externalized for easy tuning
- Comprehensive Risk Management: Multi-layer risk controls and position sizing
- Advanced Market Analysis: Multi-timeframe technical analysis
- Performance Monitoring: Real-time system health and performance tracking
MQL5_Trading_System/
├── MQL5/
│ ├── Experts/
│ │ └── main_controller.mq5 # Central system controller
│ └── Include/
│ ├── Config/
│ │ └── settings.mqh # System configuration
│ ├── Engines/
│ │ ├── market_engine.mqh # Market data & indicators
│ │ ├── risk_engine.mqh # Risk management
│ │ ├── execution_engine.mqh # Order execution
│ │ └── data_engine.mqh # Data logging
│ ├── Strategies/
│ │ └── strategy_scalper.mqh # Scalping strategy
│ └── Utils/
│ └── data_structures.mqh # Core data structures
└── Python_Analysis/
└── .env # API keys & analysis config
- Purpose: Central "operating system" that orchestrates all components
- Responsibilities:
- System initialization and cleanup
- Tick-by-tick event processing
- Health monitoring and error handling
- Component coordination
- Purpose: Centralized market data and technical indicator calculations
- Features:
- Multi-timeframe analysis (M5, M15, H1)
- 15+ technical indicators (RSI, ADX, ATR, EMA, BB, Stochastic, etc.)
- Market condition analysis
- Optimized to prevent redundant calculations
- Purpose: Final gatekeeper for all trade signals
- Features:
- Portfolio-level risk management
- Dynamic position sizing based on ATR
- Daily/hourly trading limits
- Correlation risk assessment
- Market condition filters
- Purpose: Direct broker communication and order management
- Features:
- Robust error handling and retry logic
- Slippage and latency tracking
- Position management (modify, close, trailing stops)
- Execution performance metrics
- Purpose: Comprehensive logging for analysis and ML training
- Features:
- Structured CSV logging
- Trade decision logging (approved and rejected)
- Performance metrics tracking
- File rotation and management
- Export functionality for analysis
- Purpose: High-frequency scalping strategy implementation
- Features:
- Multi-condition signal generation
- Confidence scoring
- Market session filtering
- ATR-based stop loss/take profit
All system parameters are centralized in settings.mqh
:
#define MAX_RISK_PER_TRADE 0.5 // Max risk per trade (%)
#define MAX_DAILY_DRAWDOWN 5.0 // Max daily drawdown (%)
#define MAX_CONCURRENT_TRADES 3 // Max simultaneous trades
#define ENABLE_SCALPER_STRATEGY true // Enable/disable scalper
#define SCALPER_MIN_ATR 0.0003 // Minimum ATR for scalping
#define SCALPER_TAKE_PROFIT_MULT 2.0 // TP multiplier of ATR
#define LOG_FILE_NAME "trade_log.csv"
#define LOG_LEVEL_DEBUG true // Debug logging level
The system uses standardized data structures for communication:
Contains complete market state including:
- Current prices (bid, ask, spread)
- Technical indicators across multiple timeframes
- Market condition flags
- Volume and volatility metrics
Contains complete signal information:
- Strategy identification
- Entry/exit prices
- Risk parameters
- Confidence scoring
- Market context
Contains risk analysis results:
- Portfolio and position risk
- Approval status
- Risk limits checking
- Rejection reasons
- Copy the entire
MQL5
folder structure to your MT5 data directory - Compile
main_controller.mq5
in MetaEditor - Review and adjust settings in
settings.mqh
as needed - Attach the EA to a chart with appropriate parameters
- Install required Python packages:
pip install pandas numpy scikit-learn matplotlib seaborn
- Configure API keys in
Python_Analysis/.env
- Use logged data for performance analysis and ML model training
The system includes both demo and real account configurations:
- Demo Account: For testing and development
- Real Account: For live trading (use with extreme caution)
- Switch between accounts by modifying
ACTIVE_ACCOUNT_TYPE
in .env file
- Position Level: Individual trade risk limits
- Portfolio Level: Total exposure limits
- Daily Level: Daily loss limits
- System Level: Emergency stop mechanisms
- ATR-based position sizing
- Account balance consideration
- Risk percentage limits
- Market volatility adjustment
- Spread checking
- Volatility filters
- Session timing
- News avoidance (configurable)
Every trading decision is logged with:
- Complete market state at decision time
- Signal parameters and confidence
- Risk assessment details
- Execution results and slippage
- System performance metrics
trade_log.csv
: Complete trading activityperformance_log.csv
: Performance metricserror_log.csv
: System errors and warningsmarket_data_log.csv
: Market snapshots (optional)
The logged data enables:
- Strategy performance analysis
- Market condition correlation studies
- Machine learning model training
- Risk assessment optimization
- System performance monitoring
- Multi-Condition Signals: RSI, EMA, Stochastic, ADX, Bollinger Bands
- Confidence Scoring: 0-100% confidence with weighted factors
- Market Session Awareness: Different behavior during Asian, London, NY sessions
- Volatility Adaptation: ATR-based entry and exit levels
- Risk-Reward Optimization: Configurable R:R ratios
The modular design allows easy addition of new strategies:
- Create new strategy class in
Strategies/
folder - Implement
CheckSignal()
method - Add strategy instance to main controller
- Configure enable/disable flags in settings
- Connection monitoring
- Engine health verification
- Strategy performance tracking
- Resource usage monitoring
- Execution success rates
- Slippage and latency tracking
- Signal generation statistics
- Risk management effectiveness
- Automatic emergency stop on critical errors
- Position closure on system shutdown
- Safe mode operation during health issues
- All sensitive credentials stored in
.env
files - Separate configurations for demo and real accounts
- Regular key rotation recommended
- Demo account default configuration
- Multiple confirmation layers for real trading
- Risk limits to prevent catastrophic losses
- Emergency stop mechanisms
- Single indicator handle per timeframe
- Batch data retrieval with
CopyBuffer()
- Cached calculations to avoid redundancy
- Memory management with proper cleanup
- Minimal latency order execution
- Slippage tracking and optimization
- Connection monitoring and retry logic
- Batch logging to reduce I/O operations
- Compilation Errors: Ensure all include paths are correct
- Indicator Initialization: Wait for sufficient historical data
- Connection Issues: Check broker connection and trading permissions
- Log File Access: Ensure MT5 has write permissions for log directory
Enable debug logging in settings.mqh
:
#define LOG_LEVEL_DEBUG true
Monitor console output for:
- System initialization messages
- Health check results
- Error notifications
- Performance statistics
This trading system is provided for educational and research purposes.
IMPORTANT DISCLAIMERS:
- Trading involves substantial risk of loss
- Past performance does not guarantee future results
- Test thoroughly on demo accounts before live trading
- Never risk more than you can afford to lose
- The authors are not responsible for any financial losses
For support, bug reports, or feature requests, please:
- Test the issue on a demo account first
- Provide detailed logs and system information
- Include steps to reproduce the problem
- Specify your MT5 version and broker details
- Initial release with complete modular architecture
- Scalper strategy implementation
- Comprehensive risk management system
- Full logging and analysis framework
- Multi-timeframe market analysis engine
Remember: Always test thoroughly on demo accounts and never risk money you cannot afford to lose. Trading is risky and this system does not guarantee profits.