ZoneLens - Order Blocks, Fair Value Gaps and Market Structure

preuss_steffen · study · 863 行 · 点赞 178 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © preuss_steffen
//@version=6
// ZoneLens — OB+/OB−, FVG+/FVG− from an own zone engine; BOS, ChoCH and EMA Fast/Slow as in "SkippALGO Mid";
// bar color, background and lines from an own trend channel (classic Keltner channel). Built with the build script.
// OB/FVG zones: own code without libraries; order blocks anchored to this script's structure breaks.
indicator("ZoneLens", overlay=true, max_bars_back=500, max_labels_count=500, max_lines_count=500, max_boxes_count=500)
 
 
// ════════ Display ════════
var string zgShow = "Display"
zShowObBull  = input.bool(true, "OB+ (bullish order blocks)", group=zgShow)
zShowObBear  = input.bool(true, "OB− (bearish order blocks)", group=zgShow)
zShowFvgBull = input.bool(true, "FVG+ (bullish fair value gaps)", group=zgShow)
zShowFvgBear = input.bool(true, "FVG− (bearish fair value gaps)", group=zgShow)
zShowBos     = input.bool(true, "BOS", group=zgShow)
zShowChoch   = input.bool(true, "ChoCH", group=zgShow)
zShowEmaFast = input.bool(true, "EMA Fast", group=zgShow)
zShowEmaSlow = input.bool(true, "EMA Slow", group=zgShow)
zShowBg      = input.bool(true, "Background by trend", group=zgShow)
zShowBarCol  = input.bool(true, "Color bars by trend", group=zgShow)
zShowKc      = input.bool(true, "Trend channel (midline and bands)", group=zgShow)
 
