Expert Advisor – Trailing Stop following Moving Average 1.0

Following a Moving Average is another way of performing a Trailing Stop, in this article you can download the Trailing Stop Moving Average Expert Advisor for MetaTrader 4 that can adjust the Stop Loss level following a Moving Average of set parameters.

What is a Trailing Stop?

I assume you already know what is a trailing stop however if not.

Trailing Stop is that practice of moving the Stop Loss level when the price moves in your favor.

Trailing the Stop Loss price allows to limit the losses and the risk and it is a very popular practice.

As you may have read in books and forums one of the first rules in Forex is “Cut your losses short and let your profits run“.

What is the Moving Average?

The Moving Average is one of the simples and most popular indicators.

We are not going to show you here the formula to calculate it.

In any case, you need to know that a Moving Average (in short MA) is the average of the price of the last set period.

In the image you can see in purple a Simple Moving Average of period 25.

Example of Simple Moving Average with Period Set to 25
Example of Simple Moving Average with Period set to 25

In MetaTrader 4 MQL4 language the function to retrieve the value of a Moving Average is iMA().

You can find more details about the function here.

Trailing Stop Following MA 1.0

Presentation
Presentation

The Expert Advisor TrailingStopMA_v1-0.mq4 moves the stop loss of the selected orders assigning the value of the Moving Average in the previous candle.

It can be very useful in trending periods to follow the trend and cut losses.

You can download the Expert Advisor for MetaTrader 4 with the following link, it is free to use.

If you need a more professional Trailing Stop I would suggest to have a look at this link.

Trailing-Stop-EA-Expert-Advisors-MT4

Parameters

Trailing Stop MA Parameters
Trailing Stop MA Parameters

This Expert Advisor has the following parameters that can be set:

  • MAPeriod, this is an integer to set the Period of the Moving Average
  • MAType, this can be set to 0 to use a Simple Moving Average or 1 to use an Exponential Moving Average
  • OnlyMagicNumber, true or false depending if you want to modify only the orders with a specific magic number
  • MagicNumber, specify the magic number in case the above is true
  • OnlyWithComment. true or false depending if you want to modify only the orders with a specific comment
  • MatchingComment, specify the comment if the above is true
  • Slippage, slippage in pips
  • Delay, delay to wait before change the next order in the queue

Rules

The Expert Advisor is configured with the following rules:

  • For Buy orders the Moving Average value of the previous candle must be above the original stop loss level and below the current price level
  • For Sell orders the Moving Average value of the previous candle must be below the original stop loss level and above the current price level

Remember that we want to move the stop loss level always in the direction of the order and never make it larger than the original. This is because of fundamental risk management rules.

Example

We can see an ideal example of this Expert Advisor, the Trailing Stop moves the Stop Loss level after each candle following the Moving Average (Red Line)

Trailing Stop follows the MA (Red Line)
Trailing Stop follows the MA (Red Line)
How the order is updates
How the order is updates

Conclusion

Using a trailing stop that follows the Moving Average can be ideal in a situation where there is a clear trend. This type of trailing stop will allow to follow the trend the protect the order from unexpected spikes or reverse.

You can download the source code to use or study it for free with the following link.

I remember when I first started to learn MQL coding, although I had some knowledge of coding many concept were still unclear. To speed up your learning process I would recommend to follow a quick MQL course that will give you the fundamentals you need to create functional Trading Robot.

You can check out the following two course, Udemy often has sales on to make the courses even more affordable, and if you subscribe to my newsletter (top and bottom of the page) I will let you know when this happens.

MQL4 Programming for Traders: Build Robust Trading Robots!

Black Algo Trading: Build Your Trading Robot

If you found this article useful or if you have any question please feel free to leave a comment below or Contact Us.

If you want to save hours of research and coding and you want to see some professional code check this out! You can use it to build your own EA!

11 thoughts on “Expert Advisor – Trailing Stop following Moving Average 1.0”

  1. Installed on chart in mt4. Smiley face in corner telling me all working. Price dropped below to MA stipulated in inputs. Did not stop out the trade ?? Please help. I have followed the above instructions, everything is telling me its working ok, but its not.

    • Hi Steve,
      To check that the EA is working as expected you should see that the STOP LOSS price of the order changes at each candle following the MA, if this doesn’t happen you can check in the Terminal section, Experts and Journal tabs to see if there is any error. Errors help in the troubleshooting.
      Luca

  2. hi luca, really nice job, thank you for the effort.
    i dont have any problems with buy orders, it works perfect.
    however, it is not the same case with the sell orders due to the spread, my spread for eur/usd is 12.
    is it not possible to reduce the function just based on the bid price instead of the ask price for sell orders or another solution? thank you in advance. br.

    • Hi Bahadir,
      It is certainly possible, the source code is released for free so that you can play with it and adjust to your needs.
      In this case you might want to change the following code to get the stop loss required

      double MAValue=iMA(Symbol(),0,MAPeriod,0,MAType,PRICE_CLOSE,1);

      //Get updated prices and calculate the new Stop Loss and Take Profit levels, these depends on the type of order
      RefreshRates();
      if(OrderType()==OP_BUY){
      if(MAValue>StopLossPrice && MAValueClose[0] && MAValue>TakeProfitPrice){
      NewStopLossPrice=NormalizeDouble(MAValue,Digits);
      }
      }

      I believe the easiest way is for you to account the spread when you calculate the NewStopLossPrice in the “if(OrderType()==OP_SELL){” statement.
      Hope it makes sense.
      Luca

Leave a Comment