Bollinger RSI Bands
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tseddik

//@version=5
indicator(title="Bollinger RSI Bands", shorttitle="BRSIB", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

// RSI Settings
rsiLength = input.int(14, minval=1, title="RSI Length")
rsiSource = input.source(close, "Source")
candlesMAType = input.string("EMA", title="Candles MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
candleLength = input.int(5, minval=1, title="Candle Length")
candleMALength = input.int(5, minval=1, title="Candle MA Length")
bollingerMAType = input.string("SMA", title="Bollinger MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
bollingerMALength = input.int(14, title="MA Length")
bbStdDev = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev")

RSIma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "WMA" => ta.wma(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "VWMA" => ta.vwma(source, length)

bbma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "WMA" => ta.wma(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "VWMA" => ta.vwma(source, length)

rsio = ta.rsi(open, candleLength)
rsih = ta.rsi(high, candleLength)
rsil = ta.rsi(low, candleLength)
rsic = ta.rsi(close, candleLength)

s_rsio = RSIma(rsio, candleMALength,candlesMAType)
s_rsih = RSIma(rsih, candleMALength,candlesMAType)
s_rsil = RSIma(rsil, candleMALength,candlesMAType)
s_rsic = RSIma(rsic, candleMALength,candlesMAType)

up = ta.rma(math.max(ta.change(rsiSource), 0), rsiLength)
down = ta.rma(-math.min(ta.change(rsiSource), 0), rsiLength)
rsiValue = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMAMovAvg = bbma(rsiValue, bollingerMALength , bollingerMAType)

// Plot Candle Colors
candleColor = s_rsic >= s_rsio ? #056656 : #ec407a
plotcandle(s_rsio,s_rsih,s_rsil,s_rsic, color=candleColor)

// Plot RSI and RSI-Based MA
rsiPlot = plot(rsiValue, "RSI", color=#000000)
plot(rsiMAMovAvg, "RSI-based MA", color=#787B86)

// Plot RSI Bands
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=#ff000014, title="RSI Background Fill")

// Plot Bollinger Bands
bbUpperBand = plot(rsiMAMovAvg + ta.stdev(rsiValue, bollingerMALength) * bbStdDev, title="Upper Bollinger Band", color=#f7525f)
bbLowerBand = plot(rsiMAMovAvg - ta.stdev(rsiValue, bollingerMALength) * bbStdDev, title="Lower Bollinger Band", color=#f7525f)
fill(bbUpperBand, bbLowerBand, color=color.new(color.green, 90), title="Bollinger Bands Background Fill")
