[KVA]nRSI
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kamvia
//@version=5
indicator(shorttitle="[KVA]nRSI", title="[KVA]nRSI", overlay=false,format=format.price, precision=2, timeframe="", timeframe_gaps=true)
length = input(14, title="nRsi Length")
n = input(2, title="Number of Periods for Change")
_src = input.source(close,"Source")


RSIcalc(src) =>
    delta = ta.change(src, n)
    gain = math.max(delta, 0)
    loss = math.abs(math.min(delta, 0))
    avg_gain = ta.sma(gain, length)
    avg_loss = ta.sma(loss, length)
    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))
    rsi
rsi = RSIcalc(_src)


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


maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "EMA", "RMA", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(14, title="MA Length", group="MA Settings")

rsiMA = ma(rsi, maLengthInput, maTypeInput)

rsiPlot = plot(rsi, "RSI", color=#7E57C2)

plot(rsiMA, title="N-Day RSI MA " ,color= color.green)

rsiUpperBand = hline(80, "RSI Upper Band", color=#787B86)
midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(20, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")


midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100),  title = "Overbought Gradient Fill")
fill(rsiPlot, midLinePlot, 30,  0,  top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0),      title = "Oversold Gradient Fill")


