# XAUUSD Trading Bot Documentation ## Overview This document provides comprehensive documentation for the XAUUSD (Gold) Trading Bot developed for MetaTrader 5. The bot implements a sophisticated quantitative trading strategy specifically optimized for gold trading, combining technical analysis, regime detection, and adaptive parameter optimization to generate consistent profits across different market conditions. ## Table of Contents 1. [System Requirements](#system-requirements) 2. [Installation](#installation) 3. [Configuration](#configuration) 4. [Strategy Overview](#strategy-overview) 5. [Backtesting](#backtesting) 6. [Performance Dashboard](#performance-dashboard) 7. [Risk Management](#risk-management) 8. [Troubleshooting](#troubleshooting) 9. [FAQ](#faq) ## System Requirements - Windows 10 or higher (for MetaTrader 5) - MetaTrader 5 platform (latest version) - Python 3.8 or higher - Minimum 8GB RAM recommended - Stable internet connection ## Installation ### Step 1: Install Python Dependencies ```bash pip install -r requirements.txt ``` This will install all required packages including: - MetaTrader5 - pandas - numpy - matplotlib - scikit-learn - bayesian-optimization ### Step 2: Set Up MetaTrader 5 1. Install MetaTrader 5 from your broker's website 2. Create and log into your trading account 3. Configure MetaTrader 5 for algorithmic trading: - Go to Tools > Options > Expert Advisors - Enable "Allow automated trading" - Enable "Allow DLL imports" - Check "Allow WebRequests" and add necessary URLs ### Step 3: Install the Trading Bot 1. Copy the `xauusd_mt5_bot.py` file to your MetaTrader 5 experts directory: ``` C:\Users\{YourUsername}\AppData\Roaming\MetaQuotes\Terminal\{YourTerminalID}\MQL5\Experts\ ``` 2. Copy all supporting Python files to a directory accessible by MetaTrader 5 ## Configuration ### Trading Parameters Edit the `config.json` file to customize the trading parameters: ```json { "max_risk_per_trade_percent": 1.5, "stop_loss_atr_multiple": 1.2, "take_profit_atr_multiple": 2.4, "asian_session_weight": 1.0, "london_session_weight": 0.7, "new_york_session_weight": 0.9, "regime_lookback": 44, "volatility_threshold": 0.007, "rsi_oversold": 26, "rsi_overbought": 68.5 } ``` ### Account Settings Edit the `account.json` file with your MetaTrader 5 account details: ```json { "login": YOUR_ACCOUNT_NUMBER, "password": "YOUR_PASSWORD", "server": "YOUR_BROKER_SERVER", "path": "C:/path/to/metatrader5.exe" } ``` **Important**: Keep your account credentials secure and never share this file. ## Strategy Overview The XAUUSD Trading Bot employs a multi-faceted strategy specifically designed for gold trading: ### 1. Market Regime Detection The bot uses Hidden Markov Models to identify the current market state: - Trending bullish (strong uptrend) - Trending bearish (strong downtrend) - Range-bound (consolidation) - Volatile (high volatility) Different trading approaches are applied based on the detected regime. ### 2. Technical Components The strategy incorporates multiple technical indicators: - Exponential Moving Averages (8, 34, 200 periods) - Relative Strength Index (RSI) - Average True Range (ATR) - Bollinger Bands - MACD ### 3. Session-Specific Behavior The bot adjusts its trading behavior based on the current session: - Asian Session: Focuses on range-bound strategies - London Session: More conservative approach - New York Session: Adapts to higher volatility ### 4. Macro-Economic Factor Integration The strategy incorporates correlations with: - USD Index strength - Real interest rates - Market risk sentiment ### 5. Self-Optimization The bot includes a self-optimization mechanism that periodically adjusts parameters based on recent performance. ## Backtesting ### Running a Backtest To run a backtest of the strategy: ```bash python backtesting_module.py --data_path /path/to/data --start_date 2020-01-01 --end_date 2025-01-01 ``` ### Backtest Parameters - `--data_path`: Path to historical XAUUSD data - `--start_date`: Start date for backtest (YYYY-MM-DD) - `--end_date`: End date for backtest (YYYY-MM-DD) - `--initial_balance`: Initial account balance (default: 10000) - `--params_file`: Path to custom parameters file (optional) ### Interpreting Results Backtest results include: - Return on Investment (ROI) - Win rate - Profit factor - Maximum drawdown - Sharpe ratio - Trade statistics by session and market regime ## Performance Dashboard The performance dashboard provides a visual representation of the trading bot's performance. ### Generating the Dashboard ```bash python generate_dashboard.py ``` This creates an HTML dashboard in the `dashboard` directory. ### Dashboard Components 1. **Performance Summary**: Key metrics including ROI, win rate, profit factor, etc. 2. **Equity Curve & Drawdown**: Visual representation of account growth and drawdowns 3. **Monthly Returns**: Heatmap showing performance by month and year 4. **Session Performance**: Comparison of performance across different trading sessions 5. **Market Regime Performance**: Performance breakdown by market regime 6. **Trade Distribution**: Distribution of trade profits and durations 7. **Walk-Forward Analysis**: Results of walk-forward testing ## Risk Management The bot implements several risk management features: ### Position Sizing - Maximum risk per trade is limited to 1.5% of account balance - Position size is calculated based on stop loss distance ### Stop Loss and Take Profit - Stop loss is set at 1.2 times ATR from entry - Take profit is set at 2.4 times ATR from entry (1:2 risk-reward ratio) ### Session Filters - Trading activity is weighted by session, with highest weight on Asian session - Reduced exposure during historically underperforming sessions ### Volatility Adjustments - Position sizes are reduced during high volatility periods - Wider stops are used in volatile market conditions ## Troubleshooting ### Common Issues 1. **Connection Problems**: - Verify internet connection - Check MetaTrader 5 is properly logged in - Ensure API access is enabled in MT5 2. **Authorization Failed**: - Verify account credentials in account.json - Check if account has algorithmic trading permissions 3. **No Trading Activity**: - Verify market is open - Check if symbol is available for trading - Ensure sufficient margin in account ### Error Logs Error logs are stored in the `logs` directory. Check these files for detailed error information. ## FAQ **Q: How many trades per day should I expect?** A: The bot is designed to make 2-5 trades per day on average, with higher frequency during volatile periods and lower frequency during quiet markets. **Q: What is the recommended minimum account size?** A: We recommend a minimum of $5,000 to ensure proper position sizing and risk management. **Q: Can I run the bot on multiple currency pairs?** A: This version is specifically optimized for XAUUSD (Gold). Running on other instruments would require recalibration of parameters. **Q: How often should I update the parameters?** A: The bot includes self-optimization, but we recommend reviewing and potentially updating parameters every 3-6 months or after significant market regime changes. **Q: Is the bot profitable in all market conditions?** A: The bot is designed to adapt to different market regimes, but performance may vary. It performs best during trending and range-bound markets with clear volatility patterns. **Q: How do I update the bot?** A: Check for updates in the repository and replace the files. Always backup your configuration before updating. --- ## Support For additional support or questions, please contact the developer. --- *Disclaimer: Trading involves risk. Past performance is not indicative of future results. This trading bot is provided for educational and informational purposes only and should not be construed as financial advice.*