EMS-FVG/OB/IDM

OptionFlows · study · 2109 行 · 点赞 85 · TradingView 原页

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

Pine Script

//@version=6
indicator("EMS-FVG/OB/IDM", overlay = true, max_bars_back = 510, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500, calc_bars_count = 2000)
 
// =============================== FVG / IFVG ===============================
 
// ~~ Inputs {
gDetect  = "Detection"
gFilter  = "Filters"
gGrade   = "Grading & Hold Rate"
gRanking = "Ranking"
gDisplay = "Display"
gBorder  = "Borders & Midline"
gColors  = "Colors"
gIFVG    = "IFVG"
gAlerts  = "Alerts"
 
detTF       = input.string("5", "Detection Timeframe (min)", options = ["5", "1"], group = gDetect, tooltip = "Timeframe used to detect FVGs. Zones appear when the detection candle closes (non-repainting).")
maxBarsBack = input.int(80, "Max Bars Back", minval = 10, maxval = 1000, group = gDetect, tooltip = "Zones are removed this many chart candles after they form.")
 
useMinSize  = input.bool(true, "Min FVG Size", inline = "ms", group = gFilter)
minSizeAtr  = input.float(0.4, "ATR x", minval = 0.05, step = 0.05, inline = "ms", group = gFilter, tooltip = "Ignore gaps smaller than this multiple of ATR.")
useDisp     = input.bool(true, "Require Displacement", group = gFilter, tooltip = "Middle candle must be a big, solid candle in the gap's direction.")
dispBodyAtr = input.float(0.6, "Min Body (ATR x)", minval = 0.1, step = 0.05, group = gFilter)
dispBodyRat = input.float(0.6, "Min Body/Range", minval = 0.3, maxval = 0.95, step = 0.05, group = gFilter)
useOverlap  = input.bool(true, "Skip Overlapping FVGs", group = gFilter, tooltip = "Skip a new FVG if it overlaps an existing FVG or IFVG.")
useDistHide = input.bool(false, "Hide Far Zones", inline = "dh", group = gFilter)
distMax     = input.float(8.0, "ATR x", minval = 1.0, step = 0.5, inline = "dh", group = gFilter, tooltip = "Hide zones farther than this many ATR from price.")
 
volLength     = input.int(20, "RVOL Length", minval = 5, group = gGrade, tooltip = "Average volume length used to judge the displacement candle's volume.")
gradeAMin     = input.int(6, "FVG Grade A Min Score", minval = 1, maxval = 9, group = gGrade, tooltip = "Score out of 9: gap 1+ ATR (6) or 0.5-1 ATR (2), displacement body 1+ ATR (2), RVOL 1.5+ (1). Below Grade C = D (always hidden).")
gradeBMin     = input.int(4, "FVG Grade B Min Score", minval = 0, maxval = 9, group = gGrade)
gradeCMin     = input.int(0, "FVG Grade C Min Score", minval = 0, maxval = 9, group = gGrade)
targetR       = input.float(1.0, "Target (R)", minval = 0.25, step = 0.25, group = gGrade, tooltip = "Real-trade test: entry when price touches the zone, stop = wick past the far side, target = this many zone-heights away. HOLD = target hit before stop.")
statsSessOnly = input.bool(false, "Count Only Session Zones", inline = "ss", group = gGrade)
statsSess     = input.session("0930-1100", "", inline = "ss", group = gGrade, tooltip = "Hold rate only counts zones born in this New York time window (IFVGs: when they flip).")
minSamples    = input.int(20, "Min Samples to Show %", minval = 1, group = gGrade, tooltip = "Hide the % until a grade has at least this many results.")
 
maxZones  = input.int(20, "Show Top Zones", minval = 1, maxval = 20, group = gRanking)
maxStored = input.int(50, "Max Stored Zones", minval = 10, maxval = 100, group = gRanking)
 
labelMode     = input.string("Grade + %", "Zone Label", options = ["Grade + %", "Grade", "Hidden"], group = gDisplay, tooltip = "Hidden = just FVG / IFVG text.")
minGradeShow  = input.string("C", "Show Grades", options = ["A", "B", "C"], group = gDisplay, tooltip = "Applies to FVGs and IFVGs. A = only A. B = A and B. C = A, B, C. D is never shown.")
showN         = input.bool(false, "Show Sample Size", group = gDisplay)
showFvgLabel  = input.bool(true, "Show FVG Label", group = gDisplay)
blockTextSize = input.string("auto", "Text Size", options = ["auto", "tiny", "small", "normal", "large", "huge"], group = gDisplay)
bodyTransp    = input.int(90, "Fill Transparency", minval = 0, maxval = 100, group = gDisplay)
extendBoxes   = input.bool(false, "Extend Boxes", group = gDisplay)
boxLength     = input.int(30, "Length of Boxes (bars)", minval = 1, maxval = 500, group = gDisplay)
showTable     = input.bool(false, "Show Hold-Rate Table", inline = "tb", group = gDisplay)
tablePos      = input.string("Bottom Right", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], inline = "tb", group = gDisplay)
showFactors   = input.bool(false, "Show Factor Test", inline = "ft", group = gDisplay, tooltip = "Hold rate for each scoring factor on its own.")
factorPos     = input.string("Top Right", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], inline = "ft", group = gDisplay)
 
showBorder    = input.bool(true, "Show Borders", group = gBorder)
borderStyleIn = input.string("Solid", "Border Style", options = ["Solid", "Dashed", "Dotted"], group = gBorder)
borderTransp  = input.int(0, "Border/Midline Transparency", minval = 0, maxval = 100, group = gBorder)
borderWidth   = input.int(2, "Line Width", minval = 1, maxval = 4, group = gBorder)
showMid       = input.bool(true, "Show Midline", group = gBorder)
midStyleIn    = input.string("Dashed", "Midline Style", options = ["Solid", "Dashed", "Dotted"], group = gBorder)
markCE        = input.bool(true, "Mark CE (50%) Tap", group = gBorder, tooltip = "Once price hits the 50% line of an FVG, the midline turns solid and the border thickens.")
 
