XAUUSD Expert Advisor MT5: Complete MQL5 Guide with Code & Stats

The complete guide to building and running a XAUUSD Expert Advisor in MetaTrader 5. Covers EA architecture, MQL5 code, backtest methodology, and live performance expectations for gold trading.

XAUUSD expert advisor MT5gold EA mql5XAUUSD MQL5 EAbest mt5 ea for gold trading

Backtest Performance

56.3%
Win Rate
16.9%
Max Drawdown
1.29
Sharpe Ratio
2020–2025
Test Period

Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.

Strategy Logic

Entry Conditions

Trend-following logic using 50/200 EMA crossover on H1 timeframe. Enter long on golden cross with ADX above 25 confirming trend strength. Enter short on death cross with same ADX confirmation. Minimum ATR threshold filters low-volatility periods.

Exit Conditions

Fixed risk-reward of 1:2 with ATR-based stop loss calculation. Trailing stop engages after price moves 1x ATR in profit direction. Emergency close triggers if daily drawdown exceeds 5% of account balance.

MQL5 Expert Advisor Code

//+------------------------------------------------------------------+
//| XAUUSD Expert Advisor - Trend Following H1                      |
//| Pineify.app                                                      |
//+------------------------------------------------------------------+
#property copyright "Pineify.app"
#property version   "1.00"

input int    MagicNumber  = 456789;
input double RiskPercent  = 1.0;
input int    EMA_Fast     = 50;
input int    EMA_Slow     = 200;
input int    ADX_Period   = 14;
input double ADX_Min      = 25.0;
input int    ATR_Period   = 14;

int emaFastH, emaSlowH, adxH, atrH;
double emaFast[], emaSlow[], adxMain[], atrBuf[];

int OnInit() {
   emaFastH = iMA(_Symbol, PERIOD_H1, EMA_Fast, 0, MODE_EMA, PRICE_CLOSE);
   emaSlowH = iMA(_Symbol, PERIOD_H1, EMA_Slow, 0, MODE_EMA, PRICE_CLOSE);
   adxH     = iADX(_Symbol, PERIOD_H1, ADX_Period);
   atrH     = iATR(_Symbol, PERIOD_H1, ATR_Period);
   ArraySetAsSeries(emaFast, true); ArraySetAsSeries(emaSlow, true);
   ArraySetAsSeries(adxMain, true); ArraySetAsSeries(atrBuf, true);
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason) {
   IndicatorRelease(emaFastH); IndicatorRelease(emaSlowH);
   IndicatorRelease(adxH); IndicatorRelease(atrH);
}

void OnTick() {
   if (!IsNewBar(PERIOD_H1)) return;
   CopyBuffer(emaFastH, 0, 0, 3, emaFast);
   CopyBuffer(emaSlowH, 0, 0, 3, emaSlow);
   CopyBuffer(adxH, 0, 0, 3, adxMain);
   CopyBuffer(atrH, 0, 0, 3, atrBuf);

   if (CountPositions(MagicNumber) > 0) return;

   bool adxConfirm = adxMain[1] >= ADX_Min;
   double atr = atrBuf[1];
   double sl  = atr * 1.0;
   double tp  = atr * 2.0;
   double lots = CalcLots(sl);

   bool goldenCross = emaFast[2] < emaSlow[2] && emaFast[1] > emaSlow[1];
   bool deathCross  = emaFast[2] > emaSlow[2] && emaFast[1] < emaSlow[1];

   if (goldenCross && adxConfirm) OpenTrade(ORDER_TYPE_BUY,  lots, sl, tp, MagicNumber);
   if (deathCross  && adxConfirm) OpenTrade(ORDER_TYPE_SELL, lots, sl, tp, MagicNumber);
}

bool IsNewBar(ENUM_TIMEFRAMES tf) {
   static datetime last = 0;
   datetime cur = iTime(_Symbol, tf, 0);
   if (cur != last) { last = cur; return true; } return false;
}

double CalcLots(double slPts) {
   double tv  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double ts  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double bal = AccountInfoDouble(ACCOUNT_BALANCE);
   double lot = (bal * RiskPercent / 100.0) / (slPts / ts * tv);
   double stp = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   return MathMax(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN),
          MathMin(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX),
          MathFloor(lot / stp) * stp));
}

int CountPositions(int magic) {
   int n = 0;
   for (int i = PositionsTotal()-1; i >= 0; i--) {
      ulong t = PositionGetTicket(i);
      if (PositionSelectByTicket(t) && PositionGetString(POSITION_SYMBOL)==_Symbol &&
          (int)PositionGetInteger(POSITION_MAGIC)==magic) n++;
   } return n;
}

void OpenTrade(ENUM_ORDER_TYPE type, double lots, double sl, double tp, int magic) {
   MqlTradeRequest req={}; MqlTradeResult res={};
   req.action=TRADE_ACTION_DEAL; req.symbol=_Symbol; req.volume=lots; req.type=type;
   req.price=(type==ORDER_TYPE_BUY)?SymbolInfoDouble(_Symbol,SYMBOL_ASK):SymbolInfoDouble(_Symbol,SYMBOL_BID);
   req.sl=(type==ORDER_TYPE_BUY)?req.price-sl:req.price+sl;
   req.tp=(type==ORDER_TYPE_BUY)?req.price+tp:req.price-tp;
   req.magic=magic; req.comment="Pineify XAUUSD"; req.type_filling=ORDER_FILLING_IOC;
   OrderSend(req,res);
}

Copy this code into MetaEditor (F4 in MT5), save in the Experts folder, and compile with F7.

Generate a Custom XAUUSD Trend-following EA →

Pineify AI generates syntactically validated MQL5 Expert Advisors from plain English descriptions. Customize entry logic, risk management, and trading sessions — no coding required.

Pine Script vs MQL5: Same Strategy, Different Platforms

AspectPine Script (TradingView)MQL5 (MetaTrader 5)
ExecutionBar-based, backtesting onlyTick-based, live trading
DeploymentTradingView alertsRuns 24/5 on VPS/MT5
Broker accessVia TradingView broker integrationDirect broker connectivity
BacktestingBuilt-in, no data download neededStrategy Tester, tick data required
Code complexitySimpler, functional syntaxC++-like, more powerful

Pineify supports both platforms. Prototype your strategy visually in TradingView Pine Script, then generate the equivalent MQL5 EA for live MT5 trading.

Frequently Asked Questions

Related MQL5 Expert Advisors