Open Interest Delta with MAs[Binance Perpetuals]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LordOfTheBlockchains

//@version=5
//Open Interest Delta
//ZLEMA, Tillson, VAR MAs codes are coming from @KivancOzbilgic => https://www.tradingview.com/script/sfV6H5h5-SuperTrended-Moving-Averages/
//KAMA code is coming from @HPOTTER => Kaufman Moving Average Adaptive (KAMA) => https://www.tradingview.com/script/RsdQHpdq-Kaufman-Moving-Average-Adaptive-KAMA/

// This indicator only shows Binance Perpetuals Open Interest Delta

indicator("Open Interest Delta with MAs[Binance Perpetuals]", "OI-Delta", format = format.volume)

bool overwriteSymbolInput = input.bool(false, "Override symbol", inline = "Override symbol")
string tickerInput = input.symbol("", "", inline = "Override symbol")
showInfoTable = input(true, title='Show Info Table')

string symbolOnly = str.substring(tickerInput, str.pos(tickerInput, ":") + 1)
string userSymbol = overwriteSymbolInput ? symbolOnly : syminfo.prefix + ":" + syminfo.ticker
//
// Tickers changed. Old version ends with tickerPERP. Now it ends with ticker.P
// strPerp = 'PERP'
// isPerp = str.endswith(userSymbol, strPerp)
// string openInterestTicker = isPerp ? str.format("{0}_OI", userSymbol) : str.format("{0}PERP_OI", userSymbol)
//
//###############################################
// Change for new version:
//###############################################
strPerp = '.P'
isPerp = str.endswith(userSymbol, strPerp)
string openInterestTicker = isPerp ? str.format("{0}_OI", userSymbol) : str.format("{0}.P_OI", userSymbol)
//###############################################
// Change for new version:
//###############################################
//

//
string timeframe = syminfo.type == "futures" and timeframe.isintraday ? "1D" : timeframe.period
[oiOpen, oiHigh, oiLow, oiClose, oiColorCond] = request.security(openInterestTicker, timeframe, [open, high, low, close, close > close[1]], ignore_invalid_symbol = true)
oiOpen := oiOpen ? oiOpen : na
oiHigh := oiHigh ? oiHigh : na
oiLow := oiLow ? oiLow : na

oiDelta = oiClose - oiOpen

showHighDiff = input(true, title='Show Delta Upper Shadow', group="----------Bar Edge----------")
showLowDiff = input(true, title='Show Delta Lower Shadow', group="----------Bar Edge----------")

oiDelta003= oiHigh - oiOpen
plot(showHighDiff ? oiDelta003 : na, title="OI Upper Shadow", color=color.new(color.aqua,0) , style= plot.style_histogram, linewidth=4)

oiDelta002= oiLow - oiOpen
plot(showLowDiff ? oiDelta002 : na, title="OI Lower Shadow", color=color.new(color.yellow, 0), style= plot.style_histogram, linewidth=4)

oiDelta001= oiClose - oiOpen
oiDeltaColor= oiDelta001>=0 ? color.new(color.green, 15) : color.new(color.red, 15)
plot(oiDelta001, title="Delta", color=oiDeltaColor, style= plot.style_columns)

if barstate.islastconfirmedhistory and na(oiClose)
    runtime.error(str.format("No Open Interest data found for the `{0}` symbol.", userSymbol))

if barstate.isfirst and isPerp and showInfoTable
    var table symbolTable = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.gray, 0))
    table.cell(symbolTable, 0, 0, text ="open interest Delta data: " + openInterestTicker, text_color = color.white, text_size = size.small)

if barstate.isfirst and not isPerp and showInfoTable
    var table symbolTable = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.gray, 0))
    table.cell(symbolTable, 0, 0, text = "open interest Delta data: " + openInterestTicker + " !!!!! NOT " + syminfo.tickerid + " SPOT !!!!!", text_color = color.white, text_size = size.small)

//=======================================================================================================================
//=======================================================================================================================

