Institutional Order Blocks Levels

Michael_Fx_Trader · study · 527 行 · 点赞 541 · TradingView 原页

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

Pine Script

//@version=6
// =====================================================================================================
//  INSTITUTIONAL ORDER BLOCKS LEVELS
// =====================================================================================================
//  ORIGINAL SCRIPT DECLARATION
//  -----------------------------------------------------------------------------------------------------
//  Script Name        : Institutional Order Blocks Levels
//  Short Title        : IOB Levels
//  Version            : 1.3 (Pine Script v6)
//  Release Date       : 2026-10-27
//  Author             : Michael_Fx_Trader
//  Publisher          : Michael_Fx_Trader
//  Copyright / Rights : (c) 2026 Michael_Fx_Trader. All Rights Reserved.
//
//  AUTHOR VERIFICATION & ORIGINALITY STATEMENT
//  -----------------------------------------------------------------------------------------------------
//  1. This script is an ORIGINAL work, implemented from scratch for Michael_Fx_Trader.
//  2. It is NOT a copy, fork, port, re-skin or mashup of any other published TradingView script,
//     library or open-source project. No third-party source code has been reused.
//  3. The detection engine (displacement validation, candle selection, boundary calculation), the
//     order block lifecycle manager (candidate / confirmed / pending / mitigated / invalidated /
//     expired), the duplicate filter, the capacity manager and the drawing layer were all written
//     specifically for this indicator.
//  4. Only generic, publicly known price-action concepts are used (order block, displacement, swing
//     break, mitigation). Concepts are not proprietary code; the implementation here is original.
//  5. The author and publisher of this script is Michael_Fx_Trader, who holds all rights to it.
//
//  ORDER BLOCK DEFINITION USED BY THIS INDICATOR (naming follows the COLOR of the origin candle)
//  -----------------------------------------------------------------------------------------------------
//  BEARISH ORDER BLOCK : the LAST DOWN (bearish) closed candle before a strong UP move.
//                        Its range is marked as a zone (it sits below the move, price approaches it
//                        from above).
//  BULLISH ORDER BLOCK : the LAST UP (bullish) closed candle before a strong DOWN move.
//                        Its range is marked as a zone (it sits above the move, price approaches it
//                        from below).
//  Both types are detected and drawn at the same time.
//
//  PURPOSE
//  -----------------------------------------------------------------------------------------------------
//  Detects, validates, displays, monitors and automatically removes order blocks. Only PENDING (still
//  valid) zones are displayed by default. Mitigated, invalidated or expired zones are removed unless
//  the user enables the optional history display.
//
//  This indicator is NOT a signal generator and NOT a strategy. It never places entries, exits,
//  stop losses or take profits.
//
//  DISCLAIMER
//  -----------------------------------------------------------------------------------------------------
//  Order blocks drawn by this script are RULE-BASED technical-analysis zones inferred from observable
//  price action. They do not prove the presence of actual institutional order flow. This script is for
//  educational and analytical purposes only and is not financial advice. Trading involves risk.
//
//  NON-REPAINTING DESIGN
//  -----------------------------------------------------------------------------------------------------
//  - All detection and lifecycle logic runs ONLY on confirmed (closed) bars.
//  - Zones are drawn at their historical origin candle, but are created only on the confirmation bar,
//    using only data that was available on that bar. No future data is used.
//  - Swing highs/lows use ta.pivothigh / ta.pivotlow, which are confirmed after 'Swing Length' bars.
//  - No request.security / higher-timeframe data is used, so there is no lookahead bias.
//
//  EXPIRATION RULE PRECEDENCE
//  -----------------------------------------------------------------------------------------------------
//  Exactly one primary rule (Order Block Mitigation Mode) removes a zone. The optional zone-age rule is
//  independent: whichever condition is satisfied FIRST on a confirmed bar removes the zone.
// =====================================================================================================
indicator("Institutional Order Blocks Levels", shorttitle = "IOB Levels", overlay = true, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 500)
 
