如何从 pine 脚本中的函数更改全局变量?

Mij*_*man 2 pine-script

我正在尝试编写一个脚本来获得 9 个级别的江恩平方。我已经完成了另一种语言,但无法理解这里的松树脚本,它说无法修改函数中的全局变量。有什么解决方案可以获取这里的值是我的脚本

//@version=4
study(title="Volume-weighted average example", max_bars_back=5000, overlay=true)
timeDiff = time - time[4]

// Translate that time period into seconds
diffSeconds = timeDiff / 1000

// Output calculated time difference
//plot(series=diffSeconds)
var ln = 0
var wdvaltrg = 0.0

WdGann(price) =>
    for i = 1 to 8
        wdvaltrg := (ln+(1/i))*(ln+(1/i))
        if wdvaltrg >= price
            break
    if wdvaltrg < price
        ln := ln+1
        WdGann(price)

var vwap0935 = 0.0
v = vwap
if hour == 9 and minute == 35
    vwap0935 := v



plot(vwap0935)
Run Code Online (Sandbox Code Playgroud)

Ada*_*ner 7

自 2020 年 9 月 10 日起,松木阵列可用。使用它,您可以将在函数中创建的值存储在全局范围内。

这是有效的,因为写入数组元素不会改变实际数组变量的引用。因此,您只需使用全局数组并修改其内容,就像您在函数之外所做的那样。

数组在松树脚本中打开了很多可能性。

一个简单的例子:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wallneradam
//@version=4
study("Global variables", overlay=false)

// Declare constants to access global variables
IDX_STOCH = 0
IDX_RSI = 1

// Initialize an empty array to store variables
global = array.new_float(2)

// This is the modify the array
calculate(period) =>
    v_stoch = stoch(close, high, low, period)
    v_rsi = rsi(close, period)
    array.set(global, IDX_STOCH, v_stoch)
    array.set(global, IDX_RSI, v_rsi)
     
// Call the function any times you want
calculate(14)
// Plot the results
plot(array.get(global, IDX_STOCH), color=color.red)
plot(array.get(global, IDX_RSI), color=color.yellow)
// Call the function any times you want
calculate(14 * 5)
// Plot the results
plot(array.get(global, IDX_STOCH), color=color.maroon)
plot(array.get(global, IDX_RSI), color=color.olive)
Run Code Online (Sandbox Code Playgroud)

  • @xh3b4sd 这取决于您想要实现的目标。在上面的示例中,您想要在每个时间步中计算一些指标,因此“var”在这里并不合适。不过,如果你想跨时间步存储变量,那么可以使用 var 。但问题是关于修改函数内部的全局变量。这种使用数组的方法适用于普通(不带 var)和持久(带 var)数组变量。 (2认同)