How To Code MACD Signal Line Trailing EA In MQL4?

In this post we are going to discuss in detail how you are going to code an MACD Signal Line Trailing EA in MQL4.  Why you need a Trailing Stop Loss EA? Suppose we open a trade with a take profit target of 100 pips. But the market moves 250 pips. By not trailing the price action properly you let 100+ pips on the table. If you had properly trailed the price action, you could have made a profit of 200 pips instead of 100 pips. Taking 100 pips profit instead of 200 pips is indicative of a faulty take profit strategy in your trading system. You should try to address this. Take a look at the following screenshot.

GBPUSD

In the above screenshot you can see a big move of 250+ pips on M15 timeframe. Entry is just above the up red arrow. Entry is 1.43909 and the stop loss is 1.44150. So the risk is 25 pips. But you don’t know at the time of entry how much the market will move. It can be 50 pips. It can be 100 pips. It can be 200 pips. In this case it is more than  250 pips.

One strategy is to use a fixed take profit target. Since our risk is 25 pips, we should be happy with a take profit target of 100 pips. This will give us a reward to risk of 5:1. But sometime it happens that the market moves 95 pips and then reverses itself. So the profit target is not hit and you are astonished to see you stop loss hit after a few hours  whereas when you had checked last time, the profit was 80 pips. So we need a more robust take profit strategy.

How about using a moving average as a trailing stop loss? How about using EMA21. In the above screenshot you can see you can use EMA21 (red line) as a trailing stop loss. You stay in the trade as long as price action stays below EMA21 which is the red line in the above screenshot. This take profit strategy will get us out around 1.42260 giving us a profit of around 170 pips.

Now if we use the MACD Signal Line as our trailing stop loss and get out of the trade when the signal line crosses the MACD histogram in the above figure we get out around 1.41938 and make close to 200 pips instead of 170 pips when we used EMA21 as our take profit target. So let’s discuss in detail how to code a Trailing Stop Loss EA that uses the MACD Signal Line cross as a trigger to close the trade.  Let’s start. Open your MT4 and click on the MetaQuotes Language Editor F4. Then click on File > New. MQL4 Wizard will open as shown below.

GBPUSD

Now in the above screenshot, you can see the Expert Advisor (template) already checked. Click on the next. Choose a name for the EA. We choose MACDTrailing. Click next and then next again. You get the following code!

//+——————————————————————+
//|                                                 MACDTrailing.mq4 |
//|                        Copyright 2016, MetaQuotes Software Corp. |
//|                                    https://auto.tradingninja.com |
//+——————————————————————+
#property copyright “Copyright 2016, SwingTrader23”
#property link      “https://auto.tradingninja.com”
#property version   “1.00”
#property strict
//+——————————————————————+
//| Expert initialization function                                   |
//+——————————————————————+
int OnInit()
{
//—

//—
return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| Expert deinitialization function                                 |
//+——————————————————————+
void OnDeinit(const int reason)
{
//—

}
//+——————————————————————+
//| Expert tick function                                             |
//+——————————————————————+
void OnTick()
{
//—

}
//+——————————————————————+

This is the template code that you get. Now we are going to work on this template and code our MACDTrailing EA. First we need to define a few external variables then we need to define a few functions and then we need to use these functions in the EA. I am pasting the code below, you can copy it and paste it in your Meta Editor, compile it and then start using it.

//+——————————————————————+
//|                                                 MACDTrailing.mq4                  |
//|                                    Copyright 2016, SwingTrader23         |
//|                                    https://auto.tradingninja.com            |
//+——————————————————————+

#property copyright “Copyright 2016, SwingTrader23”
#property link      “https://auto.tradingninja.com”
#property version   “1.00”
#property strict

//–External Variable you will input when you use the EA. TrailingStopLoss is by default True
//–The default chart is 15, you can change it to 5, 30 or 60 whatever you want

extern bool TrailingStopLoss = TRUE;
extern int  Chart = 15;

//–Macd and Signal variable are defined below using the inbuild iMACD function

double    Macd   =iMACD(NULL,Chart,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
double    Signal =iMACD(NULL,Chart,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);

//–function CountOrders is defined below

int CountOrders()

{

int iCnt=0;
for (int x=0; x < OrdersTotal(); x++)
{
if (OrderSelect(x, SELECT_BY_POS, MODE_TRADES)== False) break;
if (OrderSymbol() == Symbol())
{
if ( OrderType() == OP_BUY || OrderType() == OP_SELL)
{
iCnt++;

}

}
}

return(iCnt);
}

//—Function TrailOrders defined

int TrailOrders (double z)

{

int iCnt=0;

double NewSL;
for ( int x=0; x < OrdersTotal(); x++)
{
if (OrderSelect(x, SELECT_BY_POS, MODE_TRADES)== False) break;
if (OrderSymbol() == Symbol())
{
if ( OrderType() == OP_BUY || OrderType() == OP_SELL)
{

switch( OrderType())

{

case OP_BUY:
NewSL = Signal;
if ( Signal < Bid && (OrderStopLoss() < NewSL || OrderStopLoss() == 0))
{
bool res=OrderModify(OrderTicket(), OrderOpenPrice(), NewSL, OrderTakeProfit(), 0, CLR_NONE);
}
break;

case OP_SELL:
NewSL = Signal;
if ( Signal > Ask && (OrderStopLoss() > NewSL || OrderStopLoss() == 0))
{
bool res=OrderModify(OrderTicket(), OrderOpenPrice(), NewSL, OrderTakeProfit(), 0, CLR_NONE);
}
break;
default:
break;
}
}
}
}

return(iCnt);

}

//+——————————————————————+
//| Expert initialization function                                   |
//+——————————————————————+
int init()
{
//—there was nothing to initialize for this EA

//—
return(INIT_SUCCEEDED);
}

//+——————————————————————+
//| Expert deinitialization function                                 |
//+——————————————————————+

int start()
{
//—
if ( Macd == Signal)
{
int iOrderCnt= CountOrders();
if ( iOrderCnt != 0 && TrailingStopLoss == TRUE && Period() == Chart)
{

TrailOrders(Signal);

}
}
return(0);
}

//+——————————————————————+

When you are going to use this MACDTrailing EA?

This EA only trails an open order. Once you have opened an order and the trend is going strong, you are going to activate this EA when the signal line crosses the MACD histogram. Keep looking for the new post in which I am going to include the part when this EA is going to open the trade as well. You can first test this EA on your demo account.