Robust Bollinger Bands with Trend Strength
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © federalTacos5392b
//@version=5
indicator("Robust Bollinger Bands with Trend Strength", shorttitle="RBB", overlay=true) 
// Input for the number of periods
length = input(14, title="Length")
Trend_strength_length =input(14, title = "Trend Continuation length")
rank_correlation_threshold =input (0.7, title= "Trend strength threshold")
src1=input(hlc3, title= "Rank Correlation Price source")

// Input for the multiplier for IQR
multiplier = input(1.0, title="Multiplier") 

// Choose the source (hlc3 or Vwma)
useHLC3 = input.bool(true, title="Use HLC3")
src = useHLC3 ? hlc3 : ta.vwma(hlc3, 3)

// Calculate median and IQR
medianValue = ta.median(src, length)
percentile_high = ta.percentile_nearest_rank(high, length, 75)
percentile_low = ta.percentile_nearest_rank(low, length, 25)
IQR = (percentile_high - percentile_low)
iqrValue = ta.ema(IQR, length)

// Calculate upper and lower bands
upperBand = medianValue + multiplier * iqrValue
lowerBand = medianValue - multiplier * iqrValue

// Custom ranking function
var srcRank = 0.0
if bar_index > length
    srcRank := src1 > src1[length] ? srcRank + 1 : src1 < src1[length] ? srcRank - 1 : srcRank


// Calculate robust rank-based correlation coefficient based on bar count and src
robust_rank_corr = ta.correlation(srcRank, bar_index, Trend_strength_length)

// Define conditions for filling
fillUpTrend = robust_rank_corr > rank_correlation_threshold
fillDownTrend = robust_rank_corr < -1*rank_correlation_threshold
fillNeutral = -1*rank_correlation_threshold < robust_rank_corr and robust_rank_corr < 1*rank_correlation_threshold

// Define fill colors
upTrendColor = color.rgb(202, 241, 202)
downTrendColor = color.rgb(249, 210, 210)
neutralColor = color.rgb(241, 231, 158)

// Determine the color based on midline direction
color_change = medianValue > medianValue[1] ? color.green : (medianValue < medianValue[1] ? color.red : color.blue)

// Plot the Bollinger Bands
plot_u = plot(upperBand, color=color.blue, title="Upper Bollinger Band")
plot_l = plot(lowerBand, color=color.red, title="Lower Bollinger Band")
plot_m = plot(medianValue, color=color_change, title="Median Bollinger Band", linewidth=3)

// Fill based on conditions
fill(plot_u, plot_l, color=fillUpTrend ? upTrendColor : fillDownTrend ? downTrendColor : neutralColor, title="Trend Fill")
// Display the robust_rank_corr value on the chart
