Rule Sentinel Altseason Regime

RuleSentinel · study · 509 行 · 点赞 0 · 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 Altseason Regime", shorttitle="RS Altseason", overlay=false, format=format.price, precision=2)
 
//───────────────────────
// Inputs
//───────────────────────
show_rollup = input.bool(true, "Show MTF rollup table", group = "Display", display = display.none, tooltip = "On: the main table plus the 1H / 4H / 1D rollup and TOTAL. Off: the main table only (the former Lite view).")
show_hist   = input.bool(true, "Show score history in the pane", group = "Display", display = display.none, tooltip = "Columns showing the TOTAL score over time (or the main-table score when the rollup is off), drawn in the lower part of the pane so the tables stay clear.")
hist_smooth = input.int(7, "History smoothing (candles)", minval = 1, maxval = 50, group = "Display", display = display.none, tooltip = "Average of the score over this many candles, so the regime waves are easy to read. 1 = raw score on every candle.")
show_age    = input.bool(true, "Show regime age", group = "Display", display = display.none, tooltip = "How long the main-table regime has held since it last changed.")
show_pct    = input.bool(true, "Show % move in the Dir cells", group = "Display", display = display.none, tooltip = "The change of each market over the lookback, as a % of its own value (BTC.D 59.0 to 59.6 = +1.02%).")
txt_color   = input.color(color.white, "Table text color", group = "Display", display = display.none)
tbl_size    = input.string("Normal", "Table size", options = ["Tiny", "Small", "Normal", "Large"], group = "Display", display = display.none, tooltip = "Text size of both tables. Normal is the standard size. A larger size makes the tables taller: if they reach 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
 
grpS        = "Season (90 days)"
show_season = input.bool(true, "Show season rows", group = grpS, display = display.none, tooltip = "Adds the SEASON block to the main table: the alt market vs BTC, and breadth (how many top alts beat BTC) over the season length.")
season_len  = input.int(90, "Season length (days)", minval = 30, maxval = 365, group = grpS, display = display.none, tooltip = "Blockchaincenter's Altcoin Season Index uses 90 days.")
top_n       = input.int(20, "Coins counted (top N)", minval = 5, maxval = 28, group = grpS, display = display.none, tooltip = "Each day the pool is ranked by market cap and the top N coins with enough history are counted.")
alt_thr     = input.int(75, "Altcoin season at (%)", minval = 51, maxval = 100, group = grpS, display = display.none, tooltip = "Breadth at or above this level = Altcoin season (Blockchaincenter's rule: 75%).")
btc_thr     = input.int(25, "Bitcoin season at (%)", minval = 0, maxval = 49, group = grpS, display = display.none, tooltip = "Breadth at or below this level = Bitcoin season (Blockchaincenter's rule: 25%).")
lead_pts    = input.float(10.0, "Alt market lead needed (% points)", minval = 1.0, maxval = 100.0, group = grpS, display = display.none, tooltip = "Alt market vs BTC row: 'Alts ahead' when the top alts' combined market cap beats BTC by at least this many percentage points over the season, 'BTC ahead' when BTC leads by as much, otherwise 'Level'. The season verdict itself comes from the breadth row.")
pool_txt    = input.text_area("ETH, BNB, XRP, SOL, TRX, HYPEH, WBT, ZEC, DOGE, LINK, XMR, ADA, LEO, RAIN2, XLM, BCH, NEAR, UNI, LTC, AVAX, SUI, CCCA, HBAR, GRAM, QNT, TAOB, SHIB, CRO", "Coin pool (comma-separated tickers, up to 28)", group = grpS, display = display.none, tooltip = "TradingView market-cap tickers (CRYPTOCAP:<ticker>), no stablecoins or wrapped tokens. Rule Sentinel updates this list each quarter in the published script. If you edit this box, TradingView keeps your version, so keep it current yourself.")
pool_date   = input.string("Oct 2026", "Coin pool last updated", group = grpS, display = display.none)
 
grpA        = "⚠ Advanced - do not change"
btc_d_sym   = input.string("CRYPTOCAP:BTC.D",   "BTC Dominance symbol",              group = grpA, display = display.none)
btc_sym     = input.string("BINANCE:BTCUSDT",   "BTC price symbol",                  group = grpA, display = display.none)
alts_sym    = input.string("CRYPTOCAP:TOTAL2",  "ALTS index symbol (TOTAL2/TOTAL3)", group = grpA, display = display.none)
usdt_d_sym  = input.string("CRYPTOCAP:USDT.D",  "USDT Dominance symbol",             group = grpA, display = display.none)
tf_fast     = input.timeframe("60",  "Fast TF (1H)", group = grpA, display = display.none)
tf_mid      = input.timeframe("240", "Mid TF (4H)", group = grpA, display = display.none)
tf_slow     = input.timeframe("D",   "Main TF (1D) - the main table", group = grpA, display = display.none)
lookback    = input.int(5, "Lookback candles for UP/DOWN", minval=1, maxval=100, group = grpA, display = display.none, tooltip = "Each row compares its market's close with the close this many candles ago ON THAT ROW'S OWN TIMEFRAME.")
ema_len     = input.int(50, "EMA length for the trend", minval = 5, maxval = 200, group = grpA, display = display.none, tooltip = "UP needs the market above this EMA and higher than it was `lookback` candles ago; DOWN needs it below and lower; anything else is STABLE. Worked out on each row's own timeframe.")
 
//───────────────────────
// Helpers
//───────────────────────
// Fetch the current close, the close `lookback` candles ago and the EMA, all on the requested timeframe.
// (Fix: the old version fetched close only and looked back on the CHART's candles.)
f_fetch(sym, tf) =>
    float cur  = na
    float prev = na
    float ema  = na
    if sym != ""
        [c, p, e] = request.security(sym, tf, [close, close[lookback], ta.ema(close, ema_len)], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
        cur  := c
        prev := p
        ema  := e
    [cur, prev, ema]
 
// Main TF only: also returns the close time of the candle where this market's UP / DOWN / STABLE reading last changed,
// worked out on the main TF's own candles, so the regime age is the same on any chart timeframe.
f_ctx_chg() =>
    float e = ta.ema(close, ema_len)
    int d = na(e) ? 0 : close > e and close > close[lookback] ? 1 : close < e and close < close[lookback] ? -1 : 0
    [close, close[lookback], e, ta.valuewhen(d != d[1], time_close, 0)]
f_fetch_chg(sym, tf) =>
    float cur  = na
    float prev = na
    float ema  = na
    float chg  = na
    if sym != ""
        [c, p, e, t] = request.security(sym, tf, f_ctx_chg(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
        cur  := c
        prev := p
        ema  := e
        chg  := t
    [cur, prev, ema, chg]
 
// -1 = DOWN, 0 = STABLE, 1 = UP (0 also when there is no data). The suite's rule: UP = above its EMA AND higher than
// `lookback` candles ago; DOWN = below its EMA AND lower; anything else (for example above the EMA but falling) = STABLE.
f_dir(cur, prev, e) =>
    int d = 0
    if not na(cur) and not na(prev) and not na(e)
        if cur > e and cur > prev
            d := 1
        else if cur < e and cur < prev
            d := -1
    d
 
f_pct(cur, prev) =>
    na(cur) or na(prev) or prev == 0.0 ? na : (cur - prev) / prev * 100.0
 
f_dir_label(d) =>
    d == 1 ? "UP" : d == -1 ? "DOWN" : "STABLE"
 
// Dir cell text: "n/a" when the market has no data; optional % move
f_dir_text(d, cur, pct) =>
    string out = f_dir_label(d)
    if na(cur)
        out := "n/a"
    else if show_pct and not na(pct)
        out := out + " " + (pct >= 0 ? "+" : "") + str.tostring(pct, "#.##") + "%"
    out
 
// Colour cohesion: cell colour = meaning (green = supportive for crypto). inv flips polarity for headwind drivers.
f_meaning_color(d, inv) =>
    m = inv ? -d : d
    m == 1 ? color.new(color.green, 10) : m == -1 ? color.new(color.red, 10) : color.new(color.orange, 10)
 
f_cell_color(d, inv, cur) =>
    na(cur) ? color.new(color.gray, 60) : f_meaning_color(d, inv)
 
// Short regime names (rollup table)
f_regime_name(domDir, btcDir) =>
    string out = "Mixed / unclear"
    if domDir == -1 and btcDir == 1
        out := "Alts leading"
    else if domDir == -1 and btcDir == 0
        out := "Rotation into alts"
    else if domDir == 0 and btcDir == 1
        out := "Healthy trend"
    else if domDir == 1 and btcDir == -1
        out := "Alt dump"
    else if domDir == 1 and btcDir == 1
        out := "BTC-led"
    out
 
// Full regime names (main table): all 9 combinations, from the former Lite
f_regime_label(domDir, btcDir) =>
    string r = "Mixed / unclear"
    if domDir == 1 and btcDir == 1
        r := "BTC-led, alts bleed"
    else if domDir == 1 and btcDir == -1
        r := "Alt dump"
    else if domDir == 1 and btcDir == 0
        r := "BTC defense, alts heavy"
    else if domDir == 0 and btcDir == 1
        r := "Healthy market, alts OK"
    else if domDir == 0 and btcDir == -1
        r := "Market cool-off"
    else if domDir == 0 and btcDir == 0
        r := "Range / chop"
    else if domDir == -1 and btcDir == 1
        r := "Alts leading BTC"
    else if domDir == -1 and btcDir == -1
        r := "Safe-haven BTC, alts stable"
    else if domDir == -1 and btcDir == 0
        r := "Rotation into alts"
    r
 
f_regime_color(domDir, btcDir) =>
    color out = color.new(color.orange, 40) // default neutral
    if domDir == -1 and btcDir == 1
        out := color.new(color.green, 0)    // altseason
    else if domDir == -1 and btcDir == 0
        out := color.new(color.green, 20)   // rotation
    else if domDir == 0 and btcDir == 1
        out := color.new(color.lime, 20)    // healthy
    else if domDir == 1 and btcDir == -1
        out := color.new(color.red, 0)      // alt dump
    else if domDir == 1 and btcDir == 1
        out := color.new(color.red, 20)     // BTC-led
    out
 
// Alts leading (+2), rotation/healthy (+1), BTC-led (-1), alt dump (-2), else 0
f_regime_score(domDir, btcDir) =>
    int s = 0
    if domDir == -1 and btcDir == 1
        s := 2
    else if domDir == -1 and btcDir == 0
        s := 1
    else if domDir == 0 and btcDir == 1
        s := 1
    else if domDir == 1 and btcDir == -1
        s := -2
    else if domDir == 1 and btcDir == 1
        s := -1
    s
 
f_total_bias_label(totalScore) =>
    string out = "Mixed / neutral"
    if totalScore >= 4
        out := "Strong alt rotation"
    else if totalScore == 3
        out := "Alt rotation building"
    else if totalScore == 2
        out := "Alt-friendly"
    else if totalScore == 1
        out := "Slight alt tilt"
    else if totalScore == -1
        out := "Slight BTC tilt"
    else if totalScore == -2
        out := "BTC-led"
    else if totalScore <= -3
        out := "Alt dump risk"
    out
 
f_total_bias_color(totalScore) =>
    color out = color.new(color.orange, 40)
    if totalScore >= 4
        out := color.new(color.green, 0)
    else if totalScore >= 2
        out := color.new(color.green, 20)
    else if totalScore == 1
        out := color.new(color.lime, 40)
    else if totalScore == -1
        out := color.new(color.red, 20)
    else if totalScore <= -2
        out := color.new(color.red, 0)
    out
 
// Readable timeframe label: "60" -> "1H", "240" -> "4H", "D" -> "1D"
f_tf_label(tf) =>
    int s = timeframe.in_seconds(tf)
    s < 3600 ? str.tostring(math.round(s / 60)) + "m" : s < 86400 ? str.tostring(math.round(s / 3600)) + "H" : s < 604800 ? str.tostring(math.round(s / 86400)) + "D" : str.tostring(math.round(s / 604800)) + "W"
 
//───────────────────────
// Fetch data & directions for each TF. The rollup needs only BTC.D and BTC on the 1H and 4H; the main TF
// also fetches ALTS and USDT.D. 8 requests in all (the old version made 12, 4 of them unused).
//───────────────────────
[btc_d_fast, btc_d_fast_p, btc_d_fast_e] = f_fetch(btc_d_sym,  tf_fast)
[btc_fast,   btc_fast_p,   btc_fast_e]   = f_fetch(btc_sym,    tf_fast)
domDir_fast  = f_dir(btc_d_fast, btc_d_fast_p, btc_d_fast_e)
btcDir_fast  = f_dir(btc_fast,   btc_fast_p,   btc_fast_e)
score_fast   = f_regime_score(domDir_fast, btcDir_fast)
regName_fast = f_regime_name(domDir_fast, btcDir_fast)
regCol_fast  = f_regime_color(domDir_fast, btcDir_fast)
 
[btc_d_mid, btc_d_mid_p, btc_d_mid_e] = f_fetch(btc_d_sym,  tf_mid)
[btc_mid,   btc_mid_p,   btc_mid_e]   = f_fetch(btc_sym,    tf_mid)
domDir_mid  = f_dir(btc_d_mid, btc_d_mid_p, btc_d_mid_e)
btcDir_mid  = f_dir(btc_mid,   btc_mid_p,   btc_mid_e)
score_mid   = f_regime_score(domDir_mid, btcDir_mid)
regName_mid = f_regime_name(domDir_mid, btcDir_mid)
regCol_mid  = f_regime_color(domDir_mid, btcDir_mid)
 
[btc_d_slow, btc_d_slow_p, btc_d_slow_e, dom_chgT] = f_fetch_chg(btc_d_sym, tf_slow)
[btc_slow,   btc_slow_p,   btc_slow_e,   btc_chgT] = f_fetch_chg(btc_sym,   tf_slow)
[alts_slow,  alts_slow_p,  alts_slow_e]  = f_fetch(alts_sym,   tf_slow)
[usdt_slow,  usdt_slow_p,  usdt_slow_e]  = f_fetch(usdt_d_sym, tf_slow)
domDir_slow  = f_dir(btc_d_slow, btc_d_slow_p, btc_d_slow_e)
btcDir_slow  = f_dir(btc_slow,   btc_slow_p,   btc_slow_e)
altsDir_slow = f_dir(alts_slow,  alts_slow_p,  alts_slow_e)
usdtDir_slow = f_dir(usdt_slow,  usdt_slow_p,  usdt_slow_e)
score_slow   = f_regime_score(domDir_slow, btcDir_slow)
regName_slow = f_regime_name(domDir_slow, btcDir_slow)     // short name (rollup)
regLabel_slow = f_regime_label(domDir_slow, btcDir_slow)   // full name (main table)
regCol_slow  = f_regime_color(domDir_slow, btcDir_slow)
 
pct_dom  = f_pct(btc_d_slow, btc_d_slow_p)
pct_btc  = f_pct(btc_slow,   btc_slow_p)
pct_alts = f_pct(alts_slow,  alts_slow_p)
pct_usdt = f_pct(usdt_slow,  usdt_slow_p)
 
total_score  = score_fast + score_mid + score_slow
// (B) The main TF has to agree: a positive TOTAL while the main TF is BTC-led is flagged, not called a rotation trend.
slow_ok      = score_slow >= 0
slow_name    = timeframe.in_seconds(tf_slow) == 86400 ? "Daily" : f_tf_label(tf_slow)
unconfirmed  = total_score > 0 and not slow_ok
total_label  = unconfirmed ? "Short-term alt rotation, " + slow_name + " not confirming" : f_total_bias_label(total_score)
total_color  = unconfirmed ? color.rgb(201, 138, 27) : f_total_bias_color(total_score)
 
//───────────────────────
// (C) and (D) Season over N days: top alts vs BTC, from TradingView's market-cap symbols (CRYPTOCAP)
//───────────────────────
const int POOL_MAX = 28
var array<string> pool = array.new<string>()
if barstate.isfirst
    for part in str.split(str.replace_all(str.replace_all(str.replace_all(pool_txt, " ", ""), "\n", ""), "\r", ""), ",")
        if str.length(part) > 0 and array.size(pool) < POOL_MAX
            array.push(pool, str.upper(part))
 
[btcCapNow, btcCapThen] = request.security("CRYPTOCAP:BTC", "D", [close, close[season_len]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
s_btcRet = f_pct(btcCapNow, btcCapThen)
 
float  s_breadth = na
float  s_altRet  = na
int    s_beats   = 0
int    s_counted = 0
string s_missing = ""
// Worked out on the last two candles only (all the table and alerts need), so the coin requests add little load.
if show_season and array.size(pool) > 0 and bar_index >= last_bar_index - 1
    capNow  = array.new<float>()
    capThen = array.new<float>()
    for i = 0 to array.size(pool) - 1
        sym = array.get(pool, i)
        [cNow, cThen] = request.security("CRYPTOCAP:" + sym, "D", [close, close[season_len]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
        if na(cNow)
            s_missing += sym + " (no data)  "
        else if na(cThen) or cThen <= 0
            s_missing += sym + " (under " + str.tostring(season_len) + " days)  "
        else
            array.push(capNow, cNow)
            array.push(capThen, cThen)
    nValid = array.size(capNow)
    if nValid > 0 and not na(s_btcRet)
        idx = array.sort_indices(capNow, order.descending)
        s_counted := math.min(top_n, nValid)
        float sumNow  = 0.0
        float sumThen = 0.0
        for j = 0 to s_counted - 1
            k = array.get(idx, j)
            n = array.get(capNow, k)
            t = array.get(capThen, k)
            sumNow  += n
            sumThen += t
            if (n - t) / t * 100.0 > s_btcRet
                s_beats += 1
        s_breadth := s_beats * 100.0 / s_counted
        s_altRet  := (sumNow - sumThen) / sumThen * 100.0
 
// 1 = Altcoin season, -1 = Bitcoin season, 0 = Neutral
s_mkt_v   = na(s_altRet) or na(s_btcRet) ? 0 : s_altRet - s_btcRet >= lead_pts ? 1 : s_btcRet - s_altRet >= lead_pts ? -1 : 0
s_brd_v   = na(s_breadth) ? 0 : s_breadth >= alt_thr ? 1 : s_breadth <= btc_thr ? -1 : 0
f_season_txt(v) =>
    v == 1 ? "Altcoin season" : v == -1 ? "Bitcoin season" : "Neutral"
f_season_col(v) =>
    v == 1 ? color.new(color.green, 10) : v == -1 ? color.new(color.red, 10) : color.new(color.orange, 10)
f_sgn(x) =>
    (x >= 0 ? "+" : "") + str.tostring(x, "#.#")
// Alt market vs BTC: who is ahead (no season verdict here; that comes from breadth)
s_gap = na(s_altRet) or na(s_btcRet) ? na : s_altRet - s_btcRet
f_mkt_txt(v) =>
    v == 1 ? "Alts ahead +" + str.tostring(math.abs(s_gap), "#") + " pts" : v == -1 ? "BTC ahead +" + str.tostring(math.abs(s_gap), "#") + " pts" : "Level"
 
//───────────────────────
// (A) Score history in the pane
//───────────────────────
hist_raw  = show_rollup ? total_score : score_slow
hist_val  = ta.sma(hist_raw, hist_smooth)
hist_max  = show_rollup ? 6.0 : 2.0                        // the score's full range: +-6 (TOTAL) or +-2 (main)
hist_norm = hist_val / (hist_max / 2.0)                    // scaled so the colour rule is the same for both
hist_col  = hist_norm >= 1.0 ? color.new(color.green, 0) : hist_norm > 0.15 ? color.new(color.green, 45) : hist_norm > -0.15 ? color.new(color.orange, 40) : hist_norm > -1.0 ? 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)
// Invisible scale markers: reserve the top of the pane for the tables (Pine always draws tables over plots),
// so the columns sit in the lower part of the pane.
plot(show_hist ? hist_max * 5.0 : na, "Scale top", color = color.new(color.black, 100), display = display.pane, editable = false)
plot(show_hist ? -hist_max : 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)
 
//───────────────────────
// (B) Regime age: time since the main-table regime last changed
//───────────────────────
// The regime name changes exactly when BTC.D's or BTC's reading changes (each of the 9 names is one combination),
// so the regime started at the later of the two change times, both measured on the main TF's own candles.
var float firstTime = na
if barstate.isfirst
    firstTime := time
regStart = na(dom_chgT) and na(btc_chgT) ? na : math.max(nz(dom_chgT), nz(btc_chgT))
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")
// Live: the real time now. Bar Replay: the replayed candle's close (timenow is always today's real date).
nowT = math.min(timenow, time_close)
// A change on today's forming main-TF candle is dated from that candle's close, still ahead: say so instead of "0 hours".
age_text = na(btc_d_slow) and na(btc_slow) ? "No data yet" : na(regStart) ? "over " + f_age_text(nowT - firstTime) + " (before chart history)" : regStart > nowT ? "New today (" + slow_name + " not closed yet)" : f_age_text(nowT - regStart)
 
//───────────────────────
// Main table (main TF)
//───────────────────────
var table tbl_main = table.new(position.top_left, 3, 14, 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 = na(s_btcRet) ? "a" : s_counted == 0 ? "b" : "c"
bool tblBuild = tblKey != tblLayout
 
if barstate.islast
    if tblBuild
        table.clear(tbl_main, 0, 0, 2, 13)
    // spacer row (clears the status line)
    table.cell(tbl_main, 0, 0, " ", bgcolor=color.new(color.black, 100), text_color=color.new(color.black, 100), text_size = tbl_sz)
    table.cell(tbl_main, 1, 0, " ", bgcolor=color.new(color.black, 100), text_color=color.new(color.black, 100), text_size = tbl_sz)
    table.cell(tbl_main, 2, 0, " ", bgcolor=color.new(color.black, 100), text_color=color.new(color.black, 100), text_size = tbl_sz)
 
    table.cell(tbl_main, 0, 1, "RS · Altseason Regime", bgcolor=color.rgb(12,12,12), text_color=color.white, text_halign=text.align_center, text_size = tbl_sz)
    table.cell(tbl_main, 1, 1, "", bgcolor=color.rgb(12,12,12), text_size = tbl_sz)
    table.cell(tbl_main, 2, 1, "", bgcolor=color.rgb(12,12,12), text_size = tbl_sz)
    table.merge_cells(tbl_main, 0, 1, 2, 1)
 
    table.cell(tbl_main, 0, 2, "Item",   bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 1, 2, "Dir",    bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 2, 2, "Notes",  bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
 
    table.cell(tbl_main, 0, 3, "BTC.D", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 1, 3, f_dir_text(domDir_slow, btc_d_slow, pct_dom), bgcolor=f_cell_color(domDir_slow, true, btc_d_slow), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 2, 3, "BTC share vs alts", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
 
    table.cell(tbl_main, 0, 4, "BTC", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 1, 4, f_dir_text(btcDir_slow, btc_slow, pct_btc), bgcolor=f_cell_color(btcDir_slow, false, btc_slow), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 2, 4, "BTC trend", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
 
    table.cell(tbl_main, 0, 5, "ALTS", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 1, 5, f_dir_text(altsDir_slow, alts_slow, pct_alts), bgcolor=f_cell_color(altsDir_slow, false, alts_slow), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 2, 5, "TOTAL2/TOTAL3 trend", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
 
    table.cell(tbl_main, 0, 6, "USDT.D", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 1, 6, f_dir_text(usdtDir_slow, usdt_slow, pct_usdt), bgcolor=f_cell_color(usdtDir_slow, true, usdt_slow), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 2, 6, "↑ = risk-off in crypto", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
 
    table.cell(tbl_main, 0, 7, "Regime (" + f_tf_label(tf_slow) + ")", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 1, 7, "Score " + str.tostring(score_slow), bgcolor=regCol_slow, text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 2, 7, regLabel_slow, bgcolor=regCol_slow, text_color=txt_color, text_size = tbl_sz)
 
    int cheatRow = 8
    if show_age
        table.cell(tbl_main, 0, 8, "Regime age", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_main, 1, 8, age_text, bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
        table.merge_cells(tbl_main, 1, 8, 2, 8)
        cheatRow := 9
 
    if show_season
        r = cheatRow
        table.cell(tbl_main, 0, r, "SEASON (" + str.tostring(season_len) + " DAYS)", bgcolor=color.rgb(12,12,12), text_color=color.rgb(159,179,200), text_halign=text.align_center, text_size = tbl_sz)
        table.cell(tbl_main, 1, r, "", bgcolor=color.rgb(12,12,12), text_size = tbl_sz)
        table.cell(tbl_main, 2, r, "", bgcolor=color.rgb(12,12,12), text_size = tbl_sz)
        table.merge_cells(tbl_main, 0, r, 2, r)
        r += 1
        if na(s_btcRet)
            table.cell(tbl_main, 0, r, "Season rows", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
            table.cell(tbl_main, 1, r, "No data yet for a " + str.tostring(season_len) + "-day reading", bgcolor=color.new(color.gray, 60), text_color=txt_color, text_size = tbl_sz)
            table.merge_cells(tbl_main, 1, r, 2, r)
            r += 1
        else if s_counted == 0
            table.cell(tbl_main, 0, r, "Season rows", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
            table.cell(tbl_main, 1, r, "No coin data: check the coin pool in Settings", bgcolor=color.new(color.gray, 60), text_color=txt_color, tooltip = s_missing, text_size = tbl_sz)
            table.merge_cells(tbl_main, 1, r, 2, r)
            r += 1
        else
            table.cell(tbl_main, 0, r, "Alt market vs BTC", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
            table.cell(tbl_main, 1, r, "Alts " + f_sgn(s_altRet) + "% · BTC " + f_sgn(s_btcRet) + "%", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
            table.cell(tbl_main, 2, r, f_mkt_txt(s_mkt_v), bgcolor=f_season_col(s_mkt_v), text_color=txt_color, text_size = tbl_sz)
            r += 1
            table.cell(tbl_main, 0, r, "Breadth (top " + str.tostring(top_n) + ")", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
            table.cell(tbl_main, 1, r, str.tostring(s_beats) + " of " + str.tostring(s_counted) + " beat BTC (" + str.tostring(math.round(s_breadth)) + "%)", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
            table.cell(tbl_main, 2, r, f_season_txt(s_brd_v), bgcolor=f_season_col(s_brd_v), text_color=txt_color, text_size = tbl_sz)
            r += 1
            table.cell(tbl_main, 0, r, "Coins counted", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
            table.cell(tbl_main, 1, r, str.tostring(s_counted) + " of " + str.tostring(top_n), bgcolor=color.rgb(10,10,10), text_color=txt_color, tooltip = "Coin pool last updated: " + pool_date + (s_missing == "" ? ". Every pool coin has data." : ". Not counted: " + s_missing), text_size = tbl_sz)
            table.merge_cells(tbl_main, 1, r, 2, r)
            r += 1
        cheatRow := r
 
    table.cell(tbl_main, 0, cheatRow, "Cheat sheet:", bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 1, cheatRow, "Best = BTC.D ↓ & BTC ↑", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
    table.cell(tbl_main, 2, cheatRow, "Worst = BTC.D ↑ & BTC ↓", bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
    tblKey := tblLayout
 
//───────────────────────
// MTF rollup table (shown only when the switch is on)
//───────────────────────
var table tbl_mtf = table.new(position.top_right, 3, 6, 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 mtfKey = ""
string mtfLayout = "1"
bool mtfBuild = mtfKey != mtfLayout
 
if barstate.islast
    if mtfBuild
        table.clear(tbl_mtf, 0, 0, 2, 5)
    if show_rollup
        table.cell(tbl_mtf, 0, 0, " ", bgcolor=color.new(color.black, 100), text_color=color.new(color.black, 100), text_size = tbl_sz)
        table.cell(tbl_mtf, 1, 0, " ", bgcolor=color.new(color.black, 100), text_color=color.new(color.black, 100), text_size = tbl_sz)
        table.cell(tbl_mtf, 2, 0, " ", bgcolor=color.new(color.black, 100), text_color=color.new(color.black, 100), text_size = tbl_sz)
 
        table.cell(tbl_mtf, 0, 1, "TF",      bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 1, 1, "Regime",  bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 2, 1, "Score",   bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
 
        table.cell(tbl_mtf, 0, 2, f_tf_label(tf_fast), bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 1, 2, regName_fast, bgcolor=regCol_fast, text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 2, 2, str.tostring(score_fast), bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
 
        table.cell(tbl_mtf, 0, 3, f_tf_label(tf_mid), bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 1, 3, regName_mid, bgcolor=regCol_mid, text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 2, 3, str.tostring(score_mid), bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
 
        table.cell(tbl_mtf, 0, 4, f_tf_label(tf_slow), bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 1, 4, regName_slow, bgcolor=regCol_slow, text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 2, 4, str.tostring(score_slow), bgcolor=color.rgb(10,10,10), text_color=txt_color, text_size = tbl_sz)
 
        table.cell(tbl_mtf, 0, 5, "TOTAL",   bgcolor=color.rgb(20,20,20), text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 1, 5, total_label, bgcolor=total_color, text_color=txt_color, text_size = tbl_sz)
        table.cell(tbl_mtf, 2, 5, str.tostring(total_score), bgcolor=total_color, text_color=txt_color, text_size = tbl_sz)
    mtfKey := mtfLayout
 
//───────────────────────
// Alerts (all fire once, on the change)
//───────────────────────
// On the MTF TOTAL score
// The two alt-positive MTF alerts need the main TF to agree (not BTC-led).
mtf_af     = total_score >= 2 and slow_ok
mtf_strong = total_score >= 4 and slow_ok
alertcondition(mtf_af and not mtf_af[1],                  "MTF: Alt-friendly",        "Rule Sentinel · Altseason Regime: MTF turned alt-friendly (TOTAL score 2 or more, main TF not BTC-led)")
alertcondition(mtf_strong and not mtf_strong[1],          "MTF: Strong alt rotation", "Rule Sentinel · Altseason Regime: strong alt rotation (TOTAL score 4 or more, main TF not BTC-led)")
alertcondition(total_score <= -2 and total_score[1] > -2, "MTF: BTC-led",             "Rule Sentinel · Altseason Regime: shifted BTC-led (TOTAL score -2 or less)")
alertcondition(total_score <= -3 and total_score[1] > -3, "MTF: Alt dump risk",       "Rule Sentinel · Altseason Regime: alt dump risk (TOTAL score -3 or less)")
// On the main table (main TF)
alertcondition(score_slow >= 2 and score_slow[1] < 2,     "Main TF: Alts leading BTC", "Rule Sentinel · Altseason Regime: main TF flipped to alts leading BTC (BTC.D down, BTC up)")
alertcondition(score_slow >= 1 and score_slow[1] < 1,     "Main TF: Alt-friendly", "Rule Sentinel · Altseason Regime: main TF turned alt-friendly (score 1 or more)")
alertcondition(score_slow <= -1 and score_slow[1] > -1,   "Main TF: BTC-led",      "Rule Sentinel · Altseason Regime: main TF shifted BTC-led (score -1 or less)")
alertcondition(score_slow <= -2 and score_slow[1] > -2,   "Main TF: Alt dump",     "Rule Sentinel · Altseason Regime: main TF alt dump risk (score -2 or less)")
alertcondition(domDir_slow == -1 and domDir_slow[1] != -1, "Main TF: BTC.D turning down", "Rule Sentinel · Altseason Regime: BTC dominance turning down on the main TF (alt tailwind)")
// Season alerts (on breadth)
season_alt = s_breadth >= alt_thr
season_btc = s_breadth <= btc_thr
alertcondition(season_alt and not season_alt[1],          "Season: Altcoin season",   "Rule Sentinel · Altseason Regime: Altcoin season, breadth reached the Altcoin season level")
alertcondition(season_btc and not season_btc[1],          "Season: Bitcoin season",   "Rule Sentinel · Altseason Regime: Bitcoin season, breadth fell to the Bitcoin season level")

← 返回列表