Box Samples (Price Ranges)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Azzrael

//@version=5
indicator("Box Samples (Price Ranges) for Azzrael Code YT", overlay=true, max_boxes_count=500)


period = input.int(title="Период", defval=50, minval=5)

var float[] ranges = array.new_float(0)

max = ta.highest(high, period)
min = ta.lowest(low, period)
rng =  (max - min)
avg =  rng/2 + min


var lbox = box.new(
 0,0,0,0, 
 bgcolor=na,
 border_style=line.style_dotted,
 border_color=color.new(color.blue, 50),
 text_color=color.new(color.white, 70)
 )

if bar_index % period == 0
    array.push(ranges, rng)
    med_range = array.median(ranges)
    is_grow = low[period] < avg and high > avg
    
    box.new(
     bar_index[period], min, 
     bar_index, max,  
     text=str.tostring(min, ".##") + "\n" + str.tostring(rng, ".##") ,
     text_halign=text.align_right,
     text_valign= is_grow ? text.align_bottom : text.align_top,
     text_size=size.small,
     text_color=color.white,
     border_color=is_grow ? color.green : color.red,
     border_width=(rng > med_range*1.5) ? 5 : 1,
     bgcolor=na
     )
else if barstate.isrealtime or barstate.islast
    box.set_lefttop(lbox, bar_index[period], min)
    box.set_rightbottom(lbox, bar_index, max)
    box.set_text(lbox, str.tostring(rng, ".##"))
