strategy.position_size in MQL5: signed volume from positions
Short answer
MQL5 has no single value for it: loop over PositionsTotal(), add POSITION_VOLUME for a POSITION_TYPE_BUY and subtract it for a POSITION_TYPE_SELL, keeping only this symbol and this EA's magic number. The result is in lots, not contracts.
strategy.position_size is the strategy's net position: greater than zero while long, less than zero while short, exactly zero when flat, measured in contracts. MQL5 has no single value for it. The equivalent is a loop over PositionsTotal() that adds PositionGetDouble(POSITION_VOLUME) for a POSITION_TYPE_BUY and subtracts it for a POSITION_TYPE_SELL, keeping only positions on this symbol with this EA's magic number. The result is in lots.
What strategy.position_size computes
Pine keeps one net position per strategy. Every fill changes it by the signed quantity: an entry of 1 long makes it 1, a reversal to short makes it −1, a partial close of 50% makes it 0.5 of the sign it had. The value is updated when the order fills, which by default is the open of the bar after the signal, so on the signal bar itself strategy.position_size still shows the old position; the common gate if strategy.position_size == 0 therefore reads the state before this bar's orders. The number is in the units default_qty_value uses: contracts, shares or units of base currency, never lots. Its sign is the usual way Pine scripts know their side, and its absolute value feeds strategy.order(..., qty = strategy.position_size) to flatten.
The MQL5 equivalent
//@version=6
strategy("Position size demo", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 1)
rsi = ta.rsi(close, 14)
isFlat = strategy.position_size == 0
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0
if isFlat and ta.crossover(rsi, 30)
strategy.entry("L", strategy.long)
if isFlat and ta.crossunder(rsi, 70)
strategy.entry("S", strategy.short)
if isLong and rsi > 60
strategy.close("L")
if isShort and rsi < 40
strategy.close("S")The EA computes PositionSize() once per bar before any order, which reproduces Pine's "state before this bar's orders" reading, and uses the sign exactly as the Pine script does. PositionSizeContracts() shows the conversion to Pine's unit.
#include <Trade/Trade.mqh>
input double InpLots = 0.10;
input long InpMagic = 60017;
CTrade trade;
int hRsi = INVALID_HANDLE;
int OnInit()
{
hRsi = iRSI(_Symbol, _Period, 14, PRICE_CLOSE);
if(hRsi == 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 in LOTS: positive long, negative short, 0 flat.
// Sums this EA's positions on this symbol; on a netting account there is
// at most one, on a hedging account several may be open.
double PositionSize()
{
double net = 0.0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(PositionGetTicket(i) == 0)
continue;
if(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;
}
// the same number in Pine's unit (contracts / base-currency units)
double PositionSizeContracts()
{
return PositionSize() * SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
}
void CloseSide(const ENUM_POSITION_TYPE type)
{
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) == type)
trade.PositionClose(ticket);
}
}
void OnTick()
{
if(!IsNewBar())
return;
double r[2];
if(CopyBuffer(hRsi, 0, 1, 2, r) != 2)
return;
const double size = PositionSize();
const bool isFlat = size == 0.0;
const bool isLong = size > 0.0;
const bool isShort = size < 0.0;
if(isFlat && r[0] <= 30 && r[1] > 30)
trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
if(isFlat && r[0] >= 70 && r[1] < 70)
trade.Sell(InpLots, _Symbol, 0.0, 0.0, 0.0, "S");
if(isLong && r[1] > 60)
CloseSide(POSITION_TYPE_BUY);
if(isShort && r[1] < 40)
CloseSide(POSITION_TYPE_SELL);
Comment("position_size: ", DoubleToString(size, 2), " lots = ",
DoubleToString(PositionSizeContracts(), 0), " units");
}On a netting account the loop finds at most one position per symbol, so it reduces to one PositionSelect(_Symbol) plus a sign, but the loop form is the one that also works on hedging accounts, where a long and a short can coexist and the net is their difference.
Where the two differ
| Topic | Pine | MQL5 |
|---|---|---|
| Unit | contracts / units | lots; multiply by SYMBOL_TRADE_CONTRACT_SIZE for units |
| Scope | this strategy only | the whole account unless you filter by symbol and POSITION_MAGIC |
| Update time | at the fill, next bar's open | immediately after Buy/Sell returns; read it once at the top of the bar |
| Hedging account | n/a, always net | long and short can be open together; the sum nets them |
| Flat test | == 0 is exact | exact too, volumes are multiples of the lot step; compare against 0.0 |
| Realtime bar | may change intrabar with calc_on_every_tick | changes the instant an SL or TP fires, between your bar evaluations |
What the Stratlate converter emits
The converter emits strategy.position_size as the runtime call pine_position_size(), which walks PositionsTotal(), selects each position with PositionGetTicket, and adds POSITION_VOLUME for a POSITION_TYPE_BUY and subtracts it for a sell; the value is in lots and is treated as exact. The runtime does not filter by symbol or magic number, so the EA should run alone on its account or in the tester, where it is the only trader. Comparisons such as strategy.position_size > 0 convert unchanged (pine_position_size() > 0), and the entry gate pine_entry_allowed uses the same pool, so a strategy that gates its entries on being flat behaves as in Pine. Compile and backtest the output before trading it.
Pitfalls
- Comparing Pine's quantity with MT5 lots. Symptom:
qty = strategy.position_sizeported literally sends 100,000 lots on a forex symbol and is rejected. - Summing every position in the account. Symptom: a manual trade on another symbol makes the EA believe it is in a trade and it never enters.
- Re-reading the size after sending an order inside the same bar. Symptom: an entry followed by an exit on the same bar, because the "is long" branch now sees the fresh position.
- Using
PositionSelect(_Symbol)on a hedging account. Symptom: it selects one of several positions and the size ignores the rest. - Treating the stop-out of a position by the broker as impossible. Symptom: the EA's cached "I am long" flag disagrees with the account; read the pool, do not cache.
FAQ
Is there a built-in strategy.position_size in MQL5?
No. PositionGetDouble(POSITION_VOLUME) gives one position's unsigned volume; the signed net value is a loop you write, as above.
Why is the MQL5 value so much smaller than Pine's?
It is in lots. One standard forex lot is 100,000 units, so Pine's 10,000 units of EURUSD is 0.10 lot. Metals, indices and crypto have their own contract sizes, readable from SYMBOL_TRADE_CONTRACT_SIZE.
How do I check "flat" safely in MQL5?
Compute the signed sum and compare with 0.0. Volumes are exact multiples of SYMBOL_VOLUME_STEP, so a long and a short of equal size sum to exactly zero without a tolerance.
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