MQL4 BASICS - HOW TO CREATE A TRAILING STOP FOR FREE

How to Create a Trailing Stop in MQL4

A trailing stop is a type of stop loss order that moves with the market price. It's designed to protect gains by enabling a trade to remain open as long as the market price is moving in a favorable direction, but closes the trade if the market price changes direction by a specified amount.

1. Basic Concept

The key idea behind a trailing stop is to lock in profits while giving a trade room to grow. For instance, if you set a trailing stop of 20 pips and the market moves in your favor by 30 pips, the stop will move up by 30 pips. If the market then retraces by 20 pips, the stop will be hit, and the trade will close.

2. Implementing in MQL4

Below is a simple MQL4 code snippet to implement a trailing stop:

        
            
void OnTick()

{
   double TrailStop = 20; //Trailing stop in points
   


 double point = MarketInfo(Symbol(), MODE_POINT); 
 
 //A Point is the smallest possible price fluctuation for any given instrument... This is dependant on the number of digits for a given currency, commodity etc..
  
  // Check if there are open orders

if(OrdersTotal() > 0) {

// Iterate through all orders in reverse order

for(int i = OrdersTotal() - 1; i >= 0; i--) {

// Select each order by position

if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {


   if(OrderType() == OP_BUY && OrderSymbol() == Symbol()) {
  
  ///Make sure the trade is a buy trade and that the symbol is the symbol of the open chart. This avoids trailing a stop using another open charts values 
  
       if(Bid - OrderOpenPrice() > (point * TrailStop)) 
       
       // If the price difference between the current price and the OrderOpenPrice is greater than our desired threshold, continue... 
       {
           if(OrderStopLoss() < (Bid - (point * TrailStop)))
           
           // If the new stoploss will be greater than the old stoploss, then continue to modify...
           {
               OrderModify(OrderTicket(), OrderOpenPrice(), Bid - point * TrailStop, OrderTakeProfit(), 0, Green);
           }
       }
   }

   if(OrderType() == OP_SELL && OrderSymbol() == Symbol()) {
   
   //Now we do the same for a sell trade...
   
       if(OrderOpenPrice() - Ask > point * TrailStop)
       {
           if(OrderStopLoss() > Ask + point * TrailStop || OrderStopLoss() == 0)
           {
               OrderModify(OrderTicket(), OrderOpenPrice(), Ask + point * TrailStop, OrderTakeProfit(), 0, Red);
           }
       }
   }

}}} // Closing bracket for the OrderSelect()

   return; // Telling the EA to return to the top of the code...
   
}
        
    

This code checks if the current trade (either buy or sell) has moved in our favor by more than the trailing stop amount. If so, it adjusts the stop loss to lock in the profits.

3. Tips and Considerations


Other trailing stop ideas...

A trailing stop can be done in many different creative ways. Figure out which method is best for you.

We have found the parabolic sar based trailing stop is a great method for trailing our stoplosses.

Look into other indicators that you like. For example; you could use the 50 period moving average as your trailing stoploss.

Another method could be to find the high of the last 25 bars and have the EA use that to trail your stoploss.

Spread multiplier: Consider using the spread as a multiplier to add extra padding to your stoplosses. For example; if you are using the 50 period moving average as your trailing stop level, you could add (Spread*2) as your padding.

Here's how to make a trailing stop using a moving average:

void OnTick()

{
 double TrailStop = 20; //Trailing stop in points

 double point = MarketInfo(Symbol(), MODE_POINT); 
 
 double EMA50 = iMA(NULL,0,50,0,MODE_EMA,0,1); // 50 period moving average
 
  double spread=MarketInfo(Symbol(), MODE_SPREAD); // Spread of current symbol
 
 double TrailingStopbuy = NormalizeDouble((EMA50 - (spread * 2) ) * point, Digits); // Trailing Stop calculation for buy 
 
 // Normaize the double to the right digits for the open chart
 
 double TrailingStopsell = NormalizeDouble((EMA50 + (spread * 2) ) * point, Digits); // Trailing Stop calculation for sell 
 
  // Check if there are open orders

if(OrdersTotal() > 0) {

// Iterate through all orders in reverse order

for(int i = OrdersTotal() - 1; i >= 0; i--) {

// Select each order by position

if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {


   if(OrderType() == OP_BUY && OrderSymbol() == Symbol()) 
  
  
  {
       if(Bid - OrderOpenPrice() > (point * TrailStop)) 
       
       {
           if((TrailingStopbuy > OrderStopLoss() )||(OrderStopLoss()==0))
           
           // If the new stoploss will be greater than the old stoploss OR there is currently no stoploss set, then continue to modify...
           {
               int buyordermod=OrderModify(OrderTicket(), OrderOpenPrice(), TrailingStopbuy, OrderTakeProfit(), 0, Green);
           }
       }
   }

   if(OrderType() == OP_SELL && OrderSymbol() == Symbol()) 
    
   {
       if(OrderOpenPrice() - Ask> point* TrailStop)
       {
           if((TrailingStopsell < OrderStopLoss()) || (OrderStopLoss()==0))
           {
               int sellordermod=OrderModify(OrderTicket(), OrderOpenPrice(), TrailingStopsell, OrderTakeProfit(), 0, Red);
           }
       }
   }
}}} // Closing brackets for the OrderSelect()
   return; 
   
}

Conclusion

Trailing stops are a valuable tool for traders to protect profits and let their trades run. Through MQL4, traders can automate this process, ensuring they don't have to constantly monitor their positions to adjust stops manually.

Click here to return to MQL4 Basics Directory