TradingView Pinescript, why isn't the ternary operator working in this plot example?

568 views Asked by At

I have a very simple strategy in pinescript.

//@version=4
strategy("My Strategy", overlay=true)

longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)
    
...

And I'd like to plot a line at value 0 or 1 depending on whether the position size is 0 or not.

...
x = strategy.position_size == 0 ? 0 : 1
plot(x)

However the result of plotting x is a line that is only at value 1. On the chart it's clearly displaying that at some points no positions are open. Therefore the variable position_size should be 0 at certain points but it appears its only 1. Why is this the case?

1

There are 1 answers

1
e2e4 On BEST ANSWER

Your strategy flip from long to short and constantly is in a position after the first trade. See the attached screenshot. enter image description here

You should use strategy.exit or strategy.close functions to exit the position before the opposite direction signal occurs.

Example:

// Exit long after 2 candles from the entry
exitLong = nz(longCondition[2])
if exitLong
    strategy.close("My Long Entry Id", exitLong)

enter image description here