【问题标题】: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 中,如何根据自定义指标中当前柱的条件将前一根柱的值分配给当前柱?
【发布时间】:2019-10-19 11:31:28
【问题描述】:

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

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

伪代码:

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

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

【问题讨论】:

    标签: pine-script


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 完美,谢谢。我不太明白的一件事:在“color_value := nz(color_value[1])”行中,我希望括号中的“n-1”引用要替换的当前条之前的条中的值NaN(以及确保 n>0 的必要检查)......为什么只有“1”?再次感谢!
    • 这就是 [] 运算符的工作方式。例如,close[0] 表示当前收盘价。 close[1] 表示前一根柱线的收盘价。 close[2] 表示两根柱线之前的收盘价。您是否阅读了我答案中的链接?
    • 发表评论后才看到链接。 :\ 感谢您的跟进!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多