IND-Range Box [Salar Kamjoo]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// © salarkamjoo
// $KMagician/*
//@version=5

indicator('IND-Range Box [Salar kamjoo]', 'Range Boxes [Salar kamjoo]', true, max_boxes_count = 500)

// Inputs ======================================================================
count_range       = input.int(20, "Number of Candles", minval=1, group = "Strategy Settings")
range_percentage  = input.float(0.2, "Range percentage", minval=0, step = 0.1, group = "Strategy Settings")
draw_range        = input.string('close', "Calculate basis", options=['close', 'high & low'], group = "Strategy Settings")
extend_length     = input.int(5, "Number of extended candles", minval=0, group = "Strategy Settings")

float source_high = na
float source_low  = na
switch 
    draw_range == 'close' =>  source_high := close, source_low  := close
    draw_range == 'high & low' =>  source_high := high, source_low  := low


// highest and lowest ==========================================================
hh = ta.highest(source_high, count_range)
ll = ta.lowest(source_low, count_range)

// hh and ll difference in % ===================================================
difference_percentage = (((hh - ll)/(hh + ll)) * 100) * 2

// is it in the range of user's desire =========================================
is_in_range = difference_percentage <= range_percentage

// Count Candles ===============================================================
var int candle_under = 0
var int candle_above = 0

if source_high <= hh and is_in_range
    candle_under += 1
if source_low >= ll and is_in_range
    candle_above += 1
    
if not is_in_range
    candle_under := 0
    candle_above := 0


// Draw range ==================================================================
_range = (candle_under == count_range) and (candle_above == count_range)
if _range
    box.new(bar_index[count_range + extend_length], hh, bar_index + extend_length, ll, bgcolor=color.new(color.fuchsia, 80), border_color=color.fuchsia)

plotshape(_range, 'Range box', shape.labeldown, location.abovebar, text = 'Range', textcolor=color.white, color=color.fuchsia, size= size.tiny)


// Alerts ======================================================================
if _range
    message = 'Range Box\n' + syminfo.ticker + '\n' + timeframe.period
    alert(message, alert.freq_once_per_bar_close)