Crab Range Finder
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LMJ0011trader

//@version=5
indicator("Crab Range Finder", overlay=true)
prev_bars_cnt = input(5, "include the last X bars for this range")

high_vals = array.new_float(prev_bars_cnt)
for i = 0 to prev_bars_cnt
	array.push(high_vals, high[i])

low_vals = array.new_float(prev_bars_cnt)
for i = 0 to prev_bars_cnt
	array.push(low_vals, low[i])

high_avg = math.round(array.avg(high_vals), 2)

low_avg = math.round(array.avg(low_vals), 2)

median = math.round((high_avg + low_avg) / 2, 2)

var label highlabel = na
var label medianlabel = na
var label lowlabel = na

// so labels don't duplicated when new bar shows
// ref: https://stackoverflow.com/a/58703622/2445763
label.delete(highlabel)
label.delete(medianlabel)
label.delete(lowlabel)


plot(barstate.islast ? high_avg : na, title='top', color=color.green, style=plot.style_line, trackprice=true, linewidth=2)
plot(barstate.islast ? median : na, title='median', color=color.orange, style=plot.style_line, trackprice=true, linewidth=2)
plot(barstate.islast ? low_avg : na, title='bottom', color=color.yellow, style=plot.style_line, trackprice=true, linewidth=2)


if barstate.islast
    highlabel := label.new(bar_index + 5, high_avg, text=str.tostring(high_avg), color = color.green, textcolor = color.white, style=label.style_label_down)
	medianlabel := label.new(bar_index + 5, median, text=str.tostring(median), color = color.orange, textcolor = color.white, style=label.style_label_up)
	lowlabel := label.new(bar_index + 5, low_avg, text=str.tostring(low_avg), color = color.yellow, textcolor = color.black, style=label.style_label_up)
	
