Complete .mq5 source code

MQL5 Swing Trading EA: H4 Signals and ATR Stop Logic

Read a single-symbol H4 Expert Advisor built around EMA crossovers, an RSI level filter and ATR-based initial and trailing stops. Positions have no fixed holding period. The sample has fixed lots and no published, reproducible performance report.

Strategy logic

Entry conditions

A completed-bar fast EMA cross above the slow EMA with RSI above 50 permits a long; the reverse cross with RSI below 50 permits a short. The current spread must be below a fixed point threshold, not an ATR multiple. Only one matching symbol-and-magic position is allowed. There is no economic-calendar or independent news filter.

Exit conditions

Initial SL is 1.5 times the completed H4 ATR from the requested entry quote by default, not beyond the entry candle extreme. Once per new H4 bar, trailing activates at a favorable move of one current ATR and proposes a stop 1.5 current ATR behind price. At activation that can still be below break-even. There is no fixed TP, reverse-cross exit, or maximum holding duration; opposite signals are ignored while a matching position remains open.

MQL5 Expert Advisor Code

//+------------------------------------------------------------------+
//|  SwingTradingEA.mq5                                              |
//|  MQL5 Swing Trading Expert Advisor                               |
//|  Uses EMA crossover + RSI filter + ATR-based stops               |
//+------------------------------------------------------------------+
#property copyright "Pineify Example — Educational Use Only"
#property version   "1.00"
#property strict

//--- Input parameters
input int    FastEMA_Period   = 20;       // Fast EMA period
input int    SlowEMA_Period   = 50;       // Slow EMA period
input int    RSI_Period       = 14;       // RSI period
input int    ATR_Period       = 14;       // ATR period
input double ATR_SL_Mult      = 1.5;      // ATR multiplier for stop loss
input double ATR_Trail_Mult   = 1.0;      // ATR multiplier to activate trailing stop
input double LotSize          = 0.10;     // Fixed lot size
input int    MaxSpreadPoints  = 30;       // Max allowed spread in points
input ulong  MagicNumber      = 20240001; // EA magic number

//--- Indicator handles
int handleFastEMA = INVALID_HANDLE;
int handleSlowEMA = INVALID_HANDLE;
int handleRSI = INVALID_HANDLE;
int handleATR = INVALID_HANDLE;

//--- Global state
datetime lastBarTime = 0;

//+------------------------------------------------------------------+
//| Expert initialisation                                            |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(FastEMA_Period<=0 || SlowEMA_Period<=0 || RSI_Period<=0 || ATR_Period<=0
      || ATR_SL_Mult<=0 || ATR_Trail_Mult<=0 || LotSize<=0 || MaxSpreadPoints<0 || MagicNumber==0)
      return INIT_PARAMETERS_INCORRECT;
   handleFastEMA = iMA(_Symbol, PERIOD_H4, FastEMA_Period, 0, MODE_EMA, PRICE_CLOSE);
   handleSlowEMA = iMA(_Symbol, PERIOD_H4, SlowEMA_Period, 0, MODE_EMA, PRICE_CLOSE);
   handleRSI     = iRSI(_Symbol, PERIOD_H4, RSI_Period, PRICE_CLOSE);
   handleATR     = iATR(_Symbol, PERIOD_H4, ATR_Period);

   if(handleFastEMA == INVALID_HANDLE ||
      handleSlowEMA == INVALID_HANDLE ||
      handleRSI     == INVALID_HANDLE ||
      handleATR     == INVALID_HANDLE)
     {
      Print("Failed to create indicator handles. EA stopping.");
      return INIT_FAILED;
     }

   Print("SwingTradingEA initialised on ", _Symbol);
   return INIT_SUCCEEDED;
  }

//+------------------------------------------------------------------+
//| Expert deinitialization                                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   IndicatorRelease(handleFastEMA);
   IndicatorRelease(handleSlowEMA);
   IndicatorRelease(handleRSI);
   IndicatorRelease(handleATR);
   Print("SwingTradingEA removed. Reason: ", reason);
  }

//+------------------------------------------------------------------+
//| Helper: get indicator value at shift                             |
//+------------------------------------------------------------------+
double GetValue(int handle, int shift)
  {
   double buf[];
   ArraySetAsSeries(buf, true);
   if(CopyBuffer(handle, 0, shift, 1, buf) <= 0)
      return EMPTY_VALUE;
   return buf[0];
  }

//+------------------------------------------------------------------+
//| Helper: check if a position with magic exists                    |
//+------------------------------------------------------------------+
bool PositionExists(ENUM_POSITION_TYPE posType)
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(PositionSelectByTicket(ticket))
         if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
            PositionGetInteger(POSITION_MAGIC)  == MagicNumber &&
            PositionGetInteger(POSITION_TYPE)   == posType)
            return true;
     }
   return false;
  }

//+------------------------------------------------------------------+
//| Helper: send a market order                                      |
//+------------------------------------------------------------------+
bool SendOrder(ENUM_ORDER_TYPE orderType, double sl, double tp)
  {
   MqlTradeRequest  request = {};
   MqlTradeResult   result  = {};

   request.action    = TRADE_ACTION_DEAL;
   request.symbol    = _Symbol;
   request.volume    = LotSize;
   request.type      = orderType;
   request.price     = (orderType == ORDER_TYPE_BUY)
                       ? SymbolInfoDouble(_Symbol, SYMBOL_ASK)
                       : SymbolInfoDouble(_Symbol, SYMBOL_BID);
   request.sl        = sl;
   request.tp        = tp;
   request.magic     = MagicNumber;
   request.comment   = "SwingEA";
   request.type_filling = ORDER_FILLING_FOK;

   if(!OrderSend(request, result) || result.retcode!=TRADE_RETCODE_DONE)
     {
      Print("OrderSend failed. Error: ", GetLastError(),
            " Retcode: ", result.retcode);
      return false;
     }
   Print("Order placed. Ticket: ", result.order,
         " Type: ", EnumToString(orderType),
         " Price: ", result.price,
         " SL: ", sl);
   return true;
  }

