TradingView Pinescript,为什么三元运算符在此绘图示例中不起作用?

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

我在 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)
    
...

我想根据头寸规模是否为 0 在值 0 或 1 处绘制一条线。

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

然而,绘制 x 的结果是一条仅在值 1 处的线。在图表上 它清楚地表明在某些时候没有任何职位是开放的。因此 变量 position_size 在某些时候应该是 0,但它似乎只有 1。 为什么会这样?

您的策略从 long 转变为 short 并在第一笔交易后始终保持头寸。请参阅随附的屏幕截图。

您应该在反向信号出现之前使用strategy.exitstrategy.close函数退出仓位。

示例:

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