Imbalance Matrix [JOAT]

officialjackofalltrades · study · 898 行 · 点赞 74 · 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/
// © officialjackofalltrades
//@version=6
indicator("Imbalance Matrix [JOAT]", shorttitle = "IMB [JOAT]", overlay = true, max_boxes_count = 200, max_lines_count = 200, max_labels_count = 250)
 
// ─── Inputs ───────────────────────────────────────────────────────────────
const string G_GEN = "General"
const string G_FVG = "Fair value gaps (BISI / SIBI)"
const string G_IFV = "Inversion FVGs (iFVG)"
const string G_BPR = "Balanced price ranges (BPR)"
const string G_VI  = "Volume imbalances (VI)"
const string G_DSP = "Displacement candles"
const string G_STR = "Structure"
const string G_PD  = "Premium / discount"
const string G_DSH = "Dashboard"
const string G_COL = "Colours (Theme = Custom)"
 
themeIn   = input.string("Aqua Ember", "Theme", options = ["Aqua Ember", "Mystic", "Emerald Ruby", "Ice Magenta", "Royal Gold", "Ocean Amber", "Sakura Teal", "Aurora", "Mono", "Custom"], group = G_GEN, tooltip = "Colour pair for the whole map and the dashboard. Aqua Ember (aqua bull, ember orange bear) is this indicator's own palette; the others are the JOAT free-line palettes. Mono is a clean grey pair (deep grey bull on a light chart). Custom uses the five colours at the bottom of the settings.", display = display.none)
modeIn    = input.string("Live", "Display mode", options = ["Live", "All History"], group = G_GEN, tooltip = "Live keeps the newest 6 BOS / CHoCH lines and tags on the chart. All History keeps up to 100.", display = display.none)
paintBias = input.bool(true, "Paint candles by bias", group = G_GEN, tooltip = "Candles take the bull colour after a close above a major swing high and the bear colour after a close below a major swing low (the Bias row of the dashboard). Solid colours, no gradient.", display = display.none)
drawAtr   = input.float(8.0, "Draw within (ATR)", minval = 1.0, maxval = 50.0, step = 0.5, group = G_GEN, tooltip = "Only zones within this many ATR(14) of the close are drawn, so a zone far away never squashes the candles. Zones further out still count in the dashboard. The premium / discount gradient is clipped to the same distance.", display = display.none)
extBars   = input.int(8, "Zone right end (bars)", minval = 2, maxval = 60, group = G_GEN, tooltip = "How far right of the last bar the live zones end. Their tags start there, so the chart needs a right margin of about this + 32 bars.", display = display.none)
tagSizeIn = input.string("Small", "Tag size", options = ["Small", "Normal", "Large"], group = G_GEN, tooltip = "Text size of every tag on the chart. The stacking gap between right-edge tags grows with it.", display = display.none)
 
showFvg   = input.bool(true, "Show BISI / SIBI", group = G_FVG, tooltip = "Three-candle fair value gaps, formed on closed bars. BISI = bull gap (a low above the high two candles back), SIBI = bear gap (a high under the low two candles back). Gaps are tracked even when this is off, because BPRs, iFVGs, D tags and the fill rate are built from them.", display = display.none)
fvgMax    = input.int(4, "Gaps drawn per side", minval = 1, maxval = 10, group = G_FVG, tooltip = "The nearest open gaps to price on each side, inside the Draw within distance. Up to 30 open gaps per side are tracked and counted in the dashboard.", display = display.none)
fvgMinAtr = input.float(0.3, "Minimum gap size (ATR)", minval = 0.0, maxval = 5.0, step = 0.05, group = G_FVG, tooltip = "Smallest gap kept, as a multiple of ATR(14) on the bar the gap forms.", display = display.none)
showCE    = input.bool(true, "CE line (50 %)", group = G_FVG, tooltip = "A dotted line at each gap's consequent encroachment, the middle of the full gap. It disappears once wicks have filled past it.", display = display.none)
fvgFade   = input.bool(false, "Keep filled gaps faded", group = G_FVG, tooltip = "Off: a gap is deleted once a wick reaches its far side. On: the newest filled gaps stay as faint boxes, ending at the bar that filled them, with no tag.", display = display.none)
fillWin   = input.int(50, "Fill-rate window (bars)", minval = 5, maxval = 500, group = G_FVG, tooltip = "Dashboard Fill rate: the share of gaps on this chart that were filled (a wick reached the far side) within this many bars of forming. n counts the gaps already decided.", display = display.none)
 
showIfvg  = input.bool(true, "Show iFVGs", group = G_IFV, tooltip = "Inversion gaps: a filled gap that a candle then CLOSES through (a close under a bull gap's bottom, over a bear gap's top) within the flip window turns into a gap of the other side. It ends on a close back through its far side.", display = display.none)
ifvgMax   = input.int(3, "iFVGs drawn", minval = 1, maxval = 6, group = G_IFV, tooltip = "The nearest live inversion gaps to price, inside the Draw within distance.", display = display.none)
flipBars  = input.int(30, "Flip window (bars)", minval = 1, maxval = 200, group = G_IFV, tooltip = "How many bars after a gap is filled a close through it still turns it into an iFVG.", display = display.none)
ifvgStops = input.int(4, "Gradient steps", minval = 2, maxval = 8, group = G_IFV, tooltip = "Nested layers that build each iFVG's gradient: strongest at the outer edge, fading toward the inner edge.", display = display.none)
 
showBpr   = input.bool(true, "Show BPRs", group = G_BPR, tooltip = "Balanced price range: when a gap forms, the opposite gaps born within the pair window are checked, and the largest price overlap becomes a BPR in the new gap's colour. It ends on a close through its far side.", display = display.none)
bprMax    = input.int(2, "BPRs drawn", minval = 1, maxval = 5, group = G_BPR, tooltip = "The nearest live BPRs to price, inside the Draw within distance.", display = display.none)
bprWin    = input.int(20, "Pair window (bars)", minval = 2, maxval = 200, group = G_BPR, tooltip = "The opposite gap must have formed at most this many bars before the new one.", display = display.none)
bprMinAtr = input.float(0.1, "Minimum overlap (ATR)", minval = 0.0, maxval = 5.0, step = 0.05, group = G_BPR, tooltip = "Smallest overlap kept as a BPR, in ATR(14).", display = display.none)
 
