Complete .mq5 source code

MQL5 Expert Advisor Free Source: EMA/RSI Template and Setup

Copy the visible MQL5 example into a .mq5 file and inspect it in MetaEditor. This page provides one educational chart-symbol EA, not a library of downloadable binaries or a tested multi-pair system. The template demonstrates handles, completed-bar signals, CTrade requests, and position filtering. Access to this displayed source does not imply free or unlimited Pineify AI generation, and the example is not production-certified.

Strategy logic

Entry conditions

Once per chart bar, the EA reads the two completed EMA bars and completed RSI. When no matching position exists, it buys if the fast EMA is above the slow EMA and RSI is below its upper threshold, or sells under the inverse EMA relationship with RSI above its lower threshold. Entry is a level condition, not a fresh crossover: after an exit, a later bar may re-enter the same trend. Fixed lots do not keep cash risk constant across symbols.

Exit conditions

An opposite completed-bar EMA crossover requests closure of a matching position. Initial SL and TP are expressed in broker points through CTrade. Optional trailing checks on ticks and tightens the stop to a fixed distance from the current exit quote; it has no profit activation threshold and can tighten while the position is losing. Stop orders do not cap losses through gaps or guarantee a fill price. The sample uses symbol-selected filling mode and checks server return codes, but broker volume steps, stop/freeze levels, and tick sizes can still reject requests.

MQL5 Expert Advisor Code

//+------------------------------------------------------------------+
//|  FreeEA_ChartSymbol.mq5                                            |
//|  A free MQL5 Expert Advisor template using EMA cross + RSI       |
//|  For educational purposes only. Not financial advice.            |
//+------------------------------------------------------------------+
#property copyright "Pineify - pineify.app"
#property link      "https://pineify.app"
#property version   "1.00"
#property strict

#include <Trade/Trade.mqh>

//--- Input parameters
input int    FastEmaPeriod   = 10;       // Fast EMA period
input int    SlowEmaPeriod   = 30;       // Slow EMA period
input int    RsiPeriod       = 14;       // RSI period
input double RsiOverbought   = 70.0;     // RSI overbought level
input double RsiOversold     = 30.0;     // RSI oversold level
input double LotSize         = 0.10;     // Trade lot size
input int    StopLossPoints  = 500;      // Stop loss in points
input int    TakeProfitPoints = 1000;    // Take profit in points
input bool   UseTrailingStop = true;     // Enable trailing stop
input int    TrailingPoints  = 300;      // Trailing stop distance in points
input ulong  MagicNumber     = 20240001; // EA magic number

//--- Global handles and objects
int    g_handleFastEma = INVALID_HANDLE;
int    g_handleSlowEma = INVALID_HANDLE;
int    g_handleRsi     = INVALID_HANDLE;
CTrade g_trade;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(FastEmaPeriod <= 0 || SlowEmaPeriod <= FastEmaPeriod || RsiPeriod <= 0 ||
      RsiOversold < 0 || RsiOverbought > 100 || RsiOversold >= RsiOverbought ||
      LotSize <= 0 || StopLossPoints <= 0 || TakeProfitPoints <= 0 || TrailingPoints <= 0)
      return INIT_PARAMETERS_INCORRECT;
   //--- Create indicator handles
   g_handleFastEma = iMA(_Symbol, PERIOD_CURRENT, FastEmaPeriod, 0, MODE_EMA, PRICE_CLOSE);
   g_handleSlowEma = iMA(_Symbol, PERIOD_CURRENT, SlowEmaPeriod, 0, MODE_EMA, PRICE_CLOSE);
   g_handleRsi     = iRSI(_Symbol, PERIOD_CURRENT, RsiPeriod, PRICE_CLOSE);

   if(g_handleFastEma == INVALID_HANDLE ||
      g_handleSlowEma == INVALID_HANDLE ||
      g_handleRsi     == INVALID_HANDLE)
     {
      Print("ERROR: Failed to create indicator handles. EA cannot start.");
      return(INIT_FAILED);
     }

   //--- Configure trade object
   g_trade.SetExpertMagicNumber(MagicNumber);
   g_trade.SetDeviationInPoints(10);
   g_trade.SetTypeFillingBySymbol(_Symbol);
   g_trade.SetAsyncMode(false);

   Print("FreeEA_ChartSymbol initialized on ", _Symbol,
         " | Fast EMA:", FastEmaPeriod,
         " | Slow EMA:", SlowEmaPeriod,
         " | RSI:", RsiPeriod);
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   //--- Release indicator handles to free memory
   if(g_handleFastEma != INVALID_HANDLE) IndicatorRelease(g_handleFastEma);
   if(g_handleSlowEma != INVALID_HANDLE) IndicatorRelease(g_handleSlowEma);
   if(g_handleRsi     != INVALID_HANDLE) IndicatorRelease(g_handleRsi);

   Print("FreeEA_ChartSymbol deinitialized. Reason code: ", reason);
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(UseTrailingStop) ManageTrailingStop();
   //--- Entry and crossover exits are evaluated once per bar
   static datetime s_lastBarTime = 0;
   datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(currentBarTime <= 0 || currentBarTime == s_lastBarTime) return;

   //--- Copy indicator buffers (index 1 = previous closed bar)
   double fastEma[2], slowEma[2], rsi[2];
   if(CopyBuffer(g_handleFastEma, 0, 1, 2, fastEma) < 2) return;
   if(CopyBuffer(g_handleSlowEma, 0, 1, 2, slowEma) < 2) return;
   if(CopyBuffer(g_handleRsi,     0, 1, 2, rsi)     < 2) return;

   s_lastBarTime = currentBarTime;
   //--- Static arrays: index 0 is bar 2; index 1 is completed bar 1
   bool emaBullishCross = (fastEma[1] > slowEma[1]) && (fastEma[0] <= slowEma[0]);  // prev crossed above
   bool emaBearishCross = (fastEma[1] < slowEma[1]) && (fastEma[0] >= slowEma[0]);  // prev crossed below

   // Note: index 1 is the most recently closed bar
   bool emaBullCurrent  = fastEma[1] > slowEma[1];
   bool emaBearCurrent  = fastEma[1] < slowEma[1];

   double rsiValue = rsi[1];

   //--- Check if we already hold a position for this symbol + magic
   bool hasLong  = HasPosition(POSITION_TYPE_BUY);
   bool hasShort = HasPosition(POSITION_TYPE_SELL);

   //--- Entry uses EMA level plus RSI; a fresh crossover is not required
   if(!hasLong && !hasShort)
     {
      if(emaBullCurrent && rsiValue < RsiOverbought)
        {
         OpenBuy();
        }
      else if(emaBearCurrent && rsiValue > RsiOversold)
        {
         OpenSell();
        }
     }

   //--- Exit logic: close on opposing cross
   if(hasLong && emaBearishCross)
      ClosePositions(POSITION_TYPE_BUY);

   if(hasShort && emaBullishCross)
      ClosePositions(POSITION_TYPE_SELL);
  }

