如何构建数组或集合

How to build an array or collection

我想构建几个最后高点的集合,并像在数组中一样访问所有这些高点。 我怎么做?我的代码如下所示:

var float lastHigh = 0
if (highfound)
    lastHigh := high

现在我试试这个:

x := lastHigh[3]

... 但 x 只是最后的 lastHigh 值(就像 lastHigh[1])。 所以 lastHigh 只是一个 "flat" 变量,对吧?我怎样才能收集到不止一个最后高点?

假设您的 highfound 函数(未在原始问题中演示)结果为假或真,您的代码应该通过从 x 变量中删除 : 来工作:

x = lastHigh[3]

以下对我来说效果很好:

//@version=4
study("My Script")

var float lastHigh = 0
if (close>open)
    lastHigh := high

x = lastHigh[3]
plot(x, color=color.red)

我想到了下一个方法:

//@version=4
study("Three last highs", overlay=true)

// here goes the logic for finding the high
// NOTE: if you are updating this function,
// then it should return either new value for the array or n/a. 
// Because the non-n/a value will be added to the array and the oldest removed
getNewHighOrNa() =>
    pivothigh(high, 3, 3)

newHigh = getNewHighOrNa()




// ======= Array lifecicle =========
ARRAY_LENGTH = 5

arrayCell = label(na)
if bar_index < ARRAY_LENGTH
    arrayCell := label.new(0, 0)
    label.set_y(arrayCell, 0)
else
    if na(newHigh)
        val = label.get_y(arrayCell[1])
        for i = 2 to ARRAY_LENGTH
            v = label.get_y(arrayCell[i])
            label.set_y(arrayCell[i-1], v)
        arrayCell := arrayCell[ARRAY_LENGTH]
        label.set_y(arrayCell, val)
    else
        arrayCell := arrayCell[ARRAY_LENGTH]
        label.set_y(arrayCell, newHigh)
// ==================================

// Array getter by index. Note, that numeration is right to left
// so 0 is the last bar (current) and 1 it's a left to current bar
get(index) => label.get_y(arrayCell[index])

// example of using of the array for calculation average of all elements of the array
mean() =>
    sum = 0.0
    for i = 0 to ARRAY_LENGTH - 1
        sum := sum + get(i) / ARRAY_LENGTH
    sum
plot(mean(), title="Mean", color=color.green)

// example of finding of max value in the array
max_high() =>
    max = get(0)
    for i = 1 to ARRAY_LENGTH - 1
        v = get(i)
        if v > max
            max := v
    max
plot(max_high(), title="MAX", color=color.red)


// the rest is just checking that the code works:
plot(get(0))
plot(get(1))
plot(get(2))
plot(get(3))
plot(get(4))

// mark the bars where we found new highs
plotshape(not na(newHigh), style=shape.flag)

我试图让它变得更容易,但由于 pine 的限制,没有成功。但是这段代码有效,你得到了 3 个最后的局部高点并且可以迭代它们。希望我答对了你的问题。