I am attempting to create a TradingView study that draws a line from a crossunder on the current bar to a crossunder on a previous bar, where the previous bar is less than a set maximum number of bars back.
I only want to draw lines with negative slopes (i.e. the previous crossunder happens at a higher value), and I also don't want multiple lines with the same starting point (no overlapping lines).
I am able to draw the lines correctly, but I don't know how to delete lines when they overlap (have the same starting point).
When drawing a new line which will overlap an older one, how do I get a reference to the older line so that I can delete it?
The following do not seem possible in pine script:
- Iterating over previous values in line series to inspect their x,y values
- Accessing line series by an index like bar_index
- Accessing previous line value without also creating a new line
//@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)