showVi    = input.bool(true, "Show VIs", group = G_VI, tooltip = "Volume imbalance: two candles of the same direction whose bodies do not touch (this open above the prior close for bull, below it for bear) while their wicks overlap. The zone is the space between the two bodies. A wick to its far side fills it. A VI that sits inside an open gap of the same side is skipped.", display = display.none)
viMax     = input.int(4, "VIs drawn", minval = 1, maxval = 10, group = G_VI, tooltip = "The nearest open VIs to price, inside the Draw within distance.", display = display.none)
viMinAtr  = input.float(0.03, "Minimum VI size (ATR)", minval = 0.0, maxval = 2.0, step = 0.01, group = G_VI, tooltip = "Smallest body gap kept, in ATR(14). At least one tick is always required.", display = display.none)
 
showDisp  = input.bool(true, "Show D tags", group = G_DSP, tooltip = "A small filled D under (bull) or over (bear) the middle candle of a new gap when that candle's body is at least the size below.", display = display.none)
dispMult  = input.float(1.2, "Body at least (ATR)", minval = 0.3, maxval = 5.0, step = 0.1, group = G_DSP, tooltip = "Smallest body, in ATR(14), for a gap's middle candle to count as displacement.", display = display.none)
dispMax   = input.int(6, "D tags kept", minval = 1, maxval = 20, group = G_DSP, tooltip = "Only the newest displacement candles keep their tag.", display = display.none)
 
showStr   = input.bool(true, "Show BOS / CHoCH", group = G_STR, tooltip = "Major structure. A swing high or low is confirmed once price moves the swing size away from it. A close above the last swing high is a bull break, a close below the last swing low a bear break: CHoCH when it turns the bias, BOS when it continues it. Solid line from the swing to the break, filled tag at the break.", display = display.none)
pivAtr    = input.float(1.8, "Swing size (ATR)", minval = 0.3, maxval = 10.0, step = 0.1, group = G_STR, tooltip = "How far, in ATR(14), price must move away from a high or low before it counts as a swing. Larger = fewer, bigger swings and a slower bias.", display = display.none)
 
showPD    = input.bool(true, "Show premium / discount", group = G_PD, tooltip = "Gradient over the dealing range of the current leg: from the swing that started it to its extreme so far. The bear colour above the 50 % equilibrium (premium), the bull colour below it (discount), strongest at the edges.", display = display.none)
pdStops   = input.int(6, "Gradient steps", minval = 2, maxval = 12, group = G_PD, tooltip = "Nested layers per half of the range.", display = display.none)
 
showDash  = input.bool(true, "Show dashboard", group = G_DSH, display = display.none)
dashPos   = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Top Center", "Middle Right", "Middle Left", "Middle Center", "Bottom Right", "Bottom Left", "Bottom Center"], group = G_DSH, display = display.none)
dashSize  = input.string("Small", "Size", options = ["Small", "Normal", "Large"], group = G_DSH, tooltip = "Small suits most screens; Normal or Large for phones and tablets.", display = display.none)
dashTrans = input.int(15, "Background transparency", minval = 0, maxval = 80, group = G_DSH, display = display.none)
headroom  = input.float(0.30, "Keep the dashboard corner clear (x span)", minval = 0.0, maxval = 1.0, step = 0.05, group = G_DSH, tooltip = "With the dashboard at the top (or bottom), the price scale gets this much empty room above (or below) everything drawn, as a share of that range, and no tag is placed there, so the dashboard never covers a tag. 0 = off.", display = display.none)
 