// =====================================================================================================
//  CONSTANTS
// =====================================================================================================
const int ST_CONFIRMED   = 1
const int ST_PENDING     = 2
const int ST_MITIGATED   = 3
const int ST_INVALIDATED = 4
const int ST_EXPIRED     = 5
 
// =====================================================================================================
//  INPUTS
// =====================================================================================================
const string gA = "A | General Settings"
const string gB = "B | Displacement & Validation"
const string gC = "C | Mitigation & Invalidation"
const string gD = "D | Bullish OB Appearance"
const string gE = "E | Bearish OB Appearance"
const string gF = "F | Advanced"
 
// ---- Group A ----
enBull     = input.bool(true, "Show BULLISH Order Blocks (last UP candle before a DOWN move)", group = gA)
enBear     = input.bool(true, "Show BEARISH Order Blocks (last DOWN candle before an UP move)", group = gA)
valMode    = input.string("Standard", "Validation Mode", options = ["Basic", "Standard", "Strict", "Custom"], group = gA, tooltip = "Basic: opposite candle + ATR displacement (most zones).\nStandard: Basic + displacement candle body strength.\nStrict: Standard + swing (market structure) break (fewest zones).\nCustom: uses the toggles in Group B.")
candleMode = input.string("Last Candle", "Candle Selection", options = ["Last Candle", "Full Cluster", "Most Relevant"], group = gA, tooltip = "Last Candle: the last opposite candle before the move.\nFull Cluster: all consecutive opposite candles (max 10) form one zone.\nMost Relevant: the opposite candle with the most extreme low / high inside the look-back window.")
boundMode  = input.string("Full Candle Range", "Zone Boundary Method", options = ["Full Candle Range", "Candle Body"], group = gA, tooltip = "Full Candle Range: high to low of the selected candle(s).\nCandle Body: open/close extremes only.")
maxTotal   = input.int(10, "Maximum Active Order Blocks (Total)", minval = 1, maxval = 50, group = gA)
maxSide    = input.int(10, "Maximum Active Per Type", minval = 1, maxval = 50, group = gA, tooltip = "Separate cap for bullish and for bearish zones. The total cap above is always respected as well.")
retention  = input.string("Remove Oldest", "Retention Policy (when limit is reached)", options = ["Remove Oldest", "Remove Weakest"], group = gA)
dupMode    = input.string("Keep Stronger", "Overlapping Same-Type Zones", options = ["Keep Newest", "Keep Stronger", "Keep Both"], group = gA, tooltip = "Applies only to zones of the same type. Bullish and bearish zones may overlap freely.")
dupThr     = input.float(60.0, "Overlap Threshold (%)", minval = 1.0, maxval = 100.0, step = 5.0, group = gA, tooltip = "Overlap is measured against the smaller of the two zones.")
showHist   = input.bool(false, "Show Mitigated / Invalidated / Expired History", group = gA, tooltip = "When ON, removed zones stay on the chart in a faded dashed style and stop at the bar where they ended.")
maxHist    = input.int(15, "Maximum History Zones", minval = 1, maxval = 100, group = gA)
 
// ---- Group B ----
atrLen    = input.int(14, "ATR Period", minval = 1, group = gB)
dispATR   = input.float(0.5, "Minimum Displacement (ATR multiples)", minval = 0.1, step = 0.1, group = gB, tooltip = "Distance between the zone edge and the close of the confirming candle, measured in ATR. Lower = more zones, higher = only violent moves.")
minBody   = input.int(50, "Minimum Candle Body (% of range)", minval = 1, maxval = 100, group = gB)
minRun    = input.int(1, "Minimum Directional Displacement Candles", minval = 1, maxval = 5, group = gB, tooltip = "1 = one strong candle is enough. Higher values require consecutive directional candles ending on the confirmation bar.")
lookback  = input.int(10, "Candle Search Look-Back (bars)", minval = 2, maxval = 50, group = gB)
swLen     = input.int(5, "Swing Detection Length", minval = 1, maxval = 30, group = gB)
cAtr      = input.bool(true, "Custom: Require ATR Displacement", group = gB)
cBody     = input.bool(true, "Custom: Require Candle Body Strength", group = gB)
cStruct   = input.bool(false, "Custom: Require Market Structure Break", group = gB)
cRej      = input.bool(false, "Custom: Enable Rejection (Wick) Filter", group = gB)
rejPct    = input.float(25.0, "Rejection Wick Minimum (% of origin candle range)", minval = 1.0, maxval = 90.0, group = gB, tooltip = "Zones below the move need a lower wick on the origin candle, zones above the move an upper wick.")
 