showMa001_001 = input(false, title='Show OI Delta MA', group="----------MA----------", tooltip='MAs default values \n SMA=9 \n EMA=9 \n HMA=9 \n WMA=9 \n VWMA=20 \n DEMA=9 \n TEMA=9 \n RMA=15 \n SWMA=No Length \n TMA=10 \n LSMA=25 \n ZLEMA=8 \n Tillson=8 \n VAR=9')
string deltaSrcInput_001 = input.string("Delta", "MA source", options = ["Delta", "Delta (H+L)/2"], group="----------MA----------")
string maType_001 = input.string("NONE", "MA type", options = ["NONE", "EMA", "SMA","HMA", "ALMA", "WMA", "VWMA", "VWAP", "DEMA", "TEMA", "KAMA", "LSMA", "RMA", "SWMA", "TMA", "WWMA", "ZLEMA", "Tillson", "VAR"], group="----------MA----------")
int maLength_001 = input.int(10, "MA length", minval = 2, group="----------MA----------", tooltip='AMs default values \n SMA=9 \n EMA=9 \n HMA=9 \n WMA=9 \n VWMA=20 \n DEMA=9 \n TEMA=9 \n RMA=15 \n SWMA=No Length \n TMA=10 \n LSMA=25 \n ZLEMA=8 \n Tillson=8 \n VAR=9')
maWindowSizeALMA_001 = input(title="ALMA Window Size", defval=9, tooltip="It is functional when ALMA selected", group="----------MA----------")
maALMAoffset_001 = input(0.85, "ALMA Offset", tooltip="It is functional when ALMA selected", group="----------MA----------")
maALMAsigma_001 = input(6, "ALMA Sigma", tooltip="It is functional when ALMA selected", group="----------MA----------")
T3a1_001 = input.float(0.7, 'TILLSON T3 Volume Factor', tooltip="It is functional when Tillson selected", step=0.1, group="----------MA----------")

float maSrc_001 = switch deltaSrcInput_001
    "Delta" => oiDelta
    "Delta (H+L)/2"=>((oiDelta002 + oiDelta003)/2)
    =>
        runtime.error("No matching MA type found.")
        float(na)

maType_001check = (maType_001 == "ZLEMA") or (maType_001 == "Tillson") or (maType_001 == "VAR") or (maType_001 == "WWMA") or (maType_001 == "KAMA")
//VAR : Variable Index Dynamic Moving Average a.k.a. VIDYA
nAMA_001 = 0.0
WWMA_001 = 0.0
ZLEMA_001 = 0.0
TILLSONT3_001out = 0.0
VAR_001 = 0.0
    
Var_Func_001(src_001, length_001) =>
    valpha_001 = 2 / (length_001 + 1)
    vud1_001 = src_001 > src_001[1] ? src_001 - src_001[1] : 0
    vdd1_001 = src_001 < src_001[1] ? src_001[1] - src_001 : 0
    vUD_001 = math.sum(vud1_001, 9)
    vDD_001 = math.sum(vdd1_001, 9)
    vCMO_001 = nz((vUD_001 - vDD_001) / (vUD_001 + vDD_001))
    VAR_001func = 0.0
    VAR_001func := nz(valpha_001 * math.abs(vCMO_001) * src_001) + (1 - valpha_001 * math.abs(vCMO_001)) * nz(VAR_001func[1])
    VAR_001func
    
