Last Updated on January 9, 2020 by Mark Ursell

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

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.

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

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

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

## Video

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.

### Constants

#define

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

### 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:

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

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)

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.

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;

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.

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.

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:

if(ticket>0)

### 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:

for(cnt=0;cnt<EATotal;cnt++)

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(UseTrailingStop)
{
if(Bid-OrderOpenPrice()>(TSATRMultiplierATR)) { if(OrderStopLoss()<Bid-(TSATRMultiplierATR))

The stop-loss is altered using the OrderModify function.

OrderModify(OrderTicket(),OrderOpenPrice(),Bid-(TSATRMultiplier*ATR),OrderTakeProfit(),0,Green);