strategy.position_avg_price in MQL5: POSITION_PRICE_OPEN

Short answer

Read PositionGetDouble(POSITION_PRICE_OPEN). On a netting account the terminal keeps it as a volume-weighted average of the entries; on a hedging account each entry is its own position, so average their open prices weighted by POSITION_VOLUME.

strategy.position_avg_price is the average fill price of the open position, weighted by the size of each entry, and na when flat. In MQL5 the same number is PositionGetDouble(POSITION_PRICE_OPEN): on a netting account the terminal recomputes that field as a volume-weighted average every time a deal adds to the position, so one read is enough; on a hedging account each entry is its own position and you average their open prices yourself, weighting by POSITION_VOLUME.

What strategy.position_avg_price computes

With one entry it is that entry's fill price. With pyramiding, each additional fill updates it to (old_avg × old_size + fill_price × fill_size) / (old_size + fill_size), so the average moves toward the latest fill. A partial close does not change it: closing half of a position leaves the remaining half at the same average. When the position is reversed, the average becomes the fill price of the reversing order. It is updated when the fill happens, at the next bar's open, so on the entry bar it still reads the previous value (or na if the strategy was flat). Scripts use it to place exits relative to the entry: close > strategy.position_avg_price * 1.02 is a 2% target on the whole stack.

The MQL5 equivalent

//@version=6
strategy("Avg price demo", overlay = true, pyramiding = 2, default_qty_type = strategy.fixed, default_qty_value = 1)
targetPct = input.float(2.0, "Target %")
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
if ta.crossover(fast, slow)
    strategy.entry("L", strategy.long)
// second entry: the average price moves between the two fills
if strategy.position_size > 0 and close < strategy.position_avg_price * 0.99
    strategy.entry("L2", strategy.long)
// exit the whole stack a fixed percent above the average entry
if strategy.position_size > 0 and close > strategy.position_avg_price * (1 + targetPct / 100)
    strategy.close_all()
plot(strategy.position_avg_price, "Avg entry", color.orange, style = plot.style_linebr)

The EA's AvgPrice helper does the weighted average over this EA's positions and returns EMPTY_VALUE when flat, the usual MQL5 stand-in for na. On a netting account the loop sees one position and returns its POSITION_PRICE_OPEN unchanged; on a hedging account it averages the "L" and "L2" positions exactly as Pine does.

#include <Trade/Trade.mqh>
input double InpLots      = 0.10;
input double InpTargetPct = 2.0;     // Target %
input long   InpMagic     = 60018;
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_avg_price: volume-weighted average open price of this
// EA's positions on the symbol; EMPTY_VALUE when flat (Pine returns na).
// Also fills `lots` with the total volume. On a netting account the one
// position's POSITION_PRICE_OPEN is already this average.
double AvgPrice(double &lots)
  {
   double cost = 0.0;
   lots = 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);
      lots += v;
      cost += v * PositionGetDouble(POSITION_PRICE_OPEN);
     }
   return lots > 0.0 ? cost / lots : EMPTY_VALUE;
  }

int OwnLongs()
  {
   int n = 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)
         n++;
   return n;
  }

void CloseAll()
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      const ulong ticket = PositionGetTicket(i);
      if(ticket != 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
         && PositionGetInteger(POSITION_MAGIC) == InpMagic)
         trade.PositionClose(ticket);
     }
  }

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 double c = iClose(_Symbol, _Period, 1);
   double lots;
   const double avg = AvgPrice(lots);
   if(f[1] > s[1] && f[0] <= s[0] && OwnLongs() == 0)
      trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L");
   // pyramiding = 2: one add-on when price is 1% under the average
   if(lots > 0.0 && OwnLongs() < 2 && c < avg * 0.99)
      trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "L2");
   if(lots > 0.0 && c > avg * (1.0 + InpTargetPct / 100.0))
      CloseAll();
   Comment(lots > 0.0 ? "avg entry " + DoubleToString(avg, _Digits) : "flat");
  }

The plot in the Pine script has no EA equivalent; the Comment call shows the current value in the chart corner instead.

Where the two differ

TopicPineMQL5 nettingMQL5 hedging
SourceemulatorPOSITION_PRICE_OPEN, already averagedaverage over positions, weighted by volume
Flatnano position: return EMPTY_VALUE or test the count first
Partial closeunchangedunchangedunchanged per position; the weighted mean shifts if one position is trimmed
Reversalnew fill pricenew fill price, same ticketthe surviving position's open price
Precisionexact priceNormalizeDouble(avg, _Digits) before using it as an SL/TP level
Swap and commissionnot includednot included either; the broker tracks them separately on the position

What the Stratlate converter emits

The converter emits strategy.position_avg_price as the runtime call pine_position_avg_price(), which walks every open position, sums POSITION_VOLUME × POSITION_PRICE_OPEN and divides by the total volume, returning the runtime's na value when nothing is open; this is treated as exact and works identically on netting and hedging accounts. The walk is over the whole account, not filtered by symbol or magic number, so the EA should be the only trader on its account or run in the tester. Expressions such as close > strategy.position_avg_price * 1.02 convert unchanged around that call. In the script above the plot is dropped with a PM260 warning because an EA has no buffers, and pyramiding = 2 sets the runtime's entry limit (PM302, informational). Compile and backtest the output before trading it.

Pitfalls

  • Reading POSITION_PRICE_OPEN of one position on a hedging account and treating it as the average. Symptom: after the second entry the target sits at the first fill, not the blended level.
  • Using 0 or EMPTY_VALUE in a comparison without checking for a position. Symptom: close > 0 * 1.02 is always true and the EA "exits" every bar.
  • Expecting commission or swap in the number. Symptom: a break-even exit at the average price still loses the costs; add them from POSITION_SWAP and the deal history if you need true break-even.
  • Passing the raw average as an SL level. Symptom: retcode 10015 "Invalid price" on symbols where the average has more decimals than _Digits.

FAQ

Is POSITION_PRICE_OPEN the same as strategy.position_avg_price?

On a netting account, yes: MT5 maintains it as the volume-weighted average of all deals that built the position. On a hedging account it is one entry's price, and the average is computed across positions.

What does MQL5 return when there is no position?

Nothing useful: PositionGetDouble returns 0 when no position is selected. Test PositionsTotal() or your own count first and use EMPTY_VALUE as the "flat" marker, as Pine uses na.

Does the average change when I close part of the position?

No, on either platform. Closing part of a position realises profit on the closed part and leaves the remaining volume at the same average entry price.

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

Related