if maType_001check
    //ZLEMA : Zero Lag Exponential Moving Average
    ZLEMA_001 := if maType_001=="ZLEMA"
        zxLag_001 = maLength_001 / 2 == math.round(maLength_001 / 2) ? maLength_001 / 2 : (maLength_001 - 1) / 2
        zxEMAData_001 = maSrc_001 + maSrc_001 - maSrc_001[zxLag_001]
        ZLEMA_001calc = ta.ema(zxEMAData_001, maLength_001)
        ZLEMA_001calc
    
    //TILL : Tillson T3 Moving Average
    TILLSONT3_001out := if maType_001=="Tillson"
        T3e1_001 = ta.ema(maSrc_001, maLength_001)
        T3e2_001 = ta.ema(T3e1_001, maLength_001)
        T3e3_001 = ta.ema(T3e2_001, maLength_001)
        T3e4_001 = ta.ema(T3e3_001, maLength_001)
        T3e5_001 = ta.ema(T3e4_001, maLength_001)
        T3e6_001 = ta.ema(T3e5_001, maLength_001)
        T3c1_001 = -T3a1_001 * T3a1_001 * T3a1_001
        T3c2_001 = 3 * T3a1_001 * T3a1_001 + 3 * T3a1_001 * T3a1_001 * T3a1_001
        T3c3_001 = -6 * T3a1_001 * T3a1_001 - 3 * T3a1_001 - 3 * T3a1_001 * T3a1_001 * T3a1_001
        T3c4_001 = 1 + 3 * T3a1_001 + T3a1_001 * T3a1_001 * T3a1_001 + 3 * T3a1_001 * T3a1_001
        TILLSONT3_001 = T3c1_001 * T3e6_001 + T3c2_001 * T3e5_001 + T3c3_001 * T3e4_001 + T3c4_001 * T3e3_001
        TILLSONT3_001
        
    VAR_001 := if maType_001=="VAR"
        Var_Func_001(maSrc_001, maLength_001)
    
    //WWMA : Welles Wilder's Moving Average
    WWMA_001 := if maType_001=="WWMA"
        wwalpha_001 = 1 / maLength_001
        WWMA_001calc = 0.0
        WWMA_001calc := wwalpha_001 * maSrc_001 + (1 - wwalpha_001) * nz(WWMA_001calc[1])
        WWMA_001calc
    
    //Koufman MA Adaptive
    nAMA_001 := if maType_001=="KAMA"
        xPrice_001 = maSrc_001
        xvnoise_001 = math.abs(xPrice_001 - xPrice_001[1])
        nAMAcalc_001 = 0.0
        nfastend_001 = 0.666
        nslowend_001 = 0.0645
        nsignal_001 = math.abs(xPrice_001 - xPrice_001[maLength_001])
        nnoise_001 = math.sum(xvnoise_001, maLength_001)
        nefratio_001 = nnoise_001 != 0 ? nsignal_001 / nnoise_001 : 0
        nsmooth_001 = math.pow(nefratio_001 * (nfastend_001 - nslowend_001) + nslowend_001, 2)
        nAMAcalc_001 := nz(nAMAcalc_001[1]) + nsmooth_001 * (xPrice_001 - nz(nAMAcalc_001[1]))
        nAMAcalc_001

float ma001_001 = if not maType_001check 
    switch maType_001
        "NONE" => na
        "EMA" => ta.ema(maSrc_001, maLength_001)
        "SMA" => ta.sma(maSrc_001, maLength_001)
        "HMA" => ta.hma(maSrc_001, maLength_001)
        "ALMA"=> ta.alma(maSrc_001, maWindowSizeALMA_001, maALMAoffset_001, maALMAsigma_001)
        "WMA" => ta.wma(maSrc_001, maLength_001)
        "VWMA" => ta.vwma(maSrc_001, maLength_001)
        "VWAP" => ta.vwap(maSrc_001)
        "DEMA" => 2 * (ta.ema(maSrc_001, maLength_001)) - ta.ema(ta.ema(maSrc_001, maLength_001), maLength_001)
        "TEMA" => (3 * (ta.ema(maSrc_001, maLength_001) - ta.ema(ta.ema(maSrc_001, maLength_001), maLength_001))) + ta.ema(ta.ema(ta.ema(maSrc_001, maLength_001), maLength_001), maLength_001)
        "KAMA"=> nAMA_001
        "LSMA"=> ta.linreg(maSrc_001, maLength_001, 0)
        "RMA" => ta.rma(maSrc_001, maLength_001)
        "SWMA" => ta.swma(maSrc_001)
        "TMA" => ta.sma(ta.sma(maSrc_001, math.ceil(maLength_001 / 2)), math.floor(maLength_001 / 2) + 1)
        "WWMA" => WWMA_001
        "ZLEMA" => ZLEMA_001
        "Tillson" => TILLSONT3_001out
        "VAR" => VAR_001
        =>
            runtime.error("No matching MA type found.")
            float(na)
        
ma_001style = (maType_001=="VWMA") ? plot.style_cross : (maType_001=="VWAP") ? plot.style_circles : plot.style_line

ma001_001color = ma001_001>=0 ? color.blue : color.yellow

plot(showMa001_001 == true ? ma001_001 : na, color=ma001_001color, linewidth=2, title="OI Delta MA", style= ma_001style)

//=======================================================================================================================
//=======================================================================================================================

