MT5 Backtesting a 1 Rule Strategy with MA & PSAR – Does It Work?


This MQL5 Expert Advisor (EA) is based on Moving Average (MA) signals combined with a Parabolic SAR trailing stop and optimized position sizing. Below is a detailed explanation of how the strategy works, including buy, sell, and stop rules.

Backtesting a strategy involves running historical market data to evaluate its effectiveness over time, ensuring it performs well in different market conditions. Genetic optimization improves strategy parameters by simulating evolution, selecting the best-performing variations while discarding weak ones.

However, this process is slow because testing requires analyzing thousands of combinations across extensive datasets to find robust settings. The longer the backtesting period and the more data used, the more reliable the results, reducing the risk of overfitting to specific market conditions. A well-optimized strategy balances adaptability and consistency, ensuring profitability across various market phases.

See my video:

 

DOWNLOAD MQL5 STRATEGY

//+------------------------------------------------------------------+
//|                                    ExpertMAPSARSizeOptimized.mq5 |
//|                             Copyright 2000-2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2000-2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Include                                                          |
//+------------------------------------------------------------------+
#include <Expert\Expert.mqh>
#include <Expert\Signal\SignalMA.mqh>
#include <Expert\Trailing\TrailingParabolicSAR.mqh>
#include <Expert\Money\MoneySizeOptimized.mqh>
//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
//--- inputs for expert
input string             Inp_Expert_Title                      ="ExpertMAPSARSizeOptimized";
int                      Expert_MagicNumber                    =27893;
bool                     Expert_EveryTick                      =false;
//--- inputs for signal
input int                Inp_Signal_MA_Period                  =12;
input int                Inp_Signal_MA_Shift                   =6;
input ENUM_MA_METHOD     Inp_Signal_MA_Method                  =MODE_SMA;
input ENUM_APPLIED_PRICE Inp_Signal_MA_Applied                 =PRICE_CLOSE;
//--- inputs for trailing
input double             Inp_Trailing_ParabolicSAR_Step        =0.02;
input double             Inp_Trailing_ParabolicSAR_Maximum     =0.2;
//--- inputs for money
input double             Inp_Money_SizeOptimized_DecreaseFactor=3.0;
input double             Inp_Money_SizeOptimized_Percent       =10.0;
//+------------------------------------------------------------------+
//| Global expert object                                             |
//+------------------------------------------------------------------+
CExpert ExtExpert;
//+------------------------------------------------------------------+
//| Initialization function of the expert                            |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- Initializing expert
   if(!ExtExpert.Init(Symbol(),Period(),Expert_EveryTick,Expert_MagicNumber))
     {
      //--- failed
      printf(__FUNCTION__+": error initializing expert");
      ExtExpert.Deinit();
      return(-1);
     }
//--- Creation of signal object
   CSignalMA *signal=new CSignalMA;
   if(signal==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating signal");
      ExtExpert.Deinit();
      return(-2);
     }
//--- Add signal to expert (will be deleted automatically))
   if(!ExtExpert.InitSignal(signal))
     {
      //--- failed
      printf(__FUNCTION__+": error initializing signal");
      ExtExpert.Deinit();
      return(-3);
     }
//--- Set signal parameters
   signal.PeriodMA(Inp_Signal_MA_Period);
   signal.Shift(Inp_Signal_MA_Shift);
   signal.Method(Inp_Signal_MA_Method);
   signal.Applied(Inp_Signal_MA_Applied);
//--- Check signal parameters
   if(!signal.ValidationSettings())
     {
      //--- failed
      printf(__FUNCTION__+": error signal parameters");
      ExtExpert.Deinit();
      return(-4);
     }
//--- Creation of trailing object
   CTrailingPSAR *trailing=new CTrailingPSAR;
   if(trailing==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating trailing");
      ExtExpert.Deinit();
      return(-5);
     }
//--- Add trailing to expert (will be deleted automatically))
   if(!ExtExpert.InitTrailing(trailing))
     {
      //--- failed
      printf(__FUNCTION__+": error initializing trailing");
      ExtExpert.Deinit();
      return(-6);
     }
