Step RSI [Loxx]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
indicator("Step RSI [Loxx]")

greencolor = #2DD204
redcolor = #D2042D 

stepMACalc(float rsi, simple int size)=>
    float smax = rsi + 2.0 * size
    float smin = rsi - 2.0 * size
    var trend = 0
    float result = 0
    if nz(trend[1]) <= 0 and rsi > nz(smax[1]) 
        trend := 1
    if nz(trend[1]) >= 0 and rsi < nz(smin[1]) 
        trend := -1
    if trend > 0 
        if smin < nz(smin[1]) 
            smin := nz(smin[1])
        result := smin + size
    else
        if smax > nz(smax[1]) 
            smax := nz(smax[1])
        result := smax - size
    result

slowRSI(float src, simple int per)=>
    float up = 0
    float dn = 0
    float alpha = (1 / per)
    for k = 0 to per - 1
        float diff = nz(src[k]) - nz(src[k+1]) 
        if diff > 0
            up += diff
        else  
            dn -= diff
    float rma2 = ta.rma(100 * up / (up + dn), per)
    float rsival = (up + dn) == 0 ? 50 : rma2
    rsival

src = input.source(close, "Source", group = "Basic Settings")
rsiper = input.int(14, "RSI Period", group = "Basic Settings")
stpsize = input.int(5, "Step Size", group = "Basic Settings")

bool colorbars = input.bool(true, "Color bars?", group = "UI Options")
bool showSigs = input.bool(false, "Show signals?", group = "UI Options")

rsiout = slowRSI(src, rsiper)
fasttrend = stepMACalc(rsiout, stpsize)

colorout = rsiout > fasttrend ? greencolor  : redcolor

plot(rsiout, color = colorout, linewidth = 2)
plot(fasttrend, color = color.white)
barcolor(colorbars ? colorout : na)

goLong = ta.crossover(rsiout, fasttrend)
goShort = ta.crossunder(rsiout, fasttrend)

plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)

alertcondition(goLong, title="Long", message="Step RSI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Step RSI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")