The trailing stop function in MQL4 can be implemented using the
OrderModify()
function. You can use this function to change the stop loss level of an open order as the price moves in a favorable direction for you. Here is an example of how to implement the trailing stop function in MQL4:
double Trailing = 50; // Set your trailing stop value here
double StopLoss;
int Ticket;
void TrailingStop()
{
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol() == Symbol() && OrderType() == OP_BUY)
{
StopLoss = Bid - Trailing * Point;
if (StopLoss > OrderStopLoss())
{
Ticket = OrderTicket();
if (OrderModify(Ticket, OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Green))
{
Print("Trailing Stop for Order #", Ticket, " updated to ", StopLoss);
}
}
}
else if (OrderSymbol() == Symbol() && OrderType() == OP_SELL)
{
StopLoss = Ask + Trailing * Point;
if (StopLoss < OrderStopLoss())
{
Ticket = OrderTicket();
if (OrderModify(Ticket, OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Red))
{
Print("Trailing Stop for Order #", Ticket, " updated to ", StopLoss);
}
}
}
}
}
}
In this example, the
TrailingStop()
function is used to monitor open orders and update their stop loss levels if the price moves in a favorable direction. The
OrderModify()
function is used to update the new stop loss level of the order. You can customize the value of the
Trailing
variable to set your trailing stop level.
image quote pre code