A professional-grade MQL5 Expert Advisor with advanced risk management, comprehensive error handling, and modern Python integration tools. This trading bot implements sophisticated technical analysis algorithms and defensive security measures for automated forex trading.
- Modern MACD Analysis: Uses current MQL5 syntax with proper indicator handles
- Fractal-Based Support/Resistance: Intelligent price level detection using fractal analysis
- Enhanced Fair Value Gap Detection: Sophisticated gap analysis with momentum confirmation
- Multi-Timeframe Analysis: Configurable timeframe support beyond just 1-minute charts
- Dynamic Position Sizing: Intelligent lot size calculation with account equity protection
- Daily Loss Limits: Automatic trading halt when daily loss threshold is reached
- Spread Protection: Real-time spread monitoring with configurable maximum limits
- Breakeven Management: Automatic stop loss adjustment to breakeven at 1:1 R:R
- Account Safety: Maximum 5% account risk per trade with validation
- Comprehensive Error Handling: Robust error detection and logging throughout
- Modern MQL5 Syntax: Updated to use latest MetaTrader 5 functions and structures
- Input Validation: All parameters validated before execution
- Memory Management: Proper indicator handle management and cleanup
- Bearish Reversal Detection: Advanced pattern recognition identifying significant bearish zones after bullish momentum
- Fractal Support/Resistance: Multi-touch level validation using fractal analysis over configurable lookback periods
- Fair Value Gap Analysis: Sophisticated gap detection with volume and momentum confirmation
- MACD Confluence: Cross-validation using MACD histogram and signal line crossovers
- Sell Limit Orders: Strategic order placement at identified supply zones
- Dynamic Risk-Reward: Configurable minimum R:R ratios (default 1:2)
- Spread Validation: Real-time spread checking before order execution
- Duplicate Prevention: Advanced logic to prevent multiple orders on same signal
- Breakeven Automation: Automatic stop loss adjustment when trade reaches 1:1 R:R
- Trailing Stops: Optional trailing stop functionality (configurable)
- Position Monitoring: Real-time position tracking and management
- MetaTrader 5 (Build 3340 or higher recommended)
- Python 3.8+ (for auxiliary scripts and analysis)
- MetaTrader5 Python package (
pip install MetaTrader5)
- Active MetaTrader 5 trading account
- Algorithmic trading enabled
- Sufficient margin for position sizing
- DLL imports allowed (for enhanced functionality)
- Windows 10/11 (64-bit recommended)
- Stable internet connection
- Minimum 4GB RAM
- 1GB free disk space
git clone https://github.com/Astralchemist/Expert-Advisor-trading-bot.git
cd Expert-Advisor-trading-botpip install MetaTrader5-
Copy
bot.mq5to your MetaTrader 5 Experts folder:- Default path:
C:/Users/{Username}/AppData/Roaming/MetaQuotes/Terminal/{TerminalID}/MQL5/Experts/ - Alternative:
C:/Program Files/MetaTrader 5/MQL5/Experts/
- Default path:
-
Compile the Expert Advisor in MetaEditor (F7)
-
Attach to chart:
- Open MetaTrader 5
- Navigate to Navigator β Expert Advisors
- Drag
botonto your desired chart - Configure input parameters
- Enable AutoTrading (Ctrl+E)
- Edit
config.jsonto customize trading parameters - Run
python config_manager.pyto validate configuration - Test connection with
python init-test.py
- Initialize Connection: Run
python mt5-init.pyto establish MT5 connection - Verify Account: Run
python account-info.pyto check account status - Test Functionality: Run
python test-function.pyto test order placement - Attach EA: Add Expert Advisor to your trading chart
| Parameter | Default | Description |
|---|---|---|
| RiskAmount | 50.0 | Risk per trade in account currency |
| MaxDailyLoss | 200.0 | Maximum daily loss limit |
| LookbackPeriod | 20 | Candles for S/R analysis |
| MinRiskReward | 2.0 | Minimum risk:reward ratio |
| MagicNumber | 234567 | Unique EA identifier |
| EnableLogging | true | Enable detailed logging |
The bot scans for:
- Bullish momentum followed by bearish reversal
- Fractal support/resistance levels with multiple touches
- Fair value gaps aligned with key price levels
- MACD confirmation with momentum and signal crossover
- Acceptable spread conditions
- Places sell limit orders at identified supply zones
- Implements dynamic stop loss and take profit levels
- Automatically moves SL to breakeven at 1:1 R:R
- Monitors and manages positions until closure
- Dynamic Lot Calculation: Based on account equity and risk percentage
- Maximum Risk: 5% of account equity per trade (configurable)
- Minimum/Maximum Lots: Respects broker limitations
- Account Protection: Validates against margin requirements
- Daily Loss Limits: Automatic trading halt when threshold reached
- Spread Monitoring: Real-time spread validation before execution
- Equity Protection: Continuous account equity monitoring
- Error Handling: Comprehensive error detection and response
- Breakeven Automation: SL moved to entry when 1:1 R:R achieved
- Position Monitoring: Real-time position tracking
- Risk-Reward Validation: Ensures minimum R:R before execution
- Duplicate Prevention: Prevents multiple orders on same signal
{
"trading": {
"risk_amount": 50.0,
"max_daily_loss": 200.0,
"min_risk_reward": 2.0,
"max_spread_pips": 3.0
},
"analysis": {
"lookback_period": 20,
"macd_fast": 12,
"macd_slow": 26,
"macd_signal": 9
},
"symbols": [
{
"name": "EURUSD",
"enabled": true,
"max_spread": 0.0003
}
]
}from config_manager import ConfigManager
config = ConfigManager()
config.set('trading.risk_amount', 75.0)
config.save_config()- Risk Parameters: Risk amount, daily limits, R:R ratios
- Technical Indicators: MACD periods, lookback periods
- Symbol Configuration: Add/remove trading pairs
- Timeframes: Modify for different chart periods
- Logging: Detailed logging levels and options
- Open MetaTrader 5 Strategy Tester (Ctrl+R)
- Select Expert Advisor:
bot - Configure test parameters:
- Symbol: EURUSD or GBPUSD
- Timeframe: M1 (or configured timeframe)
- Date range: Sufficient historical data
- Model: Every tick (most accurate)
- Set input parameters matching your live configuration
- Run backtest and analyze results
# Test MT5 connection
python init-test.py
# Verify account information
python account-info.py
# Test order functionality
python test-function.py
# Validate configuration
python config_manager.py- Profit Factor: Target > 1.3
- Maximum Drawdown: Keep < 20%
- Win Rate: Aim for > 40%
- Risk-Reward: Maintain configured minimum R:R
- Sharpe Ratio: Target > 1.0
Expert-Advisor-trading-bot/
βββ bot.mq5 # Main Expert Advisor (MQL5)
βββ config.json # Configuration settings
βββ config_manager.py # Python configuration manager
βββ mt5-init.py # MT5 connection initializer
βββ account-info.py # Account information display
βββ test-function.py # Order testing utilities
βββ init-test.py # Connection testing suite
βββ README.md # Documentation
Connection Problems
- Ensure MetaTrader 5 is running and logged in
- Check algorithmic trading is enabled
- Verify DLL imports are allowed
- Run
python init-test.pyfor diagnostics
Trading Issues
- Check account permissions and margin
- Verify spread conditions
- Review EA logs in MT5 Experts tab
- Validate configuration with
config_manager.py
Performance Issues
- Monitor system resources
- Check internet connection stability
- Review log files for errors
- Adjust lookback periods if needed
- Input Validation: All parameters validated before use
- Error Handling: Comprehensive error detection and logging
- Account Protection: Multiple safety mechanisms
- Defensive Coding: Secure programming practices throughout
- No Hardcoded Secrets: Configuration-based sensitive data
- Account equity and balance tracking
- Position monitoring and management
- Spread and market condition analysis
- Error detection and alerting
- Trade history analysis
- Risk metrics calculation
- Drawdown monitoring
- Profit/loss tracking
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
- Follow defensive security practices
- Add comprehensive error handling
- Include input validation
- Update documentation
- Test thoroughly before submission
RISK WARNING: Trading forex involves substantial risk and may not be suitable for all investors. Past performance does not guarantee future results. This software is provided for educational purposes only. Use at your own risk.
This project is licensed under the MIT License - see the LICENSE file for details.
- GitHub: Astralchemist
- Project: Expert Advisor Trading Bot
- Version: 2.0 (Enhanced)
For support, bug reports, or feature requests, please open an issue on GitHub.