Смотрите комментарии в коде. Сделали линии толще, чтобы их было легче увидеть, и добавили отладочные графики в конце скрипта.
Основная идея 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)