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

//@version=5
indicator("Range Detection", "Range", overlay = true, max_lines_count = 500)
minimum_lemgth    = input.int(defval = 10, title = "Minimum candles to show range")

var candleLow     = low
var candleHigh    = high
var candleOpen    = open
var candleClose   = close
var insideCandles = 1
var label counterLabel = na

if high > candleHigh and close < candleHigh
    candleHigh := high
if low < candleLow and close > candleLow
    candleLow := low

breakoutCandle = close > candleHigh or close < candleLow
if breakoutCandle and barstate.isconfirmed
    candleLow     := low
    candleHigh    := high
    candleOpen    := open
    candleClose   := close
    insideCandles := 1
if close <= candleHigh and close >= candleLow
    insideCandles := insideCandles + 1
    if insideCandles >= (minimum_lemgth+1)
        counterLabel := label.new(bar_index, high, "Length: " +str.tostring(insideCandles - 1), yloc = yloc.abovebar, size = size.large, textcolor = color.white)
        label.delete(counterLabel[1])
    
break_index = ta.valuewhen(breakoutCandle, bar_index, 0)

upperLine = insideCandles >= (minimum_lemgth+1) ? line.new(break_index, candleHigh, bar_index, candleHigh, color = candleOpen < candleClose ? color.green : color.red, width = 2) : na 
lowerLine = insideCandles >= (minimum_lemgth+1) ? line.new(break_index, candleLow, bar_index, candleLow, color = candleOpen < candleClose ? color.green : color.red, width = 2) : na 

if not breakoutCandle
    line.delete(lowerLine[1])
    line.delete(upperLine[1])

linefill.new(upperLine, lowerLine, color = candleOpen < candleClose ? color.new(color.green, 90) : color.new(color.red, 90))

bullish_break = close > candleHigh[1] and barstate.isconfirmed and insideCandles[1] >= (minimum_lemgth+1)
bearish_break = close < candleLow[1] and barstate.isconfirmed and insideCandles[1] >= (minimum_lemgth+1)

alertcondition(bullish_break, "Bullish Breakout", "Bullish Breakout")
alertcondition(bearish_break, "Bearish Breakout", "Bearish Breakout")
