strategy.entry in MQL5: CTrade Buy/Sell with Pine's reversal
Short answer
Use CTrade::Buy or CTrade::Sell on the first tick of the new bar, after closing any position on the opposite side. The Pine id travels as the order comment, and a limit= or stop= entry becomes a pending BuyLimit, SellLimit, BuyStop or SellStop.
strategy.entry(id, direction) opens or reverses a position under a named id and fills at the next bar's open. The MQL5 equivalent is CTrade::Buy or CTrade::Sell, sent on the first tick of the new bar, after your code has closed any position on the opposite side; the Pine id travels as the order comment and the EA's magic number marks the trade as its own. A limit= or stop= entry is a pending order: BuyLimit, SellLimit, BuyStop or SellStop.
What strategy.entry computes
Three rules distinguish strategy.entry from a plain order. First, it is direction-aware: when the strategy holds a position the other way, the entry closes it and opens the new one in a single fill, so the net position flips from +qty to −qty. Second, it respects pyramiding: with the default of 0, a second entry in the same direction is ignored while the position is open, whatever its id. Third, an entry sent again under the same id replaces the previous unfilled order with that id, which is how a limit= entry re-armed every bar stays a single resting order. The market variant fills at the next bar's open (or the signal bar's close with process_orders_on_close); the limit=/stop= variants rest at their price until a later bar touches it. qty defaults to the declaration's default_qty_value and is in contracts, not lots.
The MQL5 equivalent
//@version=6
strategy("Entry demo", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 1)
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
if ta.crossover(fast, slow)
strategy.entry("L", strategy.long) // reverses a short
if ta.crossunder(fast, slow)
strategy.entry("S", strategy.short) // reverses a long
if ta.crossover(fast, slow) and close < ta.sma(close, 100)
strategy.entry("Dip", strategy.long, limit = low) // resting orderThe EA below keeps the three rules in two helpers. Entry walks this EA's positions on the symbol (symbol plus magic number), returns without trading if one already points the same way, closes any opposite one, then sends the market order with the id as comment. EntryLimit deletes a resting order with the same id before placing the new one.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input long InpMagic = 60012;
CTrade trade;
int hFast = INVALID_HANDLE, hSlow = INVALID_HANDLE, hBase = INVALID_HANDLE;
int OnInit()
{
hFast = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, 21, 0, MODE_EMA, PRICE_CLOSE);
hBase = iMA(_Symbol, _Period, 100, 0, MODE_SMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE || hBase == 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.entry(id, direction): ignore a same-direction entry while one
// is open, close an opposite one first, then open. Works on netting and
// hedging accounts alike because the opposite side is closed explicitly.
bool Entry(const string id, const bool isLong, const double lots)
{
for(int i = PositionsTotal() - 1; i >= 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)
return false; // pyramiding 0: already in
trade.PositionClose(ticket); // reversal: flat first
}
return isLong ? trade.Buy(lots, _Symbol, 0.0, 0.0, 0.0, id)
: trade.Sell(lots, _Symbol, 0.0, 0.0, 0.0, id);
}
// strategy.entry(id, strategy.long, limit = price): a resting order.
// Pine replaces the order when the same id is sent again; do the same.
bool EntryLimit(const string id, const bool isLong, const double lots, double price)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
const ulong ticket = OrderGetTicket(i);
if(ticket != 0 && OrderGetString(ORDER_SYMBOL) == _Symbol
&& OrderGetInteger(ORDER_MAGIC) == InpMagic
&& OrderGetString(ORDER_COMMENT) == id)
trade.OrderDelete(ticket);
}
price = NormalizeDouble(price, _Digits);
return isLong ? trade.BuyLimit(lots, price, _Symbol, 0.0, 0.0, ORDER_TIME_GTC, 0, id)
: trade.SellLimit(lots, price, _Symbol, 0.0, 0.0, ORDER_TIME_GTC, 0, id);
}
void OnTick()
{
if(!IsNewBar())
return;
double f[2], s[2], b[1];
if(CopyBuffer(hFast, 0, 1, 2, f) != 2 || CopyBuffer(hSlow, 0, 1, 2, s) != 2
|| CopyBuffer(hBase, 0, 1, 1, b) != 1)
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)
Entry("L", true, InpLots);
if(crossDown)
Entry("S", false, InpLots);
if(crossUp && iClose(_Symbol, _Period, 1) < b[0])
EntryLimit("Dip", true, InpLots, iLow(_Symbol, _Period, 1));
}trade.Buy(volume, symbol, price, sl, tp, comment) with price = 0 fills at the current ask. The reversal is explicit (close, then open) so it behaves identically on netting and hedging accounts. On a netting account you could instead send one order for twice the volume and let the terminal net it, but the same code opens two opposite positions on a hedging account, so the explicit close-then-open is the version that ports.
Where the two differ
| Topic | Pine | MQL5 |
|---|---|---|
| Fill price | next bar's open, one price for buys and sells | ask for a buy, bid for a sell, on the first tick of the bar; the spread is paid |
| Reversal | built in | you close the opposite position first; netting accounts would also accept a single oversized order |
| Same-direction repeat | ignored under pyramiding = 0 | opens another position (hedging) or enlarges the position (netting) unless you check |
| Entry id | first-class, used by strategy.close and strategy.exit | order comment; the magic number identifies the EA |
Re-sent limit= entry | replaces the resting order | a second BuyLimit is a second order unless you delete the first |
| Quantity | contracts or units | lots, rounded to SYMBOL_VOLUME_STEP |
What the Stratlate converter emits
A market strategy.entry is emitted as a positional OrderSend(Symbol(), OP_BUY, qty, ask, 3, 0, 0, "L", 0) wrapped in if(pine_entry_allowed(OP_BUY)); the runtime's OrderSend shim turns that into CTrade::Buy or Sell with the id as comment, and pine_entry_allowed drops a same-direction entry and closes every open position on the symbol before an opposite one, which is Pine's reversal. A limit= or stop= entry is emitted as pine_entry_pending(OP_BUYLIMIT, qty, price, "Dip"), which cancels the resting order with that id, then places a BuyLimit/BuyStop (or the sell variants) through CTrade; an entry with both limit and stop is emitted as the limit order and reported as an approximation (PM301). A direction that is neither strategy.long/strategy.short nor a bool is reported as unsupported rather than guessed. The script above converts CLEAN; compile and backtest the output before trading it.
Pitfalls
- Sending
trade.Sellwhile long on a hedging account. Symptom: two open positions, long and short, where Pine shows one short. - Filtering positions by symbol only. Symptom: the EA closes or refuses entries because of trades opened manually or by another EA.
- Placing a new
BuyLimiton every bar for a re-armedlimit=entry. Symptom: dozens of resting orders and a position many times the intended size. - Passing Pine's
qtyas lots. Symptom: a volume rejected as invalid, or a position 100,000 times too large on forex.
FAQ
Is CTrade.Buy the same as strategy.entry?
Only for the order itself. Buy does not reverse, does not know about pyramiding and does not replace an earlier order with the same comment, so those rules are written around it, as in the Entry helper above.
How do I carry the Pine entry id into MQL5?
Pass it as the comment argument of Buy, Sell or BuyLimit. It is then readable on the position as POSITION_COMMENT and on a pending order as ORDER_COMMENT, which is what a strategy.close("L") equivalent filters on.
Why does the MT5 backtest fill slightly worse than TradingView?
TradingView fills a market order at the bar's open price; MT5 fills a buy at the ask and a sell at the bid, so each round trip pays one spread that the Pine report never saw unless you modelled it with slippage.
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