Auto S/R v2
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © GM_Trades

//@version=5
indicator("Auto S/R v2", overlay = true)
supportresistance_tf = input.timeframe(defval='', title='S/R Timeframe', inline='1', group='S/R Settings')
sr_closeness = input.float(defval=5.00, step=0.25, minval=0, maxval=10, title='S/R Spacer', inline='2', group='S/R Settings')
sr_lines = input.int(20, title = 'Number of S/R Lines', inline = '3', minval = 5, maxval =50, group = 'S/R Settings')
show_label = input.bool(true, title = "Show S/R Line Price Labels", inline = '4', group = 'S/R Settings')
sr_color = input.color(color.new(color.gray,0), title='S/R Color', inline='5', group='S/R Settings')

getLineValue(srcHigh, srcLow, strength) =>
    pivotLow = ta.pivotlow(srcLow, strength, strength)
    levelLow = ta.valuewhen(pivotLow, srcLow[strength], 1)
    atr_value = ta.atr(200) * sr_closeness
    [pivotLow, levelLow,atr_value ]
    
[is_bull_fractal, low_level, atr_value] = request.security(syminfo.tickerid, supportresistance_tf, getLineValue(high, low, 5))

//Delete all Lines and labels
allLines = line.all
alllabels = label.all
if barstate.islast and array.size(allLines) > 0
	for i = 0 to array.size(allLines) - 1
		line.delete(array.get(allLines, i))
		
if barstate.islast and array.size(alllabels) > 0
	for i = 0 to array.size(alllabels) - 1
		label.delete(array.get(alllabels, i))

drawSR(key_levels, atr_value, line_color) =>
    for i = 0 to sr_lines/2 by 1
        support_level = key_levels - (atr_value * i)
        line s_line = line.new(x1=bar_index[1], x2=bar_index, y1=support_level, y2=support_level, xloc=xloc.bar_index, width=6, color=color.new(line_color,88), extend=extend.both)
        resistance_level = key_levels + (atr_value * (i+1))
        line r_line = line.new(x1=bar_index[1], x2=bar_index, y1=resistance_level, y2=resistance_level, xloc=xloc.bar_index, width=6, color=color.new(line_color,88), extend=extend.both)
        if show_label
            label s_label = label.new(x=bar_index + 70, y=support_level, xloc=xloc.bar_index, yloc=yloc.price, text=str.tostring(support_level, format.mintick), textcolor=color.new(line_color,0) ,style=label.style_none, color=color.white, textalign=text.align_right, size=size.normal)
            label r_label = label.new(x=bar_index + 70, y=resistance_level, xloc=xloc.bar_index, yloc=yloc.price, text=str.tostring(resistance_level, format.mintick), textcolor=color.new(line_color,0) ,style=label.style_none, color=color.white, textalign=text.align_right, size=size.normal)  
        
drawSR(low_level, atr_value, sr_color)