Super D2
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © dalderman6

//@version=4
study("Super D2")

cOpen = open
cClose = close
cClose1 = close[1]
cHigh = high
cLow = low

// D price 
dPrice = if (cOpen == cHigh)
    cClose - cLow
else if (cOpen == cLow)
    cHigh - cLow
else if (cClose1 > cOpen)
    cHigh - cLow
else if (cClose1 < cOpen)
    (cHigh - cOpen) + (cClose - cLow)
else
    cClose - cLow

// O price 
oPrice = if (cOpen == cHigh)
    cHigh - cLow
else if (cOpen == cLow)
    cHigh - cClose
else if (cClose1 > cOpen)
    (cOpen - cLow) + (cHigh - cClose)
else if (cClose1 < cOpen)
    cHigh - cLow
else
    cHigh - cClose


// vol variables
dVol = if (dPrice + oPrice) == 0
    0
else
    dPrice / (dPrice + oPrice)
    
oVol = if (dPrice + oPrice) == 0
    0
else
    oPrice / (dPrice + oPrice)


// Media Variables
Media_periods = 40

dMedia = sma(dVol,Media_periods)
oMedia = sma(oVol,Media_periods)

// dD and dO variables
dD = if (dMedia == 0)
    0
else
    ((dMedia / dMedia[1] - 1)) * 100

oD = if (oMedia == 0)
    0
else
    ((oMedia / oMedia[1] - 1)) * 100

// Momentum variables
M1_periods = 40
dM1 = dD - dD[M1_periods]
oM1 = oD - oD[M1_periods]

M2_periods = 1
dM2 = dD - dD[M2_periods]
oM2 = oD - oD[M2_periods]

// M2 adjustments
dM2_abs = abs(dM2)
oM2_abs = abs(oM2)

M2_sum_periods = M1_periods - 1
dM2_sum = sma(dM2_abs, M2_sum_periods) * M2_sum_periods // Cumulative sum of M2_sum_Days periods
oM2_sum = sma(oM2_abs, M2_sum_periods) * M2_sum_periods // Cumulative sum of M2_sum_Days periods

// Efficiency Ratio
dEffRatio = if (dM2_sum == 0)
    0
else
    dM1 / dM2_sum
    
oEffRatio = if (oM2_sum == 0)
    0
else
    oM1 / oM2_sum


// Miscellianos Variables
Corto = 150.0
Corto_adj = 2 / ( 1 + Corto )

Lungo = 300.0
Lungo_adj = 2 / ( 1 + Lungo )

// Alpha
dAlpha = abs(dEffRatio) * (Lungo_adj - Corto_adj) + Corto_adj
oAlpha = abs(oEffRatio) * (Lungo_adj - Corto_adj) + Corto_adj


// ADA
dADA = 0.0
dADA := if (dAlpha < 1 and dAlpha > -1 and ( dAlpha[1]>1 or dAlpha[1]<0 ))
    dD
else 
    nz(dADA[1]) * (1-dAlpha) + dD * dAlpha
    
oADA = 0.0
oADA := if (oAlpha < 1 and oAlpha > -1 and ( oAlpha[1]>1 or oAlpha[1]<0 ))
    oD
else 
    nz(oADA[1])  * (1-oAlpha) + oD * oAlpha
    

ADA_diff = (dADA - oADA) * 100
ADA_diff_ema20 = sma(ADA_diff,15) 
ADA_diff_sma50 = sma(ADA_diff,40) 
ADA_diff_sma100 = sma(ADA_diff,90) 

plot(ADA_diff , color = color.blue, title="Indicator")
plot(ADA_diff_ema20 , color=color.green, transp=65, title="20 ema")
plot(ADA_diff_sma50 , color=color.red, transp=65, title="50 sma")
plot(ADA_diff_sma100 , color = color.orange, transp=65, title="100 sma")
plot(0.0 , color = color.gray)

