Easy Mode Oscillator v3.1 Macro Regime

NotLazyBear · study · 853 行 · 点赞 50 · 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/
// © NotLazyBear
 
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NotLazyBear
 
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Cmo22
//
// ═══════════════════════════════════════════════════════════════════════════
//  EASY MODE OSCILLATOR v3.1 — MACRO REGIME + INTRADAY TREND-DAY ENGINE
//  FULL FACTOR SET — every intraday-capable series in the script now feeds
//  the session engine. Strategic tide unchanged from v2/v3.
// ═══════════════════════════════════════════════════════════════════════════
//
//  WHAT v3.1 ADDS (over v3.0):
//   + Every data source in this script that PRINTS intraday now scores in
//     the intraday tier. Six factors added, two promoted to default-ON:
//       · VIX/VIX3M term structure ⁻    → Volatility block (new)
//       · Dollar Index ⁻                → Cross-Asset
//       · Copper/Gold                   → Cross-Asset
//       · AUD/JPY                       → Cross-Asset (was default-OFF)
//       · Bitcoin                       → Cross-Asset (was default-OFF)
//       · HYG/IEF credit tape           → Credit block (new)
//       · XLY/XLP                       → Appetite block (new)
//       · SPHB/SPLV                     → Appetite block (new)
//   + One scorer for all of them — SESSION FLOW: return vs prior session
//     close ÷ the instrument's OWN typical full-session move (learned over
//     a rolling i_sf_days sessions), √time-of-session adjusted so an
//     on-pace move reads ≈ the same score 30 minutes in as at the close.
//     This is a SESSION-ANCHORED read — NOT the rolling 60m "flow" that
//     field-failed in v2.1 (that failure was the windowing, not the
//     instruments). Ratio spreads have no usable volume, so no VWAP is
//     required by this scorer. 24h factors (DXY / AUDJPY / BTC) carry the
//     overnight tone into the open. Each factor is na until 5 completed
//     sessions of scale data exist (honest warmup).
//   + Intraday blocks: 4 → 7 (Internals / Tape / Participation /
//     Volatility / Cross-Asset / Credit / Appetite). VIX moved from
//     Cross-Asset into the new Volatility block at the same 0.75 weight,
//     so its prominence is unchanged.
//
//  STILL EXCLUDED intraday — and why:
//   × Bonds/rates: the equity–rate correlation flips regime to regime, so
//     a signed score is meaningless — the same sign-instability that
//     killed the yield curve in v2. CAN print intraday; CANNOT be used.
//   × Every FRED series (net liquidity, HY OAS, claims): no intraday
//     prints exist. Physically impossible, not a design choice.
//
//  HARNESS STATUS — READ THIS BEFORE TRUSTING v3.1:
//   The stage-4 numbers below validate the v3.0 CORE (Internals, Tape,
//   Participation, VIX) exactly as shipped. The eight v3.1 factors, the
//   session-flow scorer, and the 7-block composite/agreement are NOT yet
//   harness-validated. Until a re-run:
//     · added blocks carry deliberately modest default weight (0.75 vol +
//       0.50 each x/credit/appetite = 2.25, vs 3.75 across the validated
//       core + VIX) — supplementary color, not the engine;
//     · the √time ramp exists specifically so new factors register inside
//       the ~30-min detection window instead of sitting sub-dead-zone and
//       dragging the agreement denominator — but it also makes them
//       noisier early in the session by construction;
//     · toggling the six new factors OFF (AUD/JPY + BTC were already OFF
//       in v3.0) reverts the math BIT-EXACT to validated v3.0: empty
//       blocks return na and drop out of BOTH the composite and the
//       agreement count, and the Volatility block collapses back to
//       VIX-only at the same 0.75 weight.
//
//  WHY v2.1's TACTICAL TIER WAS SCRAPPED (field-tested, failed):
//   × Wrong instruments — HYG/IEF, SPHB/SPLV, DXY barely move intraday;
//     their 60m "flow" was microstructure noise or flatline.
//   × Wrong horizon — 32 x 60m windows read a ~5-DAY swing. That is a
//     swing filter mislabeled "intraday," not intraday easy mode.
//   × Wrong anchor — rolling windows, when intraday easy mode is a
//     SESSION phenomenon that resets at the open.
//   × Missing the actual intraday drivers entirely: market internals,
//     price-vs-VWAP acceptance, sector participation.
//   v3.1 re-admits those instruments ONLY through the session-anchored
//   scorer above — a different mechanism from the one that failed.
//
//  TIER 1 — STRATEGIC (daily/weekly) ... the TIDE  [unchanged from v2]
//    Six blocks / 13 factors scored by movement (direction + impulse +
//    persistence, noise-scaled), block-voted, hysteresis state machine →
//    EASY BULL / EASY BEAR / NO EDGE.
//
//  TIER 2 — INTRADAY TREND-DAY ENGINE (default 5m) ... TODAY's tape
//    Everything session-anchored: resets at each open, gated until the
//    first i_min_bars complete ("let internals settle"), and forced flat
//    when the market is closed (detected by benchmark bar staleness —
//    intraday easy mode does not exist overnight; the 24h factors keep
//    computing but cannot wake the tier).
//
//    SEVEN INTRADAY BLOCKS:
//     T1 INTERNALS (w1.50)  the heart of trend-day identification:
//        · Advance/Decline net:  0.6·(level/±1500 pin) + 0.4·(Δ from open /1000)
//        · TICK:                 0.6·(session avg /±350) + 0.4·(share of + bars)
//        · Up/Down volume:       ln(UVOL/DVOL) mapped so 4:1 → ±1
//     T2 TAPE (w1.25)  benchmark (SPY) session structure:
//        · 0.5·tanh(distance from session VWAP, ATR units)
//        · 0.3·(share of session spent on that side of VWAP)
//        · 0.2·tanh(VWAP slope)
//     T3 PARTICIPATION (w1.00)  breadth of leadership:
//        · mean of ±1 for each major sector above/below ITS session VWAP
//     T4 VOLATILITY (w0.75):
//        · VIX % change vs prior close (±5% → ∓1)   [was in Cross-Asset]
//        · VIX/VIX3M term structure session flow ⁻  [v3.1]
//     T5 CROSS-ASSET (w0.50)  session-flow scored   [v3.1]:
//        · Dollar Index ⁻ · Copper/Gold · AUD/JPY · Bitcoin
//     T6 CREDIT (w0.50)  · HYG/IEF session flow     [v3.1]
//     T7 APPETITE (w0.50) · XLY/XLP · SPHB/SPLV     [v3.1]
//
//    STATE MACHINE: entry 0.35 / exit 0.05 / block gate 0.60 / confirm 2,
//    session warmup gate 6 bars, state resets at each open.
//
//  QUANTIFIED (stage-4 harness, 5m RTH sessions, 400–600 synthetic days:
//  20% trend-up, 20% trend-dn, 40% range, 20% reversal; mirrors the v3.0
//  CORE math 1:1; validates MECHANISM, not live edge — and does NOT yet
//  cover the v3.1 additions):
//    · trend days: 100% detected, median flag ~30 MIN after the open
//    · entry 0.35 vs 0.30: identical detection & speed, range-day session
//      flags 38% vs 58%, in-state engagement on range bars 8% vs 13%,
//      and HIGHER in-state drift → 0.35 dominates, chosen
//    · reversal days: median exit ~45 min after the true turn, and the
//      state flips to the new direction 100% of the time — the engine
//      tracks the session, it does not marry the morning
//    · signed 30-min forward drift while state is ON: +1.73 bp/bar vs a
//      true trend drift of 2.0 bp/bar (~85% capture)
//    · honest residual: ~4 in 10 synthetic range days get flagged
//      BRIEFLY at some point (8% of range bars in-state) — the exit
//      floor cuts these fast, but chop will occasionally ping you
//
//  ALIGNMENT LAYER:
//    EASY² BULL/BEAR   strategic regime + intraday state, same direction
//    PULLBACK / BOUNCE intraday flow AGAINST the regime (v2 harness:
//                      counter bars carry ~zero same-direction drift)
//    The intraday state also stands alone: INTRADAY EASY UP / DOWN fires
//    its own alerts regardless of the macro regime.
//
//  NON-REPAINT: both tiers compute every score inside request.security on
//  the data's own timeframe; outputs are self-lagged to the last CLOSED
//  bar. Intraday readings therefore trail by one tactical bar (5m).
//
//  DATA NOTES: internals are exchange feeds — if a default symbol errors,
//  swap it in Data Sources (alternates in tooltips). Internals and the
//  RTH spreads (HYG/IEF, XLY/XLP, SPHB/SPLV, VIX/VIX3M) print RTH only;
//  the staleness gate handles overnight/holidays automatically. Request
//  budget: ~31 of the 40-request cap at defaults (~36 with breadth on and
//  8 sectors). Best viewed on chart TF ≤ tactical TF (⚠ shows otherwise).
// ═══════════════════════════════════════════════════════════════════════════
 
