PositionSelect in Pine Script: strategy.position_size

Short answer

Use strategy.position_size (positive long, negative short, 0 flat), strategy.position_avg_price and strategy.openprofit. if(PositionSelect(_Symbol)) becomes if strategy.position_size != 0; keep SL and TP in your own var.

PositionSelect(symbol) selects the open position on a symbol so that PositionGetDouble, PositionGetInteger and PositionGetString can read its properties: entry price, volume, type, stop-loss, take-profit, profit, magic number. A Pine Script strategy exposes its single net position through built-in variables instead: strategy.position_size (signed; positive is long, negative short, 0 flat), strategy.position_avg_price and strategy.openprofit, plus per-trade details in strategy.opentrades.*. if(PositionSelect(_Symbol)) becomes if strategy.position_size != 0.

What PositionSelect computes

On a netting account there is at most one position per symbol, and PositionSelect(symbol) returns true and copies it into the program's selection when it exists. On a hedging account there can be several; PositionSelect then picks the one with the lowest ticket, and robust code iterates with PositionsTotal(), PositionGetTicket(i) and filters by POSITION_SYMBOL and POSITION_MAGIC so that it only touches its own trades. The selected data is a snapshot; it does not update until the next select. Useful properties: POSITION_TYPE (buy or sell), POSITION_VOLUME (lots), POSITION_PRICE_OPEN (weighted average on netting accounts), POSITION_SL, POSITION_TP, POSITION_PROFIT (floating, deposit currency), POSITION_TIME.

A Pine strategy simulates one net position per script on the chart symbol. Its built-ins are recomputed after each bar's order processing, and the individual entries that make up the position are listed in strategy.opentrades (a count) with accessors such as strategy.opentrades.entry_price(i), .size(i), .entry_bar_index(i), .entry_time(i), .entry_id(i) and .profit(i).

The Pine Script equivalent

A trend EA with a break-even stop. It reads the position's type, entry, current stop, volume and profit; the Pine version reads the built-ins and keeps the stop in its own variable, because Pine has no way to read a stop back.

//@version=6
strategy("Trend with break-even stop", overlay = true, default_qty_type = strategy.fixed, default_qty_value = 10000)

len     = input.int(50, "Trend SMA")
stopPts = input.int(500, "Initial stop, ticks")
bePts   = input.int(300, "Move stop to entry after this many ticks")

sma = ta.sma(close, len)

// PositionSelect(_Symbol) is "is there a position"; the type is the sign of the size.
isLong = strategy.position_size > 0

// Pine cannot read back the stop it set (no POSITION_SL), so the script keeps it itself.
var float stopLv = na

if isLong
    entry  = strategy.position_avg_price             // POSITION_PRICE_OPEN (average if scaled in)
    volume = math.abs(strategy.position_size)        // POSITION_VOLUME, in units, not lots
    profit = strategy.openprofit                     // POSITION_PROFIT, account currency

    if na(stopLv)
        stopLv := entry - stopPts * syminfo.mintick
    if close - entry >= bePts * syminfo.mintick and stopLv < entry
        stopLv := entry                              // trade.PositionModify(_Symbol, entry, 0)
    strategy.exit("long exit", from_entry = "long", stop = stopLv)

    if close < sma
        strategy.close("long")

    if barstate.islast
        label.new(bar_index, high, str.format("Long {0} @ {1}, P/L {2,number,#.##}", volume, entry, profit))
else
    stopLv := na
    if close > sma
        strategy.entry("long", strategy.long)
        strategy.exit("long exit", from_entry = "long", stop = close - stopPts * syminfo.mintick)
#include <Trade\Trade.mqh>

input double InpLots   = 0.10;   // Lots
input int    InpLen    = 50;     // Trend SMA
input int    InpStopPts = 500;   // Initial stop, points
input int    InpBePts  = 300;    // Move stop to entry after this many points

CTrade   trade;
int      smaH;
datetime lastBar = 0;

int OnInit()
{
   smaH = iMA(_Symbol, _Period, InpLen, 0, MODE_SMA, PRICE_CLOSE);
   return(smaH == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED);
}

