pyramiding in MQL5: limiting stacked entries in an EA
Short answer
MetaTrader 5 has no pyramiding setting, so the EA enforces it before every buy or sell. On a hedging account count your positions of that type; on a netting account all entries merge into one position, so keep an entry counter and reset it when the position is gone.
pyramiding in the strategy() declaration is the maximum number of strategy.entry fills allowed in the same direction while a position is open; the default 0 (like 1) allows a single entry. MetaTrader 5 has no such setting, so an EA enforces it before every buy or sell: on a hedging account each entry is its own position and the EA counts its positions of that type; on a netting account all entries merge into one position, so the EA keeps its own entry counter and resets it when the position is gone.
What pyramiding computes
With pyramiding = 3, the first three long strategy.entry calls while long each add their quantity; a fourth is ignored until at least one entry has been closed. The limit counts entries, not size, and counts them regardless of their ids: "L" three times or "L1", "L2", "L3" both reach the cap. It applies to strategy.entry only; strategy.order ignores it. Each entry stays a separate trade in Pine's trade list, so strategy.opentrades is 3, strategy.position_size is the sum, and strategy.position_avg_price is their weighted average. strategy.close("L") closes every open trade with id "L"; with close_entries_rule = "FIFO" (the default) exits otherwise take the oldest entry first.
The MQL5 equivalent
//@version=6
strategy("Pyramiding demo", overlay = true, pyramiding = 3,
default_qty_type = strategy.fixed, default_qty_value = 1)
trend = ta.ema(close, 50)
// add one unit on every pullback that holds above the trend, up to 3 entries
if close > trend and ta.crossover(close, ta.ema(close, 9))
strategy.entry("L", strategy.long)
if ta.crossunder(close, trend)
strategy.close("L") // closes all stacked "L" entriesLongEntries answers "how many entries are stacked" for both account types, and the entry is sent only below the cap. Because a broker stop-loss or a manual close can flatten the position between bars, the counter is reset whenever no long position is found.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input int InpPyramiding = 3; // strategy(pyramiding = 3)
input long InpMagic = 60023;
CTrade trade;
int hTrend = INVALID_HANDLE, hFast = INVALID_HANDLE;
int entriesOpen = 0; // entries in the current long (netting)
int OnInit()
{
hTrend = iMA(_Symbol, _Period, 50, 0, MODE_EMA, PRICE_CLOSE);
hFast = iMA(_Symbol, _Period, 9, 0, MODE_EMA, PRICE_CLOSE);
if(hTrend == INVALID_HANDLE || hFast == 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;
}
bool Hedging()
{
return AccountInfoInteger(ACCOUNT_MARGIN_MODE) == ACCOUNT_MARGIN_MODE_RETAIL_HEDGING;
}
// entries currently stacked on the long side. Hedging: one position per
// entry, so count them. Netting: they are merged into one position, so
// the EA has to keep its own counter.
int LongEntries()
{
int positions = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
if(PositionGetTicket(i) != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic
&& PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
positions++;
if(positions == 0)
entriesOpen = 0; // flat (also after an SL/TP hit)
return Hedging() ? positions : entriesOpen;
}
void CloseLongs()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
const ulong ticket = PositionGetTicket(i);
if(ticket != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
&& PositionGetInteger(POSITION_MAGIC) == InpMagic
&& PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
trade.PositionClose(ticket);
}
entriesOpen = 0;
}
void OnTick()
{
if(!IsNewBar())
return;
double t[1], f[2];
if(CopyBuffer(hTrend, 0, 1, 1, t) != 1 || CopyBuffer(hFast, 0, 1, 2, f) != 2)
return;
const double c1 = iClose(_Symbol, _Period, 1), c2 = iClose(_Symbol, _Period, 2);
const bool pullbackEnd = c1 > f[1] && c2 <= f[0];
if(c1 > t[0] && pullbackEnd && LongEntries() < MathMax(1, InpPyramiding))
if(trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L"))
entriesOpen++;
if(c1 < t[0] && c2 >= t[0])
CloseLongs();
}On a hedging account the three entries are three tickets with the comment "L", and CloseLongs closes all of them, which is strategy.close("L"). On a netting account there is one ticket whose volume grows by InpLots per entry and whose POSITION_PRICE_OPEN is re-averaged by the terminal.
Where the two differ
| Topic | Pine | MQL5 hedging | MQL5 netting |
|---|---|---|---|
| Each entry | a separate trade | a separate position | merged into one position |
| Counting entries | built in | count positions by magic and type | your own counter |
| Closing one entry | strategy.close with its id, or strategy.exit | PositionClose(ticket) | PositionClosePartial of that entry's volume |
| Brackets per entry | one strategy.exit per id | SL/TP per position | one SL/TP for the whole position |
| Default | 0 = one entry | no limit at all unless you code one | |
What the Stratlate converter emits
When pyramiding is a literal above 1, the converter writes __pinePyramiding = 3; into OnInit and notes it as PM302 (informational). Every market strategy.entry is wrapped in if(pine_entry_allowed(OP_BUY)), which counts the open positions on the symbol in the entry's direction, drops the entry when the count has reached __pinePyramiding, and closes opposite positions before a reversal. That count is of positions, so it matches Pine on a hedging account. On a netting account the stacked entries merge into one position, the count stays at 1, and the limit is not reached: a converted pyramiding strategy keeps adding on every signal there. Backtest pyramiding strategies on a hedging account, or add an entry counter like the one above. The runtime does not filter positions by magic number.
Pitfalls
- Counting positions on a netting account. Symptom: the count never exceeds 1, so the EA adds on every signal and the position grows without bound.
- Keeping the counter only in memory. Symptom: after a restart the EA forgets two entries are open and stacks three more; rebuild it from the deal history in
OnInitif that matters. - Not resetting the counter when a stop-loss closes the position. Symptom: the EA refuses all new entries after the first stopped-out stack.
- Applying the cap to
strategy.orderconversions. Symptom: scale-in logic that Pine allows is silently blocked. - Treating Pine's default 0 as "no limit". Symptom: an EA that stacks entries where the Pine strategy only ever held one.
FAQ
What does pyramiding = 0 mean?
The same as 1: one entry per direction. A second strategy.entry in the same direction is ignored while the first is open; an entry in the opposite direction still reverses.
How do I limit open positions per direction in an MQL5 EA?
Loop PositionsTotal(), count positions with your symbol, magic number and POSITION_TYPE, and send the order only when the count is below the limit. On a netting account count entries yourself, because they share one position.
Why does my pyramiding EA behave differently on another broker?
The account mode. Most retail forex accounts are hedging; many exchange and some broker accounts are netting. Read ACCOUNT_MARGIN_MODE in OnInit and handle both.
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