iFVG Core: Smart Money Concepts [AxeAlgo]

AxeAlgo · study · 1067 行 · 点赞 377 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AxeAlgo
//@version=6
// ─────────────────────────────────────────────────────────────────────────────
//  iFVG Core: Smart Money Concepts [AxeAlgo]
//  Precision Imbalance Corridors, Inversion Role-Flips & Retest Reactions
// ─────────────────────────────────────────────────────────────────────────────
//  A dedicated Smart Money Concepts (SMC) charting suite designed for
//  clean market structure visualization and price-action charting.
//
//  KEY HIGHLIGHTS:
//   • AxeAlgo Minimalist Diamond Reactions: Floating ◆ reaction
//     markers with structural SMC analysis displayed in hover tooltips.
//   • Double Diamond Spacing & Momentum Lockout: Zone reaction caps and directional
//     momentum cooldown prevent duplicate clustered markers during rapid expansions.
//   • Balanced Price Range (BPR) Highlighting: Radiant violet corridors
//     identifying two-sided overlapping imbalances (BISI ∩ SIBI).
//   • Non-Repainting Macro HTF Reference: Real-time projection of nearest Higher-
//     Timeframe (1H/4H/Daily) FVG corridors for multi-timeframe reference.
//   • Trend-Aligned Confirmation: 50 EMA baseline filtering checks trend context.
//   • Nearest-Anchor Active Level Projection: Only the nearest key levels (3 Supply,
//     3 Demand) project forward to the live price scale with right-margin tags.
//   • 50% Consequent Encroachment (C.E.): Midpoint equilibrium rail.
//   • Inversion Role-Flips: Breached demand flips to resistance (and vice-versa).
//   • Dynamic Box Trimming: Real-time visualization of unfilled open liquidity.
//   • Clean Canvas & Historical Record: Mitigated levels fade into subtle
//     frosted glass without dashed lines cluttering the screen.
// ─────────────────────────────────────────────────────────────────────────────
 
