Implementing a Trailing Stop in MetaTrader 5: A Step-by-Step Guide

Mike 2024.04.05 07:09 14 0 0
Attachments

This code snippet is versatile - it works whether you're using a Stop Loss or not.

Let's dive into the requirements for setting up a trailing stop in your MetaTrader 5 EA.

Requirements

  • First off, you’ll need to include "Trade.mqh" to gain access to the CTrade class. This class is essential for managing your positions and orders.
#include <Trade\Trade.mqh> // <<------------------------------------------ Include this "Trade.mqh" to access the CTrade Class 
  • Next, set an input parameter to adjust your trailing distance. Though not mandatory, it makes things easier.
input double Trailing_Step = 3.0;
  • Now, you need to declare an instance of the CTrade class. Feel free to name it whatever you like, but it's a good idea to define it right after the OnInit event handler.
CTrade trade; // <<------------------------------------------ Declare the "CTrade" class. You can replace "trade" with any name you want.
  • Then, create an if statement to check if any positions are currently open. This statement will call the Check_TrailingStop(); function on every tick. This is crucial for ensuring that your EA trails prices smoothly and effectively. Make sure to place this statement at the top of the OnTick event handler for optimal performance.
//+------------------------------------------------------------------+  
//| Expert initialization function                                      |  
//+------------------------------------------------------------------+  
int OnInit()  
{  
    //--- create timer  
    EventSetTimer(60);  
    //---  
    return(INIT_SUCCEEDED);  
}  

CTrade trade; // <<------------------------------------------ Declare the "CTrade" class. You can replace "trade" with any name you want.
void OnTick()  
{  
    if(PositionsTotal() > 0) // Calls the trailing stop function for every tick if there are positions running.  
    {  
        Check_TrailingStop();  
    }  
}
  • Next, declare a custom function named Check_TrailingStop(); (you can choose any name you prefer). This function will loop through all open positions and apply the trailing stop based on your specified distance.
void Check_TrailingStop()  
{  
    int totalPositions = PositionsTotal();  
    for(int count = 0; count < totalPositions; count++)  
    {  
        ulong TicketNo = PositionGetTicket(count); // Get Position Ticket number using the 'index' of the position.  
        if(PositionSelectByTicket(TicketNo)) // Select a position using the ticket number  
        {  
            if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)  
            {  
                double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);  
                double stopLoss = PositionGetDouble(POSITION_SL);  // Get Position Current Stop Loss  
                double takeProfit = PositionGetDouble(POSITION_TP);  
                double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);  
                ulong ticket = PositionGetTicket(count);  
                double trailingLevel = NormalizeDouble(bidPrice - (Trailing_Step * Point()), _Digits);  
                if(stopLoss < openPrice)  // No stop loss is true.  
                {  
                    if(bidPrice > openPrice && trailingLevel > openPrice)  
                    {  
                        trade.PositionModify(ticket, trailingLevel, takeProfit); // Modify trailing Stop using "CTrade.trade"  
                    }  
                }  
                if(bidPrice > openPrice && trailingLevel > stopLoss)  
                {  
                    trade.PositionModify(ticket, trailingLevel, takeProfit); // Modify trailing Stop using "CTrade.trade"  
                }  
            }  
            if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)  
            {  
                double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);  
                double stopLoss = PositionGetDouble(POSITION_SL);  
                double takeProfit = PositionGetDouble(POSITION_TP);  
                double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);  
                double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);  
                ulong ticket = PositionGetTicket(count);  
                double trailingLevel = NormalizeDouble(askPrice + (Trailing_Step * Point()), _Digits);  
                if(stopLoss < openPrice)  // No stop loss is true.  
                {  
                    if(askPrice < openPrice && trailingLevel < openPrice)  
                    {  
                        trade.PositionModify(ticket, trailingLevel, takeProfit); // Modify trailing Stop using "CTrade.trade"  
                    }  
                }  
                if(askPrice < openPrice && trailingLevel < stopLoss)  
                {  
                    trade.PositionModify(ticket, trailingLevel, takeProfit); // Modify trailing Stop using "CTrade.trade"  
                }  
            }  
        }  
    }  
}

And there you have it! With this setup, you can effectively manage your trailing stops to lock in profits as market conditions shift.

List
Comments 0