Crypto Leverage Ratio [Market Cap / Open Interest in %]
// 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
indicator(title = "Crypto Estimated Leverage Ratio [Market Cap / Perpetuals Open Interest in %]", shorttitle = "Estimated Leverage Ratio", overlay= false, format = format.price)

bool checkOverrideTimeFrame = input.bool(false, "Override Time Trame", inline = "Override Time Trame", group="OVERRIDE Time Trame")
overrideTF = input.timeframe(defval="D", title="Choose Timeframe",group="OVERRIDE Time Trame")


bool showInfoTable = input(true, title='Show Info Table')
bool overwriteSymbolInput = input.bool(false, "Override symbol", inline = "Override symbol", group="OVERRIDE THE SYMBOL")
string coinSymbol  = input.string("BTC", "If you want to override the chart symbol, please write the coin symbol you want to see. e.g. BTC, ETH, AVAX, TORN", inline = "Override symbol", group="OVERRIDE THE SYMBOL")
coinSymbol := str.upper(coinSymbol)

string displaySymbol = overwriteSymbolInput ? coinSymbol : syminfo.basecurrency

string openInterestTicker = str.format("{0}_PERPETUALOPENINTEREST", displaySymbol)
string marketCapTicker = str.format("CRYPTOCAP:{0}", displaySymbol)

//
isTFintra = timeframe.isintraday
string timeframe = not(checkOverrideTimeFrame) and isTFintra ? "D" : checkOverrideTimeFrame ? overrideTF : 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

hasOpIntOHLC = ta.cum(oiOpen)
color openInterestColor = oiColorCond ? color.teal : color.red

///////////////

[marketCapOpen, marketCapHigh, marketCapLow, marketCapClose, marketCapColorCond] = request.security(marketCapTicker, timeframe, [open, high, low, close, close > close[1]], ignore_invalid_symbol = true)
marketCapOpen := marketCapOpen ? marketCapOpen : na
marketCapHigh := marketCapHigh ? marketCapHigh : na
marketCapLow := marketCapLow ? marketCapLow : na

///////////////

leverageRatioClose = 1 / (marketCapClose / (100 * oiClose))
leverageRatioOpen = 1 / (marketCapOpen / (100 * oiOpen))
leverageRatioHigh = 1 / (marketCapHigh / (100 * oiHigh))
leverageRatioLow = 1 / (marketCapLow / (100 * oiLow))

hasLevRatioOHLC = ta.cum(leverageRatioOpen)


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

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


//plot(hasOpIntOHLC and hasLevRatioOHLC ? na : leverageRatioClose, "Leverage Ratio", openInterestColor, style = plot.style_stepline)
//plotcandle(leverageRatioOpen, leverageRatioHigh, leverageRatioLow, hasOpIntOHLC and hasLevRatioOHLC ? leverageRatioClose : na, "LevRatio", color = openInterestColor, wickcolor = openInterestColor, bordercolor = openInterestColor)

color plotColor = leverageRatioClose > leverageRatioClose[1] ?  color.teal : color.red
plot(leverageRatioClose, "Est Lev Ratio", plotColor, style = plot.style_stepline)
//=======================================================================================================================
//=======================================================================================================================

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

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