//@version=6
indicator("Easy Mode Oscillator v3.1 — Macro Regime + Intraday Trend-Day Engine (Full Factor Set)",
     shorttitle = "EMO v3.1", overlay = false, precision = 2, dynamic_requests = true)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — STRATEGIC FLOW ENGINE
// ─────────────────────────────────────────────────────────────────────────
grp_e  = "Strategic Engine — Daily Factors"
i_fastD = input.int(15, "Trend Fast EMA (days)",              minval = 2,  group = grp_e)
i_slowD = input.int(60, "Trend Slow EMA / Noise Window",      minval = 10, group = grp_e, tooltip = "Harness: 15/60 beat 5/20 and 10/40 on capture AND whipsaw for ~3 bars of extra lag.")
i_impD  = input.int(20, "Impulse Window (days)",              minval = 3,  group = grp_e)
i_persD = input.int(20, "Persistence Window (days)",          minval = 5,  group = grp_e)
 
grp_ew = "Strategic Engine — Weekly Factors (Net Liquidity, Claims)"
i_fastW = input.int(4,  "Trend Fast EMA (weeks)",             minval = 2,  group = grp_ew)
i_slowW = input.int(12, "Trend Slow EMA / Noise Window",      minval = 6,  group = grp_ew)
i_impW  = input.int(4,  "Impulse Window (weeks)",             minval = 2,  group = grp_ew)
i_persW = input.int(8,  "Persistence Window (weeks)",         minval = 3,  group = grp_ew)
 
grp_mx = "Strategic Engine — Component Mix"
i_w_dir  = input.float(0.40, "Direction Weight",   minval = 0.0, step = 0.05, group = grp_mx)
i_w_imp  = input.float(0.40, "Impulse Weight",     minval = 0.0, step = 0.05, group = grp_mx)
i_w_pers = input.float(0.20, "Persistence Weight", minval = 0.0, step = 0.05, group = grp_mx)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — STRATEGIC REGIME STATE MACHINE
// ─────────────────────────────────────────────────────────────────────────
grp_r = "Strategic Regime State Machine"
i_t_in    = input.float(0.40, "Entry Threshold  |composite|", minval = 0.10, maxval = 0.90, step = 0.05, group = grp_r)
i_t_out   = input.float(0.10, "Exit Threshold (hysteresis)",  minval = 0.00, maxval = 0.50, step = 0.05, group = grp_r)
i_gate    = input.float(0.65, "Block Agreement Gate",         minval = 0.50, maxval = 1.00, step = 0.05, group = grp_r)
i_agr_buf = input.float(0.15, "Agreement Collapse Buffer",    minval = 0.00, maxval = 0.50, step = 0.05, group = grp_r, tooltip = "Shared by both tiers: active state force-exits if agreement drops below its gate − this.")
i_confirm = input.int(3,      "Confirmation Bars",            minval = 1,    maxval = 10,  group = grp_r)
i_dead    = input.float(0.10, "Block Dead-Zone",              minval = 0.00, maxval = 0.30, step = 0.05, group = grp_r, tooltip = "A block only counts as agreeing if |score| exceeds this. Shared by both tiers.")
i_smooth  = input.int(3,      "Composite EMA Smoothing",      minval = 1,    maxval = 15,  group = grp_r, tooltip = "Shared by both tiers.")
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — INTRADAY TREND-DAY ENGINE
// ─────────────────────────────────────────────────────────────────────────
grp_tc = "Intraday Trend-Day Engine"
i_use_tac    = input.bool(true, "Enable Intraday Tier",        group = grp_tc)
i_tac_tf     = input.timeframe("5", "Intraday Timeframe",      group = grp_tc, tooltip = "Session engine resolution. Keep chart TF ≤ this for full fidelity (⚠ shows otherwise).")
i_min_bars   = input.int(6,      "Session Warmup Bars",        minval = 1, maxval = 24, group = grp_tc, tooltip = "No intraday state until this many bars of the session complete. 6 x 5m = the classic 'let internals settle for 30 minutes'. Harness: median trend-day flag lands right at this gate with 100% detection.")
i_tt_in      = input.float(0.35, "Entry Threshold",            minval = 0.05, maxval = 0.90, step = 0.05, group = grp_tc, tooltip = "Harness (v3.0 core): 0.35 matched 0.30 on detection (100%) and speed (~30 min) while cutting range-day flags 58%→38% and IMPROVING in-state drift.")
i_tt_out     = input.float(0.05, "Exit Threshold",             minval = 0.00, maxval = 0.50, step = 0.05, group = grp_tc)
i_tt_gate    = input.float(0.60, "Block Agreement Gate",       minval = 0.50, maxval = 1.00, step = 0.05, group = grp_tc, tooltip = "With all 7 blocks live this requires 5/7 agreeing (old 4-block config required 3/4).")
i_tt_confirm = input.int(2,      "Confirmation Bars",          minval = 1,    maxval = 10,   group = grp_tc)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — INTRADAY EXTENDED FACTORS (v3.1, session-flow scored)
// ─────────────────────────────────────────────────────────────────────────
grp_tx = "Intraday Extended Factors — v3.1"
i_it_term  = input.bool(true, "VIX/VIX3M Term Structure ⁻",  group = grp_tx, tooltip = "Session flow of the ratio, sign-flipped (backwardation move = risk-off). NOT harness-validated. Turning ALL eight factors in this group OFF reverts the intraday math bit-exact to validated v3.0.")
i_it_dxy   = input.bool(true, "Dollar Index ⁻",              group = grp_tx, tooltip = "24h instrument — carries the overnight tone into the open. NOT harness-validated.")
i_it_cg    = input.bool(true, "Copper/Gold",                 group = grp_tx, tooltip = "NOT harness-validated.")
i_use_xfx  = input.bool(true, "AUD/JPY",                     group = grp_tx, tooltip = "24h. Was default-OFF rolling-flow in v3.0; now session-flow scored and ON. NOT harness-validated.")
i_use_xbtc = input.bool(true, "Bitcoin",                     group = grp_tx, tooltip = "24h. Was default-OFF rolling-flow in v3.0; now session-flow scored and ON. NOT harness-validated.")
i_it_hyi   = input.bool(true, "Credit Tape (HYG/IEF)",       group = grp_tx, tooltip = "RTH spread. NOT harness-validated.")
i_it_xy    = input.bool(true, "XLY/XLP",                     group = grp_tx, tooltip = "RTH spread. NOT harness-validated.")
i_it_hb    = input.bool(true, "SPHB/SPLV",                   group = grp_tx, tooltip = "RTH spread. NOT harness-validated.")
i_sf_gain  = input.float(0.8, "Session-Flow Gain",           minval = 0.1, maxval = 3.0, step = 0.1, group = grp_tx, tooltip = "tanh gain on (session return ÷ typical session move, √time-adjusted). An on-pace typical trend move scores ≈ tanh(gain) ≈ 0.66 at ANY point of the session; lower to damp.")
i_sf_days  = input.int(20,   "Session-Flow Lookback (sessions)", minval = 5, maxval = 60, group = grp_tx, tooltip = "Rolling sessions used to learn each instrument's typical session move and session length. Each factor is na until 5 completed sessions exist.")
 
