Gold Expert Advisor MT5: Free MQL5 Code + Full Backtest Guide

A free, complete MQL5 Expert Advisor for gold (XAUUSD) on MetaTrader 5 using trend-following logic with ATR-based filtering. Full source code included with installation guide.

gold expert advisor free downloadgold EA MT5 freeXAUUSD expert advisor MT5best gold robot mt5

Backtest Performance

58.7%
Win Rate
18.5%
Max Drawdown
1.21
Sharpe Ratio
2021–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

Enter long when the 50-period EMA is above the 200-period EMA and price pulls back to the 50 EMA with RSI below 50. Enter short on opposite conditions. ATR must exceed a minimum threshold to confirm trending conditions.

Exit Conditions

Take profit at 2x ATR from entry, stop loss at 1x ATR. Trailing stop activates after 1x ATR profit, locking in gains as price extends.

MQL5 Expert Advisor Code

//+------------------------------------------------------------------+
//| Gold Trend EA - XAUUSD H1 (Free Version)                        |
//| Pineify.app — generate custom EAs at pineify.app/mql5           |
//+------------------------------------------------------------------+
#property copyright "Pineify.app"
#property version   "1.00"

input int    MagicNumber = 234567;
input double RiskPercent = 1.0;
input int    ATR_Period  = 14;
input double ATR_SL_Mult = 1.0;
input double ATR_TP_Mult = 2.0;

int ema50Handle, ema200Handle, atrHandle, rsiHandle;
double ema50[], ema200[], atr[], rsi[];

int OnInit() {
   ema50Handle  = iMA(_Symbol, PERIOD_H1, 50,  0, MODE_EMA, PRICE_CLOSE);
   ema200Handle = iMA(_Symbol, PERIOD_H1, 200, 0, MODE_EMA, PRICE_CLOSE);
   atrHandle    = iATR(_Symbol, PERIOD_H1, ATR_Period);
   rsiHandle    = iRSI(_Symbol, PERIOD_H1, 14, PRICE_CLOSE);
   ArraySetAsSeries(ema50, true); ArraySetAsSeries(ema200, true);
   ArraySetAsSeries(atr, true);   ArraySetAsSeries(rsi, true);
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason) {
   IndicatorRelease(ema50Handle); IndicatorRelease(ema200Handle);
   IndicatorRelease(atrHandle);   IndicatorRelease(rsiHandle);
}

void OnTick() {
   if (!IsNewBar(PERIOD_H1)) return;
   CopyBuffer(ema50Handle, 0, 0, 3, ema50);
   CopyBuffer(ema200Handle, 0, 0, 3, ema200);
   CopyBuffer(atrHandle, 0, 0, 3, atr);
   CopyBuffer(rsiHandle, 0, 0, 3, rsi);

   if (CountPositions(MagicNumber) > 0) return;

   double lots = CalcLots(atr[1] * ATR_SL_Mult);
   bool upTrend   = ema50[1] > ema200[1];
   bool downTrend = ema50[1] < ema200[1];
   double close1 = iClose(_Symbol, PERIOD_H1, 1);

   if (upTrend && close1 <= ema50[1] && rsi[1] < 50)
      OpenTrade(ORDER_TYPE_BUY, lots, atr[1] * ATR_SL_Mult, atr[1] * ATR_TP_Mult, MagicNumber);
   else if (downTrend && close1 >= ema50[1] && rsi[1] > 50)
      OpenTrade(ORDER_TYPE_SELL, lots, atr[1] * ATR_SL_Mult, atr[1] * ATR_TP_Mult, MagicNumber);
}

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

double CalcLots(double slPoints) {
   double tickVal = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tickSz  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double balance = AccountInfoDouble(ACCOUNT_BALANCE);
   double risk    = balance * RiskPercent / 100.0;
   double lots    = risk / (slPoints / tickSz * tickVal);
   double minLot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double step    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   lots = MathFloor(lots / step) * step;
   return MathMax(minLot, MathMin(maxLot, lots));
}

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

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 Gold EA";
   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