如何计算自“strategy.entry”以来的柱数

Orz*_*rzo 2 pine-script

我刚刚开始使用 PineScript 进行编码,经过几次尝试,我想寻求帮助。

我试图计算与最后一次多头头寸入场相比发生了多少根柱线。这个问题(或类似的问题)已被问过几次,但我发现barssince()并不能解决问题。简单地说,它根本不起作用。

我想测试的策略如下:如果价格比之前的高点下跌 2.5%,我想平掉多头头寸。前一个高点不需要在固定长度的窗口(例如,最后 10 个柱左右)中进行评估,但需要从完成多头入场的柱开始进行评估。

我尝试平掉多头头寸(以其 ID“买入”开仓),如下所示:

npastdays=barssince(strategy.position_size > 0)
    
prevHigh=highest(close, npastdays)
if (close < 0.975*prevHigh)
    strategy.close("buy")
Run Code Online (Sandbox Code Playgroud)

我什至尝试了其他方法,例如,在开仓时将“op”变量设置为非零值,而不是使用“change(op > 0)”或类似的“crossover(op, value)”。无论哪种方式,“npastdays”变量都不会被计算,它保持未定义状态(nd)。

编辑#1:当开多头仓位时,我再次尝试设置 op:=6.5 (任何数字都可以,或者布尔值),然后:

npastdays=barssince(op==6.5)
if (npastdays!=0)   // else, I just opened a long position
    prevHigh=highest(close, npastdays)
    if (close < 0.975*prevHigh)
        strategy.close("buy")
Run Code Online (Sandbox Code Playgroud)

我得到了一个不同的错误,“Pine无法确定系列的引用长度。尝试在研究或策略函数中使用max_bars_back。”。仍然没有解决。

Edit #2: I tried, without success, to use the built-in "bar_index" with the instrucion "posLong := bar_index" when a long entry is done. However, the code works only with a fixed number of bars: even if I try to catch a negative nPastDays value (its first value appears to be -1096 but posLong should be > posLong[1]...)

// Determine trail stop loss prices
float longStopPrice = 0.0
int nPastDays = 4
float prevHigh = 0.0
longStopPrice := if (strategy.position_size > 0)
    nPastDays := posLong - posLong[1]
    if nPastDays > 0
        prevHigh := highest(close, nPastDays)
    else
        prevHigh := highest(close, 4)
    
    prevHigh * 0.975
    
//    stopValue = close * (1 - longTrailPerc)
//    max(stopValue, longStopPrice[1])
else
    0

// Submit exit orders for trail stop loss price
if (strategy.position_size > 0)
    strategy.exit(id="buy", stop=longStopPrice)
Run Code Online (Sandbox Code Playgroud)

The interpreter gives an error about a negative nPastDays value or gives an error while suggesting to use max_bars_back. But I already set "max_bars_back=50" in the strategy declaration. Still unsolved.

fed*_*der 5

使用barsince有一个快捷方式可以实现您想要的功能。

ta.barssince(strategy.position_size == 0)
Run Code Online (Sandbox Code Playgroud)