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 that automatically moves with price. In MQL4, you can code a trailing stop inside your Expert Advisor so your stop loss follows the market and locks in profit as price moves in your favor. A trailing stop helps you protect gains while still giving your trade room to run.

1. Basic Concept

The main idea behind a trailing stop in MQL4 is simple: once price moves in your favor by a certain distance, you move the stop loss closer to price. For example, if you set a trailing stop of 20 pips and price moves 30 pips in profit, your stop loss will trail behind price. If price reverses by 20 pips, the trailing stop loss gets hit and the trade closes.

2. Implementing a Simple Trailing Stop in MQL4 (Beginner Code)

Below is a simple beginner-friendly MQL4 code example showing how to create a trailing stop in MQL4. This trailing stop code loops through all open trades (any symbol, any trade) and updates the stop loss using OrderModify() when price moves in your favor.

Note: This is a basic trailing stop example for beginners. It does not use magic numbers or filters. It simply trails the stop loss on every open trade.

//+------------------------------------------------------------------+
//|   How to Create a Simple Trailing Stop in MQL4                    |
//|   Beginner example: trails stop loss on ALL open trades.          |
//+------------------------------------------------------------------+
#property strict

// Trailing stop distance in pips (easy for beginners)
input int TrailStopPips = 20;

// Convert pips to points (important for 4-digit/5-digit brokers)
int PipsToPoints(int pips)
{
   if(Digits == 3 || Digits == 5) return pips * 10;
   return pips;
}

void OnTick()
{
   TrailStopAllTrades();
}

// Trails stop loss on all open BUY and SELL orders
void TrailStopAllTrades()
{
   int trailPts = PipsToPoints(TrailStopPips);

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         continue;

      // BUY trailing stop
      if(OrderType() == OP_BUY)
      {
         // Start trailing only after price moves in profit by the trailing distance
         if(Bid - OrderOpenPrice() > trailPts * Point)
         {
            double newSL = Bid - trailPts * Point;

            // If no stop loss yet OR new stop loss is higher than the old one
            if(OrderStopLoss() == 0 || newSL > OrderStopLoss())
            {
               bool ok = OrderModify(OrderTicket(),
                                     OrderOpenPrice(),
                                     NormalizeDouble(newSL, Digits),
                                     OrderTakeProfit(),
                                     0,
                                     clrGreen);

               if(!ok) Print("Trailing Stop MQL4 (BUY) failed. Error=", GetLastError());
            }
         }
      }

      // SELL trailing stop
      if(OrderType() == OP_SELL)
      {
         // Start trailing only after price moves in profit by the trailing distance
         if(OrderOpenPrice() - Ask > trailPts * Point)
         {
            double newSL = Ask + trailPts * Point;

            // If no stop loss yet OR new stop loss is lower than the old one
            if(OrderStopLoss() == 0 || newSL < OrderStopLoss())
            {
               bool ok = OrderModify(OrderTicket(),
                                     OrderOpenPrice(),
                                     NormalizeDouble(newSL, Digits),
                                     OrderTakeProfit(),
                                     0,
                                     clrRed);

               if(!ok) Print("Trailing Stop MQL4 (SELL) failed. Error=", GetLastError());
            }
         }
      }
   }
}

This simple trailing stop in MQL4 example checks if a trade has moved in profit by the trailing distance. If it has, the EA updates the stop loss using OrderModify(). This is the basic concept behind how to create a trailing stop in MQL4 for buy and sell trades.

3. Tips and Considerations


Other trailing stop ideas...

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

A parabolic SAR based trailing stop can be a great method for trailing stop loss levels.

You could use the 50 period moving average as your trailing stop loss.

Another method could be to find the high (or low) of the last 25 bars and have the EA use that to trail your stop loss.

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

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

//+------------------------------------------------------------------+
//|   Trailing Stop using a Moving Average (MQL4 Beginner Example)    |
//|   Uses EMA(50) as a trailing stop line + simple spread padding.   |
//|   Trails stop loss on ALL open trades (any symbol, any trade).    |
//+------------------------------------------------------------------+
#property strict

input int TrailStartPips   = 20; // Start trailing after X pips profit
input int SpreadPaddingX   = 2;  // Spread padding multiplier (ex: 2 = Spread*2)

int PipsToPoints(int pips)
{
   if(Digits == 3 || Digits == 5) return pips * 10;
   return pips;
}

void OnTick()
{
   TrailStopWithEMA50();
}

void TrailStopWithEMA50()
{
   int startPts = PipsToPoints(TrailStartPips);

   // EMA(50) value from the last closed candle (shift 1)
   double ema50 = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_CLOSE, 1);

   // Spread in points
   double sprPts = MarketInfo(Symbol(), MODE_SPREAD);

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         continue;

      // BUY: trail SL to EMA50 minus spread padding
      if(OrderType() == OP_BUY)
      {
         if(Bid - OrderOpenPrice() <= startPts * Point) continue;

         double newSL = ema50 - (sprPts * SpreadPaddingX) * Point;

         if(OrderStopLoss() == 0 || newSL > OrderStopLoss())
         {
            bool ok = OrderModify(OrderTicket(),
                                  OrderOpenPrice(),
                                  NormalizeDouble(newSL, Digits),
                                  OrderTakeProfit(),
                                  0,
                                  clrGreen);

            if(!ok) Print("EMA Trailing Stop (BUY) failed. Err=", GetLastError());
         }
      }

      // SELL: trail SL to EMA50 plus spread padding
      if(OrderType() == OP_SELL)
      {
         if(OrderOpenPrice() - Ask <= startPts * Point) continue;

         double newSL = ema50 + (sprPts * SpreadPaddingX) * Point;

         if(OrderStopLoss() == 0 || newSL < OrderStopLoss())
         {
            bool ok = OrderModify(OrderTicket(),
                                  OrderOpenPrice(),
                                  NormalizeDouble(newSL, Digits),
                                  OrderTakeProfit(),
                                  0,
                                  clrRed);

            if(!ok) Print("EMA Trailing Stop (SELL) failed. Err=", GetLastError());
         }
      }
   }
}

Conclusion

Knowing how to create a trailing stop in MQL4 is a powerful skill for any algorithmic trader. A trailing stop helps you protect profits automatically by moving your stop loss as price moves in your favor. Using MQL4, you can automate trailing stops so you don’t have to adjust stops manually.

Click here to return to MQL4 Basics Directory