PT HTF Regime - MTF Trend/Range Ribbons & Invalidation Levels

MoAlqaq · study · 981 行 · 点赞 16 · 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/
// © Mo Alqaq
//@version=6
//
// ════════════════════════════════════════════════════════════════════════════
//  Pro Trader HTF Regime V26.01 - By: Mo Alqaq
//  Multi-timeframe regime strip: shows the regime of two higher timeframes
//  on the execution chart (5M → 15M + 1H, 15M → 1H + 4H).
//  States: TREND UP / TREND DOWN / RANGE / UNDECIDED (strong / weak shade).
//  Per HTF trend: marker, invalidation level (text + dotted line), alerts on
//  15M + 1H alignment, status panel (Compact / Detailed), optional 1D row.
//  Engine ported from PT Regime Switch V26.01 (archived 2026-10-28).
//  Non-repainting: HTF values come from the last CLOSED HTF bar only.
// ════════════════════════════════════════════════════════════════════════════
//
//  VERSION HISTORY
//  V26.01 (2026-10-29) — first public release.
//
//  CREDITS (public-domain methods, own implementation)
//  Efficiency Ratio — Perry Kaufman · Choppiness Index — E.W. Dreiss
//  ADX / DMI — J. Welles Wilder · Hurst exponent via rescaled range (R/S),
//  with the Anis–Lloyd / Peters expected-R/S correction.
//
indicator("PT HTF Regime - MTF Trend/Range Ribbons & Invalidation Levels",
     shorttitle         = "PT HTF Regime",
     overlay            = true,
     scale              = scale.none,   // own hidden scale → ribbons sit at the bottom of the price pane
     max_labels_count   = 500,
     max_bars_back      = 1500)
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 1A — CONSTANTS
// ════════════════════════════════════════════════════════════════════════════
 
// Regime states
const int ST_UNDECIDED  = 0
const int ST_TREND_UP   = 1
const int ST_TREND_DOWN = 2
const int ST_RANGE      = 3
 
// Input group names
const string GRP_GEN  = "① General"
const string GRP_HTF  = "② Higher timeframes"
const string GRP_VIS  = "③ Ribbons & markers"
const string GRP_DASH = "④ Status panel & legend"
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 1B — INPUTS (user-facing only)
// ════════════════════════════════════════════════════════════════════════════
 
// ── ① General ───────────────────────────────────────────────────────────────
i_preset    = input.string("Auto", "Asset preset", options = ["Auto", "Gold", "Crypto"], group = GRP_GEN,
     tooltip = "Auto: Crypto when the symbol type is crypto, otherwise Gold.\nCrypto uses slightly lower trend thresholds for ER and ADX.")
i_speed     = input.string("Balanced", "Responsiveness", options = ["Balanced", "Fast", "Standard"], group = GRP_GEN,
     tooltip = "How quickly each higher timeframe changes regime.\nBalanced (default): suits most charts.\nFast: reacts sooner, more flicker.\nStandard: slower, steadier labels.")
 
// ── ② Higher timeframes ────────────────────────────────────────────────────
i_htfAuto   = input.bool(true,  "Auto HTFs", group = GRP_HTF,
     tooltip = "One and two steps above the chart:\n≤5M → 15M + 1H\n15M → 1H + 4H\n1H → 4H + 1D\n4H → 1D + 1W\n1D → 1W + 1M")
i_htf1TF    = input.timeframe("15", "Manual HTF 1 (when Auto is off)", group = GRP_HTF,
     tooltip = "One step up. Must be higher than the chart timeframe.")
i_htf2On    = input.bool(true,  "Show HTF 2", group = GRP_HTF)
i_htf2TF    = input.timeframe("60", "Manual HTF 2 (when Auto is off)", group = GRP_HTF,
     tooltip = "Two steps up. Must be higher than HTF 1.")
i_dailyOn   = input.bool(false, "Daily bias row in the panel", group = GRP_HTF,
     tooltip = "Adds a 1D row to the status panel (no ribbon). Context only: not part of the alignment or alerts.\nRuns the engine a third time, so the chart loads a little slower.\nHidden when HTF 2 is already 1D or higher.")
 
// ── ③ Ribbons & markers ────────────────────────────────────────────────────
i_ribbonOn  = input.bool(true,  "Show ribbons", group = GRP_VIS)
i_ribbonPct = input.float(11.0,  "Ribbon block height, % of pane", 3, 25, 0.5, group = GRP_VIS,
     tooltip = "Raise it if the timeframe tags overlap on a short chart window.")
i_tfTags    = input.bool(true,  "Timeframe tags at the ribbon end", group = GRP_VIS)
i_invLines  = input.bool(true,  "HTF invalidation levels (on the marker rows)", group = GRP_VIS,
     tooltip = "Each shown HTF trend gets a dotted line on its marker row, with text at its start, e.g. \"15M Downtrend @ 4062.84\".\n@ = invalidation level: a close below it (uptrend) or above it (downtrend) ends that trend. Set when the trend starts; it does not trail.\nLast 30 days: line and text. Older trends: hover the marker to see the level.")
i_markers   = input.bool(true,  "Regime-change markers", group = GRP_VIS, inline = "mk")
i_mkMinBars = input.int(2,      "after HTF bars", 1, 5, group = GRP_VIS, inline = "mk",
     tooltip = "A marker is drawn once the new HTF regime has lasted this many closed HTF bars, so one-bar blips get no marker.")
