Complete .mq5 source code

Gold Scalping EA MT5: AI-Generated XAUUSD Scalper with Backtest Results

A complete MQL5 scalping Expert Advisor for XAUUSD (Gold) on MetaTrader 5, featuring ATR-based take profit/stop loss, spread filter, and news-time avoidance logic.

Historical test results

61.4%
Win Rate
14.2%
Max Drawdown
1.38
Sharpe Ratio
2022–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 price crosses above the 20-period EMA on M5 and ATR spread is below the configured maximum. Enter short on opposite conditions. A session time filter restricts trades to London and New York session overlaps for optimal gold liquidity.

Exit conditions

Exit positions at ATR multiplier x 1.5 for take profit and ATR x 1.0 for stop loss. A trailing stop activates after price moves 50% toward the take profit level. All positions close before major news events identified via time-based filter.

MQL5 Expert Advisor Code

//+------------------------------------------------------------------+
//| Gold Scalping EA - XAUUSD M5                                     |
//| Generated by Pineify AI | pineify.app                           |
//+------------------------------------------------------------------+
#property copyright "Pineify.app"
#property version   "1.00"
#property strict

// Input parameters
input int    MagicNumber  = 123456;
input double Lots         = 0.01;
input int    ATR_Period   = 14;
input double ATR_SL_Mult  = 1.0;
input double ATR_TP_Mult  = 1.5;
input int    MaxSpread    = 30;   // Max spread in points
input int    SessionStart = 8;    // Hour (server time)
input int    SessionEnd   = 17;   // Hour (server time)

int    emaHandle;
int    atrHandle;
double emaBuffer[];
double atrBuffer[];

int OnInit() {
   emaHandle = iMA(_Symbol, PERIOD_M5, 20, 0, MODE_EMA, PRICE_CLOSE);
   atrHandle = iATR(_Symbol, PERIOD_M5, ATR_Period);
   if (emaHandle == INVALID_HANDLE || atrHandle == INVALID_HANDLE) return INIT_FAILED;
   ArraySetAsSeries(emaBuffer, true);
   ArraySetAsSeries(atrBuffer, true);
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason) {
   IndicatorRelease(emaHandle);
   IndicatorRelease(atrHandle);
}

void OnTick() {
   MqlTick tick;
   if (!SymbolInfoTick(_Symbol, tick)) return;

   // Session filter
   MqlDateTime dt;
   TimeToStruct(tick.time, dt);
   if (dt.hour < SessionStart || dt.hour >= SessionEnd) return;

   // Spread filter
   double spread = (tick.ask - tick.bid) / _Point;
   if (spread > MaxSpread) return;

   // Get indicator values
   if (CopyBuffer(emaHandle, 0, 0, 3, emaBuffer) < 3) return;
   if (CopyBuffer(atrHandle, 0, 0, 3, atrBuffer) < 3) return;

   double atr = atrBuffer[1];
   double ema = emaBuffer[1];
   double prevClose = iClose(_Symbol, PERIOD_M5, 1);
   double prevOpen  = iOpen(_Symbol, PERIOD_M5, 1);

   // Count open positions
   int pos = CountPositions(MagicNumber);
   if (pos > 0) return;

   double sl = atr * ATR_SL_Mult;
   double tp = atr * ATR_TP_Mult;

   // Long entry: close crosses above EMA
   if (prevClose > ema && prevOpen < ema) {
      OpenTrade(ORDER_TYPE_BUY, Lots, sl, tp, MagicNumber);
   }
   // Short entry: close crosses below EMA
   else if (prevClose < ema && prevOpen > ema) {
      OpenTrade(ORDER_TYPE_SELL, Lots, sl, tp, MagicNumber);
   }
}

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 Scalper";
   req.type_filling = ORDER_FILLING_IOC;
   OrderSend(req, res);
}

Copy this code into MetaEditor, save it in the MQL5/Experts folder, and compile with F7.

Generate a custom XAUUSD scalping EA

Describe the ATR inputs, alert rules, visual style, or confirmation filter you want. Pineify generates editable MQL5 source code that you can inspect and compile in MetaEditor.

Pine Script vs MQL5: Same Strategy, Different Platforms

AspectPine Script (TradingView)MQL5 (MetaTrader 5)
ExecutionSeries evaluated on chart updatesEvent handlers with explicit buffers
DeploymentRuns in TradingView with alertsRuns in the MT5 terminal or on a VPS
Broker accessVia TradingView broker integrationDirect broker connectivity
BacktestingStrategy Tester for strategy scriptsStrategy Tester for Expert Advisors
Code complexitySimpler, functional syntaxC++-like, more powerful

The calculation can be implemented on either platform, but the runtime model and buffer APIs differ. Read the Pine Script Supertrend reference before porting logic between them.

Frequently Asked Questions

Related MQL5 pages

Risk and testing note

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.