Bitmex BTC Perpetual Premium and Funding
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © egils75

//@version=4
study("Bitmex BTC Perp Premium and Funding", shorttitle="BTC Premium and Funding", overlay=false, format=format.percent, precision=4, resolution="")

//Interest and funding calculation
INTEREST_BASE = security("BITMEX:XBTBON8H", "", close)*100
INTEREST_QUOTE = security("BITMEX:USDBON8H", "", close)*100
INTEREST_RATE = (INTEREST_QUOTE - INTEREST_BASE)/3
PREMIUM = security("BITMEX:XBTUSDPI8H", "", close)*100
INTEREST_DIFF = INTEREST_RATE - PREMIUM
FUNDING = if INTEREST_DIFF > 0.05
    PREMIUM+0.05
else if INTEREST_DIFF < -0.05
    PREMIUM-0.05
else
    PREMIUM+INTEREST_DIFF

//Plot values
hline(0, color=color.black, title="0 Line")
plot(FUNDING, style=plot.style_columns, color=color.yellow, title="Perpetual Funding Rate")
plot(PREMIUM, color=color.red, title="Perpetual Premium")
