RSI adjusted SuperTrend
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fikira
//@version=5
indicator("RSI adjusted SuperTrend", overlay=true)

fct    = input.float (   2 , 'factor'                                    )
lenATR = input.int   (  20 , 'length ATR'                                )
lenRSI = input.int   (  14 , 'Length RSI'                                )
toggle = input.string('100', 'Divide RSI value by', options=['100', '50'])
regST  = input.bool  (false, 'show Regular ST'                           )

rsi    = ta.rsi      (close, lenRSI)
aRsi   = math.abs    (rsi  -   50  ) / (toggle == '100' ? 100 : 50)
// 90 or 10 -> 40 -> 0.4
// 80 or 20 -> 30 -> 0.3
// 60 or 40 -> 10 -> 0.1
// 50 -> 0 
//plot(aRsi)

rsiAdjustedSupertrend(fct, ATRper) =>
	src = hl2
	atr = ta.atr(ATRper)
	upper      = src + fct * atr, upper2 = src + fct * atr
	lower      = src - fct * atr, lower2 = src - fct * atr
	prevLower  = nz(lower [1]), prevLower2 = nz(lower2[1])
	prevUpper  = nz(upper [1]), prevUpper2 = nz(upper2[1])
    //
	lower  := lower  > prevLower  or close[1] < prevLower  ? lower  : prevLower
	upper  := upper  < prevUpper  or close[1] > prevUpper  ? upper  : prevUpper
    //
    lower2 -= lower2 * aRsi
    upper2 += upper2 * aRsi
    //
	lower2 := lower2 > prevLower2 or close[1] < prevLower2 ? lower2 : prevLower2
	upper2 := upper2 < prevUpper2 or close[1] > prevUpper2 ? upper2 : prevUpper2
    //
	int  direction  = na, int  direction2 = na
	float superdir  = na, float superdir2 = na
	prevSuperdir    = superdir [1]
    prevSuperdir2   = superdir2[1]
    //
	if na(atr[1])
		direction  := 1
        direction2 := 1
	else 
        if prevSuperdir  == prevUpper
		    direction  := close > upper ? -1 : 1
	    else
		    direction  := close < lower ? 1  : -1
	    if prevSuperdir2 == prevUpper2
		    direction2 := close > upper2 ? -1 : 1
	    else
		    direction2 := close < lower2 ? 1 : -1
    //           
	superdir  := direction  == -1 ? lower  : upper
    superdir2 := direction2 == -1 ? lower2 : upper2
    //
	[superdir, direction, superdir2, direction2]

[st, dir, st2, dir2] = rsiAdjustedSupertrend(fct, lenATR)

plot(regST ? st : na, 'regular SuperTrend'     , linewidth=1, color=dir  < 0 ? color.green : color.red)
plot(        st2    , 'RSI adjusted SuperTrend', linewidth=2, color=dir2 < 0 ? color.lime  : #FF0000  )
