MQL5 EXPERT ADVISOR GOLD (XAUUSD) TREND-FOLLOWING SUPPLY & DEMAND TRADING BOT Developer Specification — XAUUSD / Gold Only IMPORTANT — XAUUSD / GOLD ONLY This Expert Advisor is specifically designed for Gold Spot (XAUUSD) trading on MetaTrader 5. It is NOT a generic multi-instrument or multi-currency EA. All trading logic, supply/demand analysis, stop-loss, breakeven, position sizing, price-distance calculations and execution rules must be implemented specifically for XAUUSD using the actual symbol specifications supplied by the broker. 1. PROJECT OBJECTIVE Develop an automated MQL5 Expert Advisor that identifies the prevailing XAUUSD market phase, detects valid Gold supply and demand zones on higher timeframes, and executes trades using predefined M15 confirmation criteria. The EA must incorporate: - XAUUSD/Gold-only trading - H1, H4 and D1 market-structure analysis - H1/H4/D1 supply and demand zones - M15 entry confirmation - H1 21 EMA and 55 EMA trend confirmation - Adjustable risk and automatic XAUUSD position sizing - 100-pip default stop-loss and breakeven - Supply/demand and H1 EMA exits - No new trades during unclear/ranging conditions The strategy is trend-following. Trades should generally be taken in the direction of established higher-timeframe market structure. 2. TRADING INSTRUMENT AND PLATFORM - Instrument: Gold Spot / XAUUSD only. - Platform: MetaTrader 5. - Programming language: MQL5. - The EA must verify that the active symbol is XAUUSD/Gold before allowing a trade. - The EA must not open trades on Forex pairs, indices, crypto or other instruments. - Broker-specific Gold symbol naming should be accommodated where agreed, but the EA must verify the symbol's actual trading properties before execution. 3. MARKET PHASE IDENTIFICATION The EA must analyze H1, H4 and D1 to determine the current XAUUSD market phase. UPTREND: The market should be classified as an uptrend when Gold price structure demonstrates Higher Highs (HH) and Higher Lows (HL). DOWNTREND: The market should be classified as a downtrend when Gold price structure demonstrates Lower Lows (LL) and Lower Highs (LH). RANGE: The market should be classified as ranging when there is no sufficiently clear HH/HL or LL/LH structure. Trading rule: The EA must not initiate new XAUUSD trades when the market is classified as a range or when the trend structure is insufficiently clear. 4. H1 EMA TREND FILTER The EA must use two Exponential Moving Averages on the H1 XAUUSD chart: - Fast EMA = 21 - Slow EMA = 55 BUY FILTER: H1 21 EMA must be above H1 55 EMA. SELL FILTER: H1 21 EMA must be below H1 55 EMA. Both EMA periods must be adjustable through EA inputs. 5. XAUUSD SUPPLY AND DEMAND ZONES Supply and demand must be treated as price zones/ranges, not single horizontal price levels. The EA must identify zones on: - H1 - H4 - D1 The supplied TradingView XAUUSD 4H chart is a visual reference for the intended methodology. The orange horizontal areas demonstrate the intended zone/range concept. The prices shown on the reference chart must NOT be hard-coded into the EA. DEMAND ZONE: A demand zone represents an area on XAUUSD where significant buying activity has previously occurred and where Gold has demonstrated a meaningful bullish reaction or rejection. The EA must record: - Upper boundary - Lower boundary - Source timeframe - Historical reaction/displacement - Number of relevant historical reactions/retests - Current validity/invalidity status SUPPLY ZONE: A supply zone represents an area on XAUUSD where significant selling activity has previously occurred and where Gold has demonstrated a meaningful bearish reaction or rejection. The EA must record: - Upper boundary - Lower boundary - Source timeframe - Historical reaction/displacement - Number of relevant historical reactions/retests - Current validity/invalidity status 6. SUPPLY/DEMAND ZONE VALIDATION AND INVALIDATION The EA must not classify every Gold high or low as a supply/demand zone. A valid zone should preferably demonstrate: 1. A clear historical price reaction. 2. Meaningful bullish or bearish displacement away from the area. 3. Evidence of previous respect or retesting. 4. Clearly defined upper and lower boundaries. A zone remains active until objectively invalidated. Zone invalidation: A supply or demand zone should be considered invalid when XAUUSD decisively breaks through the zone according to objectively defined zone-break criteria. The developer must define and document measurable rules for what constitutes a decisive break before coding. A zone should NOT automatically become invalid merely because Gold touches it once. 7. ZONE HIERARCHY AND OVERLAPPING ZONES When multiple Gold zones are present, the EA should prioritize zones according to: 1. Timeframe: D1, H4, H1. 2. Strength of historical reaction. 3. Number of successful historical reactions/retests. 4. Recency. When H1, H4 and D1 zones overlap or are very close together, the EA should preferably consolidate them into one broader relevant zone rather than treating them as completely separate trade opportunities. 8. BUY SETUP — XAUUSD A buy trade should only be considered when all required conditions are satisfied. 1. MARKET PHASE: Higher-timeframe Gold structure indicates an uptrend, with a preferred sequence of Higher Highs and Higher Lows. 2. EMA CONFIRMATION: H1 21 EMA > 55 EMA. 3. DEMAND ZONE: XAUUSD price returns to or touches an active valid demand zone identified on H1, H4 or D1. 4. M15 CONFIRMATION: Once Gold reaches the demand zone, monitor M15 and wait for the first COMPLETED bullish M15 candle formed at or within the demand zone. 5. ENTRY: Execute a BUY order at the close of the first valid bullish M15 confirmation candle. The confirmation candle must be completely closed. The EA must not enter while the M15 candle is still forming. 9. BUY STOP-LOSS — XAUUSD Default buy stop-loss: 100 pips below the open price of the first bullish M15 confirmation candle. The demand-zone boundary must also be considered. Where necessary, the EA should ensure the stop-loss is positioned beyond the relevant demand zone rather than leaving the trade vulnerable to normal movement within the zone. The exact structural stop-loss rule must be objective and agreed before coding. IMPORTANT: Because this EA is designed specifically for Gold, the developer must implement the 100-pip distance using the broker's actual XAUUSD price/point specifications. The EA must not assume that the word "pip" has the same decimal or monetary meaning across all brokers. 10. BUY BREAKEVEN — XAUUSD When a Gold buy trade reaches +100 pips in profit: - Move the stop-loss to the original entry price. - Once moved to breakeven, the stop-loss must never be moved backward. 11. BUY TRADE EXIT — XAUUSD A BUY position must be closed when EITHER of the following conditions occurs: 1. SUPPLY ZONE EXIT: XAUUSD price reaches or enters a valid active supply zone. OR 2. H1 EMA EXIT: On H1, the 21 EMA crosses below the 55 EMA. The EA should close the buy position once either exit condition has been confirmed. 12. SELL SETUP — XAUUSD A sell trade should only be considered when all required conditions are satisfied. 1. MARKET PHASE: Higher-timeframe Gold structure indicates a downtrend, with a preferred sequence of Lower Lows and Lower Highs. 2. EMA CONFIRMATION: H1 21 EMA < 55 EMA. 3. SUPPLY ZONE: XAUUSD price returns to or touches an active valid supply zone identified on H1, H4 or D1. 4. M15 CONFIRMATION: Once Gold reaches the supply zone, monitor M15 and wait for the first COMPLETED bearish M15 candle formed at or within the supply zone. 5. ENTRY: Execute a SELL order at the close of the first valid bearish M15 confirmation candle. The confirmation candle must be completely closed. The EA must not enter while the M15 candle is still forming. 13. SELL STOP-LOSS — XAUUSD Default sell stop-loss: 100 pips above the open price of the first bearish M15 confirmation candle. The supply-zone boundary must also be considered. Where necessary, the EA should ensure the stop-loss is positioned beyond the relevant supply zone. The exact structural stop-loss rule must be objective and agreed before coding. The developer must implement the 100-pip distance using the broker's actual XAUUSD price/point specifications. 14. SELL BREAKEVEN — XAUUSD When a Gold sell trade reaches +100 pips in profit: - Move the stop-loss to the original entry price. - The stop-loss must not subsequently be moved backward. 15. SELL TRADE EXIT — XAUUSD A SELL position must be closed when EITHER of the following conditions occurs: 1. DEMAND ZONE EXIT: XAUUSD price reaches or enters a valid active demand zone. OR 2. H1 EMA EXIT: On H1, the 21 EMA crosses above the 55 EMA. The EA should close the sell position once either exit condition has been confirmed. 16. XAUUSD RISK MANAGEMENT Default risk per trade: 5% of account equity. The risk percentage must be fully adjustable through EA input settings. Example: RiskPercent = 5.0 Position size must be calculated automatically from: - Account equity - Risk percentage - Stop-loss distance - Actual XAUUSD tick value - Actual XAUUSD tick size - Contract size where applicable - Broker minimum volume - Broker maximum volume - Broker volume step The EA must NOT use a fixed lot size. 17. XAUUSD PIP, POINT, TICK AND VOLUME CALCULATIONS This is a critical development requirement. The developer must use the actual XAUUSD symbol properties supplied by MetaTrader 5 and the broker. Calculations must correctly account for: - Digits - Point size - Tick size - Tick value - Contract size - Volume limits - Volume step The EA must not use hard-coded assumptions that are valid only for a particular broker. The 100-pip stop-loss and 100-pip breakeven distances must be translated correctly for the target broker's XAUUSD specification. 18. XAUUSD TRADE PROTECTION AND EXECUTION The EA must: - Verify that the active symbol is XAUUSD/Gold before opening a trade. - Not open multiple identical trades from the same signal. - Not enter multiple times from the same M15 confirmation candle. - Not enter if the required supply/demand zone is invalid. - Not enter if the market is classified as ranging. - Not enter if required trend/EMA conditions are not satisfied. - Not enter if calculated XAUUSD volume violates broker limits. - Never move a stop-loss backward after breakeven. - Use a unique Magic Number so the EA only manages trades created by itself. - Handle XAUUSD spread, execution errors, trading-session restrictions and market closures safely. 19. RECOMMENDED EA INPUTS XAUUSDOnly = true RiskPercent = 5.0 FastEMA = 21 SlowEMA = 55 ConfirmationTimeframe = M15 BuyStopLossPips = 100 SellStopLossPips = 100 BuyBreakevenPips = 100 SellBreakevenPips = 100 UseSupplyDemandExit = true UseEMAExit = true AllowBuyTrades = true AllowSellTrades = true MagicNumber = [unique number] Where practical, supply/demand detection parameters, zone invalidation parameters and execution filters should also be adjustable. 20. OPTIONAL VISUAL FEATURES The EA should optionally display on the XAUUSD chart: - Active demand zones - Active supply zones - 21 EMA - 55 EMA - Buy and sell entry markers - Stop-loss level - Breakeven status - Current XAUUSD market phase - Relevant timeframe/source of supply and demand zones These features should be controlled through EA settings where practical. 21. COMPLETE XAUUSD SIGNAL SEQUENCE BUY: H1/H4/D1 Gold Uptrend → H1 21 EMA > 55 EMA → XAUUSD reaches valid Demand Zone → Wait for first completed bullish M15 candle → BUY → 100-pip SL → +100 pips → Move SL to Breakeven → Exit at Supply Zone OR H1 21 EMA crosses below 55 EMA SELL: H1/H4/D1 Gold Downtrend → H1 21 EMA < 55 EMA → XAUUSD reaches valid Supply Zone → Wait for first completed bearish M15 candle → SELL → 100-pip SL → +100 pips → Move SL to Breakeven → Exit at Demand Zone OR H1 21 EMA crosses above 55 EMA 22. XAUUSD BACKTESTING AND OPTIMIZATION The EA must be thoroughly tested specifically on XAUUSD before live deployment. Requirements: - Use MetaTrader 5 Strategy Tester with XAUUSD historical data. - Test strong Gold trends, reversals, consolidations and high-volatility periods. - Verify supply/demand zones are detected consistently. - Verify no trade is opened before the M15 confirmation candle closes. - Verify position sizing at different account balances and risk percentages. - Verify 100-pip stop-loss calculations on the target XAUUSD symbol. - Verify 100-pip breakeven logic. - Verify supply/demand exits. - Verify H1 EMA exits. - Check for duplicate entries and repeated signals. - Report key backtest statistics, including net profit, profit factor, drawdown, win rate and number of trades. Optimization must prioritize robustness and must not simply maximize historical profit through excessive curve-fitting. 23. DEVELOPMENT REQUIREMENTS The EA must be developed using objective, rule-based definitions wherever possible. Terms such as: - Strong reaction - Bounce - Valid zone - Higher high - Higher low - Significant displacement - Break of zone must be translated into measurable and reproducible rules in the code. The developer must document these definitions before coding. The programmer must NOT introduce discretionary trading logic that is not contained in this specification without discussing it and receiving approval first. Any assumptions required to convert subjective supply/demand concepts into objective algorithmic rules must be documented and agreed upon before implementation. The primary objective is to create an EA that can consistently reproduce the strategy using the same rules during historical testing, demo trading and live XAUUSD trading. 24. DELIVERABLES The developer must provide: 1. Fully functional .mq5 source code. 2. Compiled .ex5 file. 3. No compilation errors or warnings. 4. Successful XAUUSD Strategy Tester verification. 5. Explanation of the supply/demand detection algorithm. 6. Explanation of all EA input parameters. 7. Backtest report/results. 8. Installation and usage instructions. 9. Confirmation that the EA is restricted to XAUUSD. 25. VISUAL REFERENCE The supplied TradingView Gold 4H chart should be provided to the developer alongside this specification as a visual reference for the intended appearance and interpretation of the supply and demand zones. The orange horizontal areas demonstrate that the zones should be represented as areas/ranges rather than single horizontal lines. The price levels shown on the reference chart are examples only and must NOT be hard-coded into the EA. 26. DEVELOPER PRE-CODING CHECKLIST Before development begins, the developer should confirm: - Previous experience developing automated XAUUSD/Gold trading systems. - Exact algorithm for identifying swing highs and swing lows. - Objective rules for creating a Gold supply or demand zone. - Objective rules for zone strength and invalidation. - How overlapping H1/H4/D1 zones will be consolidated. - Exact XAUUSD pip/point/tick calculations for the target broker. - Exact interpretation of a completed M15 confirmation candle. - Position and duplicate-entry policy. - XAUUSD backtesting procedure. - Delivery of editable .mq5 source code and compiled .ex5 file. END OF SPECIFICATION