Market Risk Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

f_roc(_a0, _a1) => 100 * (_a0 - _a1) / _a1

f_pct(_securityRequested, _length) =>
    100 * (_securityRequested - ta.lowest(_securityRequested, _length)) / (ta.highest(_securityRequested, _length) - ta.lowest(_securityRequested, _length))

WTI = request.security("TVC:USOIL", timeframe.period, close)
HYG = request.security("AMEX:HYG", timeframe.period, close)
UST = request.security("TVC:US10Y", timeframe.period, close)
DXY = request.security("TVC:DXY", timeframe.period, close)
USDT = request.security("CRYPTOCAP:USDT", timeframe.period, close)
USDC = request.security("CRYPTOCAP:USDC", timeframe.period, close)
vBTC = request.security("BINANCE:BTCUSDT", timeframe.period, volume)

wtiPct = f_pct(WTI, 200)
hygPct = f_pct(HYG, 200)
ustPct = f_pct(UST, 200)
dxyPct = f_pct(DXY, 200)

f_color(_pct) =>
    if (_pct < 33)
        color.red
    else if (_pct >= 33) and (_pct < 66)
        color.yellow
    else if (_pct >= 66)
        color.green

plot(180, title='wti', color=color.new(f_color(wtiPct), 80), linewidth=0, style=plot.style_columns, offset=0, trackprice=false, editable=false, histbase=90)
plot(90, title='hyg', color=color.new(f_color(hygPct), 80), linewidth=0, style=plot.style_columns, offset=0, trackprice=false, editable=false, histbase=0)
plot(0, title='ust', color=color.new(f_color(100-ustPct), 80), linewidth=0, style=plot.style_columns, offset=0, trackprice=false, editable=false, histbase=-90)
plot(-90, title='dxy', color=color.new(f_color(100-dxyPct), 80), linewidth=0, style=plot.style_columns, offset=0, trackprice=false, editable=false, histbase=-180)

MRI = wtiPct+hygPct-ustPct-dxyPct
plot(MRI, title='MRI', color=color.blue, linewidth=2)
plot(ta.wma(wtiPct+hygPct-dxyPct-ustPct, 200), color=color.yellow)

//Quads by Hedgeye
GDP = request.security("ECONOMICS:USGDPCP", "3M", close)
CPI = request.security("ECONOMICS:USCPI", "3M", close)
rGDP = 100*ta.roc(GDP,1)
rCPI = 100*ta.roc(CPI,1)
dGDP = rGDP < 100 ? rGDP : 100
dGDP := dGDP > -100 ? dGDP : -100
dCPI = rCPI < 100 ? rCPI : 100
dCPI := dCPI > -100 ? dCPI : -100

plot(dGDP, title='dGDP', color=color.white, linewidth=2)
plot(dCPI, title='dCPI', color=color.orange, linewidth=2)


var table tabDisplay = table.new(position.top_right, 1, 4, frame_width = 0, frame_color = color.black)
if barstate.islast
    // We only populate the table on the last bar.
    table.cell(tabDisplay, 0, 0, "wti", text_color = color.blue)
    table.cell(tabDisplay, 0, 1, "hyg", text_color = color.blue)
    table.cell(tabDisplay, 0, 2, "us10y", text_color = color.blue)
    table.cell(tabDisplay, 0, 3, "dxy", text_color = color.blue)
    table.cell_set_height(tabDisplay, 0, 0, 25)
    table.cell_set_height(tabDisplay, 0, 1, 25)
    table.cell_set_height(tabDisplay, 0, 2, 25)
    table.cell_set_height(tabDisplay, 0, 3, 25)

//@version=5
indicator(title="MRI3", overlay=false)
