strategy.order in MQL5: an order that adds, never reverses
Short answer
strategy.order is a bare CTrade::Buy or CTrade::Sell with no reversal logic. A netting account nets the new deal against the position as Pine does; on a hedging account a sell beside a long opens a second position, so close or partially close the opposite position first.
strategy.order(id, direction, qty) is the low-level order in Pine: it adds qty contracts long or short to whatever the strategy holds, with none of strategy.entry's rules. In MQL5 that is a bare CTrade::Buy or CTrade::Sell. On a netting account the terminal nets the new deal against the existing position exactly as Pine does; on a hedging account a sell beside a long opens a second position, so an EA that wants Pine's net result closes or partially closes the opposite positions first.
What strategy.order computes
The order fills at the next bar's open (or rests at limit/stop) and changes the net position by a signed quantity: long 2 plus strategy.order("x", strategy.short, qty = 1) is long 1, and qty = 3 would make it short 1. Pyramiding does not apply to it, and an opposite order does not trigger a reversal; it simply nets. Re-sending an unfilled order under the same id modifies that order instead of adding a second one. Because the quantity is literal, strategy.order is what Pine scripts use to scale in by fixed amounts and to flatten with qty = strategy.position_size. Omitting qty uses the declaration's default_qty_value.
The MQL5 equivalent
//@version=6
strategy("Order demo", overlay = true, pyramiding = 3, default_qty_type = strategy.fixed, default_qty_value = 1)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
// strategy.order adds to whatever is held; it never reverses
if ta.crossover(fast, slow)
strategy.order("Add", strategy.long, qty = 1)
// an opposite order of the held size nets the position to flat
if ta.crossunder(fast, slow) and strategy.position_size > 0
strategy.order("Flat", strategy.short, qty = strategy.position_size)The EA's Order helper sends the order and, on a hedging account only, consumes opposite positions first so that the account's net position moves by exactly lots. The pyramiding cap in OnTick is the EA's own guard; Pine's strategy.order has none.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input long InpMagic = 60015;
CTrade trade;
int hFast = INVALID_HANDLE, hSlow = INVALID_HANDLE;
int OnInit()
{
hFast = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == 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.position_size: signed net lots of this EA on this symbol
double PositionSize()
{
double net = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(PositionGetTicket(i) == 0 || PositionGetString(POSITION_SYMBOL) != _Symbol
|| PositionGetInteger(POSITION_MAGIC) != InpMagic)
continue;
const double v = PositionGetDouble(POSITION_VOLUME);
net += PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? v : -v;
}
return net;
}
// strategy.order(id, direction, qty): add `lots` to the net position.
// Netting account: one Buy/Sell and the terminal nets it. Hedging account:
// reduce opposite positions first so the net result is the same.
bool Order(const string id, const bool isLong, double lots)
{
const bool hedging = AccountInfoInteger(ACCOUNT_MARGIN_MODE)
== ACCOUNT_MARGIN_MODE_RETAIL_HEDGING;
if(hedging)
for(int i = PositionsTotal() - 1; i >= 0 && lots > 0; i--)
{
const ulong ticket = PositionGetTicket(i);
if(ticket == 0 || PositionGetString(POSITION_SYMBOL) != _Symbol
|| PositionGetInteger(POSITION_MAGIC) != InpMagic)
continue;
const bool posLong = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY;
if(posLong == isLong)
continue; // same side: nothing to net
const double v = PositionGetDouble(POSITION_VOLUME);
if(v <= lots + 1e-9)
{
trade.PositionClose(ticket); // this one is consumed whole
lots -= v;
}
else
{
trade.PositionClosePartial(ticket, lots);
lots = 0;
}
}
if(lots < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN) - 1e-9)
return true; // fully netted, nothing to open
return isLong ? trade.Buy(lots, _Symbol, 0.0, 0.0, 0.0, id)
: trade.Sell(lots, _Symbol, 0.0, 0.0, 0.0, id);
}
void OnTick()
{
if(!IsNewBar())
return;
double f[2], s[2];
if(CopyBuffer(hFast, 0, 1, 2, f) != 2 || CopyBuffer(hSlow, 0, 1, 2, s) != 2)
return;
const bool crossUp = f[1] > s[1] && f[0] <= s[0];
const bool crossDown = f[1] < s[1] && f[0] >= s[0];
if(crossUp && PositionSize() < 3 * InpLots - 1e-9) // pyramiding = 3
Order("Add", true, InpLots);
const double held = PositionSize();
if(crossDown && held > 0)
Order("Flat", false, held); // nets to zero
}AccountInfoInteger(ACCOUNT_MARGIN_MODE) tells the two account types apart. On ACCOUNT_MARGIN_MODE_RETAIL_NETTING (and exchange netting) the Buy/Sell alone is enough: a sell of the held volume closes the position, a larger sell flips it, exactly as in Pine. The partial-close branch is what makes the same EA behave identically under hedging.
Where the two differ
| Topic | Pine | MQL5 netting | MQL5 hedging |
|---|---|---|---|
| Opposite order smaller than the position | reduces it | reduces it | opens a second position; use PositionClosePartial |
| Opposite order larger than the position | flips it | flips it, same ticket | two positions; close, then open the remainder |
| Same-direction order | adds, ignores pyramiding | enlarges the one position, average price changes | a new position per order |
| Id | names the order | the comment of the deal; a netted position keeps the comment of its first deal | |
| Quantity unit | contracts | lots, in steps of SYMBOL_VOLUME_STEP | |
| Fill | next bar's open | current ask/bid on the tick you send | |
What the Stratlate converter emits
The converter emits strategy.order through the same path as strategy.entry: a positional OrderSend(Symbol(), OP_BUY, qty, ask, 3, 0, 0, "Add", 0) that the runtime forwards to CTrade::Buy/Sell, wrapped in if(pine_entry_allowed(OP_BUY)). That gate applies the entry rules, not the order rules: a same-direction order beyond the declared pyramiding count is dropped, and an opposite-direction order first closes every open position on the symbol and then sends the full qty. For the script above the result still matches, because pine_position_size() is evaluated after the close and the zero-volume sell is refused, but a reducing order such as qty = 1 against a long of 2 ends short 1 in the EA where Pine is long 1. A limit=/stop= order is emitted as a pending OrderSend at that price without the re-arm logic. Treat every converted strategy.order as a line to review, then compile and backtest.
Pitfalls
- Using
strategy.entrylogic (close opposite, then open) for astrategy.orderthat was meant to scale out. Symptom: a reducing order flattens and reverses instead of trimming. - Selling against a long on a hedging account with a plain
Sell. Symptom: a long and a short open at once, margin for both, andstrategy.position_sizelogic that reads zero while two trades are live. - Sending the remainder when it rounds below
SYMBOL_VOLUME_MIN. Symptom: retcode 10014 "Invalid volume". - Assuming the netted position carries the new order's comment. Symptom: an id-based close finds nothing, because the position still shows the first deal's comment.
- Scaling in without a cap. Symptom: every signal bar adds another lot until margin runs out; Pine's report shows the same, but the broker stops the EA earlier.
FAQ
Is strategy.order the same as CTrade.Buy?
On a netting account, yes: both add a signed quantity to the one position and net automatically. On a hedging account Buy beside a short opens a second position, so the net effect of Pine's order needs a partial close of the opposite side first.
When should I use strategy.order instead of strategy.entry?
When the quantity matters more than the direction: adding a fixed amount, trimming by a fixed amount, or flattening with qty = strategy.position_size. strategy.entry is for "be long now" regardless of what is held.
How do I know whether the MT5 account nets or hedges?
Read AccountInfoInteger(ACCOUNT_MARGIN_MODE): ACCOUNT_MARGIN_MODE_RETAIL_HEDGING allows several positions per symbol; the two netting modes allow one. The Strategy Tester follows the account the terminal is logged into.
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