grp_tw = "Intraday Block Weights"
i_tw_int  = input.float(1.50, "Internals",       minval = 0.0, step = 0.25, group = grp_tw, tooltip = "ADD + TICK + up/down volume — internals ARE the trend-day definition; weighted highest.")
i_tw_tape = input.float(1.25, "Tape (VWAP)",     minval = 0.0, step = 0.25, group = grp_tw)
i_tw_part = input.float(1.00, "Participation",   minval = 0.0, step = 0.25, group = grp_tw)
i_tw_vol  = input.float(0.75, "Volatility",      minval = 0.0, step = 0.25, group = grp_tw, tooltip = "VIX session %chg + term structure. Carries VIX's 0.75 weight from v3.0's Cross-Asset slot — VIX prominence unchanged.")
i_tw_x    = input.float(0.50, "Cross-Asset",     minval = 0.0, step = 0.25, group = grp_tw, tooltip = "v3.1: DXY⁻ / Copper-Gold / AUD-JPY / BTC. VIX moved out to Volatility; default cut 0.75 → 0.50 accordingly.")
i_tw_cred = input.float(0.50, "Credit (HYG/IEF)", minval = 0.0, step = 0.25, group = grp_tw, tooltip = "v3.1 block. Set 0 to remove from composite AND agreement.")
i_tw_app  = input.float(0.50, "Appetite (XLY/XLP, SPHB/SPLV)", minval = 0.0, step = 0.25, group = grp_tw, tooltip = "v3.1 block. Set 0 to remove from composite AND agreement.")
 
grp_ta = "Intraday Anchors"
i_add_pin   = input.float(1500, "ADD Pin Level (→ ±1)",       step = 100,  group = grp_ta, tooltip = "Net advancers-decliners pinned beyond ±this = full score. Classic trend-day territory.")
i_add_delta = input.float(1000, "ADD Δ-from-Open Norm",       step = 100,  group = grp_ta)
i_tick_norm = input.float(350,  "TICK Session-Avg Norm (→ ±1)", step = 25, group = grp_ta)
i_vold_pin  = input.float(4.0,  "Up/Down Volume Pin Ratio",   step = 0.5,  group = grp_ta, tooltip = "UVOL:DVOL at this ratio (or 1/this) = ±1. 4:1 is conviction.")
i_vixd_span = input.float(5.0,  "VIX Session %Chg Span (→ ∓1)", step = 0.5, group = grp_ta)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — STRATEGIC BLOCK WEIGHTS + OPTIONS
// ─────────────────────────────────────────────────────────────────────────
grp_b = "Strategic Block Weights"
i_wb_liq  = input.float(1.00, "Liquidity",        minval = 0.0, step = 0.25, group = grp_b)
i_wb_cred = input.float(1.25, "Credit",           minval = 0.0, step = 0.25, group = grp_b)
i_wb_vol  = input.float(1.00, "Volatility",       minval = 0.0, step = 0.25, group = grp_b)
i_wb_ca   = input.float(1.00, "Cross-Asset",      minval = 0.0, step = 0.25, group = grp_b)
i_wb_eq   = input.float(1.00, "Equity Appetite",  minval = 0.0, step = 0.25, group = grp_b)
i_wb_mac  = input.float(0.50, "Macro Pulse",      minval = 0.0, step = 0.25, group = grp_b)
 
grp_t = "Strategic Optional Factors"
i_use_btc = input.bool(true,  "Include Bitcoin (Cross-Asset block)", group = grp_t)
i_use_br  = input.bool(false, "Include Breadth (Equity block)",      group = grp_t)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — DATA SOURCES
// ─────────────────────────────────────────────────────────────────────────
grp_s = "Data Sources — Strategic"
i_sym_liq  = input.string("FRED:WALCL-FRED:RRPONTSYD-FRED:WTREGEN", "Net Liquidity (spread, weekly)", group = grp_s)
i_sym_dxy  = input.string("TVC:DXY",             "Dollar Index",              group = grp_s)
i_sym_oas  = input.string("FRED:BAMLH0A0HYM2",   "HY Credit Spread (OAS)",    group = grp_s)
i_sym_hyi  = input.string("AMEX:HYG/NASDAQ:IEF", "Credit Tape (HYG/IEF)",     group = grp_s)
i_sym_vix  = input.string("CBOE:VIX",            "Volatility Index",          group = grp_s)
i_sym_term = input.string("CBOE:VIX/CBOE:VIX3M", "Vol Term Structure",        group = grp_s)
i_sym_cg   = input.string("AMEX:CPER/AMEX:GLD",  "Copper/Gold",               group = grp_s)
i_sym_fx   = input.string("FX_IDC:AUDJPY",       "FX Risk Barometer",         group = grp_s)
i_sym_btc  = input.string("INDEX:BTCUSD",        "Crypto Sentinel",           group = grp_s)
i_sym_xy   = input.string("AMEX:XLY/AMEX:XLP",   "Discretionary/Staples",     group = grp_s)
i_sym_hb   = input.string("AMEX:SPHB/AMEX:SPLV", "High Beta/Low Vol",         group = grp_s)
i_sym_br   = input.string("USI:ADVDEC.US",       "Breadth (optional)",        group = grp_s)
i_sym_icsa = input.string("FRED:ICSA",           "Initial Claims (weekly)",   group = grp_s)
 
