Как построить массив или коллекцию - PullRequest
1 голос
/ 24 января 2020

Я хотел бы собрать коллекцию из нескольких последних максимумов и получить доступ ко всем из них, как я мог бы в массиве. Как я могу это сделать? Мой код выглядит следующим образом:

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

Теперь я пытаюсь это сделать:

x := lastHigh[3]

... но тогда x является только последним значением LastHigh (как это будет lastHigh [1] ). Так что lastHigh - это просто «плоская» переменная, верно? Как я могу собрать более одного последнего максимума?

Ответы [ 2 ]

2 голосов
/ 25 января 2020

Я придумал следующий подход:

//@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 последних локальных максимума и можете перебирать их. Надеюсь, я правильно понял ваш вопрос.

1 голос
/ 24 января 2020

Если ваша функция 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)
...