Bars Above/Below Donchian Channel [ScalpTradr]
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ©ScalpTradr

//@version=5
indicator("Bars Above/Below Donchian Channel [ScalpTradr]", shorttitle="ST AB Donchian", overlay=true)

colorPriceBars = input(false, "Color price bars")
length = input(20, title="Length of Donchian Channel")

// Calculate Donchian Channel
upper_channel = ta.highest(high, length)
lower_channel = ta.lowest(low, length)
basis = (upper_channel + lower_channel) / 2

// Count Bars above or below
var int aboveCount = 0
var int belowCount = 0

// Label IDs
var label aboveLabel = na
var label belowLabel = na

if close > basis
    if na(aboveCount) or close[1] <= basis[1]
        aboveCount := 1
    else
        aboveCount := aboveCount + 1
    
    if na(aboveLabel)
        aboveLabel := label.new(bar_index, high, text = str.tostring(aboveCount), color=color.green, textcolor=color.white, style=label.style_label_down, yloc = yloc.price)
    else
        label.set_xy(aboveLabel, bar_index, upper_channel)
        label.set_text(aboveLabel, str.tostring(aboveCount))
else
    aboveCount := na

if close < basis
    if na(belowCount) or close[1] >= basis[1]
        belowCount := 1
    else
        belowCount := belowCount + 1
    
    if na(belowLabel)
        belowLabel := label.new(bar_index, low, text = str.tostring(belowCount), color=color.red, textcolor=color.white, style=label.style_label_up, yloc = yloc.price)
    else
        label.set_xy(belowLabel, bar_index, lower_channel)
        label.set_text(belowLabel, str.tostring(belowCount))
else
    belowCount := na

plot(upper_channel, color=color.blue, title='Bollinger bands upper')
plot(lower_channel, color=color.blue, title='Bollinger bands lower')
plot(basis, color=color.orange, title='Bollinger bands basis')

// If option enabled color the price bars red or green depening on if price closes below or above basis
barcolor(colorPriceBars ? close < basis ? color.red : color.green : na)
