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

时间:2020-10-07 14:13:31

标签: pine-script tradingview-api

我在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。 为什么会这样?

1 个答案:

答案 0 :(得分:2)

您的策略从多头变为空头,并且在首次交易后一直处于头寸位置。请参阅随附的屏幕截图。 enter image description here

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

示例:

// 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