//--- Set trailing parameters
   trailing.Step(Inp_Trailing_ParabolicSAR_Step);
   trailing.Maximum(Inp_Trailing_ParabolicSAR_Maximum);
//--- Check trailing parameters
   if(!trailing.ValidationSettings())
     {
      //--- failed
      printf(__FUNCTION__+": error trailing parameters");
      ExtExpert.Deinit();
      return(-7);
     }
//--- Creation of money object
   CMoneySizeOptimized *money=new CMoneySizeOptimized;
   if(money==NULL)
     {
      //--- failed
      printf(__FUNCTION__+": error creating money");
      ExtExpert.Deinit();
      return(-8);
     }
//--- Add money to expert (will be deleted automatically))
   if(!ExtExpert.InitMoney(money))
     {
      //--- failed
      printf(__FUNCTION__+": error initializing money");
      ExtExpert.Deinit();
      return(-9);
     }
//--- Set money parameters
   money.DecreaseFactor(Inp_Money_SizeOptimized_DecreaseFactor);
   money.Percent(Inp_Money_SizeOptimized_Percent);
//--- Check money parameters
   if(!money.ValidationSettings())
     {
      //--- failed
      printf(__FUNCTION__+": error money parameters");
      ExtExpert.Deinit();
      return(-10);
     }
//--- Tuning of all necessary indicators
   if(!ExtExpert.InitIndicators())
     {
      //--- failed
      printf(__FUNCTION__+": error initializing indicators");
      ExtExpert.Deinit();
      return(-11);
     }
//--- succeed
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Deinitialization function of the expert                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   ExtExpert.Deinit();
  }
//+------------------------------------------------------------------+
//| Function-event handler "tick"                                    |
//+------------------------------------------------------------------+
void OnTick(void)
  {
   ExtExpert.OnTick();
  }
//+------------------------------------------------------------------+
//| Function-event handler "trade"                                   |
//+------------------------------------------------------------------+
void OnTrade(void)
  {
   ExtExpert.OnTrade();
  }
//+------------------------------------------------------------------+
//| Function-event handler "timer"                                   |
//+------------------------------------------------------------------+
void OnTimer(void)
  {
   ExtExpert.OnTimer();
  }
//+------------------------------------------------------------------+

1. Strategy Overview

This EA uses:

  • Moving Average (MA) Signal: Determines to buy and sell signals.
  • Parabolic SAR (PSAR) Trailing Stop: Adjusts the stop loss dynamically.
  • Optimized Money Management: Adjusts position sizes based on account balance.

The strategy follows a trend-following approach, buying when the market is uptrend and selling during a downtrend.

2. Buy, Sell, and Stop Rules

Buy Rules

The EA opens a buy position when the following conditions are met:

  1. The price is above the Moving Average (MA).
  2. The MA is sloping upwards, indicating a bullish trend.
  3. The previous candle closes above the MA.

Sell Rules

The EA opens a sell position when:

  1. The price is below the Moving Average (MA).
  2. The MA is sloping downwards, indicating a bearish trend.
  3. The previous candle closes below the MA.

Stop and Exit Rules

  1. Trailing Stop (Parabolic SAR)
    • The stop loss is adjusted dynamically using the Parabolic SAR indicator.
    • If the PSAR dot flips to the opposite side of the price, the stop loss is updated.
    • This allows for locking in profits as the trade progresses.
  2. Money Management
    • The lot size is optimized based on account balance.
    • A risk percentage (default: 10%) determines trade size.
    • The Decrease Factor (default: 3.0) reduces trade size to protect capital if consecutive losses occur.

3. Code Breakdown

Header and Includes

#include <Expert\Expert.mqh>
#include <Expert\Signal\SignalMA.mqh>
#include <Expert\Trailing\TrailingParabolicSAR.mqh>
#include <Expert\Money\MoneySizeOptimized.mqh>
  • The EA uses MetaTrader’s built-in expert libraries for managing signals, trailing stops, and money management.

Input Parameters

