Rule Sentinel Macro Liquidity

RuleSentinel · study · 463 行 · 点赞 1 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RuleSentinel
 
//@version=6
indicator("Rule Sentinel Macro Liquidity", shorttitle="RS Macro Liquidity", overlay=false, format=format.price, precision=2)
 
//──────────────────────────────
// Inputs
//──────────────────────────────
grpD        = "Display"
show_w      = input.bool(true, "Show weekly column", group = grpD, display = display.none, tooltip = "The 1W column next to the 1D column: the slower trend behind today's reading.")
show_fm     = input.bool(true, "Show Funding vs Markets", group = grpD, display = display.none, tooltip = "Splits the Daily score into Funding (the money) and Markets (the appetite), and says when they disagree.")
show_m2     = input.bool(true, "Show Global M2 backdrop", group = grpD, display = display.none, tooltip = "Money supply of the US, Euro area, China and Japan in US dollars, over 3 and 12 months. Monthly data, about a month behind.")
show_age    = input.bool(true, "Show regime age", group = grpD, display = display.none, tooltip = "How long the Daily reading (risk-on, mixed or risk-off) has held, counted from the Daily close at which it last changed.")
show_pct    = input.bool(true, "Show the change in each cell", group = grpD, display = display.none, tooltip = "The move over the lookback: % for prices, basis points (bp) for the real yield and credit spreads.")
show_hist   = input.bool(true, "Show score history", group = grpD, display = display.none, tooltip = "Columns showing the Daily macro score over time, in the lower part of the pane.")
hist_smooth = input.int(7, "History smoothing (candles)", minval = 1, maxval = 50, group = grpD, display = display.none, tooltip = "Average of the score over this many candles. 1 = raw score on every candle.")
use_heat    = input.bool(false, "Heatmap background (old style)", group = grpD, display = display.none)
txt_color   = input.color(color.white, "Table text color", group = grpD, display = display.none)
tbl_size    = input.string("Normal", "Table size", options = ["Tiny", "Small", "Normal", "Large"], group = grpD, display = display.none, tooltip = "Text size of the table. Normal is the standard size. A larger size makes the table taller: if it reaches the score history, make the pane taller or turn the history off. Display only: readings and alerts do not change.")
tbl_sz      = switch tbl_size
    "Tiny"  => size.tiny
    "Small" => size.small
    "Large" => size.large
    => size.normal
 
grpA     = "⚠ Advanced - do not change"
fed_sym  = input.string("FRED:WALCL",          "Fed balance sheet",          group = grpA, display = display.none)
tga_sym  = input.string("FRED:WTREGEN",        "Treasury General Account",   group = grpA, display = display.none)
rrp_sym  = input.string("FRED:RRPONTSYD",      "Overnight reverse repo",     group = grpA, display = display.none)
ry_sym   = input.string("FRED:DFII10",         "10Y real yield",             group = grpA, display = display.none)
hy_sym   = input.string("FRED:BAMLH0A0HYM2",   "HY credit spread",           group = grpA, display = display.none)
dxy_sym  = input.string("TVC:DXY",             "DXY",                        group = grpA, display = display.none)
vix_sym  = input.string("TVC:VIX",             "VIX",                        group = grpA, display = display.none)
spx_sym  = input.string("SP:SPX",              "S&P 500",                    group = grpA, display = display.none)
qqq_sym  = input.string("NASDAQ:QQQ",          "QQQ",                        group = grpA, display = display.none)
gold_sym = input.string("TVC:GOLD",            "Gold",                       group = grpA, display = display.none)
usm2_sym = input.string("ECONOMICS:USM2",      "M2 United States (USD)",     group = grpA, display = display.none)
eum2_sym = input.string("ECONOMICS:EUM2",      "M2 Euro area",               group = grpA, display = display.none)
cnm2_sym = input.string("ECONOMICS:CNM2",      "M2 China",                   group = grpA, display = display.none)
jpm2_sym = input.string("ECONOMICS:JPM2",      "M2 Japan",                   group = grpA, display = display.none)
eur_fx   = input.string("FX_IDC:EURUSD",       "EUR to USD",                 group = grpA, display = display.none)
cny_fx   = input.string("FX_IDC:CNYUSD",       "CNY to USD",                 group = grpA, display = display.none)
jpy_fx   = input.string("FX_IDC:JPYUSD",       "JPY to USD",                 group = grpA, display = display.none)
lookback = input.int(10, "Lookback candles for UP / DOWN", minval = 2, maxval = 100, group = grpA, display = display.none, tooltip = "Each market is compared with its value this many candles ago, on that column's own timeframe (days on 1D, weeks on 1W).")
ema_len  = input.int(50, "Average length for the trend", minval = 5, maxval = 200, group = grpA, display = display.none, tooltip = "UP needs the market above this average and higher than the lookback; DOWN needs it below and lower.")
nl_lb    = input.int(4, "Net liquidity lookback (weeks)", minval = 1, maxval = 26, group = grpA, display = display.none)
nl_avg   = input.int(13, "Net liquidity average (weeks)", minval = 4, maxval = 52, group = grpA, display = display.none)
m2_thr   = input.float(1.0, "Global M2 growing / shrinking at (% over 3 months)", minval = 0.1, maxval = 10.0, step = 0.1, group = grpA, display = display.none)
 
