strategy.exit in MQL5: stop, limit, ticks and trailing exits
Short answer
Stop and limit prices, and tick distances from the fill, become the position's own SL and TP, set with CTrade::Buy's sl/tp arguments or with CTrade::PositionModify. A trailing stop has no broker-side equivalent and is a few lines in OnTick that run on every tick.
strategy.exit attaches a bracket to a trade: a stop-loss and take-profit given as prices (stop, limit), as tick distances from the fill (loss, profit), or as a trailing stop (trail_points, trail_offset, trail_price). In MQL5 the first two forms are the position's own SL and TP, set with the sl/tp arguments of CTrade::Buy or afterwards with CTrade::PositionModify; the trailing form has no broker-side equivalent and is a few lines in OnTick that run on every tick.
What strategy.exit computes
The exit acts on the trade named by from_entry, or on every open trade when it is omitted. It is re-evaluated on every bar, so a price computed from a series (close - 2 * atr) moves with each bar until the trade exists, then is fixed at the values of the bar on which the entry filled. loss and profit are counted in syminfo.mintick from the fill price, not in pips. The trailing stop arms once price has moved trail_points ticks in the trade's favour (or reaches trail_price), then follows the best price at a distance of trail_offset ticks and only ever tightens. If the entry has not filled yet, the exit waits for it; it is never applied to a trade with a different id. A bare strategy.exit(id, from_entry) with no bracket closes the trade at the next open.
The MQL5 equivalent
//@version=6
strategy("Exit demo", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 1)
atr = ta.atr(14)
if ta.crossover(ta.ema(close, 9), ta.ema(close, 21))
strategy.entry("L", strategy.long)
// absolute prices: stop-loss and take-profit on the "L" trade
strategy.exit("XL", from_entry = "L", stop = close - 2 * atr, limit = close + 3 * atr)
if ta.crossunder(ta.ema(close, 9), ta.ema(close, 21))
strategy.entry("S", strategy.short)
// tick distances from the fill price
strategy.exit("XS", from_entry = "S", loss = 200, profit = 400)
// a trailing stop: arms after 300 ticks of profit, trails 50 ticks behind
strategy.exit("Trail", from_entry = "L", trail_points = 300, trail_offset = 50)The EA keeps one helper per form. ExitPrices is PositionModify on the position carrying the entry id; ExitTicks turns tick counts into prices from POSITION_PRICE_OPEN; Trail runs before the new-bar gate so the stop follows every tick. The long entry sets its bracket in the same request as the order, which is the cheapest way to get Pine's "exit placed with the entry" timing.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input long InpMagic = 60013;
input int InpLossTicks = 200; // strategy.exit loss=
input int InpProfitTicks = 400; // strategy.exit profit=
input int InpTrailPoints = 300; // strategy.exit trail_points=
input int InpTrailOffset = 50; // strategy.exit trail_offset=
CTrade trade;
int hFast = INVALID_HANDLE, hSlow = INVALID_HANDLE, hAtr = INVALID_HANDLE;
int OnInit()
{
hFast = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE);
hAtr = iATR(_Symbol, _Period, 14);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE || hAtr == INVALID_HANDLE)
return INIT_FAILED;
trade.SetExpertMagicNumber(InpMagic);
trade.SetTypeFillingBySymbol(_Symbol);
return INIT_SUCCEEDED;
}
bool IsNewBar()
{
static datetime last = 0;
const datetime t = iTime(_Symbol, _Period, 0);
if(t == last)
return false;
last = t;
return true;
}
// selects this EA's position carrying `id` (the Pine entry id); 0 if none
ulong SelectById(const string id)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
const ulong ticket = PositionGetTicket(i);
if(ticket != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic
&& PositionGetString(POSITION_COMMENT) == id)
return ticket;
}
return 0;
}
// strategy.exit(from_entry = id, stop = sl, limit = tp): absolute prices.
// 0 keeps the side of the bracket the position already has.
void ExitPrices(const string id, const double sl, const double tp)
{
const ulong ticket = SelectById(id);
if(ticket == 0)
return;
const double newSl = sl > 0 ? NormalizeDouble(sl, _Digits) : PositionGetDouble(POSITION_SL);
const double newTp = tp > 0 ? NormalizeDouble(tp, _Digits) : PositionGetDouble(POSITION_TP);
if(newSl != PositionGetDouble(POSITION_SL) || newTp != PositionGetDouble(POSITION_TP))
trade.PositionModify(ticket, newSl, newTp);
}
// strategy.exit(from_entry = id, loss = n, profit = m): ticks from the fill.
// One Pine tick is syminfo.mintick, which is SYMBOL_TRADE_TICK_SIZE here.
void ExitTicks(const string id, const int lossTicks, const int profitTicks)
{
if(SelectById(id) == 0)
return;
const double tick = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
const double open = PositionGetDouble(POSITION_PRICE_OPEN);
const int dir = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? 1 : -1;
ExitPrices(id, open - dir * lossTicks * tick, open + dir * profitTicks * tick);
}
// strategy.exit(from_entry = id, trail_points = p, trail_offset = o):
// once price is p ticks in profit, keep the stop o ticks behind the
// current price, never loosening it. Must run on EVERY tick.
void Trail(const string id, const int trailPoints, const int trailOffset)
{
const ulong ticket = SelectById(id);
if(ticket == 0)
return;
const double tick = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
const double open = PositionGetDouble(POSITION_PRICE_OPEN);
const double sl = PositionGetDouble(POSITION_SL);
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
const double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(bid - open < trailPoints * tick)
return;
const double want = NormalizeDouble(bid - trailOffset * tick, _Digits);
if(want > sl)
trade.PositionModify(ticket, want, PositionGetDouble(POSITION_TP));
}
else
{
const double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if(open - ask < trailPoints * tick)
return;
const double want = NormalizeDouble(ask + trailOffset * tick, _Digits);
if(sl == 0.0 || want < sl)
trade.PositionModify(ticket, want, PositionGetDouble(POSITION_TP));
}
}
void OnTick()
{
Trail("L", InpTrailPoints, InpTrailOffset); // every tick, like the emulator
if(!IsNewBar())
return;
double f[2], s[2], a[1];
if(CopyBuffer(hFast, 0, 1, 2, f) != 2 || CopyBuffer(hSlow, 0, 1, 2, s) != 2
|| CopyBuffer(hAtr, 0, 1, 1, a) != 1)
return;
const double c = iClose(_Symbol, _Period, 1);
if(f[1] > s[1] && f[0] <= s[0] && SelectById("L") == 0)
{
// entry and bracket in one request: sl/tp computed from the signal close
trade.Buy(InpLots, _Symbol, 0.0, NormalizeDouble(c - 2 * a[0], _Digits),
NormalizeDouble(c + 3 * a[0], _Digits), "L");
}
if(f[1] < s[1] && f[0] >= s[0] && SelectById("S") == 0)
{
if(trade.Sell(InpLots, _Symbol, 0.0, 0.0, 0.0, "S"))
ExitTicks("S", InpLossTicks, InpProfitTicks); // needs the fill price
}
}Where the two differ
| Topic | Pine | MQL5 |
|---|---|---|
| Where the bracket lives | in the emulator, per entry id | on the position (POSITION_SL/POSITION_TP), enforced by the broker |
| Exit before the entry fills | queued until the fill | PositionModify fails with no position; pass sl/tp to Buy, or modify after the fill |
| Tick unit | syminfo.mintick | SYMBOL_TRADE_TICK_SIZE; _Point is the same on most symbols but not all |
| Minimum distance | none | SYMBOL_TRADE_STOPS_LEVEL points; closer levels are rejected (retcode 10016) |
| Trailing stop | built into the emulator | your code, every tick; a bar-gated EA trails once per bar |
| Intrabar fills in the tester | assumed OHLC path | "Open prices only" triggers SL/TP at bar opens; use "1 minute OHLC" or real ticks |
What the Stratlate converter emits
The converter emits stop=/limit= as pine_set_brackets(from_entry, sl, tp), which calls PositionModify on every open position whose comment equals the entry id and leaves a side given as 0 or na unchanged; loss=/profit= become pine_set_brackets_ticks(from_entry, loss, profit), which computes the prices from POSITION_PRICE_OPEN and _Point. Both are treated as exact. Any exit that carries a trail_* argument, or mixes tick distances with absolute prices, is reported as an approximation (PM270) and emitted as pine_close_id(from_entry), a market close of that trade; a bare strategy.exit(id, from_entry) is the same close. For the script above that means the global trailing exit closes "L" on the bar after it opens, so the report's PM270 is the line to act on: replace it with a Trail helper like the one here, then compile and backtest.
Pitfalls
- Calling
PositionModifywith the prices the entry bar computed but on a bar when no position exists yet. Symptom: the call fails and the trade runs without a stop. - Treating
loss = 200as 200 pips. Symptom: on a 5-digit forex symbol the stop sits ten times closer than intended and is hit at once. - Trailing inside the new-bar gate. Symptom: the stop updates once per bar, so a spike inside the bar that TradingView's emulator would have caught leaves the MT5 trade open.
- Setting a stop inside the broker's stops level. Symptom: retcode 10016 "Invalid stops", often only live and not in the tester.
FAQ
Is strategy.exit the same as CTrade.PositionModify?
For stop= and limit= on an open position, yes: both set the stop-loss and take-profit the broker will execute. The tick-distance and trailing forms need the extra code shown above.
How do I convert profit= and loss= ticks to MQL5 prices?
Read the fill price with PositionGetDouble(POSITION_PRICE_OPEN), multiply the tick count by SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE), subtract for the stop and add for the target on a long, the reverse on a short.
Can MetaTrader 5 trail a stop by itself?
The terminal has a manual Trailing Stop in the position's context menu, but it runs only while that terminal is open and is not controllable from code. An EA that must trail does it in OnTick.
Convert the whole script
Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.
Open the converter