input int Inp_Signal_MA_Period = 12; // Moving Average period
input int Inp_Signal_MA_Shift = 6; // Shift value for MA
input ENUM_MA_METHOD Inp_Signal_MA_Method = MODE_SMA;
input ENUM_APPLIED_PRICE Inp_Signal_MA_Applied = PRICE_CLOSE;
  • This configures the Moving Average strategy.
  • A 12-period Simple Moving Average (SMA) is used.
input double Inp_Trailing_ParabolicSAR_Step = 0.02;
input double Inp_Trailing_ParabolicSAR_Maximum = 0.2;
  • Defines the Parabolic SAR settings.
input double Inp_Money_SizeOptimized_DecreaseFactor = 3.0;
input double Inp_Money_SizeOptimized_Percent = 10.0;
  • Sets up money management rules.

Expert Advisor Initialization

int OnInit(void)
{
if(!ExtExpert.Init(Symbol(),Period(),Expert_EveryTick,Expert_MagicNumber))
{
printf(__FUNCTION__+": error initializing expert");
return(-1);
}
  • The EA initializes and ensures it runs on the correct symbol and timeframe.

Buy and Sell Signal Setup

CSignalMA *signal = new CSignalMA;
signal.PeriodMA(Inp_Signal_MA_Period);
signal.Shift(Inp_Signal_MA_Shift);
signal.Method(Inp_Signal_MA_Method);
signal.Applied(Inp_Signal_MA_Applied);
  • This creates a Moving Average object for generating buy/sell signals.

Trailing Stop with Parabolic SAR

CTrailingPSAR *trailing = new CTrailingPSAR;
trailing.Step(Inp_Trailing_ParabolicSAR_Step);
trailing.Maximum(Inp_Trailing_ParabolicSAR_Maximum);
  • This sets up the Parabolic SAR trailing stop.

Money Management

CMoneySizeOptimized *money = new CMoneySizeOptimized;
money.DecreaseFactor(Inp_Money_SizeOptimized_DecreaseFactor);
money.Percent(Inp_Money_SizeOptimized_Percent);
  • Implements dynamic lot sizing based on risk percentage.

Trade Execution

void OnTick(void)
{
ExtExpert.OnTick();
}
  • This function checks for new trading signals on every price update.

Closing Trades

  • The Parabolic SAR trailing stop automatically adjusts the stop loss.
  • If the price reverses and triggers the stop loss, the trade closes.

4. Optimization and Customization

1. Adjusting Moving Average

  • Modify Inp_Signal_MA_Period for faster or slower trend detection.
  • Example:
    • Inp_Signal_MA_Period = 9: Faster trend signals, more trades.
    • Inp_Signal_MA_Period = 20: Slower trend signals, fewer trades.

2. Changing Parabolic SAR Settings

  • Increase Inp_Trailing_ParabolicSAR_Step for a tighter trailing stop.
  • Decrease Inp_Trailing_ParabolicSAR_Maximum for looser stop placement.

3. Risk Management

  • Increase Inp_Money_SizeOptimized_Percent to risk more per trade.
  • Lower Inp_Money_SizeOptimized_DecreaseFactor to reduce lot sizes after losses.

5. Backtesting and Performance Analysis

  • Run this EA in MetaTrader 5’s Strategy Tester.
  • Use historical data to analyze:
    • Win rate
    • Drawdowns
    • Profitability over different market conditions

6. Conclusion

This MQL5 Expert Advisor follows a trend-following strategy using Moving Averages for entries, Parabolic SAR for exits, and optimized money management for trade sizing. By fine-tuning its parameters, traders can adapt it to different market conditions.

Would you like any modifications or a detailed optimization guide?

Fxigor

Fxigor

Igor has been a trader since 2007. Currently, Igor works for several prop trading companies. He is an expert in financial niche, long-term trading, and weekly technical levels. The primary field of Igor's research is the application of machine learning in algorithmic trading. Education: Computer Engineering and Ph.D. in machine learning. Igor regularly publishes trading-related videos on the Fxigor Youtube channel. To contact Igor write on: igor@forex.in.rs

Trade gold and silver. Visit the broker's page and start trading high liquidity spot metals - the most traded instruments in the world.

Trade Gold & Silver

GET FREE MEAN REVERSION STRATEGY

Recent Posts