在 Pine-script 中,如何根据自定义指标中当前柱的条件将上一个柱的值分配给当前柱?

In Pine-script, how to assign the value of the previous bar to the current bar based on a condition of the current bar in a custom indicator?

在 Pine-script 中,我需要根据自定义指标中当前柱的条件将上一个柱的值分配给当前柱。

我尝试了多种编码方法,导致内部服务器错误或编译错误。

伪代码:

If currentbar >= upperthreshold
   indicatorvalue = value1
Elseif currentbar <= lowerthreshold
   indicatorvalue = value2
Else
   indicatorvalue = indicatorvalue[currentbar-1]

预期结果是一个在提供的伪代码中的 2 个值之间交替的指标图,因为落在阈值之间的每个柱的值都设置为前一个柱的值。

当你想引用以前的值时,你可以使用 History Referencing Operator [].

然后您需要做的就是检查您的条件,并在您想要 re-assign 一个先前定义的变量的值时使用 []:= 运算符。

这是一个基于你的伪代码的小例子。背景颜色会根据您的条件而变化。我还绘制了两条水平线以查看 upper/lower 阈值。这样你可以看到当价格在上限和下限之间时背景颜色保持不变。

//@version=3
study("My Script", overlay=true)

upper_threshold = input(title="Upper Threshold", type=integer, defval=7000)
lower_threshold = input(title="Lower Threshold", type=integer, defval=6000)

color_value = gray

if (close >= upper_threshold)
    color_value := green
else 
    if (close <= lower_threshold)
        color_value := red
    else
        color_value := nz(color_value[1])

bgcolor(color=color_value, transp=70)

hline(price=upper_threshold, title="Upper Line", color=olive, linestyle=dashed, linewidth=2)
hline(price=lower_threshold, title="Lower Line", color=orange, linestyle=dashed, linewidth=2)