Skip to content

ns-vikas/trading-bot-mql5

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

🚀 Advanced MQL5 Trading System

A professional-grade, modular algorithmic trading system for MetaTrader 5, specifically designed for Gold (XAUUSD) scalping strategies.

🏆 Features

Core Architecture

  • 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

System Architecture

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

Core Components

1. Main Controller (main_controller.mq5)

  • 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

2. Market Engine (market_engine.mqh)

  • 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

3. Risk Engine (risk_engine.mqh)

  • 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

4. Execution Engine (execution_engine.mqh)

  • 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

5. Data Engine (data_engine.mqh)

  • 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

6. Scalper Strategy (strategy_scalper.mqh)

  • Purpose: High-frequency scalping strategy implementation
  • Features:
    • Multi-condition signal generation
    • Confidence scoring
    • Market session filtering
    • ATR-based stop loss/take profit

Configuration System

All system parameters are centralized in settings.mqh:

Risk Management

#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

Strategy Settings

#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

Logging Configuration

#define LOG_FILE_NAME              "trade_log.csv"
#define LOG_LEVEL_DEBUG            true      // Debug logging level

Data Structures

The system uses standardized data structures for communication:

MarketSnapshot

Contains complete market state including:

  • Current prices (bid, ask, spread)
  • Technical indicators across multiple timeframes
  • Market condition flags
  • Volume and volatility metrics

TradeSignal

Contains complete signal information:

  • Strategy identification
  • Entry/exit prices
  • Risk parameters
  • Confidence scoring
  • Market context

RiskAssessment

Contains risk analysis results:

  • Portfolio and position risk
  • Approval status
  • Risk limits checking
  • Rejection reasons

Installation and Setup

1. MQL5 Setup

  1. Copy the entire MQL5 folder structure to your MT5 data directory
  2. Compile main_controller.mq5 in MetaEditor
  3. Review and adjust settings in settings.mqh as needed
  4. Attach the EA to a chart with appropriate parameters

2. Python Analysis Setup

  1. Install required Python packages:
    pip install pandas numpy scikit-learn matplotlib seaborn
  2. Configure API keys in Python_Analysis/.env
  3. Use logged data for performance analysis and ML model training

3. Account Configuration

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

Risk Management Features

Multi-Layer Risk Controls

  1. Position Level: Individual trade risk limits
  2. Portfolio Level: Total exposure limits
  3. Daily Level: Daily loss limits
  4. System Level: Emergency stop mechanisms

Dynamic Position Sizing

  • ATR-based position sizing
  • Account balance consideration
  • Risk percentage limits
  • Market volatility adjustment

Market Condition Filters

  • Spread checking
  • Volatility filters
  • Session timing
  • News avoidance (configurable)

Logging and Analysis

Comprehensive Data Logging

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

Log Files Generated

  • trade_log.csv: Complete trading activity
  • performance_log.csv: Performance metrics
  • error_log.csv: System errors and warnings
  • market_data_log.csv: Market snapshots (optional)

Analysis Capabilities

The logged data enables:

  • Strategy performance analysis
  • Market condition correlation studies
  • Machine learning model training
  • Risk assessment optimization
  • System performance monitoring

Strategy Framework

Scalper Strategy Features

  • 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

Adding New Strategies

The modular design allows easy addition of new strategies:

  1. Create new strategy class in Strategies/ folder
  2. Implement CheckSignal() method
  3. Add strategy instance to main controller
  4. Configure enable/disable flags in settings

System Monitoring

Health Checks

  • Connection monitoring
  • Engine health verification
  • Strategy performance tracking
  • Resource usage monitoring

Performance Metrics

  • Execution success rates
  • Slippage and latency tracking
  • Signal generation statistics
  • Risk management effectiveness

Emergency Procedures

  • Automatic emergency stop on critical errors
  • Position closure on system shutdown
  • Safe mode operation during health issues

Security Considerations

API Key Management

  • All sensitive credentials stored in .env files
  • Separate configurations for demo and real accounts
  • Regular key rotation recommended

Trading Safety

  • Demo account default configuration
  • Multiple confirmation layers for real trading
  • Risk limits to prevent catastrophic losses
  • Emergency stop mechanisms

Performance Optimization

Efficient Indicator Calculation

  • Single indicator handle per timeframe
  • Batch data retrieval with CopyBuffer()
  • Cached calculations to avoid redundancy
  • Memory management with proper cleanup

Execution Optimization

  • Minimal latency order execution
  • Slippage tracking and optimization
  • Connection monitoring and retry logic
  • Batch logging to reduce I/O operations

Troubleshooting

Common Issues

  1. Compilation Errors: Ensure all include paths are correct
  2. Indicator Initialization: Wait for sufficient historical data
  3. Connection Issues: Check broker connection and trading permissions
  4. Log File Access: Ensure MT5 has write permissions for log directory

Debug Mode

Enable debug logging in settings.mqh:

#define LOG_LEVEL_DEBUG            true

System Status Monitoring

Monitor console output for:

  • System initialization messages
  • Health check results
  • Error notifications
  • Performance statistics

License and Disclaimer

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

Support and Contributing

For support, bug reports, or feature requests, please:

  1. Test the issue on a demo account first
  2. Provide detailed logs and system information
  3. Include steps to reproduce the problem
  4. Specify your MT5 version and broker details

Version History

Version 1.0.0

  • 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.

About

Trading bot to scalp XAUUSD

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published