//──────────────────────────────
// Helpers
//──────────────────────────────
f_pct(cur, prev) =>
    na(cur) or na(prev) or prev == 0.0 ? na : (cur - prev) / prev * 100.0
 
// -1 DOWN, 0 STABLE, 1 UP
f_dir(x, xlb, e) =>
    na(x) or na(xlb) or na(e) ? 0 : x > e and x > xlb ? 1 : x < e and x < xlb ? -1 : 0
 
// ---- evaluated inside the requests, on each market's own candles ----
// Live value, lookback value, average; then the same three on the last CLOSED candle (for the regime age)
f_lvl() =>
    int off = time_close <= timenow ? 0 : 1
    float e = ta.ema(close, ema_len)
    [close, close[lookback], e, close[off], close[off + lookback], e[off]]
 
// S&P 500 also returns its latest candle's open and close times, for the status line
f_lvl_t() =>
    int off = time_close <= timenow ? 0 : 1
    float e = ta.ema(close, ema_len)
    [close, close[lookback], e, close[off], close[off + lookback], e[off], time, time_close, time_close[off]]
 
// Fed series (weekly): value, value nl_lb weeks ago, nl_avg-week average, week
f_fed() =>
    float e = ta.ema(close, nl_avg)
    [close, close[nl_lb], e, time]
 
// M2 (monthly): now, 3 and 12 months ago, month. Non-US M2 is converted to USD at that month's exchange rate.
f_m2_us() =>
    [close, close[3], close[12], time]