i_colUp     = input.color(color.new(#1D9E75, 0), "Trend up",   group = GRP_VIS, inline = "c1")
i_colDown   = input.color(color.new(#E24B4A, 0), "Trend down", group = GRP_VIS, inline = "c1")
i_colRange  = input.color(color.new(#BA7517, 0), "Range",      group = GRP_VIS, inline = "c2")
i_colUnd    = input.color(color.new(#888780, 0), "Undecided",  group = GRP_VIS, inline = "c2")
 
// ── ④ Status panel & legend ────────────────────────────────────────────────
i_dashOn    = input.bool(true,  "Show status panel", group = GRP_DASH, inline = "db")
i_dashPos   = input.string("Top Right", "", options = ["Top Right", "Top Left", "Top Center", "Middle Right", "Middle Left", "Bottom Right", "Bottom Left"],
     group = GRP_DASH, inline = "db")
i_dashMode  = input.string("Compact", "Panel mode", options = ["Compact", "Detailed"], group = GRP_DASH,
     tooltip = "Compact: one line per timeframe (state, strength, time held) and the alignment.\nDetailed: adds a header, bars and time held, and a Next row showing a regime change that is building but not yet confirmed.")
i_legend    = input.bool(false, "Show legend", group = GRP_DASH, inline = "leg")
i_legendPos = input.string("Bottom Right", "", options = ["Top Right", "Top Left", "Top Center", "Middle Right", "Middle Left", "Bottom Right", "Bottom Left"],
     group = GRP_DASH, inline = "leg")
i_dashSize  = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = GRP_DASH,
     tooltip = "Applies to the status panel and the legend.")
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 1B+ — ENGINE SETTINGS (fixed)
//  Kept fixed so the settings page stays short. Advanced users can change
//  them here; the defaults are the values the indicator was tested with.
// ════════════════════════════════════════════════════════════════════════════
 
// Detectors: enabled + vote weight
const bool  e_erOn        = true
const float e_erW         = 1.0
const bool  e_huOn        = true
const float e_huW         = 0.5
const bool  e_ciOn        = true
const float e_ciW         = 1.0
const bool  e_adxOn       = true
const float e_adxW        = 1.0
 
// Voting & confidence
const int   e_strongConf  = 60      // strong regime at confidence ≥ 60 …
const int   e_strongBand  = 10      // … turns weak only below 50
const float e_dirMin      = 0.25    // TREND needs |D| ≥ this
const bool  e_useLinreg   = false   // add linear-regression slope to direction
const int   e_linregLen   = 20
const int   e_atrLen      = 14
 
// Hysteresis
const float e_enterT      = 0.30
const float e_exitT       = 0.10
const int   e_exitConfirm = 1
const int   e_resumeBars  = 12
const int   e_fastDirLen  = 8
const float e_fastExit    = 0.20
const float e_overrideT   = 0.60
 
// Structure rules (distances in median-true-range units)
const int   e_scaleLen    = 20
const bool  e_fastDrive   = false
const int   e_driveWin    = 4
const float e_driveUnits  = 0.85
const float e_driveEff    = 0.32
const float e_driveClear  = 0.12
const bool  e_structExit  = true
const int   e_protWin     = 4
const bool  e_rangeShape  = true
const int   e_rangeWin    = 12
const float e_rangeWidth  = 2.0
const float e_rangeCentre = 0.35
 
// Visual
const int   e_weakTransp  = 55      // weak-regime shade transparency
const int   e_lvlDays     = 30      // invalidation lines and texts: last N days only
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 1C — UTILITY FUNCTIONS
// ════════════════════════════════════════════════════════════════════════════
 
// @function Clamp x into [lo, hi].
f_clamp(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))
 
// @function Map a raw detector value onto [-1, +1] (+1 = trend, -1 = range).
//           Works for "higher = trend" (ER, Hurst, ADX) and "lower = trend" (Choppiness).
f_score(float x, float rangeLevel, float trendLevel) =>
    float half = (trendLevel - rangeLevel) / 2.0
    float mid  = (trendLevel + rangeLevel) / 2.0
    na(x) or half == 0 ? na : f_clamp((x - mid) / half, -1.0, 1.0)
 
// @function True for TREND UP or TREND DOWN.
f_isTrend(int st) =>
    st == ST_TREND_UP or st == ST_TREND_DOWN
 
// @function Display name for a regime state.
f_regimeName(int st) =>
    switch st
        ST_TREND_UP   => "TREND UP"
        ST_TREND_DOWN => "TREND DOWN"
        ST_RANGE      => "RANGE"
        => "UNDECIDED"
 
// @function Regime colour; weak regimes use a lighter shade.
f_regimeColor(int st, bool strong) =>
    color base = switch st
        ST_TREND_UP   => i_colUp
        ST_TREND_DOWN => i_colDown
        ST_RANGE      => i_colRange
        => i_colUnd
    st == ST_UNDECIDED ? color.new(base, 60) : strong ? base : color.new(base, e_weakTransp)
 
// @function Short timeframe label: 15M, 1H, 4H, 1D, 1W.
f_tfLabel(string tf) =>
    int mins = int(timeframe.in_seconds(tf) / 60)
    str.endswith(tf, "M") ? (tf == "M" ? "1M" : tf) :
     mins < 60 ? str.tostring(mins) + "M" : mins < 1440 ? str.tostring(int(mins / 60)) + "H" : mins < 10080 ? str.tostring(int(mins / 1440)) + "D" : str.tostring(int(mins / 10080)) + "W"
 
// @function Table position from its input name.
f_tablePos(string s) =>
    switch s
        "Top Left"     => position.top_left
        "Top Center"   => position.top_center
        "Middle Right" => position.middle_right
        "Middle Left"  => position.middle_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
// @function Table text size from its input name.
f_textSize(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 1D — RESOLVED PARAMETERS (presets → values used by the engine)
// ════════════════════════════════════════════════════════════════════════════
 
string assetAuto = syminfo.type == "crypto" ? "Crypto" : "Gold"
bool   isCrypto  = (i_preset == "Auto" ? assetAuto : i_preset) == "Crypto"
 
// Thresholds (only ER and ADX differ between Gold and Crypto presets)
float p_erRange  = isCrypto ? 0.12 : 0.15
float p_erTrend  = isCrypto ? 0.30 : 0.35
float p_huRange  = 0.45
float p_huTrend  = 0.55
float p_ciRange  = 61.8
float p_ciTrend  = 38.2
float p_adxRange = isCrypto ? 17.0 : 18.0
float p_adxTrend = isCrypto ? 23.0 : 25.0
 
// Responsiveness → lengths, entry confirmation, minimum hold
//   Balanced: ER 16, CI 12, ADX 12/12, Hurst 64,  confirm 3, hold 4
//   Fast:     ER 12, CI 10, ADX 10/10, Hurst 64,  confirm 2, hold 3
//   Standard: ER 20, CI 14, ADX 14/14, Hurst 128, confirm 3, hold 6
bool  spFast      = i_speed == "Fast"
bool  spStd       = i_speed == "Standard"
int   p_erLen     = spFast ? 12 : spStd ? 20  : 16
int   p_ciLen     = spFast ? 10 : spStd ? 14  : 12
int   p_diLen     = spFast ? 10 : spStd ? 14  : 12
int   p_adxSmooth = spFast ? 10 : spStd ? 14  : 12
int   p_huLen     = spStd  ? 128 : 64
int   p_confirm   = spFast ? 2  : 3
int   p_minHold   = spFast ? 3  : spStd ? 6   : 4
 
// Higher timeframes: auto = one and two steps up from the chart
int    chartSec    = timeframe.in_seconds()
string p_htf1TF    = i_htfAuto ? (chartSec <= 300 ? "15" : chartSec <= 900 ? "60" : chartSec <= 3600 ? "240" : chartSec <= 14400 ? "D" : "W") : i_htf1TF
string p_htf2TF    = i_htfAuto ? (chartSec <= 300 ? "60" : chartSec <= 900 ? "240" : chartSec <= 3600 ? "D" : chartSec <= 14400 ? "W" : "M") : i_htf2TF
bool   p_htf1Valid = timeframe.in_seconds(p_htf1TF) > chartSec
bool   p_htf2Valid = i_htf2On and timeframe.in_seconds(p_htf2TF) > timeframe.in_seconds(p_htf1TF)
 
// What is actually requested. An invalid HTF (not above the chart) is never
// requested as a lower timeframe: it falls back to the chart TF and shows "off".
string p_htf1Req   = p_htf1Valid ? p_htf1TF : timeframe.period
string p_htf2Req   = p_htf2Valid ? p_htf2TF : timeframe.period
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 2 — REGIME ENGINE (ported as-is from PT Regime Switch V26.01)
//  Runs only on the higher timeframes through request.security (Section 3).
//  gate = false everywhere: the [1] offset in the wrapper already guarantees
//  closed HTF bars, and Pine's rollback keeps var state consistent.
// ════════════════════════════════════════════════════════════════════════════
 
// ── 2A Kaufman Efficiency Ratio → [ER (0..1), signed ER (-1..+1)] ─────────
f_er(int len) =>
    float net  = close - close[len]
    float path = math.sum(math.abs(close - close[1]), len)
    float erA  = path > 0 ? math.abs(net) / path : na
    float erS  = path > 0 ? net / path : na
    [erA, erS]
 
// ── 2B Choppiness Index ────────────────────────────────────────────────────
f_chop(int len) =>
    float trSum = math.sum(ta.tr(true), len)
    float rng   = ta.highest(high, len) - ta.lowest(low, len)
    rng > 0 and trSum > 0 ? 100.0 * math.log10(trSum / rng) / math.log10(len) : na
 
// ── 2C Hurst exponent — rescaled range, Anis–Lloyd/Peters corrected ───────
// H = 0.5 + slope of [log(R/S) − log(E[R/S])] against log(n), scales N/8..N.
f_hurst(int N, bool gate) =>
    float r = math.log(close / close[1])
 
    var array<float> logN = array.new<float>()
    var array<float> logE = array.new<float>()
    if array.size(logN) == 0
        for k = 0 to 3
            int n = int(N / math.pow(2, 3 - k))
            float gr = 1.0
            if n > 340
                gr := 1.0 / math.sqrt(n * math.pi / 2.0)
            else
                for m = 2 to n - 2 by 2
                    gr := gr * (m - 1) / m
            float s = 0.0
            for i = 1 to n - 1
                s += math.sqrt(float(n - i) / i)
            float eRS = ((n - 0.5) / n) * gr * s
            array.push(logN, math.log(n))
            array.push(logE, math.log(eRS))
 
    var float hHeld = na
    if bar_index > N + 1 and (not gate or barstate.isconfirmed)
        float sx  = 0.0
        float sy  = 0.0
        float sxx = 0.0
        float sxy = 0.0
        int   cnt = 0
        for k = 0 to 3
            int n      = int(N / math.pow(2, 3 - k))
            int chunks = int(N / n)
            float rsSum = 0.0
            int   rsCnt = 0
            for c = 0 to chunks - 1
                int off = c * n
                float mean = 0.0
                for j = 0 to n - 1
                    mean += r[off + j]
                mean /= n
                float cum = 0.0
                float mx  = 0.0
                float mn  = 0.0
                float ss  = 0.0
                for j = 0 to n - 1
                    float d = r[off + j] - mean
                    cum += d
                    mx  := math.max(mx, cum)
                    mn  := math.min(mn, cum)
                    ss  += d * d
                float sd = math.sqrt(ss / n)
                if sd > 0
                    rsSum += (mx - mn) / sd
                    rsCnt += 1
            if rsCnt > 0
                float x = array.get(logN, k)
                float y = math.log(rsSum / rsCnt) - array.get(logE, k)
                sx  += x
                sy  += y
                sxx += x * x
                sxy += x * y
                cnt += 1
        if cnt >= 3
            float denom = cnt * sxx - sx * sx
            if denom != 0
                hHeld := 0.5 + (cnt * sxy - sx * sy) / denom
    hHeld
 
// ── 2D Detector bundle → [signed ER, DI spread, 4 scores, fast signed ER] ──
f_detectors(bool gate) =>
    [erA, erS]       = f_er(p_erLen)
    [erFA, erFast]   = f_er(e_fastDirLen)
    float hu         = f_hurst(p_huLen, gate)
    float ci         = f_chop(p_ciLen)
    [diP, diM, adx]  = ta.dmi(p_diLen, p_adxSmooth)
    float diSum      = diP + diM
    float diSpread   = diSum > 0 ? (diP - diM) / diSum : na
 
    float sEr  = e_erOn  ? f_score(erA, p_erRange,  p_erTrend)  : na
    float sHu  = e_huOn  ? f_score(hu,  p_huRange,  p_huTrend)  : na
    float sCi  = e_ciOn  ? f_score(ci,  p_ciRange,  p_ciTrend)  : na
    float sAdx = e_adxOn ? f_score(adx, p_adxRange, p_adxTrend) : na
    [erS, diSpread, sEr, sHu, sCi, sAdx, erFast]
 
// ── 2E Structure inputs → [drive (+1/−1/0), protected low, protected high, range ok]
f_structure() =>
    bool  gapBar   = timeframe.isintraday and not na(time_close[1]) and time > time_close[1]
    float trS      = na(close[1]) or gapBar ? high - low : math.max(high - low, math.abs(high - close[1]), math.abs(low - close[1]))
    float medTR    = ta.percentile_nearest_rank(math.max(trS, syminfo.mintick), e_scaleLen, 50)
    float scale    = na(medTR) ? math.max(trS, syminfo.mintick) : medTR
 
    float net      = close - close[e_driveWin]
    float path     = math.sum(math.abs(close - close[1]), e_driveWin)
    float eff      = path > 0 ? net / path : 0.0
    float brkHi    = ta.highest(high, e_driveWin)[1]
    float brkLo    = ta.lowest(low,  e_driveWin)[1]
    bool  driveUp  = not na(brkHi) and close > brkHi + e_driveClear * scale and net >=  e_driveUnits * scale and eff >=  e_driveEff and close > open
    bool  driveDn  = not na(brkLo) and close < brkLo - e_driveClear * scale and net <= -e_driveUnits * scale and eff <= -e_driveEff and close < open
    int   drive    = driveUp ? 1 : driveDn ? -1 : 0
 
    float protLo   = ta.lowest(low,  e_protWin)[1]
    float protHi   = ta.highest(high, e_protWin)[1]
 
    float rHi      = ta.highest(high, e_rangeWin)
    float rLo      = ta.lowest(low,  e_rangeWin)
    float rW       = rHi - rLo
    bool  rangeOk  = not e_rangeShape or (not na(rW) and rW >= e_rangeWidth * scale and math.abs(close - (rHi + rLo) / 2.0) <= rW * e_rangeCentre)
    [drive, protLo, protHi, rangeOk]
 
// ── 2F Optional linear-regression direction (slope over len, in ATR units) ─
f_linregDir(int len, float atrV) =>
    float lr0 = ta.linreg(close, len, 0)
    float lr1 = ta.linreg(close, len, 1)
    atrV > 0 ? f_clamp((lr0 - lr1) * len / (2.0 * atrV), -1.0, 1.0) : na
 
// ── 2G Weighted vote → [T, D, shareTrend, shareRange] ───────────────────────
f_vote(float sEr, float sHu, float sCi, float sAdx, float erSigned, float diSpread, float linDir) =>
    array<float> sc = array.from(sEr, sHu, sCi, sAdx)
    array<float> wt = array.from(e_erW, e_huW, e_ciW, e_adxW)
    float wSum  = 0.0
    float wsSum = 0.0
    float wUp   = 0.0
    float wDn   = 0.0
    for i = 0 to 3
        float s = array.get(sc, i)
        float w = array.get(wt, i)
        if not na(s) and w > 0
            wSum  += w
            wsSum += w * s
            if s > 0
                wUp += w
            else if s < 0
                wDn += w
    float T          = wSum > 0 ? wsSum / wSum : na
    float shareTrend = wSum > 0 ? wUp / wSum : na
    float shareRange = wSum > 0 ? wDn / wSum : na
 
    float dSum = 0.0
    int   dCnt = 0
    if not na(erSigned)
        dSum += erSigned
        dCnt += 1
    if not na(diSpread)
        dSum += diSpread
        dCnt += 1
    if e_useLinreg and not na(linDir)
        dSum += linDir
        dCnt += 1
    float D = dCnt > 0 ? dSum / dCnt : na
    [T, D, shareTrend, shareRange]
 
// ── 2H Confidence = 100 × Strength × Consensus × DirClarity ───────────────
f_confidence(int st, float T, float D, float shareTrend, float shareRange) =>
    float conf = na
    if not na(T) and st != ST_UNDECIDED
        float strength   = math.min(math.abs(T) / 0.7, 1.0)
        bool  isTrend    = f_isTrend(st)
        float consensus  = isTrend ? shareTrend : shareRange
        float dirClarity = isTrend ? (na(D) ? 0.0 : math.min(math.abs(D) / 0.5, 1.0)) : 1.0
        conf := 100.0 * strength * nz(consensus) * dirClarity
    conf
 
// ── 2I Raw candidate (before hysteresis) ───────────────────────────────────
f_candidate(float T, float D) =>
    int cand = ST_UNDECIDED
    if not na(T)
        if T >= e_enterT and not na(D) and math.abs(D) >= e_dirMin
            cand := D > 0 ? ST_TREND_UP : ST_TREND_DOWN
        else if T <= -e_enterT
            cand := ST_RANGE
    cand
 
// ── 2J Proposal: what the current state would move to this bar ─────────────
f_proposal(int st, float T, float D, float Dfast, bool rangeOk, float prot) =>
    int p = st
    if not na(T)
        bool trendEntry = T >= e_enterT and not na(D) and math.abs(D) >= e_dirMin
        int  trendDir   = not na(D) and D > 0 ? ST_TREND_UP : ST_TREND_DOWN
        int  toRange    = rangeOk ? ST_RANGE : ST_UNDECIDED
        bool lostUp     = e_structExit and not na(prot) and close < prot
        bool lostDn     = e_structExit and not na(prot) and close > prot
        switch st
            ST_TREND_UP =>
                p := T <= -e_enterT ? toRange :
                     lostUp ? ST_UNDECIDED :
                     not na(D) and D <= -e_dirMin ? ST_TREND_DOWN :
                     T <  e_exitT   ? ST_UNDECIDED :
                     not na(Dfast) and Dfast <= -e_fastExit ? ST_UNDECIDED : st
            ST_TREND_DOWN =>
                p := T <= -e_enterT ? toRange :
                     lostDn ? ST_UNDECIDED :
                     not na(D) and D >= e_dirMin ? ST_TREND_UP :
                     T <  e_exitT   ? ST_UNDECIDED :
                     not na(Dfast) and Dfast >= e_fastExit ? ST_UNDECIDED : st
            ST_RANGE =>
                p := trendEntry ? trendDir :
                     T > -e_exitT ? ST_UNDECIDED : st
            =>
                int c = f_candidate(T, D)
                p := c == ST_RANGE and not rangeOk ? st : c
    p
 
// ── 2K Hysteresis state machine → [state, changed, prevState, barsInState, potential, protected level]
f_hysteresis(float T, float D, float Dfast, bool gate, int drive, float protLoNow, float protHiNow, bool rangeOk) =>
    var int   state       = ST_UNDECIDED
    var int   prevState   = ST_UNDECIDED
    var int   barsInState = 0
    var int   pendState   = -1
    var int   pendCount   = 0
    var float prot        = na
    bool changed = false
    bool isDrive = false
    if (not gate or barstate.isconfirmed) and not na(T)
        barsInState += 1
        int prop = f_proposal(state, T, D, Dfast, rangeOk, prot)
        if e_fastDrive and drive != 0
            int dTrend = drive == 1 ? ST_TREND_UP : ST_TREND_DOWN
            if state != dTrend
                prop    := dTrend
                isDrive := true
        if prop == state
            pendState := -1
            pendCount := 0
        else
            if prop == pendState
                pendCount += 1
            else
                pendState := prop
                pendCount := 1
            bool isExit      = prop == ST_UNDECIDED
            bool isResume    = state == ST_UNDECIDED and prop == prevState and f_isTrend(prop) and barsInState <= e_resumeBars
            bool canOverride = (f_isTrend(prop) and T >= e_overrideT) or (prop == ST_RANGE and T <= -e_overrideT)
            bool holdOk      = isExit or isResume or isDrive or barsInState >= p_minHold or canOverride
            int  needed      = isExit or isResume or isDrive ? 1 : p_confirm
            needed          := isExit ? e_exitConfirm : needed
            if pendCount >= needed and holdOk
                prevState   := state
                state       := prop
                barsInState := 0
                pendState   := -1
                pendCount   := 0
                changed     := true
                prot        := state == ST_TREND_UP ? protLoNow : state == ST_TREND_DOWN ? protHiNow : na
    int potential = not changed and pendState != -1 and pendState != ST_UNDECIDED and pendCount >= 2 ? pendState : -1
    [state, changed, prevState, barsInState, potential, prot]
 
// ── 2L Strength with its own hysteresis ────────────────────────────────────
f_strength(int st, bool changed, float conf, bool gate) =>
    var bool strong = false
    if not gate or barstate.isconfirmed
        if st == ST_UNDECIDED or na(conf)
            strong := false
        else if changed
            strong := conf >= e_strongConf
        else if conf >= e_strongConf
            strong := true
        else if conf < e_strongConf - e_strongBand
            strong := false
    strong
 
// ── 2M Engine wrapper: returns the previous (closed) HTF bar's values ──────
// [state, strong, confidence, T, D, bars in state, potential, protected level]
f_regimeEngine() =>
    [eErS, eDi, eSEr, eSHu, eSCi, eSAdx, eFast] = f_detectors(false)
    [eDrive, eProtLo, eProtHi, eRangeOk] = f_structure()
    float eLin = e_useLinreg ? f_linregDir(e_linregLen, ta.atr(e_atrLen)) : na
    [eT, eD, eShT, eShR] = f_vote(eSEr, eSHu, eSCi, eSAdx, eErS, eDi, eLin)
    [eSt, eCh, ePrev, eBars, ePot, eProt] = f_hysteresis(eT, eD, eFast, false, eDrive, eProtLo, eProtHi, eRangeOk)
    float eConf   = f_confidence(eSt, eT, eD, eShT, eShR)
    bool  eStrong = f_strength(eSt, eCh, eConf, false)
    [eSt[1], eStrong[1], eConf[1], eT[1], eD[1], eBars[1], ePot[1], eProt[1]]
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 3 — HTF REQUESTS, ALIGNMENT, OUTPUT PLOTS
//  Non-repainting idiom: values offset by [1] + lookahead_on = the last
//  CLOSED HTF bar, never future data.
// ════════════════════════════════════════════════════════════════════════════
 
// ── 3A Requests ────────────────────────────────────────────────────────────
[h1Regime, h1Strong, h1Conf, h1T, h1D, h1Bars, h1Pot, h1Prot] = request.security(syminfo.tickerid, p_htf1Req, f_regimeEngine(), lookahead = barmerge.lookahead_on)
[h2Regime, h2Strong, h2Conf, h2T, h2D, h2Bars, h2Pot, h2Prot] = request.security(syminfo.tickerid, p_htf2Req, f_regimeEngine(), lookahead = barmerge.lookahead_on)
 
// Daily bias (panel row only). Shown only when 1D is above the highest active HTF.
// The request always runs (Pine cannot skip it); when unused it asks for the
// cheapest valid TF: 1D on intraday charts (few bars), else the chart TF.
bool   p_dyValid = i_dailyOn and timeframe.in_seconds("D") > timeframe.in_seconds(p_htf2Valid ? p_htf2TF : p_htf1TF)
string p_dyReq   = chartSec < 86400 ? "D" : timeframe.period
[dyRegime, dyStrong, dyConf, dyT, dyD, dyBars, dyPot, dyProt] = request.security(syminfo.tickerid, p_dyReq, f_regimeEngine(), lookahead = barmerge.lookahead_on)
 
bool h1Active = p_htf1Valid and not na(h1T)
bool h2Active = p_htf2Valid and not na(h2T)
bool dyActive = p_dyValid and not na(dyT)
 
// ── 3B Alignment between HTF 1 and HTF 2 ───────────────────────────────────
//  +2 both trend up · +1 one trend up, the other range/undecided
//   0 neither trending, or opposite trends (see conflict flag)
//  −1 one trend down, the other range/undecided · −2 both trend down
f_dirOf(int st) =>
    st == ST_TREND_UP ? 1 : st == ST_TREND_DOWN ? -1 : 0
 
int  d1         = h1Active ? f_dirOf(h1Regime) : 0
int  d2         = h2Active ? f_dirOf(h2Regime) : 0
bool htfConflict = d1 != 0 and d2 != 0 and d1 != d2
int  alignCode  = htfConflict ? 0 : d1 + d2
 
// ── 3C Regime code (same scale as PT Regime Switch) ────────────────────────
//  +2 strong up · +1 weak up · +0.5 / −0.5 undecided (lean) · 0 range
//  −1 weak down · −2 strong down
f_code(int st, bool strong, float d) =>
    switch st
        ST_TREND_UP   => strong ? 2.0 : 1.0
        ST_TREND_DOWN => strong ? -2.0 : -1.0
        ST_RANGE      => 0.0
        => na(d) or d >= 0 ? 0.5 : -0.5
 
// ── 3D Output plots (Data Window; readable by other PT tools via input.source)
plot(h1Active ? f_code(h1Regime, h1Strong, h1D) : na, "PT HTF 1 Regime Code",  display = display.data_window)
plot(h2Active ? f_code(h2Regime, h2Strong, h2D) : na, "PT HTF 2 Regime Code",  display = display.data_window)
plot(h1Active ? h1Conf : na,                          "PT HTF 1 Confidence",   display = display.data_window)
plot(h2Active ? h2Conf : na,                          "PT HTF 2 Confidence",   display = display.data_window)
plot(float(alignCode),                                "PT HTF Alignment",      display = display.data_window)
plot(htfConflict ? 1.0 : 0.0,                         "PT HTF Conflict",       display = display.data_window)
// Bars in state is shown in the status panel only: as a plot it is unbounded and
// could pull the hidden scale that keeps the ribbons pinned to the pane bottom.
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 4 — BOTTOM RIBBONS, TF TAGS, MARKERS (layout A)
//  The script runs on its own hidden scale (scale.none). Every output value
//  lies in [−3, 100]; the ribbon block sits below −3 and a transparent top
//  anchor sits at 102, so the block keeps i_ribbonPct of the pane height.
//
//  Block layout, bottom → top, in ribbon "units":
//    HTF 2 ribbon        0.00 – 0.22   (tag centre 0.11)
//    HTF 2 marker row    0.38          (+ dotted level line, Section 7)
//    HTF 2 level text    0.60
//    HTF 1 ribbon        0.82 – 1.04   (tag centre 0.93)
//    HTF 1 marker row    1.20          (+ dotted level line)
//    HTF 1 level text    1.42
//  Each marker row sits directly above its own ribbon, and each level text
//  sits above its own marker row, so the two HTFs never share a line.
// ════════════════════════════════════════════════════════════════════════════
 
// ── 4A Block geometry ──────────────────────────────────────────────────────
float rbPct = i_ribbonPct / 100.0
float rbTot = 1.60                                           // whole block, in units
float rbU   = 105.0 / (rbTot * (1.0 / rbPct - 1.0))          // one unit in hidden-scale values
float rbB   = -3.0 - rbTot * rbU                             // bottom of the block
float rbHi  = rbB + rbTot * rbU / rbPct                      // top anchor (= 102)
 
color transparentCol = color.new(color.black, 100)
plot(rbB,  "Ribbon anchor (low)",  color = transparentCol, display = display.pane, editable = false)
plot(rbHi, "Ribbon anchor (high)", color = transparentCol, display = display.pane, editable = false)
 
// ── 4B Ribbons ─────────────────────────────────────────────────────────────
pH2Bot = plot(rbB,              "HTF 2 ribbon bottom", display = display.none, editable = false)
pH2Top = plot(rbB + 0.22 * rbU, "HTF 2 ribbon top",    display = display.none, editable = false)
pH1Bot = plot(rbB + 0.82 * rbU, "HTF 1 ribbon bottom", display = display.none, editable = false)
pH1Top = plot(rbB + 1.04 * rbU, "HTF 1 ribbon top",    display = display.none, editable = false)
 
color h1Col = i_ribbonOn and h1Active ? f_regimeColor(h1Regime, h1Strong) : na
color h2Col = i_ribbonOn and h2Active ? f_regimeColor(h2Regime, h2Strong) : na
fill(pH1Bot, pH1Top, color = h1Col, title = "HTF 1 ribbon")
fill(pH2Bot, pH2Top, color = h2Col, title = "HTF 2 ribbon")
 
// ── 4C Regime-change markers ───────────────────────────────────────────────
// Drawn once the new HTF regime has lasted i_mkMinBars CLOSED HTF bars,
// on the first chart bar where that is known (never back-filled).
//   i_mkMinBars = 1 → the HTF regime differs from the previous chart bar
//   i_mkMinBars ≥ 2 → bars-in-state just reached (i_mkMinBars − 1); the count
//                      only rises inside one regime, so this fires once.
// Marker colour = the ribbon's strong/weak shade at that bar.
f_markNow(bool active, int st, int bars) =>
    bool fresh = i_mkMinBars <= 1 ? st != st[1] : bars == i_mkMinBars - 1 and bars != bars[1]
    i_ribbonOn and i_markers and active and active[1] and fresh
 
bool  mk1   = f_markNow(h1Active, h1Regime, h1Bars)
bool  mk2   = f_markNow(h2Active, h2Regime, h2Bars)
color mk1Col = f_regimeColor(h1Regime, h1Strong)
color mk2Col = f_regimeColor(h2Regime, h2Strong)
 
float y1    = rbB + 1.20 * rbU
float y2    = rbB + 0.38 * rbU
float upNudge = 0.04 * rbU                                   // ▲ draws slightly high; nudge onto the line
 
plotshape(mk1 and h1Regime == ST_TREND_UP   ? y1 - upNudge : na, "HTF 1 → trend up",   shape.triangleup,   location.absolute, mk1Col, size = size.tiny)
plotshape(mk1 and h1Regime == ST_TREND_DOWN ? y1 : na,           "HTF 1 → trend down", shape.triangledown, location.absolute, mk1Col, size = size.tiny)
plotshape(mk1 and h1Regime == ST_RANGE      ? y1 : na,           "HTF 1 → range",      shape.diamond,      location.absolute, mk1Col, size = size.tiny)
plotshape(mk1 and h1Regime == ST_UNDECIDED  ? y1 : na,           "HTF 1 → undecided",  shape.square,       location.absolute, i_colUnd, size = size.tiny)
plotshape(mk2 and h2Regime == ST_TREND_UP   ? y2 - upNudge : na, "HTF 2 → trend up",   shape.triangleup,   location.absolute, mk2Col, size = size.tiny)
plotshape(mk2 and h2Regime == ST_TREND_DOWN ? y2 : na,           "HTF 2 → trend down", shape.triangledown, location.absolute, mk2Col, size = size.tiny)
plotshape(mk2 and h2Regime == ST_RANGE      ? y2 : na,           "HTF 2 → range",      shape.diamond,      location.absolute, mk2Col, size = size.tiny)
plotshape(mk2 and h2Regime == ST_UNDECIDED  ? y2 : na,           "HTF 2 → undecided",  shape.square,       location.absolute, i_colUnd, size = size.tiny)
 
// ── 4D Timeframe tags at the live end of each ribbon ───────────────────────
// Moved to bar_index + 1 on every new bar so they sit just right of the
// newest ribbon segment.
var label tag1 = na
var label tag2 = na
 
f_endLabel(label lb, int x, float y, string txt) =>
    label out = lb
    if na(out)
        out := label.new(x, y, txt, style = label.style_label_left, color = transparentCol,
             textcolor = color.new(chart.fg_color, 15), size = size.small, textalign = text.align_left)
    else
        label.set_xy(out, x, y)
        label.set_text(out, txt)
    out
 
if barstate.islast
    bool showTags = i_ribbonOn and i_tfTags
    int  xEnd     = bar_index + 1
    if showTags and h1Active
        tag1 := f_endLabel(tag1, xEnd, rbB + 0.93 * rbU, f_tfLabel(p_htf1TF))
    else if not na(tag1)
        label.delete(tag1)
        tag1 := na
    if showTags and h2Active
        tag2 := f_endLabel(tag2, xEnd, rbB + 0.11 * rbU, f_tfLabel(p_htf2TF))
    else if not na(tag2)
        label.delete(tag2)
        tag2 := na
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 5 — STATUS PANEL (switchable, layout D) + LEGEND
//  Both are drawn on the last bar only. Colours are shown as coloured glyphs
//  (■ ▲ ▼ ◆), never as filled table cells.
//
//  Compact :  PT HTF Regime
//             15M  ▲ TREND UP · strong 72            3h
//             1H   ■ UNDECIDED · lean ↑             10h
//             Lean up · one TF trending
//  Detailed:  PT HTF Regime
//             TF   State          Strength    Held
//             15M  ▲ TREND UP     strong 72   12 bars · 3h
//             1H   ■ UNDECIDED ↑  —           10 bars · 10h
//             Next   1H → TREND UP pending
//             Align  Lean up · one TF trending
//             Levels 15M Uptrend @ 4012.50
//  Held = closed HTF bars in the current state, and the time they span.
//  State text uses the marker symbols and the regime colour.
// ════════════════════════════════════════════════════════════════════════════
 
color  pFg    = chart.fg_color
color  pMuted = color.new(chart.fg_color, 45)
color  pFrame = color.new(chart.fg_color, 82)
string pSize  = f_textSize(i_dashSize)
 
// ── 5A Panel helpers ───────────────────────────────────────────────────────
f_sym(int st) =>
    switch st
        ST_TREND_UP   => "▲"
        ST_TREND_DOWN => "▼"
        ST_RANGE      => "◆"
        => "■"
 
// Text colour = the regime's solid colour (weak shades are too faint for text)
f_stateCol(bool active, int st) =>
    not active ? pMuted : st == ST_TREND_UP ? i_colUp : st == ST_TREND_DOWN ? i_colDown : st == ST_RANGE ? i_colRange : i_colUnd
 
f_lean(float d) =>
    na(d) ? "" : d >= 0 ? "↑" : "↓"
 
f_strengthText(int st, bool strong, float conf) =>
    st == ST_UNDECIDED or na(conf) ? "—" : (strong ? "strong " : "weak ") + str.tostring(math.round(conf))
 
// Duration from seconds: 45m · 3h · 3h 15m · 2d · 2d 4h
f_dur(float secs) =>
    int m = int(math.round(secs / 60.0))
    int h = int(m / 60)
    m < 60 ? str.tostring(m) + "m" :
     m < 1440 ? str.tostring(h) + "h" + (m % 60 != 0 ? " " + str.tostring(m % 60) + "m" : "") :
     str.tostring(int(h / 24)) + "d" + (h % 24 != 0 ? " " + str.tostring(h % 24) + "h" : "")
 
f_heldTime(string tf, int bars) =>
    f_dur(float(bars + 1) * timeframe.in_seconds(tf))
 
// Compact state: "▲ TREND UP · strong 72" / "■ UNDECIDED · lean ↑"
f_compactState(bool active, int st, bool strong, float conf, float d) =>
    not active ? "off" : f_sym(st) + " " + f_regimeName(st) + " · " + (st == ST_UNDECIDED ? "lean " + f_lean(d) : f_strengthText(st, strong, conf))
 
// ── 5B Alignment and pending-change lines ─────────────────────────────────
string alignTxt = not h1Active ? "—" :
     not h2Active   ? "HTF 2 off" :
     htfConflict    ? "Conflict · opposite trends" :
     alignCode ==  2 ? "Aligned up" :
     alignCode == -2 ? "Aligned down" :
     alignCode ==  1 ? "Lean up · one TF trending" :
     alignCode == -1 ? "Lean down · one TF trending" : "Neutral"
color alignCol = not h1Active or not h2Active ? pMuted :
     htfConflict    ? i_colRange :
     alignCode >= 1 ? i_colUp :
     alignCode <= -1 ? i_colDown : pMuted
 
// Next: a new TREND or RANGE proposed for ≥ 2 HTF bars but not yet confirmed
bool   p1 = h1Active and h1Pot != -1
bool   p2 = h2Active and h2Pot != -1
string nextTxt = (p1 ? f_tfLabel(p_htf1TF) + " → " + f_regimeName(h1Pot) : "") +
     (p1 and p2 ? " · " : "") +
     (p2 ? f_tfLabel(p_htf2TF) + " → " + f_regimeName(h2Pot) : "") +
     (p1 or p2 ? " pending" : "—")
color  nextCol = p1 ? f_stateCol(true, h1Pot) : p2 ? f_stateCol(true, h2Pot) : pMuted
 
// ── 5C Invalidation levels (Detailed mode) ────────────────────────────────
// Same wording and rule as the ribbon texts (Section 7): shown trends only.
f_lvlText(int st, float lvl, string tf) =>
    tf + (st == ST_TREND_UP ? " Uptrend @ " : " Downtrend @ ") + str.tostring(lvl, format.mintick)
 
f_invText(bool shown, int st, float lvl, string tf) =>
    shown and f_isTrend(st) and not na(lvl) ? f_lvlText(st, lvl, tf) : ""
 
bool   h1Shown = h1Active and h1Bars >= i_mkMinBars - 1
bool   h2Shown = h2Active and h2Bars >= i_mkMinBars - 1
string inv1Txt = f_invText(h1Shown, h1Regime, h1Prot, f_tfLabel(p_htf1TF))
string inv2Txt = f_invText(h2Shown, h2Regime, h2Prot, f_tfLabel(p_htf2TF))
string invTxt  = inv1Txt == "" and inv2Txt == "" ? "—" : inv1Txt + (inv1Txt != "" and inv2Txt != "" ? " · " : "") + inv2Txt
 
// ── 5D Draw the panel ──────────────────────────────────────────────────────
//  Rows are numbered from the top so the optional daily row slots in cleanly.
var table panel = i_dashOn ? table.new(f_tablePos(i_dashPos), 4, 8, bgcolor = color.new(chart.bg_color, 8),
     frame_color = pFrame, frame_width = 1, border_width = 0) : na
varip bool panelMerged = false
bool isDetailed = i_dashMode == "Detailed"
 
f_pc(int c, int r, string t, color tc, string ha) =>
    table.cell(panel, c, r, t, text_color = tc, text_size = pSize, text_halign = ha)
 
f_compactRow(int r, string tfRaw, bool active, int st, bool strong, float conf, float d, int bars) =>
    f_pc(0, r, f_tfLabel(tfRaw), pFg, text.align_left)
    f_pc(1, r, f_compactState(active, st, strong, conf, d), f_stateCol(active, st), text.align_left)
    f_pc(2, r, active ? f_heldTime(tfRaw, bars) : "—", pMuted, text.align_right)
 
f_detailRow(int r, string tfRaw, bool active, int st, bool strong, float conf, float d, int bars) =>
    f_pc(0, r, f_tfLabel(tfRaw), pFg, text.align_left)
    f_pc(1, r, not active ? "off" : f_sym(st) + " " + f_regimeName(st) + (st == ST_UNDECIDED ? " " + f_lean(d) : ""), f_stateCol(active, st), text.align_left)
    f_pc(2, r, active ? f_strengthText(st, strong, conf) : "—", active ? pFg : pMuted, text.align_left)
    f_pc(3, r, active ? str.tostring(bars + 1) + (bars == 0 ? " bar · " : " bars · ") + f_heldTime(tfRaw, bars) : "—", active ? pFg : pMuted, text.align_right)
 
if i_dashOn and barstate.islast
    int extra = p_dyValid ? 1 : 0
    if isDetailed
        int rNext  = 4 + extra
        int rAlign = rNext + 1
        int rInv   = rAlign + 1
        if not panelMerged
            table.merge_cells(panel, 0, 0, 3, 0)
            table.merge_cells(panel, 1, rNext,  3, rNext)
            table.merge_cells(panel, 1, rAlign, 3, rAlign)
            table.merge_cells(panel, 1, rInv,   3, rInv)
            panelMerged := true
        f_pc(0, 0, "PT HTF Regime", pFg, text.align_left)
        f_pc(0, 1, "TF",       pMuted, text.align_left)
        f_pc(1, 1, "State",    pMuted, text.align_left)
        f_pc(2, 1, "Strength", pMuted, text.align_left)
        f_pc(3, 1, "Held",     pMuted, text.align_right)
        f_detailRow(2, p_htf1TF, h1Active, h1Regime, h1Strong, h1Conf, h1D, h1Bars)
        f_detailRow(3, p_htf2TF, h2Active, h2Regime, h2Strong, h2Conf, h2D, h2Bars)
        if p_dyValid
            f_detailRow(4, "D", dyActive, dyRegime, dyStrong, dyConf, dyD, dyBars)
        f_pc(0, rNext,  "Next",    pMuted, text.align_left)
        f_pc(1, rNext,  nextTxt,   nextCol, text.align_left)
        f_pc(0, rAlign, "Align",   pMuted, text.align_left)
        f_pc(1, rAlign, alignTxt,  alignCol, text.align_left)
        f_pc(0, rInv,   "Levels",  pMuted, text.align_left)
        f_pc(1, rInv,   invTxt,    invTxt == "—" ? pMuted : pFg, text.align_left)
    else
        int rAlign = 3 + extra
        if not panelMerged
            table.merge_cells(panel, 0, 0, 2, 0)
            table.merge_cells(panel, 0, rAlign, 2, rAlign)
            panelMerged := true
        f_pc(0, 0, "PT HTF Regime", pFg, text.align_left)
        f_compactRow(1, p_htf1TF, h1Active, h1Regime, h1Strong, h1Conf, h1D, h1Bars)
        f_compactRow(2, p_htf2TF, h2Active, h2Regime, h2Strong, h2Conf, h2D, h2Bars)
        if p_dyValid
            f_compactRow(3, "D", dyActive, dyRegime, dyStrong, dyConf, dyD, dyBars)
        f_pc(0, rAlign, alignTxt, alignCol, text.align_left)
 
// ── 5E Legend (own switch and position, default Bottom Right) ─────────────
//   Ribbon  : ███ strong | ███ weak | name
//   Markers : symbol | | meaning · note on the marker delay in the last row
var table legend = i_legend ? table.new(f_tablePos(i_legendPos), 3, 14, bgcolor = color.new(chart.bg_color, 5),
     frame_color = pFrame, frame_width = 1, border_width = 0) : na
 
f_lgCell(int col, int row, string txt, color tc, string ha) =>
    table.cell(legend, col, row, txt, text_color = tc, text_size = pSize, text_halign = ha)
 
f_lgRibbon(int row, int st, string name) =>
    f_lgCell(0, row, "███", f_regimeColor(st, true), text.align_center)
    f_lgCell(1, row, st == ST_UNDECIDED ? "" : "███", st == ST_UNDECIDED ? pFg : f_regimeColor(st, false), text.align_center)
    f_lgCell(2, row, name, pFg, text.align_left)
 
f_lgMarker(int row, string sym, color sc, string meaning) =>
    f_lgCell(0, row, sym, sc, text.align_center)
    f_lgCell(1, row, "", pFg, text.align_center)
    f_lgCell(2, row, meaning, pFg, text.align_left)
 
if i_legend and barstate.islast
    f_lgCell(0, 0, "strong", pMuted, text.align_center)
    f_lgCell(1, 0, "weak",   pMuted, text.align_center)
    f_lgCell(2, 0, "RIBBON", pMuted, text.align_left)
    f_lgRibbon(1, ST_TREND_UP,   "Trend up")
    f_lgRibbon(2, ST_TREND_DOWN, "Trend down")
    f_lgRibbon(3, ST_RANGE,      "Range")
    f_lgRibbon(4, ST_UNDECIDED,  "Undecided")
    f_lgCell(0, 5, " ", pFg, text.align_center)
    f_lgCell(2, 6, "MARKERS", pMuted, text.align_left)
    f_lgMarker(7,  "▲", i_colUp,    "Trend up starts")
    f_lgMarker(8,  "▼", i_colDown,  "Trend down starts")
    f_lgMarker(9,  "◆", i_colRange, "Range starts")
    f_lgMarker(10, "■", i_colUnd,   "Back to undecided")
    f_lgMarker(11, "▬", pFg, "Upper ribbon " + f_tfLabel(p_htf1TF) + " · lower " + f_tfLabel(p_htf2TF))
    f_lgMarker(12, "┄", pFg, "Trend line · text = invalidation level")
    f_lgCell(2, 13, "Trends shown after " + str.tostring(i_mkMinBars) + " HTF bar" + (i_mkMinBars == 1 ? "" : "s"), pMuted, text.align_left)
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 6 — ALERTS
//  Same delay as the markers: a regime counts once it has lasted
//  i_mkMinBars closed HTF bars ("Trends shown after N HTF bars").
//    Aligned up / down : both HTFs in the same trend, each past the delay
//    Alignment lost    : immediately when either HTF leaves that trend
//                        (exits are never delayed: the safe error)
//  All values come from closed HTF bars, so alerts never repaint.
//  Two ways to set them up in TradingView:
//    • pick one of the three conditions below (fixed message), or
//    • "Any alert() function call" → all three, with the real TF names.
// ════════════════════════════════════════════════════════════════════════════
 
// h1Shown / h2Shown are defined in Section 5C (same delay as the markers)
bool alignedUp = h1Shown and h2Shown and h1Regime == ST_TREND_UP   and h2Regime == ST_TREND_UP
bool alignedDn = h1Shown and h2Shown and h1Regime == ST_TREND_DOWN and h2Regime == ST_TREND_DOWN
bool alignedNow = alignedUp or alignedDn
 
bool alertUp   = alignedUp and not alignedUp[1]
bool alertDn   = alignedDn and not alignedDn[1]
bool alertLost = alignedNow[1] and not alignedNow
 
alertcondition(alertUp,   "Aligned up",     "PT HTF Regime: HTF 1 and HTF 2 aligned TREND UP on {{ticker}}")
alertcondition(alertDn,   "Aligned down",   "PT HTF Regime: HTF 1 and HTF 2 aligned TREND DOWN on {{ticker}}")
alertcondition(alertLost, "Alignment lost", "PT HTF Regime: HTF alignment lost on {{ticker}}")
 
string tfPair = f_tfLabel(p_htf1TF) + " + " + f_tfLabel(p_htf2TF)
if alertUp
    alert("PT HTF Regime: " + tfPair + " aligned TREND UP on " + syminfo.ticker, alert.freq_once_per_bar)
if alertDn
    alert("PT HTF Regime: " + tfPair + " aligned TREND DOWN on " + syminfo.ticker, alert.freq_once_per_bar)
if alertLost
    alert("PT HTF Regime: " + tfPair + " alignment lost (" + f_tfLabel(p_htf1TF) + " " + f_regimeName(h1Regime) + ", " + f_tfLabel(p_htf2TF) + " " + f_regimeName(h2Regime) + ") on " + syminfo.ticker, alert.freq_once_per_bar)
 
// ════════════════════════════════════════════════════════════════════════════
//  SECTION 7 — HTF INVALIDATION LEVELS (inside the ribbon block)
//  The engine stores a protected level when each HTF trend starts:
//    TREND UP   → swing low of the protected window; a close below ends it
//    TREND DOWN → swing high of the protected window; a close above ends it
//  Fixed for the life of the trend (no trailing). Nothing is drawn on price.
//  Per trend, on that HTF's marker row:
//    • the ▲ / ▼ marker, then a dotted line for as long as the trend is shown
//    • text above the marker:  15M Downtrend @ 4062.84
//  Same delay as the markers. Line and text for the last e_lvlDays days;
//  older trends keep the level as a hover tooltip on the marker.
// ════════════════════════════════════════════════════════════════════════════
 
bool  showLvl  = i_ribbonOn and i_invLines
bool  inWindow = timenow - time <= e_lvlDays * 86400000
 
bool tr1Now   = h1Shown and f_isTrend(h1Regime) and not na(h1Prot)
bool tr2Now   = h2Shown and f_isTrend(h2Regime) and not na(h2Prot)
bool tr1Start = tr1Now and (not tr1Now[1] or h1Regime != h1Regime[1])
bool tr2Start = tr2Now and (not tr2Now[1] or h2Regime != h2Regime[1])
 
// ── 7A Dotted level lines (break on the start bar so back-to-back trends separate)
color lvlLineCol = color.new(chart.fg_color, 50)
plot(showLvl and inWindow and tr1Now and not tr1Start ? y1 : na, "HTF 1 level line", color = lvlLineCol,
     linewidth = 1, style = plot.style_linebr, linestyle = plot.linestyle_dotted, display = display.pane, editable = false)
plot(showLvl and inWindow and tr2Now and not tr2Start ? y2 : na, "HTF 2 level line", color = lvlLineCol,
     linewidth = 1, style = plot.style_linebr, linestyle = plot.linestyle_dotted, display = display.pane, editable = false)
 
// ── 7B Level text at each trend start ──────────────────────────────────
//  Last e_lvlDays days : visible text above the marker, e.g. 15M Downtrend @ 4062.84
//  Older               : no text, only a hover tooltip on the marker (same single line)
//  A text that ages past the window on a live chart turns into a tooltip.
//  Pine keeps the newest max_labels_count labels, so the oldest tooltips drop first.
var array<label> lvlLabels = array.new<label>()
var array<int>   lvlTimes  = array.new<int>()
float lvlTextUp = 0.22 * rbU                                 // text row sits this far above its marker row
 
// f_lvlText is defined in Section 5C (shared with the panel)
f_tipOnly(int x, float yMarker, string txt) =>
    label.new(x, yMarker, "", style = label.style_circle, color = transparentCol, size = size.small, tooltip = txt)
 
f_lvlLabel(bool start, int st, float lvl, float yMarker, string tf) =>
    if start and showLvl
        string txt = f_lvlText(st, lvl, tf)
        if inWindow
            label lb = label.new(bar_index, yMarker + lvlTextUp, txt, style = label.style_label_left, color = transparentCol,
                 textcolor = color.new(chart.fg_color, 25), size = size.small, textalign = text.align_left, tooltip = txt)
            array.push(lvlLabels, lb)
            array.push(lvlTimes, time)
            lb
        else
            f_tipOnly(bar_index, yMarker, txt)
 
f_lvlLabel(tr1Start, h1Regime, h1Prot, y1, f_tfLabel(p_htf1TF))
f_lvlLabel(tr2Start, h2Regime, h2Prot, y2, f_tfLabel(p_htf2TF))
 
// Texts that age past the window (chart left open for days) become tooltips
while array.size(lvlTimes) > 0 and timenow - array.get(lvlTimes, 0) > e_lvlDays * 86400000
    label lb = array.shift(lvlLabels)
    array.shift(lvlTimes)
    f_tipOnly(label.get_x(lb), label.get_y(lb) - lvlTextUp, label.get_text(lb))
    label.delete(lb)

← 返回列表