// ---- Group C ----
mitModeBull = input.string("Wick Touch", "Mitigation Mode - BULLISH Order Blocks", options = ["Wick Touch", "Candle Body Entry", "Full Mitigation", "Close Beyond Boundary", "Wick Beyond Boundary"], group = gC, tooltip = "Same modes as the BEARISH setting below (see its description).")
mitModeBear = input.string("Close Beyond Boundary", "Mitigation Mode - BEARISH Order Blocks", options = ["Wick Touch", "Candle Body Entry", "Full Mitigation", "Close Beyond Boundary", "Wick Beyond Boundary"], group = gC, tooltip = "Wick Touch: removed on first wick touch (only untouched, pending zones stay).\nCandle Body Entry: removed when a candle body enters the zone by the % below.\nFull Mitigation: removed when price traverses the % below of the zone (100% = whole zone).\nClose Beyond Boundary: removed when a candle CLOSES beyond the far boundary.\nWick Beyond Boundary: removed when price WICKS beyond the far boundary.")
bodyPct = input.float(30.0, "Candle Body Entry Depth (% of zone)", minval = 1.0, maxval = 100.0, step = 5.0, group = gC)
mitPct  = input.float(100.0, "Full Mitigation Traversal (% of zone)", minval = 1.0, maxval = 100.0, step = 5.0, group = gC)
useAge  = input.bool(false, "Expire Zones By Age", group = gC)
maxAge  = input.int(500, "Maximum Zone Age (bars since confirmation)", minval = 1, group = gC)
 
