Last Updated on November 22, 2019 by Mark Ursell
In December 2013 I wrote an article on How to Create an MT4 EA for a SuperTrend trading strategy. Since then the MQL4 programming language has had a few changes. So in this article, I will show how to update the EA to reflect the latest version of MQL4. This article is intended for people who are new to using Expert Advisors or anyone who wants to understand the EA code better.
Don’t forget you can download the EA featured in this article for free. Simply signup to the Tradinformed Newsletter and you will receive this EA and accompanying indicator. More help and guidance is provided in the accompanying video shown below.
Properties, Define and External Inputs
The first stage of the EA sets out the #properties. The only significant one to be aware of is strict. This means that the EA will be checked against the most recent MQL4 standards by the compiler.
We use the command #define to include a Magic Number in the EA. This Magic Number is very important for live trading. This should be a unique number for each EA that is running.
The next section contains our extern inputs. These are inputs (variables) in the EA that we can manually optimize directly from our MT4 terminal. Double refers to a real number with decimal points. Bool refers to a true or false statement. Int refers to an integer.
- PercentagePerTrade – This is the percentage of capital being risked per trade
- UseStopLoss – Whether to use a stop loss
- SLATRMultiplier – The stop-loss distance as a multiple of the ATR
- UseTakeProfit – Whether to use a profit target
- TPATRMultiplier – The profit target distance as a multiple of the ATR
- UseTrailingStop – Whether to use a trailing stop
- TSATRMultiplier – The trailing stop distance as a multiple of the ATR
- STMultiplier – The SuperTrend Multiplier
- SMALength – The SMA length
- StartTime – The start time. All trades occur at this time of the day or later
- FinishTime – The finish time. All trades occur below this time of the day
Calculate Open Positions and Lot Size
The next step in the EA is to calculate the open positions. CalculateCurrentOrders(string symbol) is a function that counts the number of open positions that have the correct Magic Number. It will ignore any positions that have been opened manually or by another EA.
LotSize() is a function that calculates the size of each position. The lot size is based on the size of the stop-loss. It automatically adjusts the number of lots so that the maximum risk is a fixed percentage of capital.
Check Whether to Open a Position
The next part of the EA is a function called CheckForOpen(). This is only called when there are no other trades open. This function checks whether the conditions are right to open a trade.
The first thing we need to do before we can open a position is to declare our variables. These variables are the same types as the inputs we looked at previously. Once again we have double, bool and int types of data.
The EA is designed to only trade at the start of each bar so the code: if(Volume>1) return is used to check whether this is the start of a bar.
Next, we calculate our technical indicators. You can see that each variable is now given a value based on a technical indicator.
Open a Long or Short Trade
Now we are ready to open a trade. Our buy and sell conditions are defined. A buy trade occurs when the close price crosses over the SuperTrend and the Close is greater than the SMA OR the Close crosses over the SMA and the Close price is below the SuperTrend. Short Trades are opened in the reverse situation.
If the trade conditions are met, the function OrderSend() is used to open a position. The position is opened at market and the lot size is set based on the LotSize() function.
Close or Modify a Trade
The next part of the EA is the function CheckForClose(). This is called only when there is a position open. It checks whether the position should be closed or modified.
Close a Long or Short Trade
Firstly we declare our variables as we did previously. These variables are the same technical indicators that we used before.
Next, we need to look at what type of position is open. To do this we need to make sure that the position has been open opened by this EA by checking that the Magic Number matches up.
Next, we use the OrderType() function to check whether this is a buy order or a sell order. If the order is a buy order we check whether the Close price has crossed below the SuperTrend. if it has then we use the OrderClose() function to close the order.
For sell orders, we use the reverse conditions.
Modify a Long or Short Trade
This EA allows us to modify an open position without closing it. We want to do this because we have a trailing stop. The trailing stop adjusts the stop-loss when the position moves in the direction of the trade.
The logic that we use for a long trade is: if the distance between the current price and the open price is greater than our trailing stop distance AND the stop-loss is lower than the current price minus the trailing stop distance THEN we move the stop-loss.
We use the OrderModify() function to adjust the stop-loss to the new level.
The OnTick() function is the final part of the EA. It is important because it runs every time a new tick (price change) occurs in the market. This function calculates whether there are any open positions running. If there is are no positions open then it calls CheckForOpen(). If there is a position open then it calls CheckForClose().
Many people find it easier to watch the demonstration. Check out the accompanying video for more guidance.