bullIn    = input.color(#00E5C0, "Custom bull", group = G_COL, display = display.none)
bearIn    = input.color(#FF8C1A, "Custom bear", group = G_COL, display = display.none)
bgIn      = input.color(#0F2230, "Custom dashboard background", group = G_COL, display = display.none)
frameIn   = input.color(#1B3448, "Custom dashboard frame", group = G_COL, display = display.none)
hiIn      = input.color(#FFD2A1, "Custom highlight (BPR tags, score row)", group = G_COL, display = display.none)
 
// ─── Constants ────────────────────────────────────────────────────────────
const int   PAST_MAX  = 4990    // furthest back a drawing starts: inside the 5,000 bar times kept below
const int   TRACK_MAX = 30      // open gaps / VIs tracked per list
const int   ATR_LEN   = 14
const color WHITE     = #FFFFFF
const color MUTED     = #A8B0BD
const color DARK_TXT  = #0E1A24
const color CLEAR     = #00000000
NEUTRAL = color.new(#F0F8FF, 30)
 
// a drawing far back needs the bar times that far back; without this Pine keeps fewer and a live bar can stop the
// script with a historical-buffer error
max_bars_back(time, 5000)
 
// ─── Colours ──────────────────────────────────────────────────────────────
isLight = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color) > 140
 
cBull = switch themeIn
    "Mystic"       => #00CED1
    "Emerald Ruby" => #00C896
    "Ice Magenta"  => #00B7FF
    "Royal Gold"   => #FFC233
    "Ocean Amber"  => #00A8E8
    "Sakura Teal"  => #2EC4B6
    "Aurora"       => #00F5A0
    "Mono"         => isLight ? #2A2E39 : #E6E6E6
    "Custom"       => bullIn
    => #00E5C0
cBear = switch themeIn
    "Mystic"       => #9400D3
    "Emerald Ruby" => #E0115F
    "Ice Magenta"  => #FF2EA6
    "Royal Gold"   => #8A5CFF
    "Ocean Amber"  => #FFB000
    "Sakura Teal"  => #FF6B9D
    "Aurora"       => #7B2FF7
    "Mono"         => #7A7A7A
    "Custom"       => bearIn
    => #FF8C1A
cBg = switch themeIn
    "Mystic"       => #191970
    "Emerald Ruby" => #0B2A26
    "Ice Magenta"  => #1A1035
    "Royal Gold"   => #1C1433
    "Ocean Amber"  => #0A1F33
    "Sakura Teal"  => #1B1530
    "Aurora"       => #120D2B
    "Mono"         => #111111
    "Custom"       => bgIn
    => #0F2230
cFrame = switch themeIn
    "Mystic"       => #241A3A
    "Emerald Ruby" => #123D36
    "Ice Magenta"  => #2A1A50
    "Royal Gold"   => #2C2150
    "Ocean Amber"  => #15324F
    "Sakura Teal"  => #2C2248
    "Aurora"       => #221A45
    "Mono"         => #2E2E2E
    "Custom"       => frameIn
    => #1B3448
cHi = switch themeIn
    "Mystic"       => #B39DDB
    "Emerald Ruby" => #7FFFD4
    "Ice Magenta"  => #C77DFF
    "Royal Gold"   => #FFE08A
    "Ocean Amber"  => #7FD8FF
    "Sakura Teal"  => #FFC2D6
    "Aurora"       => #B8F5DC
    "Mono"         => #CFCFCF
    "Custom"       => hiIn
    => #FFD2A1
 
tagSz = switch tagSizeIn
    "Normal" => size.normal
    "Large"  => size.large
    => size.small
tagMult = tagSizeIn == "Large" ? 1.6 : tagSizeIn == "Normal" ? 1.25 : 1.0
dSz = switch dashSize
    "Normal" => size.normal
    "Large"  => size.large
    => size.small
 
// ─── Helpers ──────────────────────────────────────────────────────────────
chan(float v) =>
    u = v / 255.0
    u <= 0.03928 ? u / 12.92 : math.pow((u + 0.055) / 1.055, 2.4)
lum(color c) =>
    0.2126 * chan(color.r(c)) + 0.7152 * chan(color.g(c)) + 0.0722 * chan(color.b(c))
// white text on the palette fills; dark text only on very bright fills (the highlight colour, Mono's light grey)
onFill(color c) =>
    lum(c) > 0.65 ? DARK_TXT : WHITE
// plain text on the chart: the palette on a dark chart, a deeper shade of it on a light one
ink(color c) =>
    isLight ? color.rgb(color.r(c) * 0.62, color.g(c) * 0.62, color.b(c) * 0.62) : c
// values on the dark dashboard: a colour too dark to read there (Mono bull on a light chart) turns light grey
dashInk(color c) =>
    lum(c) < 0.08 ? #E6E6E6 : c
sideCol(int s) =>
    s == 1 ? cBull : cBear
xo(int b) =>
    math.max(b, bar_index - PAST_MAX)
fp(float p) =>
    str.tostring(p, format.mintick)
fa(float x) =>
    x < 0.095 ? str.tostring(x, "0.00") : str.tostring(x, "0.0")
bars(int n) =>
    str.tostring(n) + (n == 1 ? " bar" : " bars")
distOf(float top, float bot) =>
    close > top ? close - top : close < bot ? bot - close : 0.0
mn(float a, float b) =>
    na(a) ? b : na(b) ? a : math.min(a, b)
f_grad(color base, int row, int rows, int minT, int maxT) =>
    float t = rows <= 1 ? float(minT) : float(minT) + float(maxT - minT) * (float(row) / float(rows - 1))
    color.new(base, int(t))
posOf(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Middle Right"  => position.middle_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Bottom Right"  => position.bottom_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.top_right
 
// ─── Types ────────────────────────────────────────────────────────────────
// one imbalance: a fair value gap, a VI, an iFVG or a BPR
type Gap
    int   kind             // 0 FVG, 1 VI, 2 iFVG, 3 BPR
    int   side             // 1 bull, -1 bear
    int   left             // bar the box starts on
    int   born             // bar it was confirmed on
    float top0             // full range when it formed
    float bot0
    float top              // part still open (wicks shrink it from the touched edge)
    float bot
    float sizeAtr          // full height in ATR(14) when it formed
    int   fillBar = na     // bar a wick reached its far side
 
// a structure break or a displacement candle
type Ev
    int    x1
    float  y
    int    x2
    int    side
    string txt
    float  val
 
// a right-edge tag waiting for its lane
type Tag
    float  y
    string txt
    color  bg
    color  fg
    string tip
 
// ─── State ────────────────────────────────────────────────────────────────
var array<Gap>   bisi     = array.new<Gap>()
var array<Gap>   sibi     = array.new<Gap>()
var array<Gap>   vis      = array.new<Gap>()
var array<Gap>   ifvgs    = array.new<Gap>()
var array<Gap>   bprs     = array.new<Gap>()
var array<Gap>   watch    = array.new<Gap>()    // filled gaps inside their flip window
var array<Gap>   faded    = array.new<Gap>()    // filled gaps kept for the faded look
var array<Gap>   births   = array.new<Gap>()    // recent gap births, full ranges, for BPR pairing
var array<Gap>   statPend = array.new<Gap>()    // gaps waiting for the fill-rate verdict
var array<Ev>    structs  = array.new<Ev>()
var array<Ev>    disps    = array.new<Ev>()
var array<box>   dBoxes   = array.new<box>()
var array<line>  dLines   = array.new<line>()
var array<label> dLabels  = array.new<label>()
var int    fillHit      = 0
var int    fillN        = 0
var int    lastIfvgBar  = na
var int    lastIfvgSide = 0
var int    lastDispBar  = na
var int    lastDispSide = 0
var float  visHi        = na
var float  visLo        = na
 
// structure state
var float  rcHigh     = na
var int    rcHighBar  = na
var float  rcLow      = na
var int    rcLowBar   = na
var int    lastConf   = 0
var float  pendH      = na
var int    pendHBar   = na
var float  pendL      = na
var int    pendLBar   = na
var float  hiPivP     = na
var int    hiPivB     = na
var float  loPivP     = na
var int    loPivB     = na
var int    bias       = 0
var int    lastStrBar = na
var string lastStrTxt = ""
var float  dHi        = na
var float  dLo        = na
var int    dAnchor    = na
 
atrV  = ta.atr(ATR_LEN)
hi300 = ta.highest(high, 300)
lo300 = ta.lowest(low, 300)
strKeep = modeIn == "Live" ? 6 : 100
 
// the visible bars: their price range is part of the span that sets the tag stacking gap
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
    visHi := na(visHi) ? high : math.max(visHi, high)
    visLo := na(visLo) ? low : math.min(visLo, low)
 
// ─── Engine helpers ───────────────────────────────────────────────────────
// shrink a gap from the edge a wick has reached; true once a wick reaches its far side
fillStep(Gap g) =>
    bool full = false
    if g.side == 1
        if low < g.top
            g.top := math.max(low, g.bot)
        full := low <= g.bot
    else
        if high > g.bot
            g.bot := math.min(high, g.top)
        full := high >= g.top
    full
 
// run the fill step over one list; filled gaps leave it (fair value gaps go on to the flip watch and the faded list)
procFills(array<Gap> arr, bool isFvg) =>
    int n = 0
    if arr.size() > 0
        for i = arr.size() - 1 to 0
            g = arr.get(i)
            if fillStep(g)
                arr.remove(i)
                n += 1
                if isFvg
                    g.fillBar := bar_index
                    watch.push(g)
                    if watch.size() > 24
                        watch.shift()
                    faded.push(g)
                    if faded.size() > 20
                        faded.shift()
    n
 
// a VI that sits entirely inside an open gap of the same side adds nothing to the map
insideFvg(int side, float t, float b) =>
    bool found = false
    arr = side == 1 ? bisi : sibi
    for g in arr
        if t <= g.top0 and b >= g.bot0
            found := true
            break
    found
 
// a new fair value gap: track it, queue it for the fill rate, and pair it with the opposite gaps born within the pair
// window (largest overlap = BPR). Returns true when a BPR was made
newGap(int side, float t, float b) =>
    g = Gap.new(0, side, bar_index - 2, bar_index, t, b, t, b, (t - b) / atrV)
    arr = side == 1 ? bisi : sibi
    arr.push(g)
    if arr.size() > TRACK_MAX
        arr.shift()
    statPend.push(g)
    if statPend.size() > 600
        statPend.shift()
    float bT = na
    float bB = na
    for p in births
        if p.side == -side and bar_index - p.born <= bprWin
            ovT = math.min(t, p.top0)
            ovB = math.max(b, p.bot0)
            if ovT - ovB >= math.max(bprMinAtr * atrV, syminfo.mintick) and (na(bT) or ovT - ovB > bT - bB)
                bT := ovT
                bB := ovB
    births.push(g)
    if births.size() > 40
        births.shift()
    bool made = false
    if not na(bT)
        bool dup = false
        for p in bprs
            if math.abs(p.top0 - bT) < 0.1 * atrV and math.abs(p.bot0 - bB) < 0.1 * atrV
                dup := true
        if not dup
            bprs.push(Gap.new(3, side, bar_index - 2, bar_index, bT, bB, bT, bB, (bT - bB) / atrV))
            if bprs.size() > 6
                bprs.shift()
            made := true
    made
 
// ─── Engine ───────────────────────────────────────────────────────────────
bool evBisi = false
bool evSibi = false
bool evBpr  = false
bool evIfvg = false
bool evDisp = false
bool evStr  = false
 
// wick fills on every tick: within a bar the low only falls and the high only rises, so a fill never undoes itself
procFills(bisi, true)
procFills(sibi, true)
procFills(vis, false)
 
if barstate.isconfirmed
    // fill-rate verdicts: filled = a wick reached the far side within the window
    if statPend.size() > 0
        for i = statPend.size() - 1 to 0
            g = statPend.get(i)
            hit = g.side == 1 ? low <= g.bot0 : high >= g.top0
            if hit or bar_index - g.born >= fillWin
                fillN += 1
                if hit
                    fillHit += 1
                statPend.remove(i)
 
    // iFVGs and BPRs end on a close through their far side
    if ifvgs.size() > 0
        for i = ifvgs.size() - 1 to 0
            g = ifvgs.get(i)
            if g.side == 1 ? close < g.bot : close > g.top
                ifvgs.remove(i)
    if bprs.size() > 0
        for i = bprs.size() - 1 to 0
            g = bprs.get(i)
            if g.side == 1 ? close < g.bot : close > g.top
                bprs.remove(i)
 
    // inversions: a filled gap closed through within the flip window turns into a gap of the other side
    if watch.size() > 0
        for i = watch.size() - 1 to 0
            g = watch.get(i)
            if bar_index - g.fillBar > flipBars
                watch.remove(i)
            else if g.side == 1 ? close < g.bot0 : close > g.top0
                ifvgs.push(Gap.new(2, -g.side, g.left, bar_index, g.top0, g.bot0, g.top0, g.bot0, g.sizeAtr))
                if ifvgs.size() > 10
                    ifvgs.shift()
                lastIfvgBar  := bar_index
                lastIfvgSide := -g.side
                evIfvg       := true
                watch.remove(i)
 
    // major swings: confirmed once price moves the swing size away from the running extreme
    thr = atrV * pivAtr
    if na(rcHigh) or high >= rcHigh
        rcHigh    := high
        rcHighBar := bar_index
    if na(rcLow) or low <= rcLow
        rcLow    := low
        rcLowBar := bar_index
    if not na(thr)
        if lastConf != 1 and rcHigh - low >= thr
            pendH    := rcHigh
            pendHBar := rcHighBar
            hiPivP   := rcHigh
            hiPivB   := rcHighBar
            lastConf := 1
            rcLow    := low
            rcLowBar := bar_index
        else if lastConf != -1 and high - rcLow >= thr
            pendL     := rcLow
            pendLBar  := rcLowBar
            loPivP    := rcLow
            loPivB    := rcLowBar
            lastConf  := -1
            rcHigh    := high
            rcHighBar := bar_index
 
    // breaks: a close through the last swing. The dealing range restarts at the swing that began the leg
    upBrk = not na(pendH) and close > pendH
    dnBrk = not upBrk and not na(pendL) and close < pendL
    if upBrk
        kind = bias == -1 ? "CHoCH" : "BOS"
        structs.push(Ev.new(pendHBar, pendH, bar_index, 1, kind, (close - pendH) / atrV))
        while structs.size() > strKeep
            structs.shift()
        bias       := 1
        lastStrBar := bar_index
        lastStrTxt := kind
        pendH      := na
        dAnchor    := na(loPivB) ? bar_index : loPivB
        dLo        := na(loPivP) ? low : math.min(loPivP, low)
        dHi        := lastConf == -1 ? math.max(rcHigh, high) : high
        evStr      := true
    else if dnBrk
        kind = bias == 1 ? "CHoCH" : "BOS"
        structs.push(Ev.new(pendLBar, pendL, bar_index, -1, kind, (pendL - close) / atrV))
        while structs.size() > strKeep
            structs.shift()
        bias       := -1
        lastStrBar := bar_index
        lastStrTxt := kind
        pendL      := na
        dAnchor    := na(hiPivB) ? bar_index : hiPivB
        dHi        := na(hiPivP) ? high : math.max(hiPivP, high)
        dLo        := lastConf == 1 ? math.min(rcLow, low) : low
        evStr      := true
    else if bias != 0
        dHi := math.max(dHi, high)
        dLo := math.min(dLo, low)
 
    // fair value gaps on the bar that just closed: the middle candle is [1]
    bullRaw = low > high[2] and close[1] > high[2] and low - high[2] >= math.max(fvgMinAtr * atrV, syminfo.mintick)
    bearRaw = high < low[2] and close[1] < low[2] and low[2] - high >= math.max(fvgMinAtr * atrV, syminfo.mintick)
    if bullRaw
        evBisi := true
        if newGap(1, low, high[2])
            evBpr := true
        body1 = close[1] - open[1]
        if body1 >= dispMult * atrV[1]
            disps.push(Ev.new(bar_index - 1, low[1], bar_index - 1, 1, "D", body1 / atrV[1]))
            while disps.size() > dispMax
                disps.shift()
            lastDispBar  := bar_index - 1
            lastDispSide := 1
            evDisp       := true
    if bearRaw
        evSibi := true
        if newGap(-1, low[2], high)
            evBpr := true
        body1 = open[1] - close[1]
        if body1 >= dispMult * atrV[1]
            disps.push(Ev.new(bar_index - 1, high[1], bar_index - 1, -1, "D", body1 / atrV[1]))
            while disps.size() > dispMax
                disps.shift()
            lastDispBar  := bar_index - 1
            lastDispSide := -1
            evDisp       := true
 
    // volume imbalances: bodies apart, wicks overlapping, both candles the same direction
    viMin  = math.max(viMinAtr * atrV, syminfo.mintick)
    bullVi = close > open and close[1] > open[1] and open - close[1] >= viMin and low <= high[1]
    bearVi = close < open and close[1] < open[1] and close[1] - open >= viMin and high >= low[1]
    if bullVi and not insideFvg(1, open, close[1])
        vis.push(Gap.new(1, 1, bar_index - 1, bar_index, open, close[1], open, close[1], (open - close[1]) / atrV))
    if bearVi and not insideFvg(-1, close[1], open)
        vis.push(Gap.new(1, -1, bar_index - 1, bar_index, close[1], open, close[1], open, (close[1] - open) / atrV))
    while vis.size() > TRACK_MAX
        vis.shift()
 
// ─── Imbalance Score ──────────────────────────────────────────────────────
// distance (price units) from the close to the nearest open imbalance of one side in a list; 0 inside it
nearestOf(array<Gap> arr, int side) =>
    float best = na
    for g in arr
        if g.side == side
            best := mn(best, distOf(g.top, g.bot))
    best
 
// proximity 0-50: an open imbalance on the bias side, full points inside it, falling to 0 at 3 ATR away
// BPR 0-25: 25 when a live BPR is on the bias side, 10 when only an opposite one is live
// displacement 0-25: the newest D candle on the bias side, 25 on its bar, falling to 0 over 50 bars
calcScore() =>
    float bestD = na
    float dB    = na
    if bias != 0
        bestD := mn(nearestOf(bias == 1 ? bisi : sibi, bias), nearestOf(vis, bias))
        bestD := mn(bestD, nearestOf(ifvgs, bias))
        dB    := nearestOf(bprs, bias)
        bestD := mn(bestD, dB)
    prox  = na(bestD) or na(atrV) ? 0.0 : 50.0 * math.max(0.0, 1.0 - bestD / (3.0 * atrV))
    bprP  = not na(dB) ? 25.0 : bprs.size() > 0 ? 10.0 : 0.0
    dispP = bias != 0 and lastDispSide == bias and not na(lastDispBar) ? 25.0 * math.max(0.0, 1.0 - (bar_index - lastDispBar) / 50.0) : 0.0
    [math.min(100, math.round(prox + bprP + dispP)), prox, bprP, dispP, bestD]
 
[score, scProx, scBpr, scDisp, scDist] = calcScore()
 
// ─── Drawing helpers (last bar only) ──────────────────────────────────────
mkBox(int x1, float t, float b, int x2, color bg, color bd, string st) =>
    bx = box.new(x1, t, x2, b, bgcolor = bg, border_color = bd, border_width = 1, border_style = st)
    dBoxes.push(bx)
    bx
 
// the nearest n imbalances to the close in a list, within the draw distance, nearest first
pickNearest(array<Gap> arr, int n, float lim) =>
    array<Gap>   out = array.new<Gap>()
    array<float> ds  = array.new<float>()
    for g in arr
        d = distOf(g.top, g.bot)
        if d <= lim
            int at = 0
            while at < ds.size() and ds.get(at) <= d
                at += 1
            ds.insert(at, d)
            out.insert(at, g)
    while out.size() > n
        out.pop()
    out
 
drawFvg(Gap g, array<Tag> tags) =>
    col = sideCol(g.side)
    x1  = xo(g.left)
    xr  = bar_index + extBars
    mkBox(x1, g.top, g.bot, xr, color.new(col, 82), color.new(col, 45), line.style_solid)
    ce = (g.top0 + g.bot0) / 2
    if showCE and ce < g.top and ce > g.bot
        dLines.push(line.new(x1, ce, xr, ce, color = color.new(col, 25), style = line.style_dotted, width = 1))
    pct = math.round(100.0 * (g.top - g.bot) / (g.top0 - g.bot0))
    nm  = g.side == 1 ? "BISI" : "SIBI"
    tip = (g.side == 1 ? "BISI · bull fair value gap" : "SIBI · bear fair value gap") + "\nOpen part " + fp(g.bot) + " – " + fp(g.top) + "\nFull gap " + fp(g.bot0) + " – " + fp(g.top0) + "\nCE (50 %) " + fp(ce) + "\n" + str.tostring(pct) + "% still open · " + fa(g.sizeAtr) + " ATR(14) when it formed\nFormed " + bars(bar_index - g.born) + " ago"
    tags.push(Tag.new((g.top + g.bot) / 2, nm + " " + str.tostring(pct) + "% open · " + fa(g.sizeAtr) + " ATR", color.new(col, 20), onFill(col), tip))
 
drawIfvg(Gap g, array<Tag> tags) =>
    col = sideCol(g.side)
    x1  = xo(g.left)
    xr  = bar_index + extBars
    n   = ifvgStops
    h   = g.top - g.bot
    la  = int(math.round(100.0 * math.pow(0.55, 1.0 / n)))
    // nested layers from the outer edge (bottom of a bull iFVG, top of a bear one): no seams between bands
    for k = 0 to n - 1
        frac = float(n - k) / n
        t = g.side == 1 ? g.bot + h * frac : g.top
        b = g.side == 1 ? g.bot : g.top - h * frac
        mkBox(x1, t, b, xr, color.new(col, la), k == 0 ? color.new(col, 45) : CLEAR, line.style_dashed)
    tip = "iFVG · " + (g.side == 1 ? "a bear gap closed through upward, now bull" : "a bull gap closed through downward, now bear") + "\nRange " + fp(g.bot) + " – " + fp(g.top) + " · " + fa(g.sizeAtr) + " ATR(14)\nInverted " + bars(bar_index - g.born) + " ago\nEnds on a close back through its " + (g.side == 1 ? "bottom" : "top")
    tags.push(Tag.new((g.top + g.bot) / 2, "iFVG · " + fa(g.sizeAtr) + " ATR", color.new(col, 20), onFill(col), tip))
 
drawBpr(Gap g, array<Tag> tags) =>
    col = sideCol(g.side)
    x1  = xo(g.left)
    xr  = bar_index + extBars
    mkBox(x1, g.top, g.bot, xr, color.new(col, 66), color.new(cHi, 10), line.style_solid)
    ins = (g.top - g.bot) * 0.22
    mkBox(math.min(x1 + 1, xr - 1), g.top - ins, g.bot + ins, xr - 1, CLEAR, color.new(cHi, 45), line.style_solid)
    tip = "BPR · balanced price range (" + (g.side == 1 ? "bull" : "bear") + ")\nOverlap of a " + (g.side == 1 ? "bull gap with an earlier bear gap" : "bear gap with an earlier bull gap") + "\nRange " + fp(g.bot) + " – " + fp(g.top) + " · " + fa(g.sizeAtr) + " ATR(14)\nFormed " + bars(bar_index - g.born) + " ago\nEnds on a close through its " + (g.side == 1 ? "bottom" : "top")
    tags.push(Tag.new((g.top + g.bot) / 2, "BPR · " + fa(g.sizeAtr) + " ATR", color.new(cHi, 10), onFill(cHi), tip))
 
drawVi(Gap g, array<Tag> tags) =>
    col = sideCol(g.side)
    mkBox(xo(g.left), g.top, g.bot, bar_index + extBars, color.new(col, 70), color.new(col, 45), line.style_solid)
    pct = math.round(100.0 * (g.top - g.bot) / (g.top0 - g.bot0))
    tip = "VI · " + (g.side == 1 ? "bull" : "bear") + " volume imbalance (bodies apart, wicks overlapping)\nOpen part " + fp(g.bot) + " – " + fp(g.top) + " · " + str.tostring(pct) + "% open\nFull " + fp(g.bot0) + " – " + fp(g.top0) + " · " + fa(g.sizeAtr) + " ATR(14)\nFormed " + bars(bar_index - g.born) + " ago"
    tags.push(Tag.new((g.top + g.bot) / 2, "VI · " + fa(g.sizeAtr) + " ATR", color.new(col, 20), onFill(col), tip))
 
// the first imbalance in a list that holds the close
insideOf(array<Gap> arr) =>
    Gap found = na
    for g in arr
        if close <= g.top and close >= g.bot
            found := g
            break
    found
 
// ─── Render (last bar) ────────────────────────────────────────────────────
float cTop = na
float cBot = na
dashTop = showDash and str.startswith(dashPos, "Top")
dashBot = showDash and str.startswith(dashPos, "Bottom")
 
if barstate.islast
    for b in dBoxes
        box.delete(b)
    dBoxes.clear()
    for l in dLines
        line.delete(l)
    dLines.clear()
    for l in dLabels
        label.delete(l)
    dLabels.clear()
 
    lim = drawAtr * atrV
    xr  = bar_index + extBars
    top = nz(visHi, nz(hi300, high))
    bot = nz(visLo, nz(lo300, low))
    array<Tag> tags = array.new<Tag>()
 
    // premium / discount: nested layers from each edge toward the 50 % equilibrium, clipped to the draw distance
    if showPD and bias != 0 and not na(dHi) and not na(dLo) and dHi > dLo
        eq   = (dHi + dLo) / 2
        capH = close + lim
        capL = close - lim
        x1   = xo(dAnchor)
        n    = pdStops
        la   = int(math.round(100.0 * math.pow(0.55, 1.0 / n)))
        pTop = math.min(dHi, capH)
        pBot = math.max(dLo, capL)
        band = (dHi - eq) / n
        for k = 0 to n - 1
            b = eq + band * k
            if b < pTop
                mkBox(x1, pTop, math.max(b, pBot), xr, color.new(cBear, la), CLEAR, line.style_solid)
            t = eq - band * k
            if t > pBot
                mkBox(x1, math.min(t, pTop), pBot, xr, color.new(cBull, la), CLEAR, line.style_solid)
        if dHi <= capH
            dLines.push(line.new(x1, dHi, xr, dHi, color = cBear, width = 1))
        if dLo >= capL
            dLines.push(line.new(x1, dLo, xr, dLo, color = cBull, width = 1))
        posPct = math.round(100.0 * (close - dLo) / (dHi - dLo))
        rngTip = "Dealing range of the current " + (bias == 1 ? "bull" : "bear") + " leg\nFrom the swing " + (bias == 1 ? "low " : "high ") + bars(bar_index - dAnchor) + " ago to the leg's extreme\nHigh " + fp(dHi) + " · EQ " + fp(eq) + " · Low " + fp(dLo) + "\nPrice sits at " + str.tostring(posPct) + "% of the range"
        if eq <= capH and eq >= capL
            dLines.push(line.new(x1, eq, xr, eq, color = color.new(color.gray, 30), style = line.style_dashed, width = 1))
            tags.push(Tag.new(eq, "EQ · " + fp(eq), CLEAR, ink(color.gray), rngTip))
        // a half clipped away entirely by the draw distance gets no tag
        if pTop > eq
            tags.push(Tag.new(pTop, "Premium · " + fp(dHi), CLEAR, ink(cBear), rngTip))
        if pBot < eq
            tags.push(Tag.new(pBot, "Discount · " + fp(dLo), CLEAR, ink(cBull), rngTip))
        top := math.max(top, pTop)
        bot := math.min(bot, pBot)
 
    // faded filled gaps (optional): from the gap to the bar that filled it, no tag
    if fvgFade and showFvg and faded.size() > 0
        int nB = 0
        int nS = 0
        for i = faded.size() - 1 to 0
            g = faded.get(i)
            okSide = g.side == 1 ? nB < fvgMax : nS < fvgMax
            if okSide and g.fillBar >= bar_index - PAST_MAX and distOf(g.top0, g.bot0) <= lim
                col = sideCol(g.side)
                mkBox(xo(g.left), g.top0, g.bot0, g.fillBar, color.new(col, 92), color.new(col, 90), line.style_solid)
                top := math.max(top, g.top0)
                bot := math.min(bot, g.bot0)
                if g.side == 1
                    nB += 1
                else
                    nS += 1
 
    if showFvg
        for g in pickNearest(bisi, fvgMax, lim)
            drawFvg(g, tags)
            top := math.max(top, g.top)
            bot := math.min(bot, g.bot)
        for g in pickNearest(sibi, fvgMax, lim)
            drawFvg(g, tags)
            top := math.max(top, g.top)
            bot := math.min(bot, g.bot)
    if showVi
        for g in pickNearest(vis, viMax, lim)
            drawVi(g, tags)
            top := math.max(top, g.top)
            bot := math.min(bot, g.bot)
    if showIfvg
        for g in pickNearest(ifvgs, ifvgMax, lim)
            drawIfvg(g, tags)
            top := math.max(top, g.top)
            bot := math.min(bot, g.bot)
    if showBpr
        for g in pickNearest(bprs, bprMax, lim)
            drawBpr(g, tags)
            top := math.max(top, g.top)
            bot := math.min(bot, g.bot)
 
    cTop := top
    cBot := bot
 
    // right-edge tags: one lane register. Sorted by price, packed in clusters that sit as close to their zones as the
    // gap allows (gap = 0.045 x the displayed span), then held inside the drawn range so none sits under the dashboard
    span = (top - bot) * (1.0 + (dashTop ? headroom : 0.0) + (dashBot ? headroom : 0.0))
    gap  = 0.045 * math.max(span, syminfo.mintick) * tagMult
    nT   = tags.size()
    array<float> placed = array.new<float>()
    if nT > 0
        array<float> ys0 = array.new<float>()
        for tg in tags
            ys0.push(tg.y)
        idx = ys0.sort_indices(order.ascending)
        array<float> cSum = array.new<float>()
        array<int>   cCnt = array.new<int>()
        for i = 0 to nT - 1
            cSum.push(ys0.get(idx.get(i)))
            cCnt.push(1)
            while cSum.size() > 1
                m    = cSum.size()
                aCnt = cCnt.get(m - 2)
                bCnt = cCnt.get(m - 1)
                botA = cSum.get(m - 2) / aCnt
                botB = cSum.get(m - 1) / bCnt
                if botA + aCnt * gap > botB
                    merged = cSum.get(m - 2) + cSum.get(m - 1) - aCnt * bCnt * gap
                    cSum.pop()
                    cCnt.pop()
                    cSum.set(m - 2, merged)
                    cCnt.set(m - 2, aCnt + bCnt)
                else
                    break
        array<float> ys = array.new<float>()
        for c = 0 to cSum.size() - 1
            b0 = cSum.get(c) / cCnt.get(c)
            for k = 0 to cCnt.get(c) - 1
                ys.push(b0 + k * gap)
        ys.set(nT - 1, math.min(ys.get(nT - 1), top))
        if nT > 1
            for i = nT - 2 to 0
                ys.set(i, math.min(ys.get(i), ys.get(i + 1) - gap))
        ys.set(0, math.max(ys.get(0), bot))
        if nT > 1
            for i = 1 to nT - 1
                ys.set(i, math.max(ys.get(i), ys.get(i - 1) + gap))
        for i = 0 to nT - 1
            tg = tags.get(idx.get(i))
            placed.push(ys.get(i))
            dLabels.push(label.new(xr, ys.get(i), tg.txt, color = tg.bg, textcolor = tg.fg, style = label.style_label_left, size = tagSz, text_formatting = text.format_bold, tooltip = tg.tip))
 
    // structure: solid line from the broken swing to the break, filled tag at the break
    if showStr and structs.size() > 0
        for e in structs
            if e.x2 >= bar_index - PAST_MAX
                col = sideCol(e.side)
                dLines.push(line.new(xo(e.x1), e.y, e.x2, e.y, color = col, style = line.style_solid, width = 2))
                tip = e.txt + " · " + (e.side == 1 ? "close above the swing high " : "close below the swing low ") + fp(e.y) + "\n" + (e.txt == "CHoCH" ? "First break against the previous bias" : "Break in the direction of the bias") + "\nClose " + fa(e.val) + " ATR(14) beyond it · " + bars(bar_index - e.x2) + " ago"
                // a break in the last few bars whose tag would reach the right-edge tag column at the same height
                // turns its tag to the left of the break bar instead
                bool clash = false
                if xr - e.x2 < 20
                    for py in placed
                        if math.abs(py - e.y) < gap
                            clash := true
                            break
                dLabels.push(label.new(e.x2, e.y, e.txt, color = color.new(col, 15), textcolor = onFill(col), style = clash ? label.style_label_right : label.style_label_left, size = tagSz, text_formatting = text.format_bold, tooltip = tip))
 
    // displacement candles: a small filled D under a bull candle, over a bear one
    if showDisp and disps.size() > 0
        for e in disps
            if e.x1 >= bar_index - PAST_MAX
                col = sideCol(e.side)
                tip = "Displacement · " + (e.side == 1 ? "bull" : "bear") + " candle\nBody " + fa(e.val) + " ATR(14)\nIt made a " + (e.side == 1 ? "BISI" : "SIBI") + " · " + bars(bar_index - e.x1) + " ago"
                dLabels.push(label.new(e.x1, e.y, "D", color = color.new(col, 20), textcolor = onFill(col), style = e.side == 1 ? label.style_label_up : label.style_label_down, size = size.small, text_formatting = text.format_bold, tooltip = tip))
 
// ─── Dashboard ────────────────────────────────────────────────────────────
const int ROWS = 10
var table dash = showDash ? table.new(posOf(dashPos), 2, ROWS, bgcolor = color.new(cBg, 100), frame_color = color.new(cFrame, 60), frame_width = 1, border_color = color.new(cFrame, 65), border_width = 1) : na
 
dashRow(int r, string k, string v, color vc, string tip) =>
    bgc = f_grad(cBg, r, ROWS, dashTrans, dashTrans + (isLight ? 5 : 25))
    table.cell(dash, 0, r, k, text_color = MUTED, bgcolor = bgc, text_size = dSz, tooltip = tip)
    table.cell(dash, 1, r, v, text_color = dashInk(vc), bgcolor = bgc, text_halign = text.align_right, text_size = dSz, tooltip = tip)
 
// count and nearest near edge of one side's open gaps
gapRow(array<Gap> arr, int side) =>
    float best = na
    float nearP = na
    for g in arr
        d = distOf(g.top, g.bot)
        if na(best) or d < best
            best  := d
            nearP := side == 1 ? g.top : g.bot
    arr.size() == 0 ? "0" : str.tostring(arr.size()) + " · " + fp(nearP)
 
if showDash and barstate.islast
    hdrBg = f_grad(cBg, 0, ROWS, dashTrans, dashTrans + 5)
    table.cell(dash, 0, 0, "IMBALANCE CONFLUENCE", text_color = WHITE, bgcolor = hdrBg, text_size = dSz, text_font_family = font.family_monospace, text_formatting = text.format_bold, tooltip = "Every ICT imbalance type on this chart right now. Hover a row for how it is read.")
    table.cell(dash, 1, 0, "STATE", text_color = WHITE, bgcolor = hdrBg, text_halign = text.align_right, text_size = dSz, text_font_family = font.family_monospace, text_formatting = text.format_bold)
 
    // 1 bias
    biasTxt = bias == 0 ? "Neutral" : (bias == 1 ? "Bull · " : "Bear · ") + lastStrTxt + " " + bars(bar_index - lastStrBar)
    dashRow(1, "Bias", biasTxt, bias == 1 ? cBull : bias == -1 ? cBear : NEUTRAL, "Major structure: the side of the last close through a swing (swing size " + str.tostring(pivAtr) + " ATR). CHoCH = the first break against the previous bias, BOS = a break with it. Candles are painted in this colour.")
 
    // 2-3 open gaps per side
    dashRow(2, "Open BISI", gapRow(bisi, 1), cBull, "Bull fair value gaps not yet filled (a wick has not reached the bottom), up to 30 tracked. The price is the near edge (top) of the closest one.")
    dashRow(3, "Open SIBI", gapRow(sibi, -1), cBear, "Bear fair value gaps not yet filled (a wick has not reached the top), up to 30 tracked. The price is the near edge (bottom) of the closest one.")
 
    // 4 BPR
    bN = pickNearest(bprs, 1, 1e100)
    string bprTxt = "No"
    color  bprCol = NEUTRAL
    if bN.size() > 0
        bprTxt := "Yes · " + fp(bN.get(0).bot) + " – " + fp(bN.get(0).top)
        bprCol := sideCol(bN.get(0).side)
    dashRow(4, "BPR active", bprTxt, bprCol, "A balanced price range is live: the overlap of a bull and a bear gap born within " + str.tostring(bprWin) + " bars of each other, not yet closed through. " + str.tostring(bprs.size()) + " live; the range shown is the closest.")
 
    // 5 last iFVG
    ifTxt = na(lastIfvgBar) ? "None" : (lastIfvgSide == 1 ? "Bull · " : "Bear · ") + bars(bar_index - lastIfvgBar)
    dashRow(5, "Last iFVG", ifTxt, lastIfvgSide == 1 ? cBull : lastIfvgSide == -1 ? cBear : NEUTRAL, "The newest inversion: a filled gap that a candle closed through within " + str.tostring(flipBars) + " bars, now acting for the other side. " + str.tostring(ifvgs.size()) + " live.")
 
    // 6 VIs
    vN = pickNearest(vis, 1, 1e100)
    string viTxt = "0"
    color  viCol = NEUTRAL
    if vN.size() > 0
        vg = vN.get(0)
        viTxt := str.tostring(vis.size()) + " · " + fp(vg.side == 1 ? vg.top : vg.bot)
        viCol := sideCol(vg.side)
    dashRow(6, "VI open", viTxt, viCol, "Volume imbalances not yet filled, up to 30 tracked; the price is the near edge of the closest one, in its side's colour.")
 
    // 7 what price is inside
    string inTxt = "None"
    color  inCol = NEUTRAL
    Gap gIn = insideOf(bprs)
    if not na(gIn)
        inTxt := (gIn.side == 1 ? "Bull" : "Bear") + " BPR"
        inCol := sideCol(gIn.side)
    else
        gIn := insideOf(ifvgs)
        if not na(gIn)
            inTxt := (gIn.side == 1 ? "Bull" : "Bear") + " iFVG"
            inCol := sideCol(gIn.side)
        else
            gIn := insideOf(bisi)
            if na(gIn)
                gIn := insideOf(sibi)
            if not na(gIn)
                inTxt := (gIn.side == 1 ? "BISI " : "SIBI ") + str.tostring(math.round(100.0 * (gIn.top - gIn.bot) / (gIn.top0 - gIn.bot0))) + "% open"
                inCol := sideCol(gIn.side)
            else
                gIn := insideOf(vis)
                if not na(gIn)
                    inTxt := (gIn.side == 1 ? "Bull" : "Bear") + " VI"
                    inCol := sideCol(gIn.side)
    dashRow(7, "Price inside", inTxt, inCol, "The imbalance the last price sits in, checked in this order: BPR, iFVG, BISI / SIBI, VI.")
 
    // 8 fill rate
    fillTxt = fillN == 0 ? "n 0" : str.tostring(math.round(100.0 * fillHit / fillN)) + "% · n " + str.tostring(fillN)
    dashRow(8, "Fill rate", fillTxt, NEUTRAL, "Share of this chart's fair value gaps that were filled (a wick reached the far side) within " + str.tostring(fillWin) + " bars of forming. n = gaps already decided (filled, or " + str.tostring(fillWin) + " bars old). It describes the loaded history only.")
 
    // 9 score, highlighted
    scTip = "Imbalance Score " + str.tostring(score) + " / 100\nProximity " + str.tostring(math.round(scProx)) + " / 50: an open imbalance on the bias side, full inside it, 0 at 3 ATR away" + (na(scDist) ? "" : " (now " + fa(scDist / atrV) + " ATR)") + "\nBPR " + str.tostring(math.round(scBpr)) + " / 25: 25 with a live BPR on the bias side, 10 with only an opposite one\nDisplacement " + str.tostring(math.round(scDisp)) + " / 25: the newest D candle on the bias side, fading to 0 over 50 bars\nIt measures how much imbalance sits close to price on the bias side; it is not a forecast."
    hiFg = onFill(cHi)
    table.cell(dash, 0, 9, "Imbalance Score", text_color = hiFg, bgcolor = color.new(cHi, 20), text_size = dSz, text_font_family = font.family_monospace, text_formatting = text.format_bold, tooltip = scTip)
    table.cell(dash, 1, 9, str.tostring(score) + " / 100", text_color = hiFg, bgcolor = color.new(cHi, 20), text_halign = text.align_right, text_size = dSz, text_font_family = font.family_monospace, text_formatting = text.format_bold, tooltip = scTip)
 
// ─── Plots ────────────────────────────────────────────────────────────────
barcolor(paintBias and bias != 0 ? (bias == 1 ? cBull : cBear) : na, title = "Bias candles", editable = false)
// empty room above / below everything drawn, on the last bar only, so the dashboard sits over clear chart
plot(not na(cTop) and dashTop and headroom > 0 ? cTop + headroom * (cTop - cBot) : na, "Headroom top", color = CLEAR, display = display.pane, editable = false)
plot(not na(cBot) and dashBot and headroom > 0 ? cBot - headroom * (cTop - cBot) : na, "Headroom bottom", color = CLEAR, display = display.pane, editable = false)
// keeps the script on the price scale
plot(close, "Price anchor", color = CLEAR, display = display.pane, editable = false)
plot(score, "Imbalance Score", color = cHi, display = display.data_window, editable = false)
plot(bias, "Bias", color = cHi, display = display.data_window, editable = false)
 
// ─── Alerts ───────────────────────────────────────────────────────────────
alertcondition(evBisi, "New BISI", "Imbalance Matrix: a bull fair value gap (BISI) formed on {{ticker}} {{interval}}")
alertcondition(evSibi, "New SIBI", "Imbalance Matrix: a bear fair value gap (SIBI) formed on {{ticker}} {{interval}}")
alertcondition(evBpr, "New BPR", "Imbalance Matrix: a balanced price range (BPR) formed on {{ticker}} {{interval}}")
alertcondition(evIfvg, "New iFVG", "Imbalance Matrix: a gap was closed through and inverted (iFVG) on {{ticker}} {{interval}}")
alertcondition(evDisp, "Displacement candle", "Imbalance Matrix: a displacement candle made a fair value gap on {{ticker}} {{interval}}")
alertcondition(evStr, "Structure break", "Imbalance Matrix: a major BOS / CHoCH printed on {{ticker}} {{interval}}")

← 返回列表