Create an Expert Advisor for a SuperTrend Trading Strategy

Last Updated on January 9, 2020 by Mark Ursell

In this article, I will show you how to build an Expert Advisor for a SuperTrend Trading Strategy.

MT4 is a massively popular trading platform that is offered by a huge range of different brokers. This article will help you power-up your programming skills and help you quickly start backtesting your strategies.

The article and accompanying video shows how an EA is written and how that EA can be used to backtest and automatically trade a trading strategy.  I break down the components of the EA and explain how each part is used to follow the strategy.

The SuperTrend Technical Indicator

SuperTrend Icon

The SuperTrend indicator is a great indicator for identifying the current market trend.  The indicator is constructed by combining the Average True Range with the Median Price (High-Low)/2 and the Closing Price.  I explain how the indicator is calculated in my article and video How to Calculate the SuperTrend Indicator Using Excel.

SuperTrend Trading Strategy

In my previous article, Backtesting a SuperTrend Trading Strategy Using Excel, I showed how Excel can be used to test a trading strategy.

In this test we are going to use basically the same strategy using the following rules:

  • Only one trade at a time.

Enter Long:

  • When the closing price is above 200 SMA and crosses from below to above SuperTrend.  Or when the closing price is above SuperTrend and crosses from below to above 200 SMA

Enter Short:

  • When the closing price is below 200 SMA and crosses from above to below SuperTrend.Or when the closing price is below SuperTrend and crosses from above to below 200 SMA

Close Long Trade:

  • When either Profit Target or Stop-Loss is hit.  Or when closing price crosses from above to below 25 EMA.

Close Short Trade:

  • When either Profit Target or Stop-Loss is hit.  Or when closing price crosses from below to above 25 EMA


This article is accompanied by a video article and I suggest you watch the video while reading the article.

MT4 Expert Advisors

SuperTrend Trading Strategy Expert Advisor

MT4 is a widely used trading platform, offered by Forex Brokers around the world. EAs are programs written using the MQL4 language that describe trading strategies.  If you are interested in learning more about MQL4, there is an online reference guide, the MQL4 Book.

Expert Advisor for a SuperTrend Trading Strategy



We are going to use this command to define our trade opening criteria.  For example:

#define LongTrade 1

External Inputs

Any variables that we want to be able to manually change or optimise are called external variables and we indicate them using extern.  For example:

extern double PercentagePerTrade = 1.0;

The above sets an external variable that is a double type number.  Double numbers are real numbers with a decimal point.  PercentagePerTrade is the name of the variable and represents the amount of capital that we will invest per trade.  1.0 is our initial value.

Int Start()

All the calculations and trading carried out by the EA is within the Start() function.  The contents of the start function are enclosed with curly brackets {…}.

The start function runs every time a new tick (change in market price) is received.  This is important because the EA needs to be constantly monitoring the market, ready to act when the trading criteria are met.

Declaring Variables

SuperTrend Strategy Variables

Our EA uses variables to carry out the calculations that are needed to follow the trading strategy.  We declare variables by telling the MT4 what type of variables they are.  We have already seen the double type of variable.  The other types of variables used in this EA are:

  • int integer (whole number)
  • bool boolean (true or false)

Calculate Lots per Trade

I like to use trading strategies that alter the trade size based on the amount risked.  In this EA the stop-loss is automatically calculated based on a multiple of the ATR.

This part of the program uses the percentage risked and the stop-loss length to automatically set the number of lots per trade.

Calculate Technical Indicators

This part of the program sets out the technical indicators that we are going to use in this EA. The SuperTrend indicator does not come built into MT4 and so we are going to use a Custom Indicator for this.  Custom indicators are called iCustom.  In our EA we have used the following to describe the SuperTrend indicator:

double ST1 = iCustom(NULL, 0, “SuperTrend”, 20, STMultiplier, 0, 1);

