strategy.cancel in MQL5: OrderDelete for pending orders
Short answer
Use CTrade::OrderDelete(ticket) over the pending orders (OrdersTotal() and OrderGetTicket(i)), filtered by symbol, magic number and, for cancel(id), the comment that carries the id. Open positions are untouched; closing one is PositionClose.
strategy.cancel(id) removes the unfilled orders placed under an id, and strategy.cancel_all() removes every unfilled order; neither touches an open trade. The MQL5 equivalent is CTrade::OrderDelete(ticket) over the pending-order pool (OrdersTotal() / OrderGetTicket(i)), filtered to this EA's symbol, magic number and, for cancel(id), the comment that carries the id. Closing a position is a different call, PositionClose.
What strategy.cancel computes
A strategy.entry or strategy.order with limit= or stop= rests until price reaches it; a strategy.exit with a bracket rests as the trade's stop and target. strategy.cancel(id) deactivates the resting orders whose id matches, so an entry that would have filled on a later bar never fills and a cancelled exit leaves the trade without its bracket. The call takes effect immediately on the bar it runs; it does not wait for the next open. Re-sending the entry on a later bar creates the order again. strategy.cancel_all() does the same for every id. Pine scripts use it to drop a breakout order when the setup fails and to clear resting orders before a session ends, as in the example.
The MQL5 equivalent
//@version=6
strategy("Cancel demo", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 1)
hi = ta.highest(high, 20)
inSession = hour >= 9 and hour < 17
// a breakout stop order, re-armed on every bar of the session
if inSession and strategy.position_size == 0
strategy.entry("Brk", strategy.long, stop = hi[1])
// drop the resting order when the setup fails
if ta.crossunder(close, ta.sma(close, 20))
strategy.cancel("Brk")
// and whatever is still resting when the session ends
if not inSession
strategy.cancel_all()In MQL5 pending orders and positions live in separate pools, which makes Cancel simple: everything OrdersTotal() counts is a resting order. The helper below walks the pool backwards (deleting renumbers it), keeps this EA's orders on this symbol, and deletes those whose comment matches, or all of them when the id is empty.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input long InpMagic = 60016;
CTrade trade;
int hSma = INVALID_HANDLE;
int OnInit()
{
hSma = iMA(_Symbol, _Period, 20, 0, MODE_SMA, PRICE_CLOSE);
if(hSma == 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;
}
// strategy.cancel(id): delete this EA's PENDING orders carrying id.
// strategy.cancel_all(): the same with id == "". Positions are untouched:
// OrdersTotal() in MQL5 holds only pending orders. Returns how many went.
int Cancel(const string id = "")
{
int n = 0;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
const ulong ticket = OrderGetTicket(i);
if(ticket == 0 || OrderGetString(ORDER_SYMBOL) != _Symbol
|| OrderGetInteger(ORDER_MAGIC) != InpMagic)
continue;
if(id != "" && OrderGetString(ORDER_COMMENT) != id)
continue;
if(trade.OrderDelete(ticket))
n++;
}
return n;
}
bool HasPosition()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
if(PositionGetTicket(i) != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic)
return true;
return false;
}
void OnTick()
{
if(!IsNewBar())
return;
MqlDateTime dt;
TimeToStruct(iTime(_Symbol, _Period, 1), dt);
const bool inSession = dt.hour >= 9 && dt.hour < 17;
double s[2];
if(CopyBuffer(hSma, 0, 1, 2, s) != 2)
return;
// strategy.entry("Brk", strategy.long, stop = hi[1]): one resting order,
// replaced each bar -> cancel the old one, then place the new one
if(inSession && !HasPosition())
{
Cancel("Brk");
const int bar = iHighest(_Symbol, _Period, MODE_HIGH, 20, 2);
const double level = NormalizeDouble(iHigh(_Symbol, _Period, bar), _Digits);
if(level > SymbolInfoDouble(_Symbol, SYMBOL_ASK))
trade.BuyStop(InpLots, level, _Symbol, 0.0, 0.0, ORDER_TIME_GTC, 0, "Brk");
}
const double c1 = iClose(_Symbol, _Period, 1), c2 = iClose(_Symbol, _Period, 2);
if(c1 < s[1] && c2 >= s[0])
Cancel("Brk"); // strategy.cancel("Brk")
if(!inSession)
Cancel(); // strategy.cancel_all()
}Two details carry over from Pine. The breakout entry is re-armed each bar, so the EA deletes the previous "Brk" order before placing the new one, which is what the same-id rule does in Pine. And a BuyStop must sit above the current ask, otherwise the terminal rejects it with "Invalid price"; Pine would simply fill such a stop at market.
Where the two differ
| Topic | Pine | MQL5 |
|---|---|---|
| What is cancelled | resting entries, orders and exit brackets with that id | pending orders only; a bracket is removed with PositionModify(ticket, 0, 0) |
| Pool | one list of orders | OrdersTotal() for pending orders, PositionsTotal() for positions |
| Ownership | only the strategy's orders exist | filter by ORDER_MAGIC and ORDER_SYMBOL |
| Id | first-class | ORDER_COMMENT, set when the order was placed |
| Timing | same bar | same tick; OrderDelete is synchronous and returns false if the order filled meanwhile |
| Expiry alternative | none; cancel by hand | ORDER_TIME_SPECIFIED lets the broker expire the order for you |
What the Stratlate converter emits
The converter emits strategy.cancel("Brk") as pine_cancel_id("Brk") and strategy.cancel_all() as pine_cancel_all(). The runtime walks OrdersTotal() backwards, collects the tickets of pending orders on the symbol whose ORDER_COMMENT matches (every order when the id is empty) and deletes each with CTrade::OrderDelete; open positions are never touched. The resting entry itself is emitted as pine_entry_pending(OP_BUYSTOP, qty, price, "Brk"), which cancels the previous order with that id before placing the new one, so the per-bar re-arm does not pile up orders. Both calls are treated as exact. The filter is symbol and comment, not magic number. Compile and backtest the output before trading it.
Pitfalls
- Calling
PositionCloseforstrategy.cancel. Symptom: a live trade is closed while the resting order stays and fills later. - Walking
OrdersTotal()forwards while deleting. Symptom: every second order survives. - Placing the re-armed stop order without deleting the old one. Symptom: one new pending order per bar and a position several times the intended size when they all fill.
- Deleting by symbol only. Symptom: manual pending orders on the same symbol disappear.
- Expecting
cancelto remove a stop-loss. Symptom: the position keeps its SL; in MT5 the bracket belongs to the position and is cleared withPositionModify.
FAQ
Is strategy.cancel the same as OrderDelete?
For a resting entry, yes. For an exit bracket it is not: an MT5 stop-loss or take-profit is a property of the position, removed by modifying the position with zero levels, not an order you can delete.
Does strategy.cancel_all close positions?
No, in either platform. It only removes unfilled orders. To flatten, call strategy.close_all() in Pine or loop PositionClose in MQL5.
How do I find a pending order by its Pine id in MQL5?
Loop i from OrdersTotal() - 1 down to 0, call OrderGetTicket(i) to select it, and compare OrderGetString(ORDER_COMMENT) with the id, along with ORDER_SYMBOL and ORDER_MAGIC.
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