f_m2_fx(fx) =>
    float r = request.security(fx, "M", close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
    float v = close * r
    [v, v[3], v[12], time]
 
f_req(sym, tf) =>
    request.security(sym, tf, f_lvl(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
f_req_fed(sym) =>
    request.security(sym, "W", f_fed(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
 
// Fed units: WALCL is in millions, TGA and RRP in billions; full-dollar data is also handled. Result in trillions.
f_div(x, div) =>
    na(x) ? div : math.abs(x) >= 1e8 ? 1e12 : div
 
//──────────────────────────────
// Data
//──────────────────────────────
// Funding
[fd, fdl, fde, fdt] = f_req_fed(fed_sym)
[tg, tgl, tge, tgt] = f_req_fed(tga_sym)
[rp, rpl, rpe, rpt] = f_req_fed(rrp_sym)
kF = f_div(fd, 1e6)
kT = f_div(tg, 1e3)
kR = f_div(rp, 1e3)
nl   = fd / kF - tg / kT - rp / kR
nll  = fdl / kF - tgl / kT - rpl / kR
nle  = fde / kF - tge / kT - rpe / kR
nl_d = f_dir(nl, nll, nle)
 
[ry_d, ryl_d, rye_d, ryc_d, rycl_d, ryce_d] = f_req(ry_sym, "D")
[ry_w, ryl_w, rye_w, ryc_w, rycl_w, ryce_w] = f_req(ry_sym, "W")
[dx_d, dxl_d, dxe_d, dxc_d, dxcl_d, dxce_d] = f_req(dxy_sym, "D")
[dx_w, dxl_w, dxe_w, dxc_w, dxcl_w, dxce_w] = f_req(dxy_sym, "W")
[hy_d, hyl_d, hye_d, hyc_d, hycl_d, hyce_d] = f_req(hy_sym, "D")
[hy_w, hyl_w, hye_w, hyc_w, hycl_w, hyce_w] = f_req(hy_sym, "W")
// Markets
[vx_d, vxl_d, vxe_d, vxc_d, vxcl_d, vxce_d] = f_req(vix_sym, "D")
[vx_w, vxl_w, vxe_w, vxc_w, vxcl_w, vxce_w] = f_req(vix_sym, "W")
[sp_d, spl_d, spe_d, spc_d, spcl_d, spce_d, spT, spTC, spCT] = request.security(spx_sym, "D", f_lvl_t(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[sp_w, spl_w, spe_w, spc_w, spcl_w, spce_w] = f_req(spx_sym, "W")
[qq_d, qql_d, qqe_d, qqc_d, qqcl_d, qqce_d] = f_req(qqq_sym, "D")
[qq_w, qql_w, qqe_w, qqc_w, qqcl_w, qqce_w] = f_req(qqq_sym, "W")
// Context
[gd_d, gdl_d, gde_d, gdc_d, gdcl_d, gdce_d] = f_req(gold_sym, "D")
[gd_w, gdl_w, gde_w, gdc_w, gdcl_w, gdce_w] = f_req(gold_sym, "W")
// Backdrop
[us, us3, us12, usT] = request.security(usm2_sym, "M", f_m2_us(),      gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[eu, eu3, eu12, euT] = request.security(eum2_sym, "M", f_m2_fx(eur_fx), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[cn, cn3, cn12, cnT] = request.security(cnm2_sym, "M", f_m2_fx(cny_fx), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
[jp, jp3, jp12, jpT] = request.security(jpm2_sym, "M", f_m2_fx(jpy_fx), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
 
//──────────────────────────────
// Directions and scores
//──────────────────────────────
// 1D
ry1 = f_dir(ry_d, ryl_d, rye_d)
dx1 = f_dir(dx_d, dxl_d, dxe_d)
hy1 = f_dir(hy_d, hyl_d, hye_d)
vx1 = f_dir(vx_d, vxl_d, vxe_d)
sp1 = f_dir(sp_d, spl_d, spe_d)
qq1 = f_dir(qq_d, qql_d, qqe_d)
gd1 = f_dir(gd_d, gdl_d, gde_d)
// 1W
ryW = f_dir(ry_w, ryl_w, rye_w)
dxW = f_dir(dx_w, dxl_w, dxe_w)
hyW = f_dir(hy_w, hyl_w, hye_w)
vxW = f_dir(vx_w, vxl_w, vxe_w)
spW = f_dir(sp_w, spl_w, spe_w)
qqW = f_dir(qq_w, qql_w, qqe_w)
gdW = f_dir(gd_w, gdl_w, gde_w)
 
// Funding: net liquidity up, real yield down, dollar down, spreads down = supportive
fund1  = nl_d - ry1 - dx1 - hy1
// Markets: VIX down, SPX up, QQQ up = supportive
mkt1   = -vx1 + sp1 + qq1
score1 = fund1 + mkt1
scoreW = nl_d - ryW - dxW - hyW - vxW + spW + qqW
 
// How many drivers have data (missing data is left out, not counted as 0)
f_has(x) =>
    na(x) ? 0 : 1
n1 = f_has(nl) + f_has(ry_d) + f_has(dx_d) + f_has(hy_d) + f_has(vx_d) + f_has(sp_d) + f_has(qq_d)
nW = f_has(nl) + f_has(ry_w) + f_has(dx_w) + f_has(hy_w) + f_has(vx_w) + f_has(sp_w) + f_has(qq_w)
 
// The same Daily score on closed Daily values (used for the regime age)
score1c = nl_d - f_dir(ryc_d, rycl_d, ryce_d) - f_dir(dxc_d, dxcl_d, dxce_d) - f_dir(hyc_d, hycl_d, hyce_d) - f_dir(vxc_d, vxcl_d, vxce_d) + f_dir(spc_d, spcl_d, spce_d) + f_dir(qqc_d, qqcl_d, qqce_d)
 
//──────────────────────────────
// Labels and colours
//──────────────────────────────
f_label(s) =>
    s >= 4 ? "Strong risk-on" : s >= 1 ? "Risk-on" : s == 0 ? "Mixed" : s >= -3 ? "Risk-off" : "Strong risk-off"
f_col(s) =>
    s >= 4 ? color.new(color.green, 0) : s >= 1 ? color.new(color.green, 25) : s == 0 ? color.new(color.orange, 30) : s >= -3 ? color.new(color.red, 25) : color.new(color.red, 0)
amber = color.rgb(201, 138, 27)
 
// The Weekly check: a positive Daily score while the Weekly is negative is flagged
w_check   = show_w and score1 > 0 and scoreW < 0
s1_label  = w_check ? "Risk-on, Weekly not confirming" : f_label(score1)
s1_col    = w_check ? amber : f_col(score1)
 
// Funding vs Markets
fm_text = fund1 > 0 and mkt1 < 0 ? "Funding improving, markets lagging: early-turn watch" : fund1 < 0 and mkt1 > 0 ? "Markets up on weakening funding: fragile" : fund1 > 0 and mkt1 > 0 ? "Funding and markets both supportive" : fund1 < 0 and mkt1 < 0 ? "Funding and markets both weak" : "No clear lead"
fm_col  = (fund1 > 0 and mkt1 < 0) or (fund1 < 0 and mkt1 > 0) ? amber : fund1 > 0 and mkt1 > 0 ? color.new(color.green, 25) : fund1 < 0 and mkt1 < 0 ? color.new(color.red, 25) : color.new(color.orange, 30)
f_sg(x) =>
    (x > 0 ? "+" : "") + str.tostring(x)
 
// Cells
f_cell_col(d, inv, isna) =>
    m = inv ? -d : d
    isna ? color.new(color.gray, 60) : m == 1 ? color.new(color.green, 10) : m == -1 ? color.new(color.red, 10) : color.new(color.orange, 10)
f_word(d) =>
    d == 1 ? "UP" : d == -1 ? "DOWN" : "STABLE"
// Change shown as % (prices) or basis points (yields and spreads)
f_txt(d, x, xlb, bp) =>
    string out = f_word(d)
    if na(x)
        out := "n/a"
    else if show_pct and not na(xlb)
        if bp
            float c = (x - xlb) * 100.0
            out := out + " " + (c >= 0 ? "+" : "") + str.tostring(math.round(c)) + " bp"
        else
            float p = f_pct(x, xlb)
            out := na(p) ? out : out + " " + (p >= 0 ? "+" : "") + str.tostring(p, "0.0") + "%"
    out
f_gold(d, x, xlb, full) =>
    string w = d == 1 ? "ON" : d == -1 ? "OFF" : "Steady"
    string out = na(x) ? "n/a" : (full ? "Safety bid " : "") + w
    if not na(x) and show_pct and not na(xlb)
        float p = f_pct(x, xlb)
        out := na(p) ? out : out + " " + (p >= 0 ? "+" : "") + str.tostring(p, "0.0") + "%"
    out
gold_col(d, x) =>
    na(x) ? color.new(color.gray, 60) : d == 1 ? color.rgb(61, 90, 128) : color.rgb(52, 62, 80)
 
//──────────────────────────────
// Score history in the pane (optional old heatmap background)
//──────────────────────────────
hist_val  = ta.sma(float(score1), hist_smooth)
hist_norm = hist_val / 3.5
hist_col  = hist_norm >= 0.5 ? color.new(color.green, 0) : hist_norm > 0.05 ? color.new(color.green, 45) : hist_norm > -0.05 ? color.new(color.orange, 40) : hist_norm > -0.5 ? color.new(color.red, 45) : color.new(color.red, 0)
plot(show_hist ? hist_val : na, "Score history", color = hist_col, style = plot.style_columns, linewidth = 1, display = display.all - display.status_line)
plot(show_hist ? 21.0 : na, "Scale top", color = color.new(color.black, 100), display = display.pane, editable = false)
plot(show_hist ? -7.0 : na, "Scale bottom", color = color.new(color.black, 100), display = display.pane, editable = false)
hline(0, "Zero", color = color.new(color.gray, 60), linestyle = hline.style_dotted)
bgcolor(use_heat ? color.new(f_col(score1), 85) : na)
 
//──────────────────────────────
// Regime age: time since the Daily reading (risk-on / mixed / risk-off) last changed
//──────────────────────────────
state1 = score1c > 0 ? 1 : score1c < 0 ? -1 : 0
var float regStart  = na
var float firstTime = na
if barstate.isfirst
    firstTime := time
// Dated from the close of the Daily candle the closed reading belongs to, so a live session and a reload agree
if bar_index > 0 and state1 != state1[1]
    regStart := not na(spCT) ? spCT : timeframe.in_seconds() >= 86400 ? time_close : time
f_age_text(ms) =>
    float hrs = ms / 3600000.0
    int h = int(math.floor(hrs))
    int d = int(math.floor(hrs / 24))
    hrs < 24 ? str.tostring(h) + (h == 1 ? " hour" : " hours") : str.tostring(d) + (d == 1 ? " day" : " days")
nowT = math.min(timenow, time_close)
state_word = state1 > 0 ? "Risk-on" : state1 < 0 ? "Risk-off" : "Mixed"
age_text = n1 == 0 ? "No data yet" : timeframe.in_seconds() > 86400 ? "Shown on 1D charts and lower" : na(regStart) ? "1D " + state_word + " for over " + f_age_text(nowT - firstTime) + " (before chart history)" : "1D " + state_word + " for " + f_age_text(math.max(0, nowT - regStart))
 
//──────────────────────────────
// Status line: are US markets open?
//──────────────────────────────
NY = "America/New_York"
// Today's session in New York time (09:30 to 16:00, weekdays)
f_at(t, h, m) =>
    timestamp(NY, year(t, NY), month(t, NY), dayofmonth(t, NY), h, m)
f_wkday(t) =>
    d = dayofweek(t, NY)
    d != dayofweek.saturday and d != dayofweek.sunday
openT  = f_at(nowT, 9, 30)
closeT = f_at(nowT, 16, 0)
in_hours = f_wkday(nowT) and nowT >= openT and nowT < closeT
// Open until the S&P candle closes, capped at 16:00 New York (TradingView stamps the candle a few minutes later)
shutT   = na(spTC) ? closeT : math.min(spTC, closeT)
us_open = not na(spTC) and spTC > nowT and nowT < shutT
// Next open: today if before 09:30 on a weekday, otherwise the next weekday (stepping from midday keeps it right across clock changes)
f_next_open(t) =>
    int nxt = na
    if f_wkday(t) and t < f_at(t, 9, 30)
        nxt := f_at(t, 9, 30)
    else
        for k = 1 to 4
            c = f_at(t, 12, 0) + k * 86400000
            if na(nxt) and f_wkday(c)
                nxt := f_at(c, 9, 30)
    nxt
f_dur(ms) =>
    int mins = int(math.max(0, ms) / 60000)
    int h = int(mins / 60)
    int d = int(h / 24)
    d >= 1 ? str.tostring(d) + "d " + str.tostring(h % 24) + "h" : str.tostring(h) + "h " + str.tostring(mins % 60) + "m"
nextOpen = f_next_open(nowT)
last_txt = na(spTC) ? "" : str.format_time(spTC, "EEE d MMM", NY) + " close"
open_txt = na(nextOpen) ? "" : " · opens " + str.format_time(nextOpen, "EEE HH:mm", NY) + " New York"
closed_today = not na(spTC) and f_at(spTC, 0, 0) == f_at(nowT, 0, 0)
status_text = not barstate.islast ? "" : na(spTC) ? "● US market status unknown" : us_open ? "● US markets open · live · closes " + str.format_time(shutT, "HH:mm", NY) + " New York (in " + f_dur(shutT - nowT) + ")" : in_hours and not closed_today and barstate.isrealtime ? (nowT >= f_at(nowT, 9, 45) ? "● US holiday · showing " + last_txt + open_txt : "● US session opening · showing " + last_txt) : in_hours and not closed_today ? "● US session under way · showing " + last_txt : "● US markets closed · showing " + last_txt + open_txt + " (in " + f_dur(nextOpen - nowT) + ")"
status_bg   = us_open ? color.rgb(24, 64, 44) : color.rgb(34, 38, 47)
 
//──────────────────────────────
// Global M2 backdrop (US + Euro area + China + Japan, in USD)
//──────────────────────────────
float m2N  = 0.0
float m23  = 0.0
float m212 = 0.0
int   m2n  = 0
string m2miss = ""
if not na(us) and not na(us3) and not na(us12)
    m2N += us
    m23 += us3
    m212 += us12
    m2n += 1
else
    m2miss += "US M2  "
if not na(eu) and not na(eu3) and not na(eu12)
    m2N += eu
    m23 += eu3
    m212 += eu12
    m2n += 1
else
    m2miss += "Euro area M2  "
if not na(cn) and not na(cn3) and not na(cn12)
    m2N += cn
    m23 += cn3
    m212 += cn12
    m2n += 1
else
    m2miss += "China M2  "
if not na(jp) and not na(jp3) and not na(jp12)
    m2N += jp
    m23 += jp3
    m212 += jp12
    m2n += 1
else
    m2miss += "Japan M2  "
m2p3  = m2n > 0 ? f_pct(m2N, m23) : na
m2p12 = m2n > 0 ? f_pct(m2N, m212) : na
m2_state = na(m2p3) ? 0 : m2p3 >= m2_thr ? 1 : m2p3 <= -m2_thr ? -1 : 0
f_sgn(x) =>
    na(x) ? "n/a" : (x >= 0 ? "+" : "") + str.tostring(x, "0.0") + "%"
 
//──────────────────────────────
// Counted
//──────────────────────────────
f_miss(x, name) =>
    na(x) ? name + "  " : ""
miss = not barstate.islast ? "" : f_miss(fd, "Fed balance sheet") + f_miss(tg, "TGA") + f_miss(rp, "RRP") + f_miss(ry_d, "Real yield") + f_miss(hy_d, "Credit spreads") + f_miss(dx_d, "DXY") + f_miss(vx_d, "VIX") + f_miss(sp_d, "SPX") + f_miss(qq_d, "QQQ") + f_miss(gd_d, "Gold") + m2miss
n_have  = f_has(fd) + f_has(tg) + f_has(rp) + f_has(ry_d) + f_has(hy_d) + f_has(dx_d) + f_has(vx_d) + f_has(sp_d) + f_has(qq_d) + f_has(gd_d) + m2n
dates   = not barstate.islast ? "" : (na(fdt) ? "" : "Fed data: week of " + str.format_time(fdt, "d MMM", "UTC") + ". ") + (na(usT) ? "" : "M2 to " + str.format_time(usT, "MMM yyyy", "UTC") + ".")
 
//──────────────────────────────
// Table
//──────────────────────────────
var table tbl = table.new(position.top_left, 4, 21, border_width = 1)
// The table is cleared only when its layout changes. Clearing it on every live tick could leave old text showing under the new.
varip string tblKey = ""
string tblLayout = "1"
bool tblBuild = tblKey != tblLayout
cR = show_w ? 3 : 2
lastC = cR
dark  = color.rgb(10, 10, 10)
head  = color.rgb(20, 20, 20)
sec_c = color.rgb(159, 179, 200)
 
f_span(r, txt, bg, tc, al, tip) =>
    table.cell(tbl, 0, r, txt, bgcolor = bg, text_color = tc, text_halign = al, tooltip = tip, text_size = tbl_sz)
    for c = 1 to lastC
        table.cell(tbl, c, r, "", bgcolor = bg, text_size = tbl_sz)
    table.merge_cells(tbl, 0, r, lastC, r)
 
f_row(r, item, d1, dW, inv, x1, x1l, xW, xWl, bp, note) =>
    table.cell(tbl, 0, r, item, bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
    table.cell(tbl, 1, r, f_txt(d1, x1, x1l, bp), bgcolor = f_cell_col(d1, inv, na(x1)), text_color = txt_color, text_size = tbl_sz)
    if show_w
        table.cell(tbl, 2, r, f_txt(dW, xW, xWl, bp), bgcolor = f_cell_col(dW, inv, na(xW)), text_color = txt_color, text_size = tbl_sz)
    table.cell(tbl, cR, r, note, bgcolor = dark, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
 
if barstate.islast
    if tblBuild
        table.clear(tbl, 0, 0, 3, 20)
    for c = 0 to lastC
        table.cell(tbl, c, 0, " ", bgcolor = color.new(color.black, 100), text_color = color.new(color.black, 100), text_size = tbl_sz)
    f_span(1, "RS · Macro Liquidity", color.rgb(12, 12, 12), color.white, text.align_center, "")
    f_span(2, status_text, status_bg, txt_color, text.align_left, "Each market shows its latest value. While US markets are shut (nights, weekends, holidays), the US rows use their last close. Times are New York time; the countdown works wherever you are. In Bar Replay, TradingView only shows a day of US data once that day has closed, so during the session it reads US session under way and shows the previous close.")
    table.cell(tbl, 0, 3, "Driver", bgcolor = head, text_color = txt_color, text_size = tbl_sz)
    table.cell(tbl, 1, 3, "1D",     bgcolor = head, text_color = txt_color, text_size = tbl_sz)
    if show_w
        table.cell(tbl, 2, 3, "1W", bgcolor = head, text_color = txt_color, text_size = tbl_sz)
    table.cell(tbl, cR, 3, "Reads", bgcolor = head, text_color = txt_color, text_size = tbl_sz)
 
    f_span(4, "FUNDING · the money", color.rgb(15, 15, 15), sec_c, text.align_left, "")
    // Net liquidity: weekly data, one reading for both columns
    table.cell(tbl, 0, 5, "Net liquidity", bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
    nl_txt = na(nl) ? "n/a" : f_txt(nl_d, nl, nll, false) + " (" + str.tostring(nl_lb) + " wks) · weekly data"
    nl_tip = na(nl) ? "Fed data missing: see Counted." : "Net liquidity $" + str.tostring(nl, "0.00") + "T = Fed balance sheet $" + str.tostring(fd / kF, "0.00") + "T − TGA $" + str.tostring(tg / kT, "0.00") + "T − RRP $" + str.tostring(rp / kR, "0.00") + "T. " + (na(fdt) ? "" : "Week of " + str.format_time(fdt, "d MMM yyyy", "UTC") + ".")
    table.cell(tbl, 1, 5, nl_txt, bgcolor = f_cell_col(nl_d, false, na(nl)), text_color = txt_color, tooltip = nl_tip, text_size = tbl_sz)
    if show_w
        table.cell(tbl, 2, 5, "", bgcolor = f_cell_col(nl_d, false, na(nl)), text_size = tbl_sz)
        table.merge_cells(tbl, 1, 5, 2, 5)
    table.cell(tbl, cR, 5, "Fed balance sheet − TGA − RRP. ↑ more money", bgcolor = dark, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
    f_row(6, "Real yield 10Y", ry1, ryW, true, ry_d, ryl_d, ry_w, ryl_w, true,  "↓ easier money (inverted)")
    f_row(7, "DXY",            dx1, dxW, true, dx_d, dxl_d, dx_w, dxl_w, false, "↓ tailwind (inverted)")
    f_row(8, "Credit spreads", hy1, hyW, true, hy_d, hyl_d, hy_w, hyl_w, true,  "↑ credit stress (inverted)")
 
    f_span(9, "MARKETS · the appetite", color.rgb(15, 15, 15), sec_c, text.align_left, "")
    f_row(10, "VIX", vx1, vxW, true,  vx_d, vxl_d, vx_w, vxl_w, false, "↑ fear (inverted)")
    f_row(11, "SPX", sp1, spW, false, sp_d, spl_d, sp_w, spl_w, false, "↑ risk-on")
    f_row(12, "QQQ", qq1, qqW, false, qq_d, qql_d, qq_w, qql_w, false, "↑ risk appetite")
 
    f_span(13, "CONTEXT · not scored", color.rgb(15, 15, 15), sec_c, text.align_left, "")
    table.cell(tbl, 0, 14, "Gold", bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
    table.cell(tbl, 1, 14, f_gold(gd1, gd_d, gdl_d, true), bgcolor = gold_col(gd1, gd_d), text_color = txt_color, text_size = tbl_sz)
    if show_w
        table.cell(tbl, 2, 14, f_gold(gdW, gd_w, gdl_w, false), bgcolor = gold_col(gdW, gd_w), text_color = txt_color, text_size = tbl_sz)
    table.cell(tbl, cR, 14, "Hedging underneath", bgcolor = dark, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
 
    int r = 15
    if show_fm
        table.cell(tbl, 0, r, "Funding vs Markets", bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
        table.cell(tbl, 1, r, "Funding " + f_sg(fund1) + " · Markets " + f_sg(mkt1) + " · " + fm_text, bgcolor = fm_col, text_color = txt_color, tooltip = "Daily. Funding (-4 to +4): net liquidity, real yield, DXY, credit spreads. Markets (-3 to +3): VIX, SPX, QQQ.", text_size = tbl_sz)
        for c = 2 to lastC
            table.cell(tbl, c, r, "", bgcolor = fm_col, text_size = tbl_sz)
        table.merge_cells(tbl, 1, r, lastC, r)
        r += 1
 
    table.cell(tbl, 0, r, "Macro score", bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
    table.cell(tbl, 1, r, f_sg(score1) + " / " + str.tostring(n1) + " " + s1_label, bgcolor = s1_col, text_color = txt_color, tooltip = "Daily score: each counted driver adds +1 (supportive), 0 (stable) or -1 (headwind). The number after the / is how many drivers have data.", text_size = tbl_sz)
    if show_w
        table.cell(tbl, 2, r, f_sg(scoreW) + " / " + str.tostring(nW) + " " + f_label(scoreW), bgcolor = f_col(scoreW), text_color = txt_color, text_size = tbl_sz)
    table.cell(tbl, cR, r, show_w ? "1D = now · 1W = the trend" : "1D", bgcolor = dark, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
    r += 1
 
    if show_age
        table.cell(tbl, 0, r, "Regime age", bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
        table.cell(tbl, 1, r, age_text, bgcolor = dark, text_color = txt_color, text_size = tbl_sz)
        for c = 2 to lastC
            table.cell(tbl, c, r, "", bgcolor = dark, text_size = tbl_sz)
        table.merge_cells(tbl, 1, r, lastC, r)
        r += 1
 
    if show_m2
        m2_bg = na(m2p3) ? color.new(color.gray, 60) : f_cell_col(m2_state, false, false)
        m2_txt = na(m2p3) ? "No M2 data yet" : f_sgn(m2p3) + " (3m) · " + f_sgn(m2p12) + " (12m) · " + (m2_state == 1 ? "Growing" : m2_state == -1 ? "Shrinking" : "Flat")
        table.cell(tbl, 0, r, "Backdrop: Global M2", bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
        table.cell(tbl, 1, r, m2_txt, bgcolor = m2_bg, text_color = txt_color, tooltip = "Money supply of the US, Euro area, China and Japan in US dollars (" + str.tostring(m2n) + " of 4 counted). Monthly data, about a month behind. Not scored.", text_size = tbl_sz)
        for c = 2 to lastC
            table.cell(tbl, c, r, "", bgcolor = m2_bg, text_size = tbl_sz)
        table.merge_cells(tbl, 1, r, lastC, r)
        r += 1
 
    table.cell(tbl, 0, r, "Counted", bgcolor = head, text_color = txt_color, text_halign = text.align_left, text_size = tbl_sz)
    table.cell(tbl, 1, r, str.tostring(n_have) + " of 14 · hover for data dates", bgcolor = dark, text_color = txt_color, tooltip = (miss == "" ? "Every market has data. " : "No data: " + miss + ". ") + dates, text_size = tbl_sz)
    for c = 2 to lastC
        table.cell(tbl, c, r, "", bgcolor = dark, text_size = tbl_sz)
    table.merge_cells(tbl, 1, r, lastC, r)
    tblKey := tblLayout
 
//──────────────────────────────
// Alerts (all fire once, on the change)
//──────────────────────────────
alertcondition(score1 > 0 and score1[1] <= 0,    "Macro: turned risk-on",   "Rule Sentinel · Macro Liquidity: Daily score crossed above 0")
alertcondition(score1 < 0 and score1[1] >= 0,    "Macro: turned risk-off",  "Rule Sentinel · Macro Liquidity: Daily score crossed below 0")
alertcondition(score1 >= 4 and score1[1] < 4,    "Macro: strong risk-on",   "Rule Sentinel · Macro Liquidity: Daily score reached +4")
alertcondition(score1 <= -4 and score1[1] > -4,  "Macro: strong risk-off",  "Rule Sentinel · Macro Liquidity: Daily score reached -4")
alertcondition(scoreW > 0 and scoreW[1] <= 0,    "Weekly: turned risk-on",  "Rule Sentinel · Macro Liquidity: Weekly score crossed above 0")
alertcondition(scoreW < 0 and scoreW[1] >= 0,    "Weekly: turned risk-off", "Rule Sentinel · Macro Liquidity: Weekly score crossed below 0")
early   = fund1 > 0 and mkt1 < 0
fragile = fund1 < 0 and mkt1 > 0
alertcondition(early and not early[1],           "Early turn: funding improving, markets lagging", "Rule Sentinel · Macro Liquidity: funding is improving while markets are still weak")
alertcondition(fragile and not fragile[1],       "Fragile: markets up on weakening funding",       "Rule Sentinel · Macro Liquidity: markets are rising while funding weakens")
alertcondition(nl_d == 1 and nl_d[1] != 1,       "Net liquidity: turned up",        "Rule Sentinel · Macro Liquidity: net liquidity (Fed - TGA - RRP) turned up")
alertcondition(nl_d == -1 and nl_d[1] != -1,     "Net liquidity: turned down",      "Rule Sentinel · Macro Liquidity: net liquidity (Fed - TGA - RRP) turned down")
alertcondition(hy1 == 1 and hy1[1] != 1,         "Credit stress: spreads turned up", "Rule Sentinel · Macro Liquidity: high-yield credit spreads turned up (stress rising)")
alertcondition(vx1 == 1 and vx1[1] != 1,         "VIX: turned up",                  "Rule Sentinel · Macro Liquidity: VIX turned up (fear rising)")

← 返回列表