The above line sets out the following information:

  • We have called the variable ST1 and set it as a double type.
  • NULL means that this indicator can run on any market.
  • 0 means that this indicator can run on any timeframe.
  • “SuperTrend” is the name of the indicator.
  • 20 is the number of periods that the SuperTrend indicator is calculated over.
  • STMultiplier is the external variable that we set earlier, the initial value is 2.0.
  • 0 is the mode of the SuperTrend and in this case refers to the main indicator line.
  • 1 refers to the previous period which is the last complete bar.  We only want this EA to trade based on a complete bar.

The other indicators used are EMA (exponential moving average), SMA (simple moving average) and ATR.  These indicators are built into MT4 and more information can be found about how to customise them in the MQL4 Book section on Technical Indicators.

Enter Long Trade

In this section we set out our trade entry criteria.  We use an IF Statement to set the criteria.

if (Close1 > ST1 && Close2 < ST2 && Close1 > SMA1) Order = LongTrade;
if (Close1 > SMA1 && Close2 < SMA2 && Close1 > ST1) Order = LongTrade;

Check the Trading Time

The forex market is open 24 hours a day, 5 days a week.  However, the amount of liquidity varies significantly at different times of the day.  Many EAs will operate better at certain times of the day.

In our external variables, we have set the times that the EA should be looking for trades.  This IF Statement will check if the EA is allowed to trade at the current time; if so it will move to the next stage; if not it will wait for the next tick and check the time again.

Number of Trades Allowed

This part of the program counts the number of trades that are live or pending from the EA.  It will ignore manual trades and trades made by other EAs with a different Magic Number.  The Magic Number is a unique number that identifies each Expert Advisor.  It is set as an external variable.

Opening Trades

At this stage, our EA has checked that all the previous criteria have been met and can open a long trade.

Before we can open a trade we need to use our external variables to calculate our stop-loss and profit targets.

if (UseStopLoss) double LongStopLossLevel = Ask – (ATR * SLATRMultiplier) ; else LongStopLossLevel = 0.0;
if (UseTakeProfit) double LongTakeProfitLevel = Ask + (ATR * TPATRMultiplier) ; else LongTakeProfitLevel = 0.0;

The trade is opened using the function OrderSend.  Our long trades are opened with the following:

ticket=OrderSend(Symbol(),OP_BUY,LotsTraded,Ask,Slippage,LongStopLossLevel,LongTakeProfitLevel,”Buy(#” + MagicNumber + “)”,MagicNumber,0,Green);

Closing Positions

In our trading strategy, positions can be closed by crossing the EMA.  The first thing we need to do is check that the EA currently has a position open.  To do this we use for which sets up a cycle to count the number of open positions:


If we have a position open, the OrderSelect function will find this position and select it.


The OrderType function will then be used to check whether the open position is a long position or a short position.

OrderType()<=OP_SELL && OrderSymbol()==Symbol()

Our criteria for closing a long positions is:

if(Close1 < EMA1 && Close2 > EMA2)

Trailing Stop

A trailing stop can be useful for locking in profits.  Our original trading strategy does not use a trailing stop, however we can use MT4 to see whether it could improve our profitability.  The following code uses a series of if statements to check whether we are using a trailing stop and if so whether our stop-loss should be altered based on the latest price change.

if(Bid-OrderOpenPrice()>(TSATRMultiplierATR)) { if(OrderStopLoss()<Bid-(TSATRMultiplierATR))

The stop-loss is altered using the OrderModify function.


Trading Live – Caution!

This EA is a working model that can be used to backtest a trading strategy. However, if you intend to use a self-built EA for live trading you must first test it using a demo account.  Doing this you will be able to see exactly how the EA operates and whether it causes any problems with other EAs or manual trading.

Free Download – Get the Expert Advisor and SuperTrend Custom Indicator

If you want to get the EA and SuperTrend custom indicator simply subscribe to my website using the Subscribe page and I will send you a link to download them.