How to Build a Mean Reversion Expert Advisor in MQL5?

Introduction to Mean Reversion and MQL5

Understanding Mean Reversion Strategy

Mean reversion is a trading strategy based on the assumption that prices and returns eventually revert to their long-term mean or average. It seeks to capitalize on temporary price deviations from the mean, expecting the price to return to its average level. This strategy thrives in ranging markets and can be vulnerable during strong trending periods. Common indicators employed in mean reversion strategies include Moving Averages, Bollinger Bands, and Relative Strength Index (RSI).

Why MQL5 for Expert Advisors?

MQL5 (MetaQuotes Language 5) is the programming language for developing trading robots, technical indicators, and scripts for the MetaTrader 5 platform. Compared to MQL4 (used in MetaTrader 4), MQL5 offers significant advantages, including:

  • Improved speed and performance: MQL5 is optimized for 64-bit systems and supports multi-threading.
  • Object-Oriented Programming (OOP): Facilitates modular and reusable code.
  • Event-driven architecture: Provides efficient handling of market events.
  • Enhanced backtesting capabilities: Includes multi-currency and real tick data backtesting.

These features make MQL5 a robust choice for developing sophisticated mean reversion Expert Advisors (EAs).

Setting up MetaEditor and MQL5 Environment

  1. Install MetaTrader 5: Download and install MetaTrader 5 from the MetaQuotes website.
  2. Open MetaEditor: Launch MetaEditor from within MetaTrader 5 (Tools > MetaQuotes Language Editor).
  3. Create a New EA: In MetaEditor, go to File > New > Expert Advisor (template).
  4. Name Your EA: Provide a name for your Expert Advisor and click “Next”.
  5. Configure Event Handlers: Select the event handlers you need (e.g., OnTick, OnInit, OnDeinit) and click “Finish”.

Defining the Mean Reversion Logic

Identifying Overbought and Oversold Conditions

Identifying overbought and oversold conditions is crucial for a mean reversion strategy. Indicators like RSI and Stochastic Oscillator are commonly used. For example, an RSI value above 70 typically indicates an overbought condition, while a value below 30 suggests an oversold condition.

Calculating the Mean (Moving Average) in MQL5

The moving average serves as the ‘mean’ to which prices are expected to revert. The iMA() function in MQL5 calculates the moving average. Here’s an example:

int handle = iMA(Symbol(), Period(), 20, 0, MODE_SMA, PRICE_CLOSE);
MqlRates rates[1];
CopyBuffer(handle, 0, 0, 1, rates);
double mean = rates[0].close;

This code snippet calculates a 20-period Simple Moving Average (SMA) of the closing prices.

Defining Deviation Thresholds

Deviation thresholds determine how far the price must deviate from the mean before a trade is triggered. These thresholds are often based on standard deviations or fixed percentage levels. For example, a trade might be triggered when the price is two standard deviations away from the moving average. Calculating the standard deviation can be done using custom functions or indicators.

Developing the MQL5 Expert Advisor

Creating the EA Skeleton: OnInit(), OnTick(), OnDeinit()

The core functions of an MQL5 EA are OnInit(), OnTick(), and OnDeinit():

  • OnInit(): Called when the EA is initialized (e.g., when attached to a chart). Use this function to initialize variables, load indicator handles, and perform setup tasks.
  • OnTick(): Called on every new tick of the market. This is where the main trading logic resides. The majority of the trading decisions are made here.
  • OnDeinit(): Called when the EA is deinitialized (e.g., when removed from the chart). Use this function to release resources and clean up.
int OnInit()
  {
   // Initialization code here
   return(INIT_SUCCEEDED);
  }

void OnTick()
  {
   // Trading logic here
  }

void OnDeinit(const int reason)
  {
   // Deinitialization code here
  }

Implementing the Trading Logic

Within the OnTick() function, implement the core mean reversion logic:

  1. Calculate the mean (moving average).
  2. Calculate the current price deviation from the mean.
  3. Check if the deviation exceeds the predefined thresholds.
  4. If the conditions are met, open a trade in the opposite direction of the deviation. For example, if the price is significantly above the mean (overbought), open a short position.