//+------------------------------------------------------------------+
//| Helper: update trailing stop for open positions                  |
//+------------------------------------------------------------------+
void ManageTrailingStop()
  {
   double atr = GetValue(handleATR, 1);
   if(atr == EMPTY_VALUE || atr<=0) return;

   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(!PositionSelectByTicket(ticket)) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol)    continue;
      if(PositionGetInteger(POSITION_MAGIC)  != MagicNumber) continue;

      double openPrice  = PositionGetDouble(POSITION_PRICE_OPEN);
      double currentSL  = PositionGetDouble(POSITION_SL);
      ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);

      if(posType == POSITION_TYPE_BUY)
        {
         double bid       = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         double trailSL   = bid - ATR_SL_Mult * atr;
         double activateAt= openPrice + ATR_Trail_Mult * atr;
         if(bid >= activateAt && trailSL > currentSL + _Point)
           {
            MqlTradeRequest req = {}; MqlTradeResult res = {};
            req.action   = TRADE_ACTION_SLTP;
            req.position = ticket;
            req.symbol   = _Symbol;
            req.sl       = NormalizeDouble(trailSL, _Digits);
            req.tp       = PositionGetDouble(POSITION_TP);
            if(!OrderSend(req,res) || res.retcode!=TRADE_RETCODE_DONE)
               Print("Trailing request failed: ",res.retcode);
           }
        }
      else if(posType == POSITION_TYPE_SELL)
        {
         double ask       = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
         double trailSL   = ask + ATR_SL_Mult * atr;
         double activateAt= openPrice - ATR_Trail_Mult * atr;
         if(ask <= activateAt && (currentSL == 0 || trailSL < currentSL - _Point))
           {
            MqlTradeRequest req = {}; MqlTradeResult res = {};
            req.action   = TRADE_ACTION_SLTP;
            req.position = ticket;
            req.symbol   = _Symbol;
            req.sl       = NormalizeDouble(trailSL, _Digits);
            req.tp       = PositionGetDouble(POSITION_TP);
            if(!OrderSend(req,res) || res.retcode!=TRADE_RETCODE_DONE)
               Print("Trailing request failed: ",res.retcode);
           }
        }
     }
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   //--- Only act on new H4 bar
   datetime currentBar = iTime(_Symbol, PERIOD_H4, 0);
   if(currentBar == lastBarTime) return;
   if(currentBar<=0) return;

   //--- Manage trailing stops every new bar
   ManageTrailingStop();

   //--- Spread filter
   long spreadPoints = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
   if(spreadPoints > MaxSpreadPoints)
     {
      lastBarTime=currentBar;
      Print("Spread too wide (", spreadPoints, " pts). Skipping bar.");
      return;
     }

   //--- Read indicator values (bar 1 = last closed bar)
   double fastNow  = GetValue(handleFastEMA, 1);
   double fastPrev = GetValue(handleFastEMA, 2);
   double slowNow  = GetValue(handleSlowEMA, 1);
   double slowPrev = GetValue(handleSlowEMA, 2);
   double rsi      = GetValue(handleRSI,     1);
   double atr      = GetValue(handleATR,     1);

   if(fastNow == EMPTY_VALUE || fastPrev == EMPTY_VALUE || slowPrev == EMPTY_VALUE || slowNow == EMPTY_VALUE ||
      rsi     == EMPTY_VALUE || atr     == EMPTY_VALUE || atr<=0)
      return;

   lastBarTime=currentBar;
   if(PositionExists(POSITION_TYPE_BUY) || PositionExists(POSITION_TYPE_SELL)) return;
   bool bullCross = (fastPrev <= slowPrev) && (fastNow > slowNow);
   bool bearCross = (fastPrev >= slowPrev) && (fastNow < slowNow);

   //--- Long entry
   if(bullCross && rsi > 50 && !PositionExists(POSITION_TYPE_BUY))
     {
      double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      double sl  = NormalizeDouble(ask - ATR_SL_Mult * atr, _Digits);
      SendOrder(ORDER_TYPE_BUY, sl, 0);
     }

   //--- Short entry
   if(bearCross && rsi < 50 && !PositionExists(POSITION_TYPE_SELL))
     {
      double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double sl  = NormalizeDouble(bid + ATR_SL_Mult * atr, _Digits);
      SendOrder(ORDER_TYPE_SELL, sl, 0);
     }
  }
//+------------------------------------------------------------------+

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

Generate a custom Multi-pair swing-trading EA

Describe the entry, exit, position, order, and risk rules 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 accessStrategy orders are simulated; live automation needs a separate 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.

Frequently Asked Questions

Related MQL5 pages

Risk and testing note

These educational examples require independent compilation and testing. A compile pass or an illustrative setting does not establish execution correctness or profitability. Any reported performance must be supported by reproducible data and test settings; past results do not predict future returns. Trading involves significant risk of loss. This content is not financial advice.