RSI Candle with Advanced RSI fomula
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Dicargo_Beam

//@version=4
study("RSI Candle with Advanced RSI fomula")
usev21 = input(false,"")
usev2 = input(false,"\nPlease use new version 'RSI Candle Advanced V2'\n")
usev22 = input(false,"")
src = close
len = input(14,"Length")
ad = input(true,"RSI Advanced ?? (Recommend)")
cdob = input("Candle",title="Candle or Bar or Line?",options=["Candle","Bar","Line"])
uc = input(color.green,"Up Color")
dc = input(color.red,"Down Color")

_rsi(src, len) => 
    u = max(src - src[1], 0) // upward change
    d = max(src[1] - src, 0) // downward change
    rs = rma(u, len) / rma(d, len)
    res = 100 - 100 / (1 + rs)

_rma(src, length) =>
	a = 1/length
	sum = 0.0
	sum := na(sum[1]) ? sma(src, length) : a * src + (1 - a) * nz(sum[1])
	
//_rma = a*src + (1-a) * _rma[1]

//_rma_next = a * src_next + (1-a) * _rma

u = max(src - src[1], 0)
d = max(src[1] - src, 0)
a = 1/len
ruh = a * max(high-close[1],0) + (1-a) * rma(u,len)[1]
rdh = (1-a)*rma(d,len)[1]

rul = (1-a)*rma(u,len)[1]
rdl = a * max(close[1]-low,0) + (1-a) * rma(d,len)[1]

function(rsi,len) =>
    f = -pow(abs(abs(rsi-50)-50),1+(pow(len/14,0.618)-1))/pow(50,(pow(len/14,0.618)-1))+50
    rsiadvanced = if rsi>50
        f+50
    else
        -f+50



rsiha = 100 - 100/(1+ruh/rdh)
rsila = 100 - 100/(1+rul/rdl)
rsia = rsi(src,len)

rsih = if ad
    function(rsiha,len)
else
    rsiha
    
rsil = if ad
    function(rsila,len)
else
    rsila
rsi = if ad
    function(rsia,len)
else
    rsia


col = change(rsi)>0? uc:dc
colc = if cdob == "Candle"
    col
colb = if cdob == "Bar"
    col
cold = if cdob == "Line"
    col

plotcandle(rsi[1],rsih,rsil,rsi,color=colc,wickcolor=colc,bordercolor=colc)
plotbar(rsi[1],rsih,rsil,rsi,color=colb)
plot(rsi,color=cold)


ob = hline(70,"OB")
os = hline(30,"OS")
hline(50,"Balance")
fill(ob,os,color=color.purple)