grp_si = "Data Sources — Intraday"
i_sym_add   = input.string("USI:ADVDEC.US",       "Advance/Decline Net",  group = grp_si, tooltip = "Alternates if unavailable: USI:ADVN.US-USI:DECL.US, INDEX:ADD.")
i_sym_tick  = input.string("USI:TICK",            "NYSE TICK",            group = grp_si, tooltip = "Alternates: USI:TICK.US, INDEX:TICK.")
i_sym_vold  = input.string("USI:UVOL/USI:DVOL",   "Up/Down Volume Ratio", group = grp_si, tooltip = "Alternates: USI:UVOL.US/USI:DVOL.US.")
i_sym_bench = input.string("AMEX:SPY",            "Benchmark (VWAP tape)", group = grp_si, tooltip = "Session VWAP structure is read from this symbol, keeping the indicator chart-independent.")
i_sectors   = input.string("AMEX:XLK,AMEX:XLF,AMEX:XLY,AMEX:XLI,AMEX:XLV,AMEX:XLE", "Participation Sectors (comma-sep)", group = grp_si, tooltip = "Each scored ±1 above/below its own session VWAP. Keep ≤ 8 — v3.1 uses ~31 of the 40-request budget at defaults. Cyclicals chosen deliberately: defensives above VWAP on risk-off days would pollute the directional read.")
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — VOLATILITY LEVEL ANCHORS (strategic)
// ─────────────────────────────────────────────────────────────────────────
grp_a = "Strategic Volatility Level Anchors"
i_vix_mid  = input.float(20.0, "VIX Neutral Level",       step = 0.5,  group = grp_a)
i_vix_span = input.float(8.0,  "VIX Span to ±1",          step = 0.5,  group = grp_a)
i_ts_mid   = input.float(0.95, "VIX/VIX3M Neutral Ratio", step = 0.01, group = grp_a)
i_ts_span  = input.float(0.10, "Term Span to ±1",         step = 0.01, group = grp_a)
i_lvl_wt   = input.float(0.30, "Level Weight in Vol Scores", minval = 0.0, maxval = 1.0, step = 0.05, group = grp_a)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS — DISPLAY
// ─────────────────────────────────────────────────────────────────────────
grp_d = "Display"
i_show_tbl    = input.bool(true,  "Show Factor Table",          group = grp_d)
i_tbl_pos     = input.string("Top Right", "Table Position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = grp_d)
i_show_tac    = input.bool(true,  "Plot Intraday Composite",    group = grp_d)
i_show_marks  = input.bool(true,  "Plot Alignment Markers",     group = grp_d)
i_show_blocks = input.bool(false, "Plot Strategic Block Scores", group = grp_d)
 
// ═════════════════════════════════════════════════════════════════════════
//  SHARED HELPERS
// ═════════════════════════════════════════════════════════════════════════
f_clamp(float _x) =>
    math.max(-1.0, math.min(1.0, _x))
 
f_tanh(float _x) =>
    float _z = math.max(-20.0, math.min(20.0, 2.0 * _x))
    float _e = math.exp(_z)
    (_e - 1.0) / (_e + 1.0)
 
// Movement score (strategic tier): direction + impulse + persistence,
// noise-scaled so one formula works on any series.
f_flow(float _s, simple int _fast, simple int _slow, simple int _imp, simple int _pers) =>
    float _sd  = ta.stdev(_s, _slow)
    float _chg = ta.change(_s)
    float _sdc = ta.stdev(_chg, _slow)
    float _gap = (ta.ema(_s, _fast) - ta.ema(_s, _slow)) / math.max(_sd, 1e-10)
    float _dir = f_tanh(1.5 * _gap)
    float _z   = ta.change(_s, _imp) / math.max(_sdc * math.sqrt(_imp), 1e-10)
    float _im  = f_tanh(0.8 * _z)
    float _sg  = _chg > 0 ? 1.0 : _chg < 0 ? -1.0 : 0.0
    float _pe  = math.sum(_sg, _pers) / _pers
    float _ws  = math.max(i_w_dir + i_w_imp + i_w_pers, 1e-10)
    f_clamp((i_w_dir * _dir + i_w_imp * _im + i_w_pers * _pe) / _ws)
 
// Non-repainting fetches: computed on the symbol's own timeframe,
// self-lagged to the last fully CLOSED bar.
f_daily(simple string _sym) =>
    request.security(_sym, "D", f_flow(close, i_fastD, i_slowD, i_impD, i_persD)[1], lookahead = barmerge.lookahead_off)
 
f_weekly(simple string _sym) =>
    request.security(_sym, "W", f_flow(close, i_fastW, i_slowW, i_impW, i_persW)[1], lookahead = barmerge.lookahead_off)
 
f_daily_lvl(simple string _sym) =>
    request.security(_sym, "D", [f_flow(close, i_fastD, i_slowD, i_impD, i_persD)[1], close[1]], lookahead = barmerge.lookahead_off)
 
// ═════════════════════════════════════════════════════════════════════════
//  STATE MACHINE  (one function, two independent instances)
//  _flat_on_na: intraday tier drops flat when its inputs vanish (market
//  closed / warmup); strategic tier freezes through data gaps instead.
// ═════════════════════════════════════════════════════════════════════════
f_machine(float _comp, float _agree, float _tin, float _tout, float _gate, float _buf, int _confirm, bool _reset, bool _flat_on_na) =>
    var int _run = 0
    var int _st  = 0
    if _reset
        _run := 0
        _st  := 0
    if _flat_on_na and na(_comp)
        _run := 0
        _st  := 0
    int _qual = na(_comp) ? 0 : _comp >= _tin and _agree >= _gate ? 1 : _comp <= -_tin and _agree >= _gate ? -1 : 0
    _run := _qual != 0 and _qual == nz(_qual[1]) ? _run + 1 : _qual != 0 ? 1 : 0
    if _st == 1 and (_comp <= _tout or _agree < _gate - _buf)
        _st := 0
    if _st == -1 and (_comp >= -_tout or _agree < _gate - _buf)
        _st := 0
    if _st == 0 and _qual != 0 and _run >= _confirm
        _st := _qual
    [_st, _qual, _run]
 
// ═════════════════════════════════════════════════════════════════════════
//  TIER 1 — STRATEGIC FACTOR SCORES  (+1 always = equity-bullish)
// ═════════════════════════════════════════════════════════════════════════
float s_netliq = f_weekly(i_sym_liq)
float s_dxy    = -1.0 * f_daily(i_sym_dxy)
float s_oas    = -1.0 * f_daily(i_sym_oas)
float s_hyief  = f_daily(i_sym_hyi)
 
[vixF, vixL] = f_daily_lvl(i_sym_vix)
float s_vix_lvl = f_clamp((i_vix_mid - vixL) / math.max(i_vix_span, 1e-10))
float s_vix     = (1.0 - i_lvl_wt) * (-1.0 * vixF) + i_lvl_wt * s_vix_lvl
 
[tsF, tsL] = f_daily_lvl(i_sym_term)
float s_ts_lvl = f_clamp((i_ts_mid - tsL) / math.max(i_ts_span, 1e-10))
float s_term   = (1.0 - i_lvl_wt) * (-1.0 * tsF) + i_lvl_wt * s_ts_lvl
 
float s_cg  = f_daily(i_sym_cg)
float s_fx  = f_daily(i_sym_fx)
float s_btc = i_use_btc ? f_daily(i_sym_btc) : na
float s_xy  = f_daily(i_sym_xy)
float s_hb  = f_daily(i_sym_hb)
float s_br  = i_use_br ? f_daily(i_sym_br) : na
float s_icsa = -1.0 * f_weekly(i_sym_icsa)
 
// ═════════════════════════════════════════════════════════════════════════
//  TIER 2 — SESSION-ANCHORED INTRADAY FUNCTIONS
//  (each runs inside its symbol's security context on i_tac_tf; every
//  return value is self-lagged [1] → last closed intraday bar only)
// ═════════════════════════════════════════════════════════════════════════
 
// Advance/Decline net: pinned level + build since the open
f_add_score() =>
    bool nd = timeframe.change("D")
    var float _o = na
    _o := nd or na(_o) ? close : _o
    float _sc = 0.6 * f_clamp(close / i_add_pin) + 0.4 * f_clamp((close - _o) / i_add_delta)
    _sc[1]
 
// TICK: session-average level + share of positive closes
f_tick_score() =>
    bool nd = timeframe.change("D")
    var float _cum = 0.0
    var int   _n   = 0
    var int   _pos = 0
    if nd
        _cum := close
        _n   := 1
        _pos := close > 0 ? 1 : 0
    else
        _cum += close
        _n   += 1
        _pos += close > 0 ? 1 : 0
    float _avg   = _cum / math.max(_n, 1)
    float _share = 2.0 * _pos / math.max(_n, 1) - 1.0
    float _sc = 0.6 * f_clamp(_avg / i_tick_norm) + 0.4 * _share
    _sc[1]
 
// Up/Down volume ratio (symbol is the UVOL/DVOL spread): log-mapped
f_vold_score() =>
    float _sc = f_clamp(math.log(math.max(close, 1e-6)) / math.log(i_vold_pin))
    _sc[1]
 
// Benchmark session tape: VWAP distance + side-share + VWAP slope.
// Also returns session bar count (warmup gate) and bar time (staleness).
f_bench() =>
    bool nd = timeframe.change("D")
    var int _n  = 0
    var int _ab = 0
    _n := nd ? 1 : _n + 1
    float _vw  = ta.vwap
    float _atr = ta.atr(14)
    _ab := nd ? (close > _vw ? 1 : 0) : _ab + (close > _vw ? 1 : 0)
    float _dist  = f_tanh(0.8 * (close - _vw) / math.max(_atr, 1e-10))
    float _share = 2.0 * _ab / math.max(_n, 1) - 1.0
    float _vsl   = f_tanh(3.0 * (_vw - _vw[3]) / math.max(_atr, 1e-10))
    float _sc = 0.5 * _dist + 0.3 * _share + 0.2 * _vsl
    [_sc[1], _n[1], time]
 
// Sector vs its own session VWAP → ±1
f_pvwap() =>
    float _v = close > ta.vwap ? 1.0 : -1.0
    _v[1]
 
// VIX: % change vs prior session close (sign-stable intraday risk tell)
f_vix_sess() =>
    bool nd = timeframe.change("D")
    var float _pdc = na
    _pdc := nd or na(_pdc) ? close[1] : _pdc
    float _pct = na(_pdc) or _pdc == 0 ? 0.0 : close / _pdc - 1.0
    float _sc = f_clamp(-_pct / (i_vixd_span / 100.0))
    _sc[1]
 
// GENERIC SESSION FLOW [v3.1] — the scorer for everything else that trades
// intraday: return vs prior session close, ÷ the instrument's OWN typical
// full-session move (rolling i_sf_days sessions), √time-of-session adjusted
// so an on-pace move scores ≈ tanh(i_sf_gain) at any point of the session.
// No volume/VWAP needed → works on ratio spreads. na until 5 completed
// sessions of scale data exist. Session length is learned per-instrument,
// so 24h symbols (DXY/FX/BTC) mature early and carry the overnight tone
// into the equity open. Self-lagged, non-repainting.
f_sess_flow() =>
    bool nd = timeframe.change("D")
    var float   _pdc = na
    var int     _n   = 0
    var float[] _mv  = array.new_float()
    var float[] _ln  = array.new_float()
    if nd
        if not na(_pdc) and _pdc != 0 and _n > 0
            array.push(_mv, math.abs(close[1] / _pdc - 1.0))
            array.push(_ln, _n)
            if array.size(_mv) > i_sf_days
                array.shift(_mv)
                array.shift(_ln)
        _pdc := close[1]
        _n   := 1
    else
        _n += 1
    float _scale = array.size(_mv) >= 5 ? array.avg(_mv) : na
    float _tlen  = array.size(_ln) >= 5 ? array.avg(_ln) : na
    float _ret   = na(_pdc) or _pdc == 0 ? na : close / _pdc - 1.0
    float _frac  = na(_tlen) or _tlen <= 0 ? na : math.min(1.0, math.max(_n / _tlen, 1.0 / _tlen))
    float _sc    = na(_ret) or na(_scale) or _scale <= 0 or na(_frac) ? na : f_tanh(i_sf_gain * _ret / (_scale * math.sqrt(_frac)))
    _sc[1]
 
// ── intraday fetches (all gated by i_use_tac; dynamic requests)
float t_add  = i_use_tac ? request.security(i_sym_add,  i_tac_tf, f_add_score(),  lookahead = barmerge.lookahead_off) : na
float t_tick = i_use_tac ? request.security(i_sym_tick, i_tac_tf, f_tick_score(), lookahead = barmerge.lookahead_off) : na
float t_vold = i_use_tac ? request.security(i_sym_vold, i_tac_tf, f_vold_score(), lookahead = barmerge.lookahead_off) : na
float t_vixd = i_use_tac ? request.security(i_sym_vix,  i_tac_tf, f_vix_sess(),   lookahead = barmerge.lookahead_off) : na
 
// v3.1 extended factors — session-flow scored, +1 = equity-bullish
float t_term = i_use_tac and i_it_term  ? -1.0 * request.security(i_sym_term, i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
float t_dxy  = i_use_tac and i_it_dxy   ? -1.0 * request.security(i_sym_dxy,  i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
float t_cg   = i_use_tac and i_it_cg    ? request.security(i_sym_cg,  i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
float t_fx   = i_use_tac and i_use_xfx  ? request.security(i_sym_fx,  i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
float t_btc  = i_use_tac and i_use_xbtc ? request.security(i_sym_btc, i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
float t_hyi  = i_use_tac and i_it_hyi   ? request.security(i_sym_hyi, i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
float t_xy   = i_use_tac and i_it_xy    ? request.security(i_sym_xy,  i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
float t_hb   = i_use_tac and i_it_hb    ? request.security(i_sym_hb,  i_tac_tf, f_sess_flow(), lookahead = barmerge.lookahead_off) : na
 
float tb_tape = na
int   sess_n  = na
int   bench_t = na
if i_use_tac
    [b1_, b2_, b3_] = request.security(i_sym_bench, i_tac_tf, f_bench(), lookahead = barmerge.lookahead_off)
    tb_tape := b1_
    sess_n  := b2_
    bench_t := b3_
 
var string[] sec_arr = str.split(str.replace_all(i_sectors, " ", ""), ",")
float _psum = 0.0
int   _pcnt = 0
if i_use_tac and array.size(sec_arr) > 0
    for _k = 0 to array.size(sec_arr) - 1
        string _sy = array.get(sec_arr, _k)
        float _pv = request.security(_sy, i_tac_tf, f_pvwap(), lookahead = barmerge.lookahead_off)
        if not na(_pv)
            _psum += _pv
            _pcnt += 1
float tb_part = _pcnt > 0 ? _psum / _pcnt : na
 
// ═════════════════════════════════════════════════════════════════════════
//  BLOCK AGGREGATION
// ═════════════════════════════════════════════════════════════════════════
f_pair(float _a, float _b) =>
    float _s = 0.0
    int   _n = 0
    if not na(_a)
        _s += _a
        _n += 1
    if not na(_b)
        _s += _b
        _n += 1
    _n > 0 ? _s / _n : na
 
f_trio(float _a, float _b, float _c) =>
    float _s = 0.0
    int   _n = 0
    if not na(_a)
        _s += _a
        _n += 1
    if not na(_b)
        _s += _b
        _n += 1
    if not na(_c)
        _s += _c
        _n += 1
    _n > 0 ? _s / _n : na
 
// v3.1: n-wide na-safe mean for the expanded cross-asset block
f_navg(float[] _v) =>
    float _s  = 0.0
    int   _n  = 0
    int   _sz = array.size(_v)
    if _sz > 0
        for _i = 0 to _sz - 1
            float _x = array.get(_v, _i)
            if not na(_x)
                _s += _x
                _n += 1
    _n > 0 ? _s / _n : na
 
// strategic blocks (6)
float b_liq  = f_pair(s_netliq, s_dxy)
float b_cred = f_pair(s_oas, s_hyief)
float b_vol  = f_pair(s_vix, s_term)
float b_ca   = f_trio(s_cg, s_fx, s_btc)
float b_eq   = f_trio(s_xy, s_hb, s_br)
float b_mac  = s_icsa
 
// intraday blocks (7) — v3.1: Volatility, Credit, Appetite added; VIX moved
// from Cross-Asset into Volatility. Any all-na block returns na and drops
// out of BOTH the composite and the agreement count (bit-exact v3.0 revert
// when the extended factors are toggled off).
float tb_int  = f_trio(t_add, t_tick, t_vold)
float tb_vol  = f_pair(t_vixd, t_term)
float tb_x    = f_navg(array.from(t_dxy, t_cg, t_fx, t_btc))
float tb_cred = t_hyi
float tb_app  = f_pair(t_xy, t_hb)
 
// ═════════════════════════════════════════════════════════════════════════
//  COMPOSITES + BLOCK AGREEMENT  (per tier)
// ═════════════════════════════════════════════════════════════════════════
// strategic
float[] bsA = array.from(b_liq, b_cred, b_vol, b_ca, b_eq, b_mac)
float[] bwA = array.from(i_wb_liq, i_wb_cred, i_wb_vol, i_wb_ca, i_wb_eq, i_wb_mac)
 
float _sv = 0.0
float _sw = 0.0
for _i = 0 to 5
    float _b = array.get(bsA, _i)
    float _w = array.get(bwA, _i)
    if not na(_b) and _w > 0
        _sv += _b * _w
        _sw += _w
float raw_comp = _sw > 0 ? _sv / _sw : na
float comp     = ta.ema(raw_comp, i_smooth)
 
int _agree = 0
int _act   = 0
float _cs  = math.sign(nz(comp))
for _i = 0 to 5
    float _b = array.get(bsA, _i)
    float _w = array.get(bwA, _i)
    if not na(_b) and _w > 0
        _act += 1
        if math.abs(_b) >= i_dead and math.sign(_b) == _cs
            _agree += 1
float agree_pct = _act > 0 ? _agree * 1.0 / _act : 0.0
 
// intraday — 7 blocks
float[] tsA = array.from(tb_int, tb_tape, tb_part, tb_vol, tb_x, tb_cred, tb_app)
float[] twA = array.from(i_tw_int, i_tw_tape, i_tw_part, i_tw_vol, i_tw_x, i_tw_cred, i_tw_app)
 
float _tv = 0.0
float _tw = 0.0
for _i = 0 to 6
    float _b = array.get(tsA, _i)
    float _w = array.get(twA, _i)
    if not na(_b) and _w > 0
        _tv += _b * _w
        _tw += _w
float raw_tac  = _tw > 0 ? _tv / _tw : na
float tac_comp = ta.ema(raw_tac, i_smooth)
 
int _tagree = 0
int _tact   = 0
float _tcs  = math.sign(nz(tac_comp))
for _i = 0 to 6
    float _b = array.get(tsA, _i)
    float _w = array.get(twA, _i)
    if not na(_b) and _w > 0
        _tact += 1
        if math.abs(_b) >= i_dead and math.sign(_b) == _tcs
            _tagree += 1
float tac_agree = _tact > 0 ? _tagree * 1.0 / _tact : 0.0
 
// ═════════════════════════════════════════════════════════════════════════
//  SESSION GATES + STATE MACHINES + ALIGNMENT
// ═════════════════════════════════════════════════════════════════════════
int  tf_sec     = timeframe.in_seconds(i_tac_tf)
bool mkt_open   = i_use_tac and not na(bench_t) and (time - bench_t) <= 3 * tf_sec * 1000
bool sess_ready = nz(sess_n, 0) >= i_min_bars
bool tac_ok     = i_use_tac and mkt_open and sess_ready
bool tac_reset  = nz(sess_n, 0) < nz(sess_n[1], 0)          // new session detected
 
float tac_comp_g = tac_ok ? tac_comp : na
 
[regime, s_qual, s_qrun] = f_machine(comp,       agree_pct, i_t_in,  i_t_out,  i_gate,    i_agr_buf, i_confirm,    false,     false)
[tac_st, t_qual, t_qrun] = f_machine(tac_comp_g, tac_agree, i_tt_in, i_tt_out, i_tt_gate, i_agr_buf, i_tt_confirm, tac_reset, true)
 
var int regime_bars = 0
regime_bars := regime != 0 and regime == nz(regime[1]) ? regime_bars + 1 : regime != 0 ? 1 : 0
 
int align_dir   = regime != 0 and tac_st == regime  ? regime : 0    // easy² mode
int counter_dir = regime != 0 and tac_st == -regime ? regime : 0    // pullback / bounce
 
bool bull_start = regime == 1  and nz(regime[1]) != 1
bool bull_end   = regime != 1  and nz(regime[1]) == 1
bool bear_start = regime == -1 and nz(regime[1]) != -1
bool bear_end   = regime != -1 and nz(regime[1]) == -1
bool tac_up_start = tac_st == 1  and nz(tac_st[1]) != 1
bool tac_up_end   = tac_st != 1  and nz(tac_st[1]) == 1
bool tac_dn_start = tac_st == -1 and nz(tac_st[1]) != -1
bool tac_dn_end   = tac_st != -1 and nz(tac_st[1]) == -1
bool a_bull_start = align_dir == 1  and nz(align_dir[1]) != 1
bool a_bull_end   = align_dir != 1  and nz(align_dir[1]) == 1
bool a_bear_start = align_dir == -1 and nz(align_dir[1]) != -1
bool a_bear_end   = align_dir != -1 and nz(align_dir[1]) == -1
bool pullback_start = counter_dir == 1  and nz(counter_dir[1]) != 1
bool bounce_start   = counter_dir == -1 and nz(counter_dir[1]) != -1
 
bool tf_warn = i_use_tac and timeframe.in_seconds(timeframe.period) > tf_sec
 
// ═════════════════════════════════════════════════════════════════════════
//  PLOTTING
// ═════════════════════════════════════════════════════════════════════════
color c_bull = #00C853
color c_bear = #FF1744
color c_neut = #78909C
color c_warn = #FFB300
 
hline( 0.0, "Zero", color.new(color.gray, 55), hline.style_dotted)
hline( 1.0, "+1",   color.new(color.gray, 90), hline.style_dotted)
hline(-1.0, "-1",   color.new(color.gray, 90), hline.style_dotted)
 
plot( i_tt_in,  "Intraday Entry +", color.new(c_bull, 78), 1)
plot(-i_tt_in,  "Intraday Entry -", color.new(c_bear, 78), 1)
 
// strategic composite columns: saturation encodes the alignment ladder
color comp_col = align_dir == 1 ? c_bull : align_dir == -1 ? c_bear :
     regime == 1 ? color.new(c_bull, 42) : regime == -1 ? color.new(c_bear, 42) :
     s_qual == 1 ? color.new(c_bull, 65) : s_qual == -1 ? color.new(c_bear, 65) :
     color.new(c_neut, 35)
plot(comp, "Strategic Composite", comp_col, 1, plot.style_columns)
 
// intraday composite line — the session's trend-day read
color tac_col = not tac_ok ? color.new(color.gray, 65) :
     tac_st == 1 ? c_bull : tac_st == -1 ? c_bear : color.new(#ECEFF1, 30)
plot(i_use_tac and i_show_tac ? tac_comp : na, "Intraday Composite", tac_col, 2)
 
// markers: solid dot = easy² mode, x = intraday counter-flow inside a regime
plotshape(i_show_marks and align_dir == 1,    "Easy² Bull",    shape.circle, location.top,    color.new(c_bull, 0),  size = size.tiny)
plotshape(i_show_marks and align_dir == -1,   "Easy² Bear",    shape.circle, location.bottom, color.new(c_bear, 0),  size = size.tiny)
plotshape(i_show_marks and counter_dir == 1,  "Bull Pullback", shape.xcross, location.top,    color.new(c_warn, 20), size = size.tiny)
plotshape(i_show_marks and counter_dir == -1, "Bear Bounce",   shape.xcross, location.bottom, color.new(c_warn, 20), size = size.tiny)
 
// optional strategic block diagnostics
plot(i_show_blocks ? b_liq  : na, "Liquidity",       color.new(#2196F3, 25), 1)
plot(i_show_blocks ? b_cred : na, "Credit",          color.new(#FF9800, 25), 1)
plot(i_show_blocks ? b_vol  : na, "Volatility",      color.new(#E91E63, 25), 1)
plot(i_show_blocks ? b_ca   : na, "Cross-Asset",     color.new(#4CAF50, 25), 1)
plot(i_show_blocks ? b_eq   : na, "Equity Appetite", color.new(#00BCD4, 25), 1)
plot(i_show_blocks ? b_mac  : na, "Macro Pulse",     color.new(#9C27B0, 25), 1)
 
// background: deepest tint = easy² mode, soft tint = intraday state alone,
// faint tint = strategic regime alone
bgcolor(align_dir == 1 ? color.new(c_bull, 87) : align_dir == -1 ? color.new(c_bear, 87) :
     tac_st == 1 ? color.new(c_bull, 93) : tac_st == -1 ? color.new(c_bear, 93) :
     regime == 1 ? color.new(c_bull, 96) : regime == -1 ? color.new(c_bear, 96) : na, title = "State Tint")
bgcolor(a_bull_start ? color.new(c_bull, 80) : a_bear_start ? color.new(c_bear, 80) : na, title = "Easy² Entry Flash")
 
// live status label
var label lb = na
if barstate.islast
    string tac_word = not i_use_tac ? "" :
         not mkt_open ? " · MKT CLOSED" :
         not sess_ready ? " · WARMUP " + str.tostring(nz(sess_n, 0)) + "/" + str.tostring(i_min_bars) :
         tac_st == 1 ? " · INTRADAY EASY UP" : tac_st == -1 ? " · INTRADAY EASY DOWN" : " · session mixed"
    string st_txt = align_dir == 1 ? "EASY² BULL" : align_dir == -1 ? "EASY² BEAR" :
         counter_dir == 1 ? "BULL · PULLBACK" : counter_dir == -1 ? "BEAR · BOUNCE" :
         regime == 1 ? "EASY BULL" : regime == -1 ? "EASY BEAR" : "NO EDGE"
    string txt = st_txt + "  " + (na(comp) ? "—" : str.tostring(comp, "0.00")) +
         (i_use_tac and not na(tac_comp) ? " · tac " + str.tostring(tac_comp, "0.00") : "") +
         tac_word + (tf_warn ? " ⚠TF" : "")
    color lc = align_dir != 0 ? (align_dir == 1 ? c_bull : c_bear) :
         counter_dir != 0 ? c_warn :
         tac_st == 1 ? c_bull : tac_st == -1 ? c_bear :
         regime == 1 ? c_bull : regime == -1 ? c_bear : c_neut
    label.delete(lb)
    lb := label.new(bar_index, nz(comp), txt, style = label.style_label_left,
         color = color.new(lc, 25), textcolor = color.white, size = size.small)
 
// ═════════════════════════════════════════════════════════════════════════
//  FACTOR TABLE
// ═════════════════════════════════════════════════════════════════════════
f_pos(string _p) =>
    _p == "Top Left" ? position.top_left : _p == "Bottom Left" ? position.bottom_left :
     _p == "Bottom Right" ? position.bottom_right : position.top_right
 
f_fmt(float _x) =>
    na(_x) ? "—" : str.tostring(_x, "0.00")
 
f_arrow(float _x) =>
    na(_x) ? "—" : _x >= 0.15 ? "▲" : _x <= -0.15 ? "▼" : "→"
 
f_scol(float _x) =>
    na(_x) ? color.new(color.gray, 30) : _x >= 0.15 ? c_bull : _x <= -0.15 ? c_bear : c_neut
 
var table tbl = table.new(f_pos(i_tbl_pos), 3, 46, bgcolor = color.new(#101418, 12),
     border_width = 1, border_color = color.new(color.gray, 82))
 
f_row(int _r, string _name, float _sc, bool _hdr) =>
    if _hdr
        table.cell(tbl, 0, _r, _name, text_color = color.new(color.white, 5), text_size = size.tiny,
             text_halign = text.align_left, text_formatting = text.format_bold, bgcolor = color.new(#263238, 25))
        table.cell(tbl, 1, _r, f_fmt(_sc), text_color = f_scol(_sc), text_size = size.tiny,
             text_halign = text.align_right, text_formatting = text.format_bold, bgcolor = color.new(#263238, 25))
        table.cell(tbl, 2, _r, f_arrow(_sc), text_color = f_scol(_sc), text_size = size.tiny,
             text_halign = text.align_center, bgcolor = color.new(#263238, 25))
    else
        table.cell(tbl, 0, _r, _name, text_color = color.new(#B0BEC5, 10), text_size = size.tiny,
             text_halign = text.align_left)
        table.cell(tbl, 1, _r, f_fmt(_sc), text_color = f_scol(_sc), text_size = size.tiny,
             text_halign = text.align_right)
        table.cell(tbl, 2, _r, f_arrow(_sc), text_color = f_scol(_sc), text_size = size.tiny,
             text_halign = text.align_center)
 
f_info(int _r, string _name, string _val, string _mark, color _vc) =>
    table.cell(tbl, 0, _r, _name, text_color = color.new(#B0BEC5, 10), text_size = size.tiny, text_halign = text.align_left)
    table.cell(tbl, 1, _r, _val,  text_color = _vc, text_size = size.tiny, text_halign = text.align_right)
    table.cell(tbl, 2, _r, _mark, text_color = _vc, text_size = size.tiny, text_halign = text.align_center)
 
if i_show_tbl and barstate.islast
    table.cell(tbl, 0, 0, "EMO v3.1 · RISK FLOW", text_color = color.white, text_size = size.tiny,
         text_halign = text.align_left, text_formatting = text.format_bold)
    table.cell(tbl, 1, 0, "Score", text_color = color.new(color.gray, 20), text_size = size.tiny, text_halign = text.align_right)
    table.cell(tbl, 2, 0, "Dir",   text_color = color.new(color.gray, 20), text_size = size.tiny, text_halign = text.align_center)
 
    f_row( 1, "LIQUIDITY",           b_liq,    true)
    f_row( 2, "  Net Liquidity ᵂ",   s_netliq, false)
    f_row( 3, "  Dollar ⁻",          s_dxy,    false)
    f_row( 4, "CREDIT",              b_cred,   true)
    f_row( 5, "  HY OAS ⁻",          s_oas,    false)
    f_row( 6, "  HYG/IEF",           s_hyief,  false)
    f_row( 7, "VOLATILITY",          b_vol,    true)
    f_row( 8, "  VIX ⁻",             s_vix,    false)
    f_row( 9, "  VIX/VIX3M ⁻",       s_term,   false)
    f_row(10, "CROSS-ASSET",         b_ca,     true)
    f_row(11, "  Copper/Gold",       s_cg,     false)
    f_row(12, "  AUD/JPY",           s_fx,     false)
    f_row(13, i_use_btc ? "  Bitcoin" : "  Bitcoin (off)", s_btc, false)
    f_row(14, "EQUITY APPETITE",     b_eq,     true)
    f_row(15, "  XLY/XLP",           s_xy,     false)
    f_row(16, "  HiBeta/LoVol",      s_hb,     false)
    f_row(17, i_use_br ? "  Breadth" : "  Breadth (off)",  s_br,  false)
    f_row(18, "MACRO PULSE",         b_mac,    true)
    f_row(19, "  Claims ⁻ ᵂ",        s_icsa,   false)
 
    string reg_txt = regime == 1 ? "EASY BULL" : regime == -1 ? "EASY BEAR" : "NO EDGE"
    color  reg_col = regime == 1 ? c_bull : regime == -1 ? c_bear : c_neut
    f_row(20, "STRATEGIC (D/W)", comp, true)
    f_info(21, "  agreement", str.tostring(_agree) + "/" + str.tostring(_act), agree_pct >= i_gate ? "✓" : "✗", agree_pct >= i_gate ? c_bull : color.new(color.gray, 15))
    f_info(22, "  regime", reg_txt, regime != 0 ? str.tostring(regime_bars) + "b" : s_qual != 0 ? str.tostring(s_qrun) + "/" + str.tostring(i_confirm) : "·", reg_col)
 
    f_row(23, "INTRADAY (" + i_tac_tf + (tf_warn ? " ⚠" : "") + ")", tac_comp, true)
    f_row(24, "INTERNALS",           tb_int,  true)
    f_row(25, "  Adv/Decl",          t_add,   false)
    f_row(26, "  TICK",              t_tick,  false)
    f_row(27, "  Up/Down Vol",       t_vold,  false)
    f_row(28, "TAPE (VWAP)",         tb_tape, true)
    f_row(29, "PARTICIPATION",       tb_part, true)
    f_row(30, "VOLATILITY",          tb_vol,  true)
    f_row(31, "  VIX Sess ⁻",        t_vixd,  false)
    f_row(32, i_it_term ? "  VIX/VIX3M ⁻" : "  VIX/VIX3M (off)", t_term, false)
    f_row(33, "CROSS-ASSET",         tb_x,    true)
    f_row(34, i_it_dxy  ? "  Dollar ⁻"     : "  Dollar (off)",      t_dxy, false)
    f_row(35, i_it_cg   ? "  Copper/Gold"  : "  Copper/Gold (off)", t_cg,  false)
    f_row(36, i_use_xfx ? "  AUD/JPY"      : "  AUD/JPY (off)",     t_fx,  false)
    f_row(37, i_use_xbtc ? "  Bitcoin"     : "  Bitcoin (off)",     t_btc, false)
    f_row(38, "CREDIT",              tb_cred, true)
    f_row(39, i_it_hyi  ? "  HYG/IEF"      : "  HYG/IEF (off)",     t_hyi, false)
    f_row(40, "APPETITE",            tb_app,  true)
    f_row(41, i_it_xy   ? "  XLY/XLP"      : "  XLY/XLP (off)",     t_xy,  false)
    f_row(42, i_it_hb   ? "  HiBeta/LoVol" : "  HiBeta/LoVol (off)", t_hb, false)
    f_info(43, "  agreement", str.tostring(_tagree) + "/" + str.tostring(_tact), tac_agree >= i_tt_gate ? "✓" : "✗", tac_agree >= i_tt_gate ? c_bull : color.new(color.gray, 15))
    string tac_txt2 = not i_use_tac ? "OFF" : not mkt_open ? "CLOSED" : not sess_ready ? "WARMUP " + str.tostring(nz(sess_n, 0)) + "/" + str.tostring(i_min_bars) :
         tac_st == 1 ? "EASY UP" : tac_st == -1 ? "EASY DOWN" : "MIXED"
    color tac_col2 = not i_use_tac or not mkt_open ? color.new(color.gray, 40) : tac_st == 1 ? c_bull : tac_st == -1 ? c_bear : c_neut
    f_info(44, "  session", tac_txt2, tac_ok and t_qual != 0 and tac_st == 0 ? str.tostring(t_qrun) + "/" + str.tostring(i_tt_confirm) : "·", tac_col2)
 
    string al_txt = align_dir == 1 ? "EASY² BULL" : align_dir == -1 ? "EASY² BEAR" :
         counter_dir == 1 ? "PULLBACK" : counter_dir == -1 ? "BEAR BOUNCE" :
         regime != 0 ? "REGIME ONLY" : "—"
    color al_col = align_dir == 1 ? c_bull : align_dir == -1 ? c_bear :
         counter_dir != 0 ? c_warn : regime != 0 ? c_neut : color.new(color.gray, 40)
    f_info(45, "ALIGNMENT", al_txt, align_dir != 0 ? "●" : counter_dir != 0 ? "✕" : "·", al_col)
 
// ═════════════════════════════════════════════════════════════════════════
//  ALERTS
// ═════════════════════════════════════════════════════════════════════════
alertcondition(bull_start,     "EMO: Easy Bull begins",        "EMO v3.1 — strategic regime → EASY BULL")
alertcondition(bull_end,       "EMO: Easy Bull ends",          "EMO v3.1 — strategic EASY BULL ended")
alertcondition(bear_start,     "EMO: Easy Bear begins",        "EMO v3.1 — strategic regime → EASY BEAR")
alertcondition(bear_end,       "EMO: Easy Bear ends",          "EMO v3.1 — strategic EASY BEAR ended")
alertcondition(tac_up_start,   "EMO: Intraday Easy Up begins", "EMO v3.1 — session flagged INTRADAY EASY UP")
alertcondition(tac_up_end,     "EMO: Intraday Easy Up ends",   "EMO v3.1 — INTRADAY EASY UP ended")
alertcondition(tac_dn_start,   "EMO: Intraday Easy Down begins", "EMO v3.1 — session flagged INTRADAY EASY DOWN")
alertcondition(tac_dn_end,     "EMO: Intraday Easy Down ends", "EMO v3.1 — INTRADAY EASY DOWN ended")
alertcondition(a_bull_start,   "EMO: EASY² Bull begins",       "EMO v3.1 — regime + intraday aligned → EASY² BULL")
alertcondition(a_bull_end,     "EMO: EASY² Bull ends",         "EMO v3.1 — EASY² BULL alignment ended")
alertcondition(a_bear_start,   "EMO: EASY² Bear begins",       "EMO v3.1 — regime + intraday aligned → EASY² BEAR")
alertcondition(a_bear_end,     "EMO: EASY² Bear ends",         "EMO v3.1 — EASY² BEAR alignment ended")
alertcondition(pullback_start, "EMO: Pullback in bull regime", "EMO v3.1 — intraday flow against EASY BULL (pullback)")
alertcondition(bounce_start,   "EMO: Bounce in bear regime",   "EMO v3.1 — intraday flow against EASY BEAR (bounce)")

← 返回列表