How to Implement a Trailing Stop in MQL4: A Practical Code Example?

What is a Trailing Stop?

A trailing stop is a dynamic stop-loss order that adjusts automatically as the price of the asset moves in a favorable direction. Unlike a fixed stop loss, it trails the price, locking in profits while limiting potential losses. If the price reverses, the stop loss remains at its last adjusted level, triggering a sell (or buy) order if hit.

Benefits of Using Trailing Stops

Trailing stops offer several advantages:

  • Profit Protection: They automatically secure profits as the price increases (for long positions) or decreases (for short positions).
  • Risk Management: They limit potential losses by triggering an exit if the price moves against the trader.
  • Flexibility: They adapt to changing market conditions, adjusting the stop loss based on price movements.
  • Automation: They eliminate the need for constant manual adjustments of stop-loss orders.

MQL4 and its Role in Automated Trading

MQL4 is the programming language used in the MetaTrader 4 platform. It allows traders to automate their trading strategies through Expert Advisors (EAs). Implementing a trailing stop in MQL4 involves writing code that monitors the price and modifies the order’s stop loss accordingly. While MQL5 offers object-oriented features and improved performance, MQL4 remains widely used. The core logic for trailing stops remains consistent between the two languages, though syntax and available functions may differ.

Understanding the Core Logic of a Trailing Stop

Defining the Initial Stop Loss

Before implementing a trailing stop, you need to define an initial stop loss. This is the level at which the trade will be closed if the price moves against you at the start of the trade. The initial stop loss should be placed based on your trading strategy (e.g., support/resistance levels, volatility).

Calculating the Trailing Distance (in points/pips)

The trailing distance determines how far the stop loss trails the price. It’s usually defined in points (which are equivalent to pips for most currency pairs). A smaller trailing distance will result in the stop loss adjusting more frequently, potentially leading to premature exits. A larger distance offers more breathing room but may reduce profit potential.

Conditions for Moving the Stop Loss

The stop loss is only moved if the price moves in a favorable direction by at least the trailing distance. The new stop-loss level is calculated by adding the trailing distance to the highest price reached (for long positions) or subtracting it from the lowest price reached (for short positions) since the order was opened.

Practical Implementation: MQL4 Code Example

This example shows how to implement a basic trailing stop in MQL4.

Declaring Input Parameters (Stop Loss, Trailing Distance)

extern int InitialStopLoss = 30;  // Initial stop loss in points
extern int TrailingStop = 50;     // Trailing stop distance in points

Fetching Current Price Data (Ask/Bid)

double Ask = MarketInfo(Symbol(), MODE_ASK); // Current ask price
double Bid = MarketInfo(Symbol(), MODE_BID); // Current bid price

Calculating the New Stop Loss Level

void TrailingStopFunction()
{
   int total = OrdersTotal();
   for(int i = 0; i < total; i++)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue;
      if(OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) continue; // MagicNumber is a good practice

      if(OrderType() == OP_BUY)
      {
         double newStopLoss = Bid - TrailingStop * Point; // Bid price used for buy orders
         if(Bid > OrderOpenPrice() + TrailingStop * Point && OrderStopLoss() < newStopLoss)
         {
             //Modify order here (see next section)
         }
      }
      else if(OrderType() == OP_SELL)
      {
         double newStopLoss = Ask + TrailingStop * Point; // Ask price used for sell orders
         if(Ask < OrderOpenPrice() - TrailingStop * Point && OrderStopLoss() > newStopLoss)
         {
             //Modify order here (see next section)
         }
      }
   }
}

Modifying the Order with the New Stop Loss

    double newStopLoss = Bid - TrailingStop * Point;
    if(Bid > OrderOpenPrice() + TrailingStop * Point && OrderStopLoss() < newStopLoss)
    {
        OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, OrderTakeProfit(), 0, Green); // Modify the order
        Print("Trailing stop updated for order #", OrderTicket());
    }

Integrating the Trailing Stop into an Expert Advisor (EA)

Calling the Trailing Stop Function within the EA

Call the TrailingStopFunction() inside the OnTick() function of your EA to ensure continuous monitoring of the price.

void OnTick()
{
   // Your trading logic here
   TrailingStopFunction();
}

Considerations for Different Order Types (Buy/Sell)

As shown in the code, the calculation of newStopLoss differs for buy and sell orders. For buy orders, the Bid price is used, and for sell orders, the Ask price is used.

Error Handling and Order Management

It’s crucial to include error handling when modifying orders. Check the return value of OrderModify() to ensure the order was modified successfully. Also, consider using a MagicNumber to identify orders placed by your EA, preventing it from interfering with orders placed manually or by other EAs.

Advanced Techniques and Considerations

Trailing Stop Based on Volatility (ATR Indicator)

Using the Average True Range (ATR) indicator to dynamically adjust the trailing stop distance based on market volatility. This allows the stop loss to widen during volatile periods and tighten during calmer periods.

double ATR = iATR(NULL, 0, 14, 0, i);
TrailingStop = ATR * Multiplier; //Multiplier is an input parameter

Adjusting Trailing Distance Dynamically

You can implement more complex logic to adjust the trailing distance based on factors like time of day, trading volume, or other indicators.

Optimizing Trailing Stop Parameters for Different Market Conditions

Backtesting your EA with different InitialStopLoss and TrailingStop values is essential to find the optimal parameters for different currency pairs and market conditions. The optimal values will vary depending on the trading strategy and the specific market being traded.


Leave a Reply