bullColor = input.color(#00bcd4, "Bullish", inline = "colors", group = gColors)
bearColor = input.color(#ff9800, "Bearish", inline = "colors", group = gColors)
 
showIFVG      = input.bool(true, "Show IFVGs", group = gIFVG, tooltip = "When price breaks an FVG with a strong candle, the box flips into an IFVG. It is deleted if price breaks back through.")
showIfvgLabel = input.bool(true, "Show IFVG Label", group = gIFVG)
breakType     = input.string("Wick", "Break Type", options = ["Close", "Wick"], group = gIFVG)
ifvgCloseDist = input.float(0.3, "Min Close Past Gap (ATR x)", minval = 0.0, step = 0.05, group = gIFVG, tooltip = "Break candle must close this far past the gap to become an IFVG. 0 = off. Failed breaks just delete the FVG.")
ifvgReqDisp   = input.bool(true, "Require Displacement on Break", group = gIFVG)
ifvgRedraw    = input.bool(false, "Redraw IFVG to Break Candle Body", group = gIFVG)
ifvgAMin      = input.int(6, "IFVG Grade A Min Score", minval = 1, maxval = 6, group = gIFVG, tooltip = "Score out of 6: original gap size (0-2), break candle body vs ATR (0-2), close distance past the gap (0-2). Below Grade C = D (always hidden).")
ifvgBMin      = input.int(5, "IFVG Grade B Min Score", minval = 0, maxval = 6, group = gIFVG)
ifvgCMin      = input.int(4, "IFVG Grade C Min Score", minval = 0, maxval = 6, group = gIFVG)
ifvgBullColor = input.color(color.new(#00bcd4, 50), "Bullish IFVG", inline = "ic", group = gIFVG)
ifvgBearColor = input.color(color.new(#ff9800, 50), "Bearish IFVG", inline = "ic", group = gIFVG)
 
alertNewBull        = input.bool(false, "New Bullish FVG", group = gAlerts)
alertNewBear        = input.bool(false, "New Bearish FVG", group = gAlerts)
alertTopRank        = input.bool(false, "New Top-Ranked FVG", group = gAlerts)
alertBullTouch      = input.bool(false, "Bullish FVG Touch", group = gAlerts)
alertBearTouch      = input.bool(false, "Bearish FVG Touch", group = gAlerts)
alertFullyMitigated = input.bool(false, "FVG Broken Through", group = gAlerts)
alertNewIFVG        = input.bool(false, "New IFVG", group = gAlerts)
alertCETap          = input.bool(false, "FVG CE Tap", group = gAlerts)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Types {
type FVG
    float qualityScore
    float top
    float bottom
    int   direction
    int   bornBar
    int   startBar
    int   leftTime
    int   score
    int   grade
    float atrBirth
    float mitigation
    bool  counted
    bool  touched
    bool  resolved
    bool  ceTapped
    box   body
    line  midLine
    box   txtBox
    int   fSize
    int   fDisp
    int   fRvol
 
type IFVG
    float top
    float bottom
    int   direction
    int   startBar
    int   leftTime
    box   body
    line  midLine
    box   txtBox
    int   score
    int   grade
    float atrBirth
    bool  counted
    bool  touched
    bool  resolved
    int   fGap
    int   fBody
    int   fDist
 
type DetBar
    int   t
    int   t2
    float o
    float h
    float l
    float c
    float h2
    float l2
    float o1
    float h1
    float l1
    float c1
    float rvol1
    float atr
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Helpers {
styleOf(string s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
 
posOf(string p) =>
    p == "Top Right" ? position.top_right : p == "Top Left" ? position.top_left : p == "Bottom Right" ? position.bottom_right : position.bottom_left
 
borderStyle = styleOf(borderStyleIn)
midStyle    = styleOf(midStyleIn)
noColor     = color.new(color.gray, 100)
barMs       = timeframe.in_seconds(timeframe.period) * 1000
useClose    = breakType == "Close"
minGradeIdx = minGradeShow == "A" ? 0 : minGradeShow == "B" ? 1 : 2
 
sessStart = int(str.tonumber(str.substring(statsSess, 0, 2))) * 60 + int(str.tonumber(str.substring(statsSess, 2, 4)))
sessEnd   = int(str.tonumber(str.substring(statsSess, 5, 7))) * 60 + int(str.tonumber(str.substring(statsSess, 7, 9)))
 
inStatsSess(int t) =>
    int m = hour(t, "America/New_York") * 60 + minute(t, "America/New_York")
    not statsSessOnly or (m >= sessStart and m < sessEnd)
 
gradeName(int g) =>
    g == 0 ? "A" : g == 1 ? "B" : g == 2 ? "C" : "D"
 
gradeOf(int s, int aMin, int bMin, int cMin) =>
    s >= aMin ? 0 : s >= bMin ? 1 : s >= cMin ? 2 : 3
 
boxRight(int leftT) =>
    extendBoxes ? time + barMs * boxLength : leftT + barMs * boxLength
 
isDisp(float o, float h, float l, float c, float a, bool wantBull) =>
    float body = math.abs(c - o)
    float rng  = math.max(h - l, syminfo.mintick)
    bool dirOk = wantBull ? c > o : c < o
    not na(a) and a > 0 and body / a >= dispBodyAtr and body / rng >= dispBodyRat and dirOk
 
// FVG score out of 9: size first, displacement second, RVOL a little
scoreOf(int sizeT, int dispT, int rvolT) =>
    int s = 0
    s += sizeT == 2 ? 6 : sizeT == 1 ? 2 : 0
    s += dispT == 2 ? 2 : 0
    s += rvolT == 2 ? 1 : 0
    s
 
// Real-trade outcome: 0 = still open, 1 = target hit (hold), -1 = stop hit (fail)
// Entry on first touch, stop = wick past the far side, target = targetR zone-heights from the near side
tradeOutcome(int dir, float top, float bottom, bool inTradeBefore, float h, float l) =>
    float r      = math.max(top - bottom, syminfo.mintick)
    bool stopHit = dir == 1 ? l < bottom : h > top
    bool tgtHit  = dir == 1 ? h >= top + r * targetR : l <= bottom - r * targetR
    stopHit ? -1 : inTradeBefore and tgtHit ? 1 : 0
 
setTopText(box tb, int leftT, int rightT, float top, float bottom, string txt, color col) =>
    box.set_left(tb, leftT)
    box.set_right(tb, rightT)
    box.set_top(tb, top)
    box.set_bottom(tb, math.avg(top, bottom))
    box.set_text(tb, txt)
    box.set_text_color(tb, col)
    box.set_text_halign(tb, text.align_right)
    box.set_text_valign(tb, text.align_center)
    box.set_text_size(tb, blockTextSize)
 
paintIfvg(IFVG x) =>
    color ic = x.direction == 1 ? ifvgBullColor : ifvgBearColor
    box.set_bgcolor(x.body, color.new(ic, bodyTransp))
    box.set_border_color(x.body, showBorder ? color.new(ic, borderTransp) : noColor)
    box.set_border_width(x.body, borderWidth)
    line.set_color(x.midLine, showMid ? color.new(ic, borderTransp) : noColor)
    line.set_style(x.midLine, midStyle)
 
// Candle 3 = current, candle 2 = [1] (displacement), candle 1 = [2]
detData() =>
    float rv = volume[1] / math.max(nz(ta.sma(volume, volLength)[1]), 1)
    [time, time[2], open, high, low, close, high[2], low[2], open[1], high[1], low[1], close[1], rv, ta.atr(14)]
 
detDataPrev() =>
    float rv = volume[2] / math.max(nz(ta.sma(volume, volLength)[2]), 1)
    [time[1], time[3], open[1], high[1], low[1], close[1], high[3], low[3], open[2], high[2], low[2], close[2], rv, ta.atr(14)[1]]
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Detection timeframe data {
chartSec = timeframe.in_seconds(timeframe.period)
detSec   = timeframe.in_seconds(detTF)
useLTF   = chartSec > detSec
fvgHtfTF    = useLTF ? timeframe.period : detTF
ltfTF    = useLTF ? detTF : timeframe.period
 
[sT, sT2, sO, sH, sL, sC, sH2, sL2, sO1, sH1, sL1, sC1, sRv, sAtr] = request.security(syminfo.tickerid, fvgHtfTF, detDataPrev(), lookahead = barmerge.lookahead_on)
[aT, aT2, aO, aH, aL, aC, aH2, aL2, aO1, aH1, aL1, aC1, aRv, aAtr] = request.security_lower_tf(syminfo.tickerid, ltfTF, detData())
 
array<DetBar> newBars = array.new<DetBar>()
 
if useLTF
    if barstate.isconfirmed and aT.size() > 0
        for i = 0 to aT.size() - 1
            newBars.push(DetBar.new(aT.get(i), aT2.get(i), aO.get(i), aH.get(i), aL.get(i), aC.get(i), aH2.get(i), aL2.get(i),
                 aO1.get(i), aH1.get(i), aL1.get(i), aC1.get(i), aRv.get(i), aAtr.get(i)))
else
    if not na(sT) and (na(sT[1]) or sT != sT[1])
        newBars.push(DetBar.new(sT, sT2, sO, sH, sL, sC, sH2, sL2, sO1, sH1, sL1, sC1, sRv, sAtr))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ State {
var array<FVG>  fvgs  = array.new<FVG>()
var array<IFVG> ifvgs = array.new<IFVG>()
var string topFvgKey = ""
var int detCount = 0
var int lastT = 0
var float lastAtr = na
 
// Hold-rate stats per grade (A, B, C, D)
var array<int> statHold   = array.from(0, 0, 0, 0)
var array<int> statTotal  = array.from(0, 0, 0, 0)
var array<int> iStatHold  = array.from(0, 0, 0, 0)
var array<int> iStatTotal = array.from(0, 0, 0, 0)
 
// Factor test buckets: 0-8 FVG, 9-17 IFVG
var array<string> fLabels = array.from(
     "Size <0.5 ATR", "Size 0.5-1", "Size 1+", "Disp <0.6", "Disp 0.6-1", "Disp 1+", "RVOL <1", "RVOL 1-1.5", "RVOL 1.5+",
     "Gap <0.5 ATR", "Gap 0.5-1", "Gap 1+", "Break <0.6", "Break 0.6-1", "Break 1+", "Close Past <0.3", "Close Past 0.3-0.6", "Close Past 0.6+")
var array<int> fHold  = array.new<int>(18, 0)
var array<int> fTotal = array.new<int>(18, 0)
 
newBullFvgAlert     = false
newBearFvgAlert     = false
newTopRankAlert     = false
bullTouchAlert      = false
bearTouchAlert      = false
fullyMitigatedAlert = false
newIfvgAlert        = false
ceTapAlert          = false
 
overlapsAny(float top, float bot) =>
    bool hit = false
    for f in fvgs
        if top >= f.bottom and bot <= f.top
            hit := true
            break
    if not hit
        for x in ifvgs
            if top >= x.bottom and bot <= x.top
                hit := true
                break
    hit
 
inRange(float top, float bot) =>
    not useDistHide or na(lastAtr) or lastAtr <= 0 or math.abs(close - math.avg(top, bot)) / lastAtr <= distMax
 
rateOf(array<int> hold, array<int> total, int g) =>
    int n = total.get(g)
    n > 0 ? 100.0 * hold.get(g) / n : na
 
bumpIdx(array<int> idxs, bool held) =>
    for k in idxs
        fTotal.set(k, fTotal.get(k) + 1)
        if held
            fHold.set(k, fHold.get(k) + 1)
    true
 
zoneLabel(string prefix, int grade, array<int> hold, array<int> total) =>
    string txt = prefix
    if labelMode != "Hidden"
        txt := prefix == "" ? gradeName(grade) : prefix + " " + gradeName(grade)
        if labelMode == "Grade + %"
            int n = total.get(grade)
            float hr = rateOf(hold, total, grade)
            if n >= minSamples and not na(hr)
                txt += " " + str.tostring(math.round(hr)) + "%"
            if showN
                txt += " (" + str.tostring(n) + ")"
    txt
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Process each completed detection bar {
for b in newBars
    if b.t <= lastT
        continue
    lastT := b.t
    detCount += 1
    if not na(b.atr)
        lastAtr := b.atr
 
    float breakDown = useClose ? b.c : b.l
    float breakUp   = useClose ? b.c : b.h
 
    // 1) IFVGs: real-trade tracking, delete if price breaks back through
    if ifvgs.size() > 0
        for i = ifvgs.size() - 1 to 0
            IFVG x = ifvgs.get(i)
            bool wasTouched = x.touched
            bool touchedNow = x.direction == 1 ? b.l <= x.top : b.h >= x.bottom
            bool invalid    = x.direction == 1 ? breakDown < x.bottom : breakUp > x.top
 
            if touchedNow
                x.touched := true
 
            if x.counted and not x.resolved and (wasTouched or touchedNow)
                int res = tradeOutcome(x.direction, x.top, x.bottom, wasTouched, b.h, b.l)
                if res != 0
                    if res == 1
                        iStatHold.set(x.grade, iStatHold.get(x.grade) + 1)
                    iStatTotal.set(x.grade, iStatTotal.get(x.grade) + 1)
                    bumpIdx(array.from(9 + x.fGap, 12 + x.fBody, 15 + x.fDist), res == 1)
                    x.resolved := true
 
            if invalid
                box.delete(x.body)
                box.delete(x.txtBox)
                line.delete(x.midLine)
                ifvgs.remove(i)
 
    // 2) FVGs: touch, CE tap, real-trade tracking, IFVG conversion
    if fvgs.size() > 0
        for i = fvgs.size() - 1 to 0
            FVG f = fvgs.get(i)
            int age         = detCount - f.bornBar
            bool showable   = f.grade <= minGradeIdx
            bool wasTouched = f.touched
            bool touchedNow = f.direction == 1 ? b.l <= f.top : b.h >= f.bottom
            bool broken     = f.direction == 1 ? breakDown < f.bottom : breakUp > f.top
 
            if touchedNow
                f.touched := true
                bullTouchAlert := bullTouchAlert or (showable and f.direction == 1)
                bearTouchAlert := bearTouchAlert or (showable and f.direction == -1)
                float fillDistance = f.direction == 1 ? f.top - b.l : b.h - f.bottom
                float zoneSize = math.max(f.top - f.bottom, syminfo.mintick)
                f.mitigation := math.max(f.mitigation, math.min(math.max(fillDistance / zoneSize, 0), 1))
 
            float fMid = math.avg(f.top, f.bottom)
            if not f.ceTapped and (f.direction == 1 ? b.l <= fMid : b.h >= fMid)
                f.ceTapped := true
                ceTapAlert := ceTapAlert or showable
 
            if f.counted and not f.resolved and (wasTouched or touchedNow)
                int res = tradeOutcome(f.direction, f.top, f.bottom, wasTouched, b.h, b.l)
                if res != 0
                    if res == 1
                        statHold.set(f.grade, statHold.get(f.grade) + 1)
                    statTotal.set(f.grade, statTotal.get(f.grade) + 1)
                    bumpIdx(array.from(f.fSize, 3 + f.fDisp, 6 + f.fRvol), res == 1)
                    f.resolved := true
 
            f.qualityScore := f.score * 10 - f.mitigation * 50 - age * 0.1
 
            if broken
                fullyMitigatedAlert := fullyMitigatedAlert or showable
                float distReq = na(b.atr) ? 0.0 : ifvgCloseDist * b.atr
                bool closeOk  = ifvgCloseDist <= 0 ? true : f.direction == 1 ? b.c <= f.bottom - distReq : b.c >= f.top + distReq
                bool dispOk   = not ifvgReqDisp or isDisp(b.o, b.h, b.l, b.c, b.atr, f.direction == -1)
 
                if showIFVG and closeOk and dispOk
                    // Grade the IFVG at the flip
                    float atrNow    = na(b.atr) ? 0.0 : b.atr
                    float bodyAtrB  = atrNow > 0 ? math.abs(b.c - b.o) / atrNow : 0.0
                    float closePast = f.direction == 1 ? f.bottom - b.c : b.c - f.top
                    float distAtr   = atrNow > 0 ? closePast / atrNow : 0.0
                    int gT = f.fSize
                    int bT = bodyAtrB >= 1.0 ? 2 : bodyAtrB >= 0.6 ? 1 : 0
                    int dT = distAtr >= 0.6 ? 2 : distAtr >= 0.3 ? 1 : 0
                    int iScore = gT + bT + dT
                    int iGrade = gradeOf(iScore, ifvgAMin, ifvgBMin, ifvgCMin)
 
                    float nt = f.top
                    float nb = f.bottom
                    if ifvgRedraw
                        nt := math.max(b.o, b.c)
                        nb := math.min(b.o, b.c)
                        box.set_top(f.body, nt)
                        box.set_bottom(f.body, nb)
                        line.set_y1(f.midLine, math.avg(nt, nb))
                        line.set_y2(f.midLine, math.avg(nt, nb))
                    IFVG x = IFVG.new(nt, nb, -f.direction, f.startBar, f.leftTime, f.body, f.midLine, f.txtBox,
                         iScore, iGrade, atrNow, inStatsSess(b.t) and atrNow > 0, false, false, gT, bT, dT)
                    paintIfvg(x)
                    ifvgs.push(x)
                    newIfvgAlert := newIfvgAlert or iGrade <= minGradeIdx
                else
                    box.delete(f.body)
                    box.delete(f.txtBox)
                    line.delete(f.midLine)
                fvgs.remove(i)
 
    // 3) New FVG (filters + grade + factor buckets)
    bool isBull = b.l > b.h2
    bool isBear = b.h < b.l2
    if isBull or isBear
        float top     = isBull ? b.l : b.l2
        float bottom  = isBull ? b.h2 : b.h
        int direction = isBull ? 1 : -1
        float fvgSize = math.abs(top - bottom)
 
        bool sizeOk    = not useMinSize or (not na(b.atr) and fvgSize >= minSizeAtr * b.atr)
        bool dispOk    = not useDisp or isDisp(b.o1, b.h1, b.l1, b.c1, b.atr, isBull)
        bool overlapOk = not useOverlap or not overlapsAny(top, bottom)
 
        if sizeOk and dispOk and overlapOk
            float atrB    = na(b.atr) ? 0.0 : b.atr
            float sizeAtr = atrB > 0 ? fvgSize / atrB : 0.0
            float body1   = math.abs(b.c1 - b.o1)
            bool dir1Ok   = direction == 1 ? b.c1 > b.o1 : b.c1 < b.o1
            float bodyAtr = atrB > 0 ? body1 / atrB : 0.0
            float rv      = nz(b.rvol1)
 
            int sizeT = sizeAtr >= 1.0 ? 2 : sizeAtr >= 0.5 ? 1 : 0
            int dispT = not dir1Ok ? 0 : bodyAtr >= 1.0 ? 2 : bodyAtr >= 0.6 ? 1 : 0
            int rvolT = rv >= 1.5 ? 2 : rv >= 1.0 ? 1 : 0
 
            int score     = scoreOf(sizeT, dispT, rvolT)
            int grade     = gradeOf(score, gradeAMin, gradeBMin, gradeCMin)
            bool showable = grade <= minGradeIdx
 
            newBullFvgAlert := newBullFvgAlert or (showable and direction == 1)
            newBearFvgAlert := newBearFvgAlert or (showable and direction == -1)
 
            color dirColor = direction == 1 ? bullColor : bearColor
            int leftTime   = b.t2
            int rightTime  = boxRight(leftTime)
            float mid      = math.avg(top, bottom)
 
            box body = box.new(left = leftTime, right = rightTime, top = top, bottom = bottom, xloc = xloc.bar_time,
                 bgcolor = color.new(dirColor, bodyTransp), border_color = showBorder ? color.new(dirColor, borderTransp) : noColor,
                 border_style = borderStyle, border_width = borderWidth)
            line midLine = line.new(leftTime, mid, rightTime, mid, xloc = xloc.bar_time,
                 color = showMid ? color.new(dirColor, borderTransp) : noColor, style = midStyle, width = borderWidth)
            box txtBox = box.new(left = leftTime, right = rightTime, top = top, bottom = mid, xloc = xloc.bar_time, bgcolor = noColor, border_color = noColor)
 
            fvgs.push(FVG.new(score * 10.0, top, bottom, direction, detCount, bar_index, leftTime, score, grade, atrB, 0.0,
                 inStatsSess(b.t) and atrB > 0, false, false, false, body, midLine, txtBox, sizeT, dispT, rvolT))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Max bars back cleanup {
if fvgs.size() > 0
    for i = fvgs.size() - 1 to 0
        FVG f = fvgs.get(i)
        if bar_index - f.startBar > maxBarsBack
            box.delete(f.body)
            box.delete(f.txtBox)
            line.delete(f.midLine)
            fvgs.remove(i)
 
if ifvgs.size() > 0
    for i = ifvgs.size() - 1 to 0
        IFVG x = ifvgs.get(i)
        if bar_index - x.startBar > maxBarsBack
            box.delete(x.body)
            box.delete(x.txtBox)
            line.delete(x.midLine)
            ifvgs.remove(i)
 
while ifvgs.size() > maxStored
    IFVG old = ifvgs.shift()
    box.delete(old.body)
    box.delete(old.txtBox)
    line.delete(old.midLine)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Rank {
fvgs.sort(order.descending, sort_field = "qualityScore")
 
if fvgs.size() > 0
    FVG topFvg = fvgs.get(0)
    string currentTopKey = str.tostring(topFvg.leftTime) + "_" + str.tostring(topFvg.direction)
    newTopRankAlert := currentTopKey != topFvgKey
    topFvgKey := currentTopKey
 
while fvgs.size() > maxStored
    FVG removed = fvgs.pop()
    box.delete(removed.body)
    box.delete(removed.txtBox)
    line.delete(removed.midLine)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Draw FVGs {
if fvgs.size() > 0
    for i = 0 to fvgs.size() - 1
        FVG fvg = fvgs.get(i)
        color dirColor = fvg.direction == 1 ? bullColor : bearColor
        int left  = fvg.leftTime
        int right = boxRight(left)
        float top = box.get_top(fvg.body)
        float bot = box.get_bottom(fvg.body)
 
        bool showZone = i < maxZones and fvg.grade <= minGradeIdx and inRange(top, bot)
        bool tapped   = markCE and fvg.ceTapped
 
        box.set_right(fvg.body, right)
        box.set_bgcolor(fvg.body, showZone ? color.new(dirColor, bodyTransp) : noColor)
        box.set_border_color(fvg.body, showZone and showBorder ? color.new(dirColor, borderTransp) : noColor)
        box.set_border_width(fvg.body, tapped ? math.min(borderWidth + 1, 4) : borderWidth)
 
        line.set_x2(fvg.midLine, right)
        line.set_color(fvg.midLine, showZone and showMid ? color.new(dirColor, borderTransp) : noColor)
        line.set_style(fvg.midLine, tapped ? line.style_solid : midStyle)
 
        string txt = showZone and showFvgLabel ? zoneLabel("FVG", fvg.grade, statHold, statTotal) : ""
        setTopText(fvg.txtBox, left, right, top, bot, txt, color.new(dirColor, 0))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Draw IFVGs {
if ifvgs.size() > 0
    for i = 0 to ifvgs.size() - 1
        IFVG x = ifvgs.get(i)
        color ic = x.direction == 1 ? ifvgBullColor : ifvgBearColor
        int right = boxRight(x.leftTime)
        bool vis = inRange(x.top, x.bottom) and x.grade <= minGradeIdx
        box.set_right(x.body, right)
        line.set_x2(x.midLine, right)
        if vis
            paintIfvg(x)
        else
            box.set_bgcolor(x.body, noColor)
            box.set_border_color(x.body, noColor)
            line.set_color(x.midLine, noColor)
        string itxt = vis and showIfvgLabel ? zoneLabel("IFVG", x.grade, iStatHold, iStatTotal) : ""
        setTopText(x.txtBox, x.leftTime, right, x.top, x.bottom, itxt, color.new(ic, 0))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Tables {
var table st = table.new(posOf(tablePos), 3, 9, bgcolor = color.new(#0d1117, 20), border_width = 0)
var table ft = table.new(posOf(factorPos), 3, 20, bgcolor = color.new(#0d1117, 20), border_width = 0)
 
if showTable and barstate.islast
    table.cell(st, 0, 0, "Grade", text_color = color.gray, text_size = size.tiny)
    table.cell(st, 1, 0, "Hold",  text_color = color.gray, text_size = size.tiny)
    table.cell(st, 2, 0, "n",     text_color = color.gray, text_size = size.tiny)
    for g = 0 to 3
        color rowCol = g == 3 ? color.gray : color.white
        int n = statTotal.get(g)
        float hr = rateOf(statHold, statTotal, g)
        table.cell(st, 0, g + 1, gradeName(g), text_color = rowCol, text_size = size.tiny, text_halign = text.align_left)
        table.cell(st, 1, g + 1, na(hr) ? "–" : str.tostring(math.round(hr)) + "%", text_color = rowCol, text_size = size.tiny)
        table.cell(st, 2, g + 1, str.tostring(n), text_color = color.gray, text_size = size.tiny)
        int ni = iStatTotal.get(g)
        float hi = rateOf(iStatHold, iStatTotal, g)
        table.cell(st, 0, g + 5, "IFVG " + gradeName(g), text_color = rowCol, text_size = size.tiny, text_halign = text.align_left)
        table.cell(st, 1, g + 5, na(hi) ? "–" : str.tostring(math.round(hi)) + "%", text_color = rowCol, text_size = size.tiny)
        table.cell(st, 2, g + 5, str.tostring(ni), text_color = color.gray, text_size = size.tiny)
 
if showFactors and barstate.islast
    table.cell(ft, 0, 0, "FVG Factor", text_color = color.gray, text_size = size.tiny, text_halign = text.align_left)
    table.cell(ft, 1, 0, "Hold", text_color = color.gray, text_size = size.tiny)
    table.cell(ft, 2, 0, "n",    text_color = color.gray, text_size = size.tiny)
    table.cell(ft, 0, 10, "IFVG Factor", text_color = color.gray, text_size = size.tiny, text_halign = text.align_left)
    table.cell(ft, 1, 10, "", text_size = size.tiny)
    table.cell(ft, 2, 10, "", text_size = size.tiny)
    for k = 0 to 17
        int row = k < 9 ? k + 1 : k + 2
        int n = fTotal.get(k)
        string hr = n > 0 ? str.tostring(math.round(100.0 * fHold.get(k) / n)) + "%" : "–"
        table.cell(ft, 0, row, fLabels.get(k), text_color = color.white, text_size = size.tiny, text_halign = text.align_left)
        table.cell(ft, 1, row, hr, text_color = color.white, text_size = size.tiny)
        table.cell(ft, 2, row, str.tostring(n), text_color = color.gray, text_size = size.tiny)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// ~~ Alerts {
alertcondition(alertNewBull and newBullFvgAlert, "New Bullish FVG", "A new bullish FVG has formed.")
alertcondition(alertNewBear and newBearFvgAlert, "New Bearish FVG", "A new bearish FVG has formed.")
alertcondition(alertTopRank and newTopRankAlert, "New Top-Ranked FVG", "A new FVG has become the highest-ranked zone.")
alertcondition(alertBullTouch and bullTouchAlert, "Bullish FVG Touch", "Price has touched a bullish FVG.")
alertcondition(alertBearTouch and bearTouchAlert, "Bearish FVG Touch", "Price has touched a bearish FVG.")
alertcondition(alertFullyMitigated and fullyMitigatedAlert, "FVG Broken Through", "Price broke through an FVG.")
alertcondition(alertNewIFVG and newIfvgAlert, "New IFVG", "An FVG converted into an IFVG.")
alertcondition(alertCETap and ceTapAlert, "FVG CE Tap", "Price tapped the 50% (CE) of an FVG.")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
 
// =============================== ORDER BLOCKS ===============================
 
// -----------------------------------------------------------------------------------------------
// ----------------------------------   FRACTAL RANGE   ------------------------------------------
// -----------------------------------------------------------------------------------------------  
 
temp0 = input.bool(true, '••••••••••••••••••• Fractals ••••••••••••••••••••••')
showFractals = input.bool(true, 'Show Fractal Points ?')
filterFractal = input.string('3', 'Filter 3/5 bar fractal', options=['3', '5'])
fractal_pos = input.string('On wick', 'Fractal position', options=['On wick', 'Above/below bar'])
fractal_style = input.string('Dot', 'Fractal style', options=['Dot', 'Triangle', 'Diamond', 'X'])
fractal_size = input.string('Small', 'Fractal size', options=['Tiny', 'Small', 'Normal', 'Large', 'Huge'])
fractal_high_color = input(#FF0000, 'Fractal High color')
fractal_low_color = input(#33FF00, 'Fractal Low color')
 
temp1 = input.bool(true, '••••••••••••••••••• Orderblocks •••••••••••••••••••')
findObType = input.string('Close', 'Find OB after fractal break of close/HL', options=['Close', 'HL'])
filterFvgs = input.bool(true, 'Filter only OB that follow with FVG ?')
fvgDistance = input.int(3, 'Max bars between the OB and FVG', minval=1, maxval=6)
obLookback = input.int(150, 'Max candles back (everything)', minval=1, maxval=500)
lineHeight = input.string('Wick', 'Line Height', options=['Body', 'Wick'])
delLines = input.bool(true, 'Delete lines after fill ?')
 
temp6 = input.bool(false, '•••••••••••••••• 5-min Order Blocks •••••••••••••••')
htfOn = input.bool(false, 'Show 5-min order blocks on lower charts ?')
obHtfTF = input.timeframe('5', 'Order block timeframe')
 
temp2 = input.bool(false, '••••••••••••••••••• Possible Zones ••••••••••••••••')
showPreview = input.bool(true, 'Show possible zone before the break ?')
previewATR = input.float(0.5, 'Show when price is within (x ATR) of fractal', minval=0.05, maxval=5, step=0.05)
previewTransp = input.int(50, 'Possible zone transparency', minval=0, maxval=90)
 
temp3 = input.bool(true, '•••••••••••••••••••• Styles ••••••••••••••••••••••••')
lines_style = input.string('Solid', 'Lines style', options=['Solid', 'Dashed', 'Dotted'])
line_length = input.int(25, 'Length of lines', minval=1, maxval=100)
lineStyle = lines_style == 'Solid' ? line.style_solid : lines_style == 'Dashed' ? line.style_dashed : line.style_dotted
linesWidth = input.int(2, 'Lines Width ?', minval=1, maxval=4)
bear_line_color = input(color.red, 'Bear OB Line color')
bull_line_color = input(#33FF00, 'Bull OB Line color')
 
temp4 = input.bool(true, '••••••••••••••••••• Shaded Zone •••••••••••••••••••')
shadeZones = input.bool(true, 'Shade area between the lines ?')
shade_bear_color = input(color.red, 'Bear zone fill color')
shade_bull_color = input(#4CAF50, 'Bull zone fill color')
shade_transparency = input.int(80, 'Fill transparency', minval=0, maxval=100)
 
temp5 = input.bool(false, '••••••••••••••••••• Block Stats •••••••••••••••••••')
showStats = input.bool(true, 'Show block stats text ?')
scaleText = input.bool(true, 'Text scales with zoom ?')
showBE = input.bool(true, 'Show back-to-even line ?')
showRetest = input.bool(true, 'Include the retest count ?')
stats_bear_color = input(#FFCDD2, 'Bear text color')
stats_bull_color = input(#33FF00, 'Bull text color')
stats_size = input.string('Large', 'Stats text size', options=['Tiny', 'Small', 'Normal', 'Large', 'Huge', 'Auto'])
be_bear_color = input(#FF0000, 'Bear BE line color')
be_bull_color = input(#33FF00, 'Bull BE line color')
be_width = input.int(3, 'BE line width', minval=1, maxval=4)
fpOn = input.bool(true, 'Use footprint data (Premium) ?')
fpTicks = input.int(5, 'Footprint row size (ticks)', minval=1, maxval=100)
fpImb = input.int(300, 'Imbalance ratio %', minval=150, maxval=1000, step=50)
fpStack = input.int(3, 'Stacked rows for trapped', minval=2, maxval=10)
useEst = input.bool(true, 'Estimate when there is no footprint ?')
estTF = input.string('1', 'Estimate data timeframe', options=['1S', '5S', '10S', '15S', '1'])
balPct = input.int(60, 'Balanced below %', minval=51, maxval=90)
strongCut = input.float(80, 'STRONG percentile >=', minval=0, maxval=100)
highCut = input.float(50, 'HIGH percentile >=', minval=0, maxval=100)
 
frSize = fractal_size == 'Tiny' ? size.tiny : fractal_size == 'Small' ? size.small : fractal_size == 'Normal' ? size.normal : fractal_size == 'Large' ? size.large : size.huge
 
// Zoom-scaling text lives in its own invisible box (right half; upper half for bear, lower half for bull)
useBoxTxt = showStats and scaleText
 
// Fractal marker look and placement
frYlocHi = fractal_pos == 'On wick' ? yloc.price : yloc.abovebar
frYlocLo = fractal_pos == 'On wick' ? yloc.price : yloc.belowbar
frStyleHi = fractal_style == 'Dot' ? label.style_circle : fractal_style == 'Diamond' ? label.style_diamond : fractal_style == 'X' ? label.style_xcross : label.style_triangledown
frStyleLo = fractal_style == 'Dot' ? label.style_circle : fractal_style == 'Diamond' ? label.style_diamond : fractal_style == 'X' ? label.style_xcross : label.style_triangleup
 
// 5-min mode is only active when the chart is on a LOWER timeframe than the order block timeframe.
// On the 5-min chart itself (or higher) the script works exactly as normal.
htfActive = htfOn and timeframe.in_seconds() < timeframe.in_seconds(obHtfTF)
htfMs = timeframe.in_seconds(obHtfTF) * 1000
 
// ATR for the "possible zone" distance (calculated every bar)
atrV = ta.atr(14)
 
// Ring size: one slot per candle inside the max lookback (500) plus the current one
RING = 501
 
// One record per live zone: what traded in the block candle, and its drawings.
type zstat
    float buy = na
    float sell = na
    bool isfp = false
    float poc = na
    float rank = na
    float vol = na
    bool trap = false
    int born = 0
    int touch = 0
    bool inPrev = false
    label lb = na
    line be = na
    box tb = na
 
// Per-candle volume data, kept by candle so a zone can read the block candle later.
var array<float> upRing = array.new<float>(RING, na)
var array<float> dnRing = array.new<float>(RING, na)
var array<float> fbRing = array.new<float>(RING, na)
var array<float> fsRing = array.new<float>(RING, na)
var array<float> ftbRing = array.new<float>(RING, na)
var array<float> ftsRing = array.new<float>(RING, na)
var array<float> fpocRing = array.new<float>(RING, na)
var array<float> obVolHist = array.new<float>()
var array<int> obVolBars = array.new<int>()
 
 
 
// -------------------- FUNCTIONS --------------------
bullishImb(i=0) => close[i+1] > high[i+2] and low[i] > high[i+2]
bearishImb(i=0) => close[i+1] < low[i+2] and high[i] < low[i+2]
 
//  Fractals
isRegularFractal(mode) =>
    ret = mode == 'Buy' ? high[0] < high[1] and (high[2] < high[1] or high[2] == high[1] and high[3] < high[2]) : mode == 'Sell' ? low[0] > low[1] and (low[2] > low[1] or low[2] == low[1] and low[3] > low[2]) : false
    ret
 
isBWFractal(mode) =>
    ret = mode == 'Buy' ? high[0] < high[2] and high[1] < high[2] and high[3] < high[2] and high[4] < high[2] : mode == 'Sell' ? low[0] > low[2] and low[1] > low[2] and low[3] > low[2] and low[4] > low[2] : false
    ret
 
isFractalHigh() =>
    filterFractal == '3' ? isRegularFractal('Buy') : isBWFractal('Buy')
 
isFractalLow() =>
    filterFractal == '3' ? isRegularFractal('Sell') : isBWFractal('Sell')
 
// Forget fractals whose pivot is older than the candle limit, so nothing outside it is kept or re-checked
f_pruneFractals(array<float> prices, array<int> bars, int oldestBar) =>
    if array.size(bars) > 0
        for j = array.size(bars) - 1 to 0 by 1
            if array.get(bars, j) < oldestBar
                array.remove(prices, j)
                array.remove(bars, j)
 
// Same OB search as the confirmed zones, used for the possible-zone preview and 5-min mode
f_scanBear(int fb) =>
    int idx = 0
    float mx = -1000000000.0
    int gapIndex = 0
    int maxK = math.min(obLookback, bar_index - fb)
    for k = 0 to maxK by 1
        if close[k] > open[k] and high[k] > mx
            idx := k
            mx := high[k]
        if filterFvgs and close[k+1] < low[k+2] and high[k] < low[k+2]
            gapIndex := k + 2
    [idx, gapIndex]
 
f_scanBull(int fb) =>
    int idx = 0
    float mn = 1000000000.0
    int gapIndex = 0
    int maxK = math.min(obLookback, bar_index - fb)
    for k = 0 to maxK by 1
        if close[k] < open[k] and low[k] < mn
            idx := k
            mn := low[k]
        if filterFvgs and close[k+1] > high[k+2] and low[k] > high[k+2]
            gapIndex := k + 2
    [idx, gapIndex]
 
// Runs ON THE 5-MIN CANDLES: same fractal-break logic, returns the zone found on the last CLOSED 5-min candle
f_htfOB() =>
    var array<float> hfl = array.new<float>()
    var array<int> hflb = array.new<int>()
    var array<float> hfh = array.new<float>()
    var array<int> hfhb = array.new<int>()
    if isFractalHigh()
        array.push(hfh, filterFractal == '3' ? high[1] : high[2])
        array.push(hfhb, bar_index - (filterFractal == '3' ? 1 : 2))
    if isFractalLow()
        array.push(hfl, filterFractal == '3' ? low[1] : low[2])
        array.push(hflb, bar_index - (filterFractal == '3' ? 1 : 2))
    f_pruneFractals(hfh, hfhb, bar_index - obLookback)
    f_pruneFractals(hfl, hflb, bar_index - obLookback)
    float bT = na
    float bB = na
    int bTm = na
    float uT = na
    float uB = na
    int uTm = na
    if array.size(hfl) > 0
        for i = array.size(hfl) - 1 to 0 by 1
            if (findObType == 'Close' ? close : low) < array.get(hfl, i)
                [idx, gap] = f_scanBear(array.get(hflb, i))
                bool ok = filterFvgs ? gap > 0 and idx - gap >= 0 and idx - gap <= fvgDistance : true
                if idx != 0 and ok and na(bTm)
                    bT := high[idx]
                    bB := lineHeight == 'Body' ? open[idx] : low[idx]
                    bTm := time[idx]
                array.remove(hfl, i)
                array.remove(hflb, i)
    if array.size(hfh) > 0
        for i = array.size(hfh) - 1 to 0 by 1
            if (findObType == 'Close' ? close : high) > array.get(hfh, i)
                [idx, gap] = f_scanBull(array.get(hfhb, i))
                bool ok = filterFvgs ? gap > 0 and idx - gap >= 0 and idx - gap <= fvgDistance : true
                if idx != 0 and ok and na(uTm)
                    uB := low[idx]
                    uT := lineHeight == 'Body' ? open[idx] : high[idx]
                    uTm := time[idx]
                array.remove(hfh, i)
                array.remove(hfhb, i)
    [bT[1], bB[1], bTm[1], uT[1], uB[1], uTm[1]]
 
// Longest run of stacked imbalance rows in a row
f_stackLen(array<float> lows, float step) =>
    int best = 0
    int n = array.size(lows)
    if n > 0
        array.sort(lows)
        best := 1
        int run = 1
        if n > 1
            for i = 1 to n - 1
                bool adj = step > 0 and math.abs(array.get(lows, i) - array.get(lows, i - 1) - step) <= step * 0.25
                run := adj ? run + 1 : 1
                best := math.max(best, run)
    best
 
// Percentile rank of a block candle volume against the blocks inside the candle limit only
f_rankIn(array<float> hist, array<int> histBars, float v, int oldestBar) =>
    if array.size(histBars) > 0
        for j = array.size(histBars) - 1 to 0 by 1
            if array.get(histBars, j) < oldestBar
                array.remove(hist, j)
                array.remove(histBars, j)
    int n = array.size(hist)
    float r = 50.0
    if n > 0
        int cnt = 0
        for x in hist
            if x < v
                cnt += 1
        r := 100.0 * cnt / n
    array.push(hist, nz(v))
    array.push(histBars, bar_index)
    if array.size(hist) > 500
        array.shift(hist)
        array.shift(histBars)
    r
 
f_k(float v) =>
    float a = math.abs(v)
    a >= 1e6 ? str.tostring(a / 1e6, '0.00') + 'm' : a >= 1e3 ? str.tostring(a / 1e3, '0.00') + 'k' : str.tostring(a, '0')
 
f_rankLbl(float r) =>
    nz(r) >= strongCut ? 'STRONG' : nz(r) >= highCut ? 'HIGH' : 'NORMAL'
 
f_rtWord(int n) =>
    n <= 0 ? 'FRESH' : n == 1 ? 'GREAT' : n == 2 ? 'OK' : 'WEAK'
 
f_txtSize() =>
    stats_size == 'Tiny' ? size.tiny : stats_size == 'Small' ? size.small : stats_size == 'Large' ? size.large : stats_size == 'Huge' ? size.huge : stats_size == 'Auto' ? size.auto : size.normal
 
// The three lines of text that sit inside the zone, at its right edge
f_statsTxt(zstat z, bool bull) =>
    string out = ''
    float tot = nz(z.buy) + nz(z.sell)
    bool hasBS = not na(z.buy) and not na(z.sell) and tot > 0
    if hasBS
        int pb = int(math.round(z.buy / tot * 100))
        int ps = 100 - pb
        bool trapped = z.isfp and z.trap
        string word = trapped ? (bull ? 'TRAPPED SELLERS' : 'TRAPPED BUYERS') : math.max(pb, ps) < balPct ? 'BALANCED' : pb > ps ? 'BUYERS' : 'SELLERS'
        float dl = z.buy - z.sell
        out := (z.isfp ? '' : '~') + 'Buy' + str.tostring(pb) + '%/Sell' + str.tostring(ps) + '%=' + word + '\nDelta ' + (dl >= 0 ? '+' : '-') + f_k(dl) + '/Vol ' + f_k(z.vol) + '=' + f_rankLbl(z.rank)
    else
        out := 'Buy n/a/Sell n/a\nVol ' + f_k(z.vol) + '=' + f_rankLbl(z.rank)
    if showRetest
        out += '\nRetest ' + str.tostring(z.touch) + '=' + f_rtWord(z.touch)
    out
 
// Text for 5-min zones shown on a lower chart (no footprint stats available there)
f_htfTxt(zstat z) =>
    obHtfTF + 'm OB' + (showRetest ? '\nRetest ' + str.tostring(z.touch) + '=' + f_rtWord(z.touch) : '')
 
// Fills a stats record from the block candle, which is idx candles back.
f_makeStats(int idx) =>
    int bk = (bar_index - idx) % RING
    float fB = array.get(fbRing, bk)
    float fS = array.get(fsRing, bk)
    bool hasFP = not na(fB) and not na(fS) and fB + fS > 0
    zstat z = zstat.new()
    z.isfp := hasFP
    z.buy := hasFP ? fB : array.get(upRing, bk)
    z.sell := hasFP ? fS : array.get(dnRing, bk)
    z.poc := array.get(fpocRing, bk)
    z.vol := volume[idx]
    z.rank := f_rankIn(obVolHist, obVolBars, volume[idx], bar_index - obLookback)
    z.born := bar_index
    z
// -------------------- FUNCTIONS --------------------
 
 
 
// -------------------- BLOCK STATS DATA --------------------
// Footprint first: it is the main source (skipped in 5-min mode, where chart-candle stats are not used)
float fpB = na
float fpS = na
float fpPoc = na
bool fpTrB = false
bool fpTrS = false
if fpOn and not htfActive
    fpObj = request.footprint(fpTicks, 70, fpImb)
    if not na(fpObj)
        fpB := fpObj.buy_volume()
        fpS := fpObj.sell_volume()
        pRow = fpObj.poc()
        if not na(pRow)
            fpPoc := math.avg(pRow.up_price(), pRow.down_price())
        rws = fpObj.rows()
        nR = array.size(rws)
        if nR > 0
            avgV = fpObj.total_volume() / nR
            row0 = array.get(rws, 0)
            rowStep = row0.up_price() - row0.down_price()
            topCut = high - (high - low) / 3.0
            botCut = low + (high - low) / 3.0
            bLows = array.new<float>()
            sLows = array.new<float>()
            for r in rws
                mid = math.avg(r.up_price(), r.down_price())
                bool big = r.total_volume() >= avgV
                if big and r.has_buy_imbalance() and mid >= topCut
                    array.push(bLows, r.down_price())
                if big and r.has_sell_imbalance() and mid <= botCut
                    array.push(sLows, r.down_price())
            fpTrB := f_stackLen(bLows, rowStep) >= fpStack
            fpTrS := f_stackLen(sLows, rowStep) >= fpStack
 
bool hasFpNow = not na(fpB) and not na(fpS) and fpB + fpS > 0
 
// Estimate is only a backup: skipped on candles that already have footprint data
float ltfUp = na
float ltfDn = na
if useEst and not hasFpNow and not htfActive
    [ltfO, ltfC, ltfV] = request.security_lower_tf(syminfo.tickerid, estTF, [open, close, volume], ignore_invalid_timeframe = true)
    if not na(ltfV) and array.size(ltfV) > 0
        ltfUp := 0.0
        ltfDn := 0.0
        float prevC = na
        for j = 0 to array.size(ltfV) - 1
            float o1 = array.get(ltfO, j)
            float c1 = array.get(ltfC, j)
            float v1 = nz(array.get(ltfV, j))
            bool upBar = c1 > o1 ? true : c1 < o1 ? false : na(prevC) ? true : c1 >= prevC
            if upBar
                ltfUp += v1
            else
                ltfDn += v1
            prevC := c1
 
ringK = bar_index % RING
array.set(upRing, ringK, ltfUp)
array.set(dnRing, ringK, ltfDn)
array.set(fbRing, ringK, fpB)
array.set(fsRing, ringK, fpS)
array.set(ftbRing, ringK, fpTrB ? 1.0 : 0.0)
array.set(ftsRing, ringK, fpTrS ? 1.0 : 0.0)
array.set(fpocRing, ringK, fpPoc)
// -------------------- BLOCK STATS DATA --------------------
 
 
 
// -------------------- Fractals --------------------
fractal_high_val = 0.0
fractal_low_val = 0.0
 
var fractal_highs = array.new<float>(0)  // array of high fractal values
var fractal_high_bars = array.new<int>(0)  // array of high fractal bar numbers
var fractal_lows = array.new<float>(0)  // array of low fractal values
var fractal_low_bars = array.new<int>(0)  // array of low fractal bar numbers
 
//Bookkeeping of every live order block, so a fractal can know if it is inside one
var ob_bear_id = array.new<int>()
var ob_bear_x0 = array.new<int>()
var ob_bear_x1 = array.new<int>()
var ob_bull_id = array.new<int>()
var ob_bull_x0 = array.new<int>()
var ob_bull_x1 = array.new<int>()
var ob_lbl = array.new<label>()
var ob_lbl_owner = array.new<int>()
var ob_next_id = 0
 
// The block candle of every live zone, so the same block is never drawn twice
var ob_bear_blk = array.new<int>()
var ob_bull_blk = array.new<int>()
 
// Stats of every live zone, kept in the same order as the lines of that side
var ob_bear_z = array.new<zstat>()
var ob_bull_z = array.new<zstat>()
 
// Returns the id of the live order block ON ONE SIDE whose lines cover this bar, or -1 when none does
// bull = true checks bullish zones only, bull = false checks bearish zones only
zoneCovering(int pivotBar, bool bull) =>
    found = -1
    if bull
        if array.size(ob_bull_id) > 0
            for j = array.size(ob_bull_id) - 1 to 0 by 1
                if pivotBar >= array.get(ob_bull_x0, j) and pivotBar <= array.get(ob_bull_x1, j)
                    found := array.get(ob_bull_id, j)
    else
        if array.size(ob_bear_id) > 0
            for j = array.size(ob_bear_id) - 1 to 0 by 1
                if pivotBar >= array.get(ob_bear_x0, j) and pivotBar <= array.get(ob_bear_x1, j)
                    found := array.get(ob_bear_id, j)
    found
 
// Check if fractal and add it to array
if isFractalHigh()
    if filterFractal == '3'
        array.push(fractal_highs, high[1])
        array.push(fractal_high_bars, bar_index - 1)
        fractal_high_val := high[1]
    else
        array.push(fractal_highs, high[2])
        array.push(fractal_high_bars, bar_index - 2)
        fractal_high_val := high[2]
 
if isFractalLow()
    if filterFractal == '3'
        array.push(fractal_lows, low[1])
        array.push(fractal_low_bars, bar_index - 1)
        fractal_low_val := low[1]
    else
        array.push(fractal_lows, low[2])
        array.push(fractal_low_bars, bar_index - 2)
        fractal_low_val := low[2]
 
//Nothing outside the candle limit is kept: old fractals are dropped here
f_pruneFractals(fractal_highs, fractal_high_bars, bar_index - obLookback)
f_pruneFractals(fractal_lows, fractal_low_bars, bar_index - obLookback)
// -------------------- Fractals --------------------
 
 
 
// -------------------- Orderblocks --------------------
var line1 = array.new<line>()
var line2 = array.new<line>()
var line3 = array.new<line>()
var line4 = array.new<line>()
 
var boxBear = array.new<box>()
var boxBull = array.new<box>()
 
// True when a live zone is already sitting on that block candle
f_seenBlk(array<int> blks, int blkBar) =>
    hit = false
    if array.size(blks) > 0
        for j = 0 to array.size(blks) - 1
            if array.get(blks, j) == blkBar
                hit := true
    hit
 
// Removes one bear zone from tracking; del = also delete its drawings from the chart
f_dropBear(int i, int zid, bool del) =>
    if del
        line.delete(array.get(line1, i))
        line.delete(array.get(line2, i))
        if array.size(boxBear) > i and not na(array.get(boxBear, i))
            box.delete(array.get(boxBear, i))
        if array.size(ob_bear_z) > i
            zdB = array.get(ob_bear_z, i)
            if not na(zdB.be)
                line.delete(zdB.be)
            if not na(zdB.lb)
                label.delete(zdB.lb)
            if not na(zdB.tb)
                box.delete(zdB.tb)
    array.remove(line1, i)
    array.remove(line2, i)
    if array.size(boxBear) > i
        array.remove(boxBear, i)
    if array.size(ob_bear_z) > i
        array.remove(ob_bear_z, i)
    if array.size(ob_bear_id) > i
        array.remove(ob_bear_id, i)
        array.remove(ob_bear_x0, i)
        array.remove(ob_bear_x1, i)
    if array.size(ob_bear_blk) > i
        array.remove(ob_bear_blk, i)
    if zid != -1 and array.size(ob_lbl) > 0
        for j = array.size(ob_lbl) - 1 to 0 by 1
            if array.get(ob_lbl_owner, j) == zid
                if del
                    label.delete(array.get(ob_lbl, j))
                array.remove(ob_lbl, j)
                array.remove(ob_lbl_owner, j)
 
// Removes one bull zone from tracking; del = also delete its drawings from the chart
f_dropBull(int i, int zid, bool del) =>
    if del
        line.delete(array.get(line3, i))
        line.delete(array.get(line4, i))
        if array.size(boxBull) > i and not na(array.get(boxBull, i))
            box.delete(array.get(boxBull, i))
        if array.size(ob_bull_z) > i
            zdU = array.get(ob_bull_z, i)
            if not na(zdU.be)
                line.delete(zdU.be)
            if not na(zdU.lb)
                label.delete(zdU.lb)
            if not na(zdU.tb)
                box.delete(zdU.tb)
    array.remove(line3, i)
    array.remove(line4, i)
    if array.size(boxBull) > i
        array.remove(boxBull, i)
    if array.size(ob_bull_z) > i
        array.remove(ob_bull_z, i)
    if array.size(ob_bull_id) > i
        array.remove(ob_bull_id, i)
        array.remove(ob_bull_x0, i)
        array.remove(ob_bull_x1, i)
    if array.size(ob_bull_blk) > i
        array.remove(ob_bull_blk, i)
    if zid != -1 and array.size(ob_lbl) > 0
        for j = array.size(ob_lbl) - 1 to 0 by 1
            if array.get(ob_lbl_owner, j) == zid
                if del
                    label.delete(array.get(ob_lbl, j))
                array.remove(ob_lbl, j)
                array.remove(ob_lbl_owner, j)
 
// Fractal HIGHS only show inside a live BEARISH zone
if showFractals and isFractalHigh()
    fr_bar = bar_index - (filterFractal == '3' ? 1 : 2)
    fr_price = filterFractal == '3' ? high[1] : high[2]
    owner = zoneCovering(fr_bar, false)
    if owner != -1
        array.push(ob_lbl, label.new(fr_bar, fr_price, '', xloc=xloc.bar_index, yloc=frYlocHi, style=frStyleHi, color=fractal_high_color, textcolor=fractal_high_color, size=frSize))
        array.push(ob_lbl_owner, owner)
 
// Fractal LOWS only show inside a live BULLISH zone
if showFractals and isFractalLow()
    fr_bar2 = bar_index - (filterFractal == '3' ? 1 : 2)
    fr_price2 = filterFractal == '3' ? low[1] : low[2]
    owner2 = zoneCovering(fr_bar2, true)
    if owner2 != -1
        array.push(ob_lbl, label.new(fr_bar2, fr_price2, '', xloc=xloc.bar_index, yloc=frYlocLo, style=frStyleLo, color=fractal_low_color, textcolor=fractal_low_color, size=frSize))
        array.push(ob_lbl_owner, owner2)
 
// Bearish loop (chart-timeframe zones; off while 5-min mode is active)
if not htfActive and array.size(fractal_lows) > 0
    for i = array.size(fractal_lows) - 1 to 0 by 1
        if (findObType == 'Close' ? close : low) < array.get(fractal_lows, i)
            idx = 0
            max = -1000000000.0  //no candle excluded at the start
            gapIndex = 0
            // Only scan the candles from the fractal pivot to now
            maxK = math.min(obLookback, bar_index - array.get(fractal_low_bars, i))
 
            for k = 0 to maxK by 1
                //Get all bullish candles in range
                if close[k] > open[k] and high[k] > max
                    idx := k
                    max := high[k]
 
                if filterFvgs and close[k+1] < low[k+2] and high[k] < low[k+2]
                    gapIndex := k+2
 
            _filterFvg = filterFvgs ? gapIndex > 0 and idx - gapIndex >= 0 and idx - gapIndex <= fvgDistance : true
            // Line on OB, but never a second zone on the same block candle
            if idx != 0 and _filterFvg and not f_seenBlk(ob_bear_blk, bar_index - idx)
                xFrom = bar_index - idx
                xTo = xFrom + line_length
                loc = lineHeight == 'Body' ? open[idx] : low[idx]
 
                // Block stats: what traded in the block candle
                zb = f_makeStats(idx)
                zb.trap := array.get(ftbRing, (bar_index - idx) % RING) == 1.0
                zTopB = math.max(high[idx], loc)
                zBtmB = math.min(high[idx], loc)
 
                array.push(line1, line.new(x1=xFrom, y1=high[idx], x2=xTo, y2=high[idx], xloc=xloc.bar_index, style=lineStyle, color=bear_line_color, width=linesWidth))
                array.push(line2, line.new(x1=xFrom, y1=loc, x2=xTo, y2=loc, xloc=xloc.bar_index, style=lineStyle, color=bear_line_color, width=linesWidth))
 
                if shadeZones
                    array.push(boxBear, box.new(left=xFrom, top=zTopB, right=xTo, bottom=zBtmB, xloc=xloc.bar_index, border_color=color.new(bear_line_color, 100), bgcolor=color.new(shade_bear_color, shade_transparency)))
                else
                    array.push(boxBear, na)
 
                ob_next_id += 1
                array.push(ob_bear_id, ob_next_id)
                array.push(ob_bear_x0, xFrom)
                array.push(ob_bear_x1, xTo)
                array.push(ob_bear_blk, xFrom)
 
                if showBE and not na(zb.poc) and zb.poc <= zTopB and zb.poc >= zBtmB
                    zb.be := line.new(x1=xFrom, y1=zb.poc, x2=xTo, y2=zb.poc, xloc=xloc.bar_index, style=line.style_dotted, color=be_bear_color, width=be_width)
                // Zoom-scaling text: invisible box over the right half, upper half of the zone
                if useBoxTxt
                    zb.tb := box.new(left=xFrom + math.round(line_length / 2), top=zTopB, right=xTo, bottom=math.avg(zTopB, zBtmB), xloc=xloc.bar_index, border_color=color.new(color.white, 100), bgcolor=color.new(color.white, 100), text=f_statsTxt(zb, false), text_size=size.auto, text_color=stats_bear_color, text_halign=text.align_right, text_valign=text.align_top)
                // Normal fixed-size label (used when zoom-scaling is off)
                else if showStats
                    zb.lb := label.new(xTo, zTopB, f_statsTxt(zb, false), xloc=xloc.bar_index, style=label.style_label_upper_right, color=color.new(color.white, 100), textcolor=stats_bear_color, size=f_txtSize(), textalign=text.align_right)
                array.push(ob_bear_z, zb)
 
            array.remove(fractal_lows, i)
            array.remove(fractal_low_bars, i)
 
// Bullish loop (chart-timeframe zones; off while 5-min mode is active)
if not htfActive and array.size(fractal_highs) > 0
    for i = array.size(fractal_highs) - 1 to 0 by 1
        if (findObType == 'Close' ? close : high) > array.get(fractal_highs, i)
            idx = 0
            min = 1000000000.0  //no candle excluded at the start
            gapIndex = 0
            // Only scan the candles from the fractal pivot to now
            maxK = math.min(obLookback, bar_index - array.get(fractal_high_bars, i))
 
            for k = 0 to maxK by 1
                //  if bearish candle
                if close[k] < open[k] and low[k] < min
                    idx := k
                    min := low[k]
 
                if filterFvgs and close[k+1] > high[k+2] and low[k] > high[k+2]
                    gapIndex := k+2
 
            _filterFvg = filterFvgs ? gapIndex > 0 and idx - gapIndex >= 0 and idx - gapIndex <= fvgDistance : true
            // Line on OB, but never a second zone on the same block candle
            if idx != 0 and _filterFvg and not f_seenBlk(ob_bull_blk, bar_index - idx)
                xFrom = bar_index - idx
                xTo = xFrom + line_length
                loc = lineHeight == 'Body' ? open[idx] : high[idx]
 
                // Block stats: what traded in the block candle
                zu = f_makeStats(idx)
                zu.trap := array.get(ftsRing, (bar_index - idx) % RING) == 1.0
                zTopU = math.max(low[idx], loc)
                zBtmU = math.min(low[idx], loc)
 
                array.push(line3, line.new(x1=xFrom, y1=low[idx], x2=xTo, y2=low[idx], xloc=xloc.bar_index, style=lineStyle, color=bull_line_color, width=linesWidth))
                array.push(line4, line.new(x1=xFrom, y1=loc, x2=xTo, y2=loc, xloc=xloc.bar_index, style=lineStyle, color=bull_line_color, width=linesWidth))
 
                if shadeZones
                    array.push(boxBull, box.new(left=xFrom, top=zTopU, right=xTo, bottom=zBtmU, xloc=xloc.bar_index, border_color=color.new(bull_line_color, 100), bgcolor=color.new(shade_bull_color, shade_transparency)))
                else
                    array.push(boxBull, na)
 
                ob_next_id += 1
                array.push(ob_bull_id, ob_next_id)
                array.push(ob_bull_x0, xFrom)
                array.push(ob_bull_x1, xTo)
                array.push(ob_bull_blk, xFrom)
 
                if showBE and not na(zu.poc) and zu.poc <= zTopU and zu.poc >= zBtmU
                    zu.be := line.new(x1=xFrom, y1=zu.poc, x2=xTo, y2=zu.poc, xloc=xloc.bar_index, style=line.style_dotted, color=be_bull_color, width=be_width)
                // Zoom-scaling text: invisible box over the right half, lower half of the zone
                if useBoxTxt
                    zu.tb := box.new(left=xFrom + math.round(line_length / 2), top=math.avg(zTopU, zBtmU), right=xTo, bottom=zBtmU, xloc=xloc.bar_index, border_color=color.new(color.white, 100), bgcolor=color.new(color.white, 100), text=f_statsTxt(zu, true), text_size=size.auto, text_color=stats_bull_color, text_halign=text.align_right, text_valign=text.align_bottom)
                // Normal fixed-size label (used when zoom-scaling is off)
                else if showStats
                    zu.lb := label.new(xTo, zBtmU, f_statsTxt(zu, true), xloc=xloc.bar_index, style=label.style_label_lower_right, color=color.new(color.white, 100), textcolor=stats_bull_color, size=f_txtSize(), textalign=text.align_right)
                array.push(ob_bull_z, zu)
 
            array.remove(fractal_highs, i)
            array.remove(fractal_high_bars, i)
 
// -------------------- Orderblocks --------------------
 
// -------------------- 5-min order blocks on a lower chart --------------------
var array<line> hBearA = array.new<line>()
var array<line> hBearB = array.new<line>()
var array<box> hBearBx = array.new<box>()
var array<int> hBearTm = array.new<int>()
var array<zstat> hBearZ = array.new<zstat>()
var array<line> hBullA = array.new<line>()
var array<line> hBullB = array.new<line>()
var array<box> hBullBx = array.new<box>()
var array<int> hBullTm = array.new<int>()
var array<zstat> hBullZ = array.new<zstat>()
 
// Removes one 5-min zone from tracking; del = also delete its drawings
f_hDrop(array<line> a, array<line> b, array<box> bx, array<int> tm, array<zstat> zs, int i, bool del) =>
    if del
        line.delete(array.get(a, i))
        line.delete(array.get(b, i))
        if not na(array.get(bx, i))
            box.delete(array.get(bx, i))
        zd = array.get(zs, i)
        if not na(zd.lb)
            label.delete(zd.lb)
        if not na(zd.tb)
            box.delete(zd.tb)
    array.remove(a, i)
    array.remove(b, i)
    array.remove(bx, i)
    array.remove(tm, i)
    array.remove(zs, i)
 
float hbT = na
float hbB = na
int hbTm = na
float huT = na
float huB = na
int huTm = na
if htfActive
    [r1, r2, r3, r4, r5, r6] = request.security(syminfo.tickerid, obHtfTF, f_htfOB(), lookahead=barmerge.lookahead_on)
    hbT := r1
    hbB := r2
    hbTm := r3
    huT := r4
    huB := r5
    huTm := r6
 
// Draw once per new 5-min candle, from the last CLOSED 5-min candle (no repaint)
if htfActive and timeframe.change(obHtfTF)
    if not na(hbTm) and not array.includes(hBearTm, hbTm)
        int hx2 = hbTm + line_length * htfMs
        int hxMid = hbTm + math.round(line_length * htfMs / 2)
        float hTop = math.max(hbT, hbB)
        float hBot = math.min(hbT, hbB)
        zh = zstat.new()
        zh.born := bar_index
        array.push(hBearA, line.new(hbTm, hbT, hx2, hbT, xloc=xloc.bar_time, style=lineStyle, color=bear_line_color, width=linesWidth))
        array.push(hBearB, line.new(hbTm, hbB, hx2, hbB, xloc=xloc.bar_time, style=lineStyle, color=bear_line_color, width=linesWidth))
        if shadeZones
            array.push(hBearBx, box.new(left=hbTm, top=hTop, right=hx2, bottom=hBot, xloc=xloc.bar_time, border_color=color.new(bear_line_color, 100), bgcolor=color.new(shade_bear_color, shade_transparency)))
        else
            array.push(hBearBx, na)
        if useBoxTxt
            zh.tb := box.new(left=hxMid, top=hTop, right=hx2, bottom=math.avg(hTop, hBot), xloc=xloc.bar_time, border_color=color.new(color.white, 100), bgcolor=color.new(color.white, 100), text=f_htfTxt(zh), text_size=size.auto, text_color=stats_bear_color, text_halign=text.align_right, text_valign=text.align_top)
        else if showStats
            zh.lb := label.new(hx2, hTop, f_htfTxt(zh), xloc=xloc.bar_time, style=label.style_label_upper_right, color=color.new(color.white, 100), textcolor=stats_bear_color, size=f_txtSize(), textalign=text.align_right)
        array.push(hBearTm, hbTm)
        array.push(hBearZ, zh)
    if not na(huTm) and not array.includes(hBullTm, huTm)
        int ux2 = huTm + line_length * htfMs
        int uxMid = huTm + math.round(line_length * htfMs / 2)
        float uTop = math.max(huT, huB)
        float uBot = math.min(huT, huB)
        zh2 = zstat.new()
        zh2.born := bar_index
        array.push(hBullA, line.new(huTm, huB, ux2, huB, xloc=xloc.bar_time, style=lineStyle, color=bull_line_color, width=linesWidth))
        array.push(hBullB, line.new(huTm, huT, ux2, huT, xloc=xloc.bar_time, style=lineStyle, color=bull_line_color, width=linesWidth))
        if shadeZones
            array.push(hBullBx, box.new(left=huTm, top=uTop, right=ux2, bottom=uBot, xloc=xloc.bar_time, border_color=color.new(bull_line_color, 100), bgcolor=color.new(shade_bull_color, shade_transparency)))
        else
            array.push(hBullBx, na)
        if useBoxTxt
            zh2.tb := box.new(left=uxMid, top=math.avg(uTop, uBot), right=ux2, bottom=uBot, xloc=xloc.bar_time, border_color=color.new(color.white, 100), bgcolor=color.new(color.white, 100), text=f_htfTxt(zh2), text_size=size.auto, text_color=stats_bull_color, text_halign=text.align_right, text_valign=text.align_bottom)
        else if showStats
            zh2.lb := label.new(ux2, uBot, f_htfTxt(zh2), xloc=xloc.bar_time, style=label.style_label_lower_right, color=color.new(color.white, 100), textcolor=stats_bull_color, size=f_txtSize(), textalign=text.align_right)
        array.push(hBullTm, huTm)
        array.push(hBullZ, zh2)
 
// Retests for 5-min zones
if array.size(hBearZ) > 0
    for i = 0 to array.size(hBearZ) - 1
        zq = array.get(hBearZ, i)
        qa = line.get_y1(array.get(hBearA, i))
        qb = line.get_y1(array.get(hBearB, i))
        bool qIn = high >= math.min(qa, qb) and low <= math.max(qa, qb)
        bool qHit = qIn and not zq.inPrev and bar_index > zq.born
        if qHit
            zq.touch += 1
        zq.inPrev := qIn
        if showStats and qHit
            if not na(zq.lb)
                label.set_text(zq.lb, f_htfTxt(zq))
            if not na(zq.tb)
                box.set_text(zq.tb, f_htfTxt(zq))
 
if array.size(hBullZ) > 0
    for i = 0 to array.size(hBullZ) - 1
        zq2 = array.get(hBullZ, i)
        qc = line.get_y1(array.get(hBullA, i))
        qd = line.get_y1(array.get(hBullB, i))
        bool qIn2 = high >= math.min(qc, qd) and low <= math.max(qc, qd)
        bool qHit2 = qIn2 and not zq2.inPrev and bar_index > zq2.born
        if qHit2
            zq2.touch += 1
        zq2.inPrev := qIn2
        if showStats and qHit2
            if not na(zq2.lb)
                label.set_text(zq2.lb, f_htfTxt(zq2))
            if not na(zq2.tb)
                box.set_text(zq2.tb, f_htfTxt(zq2))
 
// Expire old 5-min zones, then remove filled ones
if array.size(hBearTm) > 0
    for i = array.size(hBearTm) - 1 to 0 by 1
        if time - array.get(hBearTm, i) > obLookback * htfMs
            f_hDrop(hBearA, hBearB, hBearBx, hBearTm, hBearZ, i, true)
        else if high >= math.max(line.get_y1(array.get(hBearA, i)), line.get_y1(array.get(hBearB, i)))
            f_hDrop(hBearA, hBearB, hBearBx, hBearTm, hBearZ, i, delLines)
 
if array.size(hBullTm) > 0
    for i = array.size(hBullTm) - 1 to 0 by 1
        if time - array.get(hBullTm, i) > obLookback * htfMs
            f_hDrop(hBullA, hBullB, hBullBx, hBullTm, hBullZ, i, true)
        else if low <= math.min(line.get_y1(array.get(hBullA, i)), line.get_y1(array.get(hBullB, i)))
            f_hDrop(hBullA, hBullB, hBullBx, hBullTm, hBullZ, i, delLines)
// -------------------- 5-min order blocks --------------------
 
// -------------------- Possible zones (before the break) --------------------
// Faded dotted lines on the OB that would form if price breaks the nearest fractal.
// Redrawn every bar; replaced by the real zone once the break confirms.
var line pvBearA = na
var line pvBearB = na
var line pvBullA = na
var line pvBullB = na
line.delete(pvBearA)
line.delete(pvBearB)
line.delete(pvBullA)
line.delete(pvBullB)
pvBearA := na
pvBearB := na
pvBullA := na
pvBullB := na
 
if showPreview and not htfActive and array.size(fractal_lows) > 0
    float pxB = findObType == 'Close' ? close : low
    int bestB = -1
    float bestPB = na
    for i = 0 to array.size(fractal_lows) - 1
        float fp = array.get(fractal_lows, i)
        if pxB > fp and pxB - fp <= previewATR * atrV and (na(bestPB) or fp > bestPB)
            bestB := i
            bestPB := fp
    if bestB != -1
        [pIdxB, pGapB] = f_scanBear(array.get(fractal_low_bars, bestB))
        bool okB = filterFvgs ? pGapB > 0 and pIdxB - pGapB >= 0 and pIdxB - pGapB <= fvgDistance : true
        if pIdxB != 0 and okB and not f_seenBlk(ob_bear_blk, bar_index - pIdxB)
            int pxFromB = bar_index - pIdxB
            float pLocB = lineHeight == 'Body' ? open[pIdxB] : low[pIdxB]
            pvBearA := line.new(x1=pxFromB, y1=high[pIdxB], x2=pxFromB + line_length, y2=high[pIdxB], xloc=xloc.bar_index, style=line.style_dotted, color=color.new(bear_line_color, previewTransp), width=1)
            pvBearB := line.new(x1=pxFromB, y1=pLocB, x2=pxFromB + line_length, y2=pLocB, xloc=xloc.bar_index, style=line.style_dotted, color=color.new(bear_line_color, previewTransp), width=1)
 
if showPreview and not htfActive and array.size(fractal_highs) > 0
    float pxU = findObType == 'Close' ? close : high
    int bestU = -1
    float bestPU = na
    for i = 0 to array.size(fractal_highs) - 1
        float fp = array.get(fractal_highs, i)
        if pxU < fp and fp - pxU <= previewATR * atrV and (na(bestPU) or fp < bestPU)
            bestU := i
            bestPU := fp
    if bestU != -1
        [pIdxU, pGapU] = f_scanBull(array.get(fractal_high_bars, bestU))
        bool okU = filterFvgs ? pGapU > 0 and pIdxU - pGapU >= 0 and pIdxU - pGapU <= fvgDistance : true
        if pIdxU != 0 and okU and not f_seenBlk(ob_bull_blk, bar_index - pIdxU)
            int pxFromU = bar_index - pIdxU
            float pLocU = lineHeight == 'Body' ? open[pIdxU] : high[pIdxU]
            pvBullA := line.new(x1=pxFromU, y1=low[pIdxU], x2=pxFromU + line_length, y2=low[pIdxU], xloc=xloc.bar_index, style=line.style_dotted, color=color.new(bull_line_color, previewTransp), width=1)
            pvBullB := line.new(x1=pxFromU, y1=pLocU, x2=pxFromU + line_length, y2=pLocU, xloc=xloc.bar_index, style=line.style_dotted, color=color.new(bull_line_color, previewTransp), width=1)
// -------------------- Possible zones --------------------
 
// -------------------- Retests --------------------
// One retest each time price comes back into a live zone, and the text follows it.
if array.size(ob_bear_z) > 0 and array.size(line1) > 0
    for i = 0 to math.min(array.size(ob_bear_z), array.size(line1)) - 1
        zB = array.get(ob_bear_z, i)
        yA = line.get_y1(array.get(line1, i))
        yB = line.get_y1(array.get(line2, i))
        bool inNowB = high >= math.min(yA, yB) and low <= math.max(yA, yB)
        bool hitB = inNowB and not zB.inPrev and bar_index > zB.born
        if hitB
            zB.touch += 1
        zB.inPrev := inNowB
        if showStats and hitB
            if not na(zB.lb)
                label.set_text(zB.lb, f_statsTxt(zB, false))
            if not na(zB.tb)
                box.set_text(zB.tb, f_statsTxt(zB, false))
 
if array.size(ob_bull_z) > 0 and array.size(line3) > 0
    for i = 0 to math.min(array.size(ob_bull_z), array.size(line3)) - 1
        zU = array.get(ob_bull_z, i)
        yC = line.get_y1(array.get(line3, i))
        yD = line.get_y1(array.get(line4, i))
        bool inNowU = high >= math.min(yC, yD) and low <= math.max(yC, yD)
        bool hitU = inNowU and not zU.inPrev and bar_index > zU.born
        if hitU
            zU.touch += 1
        zU.inPrev := inNowU
        if showStats and hitU
            if not na(zU.lb)
                label.set_text(zU.lb, f_statsTxt(zU, true))
            if not na(zU.tb)
                box.set_text(zU.tb, f_statsTxt(zU, true))
// -------------------- Retests --------------------
 
// Expire zones whose block candle is older than the candle limit
if array.size(ob_bear_x0) > 0
    for i = array.size(ob_bear_x0) - 1 to 0 by 1
        if array.get(ob_bear_x0, i) < bar_index - obLookback
            f_dropBear(i, array.size(ob_bear_id) > i ? array.get(ob_bear_id, i) : -1, true)
 
if array.size(ob_bull_x0) > 0
    for i = array.size(ob_bull_x0) - 1 to 0 by 1
        if array.get(ob_bull_x0, i) < bar_index - obLookback
            f_dropBull(i, array.size(ob_bull_id) > i ? array.get(ob_bull_id, i) : -1, true)
 
// Remove filled zones (drawings deleted only when "Delete lines after fill" is on)
if array.size(line1) > 0
    for i = array.size(line1) - 1 to 0 by 1
        if high >= line.get_y1(array.get(line1, i)) and high >= line.get_y1(array.get(line2, i))
            f_dropBear(i, array.size(ob_bear_id) > i ? array.get(ob_bear_id, i) : -1, delLines)
 
if array.size(line3) > 0
    for i = array.size(line3) - 1 to 0 by 1
        if low <= line.get_y1(array.get(line3, i)) and low <= line.get_y1(array.get(line4, i))
            f_dropBull(i, array.size(ob_bull_id) > i ? array.get(ob_bull_id, i) : -1, delLines)
 
// -----------------------------------------------------------------------------------------------
// ----------------------------------   IDM (INDUCEMENT)   ---------------------------------------
// -----------------------------------------------------------------------------------------------
// Structure is a silent copy of the EMS swing rules (BOS / CHoCH, swing confirm candles, wick check).
// Nothing of it is drawn. After a bullish BOS / CHoCH the FIRST pullback low is the IDM (bearish: the
// first pullback high). ⚠ IDM = not swept yet, do not enter. IDM ✓ = price traded through it.
// A new BOS / CHoCH before it is swept cancels it. Minor IDM (optional) = the latest pullback.
gIDM = "IDM (Inducement)"
idmOn      = input.bool(true, "Show IDM", group = gIDM, tooltip = "IDM = the first pullback after a BOS / CHoCH. ⚠ IDM = not swept yet: do not enter, the zone behind it is not ready. IDM ✓ = price traded through it: the trap is done. A new BOS / CHoCH before it is swept cancels it.")
idmTF      = input.string("5", "IDM structure timeframe", options = ["5", "1"], group = gIDM, tooltip = "Which candles the BOS / CHoCH and swings come from. 5 = 5-minute structure drawn on any lower chart (updates when each 5-minute candle closes, never repaints). Works on charts of this timeframe or lower.")
idmMinor   = input.bool(false, "Show minor IDM (latest pullback)", group = gIDM, tooltip = "mIDM = the latest pullback since the break; it moves to a newer pullback closer to the trend. Off = only the first pullback (the main IDM).")
idmSess    = input.session("0400-2000", "Session hours (match EMS)", group = gIDM, tooltip = "Same session as your EMS. Structure resets at the start of each session (New York time).")
iMsLen     = input.int(5, "CHoCH pivot length (match EMS)", minval = 2, group = gIDM)
iMsMode    = input.string("Adjusted Points", "CHoCH logic (match EMS)", options = ["Extreme Points", "Adjusted Points"], group = gIDM)
iChSrc     = input.string("Pivot", "CHoCH level follows (match EMS)", options = ["Pivot", "Swing labels"], group = gIDM)
iSwConf    = input.int(2, "Swing confirm candles (match EMS)", minval = 1, maxval = 5, group = gIDM, tooltip = "Keep these four the same as your EMS settings so the IDM follows the same structure.")
idmWarnCol = input.color(#ff9800, "⚠ IDM color", inline = "ic1", group = gIDM)
idmDoneCol = input.color(#b2b5be, "IDM ✓ color", inline = "ic1", group = gIDM)
idmW       = input.int(2, "Line width", minval = 1, maxval = 4, group = gIDM)
idmTxt     = input.string("Normal", "Text size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = gIDM)
idmBgOn    = input.bool(true, "Label background", inline = "ibg", group = gIDM)
idmBgCol   = input.color(#4a4a4a, "", inline = "ibg", group = gIDM)
idmExt     = input.int(4, "Line runs past price (candles)", minval = 0, maxval = 50, group = gIDM)
idmKeep    = input.int(10, "Swept IDMs to keep", minval = 0, maxval = 50, group = gIDM)
 
f_runDn(int n) =>
    bool ok = n > 0
    if n > 0
        for k = 0 to n - 1
            if not (close[k] < open[k] and high[k] < high[k + 1] and low[k] < low[k + 1])
                ok := false
    ok
 
f_runUp(int n) =>
    bool ok = n > 0
    if n > 0
        for k = 0 to n - 1
            if not (close[k] > open[k] and low[k] > low[k + 1] and high[k] > high[k + 1])
                ok := false
    ok
 
f_idm(string sess, int off) =>
    // structure
    var int   sStart = 0
    var float sBos   = na
    var float sChoch = na
    var int   sLoc   = na
    var int   sTemp  = na
    var int   sTrend = 0
    var float sMain  = na
    var float sUp    = na
    var float sDn    = na
    var float sWick  = na
    var int   sTrBar = na
    var int   sSesB  = na
    var float pHiP   = na      // latest unbroken pivot high / low (CHoCH logic: Pivot)
    var int   pHiB   = na
    var float pLoP   = na
    var int   pLoB   = na
    // swings
    var int   vType  = 0
    var int   vBar   = na
    var float vPx    = na
    var int   cBar   = na
    var float cPx    = na
    var float hiS    = na
    var int   hiSB   = na
    var float loS    = na
    var int   loSB   = na
    var float prHi   = na
    var int   prHiB  = na
    var bool  hiOk   = false
    var float prLo   = na
    var int   prLoB  = na
    var bool  loOk   = false
    // output: older swing (a), newer swing (b), and a count of new swings
    var int   swAT     = na
    var float swAP     = na
    var int   swBT     = na
    var float swBP     = na
    var int   swCnt    = 0
    // IDM: dir 1 = after a bullish break (IDM is a pullback LOW), -1 = after a bearish break (a pullback HIGH)
    // state 0 = none / cancelled, 1 = waiting to be swept (⚠), 2 = swept (✓)
    var int   iDir   = 0
    var int   brkBar = na
    var bool  iWait  = false
    var float mjP    = na
    var int   mjT    = na
    var int   mjS    = 0
    var int   mjSwT  = na
    var float mnP    = na
    var int   mnT    = na
    var int   mnS    = 0
    var int   mnSwT  = na
 
    float ph    = ta.pivothigh(high, iMsLen, iMsLen)
    float pl    = ta.pivotlow(low, iMsLen, iMsLen)
    float a14   = ta.atr(14)
    float wPen  = a14 * 10.0 / 100.0
    bool  runDn = f_runDn(iSwConf)
    bool  runUp = f_runUp(iSwConf)
    bool  inS   = not na(time(timeframe.period, sess, "America/New_York"))
    bool  ss    = inS and (not inS[1] or ta.change(time("D")) != 0)
 
    if ss
        // a new session: an IDM still waiting is cancelled (swept ones stay as history)
        if mjS == 1
            mjS := 0
        if mnS == 1
            mnS := 0
        iDir  := 0
        iWait := false
        sStart := 0
        sUp    := na
        sDn    := na
        sWick  := na
        sTrBar := na
        sSesB  := bar_index
        pHiP   := na
        pHiB   := na
        pLoP   := na
        pLoB   := na
        vType  := 0
        vBar   := na
        vPx    := na
        cBar   := na
        cPx    := na
        hiS    := na
        hiSB   := na
        loS    := na
        loSB   := na
        swAT     := na
        swAP     := na
        swBT     := na
        swBP     := na
 
    if inS
        // IDM sweep check first: bullish IDM swept when price trades below it, bearish above it
        if mjS == 1 and (iDir == 1 ? low < mjP : high > mjP)
            mjS   := 2
            mjSwT := time
        if mnS == 1 and (iDir == 1 ? low < mnP : high > mnP)
            mnS   := 2
            mnSwT := time
        // pivots and "still intact" checks (section 2)
        int fromB = nz(sSesB, 0)
        if not na(ph) and bar_index - iMsLen >= fromB
            pHiP := high[iMsLen]
            pHiB := bar_index - iMsLen
        if not na(pl) and bar_index - iMsLen >= fromB
            pLoP := low[iMsLen]
            pLoB := bar_index - iMsLen
        if not na(pHiP) and high > pHiP
            pHiP := na
            pHiB := na
        if not na(pLoP) and low < pLoP
            pLoP := na
            pLoB := na
        if not na(prHi) and close > prHi
            hiOk := false
        if not na(prLo) and close < prLo
            loOk := false
 
        // structure (section 3)
        int  evB  = 0
        int  evW  = 0
        bool setH = false
        bool setL = false
        bool crU  = false
        bool crD  = false
        if na(sUp)
            sUp := high
        if na(sDn)
            sDn := low
        if high > sUp
            sUp := high
            sDn := low
            crU := true
        if low < sDn
            sUp := high
            sDn := low
            crD := true
 
        if sStart == 0
            sStart := 1
            sBos   := high
            sChoch := low
            sLoc   := bar_index
            sTemp  := bar_index
            sTrend := 0
            sMain  := na
 
        if sStart == 1
            if close <= sChoch
                sTrend := -1
                sTrBar := bar_index
                sChoch := sBos
                sBos   := na
                sStart := 2
                sLoc   := bar_index
                sMain  := low
                sTemp  := bar_index
                evB    := 4
            else if close >= sBos
                sTrend := 1
                sTrBar := bar_index
                sBos   := na
                sStart := 2
                sLoc   := bar_index
                sMain  := high
                sTemp  := bar_index
                evB    := 3
 
        if sStart == 2
            if sTrend == -1
                if low <= sMain
                    sMain := low
                    sTemp := bar_index
                float adjP = na
                int   adjB = na
                if iChSrc == "Pivot"
                    adjP := pHiP
                    adjB := pHiB
                else if not na(prHi) and hiOk and prHiB > nz(sTrBar, 0)
                    adjP := prHi
                    adjB := prHiB
                if not na(sBos) and iMsMode == "Adjusted Points" and not na(adjP) and adjP < sChoch
                    sChoch := adjP
                    sLoc   := adjB
                if na(sBos) and crU and close > open and close[1] > open[1]
                    sBos := sMain
                    sLoc := sTemp
                    setL := true
                if not na(sBos) and close <= sBos
                    int n  = math.min(math.max(bar_index - sLoc - 1 > 0 ? bar_index - sLoc - 1 : bar_index - sLoc, 0), 500)
                    int id = 0
                    float mx = 0.
                    for k = 0 to n
                        if high[k] >= mx
                            mx := high[k]
                            id := k
                    sBos   := na
                    sChoch := high[id]
                    sLoc   := bar_index - id
                    evB    := 2
                if evB == 0 and not na(sChoch)
                    float reach = high - sChoch
                    if reach > 0 and reach >= wPen and close < sChoch and (na(sWick) or sWick != sChoch)
                        evW   := 1
                        sWick := sChoch
                if close >= sChoch
                    int n  = math.min(math.max(bar_index - sLoc - 1 > 0 ? bar_index - sLoc - 1 : bar_index - sLoc, 0), 500)
                    int id = 0
                    float mn = 99999999.
                    for k = 0 to n
                        if low[k] <= mn
                            mn := low[k]
                            id := k
                    sChoch := na(sBos) ? low[id] : sBos
                    sBos   := na
                    sMain  := high
                    sTrend := 1
                    sTrBar := bar_index
                    sLoc   := bar_index
                    sTemp  := bar_index
                    evB    := 3
            else if sTrend == 1
                if high >= sMain
                    sMain := high
                    sTemp := bar_index
                if na(sBos) and crD and close < open and close[1] < open[1]
                    sBos := sMain
                    sLoc := sTemp
                    setH := true
                float adjP = na
                int   adjB = na
                if iChSrc == "Pivot"
                    adjP := pLoP
                    adjB := pLoB
                else if not na(prLo) and loOk and prLoB > nz(sTrBar, 0)
                    adjP := prLo
                    adjB := prLoB
                if not na(sBos) and iMsMode == "Adjusted Points" and not na(adjP) and adjP > sChoch
                    sChoch := adjP
                    sLoc   := adjB
                if not na(sBos) and close >= sBos
                    int n  = math.min(math.max(bar_index - sLoc - 1 > 0 ? bar_index - sLoc - 1 : bar_index - sLoc, 0), 500)
                    int id = 0
                    float mn = 99999999.
                    for k = 0 to n
                        if low[k] <= mn
                            mn := low[k]
                            id := k
                    sBos   := na
                    sChoch := low[id]
                    sLoc   := bar_index - id
                    evB    := 1
                if evB == 0 and not na(sChoch)
                    float reach = sChoch - low
                    if reach > 0 and reach >= wPen and close > sChoch and (na(sWick) or sWick != sChoch)
                        evW   := 2
                        sWick := sChoch
                if close <= sChoch
                    int n  = math.min(math.max(bar_index - sLoc - 1 > 0 ? bar_index - sLoc - 1 : bar_index - sLoc, 0), 500)
                    int id = 0
                    float mx = 0.
                    for k = 0 to n
                        if high[k] >= mx
                            mx := high[k]
                            id := k
                    sChoch := na(sBos) ? high[id] : sBos
                    sBos   := na
                    sMain  := low
                    sTrend := -1
                    sTrBar := bar_index
                    sLoc   := bar_index
                    sTemp  := bar_index
                    evB    := 4
        if not na(sWick) and (evB == 3 or evB == 4 or na(sChoch) or sChoch != sWick)
            sWick := na
 
        // a new BOS / CHoCH: an IDM still waiting is cancelled, start looking for the first pullback
        if evB != 0
            if mjS == 1
                mjS := 0
            if mnS == 1
                mnS := 0
            iDir   := evB == 1 or evB == 3 ? 1 : -1
            brkBar := bar_index
            iWait  := true
 
        // swings (section 3b). place: 0 none, 1 new swing, 2 the last swing moved
        if na(hiS) or high > hiS
            hiS  := high
            hiSB := bar_index
        if na(loS) or low < loS
            loS  := low
            loSB := bar_index
        int   place = 0
        bool  pHi   = false
        int   pBar  = na
        float pPx   = na
        bool  reset = false      // after placing, the next swing in waiting starts on this candle
        if vType == 0
            if sTrend == -1
                place := 1
                pHi   := true
                pBar  := hiSB
                pPx   := hiS
            else if sTrend == 1
                place := 1
                pHi   := false
                pBar  := loSB
                pPx   := loS
        else
            bool  lookHi  = vType == -1
            bool  done    = false
            bool  thru    = lookHi ? close < vPx : close > vPx
            bool  wick    = lookHi ? low < vPx : high > vPx
            float prSame  = lookHi ? prHi : prLo
            bool  cur     = na(cPx) or (lookHi ? high > cPx : low < cPx)
            float candNow = cur ? (lookHi ? high : low) : cPx
            bool  real    = (thru and not na(cBar) and cBar > vBar) or (not na(prSame) and (lookHi ? candNow > prSame : candNow < prSame))
            if wick
                if real
                    place := 1
                    pHi   := lookHi
                    pBar  := cur ? bar_index : cBar
                    pPx   := cur ? (lookHi ? high : low) : cPx
                    reset := cur
                else
                    place := 2
                    pHi   := not lookHi
                    pBar  := bar_index
                    pPx   := lookHi ? low : high
                done := true
            else if cur
                cPx  := lookHi ? high : low
                cBar := bar_index
            if not done and not na(cBar)
                bool counter  = lookHi ? sTrend == -1 : sTrend == 1
                bool turn2    = counter and cBar <= bar_index - iSwConf and (lookHi ? runDn : runUp)
                bool wickTurn = lookHi ? evW == 1 : evW == 2
                if turn2 or wickTurn or (lookHi ? setH : setL)
                    place := 1
                    pHi   := lookHi
                    pBar  := cBar
                    pPx   := cPx
                    reset := wickTurn and cBar == bar_index
 
        // IDM: a new pullback swing after the break (a swing LOW after a bullish break, a HIGH after a bearish one)
        if place == 1 and iDir != 0 and pBar > nz(brkBar) and (iDir == 1 ? not pHi : pHi)
            int tP = time[math.min(bar_index - pBar, 500)]
            if iWait
                // Major IDM: the FIRST pullback, fixed until swept or the next break
                iWait := false
                mjP   := pPx
                mjT   := tP
                mjS   := 1
                mjSwT := na
                mnP   := pPx
                mnT   := tP
                mnS   := 1
                mnSwT := na
            else if mjS == 1
                // Minor IDM: the latest pullback; it moves to a newer one that is closer to the trend
                // (higher low after a bullish break, lower high after a bearish one), or after it was swept
                if mnS == 2 or (iDir == 1 ? pPx > mnP : pPx < mnP)
                    mnP   := pPx
                    mnT   := tP
                    mnS   := 1
                    mnSwT := na
 
        if place > 0
            int pT = time[math.min(bar_index - pBar, 500)]
            if place == 1
                if vType != 0
                    swAT := swBT
                    swAP := swBP
                    swCnt += 1
                swBT := pT
                swBP := pPx
            else
                swBT := pT
                swBP := pPx
            vType := pHi ? 1 : -1
            vBar  := pBar
            vPx   := pPx
            if pHi
                prHi  := pPx
                prHiB := pBar
                hiOk  := true
            else
                prLo  := pPx
                prLoB := pBar
                loOk  := true
            // the next swing in waiting: the extreme since this swing
            cBar := na
            cPx  := na
            int nR = math.min(bar_index - vBar, 500)
            if nR >= 1
                for k = nR - 1 to 0
                    float v = vType == 1 ? low[k] : high[k]
                    if na(cPx) or (vType == 1 ? v < cPx : v > cPx)
                        cPx  := v
                        cBar := bar_index - k
            if reset
                cPx  := pHi ? low : high
                cBar := bar_index
    [iDir[off], mjP[off], mjT[off], mjS[off], mjSwT[off], mnP[off], mnT[off], mnS[off], mnSwT[off]]
 
var bool idmChartOk = timeframe.in_seconds() <= timeframe.in_seconds(idmTF)
bool idmSameTF = timeframe.in_seconds() == timeframe.in_seconds(idmTF)
int  idmTfMs   = timeframe.in_seconds(idmTF) * 1000
 
// Other timeframe: only closed candles of that timeframe ([1] with lookahead on), so it never repaints.
[qDir, qMjP, qMjT, qMjS, qMjSwT, qMnP, qMnT, qMnS, qMnSwT] = request.security(syminfo.tickerid, idmTF, f_idm(idmSess, 1), lookahead = barmerge.lookahead_on)
int   iD    = qDir
float iMjP  = qMjP
int   iMjT  = qMjT
int   iMjS  = qMjS
int   iMjSw = qMjSwT
float iMnP  = qMnP
int   iMnT  = qMnT
int   iMnS  = qMnS
int   iMnSw = qMnSwT
// Same timeframe as the chart: calculated right here, no delay
if idmSameTF
    [d0, a0, b0, c0, e0, f0, g0, h0, j0] = f_idm(idmSess, 0)
    iD    := d0
    iMjP  := a0
    iMjT  := b0
    iMjS  := c0
    iMjSw := e0
    iMnP  := f0
    iMnT  := g0
    iMnS  := h0
    iMnSw := j0
 
// Snap a higher-timeframe swing to the exact chart candle whose wick made it
f_snapIdm(int tHi, float p) =>
    int out = tHi
    if not idmSameTF and not na(tHi) and not na(p) and tHi < time
        int tEnd = tHi + idmTfMs
        for k = 0 to math.min(bar_index, 500)
            int tk = time[k]
            if tk < tHi
                break
            if tk < tEnd and (high[k] == p or low[k] == p)
                out := tk
    out
 
f_idmSz(string s) =>
    s == 'Tiny' ? size.tiny : s == 'Small' ? size.small : s == 'Large' ? size.large : s == 'Huge' ? size.huge : size.normal
 
var int   idmBarMs = timeframe.in_seconds() * 1000
var array<line>  idmOldLn = array.new<line>()
var array<label> idmOldLb = array.new<label>()
 
// One IDM drawing (major or minor): its line, label and which swing it belongs to
type idmDraw
    line  ln   = na
    label lb   = na
    int   keyT = na
    float keyP = na
    bool  done = false
 
var idmDraw dMj = idmDraw.new()
var idmDraw dMn = idmDraw.new()
 
f_idmKeep(idmDraw d) =>
    idmOldLn.push(d.ln)
    idmOldLb.push(d.lb)
    while idmOldLn.size() > idmKeep * 2
        line.delete(idmOldLn.shift())
        label.delete(idmOldLb.shift())
    true
 
f_idmKill(idmDraw d) =>
    line.delete(d.ln)
    label.delete(d.lb)
    d.ln   := na
    d.lb   := na
    d.keyT := na
    d.keyP := na
    d.done := false
    true
 
// Draws / updates one IDM. nm = 'IDM' or 'mIDM'
f_idmRun(idmDraw d, int dir, float p, int t, int st, int swT, string nm) =>
    bool bull = dir == 1
    if (st == 1 or st == 2) and not na(p) and not na(t)
        if na(d.keyT) or d.keyT != t or d.keyP != p
            // a different swing: the old one goes to history if swept, otherwise it is removed
            if not na(d.ln)
                if d.done
                    f_idmKeep(d)
                    d.ln := na
                    d.lb := na
                else
                    f_idmKill(d)
            int x0 = f_snapIdm(t, p)
            int xR = time + idmExt * idmBarMs
            d.ln   := line.new(x0, p, xR, p, xloc = xloc.bar_time, color = idmWarnCol, width = idmW, style = line.style_dashed)
            d.lb   := label.new(xR, p, '⚠ ' + nm, xloc = xloc.bar_time, yloc = yloc.price, color = idmBgOn ? idmBgCol : #ffffff00, textcolor = idmWarnCol, style = label.style_label_left, size = f_idmSz(idmTxt))
            d.keyT := t
            d.keyP := p
            d.done := false
        if st == 2 and not d.done
            // swept: line stops at the sweep candle, label turns ✓
            int xs = na(swT) ? time : swT
            line.set_x2(d.ln, xs)
            line.set_color(d.ln, idmDoneCol)
            line.set_style(d.ln, line.style_dotted)
            label.set_x(d.lb, xs)
            label.set_text(d.lb, nm + ' ✓')
            label.set_textcolor(d.lb, idmDoneCol)
            d.done := true
        else if st == 1
            int xR2 = time + idmExt * idmBarMs
            line.set_x2(d.ln, xR2)
            label.set_x(d.lb, xR2)
    else if st == 0 and not na(d.ln) and not d.done
        // cancelled by a new BOS / CHoCH or a new session
        f_idmKill(d)
    true
 
bool idmSweptNow = false
if idmOn and idmChartOk
    idmSweptNow := iMjS == 2 and nz(iMjS[1]) == 1
    f_idmRun(dMj, iD, iMjP, iMjT, iMjS, iMjSw, 'IDM')
    if idmMinor
        // the minor only shows when it sits on a different pullback than the major
        bool mnSame = iMnT == iMjT and iMnP == iMjP
        f_idmRun(dMn, iD, iMnP, iMnT, mnSame ? 0 : iMnS, iMnSw, 'mIDM')
 
alertcondition(idmOn and idmSweptNow, 'IDM swept', 'The IDM (inducement) was swept: the zone behind it is armed.')

← 返回列表