// ---- Group D (Bullish OB) ----
bullFillIn = input.color(#7f9e99, "Bullish Fill Color", group = gD)
bullTr     = input.int(45, "Bullish Fill Transparency (%)", minval = 0, maxval = 100, group = gD)
bullBorder = input.color(#2962FF, "Bullish Border Color", group = gD)
bullTxt    = input.string("BULLISH ORDER BLOCK", "Bullish Label Text", group = gD)
bullTxtCol = input.color(color.black, "Bullish Label Color", group = gD)
bullSize   = input.string(size.small, "Bullish Label Size", options = [size.tiny, size.small, size.normal], group = gD)
 
// ---- Group E (Bearish OB) ----
bearFillIn = input.color(#8a9b9d, "Bearish Fill Color", group = gE)
bearTr     = input.int(45, "Bearish Fill Transparency (%)", minval = 0, maxval = 100, group = gE)
bearBorder = input.color(#2962FF, "Bearish Border Color", group = gE)
bearTxt    = input.string("BEARISH ORDER BLOCK", "Bearish Label Text", group = gE)
bearTxtCol = input.color(color.black, "Bearish Label Color", group = gE)
bearSize   = input.string(size.small, "Bearish Label Size", options = [size.tiny, size.small, size.normal], group = gE)
 
// ---- Group F ----
boldTxt    = input.bool(true, "Bold Order Block Label Text", group = gF)
showStr    = input.bool(false, "Show Displacement Strength (ATR) In Label", group = gF)
showOrigin = input.bool(false, "Show Zone Origin Markers", group = gF)
showConf   = input.bool(false, "Show Confirmation Markers", group = gF)
extFuture  = input.int(10, "Extend Zone Into Future (bars)", minval = 0, maxval = 100, group = gF)
minW       = input.int(20, "Minimum Zone Width (bars, for label readability)", minval = 1, maxval = 100, group = gF)
histCol    = input.color(color.gray, "History Zone Color", group = gF)
debugOn    = input.bool(false, "Debug Mode", group = gF)
 
// =====================================================================================================
//  DERIVED SETTINGS
// =====================================================================================================
color bullFill = color.new(bullFillIn, bullTr)
color bearFill = color.new(bearFillIn, bearTr)
 
bool fAtr    = valMode != "Custom" or cAtr
bool fBody   = valMode == "Standard" or valMode == "Strict" or (valMode == "Custom" and cBody)
bool fStruct = valMode == "Strict" or (valMode == "Custom" and cStruct)
bool fRej    = valMode == "Custom" and cRej
 
int warmBars = lookback + 12 + math.max(atrLen, 2 * swLen)
 
// =====================================================================================================
//  TYPES
//  up = true  : displacement was UP   -> origin is a DOWN candle -> BEARISH order block (zone below move)
//  up = false : displacement was DOWN -> origin is an UP candle   -> BULLISH order block (zone above move)
// =====================================================================================================
type OB
    bool   up
    float  top
    float  bot
    int    leftBar
    int    originBar
    int    confBar
    int    originTime
    int    confTime
    int    endBar
    float  strength
    int    state
    string baseTxt
    box    bx
    label  lblO
    label  lblC
 
// =====================================================================================================
//  SERIES CALCULATIONS (global scope, executed on every bar)
// =====================================================================================================
float atrV = ta.atr(atrLen)
float phV  = ta.pivothigh(high, swLen, swLen)
float plV  = ta.pivotlow(low, swLen, swLen)
 
var float lastSH = na
var float lastSL = na
if not na(phV)
    lastSH := phV
if not na(plV)
    lastSL := plV
 
// =====================================================================================================
//  PERSISTENT STATE
// =====================================================================================================
var array<OB>  obs         = array.new<OB>()
var array<OB>  hist        = array.new<OB>()
var array<int> usedOrigins = array.new<int>()
var int        createdCnt  = 0
var array<int> stats       = array.new<int>(4, 0)   // 0 created bullish, 1 created bearish, 2 removed bullish, 3 removed bearish
var label      dbgLbl      = na
 
// =====================================================================================================
//  HELPER FUNCTIONS
// =====================================================================================================
bodyRatio(int k) =>
    float rng = high[k] - low[k]
    rng > 0 ? math.abs(close[k] - open[k]) / rng : 0.0
 
// dir = 1 : displacement UP (directional candle = bullish). dir = -1 : displacement DOWN.
isDirC(int k, int dir) =>
    dir == 1 ? close[k] > open[k] : close[k] < open[k]
 
// Opposite (origin) candle: DOWN candle before an UP move, UP candle before a DOWN move.
isOppC(int k, int dir) =>
    dir == 1 ? close[k] < open[k] : close[k] > open[k]
 
overlapPct(float t1, float b1, float t2, float b2) =>
    float ov = math.min(t1, t2) - math.max(b1, b2)
    float smaller = math.min(t1 - b1, t2 - b2)
    ov > 0 and smaller > 0 ? ov / smaller * 100.0 : 0.0
 
deleteVisuals(OB o) =>
    if not na(o.bx)
        box.delete(o.bx)
    if not na(o.lblO)
        label.delete(o.lblO)
    if not na(o.lblC)
        label.delete(o.lblC)
 
// Moves a zone out of the active list. Either deletes it or keeps it as a faded historical zone.
retire(array<OB> list, array<OB> hlist, int idx, int newState) =>
    OB o = list.get(idx)
    list.remove(idx)
    int sIdx = o.up ? 3 : 2
    stats.set(sIdx, stats.get(sIdx) + 1)
    if showHist
        o.state  := newState
        o.endBar := bar_index
        string tag = newState == ST_MITIGATED ? " (MITIGATED)" : newState == ST_INVALIDATED ? " (INVALIDATED)" : " (EXPIRED)"
        box.set_right(o.bx, bar_index)
        box.set_bgcolor(o.bx, color.new(histCol, 88))
        box.set_border_color(o.bx, color.new(histCol, 40))
        box.set_border_style(o.bx, line.style_dashed)
        box.set_text(o.bx, o.baseTxt + tag)
        box.set_text_color(o.bx, color.new(histCol, 20))
        if not na(o.lblO)
            label.delete(o.lblO)
        if not na(o.lblC)
            label.delete(o.lblC)
        hlist.push(o)
        while hlist.size() > maxHist
            OB old = hlist.shift()
            deleteVisuals(old)
    else
        deleteVisuals(o)
 
// Evaluates one active zone on the current confirmed bar. Returns 0 (still valid) or the new state.
// 'below' = zone sits below the move (price returns from above) = BEARISH order block.
// '!below' = zone sits above the move (price returns from below) = BULLISH order block.
evalZone(OB o) =>
    int ns = 0
    float h = o.top - o.bot
    string mm = o.up ? mitModeBear : mitModeBull
    bool below = o.up
    bool trig = false
    if mm == "Wick Touch"
        trig := below ? low <= o.top : high >= o.bot
    else if mm == "Candle Body Entry"
        float pen = below ? o.top - math.min(open, close) : math.max(open, close) - o.bot
        trig := pen > 0 and pen >= bodyPct / 100.0 * h
    else if mm == "Full Mitigation"
        float pen2 = below ? o.top - low : high - o.bot
        trig := pen2 > 0 and pen2 >= mitPct / 100.0 * h
    else if mm == "Close Beyond Boundary"
        trig := below ? close < o.bot : close > o.top
    else
        trig := below ? low < o.bot : high > o.top
    if trig
        // Invalidation has priority: a bar that closes beyond the far boundary is always "invalidated".
        bool brokeClose = below ? close < o.bot : close > o.top
        bool invMode = mm == "Close Beyond Boundary" or mm == "Wick Beyond Boundary"
        ns := (invMode or brokeClose) ? ST_INVALIDATED : ST_MITIGATED
    else if useAge and (bar_index - o.confBar) >= maxAge
        ns := ST_EXPIRED
    ns
 
// Updates every active zone (iterates backwards so removals never skip elements).
updateZones(array<OB> list, array<OB> hlist) =>
    int i = list.size() - 1
    while i >= 0
        OB o = list.get(i)
        int ns = evalZone(o)
        if ns != 0
            retire(list, hlist, i, ns)
        else if o.state == ST_CONFIRMED
            o.state := ST_PENDING
        i -= 1
 
// dirF: 1 = BEARISH order blocks (up move), -1 = BULLISH order blocks (down move), 0 = all.
countDir(array<OB> list, int dirF) =>
    int c = 0
    int i = 0
    while i < list.size()
        OB o = list.get(i)
        if dirF == 0 or (dirF == 1 and o.up) or (dirF == -1 and not o.up)
            c += 1
        i += 1
    c
 
// Picks the zone to drop when a cap is exceeded. The newest zone (last element) is never selected.
pickVictim(array<OB> list, int dirF) =>
    int idx = -1
    float best = na
    int i = 0
    while i < list.size() - 1
        OB o = list.get(i)
        bool m = dirF == 0 or (dirF == 1 and o.up) or (dirF == -1 and not o.up)
        if m
            if retention == "Remove Oldest"
                idx := i
                break
            else if na(best) or o.strength < best
                best := o.strength
                idx := i
        i += 1
    idx
 
enforceCaps(array<OB> list) =>
    int idx = 0
    while countDir(list, 1) > maxSide and idx >= 0
        idx := pickVictim(list, 1)
        if idx >= 0
            OB v = list.get(idx)
            list.remove(idx)
            deleteVisuals(v)
    idx := 0
    while countDir(list, -1) > maxSide and idx >= 0
        idx := pickVictim(list, -1)
        if idx >= 0
            OB v2 = list.get(idx)
            list.remove(idx)
            deleteVisuals(v2)
    idx := 0
    while list.size() > maxTotal and idx >= 0
        idx := pickVictim(list, 0)
        if idx >= 0
            OB v3 = list.get(idx)
            list.remove(idx)
            deleteVisuals(v3)
 
// =====================================================================================================
//  DETECTION ENGINE
//  dir = 1  : UP move   -> origin = last DOWN candle  -> BEARISH order block
//  dir = -1 : DOWN move -> origin = last UP candle    -> BULLISH order block
//  Runs only on confirmed bars. Offset 0 is the confirmation bar (current closed bar).
// =====================================================================================================
detectOB(int dir, array<OB> list, array<int> used) =>
    bool created = false
    if not na(atrV) and bar_index > warmBars
 
        // 1) Displacement run: consecutive directional candles ending on the current bar
        int run = 0
        for k = 0 to 5
            bool okC = isDirC(k, dir) and (not fBody or bodyRatio(k) >= minBody / 100.0)
            if okC
                run += 1
            else
                break
 
        if run >= minRun
 
            // 2) Origin candle search (strictly BEFORE the displacement run)
            int jEnd = run + lookback - 1
            int jSel = -1
            if candleMode == "Most Relevant"
                float bestV = na
                for j = run to jEnd
                    if isOppC(j, dir)
                        float v = dir == 1 ? low[j] : high[j]
                        if na(bestV) or (dir == 1 ? v < bestV : v > bestV)
                            bestV := v
                            jSel := j
            else
                for j = run to jEnd
                    if isOppC(j, dir)
                        jSel := j
                        break
 
            if jSel >= 0
 
                // 3) Optional cluster expansion (older consecutive opposite candles, max 10 total)
                int jFirst = jSel
                if candleMode == "Full Cluster"
                    for c = 1 to 9
                        if isOppC(jSel + c, dir)
                            jFirst := jSel + c
                        else
                            break
 
                // 4) Zone boundaries
                float zTop = na
                float zBot = na
                for j = jSel to jFirst
                    float t = boundMode == "Candle Body" ? math.max(open[j], close[j]) : high[j]
                    float b = boundMode == "Candle Body" ? math.min(open[j], close[j]) : low[j]
                    zTop := na(zTop) ? t : math.max(zTop, t)
                    zBot := na(zBot) ? b : math.min(zBot, b)
 
                bool ok = zTop > zBot
 
                // 5) Displacement measured from the zone edge to the confirming close
                float move = dir == 1 ? close - zTop : zBot - close
                float strength = move / atrV
                if ok and move <= 0
                    ok := false
                if ok and fAtr and strength < dispATR
                    ok := false
 
                // 6) Optional market-structure confirmation (swing break)
                if ok and fStruct
                    if dir == 1
                        ok := not na(lastSH) and close > lastSH and close[run] <= lastSH
                    else
                        ok := not na(lastSL) and close < lastSL and close[run] >= lastSL
 
                // 7) Optional rejection (wick) filter on the origin candle
                if ok and fRej
                    float rng = high[jSel] - low[jSel]
                    float wick = dir == 1 ? math.min(open[jSel], close[jSel]) - low[jSel] : high[jSel] - math.max(open[jSel], close[jSel])
                    if rng <= 0 or wick / rng * 100.0 < rejPct
                        ok := false
 
                // 8) Zone must not already be broken between its origin and the confirmation bar
                if ok
                    for j = 0 to jSel - 1
                        bool brk = dir == 1 ? close[j] < zBot : close[j] > zTop
                        if brk
                            ok := false
                            break
 
                // 9) Never re-create a zone from the same origin candle
                int originBar = bar_index - jSel
                int key = originBar * 2 + (dir == 1 ? 1 : 0)
                if ok and used.includes(key)
                    ok := false
 
                // 10) Duplicate / overlap handling (same type only)
                if ok and dupMode != "Keep Both"
                    int i = 0
                    while i < list.size()
                        OB e = list.get(i)
                        if e.up == (dir == 1) and overlapPct(zTop, zBot, e.top, e.bot) >= dupThr
                            if dupMode == "Keep Stronger" and e.strength >= strength
                                ok := false
                        i += 1
                    if ok
                        i := list.size() - 1
                        while i >= 0
                            OB e2 = list.get(i)
                            if e2.up == (dir == 1) and overlapPct(zTop, zBot, e2.top, e2.bot) >= dupThr
                                list.remove(i)
                                deleteVisuals(e2)
                            i -= 1
 
                // 11) Create the zone (confirmed on this bar, drawn at its historical origin)
                if ok
                    bool isBullOB = dir == -1
                    string baseText = isBullOB ? bullTxt : bearTxt
                    string fullText = showStr ? baseText + " | " + str.tostring(strength, "#.0") + " ATR" : baseText
                    int leftBar = bar_index - jFirst
                    box bx = box.new(left = leftBar, top = zTop, right = math.max(bar_index + extFuture, leftBar + minW), bottom = zBot, border_color = isBullOB ? bullBorder : bearBorder, border_width = 1, xloc = xloc.bar_index, bgcolor = isBullOB ? bullFill : bearFill, text = fullText, text_size = isBullOB ? bullSize : bearSize, text_color = isBullOB ? bullTxtCol : bearTxtCol, text_halign = text.align_center, text_valign = text.align_center, text_wrap = text.wrap_auto, text_formatting = boldTxt ? text.format_bold : text.format_none)
 
                    label mkO = na
                    label mkC = na
                    if showOrigin
                        mkO := label.new(x = originBar, y = dir == 1 ? low[jSel] : high[jSel], text = "O", xloc = xloc.bar_index, yloc = yloc.price, color = isBullOB ? bullBorder : bearBorder, style = dir == 1 ? label.style_label_up : label.style_label_down, textcolor = color.white, size = size.tiny)
                    if showConf
                        mkC := label.new(x = bar_index, y = dir == 1 ? low : high, text = "C", xloc = xloc.bar_index, yloc = yloc.price, color = isBullOB ? bullBorder : bearBorder, style = dir == 1 ? label.style_label_up : label.style_label_down, textcolor = color.white, size = size.tiny)
 
                    OB nz = OB.new(up = dir == 1, top = zTop, bot = zBot, leftBar = leftBar, originBar = originBar, confBar = bar_index, originTime = time[jSel], confTime = time, endBar = na, strength = strength, state = ST_CONFIRMED, baseTxt = fullText, bx = bx, lblO = mkO, lblC = mkC)
                    list.push(nz)
                    used.push(key)
                    while used.size() > 300
                        used.shift()
                    enforceCaps(list)
                    int cIdx = dir == 1 ? 1 : 0
                    stats.set(cIdx, stats.get(cIdx) + 1)
                    created := true
    created
 
// =====================================================================================================
//  MAIN LOGIC (confirmed bars only)
// =====================================================================================================
if barstate.isconfirmed
    // Lifecycle first: zones created on earlier bars are checked from the bar AFTER their confirmation.
    updateZones(obs, hist)
    // UP move  -> last DOWN candle -> BEARISH order block
    if enBear
        if detectOB(1, obs, usedOrigins)
            createdCnt += 1
    // DOWN move -> last UP candle -> BULLISH order block
    if enBull
        if detectOB(-1, obs, usedOrigins)
            createdCnt += 1
 
// Keep active zones extended to the right edge of the chart.
if barstate.islast
    int n = obs.size()
    int q = 0
    while q < n
        OB z = obs.get(q)
        box.set_right(z.bx, math.max(bar_index + extFuture, z.leftBar + minW))
        q += 1
 
// Optional debug read-out
if debugOn and barstate.islast
    string dbg = "IOB Levels debug\nActive bullish OB: " + str.tostring(countDir(obs, -1)) + "\nActive bearish OB: " + str.tostring(countDir(obs, 1)) + "\nCreated bullish/bearish: " + str.tostring(stats.get(0)) + "/" + str.tostring(stats.get(1)) + "\nRemoved bullish/bearish: " + str.tostring(stats.get(2)) + "/" + str.tostring(stats.get(3)) + "\nHistory: " + str.tostring(hist.size()) + "\nCreated total: " + str.tostring(createdCnt) + "\nATR: " + str.tostring(atrV, format.mintick)
    if na(dbgLbl)
        dbgLbl := label.new(bar_index, high, dbg, style = label.style_label_down, color = color.new(color.gray, 20), textcolor = color.white, size = size.small)
    else
        label.set_xy(dbgLbl, bar_index, high)
        label.set_text(dbgLbl, dbg)

← 返回列表