Ranging Market Detector [AstrideUnicorn]
// 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/
// All rights reserved.
// (c) AstrideUnicorn

//@version=5
indicator('Ranging Market Detector', shorttitle='RMD')

// input paraneters
treshold_level = input.float(title='treshold', defval=-0.1, minval=-0.1, maxval=0.5, step=0.01)

//Kalman filter calculation

p = ohlc4

value1 = 0.0
value2 = 0.0
klmf = 0.0

value1 := 0.2 * (p - p[1]) + 0.8 * nz(value1[1])
value2 := 0.1 * (high - low) + 0.8 * nz(value2[1])
lambda = math.abs(value1 / value2)

alpha = (-lambda * lambda + math.sqrt(lambda * lambda * lambda * lambda + 16 * lambda * lambda)) / 8
klmf := alpha * p + (1 - alpha) * nz(klmf[1])


// Calculateing the absolute value of the Kalman filter curve slope
klmf_diff = math.abs(klmf - klmf[1])

// Long term average of the Kalman filter slope
av_klmf_diff = 1.0 * ta.ema(klmf_diff, 200)

// The Kalman filter slope minus the average slope (Decline from the average slope)
// This slope decline is divided by the average slope value to normalize it
normalized_slope_decline = (klmf_diff - av_klmf_diff) / av_klmf_diff

// Condition that defines the trend regime
// Slope declined from the average by not less than the given treshold value
trend_condition = normalized_slope_decline >= treshold_level


// Plot normalized slope decline as histogram plot
plot(normalized_slope_decline, style=plot.style_histogram, color=color.new(color.blue, 0), linewidth=3)

// Plot treshold level line
plot(treshold_level, color=color.new(color.red, 0))

// If trend contition is satisfied color the backfround in blue (trending market regime highlighting), 
// if not color the background in red (ranging market regime highlighting)
bgcol = barstate.isconfirmed ? trend_condition ? color.new(color.blue, 70) : color.new(color.red, 70) : na
bgcolor(bgcol, transp=90)

