Как условно удалить строку в Pine Script - PullRequest
3 голосов
/ 24 января 2020

Я пытаюсь создать исследование TradingView, которое выводит aws линию от перекрестия на текущем баре до перекрестия на предыдущем баре, где предыдущий бар меньше установленного максимального количества баров назад.

Я хочу рисовать линии только с отрицательным уклоном (т. Е. Предыдущий перекрестный переход встречается с более высоким значением), и я также не хочу, чтобы несколько линий имели одинаковую начальную точку (без перекрывающихся линий).

Я могу рисовать линии правильно, но я не знаю, как удалять линии, когда они перекрываются (имеют одинаковую начальную точку).

При рисовании новой линии, которая будет перекрывать более старую, как получить ссылку на более старую строку, чтобы я мог удалить ее?

Следующее не представляется возможным в сценарии Pine :

  • Итерация по предыдущим значениям в ряду строк для проверки их значений x, y
  • Доступ к ряду строк по индексу типа bar_index
  • Доступ к предыдущему значению строки без создание новой строки
//@version=4
study(title='MACD trend')
src = input(close)
fast = input(12)
slow = input(26)
smooth = input(9)
numBarsBack = input(50)

fast_ma = wma(src, fast)
slow_ma = wma(src, slow)
macd = fast_ma-slow_ma
signal = wma(macd, smooth)
hist = macd - signal

if (crossunder(macd, signal))
// cross under happened on previous bar
    for i = 1 to numBarsBack
    // inspect previous bars up to 'numBarsBack'
        if (crossunder(macd,signal)[i])
            if (macd - macd[i] < 0)
            // located a previous cross under with a higher macd value
                l = line.new(bar_index[1], macd[1], bar_index[i+1], macd[i+1], width=1, color=color.red)
                // drew line from previous cross under to current cross under, 
                // offset x's by 1 bar since crossunder returns true based on previous bar's cross under
                for k = 1 to i
                // inspect previous bars up to the starting point of drawn line
                    if (crossunder(macd, signal)[k] and macd > macd[k])
                    // if the previous cross under value is less than the current one
                        line.delete(l[1])
                        // not sure what the 1 here indexes???

plot(title='MACD', series=macd,transp=0,linewidth=2, color=color.yellow)
plot(title='SIGNAL', series=signal,transp=0,linewidth=2, color=color.red)

1 Ответ

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

Смотрите комментарии в коде. Сделали линии толще, чтобы их было легче увидеть, и добавили отладочные графики в конце скрипта.

Основная идея c заключается в распространении идентификатора строки ранее созданной строки с использованием очень удобного Ключевое слово var при инициализации переменной l. Таким образом, перед созданием новой линии мы извлекаем y2, использованный для создания предыдущей строки, чтобы эту линию можно было удалить, если ее y2 совпадает с той, которую мы собираемся создать (поэтому было получено из того же пика).

Обнаружение пиков перекрестия использует встроенные модули Pine вместо for l oop. Код будет работать быстрее таким образом.

//@version=4
study(title='MACD trend2')
src = input(close)
fast = input(12)
slow = input(26)
smooth = input(9)
numBarsBack = input(50)

fast_ma = wma(src, fast)
slow_ma = wma(src, slow)
macd = fast_ma-slow_ma
signal = wma(macd, smooth)
hist = macd - signal

xDn = crossunder(macd, signal)
// Get macd at at highest xDn in last numBarsBack bars. If no Xdn found, set value to -10e10.
highestXDnMacd = highest(xDn ? macd : -10e10, numBarsBack)
// Get offset to that point.
highestXDnOffset = - highestbars(xDn ? macd : -10e10, numBarsBack)

// Detect if previous xDn meets all criteria.
lastXDnWasHigher = xDn and macd < highestXDnMacd
// Make l persistent, so that it always contains the line id of the last line created.
var line l = na
if lastXDnWasHigher
    // Retrieve y2 used to draw previous line.
    if line.get_y2(l) == highestXDnMacd
        // Last line drawn used same y2 as the one we are about to use; delete it.
        // No more than one line back can have same peak since previous ones have already been deleted.
        line.delete(l)
    // The line id we assign to l here will persist through future bars,
    // which is what will allow us to delete the corresponding line using the line.delete() above, if needed.
    l := line.new(bar_index[1], macd[1], bar_index - highestXDnOffset, macd[highestXDnOffset], width=3, color=color.black)

plot(title='MACD', series=macd,transp=0,linewidth=2, color=color.yellow)
plot(title='SIGNAL', series=signal,transp=0,linewidth=2, color=color.red)

// Debugging.
plot(highestXDnMacd != -10e10 ? highestXDnMacd : na, "highestXDnMacd", color.silver, 2, plot.style_circles)
plotchar(highestXDnOffset, "highestXDnOffset", "", location.top)    // For Data Window display.
bgcolor(lastXDnWasHigher ? color.green : xDn ? color.silver : na, 60)

enter image description here

...