PineScript - 全局范围变量不是在函数内部获得的

PineScript - global scope variables are not obtained inside function

例如下面的脚本:

//@version=4
study("sample")
func(val)=>
    label l1= label.new(bar_index, high, text=tostring(val[2]), style=label.style_circle) 
trigger_condition = barstate.islast
if(barstate.islast)
    func(close)

结果总是显示 nan。这是什么原因?将 xyz_[2] 更改为 xyz[2] 都不起作用。

您的问题不是全局变量在函数范围内的可见性,因为函数使用的值是作为参数传递给它的。

您的代码没有像您预期的那样工作,因为您只在数据集的最后一个柱上调用该函数,并且由于这是第一次调用,因此没有 val 的历史值可供参考您创建标签。

解决方案是在每个柱上执行函​​数。这段代码展示了两种等效的方法,第二种方法效率最高。查看代码中的注释:

//@version=4
study("sample")

func1(val)=>
    // Create label on first bar.
    var label l1 = label.new(bar_index, high, "", style=label.style_circle)
    // Redefine label's position and text on each bar.
    label.set_text(l1, tostring(val[2]))
    label.set_xy(l1, bar_index, high)

func2(val)=>
    // Track history of the values on every bar but do nothing else.
    _v = val[2]
    if barstate.islast
        // Create label on last bar only.
        l1 = label.new(bar_index, high, tostring(_v), style=label.style_circle)

func1(close)

[编辑:2020.09.15 15:26 — LucF]
第三个等价物的例子说明了要回答的评论中的评论:

func3(_val)=>
    if barstate.islast
        // Create label on last bar only.
        l1 = label.new(bar_index, high, tostring(_val), style=label.style_circle)

func3(close[2])

此方法也有效,因为历史缓冲区的当前默认值 250 可确保在偏移量 2 处存在关闭值:

if barstate.islast
    label.new(bar_index, high, tostring(close[2]), style=label.style_circle)