bool CheckTradeResult(bool sent, string action)
  {
   uint code = g_trade.ResultRetcode();
   bool completed = sent && (code == TRADE_RETCODE_DONE || code == TRADE_RETCODE_DONE_PARTIAL);
   if(!completed) Print(action, " not completed: ", code, " ", g_trade.ResultRetcodeDescription());
   return completed;
  }

//+------------------------------------------------------------------+
//| Open a BUY position                                              |
//+------------------------------------------------------------------+
void OpenBuy()
  {
   double ask        = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double point      = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   double sl         = ask - StopLossPoints   * point;
   double tp         = ask + TakeProfitPoints * point;

   sl = NormalizeDouble(sl, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
   tp = NormalizeDouble(tp, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));

   CheckTradeResult(g_trade.Buy(LotSize, _Symbol, ask, sl, tp, "FreeEA Buy"), "Buy");
  }

//+------------------------------------------------------------------+
//| Open a SELL position                                             |
//+------------------------------------------------------------------+
void OpenSell()
  {
   double bid        = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double point      = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   double sl         = bid + StopLossPoints   * point;
   double tp         = bid - TakeProfitPoints * point;

   sl = NormalizeDouble(sl, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
   tp = NormalizeDouble(tp, (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));

   CheckTradeResult(g_trade.Sell(LotSize, _Symbol, bid, sl, tp, "FreeEA Sell"), "Sell");
  }

//+------------------------------------------------------------------+
//| Close all positions of given type for this symbol               |
//+------------------------------------------------------------------+
void ClosePositions(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)  == (long)MagicNumber &&
            (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == posType)
           {
            CheckTradeResult(g_trade.PositionClose(ticket), "Close");
           }
        }
     }
  }

//+------------------------------------------------------------------+
//| Check if a position of given type exists                        |
//+------------------------------------------------------------------+
bool HasPosition(ENUM_POSITION_TYPE posType)
  {
   for(int i = 0; i < PositionsTotal(); i++)
     {
      ulong ticket = PositionGetTicket(i);
      if(PositionSelectByTicket(ticket))
        {
         if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
            PositionGetInteger(POSITION_MAGIC)  == (long)MagicNumber &&
            (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == posType)
            return true;
        }
     }
   return false;
  }

//+------------------------------------------------------------------+
//| Manage trailing stop for open positions                         |
//+------------------------------------------------------------------+
void ManageTrailingStop()
  {
   double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   int    digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);

   for(int i = 0; i < PositionsTotal(); i++)
     {
      ulong ticket = PositionGetTicket(i);
      if(!PositionSelectByTicket(ticket)) continue;
      if(PositionGetString(POSITION_SYMBOL) != _Symbol)      continue;
      if(PositionGetInteger(POSITION_MAGIC) != (long)MagicNumber) continue;

      ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      double currentSL = PositionGetDouble(POSITION_SL);
      double newSL     = 0.0;

      if(type == POSITION_TYPE_BUY)
        {
         double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         newSL = NormalizeDouble(bid - TrailingPoints * point, digits);
         if(newSL > currentSL + point)
            CheckTradeResult(g_trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP)), "Trail");
        }
      else if(type == POSITION_TYPE_SELL)
        {
         double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
         newSL = NormalizeDouble(ask + TrailingPoints * point, digits);
         if(newSL < currentSL - point || currentSL == 0.0)
            CheckTradeResult(g_trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP)), "Trail");
        }
     }
  }
//+------------------------------------------------------------------+

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

Generate a custom Multi-pair resource 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.