Home / Articles / #1



/imgs/articles/Metabacktest-article-1-backtesting-cover.jpg



Is a simple 'EMA-CrossOver' strategy, a winning one for the long term?


Hadi

2024-08-19 09:32:32



In this article, we will develop a MQL4 Expert Advisor from the ground up, designed to execute automatic trades based on exponential moving average (EMA) crossovers. Subsequently, we will conduct a backtest utilizing high-quality data spanning over a decade across various currency pairs. This analysis aims to determine the long-term efficacy of this straightforward trading strategy.



Let us begin by initiating the creation of a new Expert Advisor file

  • Open the MetaEditor window by clicking the icon or by pressing F4 on the terminal.
  • Select “File” -> “New” -> “Expert Advisor (template)”.
  • Name the file “EMA-CrossOver” and click “Next” -> “Next” -> “Finish”.


//+------------------------------------------------------------------+
//|                                                EMA-CrossOver.mq4 |
//|                                    Copyright 2024, MetaBacktest. |
//|                                     https://www.MetaBacktest.com |
//+------------------------------------------------------------------+

#property copyright   "Copyright 2024, MetaBacktest."
#property link      "https://www.MetaBacktest.com"
#property version   "1.00"
#property strict


//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
  }
//+------------------------------------------------------------------+


         

isNewCandle()   Function

Lets now write out a function we shall call isNewCandle() that will run its code whenever a new candle opens. The eventual consequence of this method will be better efficiency of algorithms and decrease in false EMA impulses caused by price modifications during the opening times of candlesticks.




//+------------------------------------------------------------------+ 
bool    IsNewCanlde()
{
    //--- memorize the time of opening of the last bar in the static variable
    static datetime last_time=0;
    //--- Get current time
    datetime lastbar_time=SeriesInfoInteger(Symbol(),Period(),SERIES_LASTBAR_DATE);
    //--- See if it is the first call of the function
    if(last_time==0)
    {
    //--- set the time then exit
    last_time=lastbar_time;
    return(false);
    }
    //--- if the time differs
    if(last_time!=lastbar_time)
    {
    //--- memorize the time then  return true
    last_time=lastbar_time;
    return(true);
    }
    //--- Then the bar is not new; return false
    return(false);
}

//+------------------------------------------------------------------+



         

Extern Variables

Next, we shall define some external setting variables. These variable are designed to govern the settings and inputs of the Indicator/EA, thereby facilitating the ability to run and test each aspect. This enhancement will ultimately provide greater flexibility in our operations.



extern int EMA1Period=8;
extern int EMA2Period=21;
extern int TotalTrades=1;
extern int StopLoss=500;
extern int TakeProfit=500;
extern double LotSize=0.1;
extern bool ReverseOrders=false;

         

EMA values

We will now obtain the values of each Exponential Moving Average (EMA) and compare them at the opening price of the candlestick to identify the crossovers, then make trades. If EMA 1 crosses down EMA 2, that will be a sell signal, and if EMA 1 crosses up EMA 2, that will be a buy signal. If you change the value of ReverseOrders to 'true', it will make a buy trade on a sell signal or a sell trade on a buy signal."



if(IsNewCanlde())
{
    if(OrdersTotal()<TotalTrades)
    {
        //A simple way to detect number of points for converting EMA value to a real number
        int _2Real;
        if(StringFind(Symbol(),"JPY")>-1){
        _2Real=1000;}else{_2Real=100000;}
        
        int ema1,ema2,ema1_i2,ema2_i2;
        ema1=iMA (Symbol(),0,EMA1Period,0,MODE_EMA,PRICE_CLOSE,1)*_2Real;
        ema1_i2=iMA (Symbol(),0,EMA1Period,0,MODE_EMA,PRICE_CLOSE,2)*_2Real;
        ema2=iMA (Symbol(),0,EMA2Period,0,MODE_EMA,PRICE_CLOSE,1)*_2Real;
        ema2_i2=iMA (Symbol(),0,EMA2Period,0,MODE_EMA,PRICE_CLOSE,2)*_2Real;
        
        //if EMA1 crossed down
        if(ema1_i2> ema2_i2 && ema1< ema2)
        {
            if(!ReverseOrders)
            {
                int Ticket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,0,Ask+StopLoss*Point,Ask-TakeProfit*Point);
            }
            else
            {
                int Ticket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,0,Bid-StopLoss*Point,Bid+TakeProfit*Point);
            }
        }
        //if EMA1 crossed Up
        if(ema1_i2< ema2_i2 && ema1> ema2)
        {
            if(!ReverseOrders)
            {
                int Ticket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,0,Bid-StopLoss*Point,Bid+TakeProfit*Point);
            }
            else
            {
                int Ticket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,0,Ask+StopLoss*Point,Ask-TakeProfit*Point);
            }
        }
    }
}



         

Compile EA
We will now compile the codes into EA and utilize the MetaBacktest platform to conduct high quality backtesting on various symbols. This will allow us to analyze the results of the backtesting process.

  • Click on Compile, or press "F7" key on the MetaEditor.

You can also download the file from the Download Box below.




Backtesting

_To access the compiled EA:

  • Open Terminal.
  • Click on “File” -> “Open Data Folder”.
  • Navigate to “MQL4” -> “Experts”.
  • And there you can find “EMA-CrossOver.ex4”.

_Let's start Backtesting:
  • Login into your MetaBacktest account.
  • Navigate to “Backtest” page.
  • Click on upload box to select the EA, or simply drag&drop it.
  • And there you can find “EMA-CrossOver.ex4”.


  • MetaBacktest Backtest Page


_Scroll down to select Backtest settings.
we will start by backtesting a 10-years date on EURUSD H1 chart:
  • Symbol -> “EURUSD”.
  • Start Date -> “08/16/2014”.
  • Start Date -> “08/16/2024”.
  • Period -> “H1”.
  • Start.


  • MetaBacktest Backtesting


_Let's wait for the backtesting to get finished.
Typically, the results will be available within 15 to 30 seconds. However, please note that the duration may vary significantly based on the complexity of the code structure and the intricacies of the strategy employed. In some instances, it may take several hours for the results to be generated. (In that case, we recommend reviewing the coding logic of your algorithm for potential optimization).

MetaBacktest Backtesting


_The Backtest result.
That's it, the result Is now ready. Let us proceed to review it

MetaBacktest Backtest finished



_View the detailed result.


MetaBacktest Detailed Backtest result



Download Box


EMA-CrossOver.ex4
EMA-CrossOver.mq4 
EMA-CrossOver_Detailed-result.zip 
 

Please Login or Signup
to be able to download the files.