void OnTick()
{
   double mean = iMA(...); // Calculate moving average
   double currentPrice = SymbolInfoDouble(Symbol(), SYMBOL_ASK); // Get current price
   double deviation = currentPrice - mean;

   if (deviation > upperThreshold && PositionsTotal() == 0) //Overbought
   {
      //Open Sell Order
       OrderSend(Symbol(), ORDER_TYPE_SELL,Lots,SymbolInfoDouble(Symbol(),SYMBOL_ASK), Slippage,0,0,Comment,MagicNumber,0,Red);
   }
   else if (deviation < lowerThreshold && PositionsTotal() == 0) //Oversold
   {
      //Open Buy Order
      OrderSend(Symbol(), ORDER_TYPE_BUY,Lots,SymbolInfoDouble(Symbol(),SYMBOL_BID), Slippage,0,0,Comment,MagicNumber,0,Green);
   }
}

Position Management: Entry and Exit Rules

Entry Rules: As described above, entry rules are based on price deviations exceeding predefined thresholds.

Exit Rules: Exit rules can be based on:

  • Price Reaching the Mean: Close the position when the price reverts to the moving average.
  • Time-Based Exits: Close the position after a certain period.
  • Opposite Signal: Close the position when the opposite signal is generated.
void OnTick()
{
   // ... (Entry logic) ...
   if(PositionSelect(_Symbol))
   {
    double deviation = SymbolInfoDouble(Symbol(), SYMBOL_ASK) - mean;
    if(PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL && deviation <= 0) //Price Reverted to Mean
     {PositionClose(_Symbol,Slippage);}
    else if (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY && deviation >= 0)
     {PositionClose(_Symbol,Slippage);}
   }
}

Risk Management: Stop Loss and Take Profit

Implementing risk management is crucial. Use stop-loss orders to limit potential losses and take-profit orders to secure profits.

void OnTick()
{
   // ... (Entry logic) ...
    double stopLoss = currentPrice + stopLossPips * Point(); //Calculate Stop Loss
    double takeProfit = currentPrice - takeProfitPips * Point();//Calculate Take Profit

      OrderSend(Symbol(), ORDER_TYPE_SELL,Lots,SymbolInfoDouble(Symbol(),SYMBOL_ASK), Slippage,stopLoss,takeProfit,Comment,MagicNumber,0,Red);

}

Backtesting and Optimization

Backtesting the EA in MetaTrader 5 Strategy Tester

  1. Open Strategy Tester: In MetaTrader 5, go to View > Strategy Tester.
  2. Configure Settings: Select your EA, the symbol you want to test, the time period, and the testing mode (e.g., “Every tick based on real ticks”).
  3. Start Backtesting: Click “Start” to begin the backtest.

Analyzing Backtesting Results and Metrics

Analyze the backtesting results to evaluate the EA’s performance. Key metrics include:

  • Net Profit: The total profit generated by the EA.
  • Profit Factor: The ratio of gross profit to gross loss. A profit factor greater than 1 indicates profitability.
  • Drawdown: The maximum decline in equity during the backtesting period. Minimizing drawdown is crucial for risk management.
  • Win Rate: Percentage of profitable trades.

Optimizing Parameters for Improved Performance

Use the Strategy Tester’s optimization feature to find the optimal parameter values for your EA. This involves running multiple backtests with different parameter combinations and selecting the combination that yields the best performance based on your chosen criteria (e.g., maximum profit, minimum drawdown).

Advanced Techniques and Considerations

Adaptive Mean Reversion: Adjusting Parameters Dynamically

Instead of using fixed parameters, consider adjusting them dynamically based on market conditions. For example, you could adjust the moving average period or deviation thresholds based on the current volatility (using ATR – Average True Range).

Combining Mean Reversion with Other Indicators

Enhance the robustness of your strategy by combining mean reversion with other indicators. For example, you could use volume indicators to confirm overbought/oversold conditions or trend indicators to avoid trading against the prevailing trend.

Handling Market Volatility and News Events

Mean reversion strategies can be sensitive to market volatility and news events. Implement filters to avoid trading during periods of high volatility or before and after major news announcements. News filters can be implemented using economic calendars and checking for upcoming events before placing trades. You can find ways to access and process news data via web requests inside the Expert Advisor, and stop trading when important events are nearby.


Leave a Reply