// ════════ Trend channel: classic Keltner channel ════════
// Midline = SMA of the typical price (H+L+C)/3, bands = midline ± factor × ATR of the same length (Chester Keltner 1960,
// bands later with ATR instead of trading range). Trend state with memory: up after a close above the upper band,
// down after a close below the lower band, otherwise unchanged; neutral (no color) before the first change.
var string zgKc = "Trend channel (Keltner)"
zKcLength = input.int(20, "Length", minval=2, group=zgKc, tooltip="Length of the SMA of the typical price and of the ATR.")
zKcMult   = input.float(2.0, "ATR factor", minval=0.1, step=0.1, group=zgKc, tooltip="Band distance in ATR. Larger = fewer trend changes.")
zUpColor   = input.color(#169c86, "Up color", group=zgKc)
zDownColor = input.color(#e0532c, "Down color", group=zgKc)
zBgTransp  = input.int(96, "Background transparency", minval=0, maxval=100, group=zgKc)
 
// ════════ Market structure (BOS/ChoCH) and EMA from "SkippALGO Mid" (rev8, verbatim excerpt) ════════
var string zgStruct = "Market structure (BOS / ChoCH)"
var string zgEma = "EMA"
swingL = input.int(5, "Breakout swing left (L)", minval=1, maxval=20, group=zgStruct)
swingR = input.int(3, "Breakout swing right (R)", minval=1, maxval=20, tooltip="Lower 'R' values detect new structure levels faster.", group=zgStruct)
swingMaxAgeBars = input.int(0, "Breakout swing max age (bars)", minval=0, maxval=2000, tooltip="0 disables expiry of old swings", group=zgStruct)
breakoutSource = input.string("Close", "Breakout Source", options=["Close", "Wick"], tooltip="Determines if a breakout requires a candle Close or just a Wick cross.", group=zgStruct)
chochScalpPreset = input.bool(false, "ChoCH Scalp Fast preset", tooltip="Preset values: breakoutSource=Wick, chochSignalMode=Ping (Fast), swingREff=max(swingR,1). Note: if Fast+Safer is also enabled, Fast+Safer takes precedence.", group=zgStruct)
chochScalpSaferPreset = input.bool(false, "ChoCH Fast+Safer preset", tooltip="Preset values: breakoutSource=Wick, chochSignalMode=Ping+Verify, swingREff=max(swingR,1). Safer than Fast due to additional verify confirmation.", group=zgStruct)
chochSignalMode  = input.string("Ping+Verify", "ChoCH signal mode", options=["Ping (Fast)", "Verify (Safer)", "Ping+Verify"], tooltip="Manual mode selector when no ChoCH preset is active. Preset override: Fast => Ping (Fast), Fast+Safer => Ping+Verify.", group=zgStruct)
emaFastLen = input.int(21, "EMA fast", minval=1, group=zgEma)
emaSlowLen = input.int(55, "EMA slow", minval=1, group=zgEma)
bool chochFastPresetEff = chochScalpPreset and not chochScalpSaferPreset
bool chochSaferPresetEff = chochScalpSaferPreset
int swingREff = (chochFastPresetEff or chochSaferPresetEff) ? math.max(1, swingR) : swingR
string breakoutSourceEff = (chochFastPresetEff or chochSaferPresetEff) ? "Wick" : breakoutSource
string chochSignalModeEff = chochFastPresetEff ? "Ping (Fast)" : chochSaferPresetEff ? "Ping+Verify" : chochSignalMode
emaF = ta.ema(close, emaFastLen)
emaS = ta.ema(close, emaSlowLen)
// Breakout levels
var float lastSwingHigh = na
var float lastSwingLow  = na
var int lastSwingHighBar = na
var int lastSwingLowBar  = na
ph = ta.pivothigh(high, swingL, swingREff)
pl = ta.pivotlow(low,  swingL, swingREff)
prevSwingHigh = lastSwingHigh
prevSwingLow = lastSwingLow
if not na(ph)
    lastSwingHigh := ph
    lastSwingHighBar := bar_index
if not na(pl)
    lastSwingLow := pl
    lastSwingLowBar := bar_index
if swingMaxAgeBars > 0
    if not na(lastSwingHighBar) and (bar_index - lastSwingHighBar > swingMaxAgeBars)
        lastSwingHigh := na
        lastSwingHighBar := na
    if not na(lastSwingLowBar) and (bar_index - lastSwingLowBar > swingMaxAgeBars)
        lastSwingLow := na
        lastSwingLowBar := na
 
// Breakout Logic (Close vs Wick)
bool breakHigh = false
bool breakLow  = false
 
bool _xoWick = ta.crossover(high, lastSwingHigh)
bool _xuWick = ta.crossunder(low, lastSwingLow)
 
if breakoutSourceEff == "Close"
    breakHigh := (not na(lastSwingHigh)) and (not na(prevSwingHigh)) and close > lastSwingHigh and close[1] <= lastSwingHigh[1]
    breakLow  := (not na(lastSwingLow)) and (not na(prevSwingLow)) and close < lastSwingLow  and close[1] >= lastSwingLow[1]
else // Wick
    if not na(lastSwingHigh)
        breakHigh := _xoWick
    if not na(lastSwingLow)
        breakLow  := _xuWick
 
breakoutLong  = not na(lastSwingHigh) and breakHigh
breakoutShort = not na(lastSwingLow)  and breakLow
 
// --- Market Structure State (BOS vs ChoCH) ---
var int structState = 0 // 0=Neutral, 1=Bullish, -1=Bearish
bool isChoCH_Long = false
bool isBOS_Long   = false
bool isChoCH_Short = false
bool isBOS_Short   = false
bool chochPingLong = false
bool chochPingShort = false
bool chochVerifyLong = false
bool chochVerifyShort = false
 
// Standard trend logic: break of the last swing high/low; against the current structure = ChoCH, otherwise BOS
if breakoutLong
    chochPingLong := structState == -1
    if not chochPingLong
        isBOS_Long := true
    structState := 1
 
if breakoutShort
    chochPingShort := structState == 1
    if not chochPingShort
        isBOS_Short := true
    structState := -1
 
var float chochPingHighLevel = na
var float chochPingLowLevel = na
if chochPingLong
    chochPingHighLevel := lastSwingHigh
if chochPingShort
    chochPingLowLevel := lastSwingLow
// Fix: use [1] so a same-bar ping doesn't overwrite the verify level before the check runs
chochVerifyLong := chochPingLong[1] and (not na(chochPingHighLevel[1]) and close > chochPingHighLevel[1])
chochVerifyShort := chochPingShort[1] and (not na(chochPingLowLevel[1]) and close < chochPingLowLevel[1])
isChoCH_Long := chochSignalModeEff == "Ping (Fast)" ? chochPingLong : chochSignalModeEff == "Verify (Safer)" ? chochVerifyLong : (chochPingLong or chochVerifyLong)
isChoCH_Short := chochSignalModeEff == "Ping (Fast)" ? chochPingShort : chochSignalModeEff == "Verify (Safer)" ? chochVerifyShort : (chochPingShort or chochVerifyShort)
// ZoneLens (public version): labels without Mid's REV-BUY/REV-SHORT suppression (that needs Mid's signal engine)
labelChoCH_L = isChoCH_Long
labelChoCH_S = isChoCH_Short
labelBOS_L = isBOS_Long
labelBOS_S = isBOS_Short
 
// ════════ Zones: order blocks and fair value gaps (own implementation, 2026-10) ════════
// Order blocks: own design, anchored to the structure breaks shown by this script (last opposite candle before the push
// that broke the swing). Fair value gaps: clean-room implementation written from a behaviour specification.
const int Z_ATR_LEN_MAIN = 50
const int Z_DEFAULT_OB_SHOW_LAST = 2
const int Z_DEFAULT_FVG_SHOW_LAST = 2
const int Z_DEFAULT_KEEP_HISTORY = 1
const float Z_DEFAULT_OB_FILTER_MIN_MULT = 0.2
const float Z_DEFAULT_OB_FILTER_MAX_MULT = 3.0
const float Z_DEFAULT_FVG_MIN_SIZE_MULT = 0.5
const float Z_DEFAULT_FVG_FILL_TARGET_PCT = 60.0
 
enum ZSignalMode
    CONFIRMED_ONLY = 'Confirmed only'
    AGGRESSIVE_LIVE = 'Aggressive live'
 
var string zgCalc = "OB / FVG – calculation"
var ZSignalMode zSignalMode = input.enum(ZSignalMode.CONFIRMED_ONLY, "Signal Mode", group=zgCalc, tooltip="Confirmed only: zones break and gaps fill on bar closes. Aggressive live: on highs/lows, also within the forming bar.")
var bool zRenderVisibleOnly = input.bool(true, "Render visible range only", group=zgCalc)
 
var string zgOb = "Order blocks"
var zBullObCss = input.color(color.new(#169c86, 74), "OB+", group=zgOb, inline="obbull")
var zBullObCssLine = input.color(color.new(#169c86, 5), "", group=zgOb, inline="obbull")
var zBearObCss = input.color(color.new(#e0532c, 74), "OB−", group=zgOb, inline="obbear")
var zBearObCssLine = input.color(color.new(#e0532c, 5), "", group=zgOb, inline="obbear")
var zObShowLast = input.int(Z_DEFAULT_OB_SHOW_LAST, "Zones shown per side", minval=1, group=zgOb)
var string zObEdges = input.string("Wick", "Zone edges", options=["Wick", "Body"], group=zgOb, tooltip="Wick: high to low of the order block candle. Body: open to close.")
var int zObDepth = input.int(10, "Search depth (bars)", minval=1, maxval=50, group=zgOb, tooltip="How far back from the break the last opposite candle is searched.")
var zObFilterMinMult = input.float(Z_DEFAULT_OB_FILTER_MIN_MULT, "Min size × ATR(50)", minval=0, step=0.1, group=zgOb, inline="obf")
var zObFilterMaxMult = input.float(Z_DEFAULT_OB_FILTER_MAX_MULT, "max", minval=0.1, step=0.1, group=zgOb, inline="obf")
var zObExtendUntilBroken = input.bool(true, "Extend right until broken", group=zgOb)
var zObKeepBroken = input.bool(true, "Show broken zones", group=zgOb, inline="obkb")
var zObKeepBrokenMax = input.int(Z_DEFAULT_KEEP_HISTORY, "", minval=0, group=zgOb, inline="obkb")
var zObCssBroken = input.color(color.new(#787b86, 88), "", group=zgOb, inline="obkb")
var zObLineCssBroken = color.new(zObCssBroken, 50)
var bool zObMidline = input.bool(true, "Midline (50 %)", group=zgOb)
var bool zObFlip = input.bool(true, "Flip after a gap (FVG)", group=zgOb, tooltip="A zone that price breaks with a fair value gap (same minimum size as the FVG settings) becomes a zone of the opposite direction at the same price range, starting at the break.")
var bool zObHideTouched = input.bool(true, "Hide after first touch", group=zgOb, tooltip="A zone is no longer drawn once price has reached it (the edge seen from the side it was created on).")
var float zObAlertDist = input.float(0.0, "Touch alert distance × ATR(50)", minval=0, step=0.05, group=zgOb, tooltip="All \"touched\" alerts (order blocks, gaps, higher-timeframe zones) fire on the first bar that comes this close to a zone (0 = reaches it). 0.25 = already a quarter ATR before the zone.")
var string zObHtf = input.timeframe("", "Zones from higher timeframe", group=zgOb, tooltip="Empty = off. Shows the two newest active order blocks per side of this timeframe, computed on its bars with the same rules, values of its last completed bar (no repainting).")
 
var string zgFvg = "Fair value gaps"
var zBullFvgCss = input.color(color.new(#3d8bfd, 82), "FVG+", group=zgFvg, inline="fvgbull")
var zBullFvgLineCss = input.color(color.new(#3d8bfd, 5), "", group=zgFvg, inline="fvgbull")
var zBearFvgCss = input.color(color.new(#c8861e, 82), "FVG−", group=zgFvg, inline="fvgbear")
var zBearFvgLineCss = input.color(color.new(#c8861e, 5), "", group=zgFvg, inline="fvgbear")
var zFvgShowLast = input.int(Z_DEFAULT_FVG_SHOW_LAST, "Gaps shown per side", minval=1, group=zgFvg)
var zFvgExtendUntilFilled = input.bool(true, "Extend right until filled", group=zgFvg)
var zFvgKeepFilled = input.bool(true, "Show filled gaps", group=zgFvg, inline="fvgkf")
var zFvgKeepFilledMax = input.int(Z_DEFAULT_KEEP_HISTORY, "", minval=1, group=zgFvg, inline="fvgkf")
var zFvgCssFilled = input.color(color.new(#787b86, 85), "", group=zgFvg, inline="fvgkf")
var zFvgLineCssFilled = color.new(zFvgCssFilled, 50)
var zFilterInsignificantFvgs = input.bool(true, "Min gap size", group=zgFvg, inline="fvgmin")
var zMinFvgSizeAtrLen = input.int(Z_ATR_LEN_MAIN, "ATR length", minval=1, group=zgFvg, inline="fvgmin")
var zMinFvgSizeAtrMult = input.float(Z_DEFAULT_FVG_MIN_SIZE_MULT, "× ATR", minval=0, step=0.1, group=zgFvg, inline="fvgmin")
var float zFvgFillTargetPct = input.float(Z_DEFAULT_FVG_FILL_TARGET_PCT, "Filled at % of the gap", minval=0, maxval=100, step=5, group=zgFvg)
 
// Break / fill rule: true = decided on the bar close (confirmed bars only), false = on high/low, also intrabar
bool zBreakOnClose = zSignalMode == ZSignalMode.CONFIRMED_ONLY
int zVisibleLeftTime = zRenderVisibleOnly ? chart.left_visible_bar_time : na
int zVisibleRightTime = zRenderVisibleOnly ? chart.right_visible_bar_time : na
 
// ════════ IMPLEMENTATION ════════
 
// ---- Stable ATR: running mean of the true range until the ATR has its full length ----
znStableAtr(simple int n) =>
    float znAtrFull = ta.atr(n)
    float znTrSum = ta.cum(ta.tr(true))
    bar_index < n ? znTrSum / (bar_index + 1) : znAtrFull
 
float znAtr50 = znStableAtr(Z_ATR_LEN_MAIN)
float znAtrFvg = znStableAtr(zMinFvgSizeAtrLen)
float znFvgThreshold = zFilterInsignificantFvgs ? znAtrFvg * zMinFvgSizeAtrMult : 0.0
float znFillRatio = math.max(0.0, math.min(1.0, zFvgFillTargetPct / 100))
bool znBreakAllowed = zBreakOnClose ? barstate.isconfirmed : true
 
// ---- Order blocks: last opposite candle before the push that broke a swing (BOS or ChoCH of this script) ----
type ZnOb
    int dir
    int t1          // open time of the order block candle (flipped zones: open time of the flip bar)
    int tBreak      // close time of the bar that created the zone
    float top
    float bottom
    bool broken = false
    int brokenTime = na
    bool flipped = false   // created by a break with a gap (opposite direction of the broken zone)
    bool touched = false   // price reached the zone after it was created
    bool alerted = false   // touch alert already raised for this zone
 
// All order block state of one timeframe
type ZnObBook
    array<ZnOb> bull
    array<ZnOb> bear
    array<ZnOb> bullBroken
    array<ZnOb> bearBroken
 
const int ZN_OB_MEMORY = 100
 
znObBookNew() =>
    ZnObBook.new(array.new<ZnOb>(), array.new<ZnOb>(), array.new<ZnOb>(), array.new<ZnOb>())
 
// Bars back (1 = previous bar) to the most recent candle of the opposite colour, na if none within the depth
znOppositeCandle(int dir, int depth) =>
    int found = na
    for k = 1 to depth
        if dir == 1 ? close[k] < open[k] : close[k] > open[k]
            found := k
            break
    found
 
// First contact with zones that existed before this bar (distance in price).
// Returns [touch alert due for any zone, touch alert due for a flipped zone].
znObTouches(array<ZnOb> act, int dir, float alertDist) =>
    bool alert = false
    bool alertFlipped = false
    for o in act
        if not o.alerted and (dir == 1 ? low <= o.top + alertDist : high >= o.bottom - alertDist)
            o.alerted := true
            alert := true
            if o.flipped
                alertFlipped := true
        if not o.touched and (dir == 1 ? low <= o.top : high >= o.bottom)
            o.touched := true
    [alert, alertFlipped]
 
// A zone breaks when price closes (or trades, in aggressive mode) beyond its far edge. If the breaking bar leaves a
// fair value gap in the direction of the break, the zone is flipped: returned as a zone of the opposite direction.
znObBreaks(array<ZnOb> act, array<ZnOb> done, int dir, float fvgThr, bool closeRule, int keepBroken) =>
    float src = closeRule ? close : dir == 1 ? low : high
    bool gapWithBreak = dir == 1 ? low[2] - high > fvgThr : low - high[2] > fvgThr
    array<ZnOb> flips = array.new<ZnOb>()
    int n = array.size(act)
    if n > 0
        for i = n - 1 to 0
            ZnOb o = array.get(act, i)
            if dir == 1 ? src < o.bottom : src > o.top
                o.broken := true
                o.brokenTime := time_close
                array.remove(act, i)
                array.push(done, o)
                if zObFlip and barstate.isconfirmed and gapWithBreak
                    array.unshift(flips, ZnOb.new(-dir, time, time_close, o.top, o.bottom, flipped = true))
    while array.size(done) > keepBroken
        array.shift(done)
    flips
 
znObOverlapsAny(array<ZnOb> act, float top, float bottom) =>
    bool hit = false
    for z in act
        if z.bottom < top and z.top > bottom
            hit := true
            break
    hit
 
znObAddFlips(array<ZnOb> act, array<ZnOb> flips) =>
    for f in flips
        if not znObOverlapsAny(act, f.top, f.bottom)
            array.push(act, f)
            if array.size(act) > ZN_OB_MEMORY
                array.shift(act)
 
znObAdd(array<ZnOb> act, int dir, float atr) =>
    int k = znOppositeCandle(dir, zObDepth)
    if not na(k)
        float top = zObEdges == "Wick" ? high[k] : math.max(open[k], close[k])
        float bottom = zObEdges == "Wick" ? low[k] : math.min(open[k], close[k])
        float size = top - bottom
        bool sameCandle = array.size(act) > 0 and array.get(act, array.size(act) - 1).t1 == time[k]
        if not sameCandle and size >= zObFilterMinMult * atr and size <= zObFilterMaxMult * atr
            array.push(act, ZnOb.new(dir, time[k], time_close, top, bottom))
            if array.size(act) > ZN_OB_MEMORY
                array.shift(act)
 
// One bar of the order block engine: touches/alerts, breaks (with flips), then new zones from this bar's structure breaks.
// Returns [OB+ touch alert, OB− touch alert, flipped OB+ touch alert, flipped OB− touch alert].
znObStep(ZnObBook b, bool brkLong, bool brkShort, float atr, float fvgThr, float alertDist, bool allowed, bool closeRule, int keepBroken) =>
    bool bullAlert = false
    bool bearAlert = false
    bool bullFlipAlert = false
    bool bearFlipAlert = false
    if allowed
        [ba, bf] = znObTouches(b.bull, 1, alertDist)
        [sa, sf] = znObTouches(b.bear, -1, alertDist)
        bullAlert := ba
        bullFlipAlert := bf
        bearAlert := sa
        bearFlipAlert := sf
        array<ZnOb> toBear = znObBreaks(b.bull, b.bullBroken, 1, fvgThr, closeRule, keepBroken)
        array<ZnOb> toBull = znObBreaks(b.bear, b.bearBroken, -1, fvgThr, closeRule, keepBroken)
        znObAddFlips(b.bear, toBear)
        znObAddFlips(b.bull, toBull)
    if barstate.isconfirmed and brkLong
        znObAdd(b.bull, 1, atr)
    if barstate.isconfirmed and brkShort
        znObAdd(b.bear, -1, atr)
    [bullAlert, bearAlert, bullFlipAlert, bearFlipAlert]
 
var ZnObBook znBook = znObBookNew()
[znBullTouchAlert, znBearTouchAlert, znBullFlipTouchAlert, znBearFlipTouchAlert] = znObStep(znBook, breakoutLong, breakoutShort, znAtr50,
     znFvgThreshold, zObAlertDist * znAtr50, znBreakAllowed, zBreakOnClose, zObKeepBrokenMax)
 
// ---- Order blocks of a higher timeframe: the same engine, run on that timeframe's bars ----
// n-th newest active zone of a list (optionally skipping touched ones), na if there is none
znObPick(array<ZnOb> act, int nth, bool skipTouched) =>
    ZnOb found = na
    int seen = 0
    int n = array.size(act)
    if n > 0
        for i = n - 1 to 0
            ZnOb o = array.get(act, i)
            if not (skipTouched and o.touched)
                if seen == nth
                    found := o
                    break
                seen += 1
    found
 
znObVals(ZnOb o) =>
    float t = na
    float top = na
    float bottom = na
    float flipped = na
    if not na(o)
        t := o.t1
        top := o.top
        bottom := o.bottom
        flipped := o.flipped ? 1 : 0
    [t, top, bottom, flipped]
 
// Structure breaks with the settings of the structure section, computed on the bars of the requested timeframe
znHtfZones() =>
    var float hi = na
    var float lo = na
    var int hiBar = na
    var int loBar = na
    float sph = ta.pivothigh(high, swingL, swingREff)
    float spl = ta.pivotlow(low, swingL, swingREff)
    float prevHi = hi
    float prevLo = lo
    if not na(sph)
        hi := sph
        hiBar := bar_index
    if not na(spl)
        lo := spl
        loBar := bar_index
    if swingMaxAgeBars > 0
        if not na(hiBar) and bar_index - hiBar > swingMaxAgeBars
            hi := na
            hiBar := na
        if not na(loBar) and bar_index - loBar > swingMaxAgeBars
            lo := na
            loBar := na
    bool xoWick = ta.crossover(high, hi)
    bool xuWick = ta.crossunder(low, lo)
    bool brkL = breakoutSourceEff == "Close" ? (not na(hi) and not na(prevHi) and close > hi and close[1] <= hi[1]) : (not na(hi) and xoWick)
    bool brkS = breakoutSourceEff == "Close" ? (not na(lo) and not na(prevLo) and close < lo and close[1] >= lo[1]) : (not na(lo) and xuWick)
    float atr = znStableAtr(Z_ATR_LEN_MAIN)
    float fvgThr = zFilterInsignificantFvgs ? znStableAtr(zMinFvgSizeAtrLen) * zMinFvgSizeAtrMult : 0.0
    var ZnObBook bk = znObBookNew()
    znObStep(bk, brkL, brkS, atr, fvgThr, 0.0, zBreakOnClose ? barstate.isconfirmed : true, zBreakOnClose, 0)
    ZnOb b1 = znObPick(bk.bull, 0, zObHideTouched)
    ZnOb b2 = znObPick(bk.bull, 1, zObHideTouched)
    ZnOb s1 = znObPick(bk.bear, 0, zObHideTouched)
    ZnOb s2 = znObPick(bk.bear, 1, zObHideTouched)
    [b1t, b1u, b1d, b1f] = znObVals(b1)
    [b2t, b2u, b2d, b2f] = znObVals(b2)
    [s1t, s1u, s1d, s1f] = znObVals(s1)
    [s2t, s2u, s2d, s2f] = znObVals(s2)
    // values of the last completed bar of that timeframe (no repainting with lookahead_on)
    [b1t[1], b1u[1], b1d[1], b1f[1], b2t[1], b2u[1], b2d[1], b2f[1], s1t[1], s1u[1], s1d[1], s1f[1], s2t[1], s2u[1], s2d[1], s2f[1]]
 
bool znHtfOn = zObHtf != "" and timeframe.in_seconds(zObHtf) > timeframe.in_seconds(timeframe.period)
var array<float> znHtf = array.new<float>(16, na)
if znHtfOn
    [h1t, h1u, h1d, h1f, h2t, h2u, h2d, h2f, l1t, l1u, l1d, l1f, l2t, l2u, l2d, l2f] =
         request.security(syminfo.tickerid, zObHtf, znHtfZones(), lookahead = barmerge.lookahead_on)
    znHtf := array.from(h1t, h1u, h1d, h1f, h2t, h2u, h2d, h2f, l1t, l1u, l1d, l1f, l2t, l2u, l2d, l2f)
 
// First contact of a chart bar with a shown higher-timeframe zone (slot i of znHtf); each zone alerts once
var array<string> znHtfAlerted = array.new<string>()
znHtfTouch(int i, int dir, float alertDist) =>
    bool hit = false
    float t = array.get(znHtf, i)
    if not na(t)
        float top = array.get(znHtf, i + 1)
        float bottom = array.get(znHtf, i + 2)
        string key = str.tostring(dir) + "|" + str.tostring(t) + "|" + str.tostring(top) + "|" + str.tostring(bottom)
        if not array.includes(znHtfAlerted, key) and (dir == 1 ? low <= top + alertDist : high >= bottom - alertDist)
            array.push(znHtfAlerted, key)
            if array.size(znHtfAlerted) > 50
                array.shift(znHtfAlerted)
            hit := true
    hit
 
bool znHtfBullTouchAlert = false
bool znHtfBearTouchAlert = false
if znHtfOn and znBreakAllowed
    float d = zObAlertDist * znAtr50
    bool b1 = znHtfTouch(0, 1, d)
    bool b2 = znHtfTouch(4, 1, d)
    bool s1 = znHtfTouch(8, -1, d)
    bool s2 = znHtfTouch(12, -1, d)
    znHtfBullTouchAlert := b1 or b2
    znHtfBearTouchAlert := s1 or s2
 
// ---- Fair value gap record ----
type ZnGap
    int dir
    int t1
    int i1
    int t2
    int i2
    float gTop
    float gBot
    float thr
    float target
    float level
    float share
    float vol
    bool filled = false
    int fillTime = na
    bool alerted = false   // touch alert already raised for this gap
 
// ---- Fair value gaps ----
var array<ZnGap> znBullGaps = array.new<ZnGap>()
var array<ZnGap> znBearGaps = array.new<ZnGap>()
var array<ZnGap> znBullFilled = array.new<ZnGap>()
var array<ZnGap> znBearFilled = array.new<ZnGap>()
 
// 1. Detection (confirmed bars only)
ZnGap znNewBullGap = na
ZnGap znNewBearGap = na
if barstate.isconfirmed
    float gt = low
    float gb = high[2]
    if gt - gb > znFvgThreshold
        znNewBullGap := ZnGap.new(1, time[2], bar_index[2], time_close, bar_index, gt, gb, znFvgThreshold, gt - znFillRatio * (gt - gb), gt, 0.0, volume[2] + volume[1] + volume)
    gt := low[2]
    gb := high
    if gt - gb > znFvgThreshold
        znNewBearGap := ZnGap.new(-1, time[2], bar_index[2], time_close, bar_index, gt, gb, znFvgThreshold, gb + znFillRatio * (gt - gb), gb, 0.0, volume[2] + volume[1] + volume)
 
// 2. Fill progress of open gaps
znGapUpdate(array<ZnGap> act, int dir, float src) =>
    for g in act
        if not g.filled
            if dir == 1
                if g.level > src
                    g.filled := src <= g.target
                    g.level := math.min(g.level, src)
                    g.share := (g.gTop - g.level) / math.max(g.gTop - g.gBot, syminfo.mintick)
                    if g.filled
                        g.fillTime := time_close
            else
                if g.level < src
                    g.filled := src >= g.target
                    g.level := math.max(g.level, src)
                    g.share := (g.level - g.gBot) / math.max(g.gTop - g.gBot, syminfo.mintick)
                    if g.filled
                        g.fillTime := time_close
 
// First contact with gaps that existed before this bar (FVG+: low reaches the top, FVG−: high reaches the bottom)
znGapTouches(array<ZnGap> act, int dir, float alertDist) =>
    bool alert = false
    for g in act
        if not g.filled and not g.alerted and (dir == 1 ? low <= g.gTop + alertDist : high >= g.gBot - alertDist)
            g.alerted := true
            alert := true
    alert
 
bool znFvgBullTouchAlert = false
bool znFvgBearTouchAlert = false
if znBreakAllowed
    znFvgBullTouchAlert := znGapTouches(znBullGaps, 1, zObAlertDist * znAtr50)
    znFvgBearTouchAlert := znGapTouches(znBearGaps, -1, zObAlertDist * znAtr50)
 
if znBreakAllowed
    znGapUpdate(znBullGaps, 1, zBreakOnClose ? close : low)
    znGapUpdate(znBearGaps, -1, zBreakOnClose ? close : high)
 
// 3. Move filled gaps (order kept) and trim the filled list
znGapMoveFilled(array<ZnGap> act, array<ZnGap> done) =>
    array<ZnGap> moved = array.new<ZnGap>()
    int n = array.size(act)
    if n > 0
        for i = n - 1 to 0
            if array.get(act, i).filled
                array.unshift(moved, array.remove(act, i))
    for g in moved
        array.push(done, g)
    while array.size(done) > zFvgKeepFilledMax
        array.shift(done)
 
znGapMoveFilled(znBullGaps, znBullFilled)
znGapMoveFilled(znBearGaps, znBearFilled)
 
// 4. (Clean-up of undersized gaps never applies: gaps are only created above their threshold.)
// 5. Append this bar's new gaps
if not na(znNewBullGap)
    array.push(znBullGaps, znNewBullGap)
if not na(znNewBearGap)
    array.push(znBearGaps, znNewBearGap)
 
// ---- Touch alerts (first contact per zone; see "Touch alert distance") ----
alertcondition(znBullTouchAlert, title="OB+ touched", message="ZoneLens OB+ touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znBearTouchAlert, title="OB− touched", message="ZoneLens OB- touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znFvgBullTouchAlert, title="FVG+ touched", message="ZoneLens FVG+ touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znFvgBearTouchAlert, title="FVG− touched", message="ZoneLens FVG- touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znBullTouchAlert or znFvgBullTouchAlert, title="OB+ or FVG+ touched", message="ZoneLens OB+ or FVG+ touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znBearTouchAlert or znFvgBearTouchAlert, title="OB− or FVG− touched", message="ZoneLens OB- or FVG- touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znHtfBullTouchAlert, title="OB+ higher timeframe touched", message="ZoneLens OB+ higher timeframe touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znHtfBearTouchAlert, title="OB− higher timeframe touched", message="ZoneLens OB- higher timeframe touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znBullFlipTouchAlert, title="OB+ FVG touched", message="ZoneLens OB+ FVG touched | {{ticker}} @ {{close}} | {{time}}")
alertcondition(znBearFlipTouchAlert, title="OB− FVG touched", message="ZoneLens OB- FVG touched | {{ticker}} @ {{close}} | {{time}}")
 
// ---- Rendering (last bar only; all drawings are rebuilt on every execution of it) ----
var array<box> znBoxes = array.new<box>()
var array<line> znLines = array.new<line>()
var array<label> znLabels = array.new<label>()
 
znClearDrawings() =>
    for b in znBoxes
        box.delete(b)
    for l in znLines
        line.delete(l)
    for lb in znLabels
        label.delete(lb)
    array.clear(znBoxes)
    array.clear(znLines)
    array.clear(znLabels)
 
int znNowRight = barstate.isrealtime ? math.min(time_close, timenow) : time_close
 
znEventTime(int t, int fallback) =>
    int base = nz(t, fallback)
    barstate.isrealtime ? math.min(base, znNowRight) : base
 
znIsVisible(int left, int right) =>
    na(zVisibleLeftTime) or na(zVisibleRightTime) or (right >= zVisibleLeftTime and left <= zVisibleRightTime)
 
znObRight(ZnOb o) =>
    zObExtendUntilBroken ? (o.broken ? znEventTime(o.brokenTime, o.tBreak) : znNowRight) : o.tBreak
 
znGapRight(ZnGap g) =>
    int base = math.max(g.t1, g.t2)
    int f = znEventTime(g.fillTime, base)
    zFvgExtendUntilFilled ? (g.filled ? f : znNowRight) : (g.filled ? math.min(f, base) : base)
 
znDrawOb(ZnOb o, bool isBroken) =>
    int right = znObRight(o)
    color lc = isBroken ? zObLineCssBroken : o.dir == 1 ? zBullObCssLine : zBearObCssLine
    color bg = isBroken ? zObCssBroken : o.dir == 1 ? zBullObCss : zBearObCss
    string txt = isBroken ? "" : (o.dir == 1 ? "OB+" : "OB−") + (o.flipped ? " FVG" : "")
    color brd = isBroken ? #00000000 : lc
    array.push(znBoxes, box.new(o.t1, o.top, right, o.bottom, border_color = brd, border_width = 1, border_style = o.flipped ? line.style_dashed : line.style_solid, extend = extend.none, xloc = xloc.bar_time, bgcolor = bg, text = txt, text_size = size.normal, text_color = lc, text_halign = text.align_right, text_valign = text.align_center, text_wrap = text.wrap_none))
    if zObMidline
        float mid = (o.top + o.bottom) / 2
        array.push(znLines, line.new(o.t1, mid, right, mid, xloc = xloc.bar_time, extend = extend.none, color = lc, style = line.style_dashed, width = 1))
 
znDrawObList(array<ZnOb> lst, int k, bool isBroken) =>
    int n = array.size(lst)
    int shown = 0
    if n > 0 and k > 0
        for i = n - 1 to 0
            ZnOb o = array.get(lst, i)
            if not (zObHideTouched and o.touched and not isBroken) and znIsVisible(o.t1, znObRight(o))
                znDrawOb(o, isBroken)
                shown += 1
                if shown >= k
                    break
 
// "240" -> "4H", "D" -> "1D", "W" -> "1W", "M" -> "1M", "30" -> "30m"
znTfLabel(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec % 2592000 == 0 and str.contains(tf, "M") ? str.tostring(sec / 2592000) + "M" : sec % 604800 == 0 ? str.tostring(sec / 604800) + "W" :
         sec % 86400 == 0 ? str.tostring(sec / 86400) + "D" : sec % 3600 == 0 ? str.tostring(sec / 3600) + "H" : str.tostring(sec / 60) + "m"
 
// Zone of the higher timeframe: values at slot i of znHtf (time, top, bottom, flipped), 2 px border and timeframe in the label
znDrawHtf(int i, int dir, string tfTxt) =>
    float t = array.get(znHtf, i)
    if not na(t)
        float top = array.get(znHtf, i + 1)
        float bottom = array.get(znHtf, i + 2)
        bool flipped = array.get(znHtf, i + 3) == 1
        if znIsVisible(int(t), znNowRight)
            color lc = dir == 1 ? zBullObCssLine : zBearObCssLine
            color bg = dir == 1 ? zBullObCss : zBearObCss
            string txt = (dir == 1 ? "OB+ " : "OB− ") + tfTxt + (flipped ? " FVG" : "")
            array.push(znBoxes, box.new(int(t), top, znNowRight, bottom, border_color = lc, border_width = 2, border_style = flipped ? line.style_dashed : line.style_solid, extend = extend.none, xloc = xloc.bar_time, bgcolor = bg, text = txt, text_size = size.normal, text_color = lc, text_halign = text.align_right, text_valign = text.align_center, text_wrap = text.wrap_none))
 
znGapQuality(ZnGap g) =>
    float thr = nz(g.thr)
    float nq = thr > 0 ? math.min(math.max(g.gTop - g.gBot, syminfo.mintick) / math.max(3 * thr, syminfo.mintick), 1) : 0.5
    float uq = 1 - math.max(0, math.min(1, g.share))
    float q = 0.15 + 0.35 * nq + 0.25 * uq + (g.filled ? 0 : 0.15) + (nz(g.vol) > 0 ? 0.10 : 0)
    math.max(0, math.min(1, q))
 
znDrawGap(ZnGap g, bool isFilled) =>
    int right = znGapRight(g)
    color lineCss = g.dir == 1 ? zBullFvgLineCss : zBearFvgLineCss
    color bg = isFilled ? zFvgCssFilled : g.dir == 1 ? zBullFvgCss : zBearFvgCss
    color brd = isFilled ? zFvgLineCssFilled : lineCss
    array.push(znBoxes, box.new(g.t1, g.gTop, right, g.gBot, border_color = brd, border_width = 1, border_style = line.style_dotted, extend = extend.none, xloc = xloc.bar_time, bgcolor = bg, text = isFilled ? " " : "", text_size = size.normal, text_color = isFilled ? chart.fg_color : lineCss, text_halign = text.align_right, text_valign = text.align_center, text_wrap = text.wrap_none))
    array.push(znLines, line.new(g.t1, g.target, right, g.target, xloc = xloc.bar_time, extend = extend.none, color = isFilled ? zFvgLineCssFilled : lineCss, style = line.style_solid, width = 1))
    string lt = " "
    if not isFilled
        float q = znGapQuality(g)
        lt := (g.dir == 1 ? "FVG+ " : "FVG− ") + (q > 0 ? str.format("(Q {0,number,percent})", q) : "")
    array.push(znLabels, label.new(right, g.target, lt, xloc = xloc.bar_time, yloc = yloc.price, color = #00000000, style = label.style_label_left, textcolor = isFilled ? #00000000 : lineCss, size = size.normal, textalign = text.align_left))
 
znDrawGapList(array<ZnGap> lst, int k, bool isFilled) =>
    int n = array.size(lst)
    int shown = 0
    if n > 0 and k > 0
        for i = n - 1 to 0
            ZnGap g = array.get(lst, i)
            if znIsVisible(g.t1, znGapRight(g))
                znDrawGap(g, isFilled)
                shown += 1
                if shown >= k
                    break
 
if barstate.islast
    znClearDrawings()
    if zShowObBull
        znDrawObList(znBook.bull, zObShowLast, false)
        if zObKeepBroken and zObKeepBrokenMax > 0
            znDrawObList(znBook.bullBroken, zObKeepBrokenMax, true)
    if zShowObBear
        znDrawObList(znBook.bear, zObShowLast, false)
        if zObKeepBroken and zObKeepBrokenMax > 0
            znDrawObList(znBook.bearBroken, zObKeepBrokenMax, true)
    if znHtfOn
        string tfTxt = znTfLabel(zObHtf)
        if zShowObBull
            znDrawHtf(0, 1, tfTxt)
            znDrawHtf(4, 1, tfTxt)
        if zShowObBear
            znDrawHtf(8, -1, tfTxt)
            znDrawHtf(12, -1, tfTxt)
    if zShowFvgBull
        znDrawGapList(znBullGaps, zFvgShowLast, false)
        if zFvgKeepFilled and zFvgKeepFilledMax > 0
            znDrawGapList(znBullFilled, zFvgKeepFilledMax, true)
    if zShowFvgBear
        znDrawGapList(znBearGaps, zFvgShowLast, false)
        if zFvgKeepFilled and zFvgKeepFilledMax > 0
            znDrawGapList(znBearFilled, zFvgKeepFilledMax, true)
 
 
// ════════ Displays as in "SkippALGO Mid" (there lines 2449/2450, 2665–2670, 2794/2795) ════════
plot(zShowEmaFast ? emaF : na, "EMA Fast", color=color.new(color.yellow, 0))
plot(zShowEmaSlow ? emaS : na, "EMA Slow", color=color.new(color.purple, 0))
plotshape(zShowChoch and labelChoCH_L, title="ChoCH (Long)", style=shape.labelup,   location=location.belowbar, size=size.small, text="ChoCH", textcolor=color.white, color=color.new(color.purple, 0))
plotshape(zShowChoch and labelChoCH_S, title="ChoCH (Short)", style=shape.labeldown, location=location.abovebar, size=size.small, text="ChoCH", textcolor=color.white, color=color.new(color.maroon, 0))
plotshape(zShowBos and labelBOS_L, title="BOS (Long)", style=shape.labelup, location=location.belowbar, size=size.tiny, text="BOS", textcolor=color.white, color=color.new(#169c86, 0))
plotshape(zShowBos and labelBOS_S, title="BOS (Short)", style=shape.labeldown, location=location.abovebar, size=size.tiny, text="BOS", textcolor=color.white, color=color.new(#e0532c, 0))
 
// ════════ Alerts BOS/CHoCH ════════
// Fire on exactly the bars that carry the label, even when the label is hidden.
// Only on bar close: the breakout is measured at the close and can still dissolve within the bar.
alertcondition(labelBOS_L and barstate.isconfirmed, title="BOS+", message="ZoneLens BOS+ | {{ticker}} @ {{close}} | {{time}}")
alertcondition(labelBOS_S and barstate.isconfirmed, title="BOS-", message="ZoneLens BOS- | {{ticker}} @ {{close}} | {{time}}")
alertcondition(labelChoCH_L and barstate.isconfirmed, title="CHoCH+", message="ZoneLens CHoCH+ | {{ticker}} @ {{close}} | {{time}}")
alertcondition(labelChoCH_S and barstate.isconfirmed, title="CHoCH-", message="ZoneLens CHoCH- | {{ticker}} @ {{close}} | {{time}}")
// Combined: one alert for both long and both short structure breaks respectively, same bars as the single alerts
alertcondition((labelBOS_L or labelChoCH_L) and barstate.isconfirmed, title="BOS+ or CHoCH+", message="ZoneLens BOS+ or CHoCH+ | {{ticker}} @ {{close}} | {{time}}")
alertcondition((labelBOS_S or labelChoCH_S) and barstate.isconfirmed, title="BOS- or CHoCH-", message="ZoneLens BOS- or CHoCH- | {{ticker}} @ {{close}} | {{time}}")
 
// ════════ Trend channel: calculation and display ════════
zKcMid   = ta.sma(hlc3, zKcLength)
zKcAtr   = ta.atr(zKcLength)
zKcUpper = zKcMid + zKcMult * zKcAtr
zKcLower = zKcMid - zKcMult * zKcAtr
var int zKcState = 0
if close > zKcUpper
    zKcState := 1
else if close < zKcLower
    zKcState := -1
color zKcCol = zKcState == 1 ? zUpColor : zKcState == -1 ? zDownColor : na
bgcolor(zShowBg and zKcState != 0 ? color.new(zKcCol, zBgTransp) : na, title="Background by trend")
zMidPlot   = plot(zShowKc ? zKcMid : na, "Channel midline", color=zKcCol, linewidth=2)
zUpperPlot = plot(zShowKc ? zKcUpper : na, "Channel upper band", color=zKcState != 0 ? color.new(zKcCol, 40) : na)
zLowerPlot = plot(zShowKc ? zKcLower : na, "Channel lower band", color=zKcState != 0 ? color.new(zKcCol, 40) : na)
fill(zUpperPlot, zLowerPlot, zShowKc and zKcState != 0 ? color.new(zKcCol, 93) : na, title="Channel fill")
barcolor(zShowBarCol and zKcState != 0 ? zKcCol : na, title="Bars by trend")
 
// ════════ Repeated tests (resistance / support) and current swing levels — since update 4.0 (19.10.2026) ════════
// Resistance zone: at least N highs within ± tolerance × ATR(50) of one level; each test closes below the level, tests are
// separated by a close at least "move away" × ATR(50) below the level, and since the first test no high has gone above
// level + tolerance (the zone is the ceiling). Support mirrored with lows. Searched on the last bar over the last L bars;
// the zone with the most tests (then the most recent last test) is drawn per side. Display only, not tested as a rule.
var string zgRt = "Repeated tests and swing levels"
bool  zRtShow   = input.bool(true, "Zones from repeated tests (resistance / support)", group=zgRt,
     tooltip="Draws the price band that was tested several times from one side and never exceeded since the first test, with the number of tests. Display only.")
int   zRtMin    = input.int(3, "Minimum tests", minval=2, maxval=10, group=zgRt)
float zRtTol    = input.float(0.2, "Tolerance × ATR(50)", minval=0.05, step=0.05, group=zgRt, tooltip="How far apart the tested highs (lows) may be.")
float zRtAway   = input.float(0.5, "Move away between tests × ATR(50)", minval=0.1, step=0.1, group=zgRt,
     tooltip="A new test counts only after a close this far away from the level, so one long touch is not counted many times.")
int   zRtLook   = input.int(100, "Look back (bars)", minval=20, maxval=400, group=zgRt)
color zRtResCol = input.color(color.new(#e0532c, 80), "Resistance", group=zgRt, inline="rtc")
color zRtSupCol = input.color(color.new(#169c86, 80), "Support", group=zgRt, inline="rtc")
bool  zSwShow   = input.bool(true, "Current swing high / low as lines", group=zgRt,
     tooltip="The swing levels used for BOS/ChoCH: breaking the swing high gives BOS+ (ChoCH+ if the structure was bearish), breaking the swing low BOS− (ChoCH− if it was bullish). A break needs a close beyond the level, or only a wick with Breakout Source = Wick or a ChoCH preset. A broken level is no longer drawn until a new swing forms.")
 
float zRtAtr = ta.atr(Z_ATR_LEN_MAIN)
 
// Swing level broken since it was set? Reset when a new swing is confirmed, set on the structure break of that side.
var bool zSwHiBroken = false
var bool zSwLoBroken = false
if not na(ph)
    zSwHiBroken := false
if not na(pl)
    zSwLoBroken := false
if breakoutLong
    zSwHiBroken := true
if breakoutShort
    zSwLoBroken := true
 
// Returns [tests, zone low, zone high, bars back to the first test]; tests = 0 if nothing qualifies.
zRtFind(bool res) =>
    float tol  = zRtTol * zRtAtr
    float away = zRtAway * zRtAtr
    int   look = math.min(zRtLook, bar_index)
    int   bestN = 0
    int   bestLast = 100000
    float bestLo = na
    float bestHi = na
    int   bestFirst = na
    for i = look to 0
        float lvl = res ? high[i] : low[i]
        int   n = 0
        bool  moved = true
        bool  ok = true
        int   first = na
        int   last = na
        float lo = na
        float hi = na
        for j = look to 0
            float x = res ? high[j] : low[j]
            if n > 0 and (res ? x > lvl + tol : x < lvl - tol)
                ok := false
                break
            bool inBand = math.abs(x - lvl) <= tol and (res ? close[j] < lvl : close[j] > lvl)
            if inBand and moved
                n += 1
                moved := false
                last := j
                if n == 1
                    first := j
                lo := na(lo) ? x : math.min(lo, x)
                hi := na(hi) ? x : math.max(hi, x)
            if n > 0 and (res ? close[j] < lvl - away : close[j] > lvl + away)
                moved := true
        if ok and n >= zRtMin and (n > bestN or (n == bestN and last < bestLast))
            bestN := n
            bestLast := last
            bestLo := lo
            bestHi := hi
            bestFirst := first
    [bestN, bestLo, bestHi, bestFirst]
 
var box   zRtResBox = na
var box   zRtSupBox = na
var line  zSwHiLine = na
var line  zSwLoLine = na
var label zSwHiLab  = na
var label zSwLoLab  = na
if barstate.islast
    box.delete(zRtResBox)
    box.delete(zRtSupBox)
    line.delete(zSwHiLine)
    line.delete(zSwLoLine)
    label.delete(zSwHiLab)
    label.delete(zSwLoLab)
    if zRtShow and not na(zRtAtr)
        [rn, rlo, rhi, rfirst] = zRtFind(true)
        if rn > 0
            zRtResBox := box.new(bar_index - rfirst, rhi, bar_index, rlo, border_color=color.new(#e0532c, 20), bgcolor=zRtResCol,
                 extend=extend.right, text="R ×" + str.tostring(rn) + " · " + str.tostring(rlo, format.mintick) + "–" + str.tostring(rhi, format.mintick),
                 text_size=size.small, text_color=color.new(#e0532c, 0), text_halign=text.align_right, text_valign=text.align_top)
        [sn, slo, shi, sfirst] = zRtFind(false)
        if sn > 0
            zRtSupBox := box.new(bar_index - sfirst, shi, bar_index, slo, border_color=color.new(#169c86, 20), bgcolor=zRtSupCol,
                 extend=extend.right, text="S ×" + str.tostring(sn) + " · " + str.tostring(slo, format.mintick) + "–" + str.tostring(shi, format.mintick),
                 text_size=size.small, text_color=color.new(#169c86, 0), text_halign=text.align_right, text_valign=text.align_bottom)
    if zSwShow
        bool zSwWick = breakoutSourceEff != "Close"
        if not na(lastSwingHigh) and not zSwHiBroken
            int x1 = lastSwingHighBar - swingREff
            zSwHiLine := line.new(x1, lastSwingHigh, bar_index, lastSwingHigh, extend=extend.right, color=color.new(#e0532c, 30), style=line.style_dashed, width=1)
            zSwHiLab := label.new(bar_index + 2, lastSwingHigh, "Swing high " + str.tostring(lastSwingHigh, format.mintick) + " · " + (zSwWick ? "high" : "close") +
                 " above = " + (structState == -1 ? "ChoCH+" : "BOS+"),
                 style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.new(#e0532c, 0), size=size.small)
        if not na(lastSwingLow) and not zSwLoBroken
            int x2 = lastSwingLowBar - swingREff
            zSwLoLine := line.new(x2, lastSwingLow, bar_index, lastSwingLow, extend=extend.right, color=color.new(#169c86, 30), style=line.style_dashed, width=1)
            zSwLoLab := label.new(bar_index + 2, lastSwingLow, "Swing low " + str.tostring(lastSwingLow, format.mintick) + " · " + (zSwWick ? "low" : "close") +
                 " below = " + (structState == 1 ? "ChoCH−" : "BOS−"),
                 style=label.style_label_left, color=color.new(color.black, 100), textcolor=color.new(#169c86, 0), size=size.small)
 
// ════════ Values for other scripts — since update 6.0 ════════
// Not drawn. Shown in the Data Window and selectable as a source in other indicators and strategies (their "Source"
// input lists "ZoneLens: Export: …"), e.g. as an external signal in a strategy or alert builder. Final at the bar's
// close; on the open bar they follow price like the alerts. A zone created on this bar or broken by it does not count.
znExpObHit(array<ZnOb> act) =>
    bool hit = false
    for o in act
        if o.tBreak < time_close and low <= o.top and high >= o.bottom
            hit := true
            break
    hit
 
znExpGapHit(array<ZnGap> act) =>
    bool hit = false
    for g in act
        if g.i2 < bar_index and low <= g.gTop and high >= g.gBot
            hit := true
            break
    hit
 
plot(znExpObHit(znBook.bull) ? 2 : znExpGapHit(znBullGaps) ? 1 : 0, "Export: long zone (2 = in OB+, 1 = in FVG+, 0 = none)", display=display.data_window)
plot(znExpObHit(znBook.bear) ? -2 : znExpGapHit(znBearGaps) ? -1 : 0, "Export: short zone (−2 = in OB−, −1 = in FVG−, 0 = none)", display=display.data_window)
plot(znBullTouchAlert ? 2 : znFvgBullTouchAlert ? 1 : 0, "Export: long first touch (2 = OB+, 1 = FVG+, same bars as the alerts)", display=display.data_window)
plot(znBearTouchAlert ? -2 : znFvgBearTouchAlert ? -1 : 0, "Export: short first touch (−2 = OB−, −1 = FVG−, same bars as the alerts)", display=display.data_window)
plot(structState, "Export: structure (1 = bullish, −1 = bearish, 0 = none yet)", display=display.data_window)
plot(zKcState, "Export: trend channel (1 = up, −1 = down, 0 = none yet)", display=display.data_window)

← 返回列表