indicator("iFVG Core: Smart Money Concepts [AxeAlgo]", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
 
// ═════════════════════════════════════════════════════════════════════════════
//  INPUTS & CONFIGURATION
// ═════════════════════════════════════════════════════════════════════════════
 
// ───────── 1. LIQUIDITY CORRIDORS & HTF STRUCTURE ─────────
g01 = "1. LIQUIDITY CORRIDORS & HTF STRUCTURE"
showBullFvg         = input.bool(true,  "Bullish (BISI)", inline = "lvl_toggle", group = g01, tooltip = "Plots buy-side liquidity imbalance corridors.")
showBearFvg         = input.bool(true,  "Bearish (SIBI)", inline = "lvl_toggle", group = g01, tooltip = "Plots sell-side liquidity imbalance corridors.")
showBpr             = input.bool(true,  "Balanced Ranges (⚡ BPR)", inline = "bpr_inv", group = g01, tooltip = "Identifies two-sided overlapping imbalances where active BISI and SIBI corridors intersect. Renders with signature radiant violet.")
showInversion       = input.bool(true,  "Inversion Flips (iFVG)", inline = "bpr_inv", group = g01, tooltip = "When violated, flips demand to resistance and supply to support.")
imbalanceType       = input.string("Both (FVG + VI)", "Imbalance Mode", options = ["Fair Value Gaps (FVG)", "Volume Imbalances (VI)", "Both (FVG + VI)"], group = g01, tooltip = "Select between standard Fair Value Gaps, pure Volume Imbalances, or both combined.")
 
showHtfAnchor       = input.bool(true,  "Macro HTF Anchor Corridor", inline = "htf_ctrl", group = g01, tooltip = "Projects the nearest unmitigated Higher-Timeframe (1H, 4H, Daily) FVG anchor corridor to the live chart with non-repainting historical data.")
htfTimeframe        = input.timeframe("60", "", inline = "htf_ctrl", group = g01, tooltip = "Select macro higher timeframe: 60 (1H), 240 (4H), D (Daily), W (Weekly). Must be strictly higher than chart timeframe.")
 
showCeMidline       = input.bool(true,  "50% C.E. Equilibrium Rail", inline = "ce_tags", group = g01, tooltip = "Draws the 50% consequent encroachment equilibrium rail inside active corridors.")
showPriceTags       = input.bool(true,  "Right Price Tags", inline = "ce_tags", group = g01, tooltip = "Pins clean level tags to the right margin next to the price scale.")
 
maxActiveDemand     = input.int(3,      "Max Active Demand", minval = 1, maxval = 8, inline = "act_lvl", group = g01, tooltip = "Only the nearest N active demand and supply corridors project forward across the chart. Older levels freeze locally.")
maxActiveSupply     = input.int(3,      "Max Active Supply", minval = 1, maxval = 8, inline = "act_lvl", group = g01)
forwardBars         = input.int(15,     "Lead Bars", minval = 1, maxval = 30, inline = "act_lvl", group = g01, tooltip = "Projects active levels forward toward the live price scale.")
 
mitMethod           = input.string("Candle Close", "Mitigation Method", options = ["Candle Close", "Wick Touch", "50% C.E. Touch"], inline = "mit_rules", group = g01, tooltip = "Determines when a corridor is considered mitigated.")
mitDisplay          = input.string("Fade Level", "Display", options = ["Fade Level", "Hide Completely"], inline = "mit_rules", group = g01, tooltip = "Fade Level retains a subtle historical record of filled gaps. Hide Completely removes them.")
invBreakMethod      = input.string("Candle Close", "Inversion Trigger", options = ["Candle Close", "Wick Penetration"], inline = "inv_rules", group = g01, tooltip = "Determines when a gap is violated and flips role.")
trimOnFill          = input.bool(true,  "Trim on Retest", inline = "inv_rules", group = g01, tooltip = "Dynamically adjusts the corridor boundary as price fills into the gap, showing only remaining unfilled liquidity.")
 
// ───────── 2. RETEST REACTION MARKERS (SMC ◆) ─────────
g02 = "2. RETEST REACTION MARKERS (SMC ◆)"
showSignals         = input.bool(true,   "Show Retest Markers", inline = "sig_main", group = g02, tooltip = "Plots SMC reaction markers (◆ / ▲ / ▼) when price confirms a defense off active FVG, BPR, or inverted corridors.")
minimalistMode      = input.bool(true,   "Minimalist Mode (◆ Only)", inline = "sig_main", group = g02, tooltip = "When enabled (default), labels display only the sleek AxeAlgo diamond ◆ and tuck all detailed structure into hover tooltips. Disable to display full text labels on chart.")
signalStyle         = input.string("Solid Modern Pill", "Marker Style", options = ["AxeAlgo Obsidian Pill", "Directional Glass Tag", "Solid Modern Pill", "Cyber Minimalist (No Box)"], inline = "sig_vis", group = g02, tooltip = "Select between AxeAlgo signature dark obsidian glass capsules, directional tags, solid modern badges, or minimal cyber glyphs.")
signalSizeOpt       = input.string("Small", "Size", options = ["Tiny", "Small", "Normal"], inline = "sig_vis", group = g02, tooltip = "Small provides crisp readability on modern retina displays. Tiny is ultra-compact.")
signalTextMode      = input.string("AxeAlgo Signature (◆ iFVG / ◆ FVG)", "Full Text Format (when Minimalist is off)", options = ["AxeAlgo Signature (◆ iFVG / ◆ FVG)", "SMC Chevrons (▲ FVG Retest / ▼ FVG Retest)", "SMC Code (BISI / SIBI)", "Axe Diamonds Only (◆)"], group = g02, tooltip = "Determines the full text format displayed when Minimalist Mode is disabled.")
 
filterByTrend       = input.bool(true,   "Trend Alignment Filter", inline = "tr_flt", group = g02, tooltip = "Filters out counter-trend reactions. Only confirms bullish reactions when above the 50 EMA, and bearish reactions when below.")
trendEmaLen         = input.int(50,      "EMA Period", minval = 10, maxval = 200, inline = "tr_flt", group = g02, tooltip = "Period length for the trend reference baseline.")
showTrendLine       = input.bool(false,  "Plot Trend Baseline (50 EMA)", inline = "tr_disp", group = g02, tooltip = "Plots the 50-period EMA reference line on chart for visual trend alignment.")
highlightSignalBars = input.bool(false,  "Tint Trigger Candles", inline = "tr_disp", group = g02, tooltip = "Subtly tints the candle when a reaction confirms for instant visual recognition.")
 
retestFilterMode    = input.string("Wick Rejection & Close (Strict)", "Retest Requirement", options = ["Wick Rejection & Close (Strict)", "Candle Close (Standard)", "Any Bar Color (Loose)"], group = g02, tooltip = "Strict requires >= 20% rejection wick and closing on the defended side of the 50% C.E. level.")
minBarsBetweenSig   = input.int(10,      "Opposing Cooldown (bars)", minval = 2, maxval = 50, inline = "sig_spacing", group = g02, tooltip = "Enforces minimum bar spacing between opposing reactions so they never cluster during consolidation.")
sigMomentumCooldown = input.int(15,      "Directional Lockout (bars)", minval = 5, maxval = 50, inline = "sig_spacing", group = g02, tooltip = "Enforces spacing between consecutive reactions in the same direction, preventing duplicate clustered diamond badges during rapid momentum runs.")
maxReactionsPerZone = input.int(1,       "Max Reactions / Corridor", minval = 1, maxval = 3, inline = "sig_limits", group = g02, tooltip = "Limits the number of confirmed retest reaction markers from any single liquidity zone to avoid duplicate markers.")
alternateSignals    = input.bool(true,  "Enforce Alternating (Bull ⇄ Bear)", inline = "sig_limits", group = g02, tooltip = "When enabled, suppresses consecutive reactions in the same direction until an opposing reaction occurs.")
 
// ───────── 3. DETECTION SENSITIVITY & DEDUPLICATION ─────────
g03 = "3. DETECTION SENSITIVITY & DEDUPLICATION"
minGapAtr          = input.float(0.20, "Min Gap Size (× ATR)", minval = 0.05, maxval = 3.0, step = 0.05, inline = "gap_atr", group = g03, tooltip = "Filters out micro noise. Default 0.20 ATR isolates clear imbalance corridors.")
atrLength          = input.int(14,     "ATR Period", minval = 1, maxval = 100, inline = "gap_atr", group = g03, tooltip = "ATR calculation length.")
useBodyFilter      = input.bool(true,  "Require Candle Body Dominance (>= 45%)", inline = "filt_b", group = g03, tooltip = "Ensures the displacement candle has a dominant body relative to its range.")
cascadeDedupe      = input.bool(true,  "Skip Overlaps", inline = "filt_b", group = g03, tooltip = "Prevents drawing duplicate stacked levels in the same price range.")
useVolFilter       = input.bool(true, "Require Volume Expansion", inline = "filt_v", group = g03, tooltip = "Requires displacement candle volume to exceed the volume SMA baseline.")
volSmaLen          = input.int(20,     "Volume SMA", minval = 5, maxval = 100, inline = "filt_v", group = g03, tooltip = "Volume moving average length.")
minBarsBetweenGaps = input.int(3,      "Min Gap Spacing (bars)", minval = 1, maxval = 20, inline = "win_ctrl", group = g03, tooltip = "Minimum bars between new gap formations on the same side.")
retestWindowBars   = input.int(4,      "Retest Window (bars)", minval = 1, maxval = 8, inline = "win_ctrl", group = g03, tooltip = "Maximum bars after gap entry allowed for confirming a retest reaction.")
 
// ───────── 4. SMC PALETTE & BRANDING ─────────
g04 = "4. SMC PALETTE & BRANDING"
colBullRail   = input.color(#10B981, "Bullish Corridors (BISI)", inline = "c_bisi", group = g04)
colBullGhost  = input.color(color.new(#10B981, 93), "Tint", inline = "c_bisi", group = g04)
colBearRail   = input.color(#F43F5E, "Bearish Corridors (SIBI)", inline = "c_sibi", group = g04)
colBearGhost  = input.color(color.new(#F43F5E, 93), "Tint", inline = "c_sibi", group = g04)
colBprRail    = input.color(#A855F7, "Balanced Price Range (⚡ BPR)", inline = "c_bpr", group = g04)
colBprGhost   = input.color(color.new(#A855F7, 90), "Tint", inline = "c_bpr", group = g04)
colHtfBorder  = input.color(#F59E0B, "Macro HTF Anchor Accent", inline = "c_htf", group = g04)
colHtfFill    = input.color(color.new(#F59E0B, 92), "Tint", inline = "c_htf", group = g04)
colInvRail    = input.color(#D4AF37, "Inversion Corridors (iFVG)", inline = "c_inv", group = g04)
colInvGhost   = input.color(color.new(#D4AF37, 92), "Tint", inline = "c_inv", group = g04)
colCeRail     = input.color(color.new(#FFD400, 35), "50% C.E. Equilibrium Rail", inline = "c_ce", group = g04)
colCeTested   = input.color(#FFD400, "Tested Accent", inline = "c_ce", group = g04)
 
colBullSignal = input.color(#10B981, "Marker Accents: Bull", inline = "c_sig", group = g04, tooltip = "AxeAlgo Emerald accent for bullish demand retests.")
colBearSignal = input.color(#F43F5E, "Bear", inline = "c_sig", group = g04, tooltip = "AxeAlgo Rose accent for bearish supply retests.")
colInvSignal  = input.color(#D4AF37, "Inversion", inline = "c_sig", group = g04, tooltip = "AxeAlgo Royal Gold accent for inverted role-flip defenses.")
 
showStatusPill = input.bool(true,  "Status HUD Pill", inline = "c_hud", group = g04, tooltip = "Displays a discreet single-line status pill in the chart corner.")
pillPos        = input.string("Top Right", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], inline = "c_hud", group = g04)
showWatermark  = input.bool(true,  "AxeAlgo Canvas Watermark", group = g04, tooltip = "Displays the signature AxeAlgo watermark at the bottom of the chart.")
 
 
// ═════════════════════════════════════════════════════════════════════════════
//  DATA STRUCTURE & TYPE DEFINITIONS
// ═════════════════════════════════════════════════════════════════════════════
 
type SmcRail
    box     bx_zone
    line    ln_ce
    label   tag_lbl
    int     left_bar
    int     right_bar
    float   top
    float   bot
    float   ce
    float   vis_top
    float   vis_bot
    bool    is_bull
    bool    is_inverted
    bool    is_mitigated
    bool    is_ce_tested
    int     birth_bar
    int     invert_bar
    int     entry_bar
    bool    was_inside
    bool    touch_reacted
    int     reaction_count
    bool    is_bpr
 
atrVal   = ta.atr(atrLength)
volSma   = ta.sma(volume, volSmaLen)
trendEma = ta.ema(close, trendEmaLen)
 
// Trend Reference Baseline Plot
plot(showTrendLine and filterByTrend ? trendEma : na, "Trend Baseline (50 EMA)", color = color.new(#3B82F6, 50), linewidth = 1)
 
// Table position helper
f_getPillPos(string posTxt) =>
    switch posTxt
        "Top Left"      => position.top_left
        "Top Right"     => position.top_right
        "Bottom Left"   => position.bottom_left
        "Bottom Right"  => position.bottom_right
        => position.top_right
 
// Level Constructor: 1 sleek corridor box + 1 50% CE rail + 1 right-margin tag
f_spawnRail(int l_bar, float top, float bot, bool isBull, bool isBpr) =>
    mid = (top + bot) * 0.5
    leadBar = bar_index + forwardBars
    rCol = isBpr ? colBprRail : (isBull ? colBullRail : colBearRail)
    gCol = isBpr ? colBprGhost : (isBull ? colBullGhost : colBearGhost)
    bdrWid = isBpr ? 2 : 1
 
    // Single sleek translucent corridor box (1-2px subtle border)
    box bZone = box.new(left = l_bar, top = top, right = leadBar, bottom = bot, bgcolor = gCol, border_color = color.new(rCol, 30), border_width = bdrWid, border_style = line.style_solid)
 
    // Single 50% C.E. Equilibrium Rail
    line lCe = na
    if showCeMidline
        lCe := line.new(x1 = l_bar, y1 = mid, x2 = leadBar, y2 = mid, color = isBpr ? color.new(colBprRail, 30) : colCeRail, width = 1, style = line.style_dotted)
 
    // Pinned Right-Margin Price Scale Tag
    label tag = na
    if showPriceTags
        tagBg   = color.new(#081016, 10)
        tagTxt  = rCol
        tagPrefix = isBpr ? "⚡ BPR " : (isBull ? "▲ BISI " : "▼ SIBI ")
        tagText = tagPrefix + str.tostring(mid, format.mintick)
        tagTip  = (isBpr ? "⚡ Balanced Price Range (BPR Intersect)\n" : (isBull ? "⚡ Active Bullish Demand (BISI)\n" : "⚡ Active Bearish Supply (SIBI)\n")) +
                  "━━━━━━━━━━━━━━━━━━━━━━━━━\n" +
                  (isBpr ? "• Structure: Two-Sided Opposing Imbalance Overlap\n" : "") +
                  "• Range: " + str.tostring(bot, format.mintick) + " — " + str.tostring(top, format.mintick) + "\n" +
                  "• 50% C.E. Equilibrium: " + str.tostring(mid, format.mintick) + "\n" +
                  "• Corridor Width: " + str.tostring(top - bot, format.mintick) + " pts" +
                  (isBpr ? "\n• Note: Overlapping imbalances define a balanced equilibrium corridor." : "")
        tag := label.new(x = leadBar, y = mid, text = tagText, color = tagBg, textcolor = tagTxt, style = label.style_label_left, size = size.tiny, tooltip = tagTip)
 
    SmcRail.new(bZone, lCe, tag, l_bar, leadBar, top, bot, mid, top, bot, isBull, false, false, false, bar_index, na, na, false, false, 0, isBpr)
 
// Clean Deletion of a Rail
f_deleteRail(SmcRail r) =>
    if not na(r.bx_zone)
        box.delete(r.bx_zone)
        r.bx_zone := na
    if not na(r.ln_ce)
        line.delete(r.ln_ce)
        r.ln_ce := na
    if not na(r.tag_lbl)
        label.delete(r.tag_lbl)
        r.tag_lbl := na
 
// ─────────────────────────────────────────────────────────────────────────────
//  AESTHETIC SMC REACTION MARKER FACTORY (AXEALGO SIGNATURE STYLING)
// ─────────────────────────────────────────────────────────────────────────────
f_createSignalLabel(int x, bool isBull, bool isInv, float topVal, float botVal, float ceVal, bool isBpr) =>
    // Text formatting: Minimalist Mode displays only the AxeAlgo diamond ◆
    string txt = ""
    if minimalistMode
        txt := "◆"
    else if signalTextMode == "AxeAlgo Signature (◆ iFVG / ◆ FVG)"
        if isBpr
            txt := isBull ? "◆ BPR Support" : "◆ BPR Resist"
        else if isBull
            txt := isInv ? "◆ iFVG Support" : "◆ FVG Retest"
        else
            txt := isInv ? "◆ iFVG Resist" : "◆ FVG Retest"
    else if signalTextMode == "SMC Chevrons (▲ FVG Retest / ▼ FVG Retest)"
        if isBpr
            txt := isBull ? "▲ BPR Retest" : "▼ BPR Retest"
        else if isBull
            txt := isInv ? "▲ iFVG Support" : "▲ FVG Retest"
        else
            txt := isInv ? "▼ iFVG Resist" : "▼ FVG Retest"
    else if signalTextMode == "SMC Code (BISI / SIBI)"
        if isBpr
            txt := isBull ? "◆ BPR [BISI]" : "◆ BPR [SIBI]"
        else if isBull
            txt := isInv ? "◆ iFVG [BISI]" : "◆ BISI Retest"
        else
            txt := isInv ? "◆ iFVG [SIBI]" : "◆ SIBI Retest"
    else // "Axe Diamonds Only (◆)"
        txt := "◆"
 
    // Size resolution
    sz = signalSizeOpt == "Tiny" ? size.tiny : signalSizeOpt == "Normal" ? size.normal : size.small
 
    // Dynamic style & color resolution in AxeAlgo signature palette
    color bgCol  = na
    color txtCol = na
    styleLabel   = label.style_label_center
 
    // Text color logic: BPR uses Radiant Purple (#A855F7); Inversions use AxeAlgo Royal Gold; Standard FVGs use Emerald & Rose
    color targetAccent = isBpr ? colBprRail : (isInv ? colInvSignal : (isBull ? colBullSignal : colBearSignal))
 
    if signalStyle == "AxeAlgo Obsidian Pill" or signalStyle == "Obsidian Glass Pill (Floating)"
        // Deep obsidian glass bases matching AxeAlgo watermark (#14110B)
        bgCol      := isBpr ? color.new(#150E22, 6) : (isInv ? color.new(#14110B, 6) : (isBull ? color.new(#091712, 8) : color.new(#1A0B10, 8)))
        txtCol     := targetAccent
        styleLabel := isBull ? label.style_label_up : label.style_label_down
 
    else if signalStyle == "Directional Glass Tag"
        bgCol      := isBpr ? color.new(#150E22, 6) : (isInv ? color.new(#14110B, 6) : (isBull ? color.new(#091712, 8) : color.new(#1A0B10, 8)))
        txtCol     := targetAccent
        styleLabel := isBull ? label.style_label_up : label.style_label_down
 
    else if signalStyle == "Solid Modern Pill"
        bgCol      := isBpr ? color.new(#7C3AED, 10) : (isInv ? color.new(#D4AF37, 10) : (isBull ? color.new(#059669, 10) : color.new(#E11D48, 10)))
        txtCol     := (isInv and not isBpr) ? #14110B : #FFFFFF
        styleLabel := isBull ? label.style_label_up : label.style_label_down
 
    else // "Cyber Minimalist (No Box)"
        bgCol      := color.new(#000000, 100)
        txtCol     := targetAccent
        styleLabel := label.style_none
 
    // Rich informative educational tooltip for hover inspection
    string tipTxt = ""
    zoneStr = str.tostring(botVal, format.mintick) + " — " + str.tostring(topVal, format.mintick)
    ceStr   = str.tostring(ceVal, format.mintick)
    bprNote = isBpr ? "• Confluence: Balanced Price Range (BPR Overlap)\n" : ""
    if isBull
        if not isInv
            tipTxt := (isBpr ? "⚡ AxeAlgo iFVG · BPR Demand Retest\n" : "⚡ AxeAlgo iFVG · Bullish Demand Retest\n") +
                      "━━━━━━━━━━━━━━━━━━━━━━━━━\n" +
                      (isBpr ? "• Structure: Balanced Price Range (BISI ∩ SIBI)\n" : "• Structure: Unmitigated BISI (Demand)\n") +
                      bprNote +
                      "• Defending Range: " + zoneStr + "\n" +
                      "• 50% C.E. Equilibrium: " + ceStr + "\n" +
                      "• Reaction: Lower wick defense off equilibrium\n" +
                      "• Trend Filter: Bullish (Close >= 50 EMA)"
        else
            tipTxt := "⚡ AxeAlgo iFVG · Inversion Support Defense\n" +
                      "━━━━━━━━━━━━━━━━━━━━━━━━━\n" +
                      "• Structure: Inverted SIBI Flipped to Support\n" +
                      bprNote +
                      "• Defending Range: " + zoneStr + "\n" +
                      "• 50% C.E. Equilibrium: " + ceStr + "\n" +
                      "• Role Flip: Prior Resistance Breached ➔ Now Support\n" +
                      "• Trend Filter: Bullish (Close >= 50 EMA)"
    else
        if not isInv
            tipTxt := (isBpr ? "⚡ AxeAlgo iFVG · BPR Supply Retest\n" : "⚡ AxeAlgo iFVG · Bearish Supply Retest\n") +
                      "━━━━━━━━━━━━━━━━━━━━━━━━━\n" +
                      (isBpr ? "• Structure: Balanced Price Range (SIBI ∩ BISI)\n" : "• Structure: Unmitigated SIBI (Supply)\n") +
                      bprNote +
                      "• Defending Range: " + zoneStr + "\n" +
                      "• 50% C.E. Equilibrium: " + ceStr + "\n" +
                      "• Reaction: Upper wick defense off equilibrium\n" +
                      "• Trend Filter: Bearish (Close <= 50 EMA)"
        else
            tipTxt := "⚡ AxeAlgo iFVG · Inversion Resistance Defense\n" +
                      "━━━━━━━━━━━━━━━━━━━━━━━━━\n" +
                      "• Structure: Inverted BISI Flipped to Resistance\n" +
                      bprNote +
                      "• Defending Range: " + zoneStr + "\n" +
                      "• 50% C.E. Equilibrium: " + ceStr + "\n" +
                      "• Role Flip: Prior Support Breached ➔ Now Resistance\n" +
                      "• Trend Filter: Bearish (Close <= 50 EMA)"
 
    // Position using yloc: belowbar for bullish, abovebar for bearish
    ylocVal = isBull ? yloc.belowbar : yloc.abovebar
 
    label.new(x = x, y = na, text = txt, yloc = ylocVal, color = bgCol, textcolor = txtCol, style = styleLabel, size = sz, tooltip = tipTxt)
 
 
// ═════════════════════════════════════════════════════════════════════════════
//  IMBALANCE & DISPLACEMENT DETECTION
// ═════════════════════════════════════════════════════════════════════════════
 
f_detectDisplacement() =>
    minGap = atrVal * minGapAtr
    bool bullFound = false
    bool bearFound = false
    float rawBullTop = na
    float rawBullBot = na
    float rawBearTop = na
    float rawBearBot = na
 
    candleRange = math.max(high[1] - low[1], syminfo.mintick)
    candleBody  = math.abs(close[1] - open[1])
    bodyRatio   = candleBody / candleRange
    bodyOK      = not useBodyFilter or (bodyRatio >= 0.45)
    volOK       = not useVolFilter or na(volume) or (volume[1] >= volSma[1])
 
    if bodyOK and volOK
        // Standard 3-Candle FVG
        if imbalanceType == "Fair Value Gaps (FVG)" or imbalanceType == "Both (FVG + VI)"
            if low > high[2] and (low - high[2]) >= minGap and close[1] > open[1]
                bullFound  := true
                rawBullTop := low
                rawBullBot := high[2]
            if high < low[2] and (low[2] - high) >= minGap and close[1] < open[1]
                bearFound  := true
                rawBearTop := low[2]
                rawBearBot := high
 
        // 2-Candle Volume Imbalance
        if (imbalanceType == "Volume Imbalances (VI)" or imbalanceType == "Both (FVG + VI)") and not bullFound and not bearFound
            bLow_curr  = math.min(open[1], close[1])
            bHigh_curr = math.max(open[1], close[1])
            bLow_prev  = math.min(open[2], close[2])
            bHigh_prev = math.max(open[2], close[2])
 
            if bLow_curr > bHigh_prev and (bLow_curr - bHigh_prev) >= minGap
                bullFound  := true
                rawBullTop := bLow_curr
                rawBullBot := bHigh_prev
            else if bHigh_curr < bLow_prev and (bLow_prev - bHigh_curr) >= minGap
                bearFound  := true
                rawBearTop := bLow_prev
                rawBearBot := bHigh_curr
 
    [bullFound, bearFound, rawBullTop, rawBullBot, rawBearTop, rawBearBot]
 
 
// ═════════════════════════════════════════════════════════════════════════════
//  EXECUTION & ACTIVE LEVELS MANAGEMENT
// ═════════════════════════════════════════════════════════════════════════════
 
var array<SmcRail> activeRails = array.new<SmcRail>()
var array<label>   signalBadges = array.new<label>()
var int            lastSignalBar = na
var int            lastSignalSide = 0
var int            lastBullGapBar = na
var int            lastBearGapBar = na
 
// Event triggers for Alerts
var bool evBullFormed = false
var bool evBearFormed = false
var bool evBprFormed  = false
var bool evInverted   = false
var bool evBuySignal  = false
var bool evSellSignal = false
 
evBullFormed := false
evBearFormed := false
evBprFormed  := false
evInverted   := false
evBuySignal  := false
evSellSignal := false
 
[isBull, isBear, bTop, bBot, sTop, sBot] = f_detectDisplacement()
 
// Overlap & Proximity Deduplication Helper (0.8 ATR Buffer)
f_hasOverlap(array<SmcRail> arr, bool isBull, float top, float bot) =>
    bool overlap = false
    if array.size(arr) > 0
        for i = 0 to array.size(arr) - 1
            SmcRail r = array.get(arr, i)
            if not r.is_mitigated and r.is_bull == isBull
                // Checks price overlap or tight proximity (< 0.8 ATR separation)
                if not (top < (r.bot - atrVal * 0.8) or bot > (r.top + atrVal * 0.8))
                    overlap := true
                    break
    overlap
 
// Checks if a candidate zone overlaps an active opposing imbalance zone, forming a Balanced Price Range (BPR)
f_checkBprOverlap(array<SmcRail> arr, bool isBull, float zTop, float zBot) =>
    bool hasBpr = false
    if showBpr and array.size(arr) > 0
        for i = 0 to array.size(arr) - 1
            SmcRail cand = array.get(arr, i)
            bool candActsBull = cand.is_bull != cand.is_inverted
            if not cand.is_mitigated and candActsBull != isBull
                ovTop = math.min(zTop, cand.top)
                ovBot = math.max(zBot, cand.bot)
                if ovTop > ovBot and (ovTop - ovBot) >= math.min(zTop - zBot, cand.top - cand.bot) * 0.20
                    hasBpr := true
                    break
    hasBpr
 
// Bullish Level Creation
bullSpacingOK = na(lastBullGapBar) or (bar_index - lastBullGapBar) >= minBarsBetweenGaps
if isBull and showBullFvg and bullSpacingOK
    bool allowBull = true
    if cascadeDedupe and f_hasOverlap(activeRails, true, bTop, bBot)
        allowBull := false
 
    if allowBull
        bool isBprBull = showBpr and f_checkBprOverlap(activeRails, true, bTop, bBot)
        SmcRail rBull  = f_spawnRail(bar_index - 1, bTop, bBot, true, isBprBull)
        array.unshift(activeRails, rBull)
        evBullFormed   := true
        evBprFormed    := evBprFormed or isBprBull
        lastBullGapBar := bar_index
 
// Bearish Level Creation
bearSpacingOK = na(lastBearGapBar) or (bar_index - lastBearGapBar) >= minBarsBetweenGaps
if isBear and showBearFvg and bearSpacingOK
    bool allowBear = true
    if cascadeDedupe and f_hasOverlap(activeRails, false, sTop, sBot)
        allowBear := false
 
    if allowBear
        bool isBprBear = showBpr and f_checkBprOverlap(activeRails, false, sTop, sBot)
        SmcRail rBear  = f_spawnRail(bar_index - 1, sTop, sBot, false, isBprBear)
        array.unshift(activeRails, rBear)
        evBearFormed   := true
        evBprFormed    := evBprFormed or isBprBear
        lastBearGapBar := bar_index
 
 
// ─────────────────────────────────────────────────────────────────────────────
//  PER-BAR DYNAMIC PROJECTION, INVERSIONS & ACTIONABLE RETEST SIGNALS
// ─────────────────────────────────────────────────────────────────────────────
f_updateRails(int lastSigIn, int lastSideIn) =>
    bool anyFlip     = false
    bool anyBuy      = false
    bool anySell     = false
    int  lastSigOut  = lastSigIn
    int  lastSideOut = lastSideIn
    leadBar = bar_index + forwardBars
 
    // Active projection counters
    int supplyProjected = 0
    int demandProjected = 0
 
    if array.size(activeRails) > 0
        for i = 0 to array.size(activeRails) - 1
            SmcRail r = array.get(activeRails, i)
 
            if not r.is_mitigated
                isSupplyRole = r.is_inverted ? r.is_bull : not r.is_bull
 
                // Precision Selective Projection: Only the nearest key levels extend to live price scale!
                bool canExtend = false
                if isSupplyRole
                    supplyProjected += 1
                    if supplyProjected <= maxActiveSupply
                        canExtend := true
                else
                    demandProjected += 1
                    if demandProjected <= maxActiveDemand
                        canExtend := true
 
                if canExtend
                    if r.right_bar != leadBar
                        r.right_bar := leadBar
                        if not na(r.bx_zone)
                            box.set_right(r.bx_zone, leadBar)
                        if not na(r.ln_ce)
                            line.set_x2(r.ln_ce, leadBar)
                        if not na(r.tag_lbl)
                            label.set_x(r.tag_lbl, leadBar)
                else
                    // Older unmitigated zone: freeze locally once without right tag
                    histRight = math.min(r.birth_bar + 35, bar_index)
                    if r.right_bar != histRight
                        r.right_bar := histRight
                        if not na(r.bx_zone) and (bar_index - histRight < 4500)
                            box.set_right(r.bx_zone, histRight)
                        if not na(r.ln_ce) and (bar_index - histRight < 4500)
                            line.set_x2(r.ln_ce, histRight)
                        if not na(r.tag_lbl)
                            label.delete(r.tag_lbl)
                            r.tag_lbl := na
 
                // ───────── STAGE 1: UNINVERTED SMC GAPS ─────────
                if not r.is_inverted
                    if r.is_bull // Bullish FVG (Demand)
                        isTapped = low <= r.top and high >= r.bot
                        if isTapped and not r.is_ce_tested and low <= r.ce
                            r.is_ce_tested := true
                            if not na(r.ln_ce)
                                line.set_color(r.ln_ce, colCeTested)
                                line.set_width(r.ln_ce, 2)
 
                        // Dynamic Real-time Trimming
                        if trimOnFill and isTapped and low < r.vis_top
                            r.vis_top := math.max(low, r.bot)
                            if not na(r.bx_zone)
                                box.set_top(r.bx_zone, r.vis_top)
 
                        // RETEST REJECTION BOUNCE (BULLISH REACTION)
                        if isTapped and not r.touch_reacted and r.reaction_count < maxReactionsPerZone
                            candleRange = math.max(high - low, syminfo.mintick)
                            lowerWick   = math.min(open, close) - low
                            wickRej     = (lowerWick >= candleRange * 0.20) or (close >= (high + low) * 0.50)
                            trendPass   = not filterByTrend or (close >= trendEma)
                            bool bullConfirmed = false
                            if retestFilterMode == "Wick Rejection & Close (Strict)"
                                bullConfirmed := close > open and wickRej and close >= r.ce and trendPass
                            else if retestFilterMode == "Candle Close (Standard)"
                                bullConfirmed := close > open and close >= (high + low) * 0.45 and trendPass
                            else
                                bullConfirmed := close > open and trendPass
 
                            if bullConfirmed
                                r.touch_reacted  := true
                                r.reaction_count += 1
                                anyBuy := true
                                int cooldownReq  = (lastSideOut == 1) ? sigMomentumCooldown : minBarsBetweenSig
                                cooldownOK  = na(lastSigOut) or (bar_index - lastSigOut) >= cooldownReq
                                alternateOK = not alternateSignals or (lastSideOut != 1)
                                if showSignals and cooldownOK and alternateOK
                                    sigLbl = f_createSignalLabel(bar_index, true, false, r.top, r.bot, r.ce, r.is_bpr)
                                    array.push(signalBadges, sigLbl)
                                    lastSigOut  := bar_index
                                    lastSideOut := 1
 
                        isBreached = invBreakMethod == "Candle Close" ? close < r.bot : low < r.bot
                        isMit      = mitMethod == "Candle Close" ? close <= r.bot : mitMethod == "50% C.E. Touch" ? low <= r.ce : low <= r.bot
 
                        if isBreached and showInversion
                            // Inversion Role-Flip: Bullish demand becomes Bearish resistance
                            r.is_inverted := true
                            r.invert_bar  := bar_index
                            r.was_inside  := false
                            r.touch_reacted := false
                            r.vis_top     := r.top
                            r.vis_bot     := r.bot
                            anyFlip       := true
 
                            if not na(r.bx_zone)
                                box.set_top(r.bx_zone, r.top)
                                box.set_bottom(r.bx_zone, r.bot)
                                box.set_bgcolor(r.bx_zone, colInvGhost)
                                box.set_border_color(r.bx_zone, color.new(colInvRail, 30))
                                box.set_border_style(r.bx_zone, line.style_dashed)
 
                            if not na(r.ln_ce)
                                line.set_color(r.ln_ce, color.new(colInvRail, 20))
 
                            if showPriceTags and not na(r.tag_lbl)
                                label.set_text(r.tag_lbl, "⚡ iFVG Resist " + str.tostring(r.ce, format.mintick))
                                label.set_textcolor(r.tag_lbl, colInvRail)
                                label.set_tooltip(r.tag_lbl, "⚡ Inverted Resistance (iFVG)\n━━━━━━━━━━━━━━━━━━━━━━━━━\n• Flipped Role: Prior Bull Demand Breached\n• Defending Range: " + str.tostring(r.bot, format.mintick) + " — " + str.tostring(r.top, format.mintick) + "\n• Defended Equilibrium (C.E.): " + str.tostring(r.ce, format.mintick))
 
                        else if isMit and not showInversion
                            r.is_mitigated := true
                            if mitDisplay == "Fade Level"
                                if not na(r.bx_zone)
                                    box.set_right(r.bx_zone, bar_index)
                                    box.set_bgcolor(r.bx_zone, color.new(colBullRail, 96))
                                    box.set_border_color(r.bx_zone, color.new(colBullRail, 92))
                                    box.set_border_style(r.bx_zone, line.style_solid)
                                if not na(r.ln_ce)
                                    line.delete(r.ln_ce)
                                    r.ln_ce := na
                                if not na(r.tag_lbl)
                                    label.delete(r.tag_lbl)
                                    r.tag_lbl := na
                            else
                                f_deleteRail(r)
 
                    else // Bearish FVG (Supply)
                        isTapped = high >= r.bot and low <= r.top
                        if isTapped and not r.is_ce_tested and high >= r.ce
                            r.is_ce_tested := true
                            if not na(r.ln_ce)
                                line.set_color(r.ln_ce, colCeTested)
                                line.set_width(r.ln_ce, 2)
 
                        // Dynamic Real-time Trimming
                        if trimOnFill and isTapped and high > r.vis_bot
                            r.vis_bot := math.min(high, r.top)
                            if not na(r.bx_zone)
                                box.set_bottom(r.bx_zone, r.vis_bot)
 
                        // RETEST REJECTION FALL (BEARISH REACTION)
                        if isTapped and not r.touch_reacted and r.reaction_count < maxReactionsPerZone
                            candleRange = math.max(high - low, syminfo.mintick)
                            upperWick   = high - math.max(open, close)
                            wickRej     = (upperWick >= candleRange * 0.20) or (close <= (high + low) * 0.50)
                            trendPass   = not filterByTrend or (close <= trendEma)
                            bool bearConfirmed = false
                            if retestFilterMode == "Wick Rejection & Close (Strict)"
                                bearConfirmed := close < open and wickRej and close <= r.ce and trendPass
                            else if retestFilterMode == "Candle Close (Standard)"
                                bearConfirmed := close < open and close <= (high + low) * 0.55 and trendPass
                            else
                                bearConfirmed := close < open and trendPass
 
                            if bearConfirmed
                                r.touch_reacted  := true
                                r.reaction_count += 1
                                anySell := true
                                int cooldownReq  = (lastSideOut == -1) ? sigMomentumCooldown : minBarsBetweenSig
                                cooldownOK  = na(lastSigOut) or (bar_index - lastSigOut) >= cooldownReq
                                alternateOK = not alternateSignals or (lastSideOut != -1)
                                if showSignals and cooldownOK and alternateOK
                                    sigLbl = f_createSignalLabel(bar_index, false, false, r.top, r.bot, r.ce, r.is_bpr)
                                    array.push(signalBadges, sigLbl)
                                    lastSigOut  := bar_index
                                    lastSideOut := -1
 
                        isBreached = invBreakMethod == "Candle Close" ? close > r.top : high > r.top
                        isMit      = mitMethod == "Candle Close" ? close >= r.top : mitMethod == "50% C.E. Touch" ? high >= r.ce : high >= r.top
 
                        if isBreached and showInversion
                            // Inversion Role-Flip: Bearish supply becomes Bullish support
                            r.is_inverted := true
                            r.invert_bar  := bar_index
                            r.was_inside  := false
                            r.touch_reacted := false
                            r.vis_top     := r.top
                            r.vis_bot     := r.bot
                            anyFlip       := true
 
                            if not na(r.bx_zone)
                                box.set_top(r.bx_zone, r.top)
                                box.set_bottom(r.bx_zone, r.bot)
                                box.set_bgcolor(r.bx_zone, colInvGhost)
                                box.set_border_color(r.bx_zone, color.new(colInvRail, 30))
                                box.set_border_style(r.bx_zone, line.style_dashed)
 
                            if not na(r.ln_ce)
                                line.set_color(r.ln_ce, color.new(colInvRail, 20))
 
                            if showPriceTags and not na(r.tag_lbl)
                                label.set_text(r.tag_lbl, "⚡ iFVG Supp " + str.tostring(r.ce, format.mintick))
                                label.set_textcolor(r.tag_lbl, colInvRail)
                                label.set_tooltip(r.tag_lbl, "⚡ Inverted Support (iFVG)\n━━━━━━━━━━━━━━━━━━━━━━━━━\n• Flipped Role: Prior Bear Supply Breached\n• Defending Range: " + str.tostring(r.bot, format.mintick) + " — " + str.tostring(r.top, format.mintick) + "\n• Defended Equilibrium (C.E.): " + str.tostring(r.ce, format.mintick))
 
                        else if isMit and not showInversion
                            r.is_mitigated := true
                            if mitDisplay == "Fade Level"
                                if not na(r.bx_zone)
                                    box.set_right(r.bx_zone, bar_index)
                                    box.set_bgcolor(r.bx_zone, color.new(colBearRail, 96))
                                    box.set_border_color(r.bx_zone, color.new(colBearRail, 92))
                                    box.set_border_style(r.bx_zone, line.style_solid)
                                if not na(r.ln_ce)
                                    line.delete(r.ln_ce)
                                    r.ln_ce := na
                                if not na(r.tag_lbl)
                                    label.delete(r.tag_lbl)
                                    r.tag_lbl := na
                            else
                                f_deleteRail(r)
 
                // ───────── STAGE 2: INVERTED (iFVG) RETEST CONFIRMATION ─────────
                else
                    if r.is_bull // Originally Bullish -> Flipped Bearish Resistance
                        if close > r.top
                            r.is_mitigated := true
                            if mitDisplay == "Fade Level"
                                if not na(r.bx_zone)
                                    box.set_right(r.bx_zone, bar_index)
                                    box.set_bgcolor(r.bx_zone, color.new(colInvRail, 96))
                                    box.set_border_color(r.bx_zone, color.new(colInvRail, 92))
                                    box.set_border_style(r.bx_zone, line.style_solid)
                                if not na(r.ln_ce)
                                    line.delete(r.ln_ce)
                                    r.ln_ce := na
                                if not na(r.tag_lbl)
                                    label.delete(r.tag_lbl)
                                    r.tag_lbl := na
                            else
                                f_deleteRail(r)
                        else
                            inside = high >= r.bot and low <= r.top and bar_index > r.invert_bar
                            entered = inside and not r.was_inside
                            if entered
                                r.entry_bar := bar_index
                                r.touch_reacted := false
 
                            inEvalWindow = inside and not r.touch_reacted and r.reaction_count < maxReactionsPerZone and not na(r.entry_bar) and (bar_index - r.entry_bar) < retestWindowBars
                            if inEvalWindow
                                candleRange = math.max(high - low, syminfo.mintick)
                                upperWick   = high - math.max(open, close)
                                wickRej     = (upperWick >= candleRange * 0.20) or (close <= (high + low) * 0.50)
                                trendPass   = not filterByTrend or (close <= trendEma)
                                bool bearConfirmed = false
                                if retestFilterMode == "Wick Rejection & Close (Strict)"
                                    bearConfirmed := close < open and wickRej and close <= r.ce and trendPass
                                else if retestFilterMode == "Candle Close (Standard)"
                                    bearConfirmed := close < open and close <= (high + low) * 0.55 and trendPass
                                else
                                    bearConfirmed := close < open and trendPass
 
                                if bearConfirmed
                                    r.touch_reacted  := true
                                    r.reaction_count += 1
                                    anySell := true
                                    int cooldownReq  = (lastSideOut == -1) ? sigMomentumCooldown : minBarsBetweenSig
                                    cooldownOK  = na(lastSigOut) or (bar_index - lastSigOut) >= cooldownReq
                                    alternateOK = not alternateSignals or (lastSideOut != -1)
                                    if showSignals and cooldownOK and alternateOK
                                        sigLbl = f_createSignalLabel(bar_index, false, true, r.top, r.bot, r.ce, r.is_bpr)
                                        array.push(signalBadges, sigLbl)
                                        lastSigOut  := bar_index
                                        lastSideOut := -1
                            r.was_inside := inside
 
                    else // Originally Bearish -> Flipped Bullish Support
                        if close < r.bot
                            r.is_mitigated := true
                            if mitDisplay == "Fade Level"
                                if not na(r.bx_zone)
                                    box.set_right(r.bx_zone, bar_index)
                                    box.set_bgcolor(r.bx_zone, color.new(colInvRail, 96))
                                    box.set_border_color(r.bx_zone, color.new(colInvRail, 92))
                                    box.set_border_style(r.bx_zone, line.style_solid)
                                if not na(r.ln_ce)
                                    line.delete(r.ln_ce)
                                    r.ln_ce := na
                                if not na(r.tag_lbl)
                                    label.delete(r.tag_lbl)
                                    r.tag_lbl := na
                            else
                                f_deleteRail(r)
                        else
                            inside = low <= r.top and high >= r.bot and bar_index > r.invert_bar
                            entered = inside and not r.was_inside
                            if entered
                                r.entry_bar := bar_index
                                r.touch_reacted := false
 
                            inEvalWindow = inside and not r.touch_reacted and r.reaction_count < maxReactionsPerZone and not na(r.entry_bar) and (bar_index - r.entry_bar) < retestWindowBars
                            if inEvalWindow
                                candleRange = math.max(high - low, syminfo.mintick)
                                lowerWick   = math.min(open, close) - low
                                wickRej     = (lowerWick >= candleRange * 0.20) or (close >= (high + low) * 0.50)
                                trendPass   = not filterByTrend or (close >= trendEma)
                                bool bullConfirmed = false
                                if retestFilterMode == "Wick Rejection & Close (Strict)"
                                    bullConfirmed := close > open and wickRej and close >= r.ce and trendPass
                                else if retestFilterMode == "Candle Close (Standard)"
                                    bullConfirmed := close > open and close >= (high + low) * 0.45 and trendPass
                                else
                                    bullConfirmed := close > open and trendPass
 
                                if bullConfirmed
                                    r.touch_reacted  := true
                                    r.reaction_count += 1
                                    anyBuy := true
                                    int cooldownReq  = (lastSideOut == 1) ? sigMomentumCooldown : minBarsBetweenSig
                                    cooldownOK  = na(lastSigOut) or (bar_index - lastSigOut) >= cooldownReq
                                    alternateOK = not alternateSignals or (lastSideOut != 1)
                                    if showSignals and cooldownOK and alternateOK
                                        sigLbl = f_createSignalLabel(bar_index, true, true, r.top, r.bot, r.ce, r.is_bpr)
                                        array.push(signalBadges, sigLbl)
                                        lastSigOut  := bar_index
                                        lastSideOut := 1
                            r.was_inside := inside
 
    [anyFlip, anyBuy, anySell, lastSigOut, lastSideOut]
 
// Execute Lifecycle
[evFl, evB, evS, lsOut, lsSide] = f_updateRails(lastSignalBar, lastSignalSide)
evInverted     := evFl
evBuySignal    := evB
evSellSignal   := evS
lastSignalBar  := lsOut
lastSignalSide := lsSide
 
// Optional Trigger Candle Highlight
sigBarColor = highlightSignalBars ? (evBuySignal ? color.new(colBullSignal, 20) : evSellSignal ? color.new(colBearSignal, 20) : na) : na
barcolor(sigBarColor, title = "Reaction Trigger Candle")
 
 
// ═════════════════════════════════════════════════════════════════════════════
//  HIGHER-TIMEFRAME (HTF) NON-REPAINTING ANCHOR CORRIDOR
// ═════════════════════════════════════════════════════════════════════════════
 
f_isStrictlyHigher(string tf) =>
    timeframe.in_seconds(tf) > timeframe.in_seconds(timeframe.period)
 
f_htfBarSnapshot() =>
    fH = high[3]
    fL = low[3]
    dO = open[2]
    dC = close[2]
    tH = high[1]
    tL = low[1]
    atrR = nz(ta.atr(14)[1], syminfo.mintick)
    [time[1], fH, fL, dO, dC, tH, tL, atrR]
 
bool htfIsHigher = f_isStrictlyHigher(htfTimeframe)
 
// Safe historical completed HTF security fetch (zero repainting)
[htf_t, htf_firstH, htf_firstL, htf_dispO, htf_dispC, htf_thirdH, htf_thirdL, htf_atr] = request.security(
     syminfo.tickerid,
     htfIsHigher ? htfTimeframe : timeframe.period,
     f_htfBarSnapshot(),
     lookahead = barmerge.lookahead_off
)
 
var box   htfDemBx    = na
var line  htfDemCe    = na
var label htfDemLbl   = na
var float htfDemTop   = na
var float htfDemBot   = na
var float htfDemMid   = na
var bool  htfDemLive  = false
var int   htfDemLeft  = na
 
var box   htfSupBx    = na
var line  htfSupCe    = na
var label htfSupLbl   = na
var float htfSupTop   = na
var float htfSupBot   = na
var float htfSupMid   = na
var bool  htfSupLive  = false
var int   htfSupLeft  = na
 
var bool evHtfFormed = false
evHtfFormed := false
 
if showHtfAnchor and htfIsHigher
    htfChanged = ta.change(htf_t) != 0
 
    // HTF Bullish FVG
    bool htfBullFound = htfChanged and htf_thirdL > htf_firstH and (htf_thirdL - htf_firstH) >= minGapAtr * htf_atr and htf_dispC > htf_dispO
    if htfBullFound
        if not na(htfDemBx)
            box.delete(htfDemBx)
        if not na(htfDemCe)
            line.delete(htfDemCe)
        if not na(htfDemLbl)
            label.delete(htfDemLbl)
 
        htfDemTop  := htf_thirdL
        htfDemBot  := htf_firstH
        htfDemMid  := (htfDemTop + htfDemBot) * 0.5
        htfDemLive := true
        htfDemLeft := bar_index - 1
        leadBarHtf = bar_index + forwardBars
 
        htfDemBx  := box.new(left = htfDemLeft, top = htfDemTop, right = leadBarHtf, bottom = htfDemBot, bgcolor = colHtfFill, border_color = color.new(colHtfBorder, 20), border_width = 1, border_style = line.style_dashed)
        htfDemCe  := line.new(x1 = htfDemLeft, y1 = htfDemMid, x2 = leadBarHtf, y2 = htfDemMid, color = color.new(colHtfBorder, 30), width = 1, style = line.style_dotted)
        if showPriceTags
            htfDemTip = "🔱 AxeAlgo Macro HTF Demand\n━━━━━━━━━━━━━━━━━━━━━━━━━\n• Macro Timeframe: " + htfTimeframe + "\n• Range: " + str.tostring(htfDemBot, format.mintick) + " — " + str.tostring(htfDemTop, format.mintick) + "\n• 50% Equilibrium: " + str.tostring(htfDemMid, format.mintick) + "\n• Non-Repainting Reference Anchor"
            htfDemLbl := label.new(x = leadBarHtf, y = htfDemMid, text = "🔱 HTF [" + htfTimeframe + "] Demand " + str.tostring(htfDemMid, format.mintick), color = color.new(#14110B, 10), textcolor = colHtfBorder, style = label.style_label_left, size = size.tiny, tooltip = htfDemTip)
        evHtfFormed := true
 
    // HTF Bearish FVG
    bool htfBearFound = htfChanged and htf_thirdH < htf_firstL and (htf_firstL - htf_thirdH) >= minGapAtr * htf_atr and htf_dispC < htf_dispO
    if htfBearFound
        if not na(htfSupBx)
            box.delete(htfSupBx)
        if not na(htfSupCe)
            line.delete(htfSupCe)
        if not na(htfSupLbl)
            label.delete(htfSupLbl)
 
        htfSupTop  := htf_firstL
        htfSupBot  := htf_thirdH
        htfSupMid  := (htfSupTop + htfSupBot) * 0.5
        htfSupLive := true
        htfSupLeft := bar_index - 1
        leadBarHtf = bar_index + forwardBars
 
        htfSupBx  := box.new(left = htfSupLeft, top = htfSupTop, right = leadBarHtf, bottom = htfSupBot, bgcolor = colHtfFill, border_color = color.new(colHtfBorder, 20), border_width = 1, border_style = line.style_dashed)
        htfSupCe  := line.new(x1 = htfSupLeft, y1 = htfSupMid, x2 = leadBarHtf, y2 = htfSupMid, color = color.new(colHtfBorder, 30), width = 1, style = line.style_dotted)
        if showPriceTags
            htfSupTip = "🔱 AxeAlgo Macro HTF Supply\n━━━━━━━━━━━━━━━━━━━━━━━━━\n• Macro Timeframe: " + htfTimeframe + "\n• Range: " + str.tostring(htfSupBot, format.mintick) + " — " + str.tostring(htfSupTop, format.mintick) + "\n• 50% Equilibrium: " + str.tostring(htfSupMid, format.mintick) + "\n• Non-Repainting Reference Anchor"
            htfSupLbl := label.new(x = leadBarHtf, y = htfSupMid, text = "🔱 HTF [" + htfTimeframe + "] Supply " + str.tostring(htfSupMid, format.mintick), color = color.new(#14110B, 10), textcolor = colHtfBorder, style = label.style_label_left, size = size.tiny, tooltip = htfSupTip)
        evHtfFormed := true
 
    // Dynamic rightward extension & mitigation
    leadBarNow = bar_index + forwardBars
    if htfDemLive
        if close < htfDemBot
            htfDemLive := false
            if not na(htfDemBx)
                box.set_right(htfDemBx, bar_index)
                box.set_border_style(htfDemBx, line.style_dotted)
            if not na(htfDemCe)
                line.delete(htfDemCe)
                htfDemCe := na
            if not na(htfDemLbl)
                label.delete(htfDemLbl)
                htfDemLbl := na
        else
            if not na(htfDemBx)
                box.set_right(htfDemBx, leadBarNow)
            if not na(htfDemCe)
                line.set_x2(htfDemCe, leadBarNow)
            if not na(htfDemLbl)
                label.set_x(htfDemLbl, leadBarNow)
 
    if htfSupLive
        if close > htfSupTop
            htfSupLive := false
            if not na(htfSupBx)
                box.set_right(htfSupBx, bar_index)
                box.set_border_style(htfSupBx, line.style_dotted)
            if not na(htfSupCe)
                line.delete(htfSupCe)
                htfSupCe := na
            if not na(htfSupLbl)
                label.delete(htfSupLbl)
                htfSupLbl := na
        else
            if not na(htfSupBx)
                box.set_right(htfSupBx, leadBarNow)
            if not na(htfSupCe)
                line.set_x2(htfSupCe, leadBarNow)
            if not na(htfSupLbl)
                label.set_x(htfSupLbl, leadBarNow)
else
    if not na(htfDemBx)
        box.delete(htfDemBx)
        htfDemBx := na
    if not na(htfDemCe)
        line.delete(htfDemCe)
        htfDemCe := na
    if not na(htfDemLbl)
        label.delete(htfDemLbl)
        htfDemLbl := na
    if not na(htfSupBx)
        box.delete(htfSupBx)
        htfSupBx := na
    if not na(htfSupCe)
        line.delete(htfSupCe)
        htfSupCe := na
    if not na(htfSupLbl)
        label.delete(htfSupLbl)
        htfSupLbl := na
    htfDemLive := false
    htfSupLive := false
 
 
// ─────────────────────────────────────────────────────────────────────────────
//  SAFE BUFFER HYGIENE
// ─────────────────────────────────────────────────────────────────────────────
 
// Prune ancient levels (> 4000 bars back) and keep active buffer under safe threshold
if array.size(activeRails) > 0
    for i = array.size(activeRails) - 1 to 0
        if i < array.size(activeRails)
            SmcRail cand = array.get(activeRails, i)
            if (bar_index - cand.birth_bar > 4000)
                SmcRail oldR = array.remove(activeRails, i)
                f_deleteRail(oldR)
 
// Prune oldest mitigated levels to maintain safe Pine Script memory
while array.size(activeRails) > 35
    int delIdx = array.size(activeRails) - 1
    for i = array.size(activeRails) - 1 to 0
        SmcRail cand = array.get(activeRails, i)
        if cand.is_mitigated
            delIdx := i
            break
    SmcRail oldR = array.remove(activeRails, delIdx)
    f_deleteRail(oldR)
 
// Signal Badges: Keep only 40 latest
while array.size(signalBadges) > 40
    label.delete(array.shift(signalBadges))
 
 
// ═════════════════════════════════════════════════════════════════════════════
//  MINIMALIST STATUS PILL & ROYAL WATERMARK
// ═════════════════════════════════════════════════════════════════════════════
 
int actBull = 0
int actBear = 0
int actSupp = 0
int actRes  = 0
int actBpr  = 0
float nearestDistance = na
string nearestName = "None"
 
if array.size(activeRails) > 0
    for i = 0 to array.size(activeRails) - 1
        r = array.get(activeRails, i)
        if not r.is_mitigated and not na(r.tag_lbl)
            if r.is_bpr
                actBpr += 1
            if not r.is_inverted
                if r.is_bull
                    actBull += 1
                else
                    actBear += 1
            else
                if r.is_bull
                    actRes += 1
                else
                    actSupp += 1
 
            dist = close > r.top ? close - r.top : close < r.bot ? r.bot - close : 0.0
            if na(nearestDistance) or dist < nearestDistance
                nearestDistance := dist
                nearestName := r.is_bpr ? "⚡ BPR" : (r.is_inverted ? (r.is_bull ? "iFVG Resist" : "iFVG Support") : (r.is_bull ? "Bull FVG" : "Bear FVG"))
 
totDemand = actBull + actSupp
totSupply = actBear + actRes
imbalanceBias = totDemand > totSupply ? "Bullish Imbalance" : totSupply > totDemand ? "Bearish Imbalance" : "Balanced"
 
// Minimalist Single-Line Status Pill
if showStatusPill and barstate.islast
    pillPosVal = f_getPillPos(pillPos)
    var table pill = table.new(position = pillPosVal, columns = 1, rows = 1, bgcolor = color.new(#081016, 20), border_width = 1, border_color = color.new(#D4AF37, 70), frame_width = 1, frame_color = color.new(#D4AF37, 70))
    distStr = na(nearestDistance) ? "None" : str.tostring(nearestDistance, format.mintick) + " pts (" + str.tostring(nearestDistance / atrVal, "#.#") + " ATR)"
    bprPillTxt = actBpr > 0 ? "  |  ⚡ " + str.tostring(actBpr) + " BPR" : ""
    htfPillTxt = (htfDemLive or htfSupLive) ? "  |  🔱 HTF [" + htfTimeframe + "]" : ""
    pillTxt = "⚡ AxeAlgo iFVG · " + imbalanceBias + "  |  ▲ " + str.tostring(totDemand) + " Supp  ▼ " + str.tostring(totSupply) + " Res" + bprPillTxt + htfPillTxt + "  |  Nearest: " + nearestName + " (" + distStr + ")"
    table.cell(pill, 0, 0, pillTxt, text_color = #F5F5F5, bgcolor = color.new(#0D151D, 15), text_size = size.tiny, text_halign = text.align_center)
 
// Signature Royal Gold Watermark
var table wm = table.new(position.bottom_center, 2, 1, frame_width = 1, border_width = 0)
if showWatermark and barstate.islast
    dark       = true
    wm_bg      = dark ? color.new(#14110B, 0) : color.new(#F2EAD3, 0)
    wm_dot_col = dark ? color.new(#D4AF37, 15) : color.new(#B8860B, 10)
    wm_txt_col = dark ? color.new(#C9B37E, 0) : color.new(#7A6423, 0)
    wm_frm_col = dark ? color.new(#D4AF37, 60) : color.new(#B8860B, 60)
 
    table.set_frame_color(wm, wm_frm_col)
    table.cell(wm, 0, 0, " ◆ ", bgcolor = wm_bg, text_color = wm_dot_col, text_size = size.small, text_formatting = text.format_bold)
    table.cell(wm, 1, 0, " A X E A L G O ", bgcolor = wm_bg, text_color = wm_txt_col, text_size = size.small, text_formatting = text.format_bold)
 
 
// ═════════════════════════════════════════════════════════════════════════════
//  ALERT CONDITIONS
// ═════════════════════════════════════════════════════════════════════════════
 
alertcondition(evBuySignal,  "Bullish Retest Reaction", "iFVG Core: Bullish SMC rejection confirmed on {{ticker}} ({{interval}})")
alertcondition(evSellSignal, "Bearish Retest Reaction", "iFVG Core: Bearish SMC rejection confirmed on {{ticker}} ({{interval}})")
alertcondition(evBullFormed, "Bullish FVG Formed", "iFVG Core: New Bullish Fair Value Gap formed on {{ticker}} ({{interval}})")
alertcondition(evBearFormed, "Bearish FVG Formed", "iFVG Core: New Bearish Fair Value Gap formed on {{ticker}} ({{interval}})")
alertcondition(evInverted,   "iFVG Inversion Role Flip", "iFVG Core: Zone inverted and flipped role on {{ticker}} ({{interval}})")
alertcondition(evBprFormed,  "Balanced Price Range (BPR) Formed", "iFVG Core: Balanced Price Range (BPR) formed on {{ticker}} ({{interval}})")
alertcondition(evHtfFormed,  "Macro HTF Corridor Formed", "iFVG Core: New Macro HTF Reference Corridor formed on {{ticker}} ({{interval}})")

← 返回列表