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

Mar*_*ark 3 pine-script

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

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

伪代码:

If currentbar >= upperthreshold
   indicatorvalue = value1
Elseif currentbar <= lowerthreshold
   indicatorvalue = value2
Else
   indicatorvalue = indicatorvalue[currentbar-1]
Run Code Online (Sandbox Code Playgroud)

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

Bar*_*kut 6

当您想引用以前的值时,可以使用历史引用运算符 []

然后,您需要做的就是检查条件并在想要为先前定义的变量重新分配值时使用[]with运算符。:=

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

//@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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 这就是 [] 运算符的工作方式。例如,close[0] 表示当前收盘价。close[1] 表示一柱之前的收盘价。close[2] 表示两根柱之前的收盘价。您阅读了我的答案中的链接吗? (2认同)