Code Library / Trailing Stop
MQL5 Multi-Level Trailing Stop
Multi-level trailing stop that tightens as profit increases.
Language: MQL5 · Category: Trailing Stop · Tags: multi-level, trailing stop, MQL5, advanced, risk management
Source code
void MultiLevelTrail(ulong ticket) {
double levels[]={20,40,60}, trails[]={15,10,5};
if(PositionSelectByTicket(ticket)) {
double op=PositionGetDouble(POSITION_PRICE_OPEN);
double sl=PositionGetDouble(POSITION_SL);
double bid=SymbolInfoDouble(_Symbol,SYMBOL_BID);
double pt=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
double pips=(bid-op)/pt, td=20*pt;
for(int i=2;i>=0;i--) if(pips>=levels[i]){td=trails[i]*pt;break;}
double ns=bid-td;
if(ns>sl&&ns>op){MqlTradeRequest r={};MqlTradeResult s={};
r.action=TRADE_ACTION_SLTP;r.position=ticket;r.symbol=_Symbol;
r.sl=NormalizeDouble(ns,_Digits);OrderSend(r,s);}
}
}How to use this snippet
This is a building block, not a finished trading system. Paste it into your own MQL5 project, compile it, and test it on a demo account with your broker's real spreads before relying on it. If MetaEditor reports errors, the compilation error fixer can help.