Implementing a trailing stop in MQL5 involves continuously monitoring the market during each tick by iterating through all open positions. This allows the program to check if the market price has moved in a favorable direction, which may warrant adjusting the position's trailing stop. The trailing stop can be adjusted higher or lower based on the market movements, aiming to lock in profits and minimize potential losses. By implementing a trailing stop, traders can benefit from an automated system that helps protect their positions while allowing them to capture gains as the market moves in their favor.
Source code viewer
#include <Trade\PositionInfo.mqh> #include <Trade\Trade.mqh> CPositionInfo position; CTrade trade; input bool trailingStopLoss = true; // Enable trailing stop loss int stopLossPoints = 1000; // Stop loss in points // Move trailing stop towards profit. double stopLoss = stopLossPoints * Point(); uint PositionsCount = PositionsTotal(); if(trailingStopLoss && PositionsCount > 0) { for(int i = PositionsCount-1; i >= 0; i--) { if(position.SelectByIndex(i) && position.Symbol() == Symbol()) { ENUM_POSITION_TYPE type = position.PositionType(); double CurrentSL = position.StopLoss(); double CurrentTP = position.TakeProfit(); double CurrentPrice = position.PriceCurrent(); if(type == POSITION_TYPE_BUY) { if(CurrentPrice - stopLoss > CurrentSL || CurrentSL == 0.0) { trade.PositionModify(position.Ticket(), NormalizeDouble((CurrentPrice - stopLoss), Digits()), 0); } } if(type == POSITION_TYPE_SELL) { if(CurrentPrice + stopLoss < CurrentSL || CurrentSL == 0.0) { trade.PositionModify(position.Ticket(), NormalizeDouble((CurrentPrice + stopLoss), Digits()), 0); } } } } }Programming Language: MQL5