Hands-On Guide: Implementing a Dynamic Trailing Stop in Your MQL5 Expert Advisor
A static Stop Loss is crucial when entering a trade, but once a position moves significantly in your favor, keeping your stop loss fixed leaves potential profits on the table. A dynamic trailing stop automatically adjusts your Stop Loss closer to the current market price as the trade progresses.
In this hands-on tutorial, we will upgrade our MQL5 Expert Advisor to include a trailing stop function that locks in gains during strong trends.
---------------------------------------------------
1. How a Trailing Stop Works in MQL5
A trailing stop operates by monitoring open positions on every tick:
• For a Buy Trade: If the current Bid price rises above your open price by more than your trigger distance, the Stop Loss moves up to trail behind the price by a set number of points.
• For a Sell Trade: If the current Ask price drops below your open price, the Stop Loss moves down to trail the market.
---------------------------------------------------
2. Implementing the Trailing Stop Function
Open your existing Expert Advisor file in MetaEditor (F4) and add the following custom function to handle trailing checks:
// Include trade and position libraries
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
CTrade trade;
CPositionInfo positionInfo;
input int TrailingStopDistance = 150; // Distance in points to trail
input int TrailingStopTrigger = 200; // Profit in points before trailing activates
void CheckTrailingStop()
{
// Loop through all open positions
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket <= 0) continue;
// Ensure the position belongs to our symbol and magic number
if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue;
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentSL = PositionGetDouble(POSITION_SL);
double currentTP = PositionGetDouble(POSITION_TP);
long positionType = PositionGetInteger(POSITION_TYPE);
// TRAILING STOP FOR BUY POSITIONS
if(positionType == POSITION_TYPE_BUY)
{
double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Check if price has moved past the trigger threshold
if(bidPrice - openPrice >= TrailingStopTrigger * _Point)
{
double newSL = bidPrice - (TrailingStopDistance * _Point);
// Only update if the new SL is higher than the current SL (or if SL is 0)
if(newSL > currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, currentTP);
Print("Trailing stop updated for Buy ticket #", ticket);
}
}
}
// TRAILING STOP FOR SELL POSITIONS
else if(positionType == POSITION_TYPE_SELL)
{
double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
// Check if price has dropped past the trigger threshold
if(openPrice - askPrice >= TrailingStopTrigger * _Point)
{
double newSL = askPrice + (TrailingStopDistance * _Point);
// Only update if the new SL is lower than current SL (or if SL is 0)
if(newSL < currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, currentTP);
Print("Trailing stop updated for Sell ticket #", ticket);
}
}
}
}
}
---------------------------------------------------
3. Integrating into OnTick()
To ensure your trailing stop evaluates market shifts continuously, call your function right inside the main `OnTick()` loop:
void OnTick()
{
// Execute trailing stop checks on every incoming tick
CheckTrailingStop();
// --- Your existing entry signals and trade logic go here ---
}
---------------------------------------------------
4. Compiling & Testing in Strategy Tester
1. Press F7 in MetaEditor to compile your updated script (verify 0 errors).
2. Open the Strategy Tester in MT5 (Ctrl + R).
3. Run a visual test to watch how the Stop Loss dynamically steps upward or downward as historical trades move into profit.
---------------------------------------------------
Final Thoughts
Adding a trailing stop transforms your Expert Advisor from a rigid order-sender into an adaptive trading system. It helps protect gains against sudden market reversals.
Stay tuned for our next guide as we march closer to our content milestone!
Comments
Post a Comment