void OnTick()
{
   datetime t = iTime(_Symbol, _Period, 0);
   if(t == lastBar) return;
   lastBar = t;

   double sma[1];
   if(CopyBuffer(smaH, 0, 1, 1, sma) < 1) return;
   double lastClose = iClose(_Symbol, _Period, 1);

   if(PositionSelect(_Symbol))
   {
      long   type   = PositionGetInteger(POSITION_TYPE);
      double entry  = PositionGetDouble(POSITION_PRICE_OPEN);
      double sl     = PositionGetDouble(POSITION_SL);
      double volume = PositionGetDouble(POSITION_VOLUME);
      double profit = PositionGetDouble(POSITION_PROFIT);

      // Break-even: once the last close is InpBePts above entry, move the stop to entry.
      if(type == POSITION_TYPE_BUY && lastClose - entry >= InpBePts * _Point && sl < entry)
         trade.PositionModify(_Symbol, entry, 0.0);

      if(lastClose < sma[0])
         trade.PositionClose(_Symbol);

      Comment(StringFormat("Long %.2f lots @ %.5f, P/L %.2f", volume, entry, profit));
   }
   else if(lastClose > sma[0])
   {
      double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
      trade.Buy(InpLots, _Symbol, ask, ask - InpStopPts * _Point, 0.0);
   }
}
MQL5Pine
PositionSelect(_Symbol)strategy.position_size != 0
POSITION_TYPE == POSITION_TYPE_BUYstrategy.position_size > 0
POSITION_VOLUMEmath.abs(strategy.position_size) (units, not lots)
POSITION_PRICE_OPENstrategy.position_avg_price, or strategy.opentrades.entry_price(i) per entry
POSITION_PROFITstrategy.openprofit, or strategy.opentrades.profit(i)
POSITION_TIMEstrategy.opentrades.entry_time(0) (ms)
POSITION_SL, POSITION_TPNone; store the levels you pass to strategy.exit
POSITION_MAGIC, POSITION_TICKETNone; entries are identified by their string id
PositionsTotal()strategy.opentrades (entries, not positions)

Where the two differ

Timing. After trade.Buy returns, PositionSelect in the same OnTick already finds the position. In Pine the entry fills on the next bar, so strategy.position_size is still 0 for the rest of the bar on which strategy.entry was called. Logic that opens and immediately manages a position must be split across bars, or the exit issued together with the entry (as in the example).

Units. Volume is lots in MQL5 and units (contracts, shares, base currency) in Pine. Profit is in deposit currency in MQL5 and in the strategy's currency (default: the symbol's) in Pine.

No stop read-back. Pine keeps exit orders internally but offers no getter. Any MQL5 logic that compares the current price with POSITION_SL (trailing stops, break-even) needs a var holding the last level you issued.

One net position. Hedged long and short positions on one symbol, or positions belonging to other EAs (filtered by magic), do not exist in a Pine strategy. strategy.opentrades counts the open entries of this script's net position, which is not the same as PositionsTotal() on a hedging account.

Average price. With scaling in, both platforms report a volume-weighted average for a netting position, but Pine's per-entry prices remain available through strategy.opentrades.entry_price(i).

What the Stratlate converter emits

The MQL5 to Pine engine maps PositionsTotal() to strategy.opentrades and routes PositionSelect, PositionGetDouble and PositionGetInteger through the runtime helper f_pos_get, which selects the newest open trade and reads strategy.opentrades.size, .entry_price, .profit and .entry_time for volume, open price, profit and time, and close for POSITION_PRICE_CURRENT (PinePrelude). POSITION_SL and POSITION_TP return the levels the converted script last passed to its own order helper, since Pine keeps no readable bracket; magic is the script's own. All of these are reported as approximations (MQLW0501), and PositionGetString / PositionGetSymbol return syminfo.ticker. One limitation showed up in the program above: trade.PositionModify becomes f_order_modify, which re-issues strategy.exit("trade_exit", "trade", …), while entries made by the order helper are named "p1", "p2" and so on, so the break-even stop is not attached to the open position. Re-issue the exit with the entry's id by hand, as the example does, and backtest the result against the original before relying on it.

Pitfalls

  • Testing strategy.position_size right after strategy.entry to avoid a double entry. It is still 0 on that bar; use pyramiding = 0 (the default), which ignores a second entry in the same direction.
  • Comparing strategy.position_size with a lot value. A 0.1-lot position on EURUSD is 10000 units in Pine; checks like size == 0.1 are never true.
  • Reading strategy.openprofit as the result of one trade. It is the sum over all open entries of the net position; use strategy.opentrades.profit(i) per entry.
  • Forgetting to reset your stored stop when the position closes. A stale var level is then applied to the next trade on its first bar.
  • Porting a magic-number filter that loops over positions. With one script per chart there is nothing to filter; drop the loop rather than imitating it.

FAQ

How do I know whether the position is long or short?

By the sign of strategy.position_size: greater than 0 is long, less than 0 is short, 0 is flat. strategy.opentrades.size(i) is signed the same way for each open entry.

Can I read the stop-loss of the open position in Pine?

No. There is no getter for pending exit orders. Keep the level in a var float that you update whenever you call strategy.exit, and reset it to na when strategy.position_size returns to 0.

What is the equivalent of POSITION_PRICE_CURRENT?

close on the current bar. A strategy evaluates at bar close, so the mark-to-market price used by strategy.openprofit is the close as well.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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