showBB001 = input(false, title='Show BB', group="----------Bollinger Bands----------")
BBlength = input.int(20, minval=1, title="BB Length",  group= "----------Bollinger Bands----------" )
string bbSrcInput = input.string("close", "BB source", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4"], group="----------Bollinger Bands----------")

float src1 = switch bbSrcInput
    "open" => leverageRatioOpen
    "high" => leverageRatioHigh
    "low" => leverageRatioLow
    "close" => leverageRatioClose
    "hl2"=> (leverageRatioHigh+leverageRatioLow)/2
    "hlc3" => (leverageRatioHigh+leverageRatioLow+leverageRatioClose)/3
    "ohlc4" => (leverageRatioOpen+leverageRatioHigh+leverageRatioLow+leverageRatioClose)/4
    "hlcc4" => (leverageRatioHigh+leverageRatioLow+leverageRatioClose+leverageRatioClose)/4

mult1 = input.float(2.0, minval=0.001, maxval=50, title="Standart Deviation", group= "----------Bollinger Bands----------")
basis = ta.sma(src1, BBlength)
dev = mult1 * ta.stdev(src1, BBlength)
upper1 = basis + dev
lower = basis - dev
offset1 = input.int(0, "Offset", minval = -500, maxval = 500, group= "----------Bollinger Bands----------")
plot(not(isTFintra) and showBB001 == true ? basis : na , "Basis", color=color.new(#26dff7,50), offset = offset1, linewidth=2)
p11 = plot (not(isTFintra) and showBB001 == true ? upper1 : na , "Upper", color=color.new(#2962FF, 50), offset = offset1)
p21 = plot(not(isTFintra) and showBB001 == true ? lower : na , "Lower", color=color.new(#2962FF,50), offset = offset1)
fill( p11, p21 , title = "Background", color=color.rgb(33, 150, 243, 95))
//=======================================================================================================================
//=======================================================================================================================

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

//=======================================================================================================================
//=======================================================================================================================
showMa001_001 = input(false, title='Show leverageRatio MA-1', group="----------MA-1----------")
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-1----------")
string maSrcInput_001 = input.string("close", "MA source", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4"], group="----------MA-1----------")
int maLength_001 = input.int(10, "MA length", minval = 2, group="----------MA-1----------", 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-1----------")
maALMAoffset_001 = input(0.85, "ALMA Offset", tooltip="It is functional when ALMA selected", group="----------MA-1----------")
maALMAsigma_001 = input(6, "ALMA Sigma", tooltip="It is functional when ALMA selected", group="----------MA-1----------")
T3a1_001 = input.float(0.7, 'TILLSON T3 Volume Factor', tooltip="It is functional when Tillson selected", step=0.1, group="----------MA-1----------")

float maSrc_001 = switch maSrcInput_001
    "open" => leverageRatioOpen
    "high" => leverageRatioHigh
    "low" => leverageRatioLow
    "close" => leverageRatioClose
    "hl2"=> (leverageRatioHigh+leverageRatioLow)/2
    "hlc3" => (leverageRatioHigh+leverageRatioLow+leverageRatioClose)/3
    "ohlc4" => (leverageRatioOpen+leverageRatioHigh+leverageRatioLow+leverageRatioClose)/4
    "hlcc4" => (leverageRatioHigh+leverageRatioLow+leverageRatioClose+leverageRatioClose)/4
    =>
        runtime.error("No matching MA type found.")
        float(na)

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

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
        
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

ma_001style= (maType_001=="VWMA") ? plot.style_cross : (maType_001=="VWAP") ? plot.style_circles : plot.style_line

plot(not(isTFintra) and showMa001_001 == true ? ma001_001 : na, color=color.yellow, linewidth=1, title="leverageRatio MA", style= ma_001style)
//=======================================================================================================================
//=======================================================================================================================

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

//=======================================================================================================================
//=======================================================================================================================
showMa001_002 = input(false, title='Show leverageRatio MA-2', group="----------MA-2----------")
string maType_002 = 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-2----------")
string maSrcInput_002 = input.string("close", "MA source", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4"], group="----------MA-2----------")
int maLength_002 = input.int(14, "MA length", minval = 2, group="----------MA-2----------", 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_002 = input(title="ALMA Window Size", defval=9, tooltip="It is functional when ALMA selected", group="----------MA-2----------")
maALMAoffset_002 = input(0.85, "ALMA Offset", tooltip="It is functional when ALMA selected", group="----------MA-2----------")
maALMAsigma_002 = input(6, "ALMA Sigma", tooltip="It is functional when ALMA selected", group="----------MA-2----------")
T3a1_002 = input.float(0.7, 'TILLSON T3 Volume Factor', tooltip="It is functional when Tillson selected", step=0.1, group="----------MA-2----------")

float maSrc_002 = switch maSrcInput_002
    "open" => leverageRatioOpen
    "high" => leverageRatioHigh
    "low" => leverageRatioLow
    "close" => leverageRatioClose
    "hl2"=> (leverageRatioHigh+leverageRatioLow)/2
    "hlc3" => (leverageRatioHigh+leverageRatioLow+leverageRatioClose)/3
    "ohlc4" => (leverageRatioOpen+leverageRatioHigh+leverageRatioLow+leverageRatioClose)/4
    "hlcc4" => (leverageRatioHigh+leverageRatioLow+leverageRatioClose+leverageRatioClose)/4

Var_Func_002(src_002, length_002) =>
    valpha_002 = 2 / (length_002 + 1)
    vud1_002 = src_002 > src_002[1] ? src_002 - src_002[1] : 0
    vdd1_002 = src_002 < src_002[1] ? src_002[1] - src_002 : 0
    vUD_002 = math.sum(vud1_002, 9)
    vDD_002 = math.sum(vdd1_002, 9)
    vCMO_002 = nz((vUD_002 - vDD_002) / (vUD_002 + vDD_002))
    VAR_002func = 0.0
    VAR_002func := nz(valpha_002 * math.abs(vCMO_002) * src_002) + (1 - valpha_002 * math.abs(vCMO_002)) * nz(VAR_002func[1])
    VAR_002func


maType_002check = maType_002 == "ZLEMA" or maType_002 == "Tillson" or maType_002 == "VAR" or maType_002 == "WWMA" or maType_002 == "KAMA"
//VAR : Variable Index Dynamic Moving Average a.k.a. VIDYA
nAMA_002 = 0.0
WWMA_002 = 0.0
ZLEMA_002 = 0.0
TILLSONT3_002out = 0.0
VAR_002 = 0.0
        
if maType_002check
    //ZLEMA : Zero Lag Exponential Moving Average
    ZLEMA_002 := if maType_002=="ZLEMA"
        zxLag_002 = maLength_002 / 2 == math.round(maLength_002 / 2) ? maLength_002 / 2 : (maLength_002 - 1) / 2
        zxEMAData_002 = maSrc_002 + maSrc_002 - maSrc_002[zxLag_002]
        ZLEMA_002calc = ta.ema(zxEMAData_002, maLength_002)
        ZLEMA_002calc
    
    //TILL : Tillson T3 Moving Average
    TILLSONT3_002out := if maType_002=="Tillson"
        T3e1_002 = ta.ema(maSrc_002, maLength_002)
        T3e2_002 = ta.ema(T3e1_002, maLength_002)
        T3e3_002 = ta.ema(T3e2_002, maLength_002)
        T3e4_002 = ta.ema(T3e3_002, maLength_002)
        T3e5_002 = ta.ema(T3e4_002, maLength_002)
        T3e6_002 = ta.ema(T3e5_002, maLength_002)
        T3c1_002 = -T3a1_002 * T3a1_002 * T3a1_002
        T3c2_002 = 3 * T3a1_002 * T3a1_002 + 3 * T3a1_002 * T3a1_002 * T3a1_002
        T3c3_002 = -6 * T3a1_002 * T3a1_002 - 3 * T3a1_002 - 3 * T3a1_002 * T3a1_002 * T3a1_002
        T3c4_002 = 1 + 3 * T3a1_002 + T3a1_002 * T3a1_002 * T3a1_002 + 3 * T3a1_002 * T3a1_002
        TILLSONT3_002 = T3c1_002 * T3e6_002 + T3c2_002 * T3e5_002 + T3c3_002 * T3e4_002 + T3c4_002 * T3e3_002
        TILLSONT3_002
        
    VAR_002 := if maType_002=="VAR"
        Var_Func_002(maSrc_002, maLength_002)
    
    //WWMA : Welles Wilder's Moving Average
    WWMA_002 := if maType_002=="WWMA"
        wwalpha_002 = 1 / maLength_002
        WWMA_002calc = 0.0
        WWMA_002calc := wwalpha_002 * maSrc_002 + (1 - wwalpha_002) * nz(WWMA_002calc[1])
        WWMA_002calc
    
    //Koufman MA Adaptive
    nAMA_002 := if maType_002=="KAMA"
        xPrice_002 = maSrc_002
        xvnoise_002 = math.abs(xPrice_002 - xPrice_002[1])
        nAMAcalc_002 = 0.0
        nfastend_002 = 0.666
        nslowend_002 = 0.0645
        nsignal_002 = math.abs(xPrice_002 - xPrice_002[maLength_002])
        nnoise_002 = math.sum(xvnoise_002, maLength_002)
        nefratio_002 = nnoise_002 != 0 ? nsignal_002 / nnoise_002 : 0
        nsmooth_002 = math.pow(nefratio_002 * (nfastend_002 - nslowend_002) + nslowend_002, 2)
        nAMAcalc_002 := nz(nAMAcalc_002[1]) + nsmooth_002 * (xPrice_002 - nz(nAMAcalc_002[1]))
        nAMAcalc_002

float ma001_002 = if not maType_002check 
    switch maType_002
        "NONE" => na
        "EMA" => ta.ema(maSrc_002, maLength_002)
        "SMA" => ta.sma(maSrc_002, maLength_002)
        "HMA" => ta.hma(maSrc_002, maLength_002)
        "ALMA"=> ta.alma(maSrc_002, maWindowSizeALMA_002, maALMAoffset_002, maALMAsigma_002)
        "WMA" => ta.wma(maSrc_002, maLength_002)
        "VWMA" => ta.vwma(maSrc_002, maLength_002)
        "VWAP" => ta.vwap(maSrc_002)
        "DEMA" => 2 * (ta.ema(maSrc_002, maLength_002)) - ta.ema(ta.ema(maSrc_002, maLength_002), maLength_002)
        "TEMA" => (3 * (ta.ema(maSrc_002, maLength_002) - ta.ema(ta.ema(maSrc_002, maLength_002), maLength_002))) + ta.ema(ta.ema(ta.ema(maSrc_002, maLength_002), maLength_002), maLength_002)
        "KAMA"=> nAMA_002
        "LSMA"=> ta.linreg(maSrc_002, maLength_002, 0)
        "RMA" => ta.rma(maSrc_002, maLength_002)
        "SWMA" => ta.swma(maSrc_002)
        "TMA" => ta.sma(ta.sma(maSrc_002, math.ceil(maLength_002 / 2)), math.floor(maLength_002 / 2) + 1)
        "WWMA" => WWMA_002
        "ZLEMA" => ZLEMA_002
        "Tillson" => TILLSONT3_002out
        "VAR" => VAR_002

ma_002style= (maType_002=="VWMA") ? plot.style_cross : (maType_002=="VWAP") ? plot.style_circles : plot.style_line

plot(not(isTFintra) and showMa001_002 == true ? ma001_002 : na, color=color.blue, linewidth=1, title="leverageRatio MA-2", style= ma_002style)
