Chicken Joe Levels

coastingbeats · study · 1775 行 · 点赞 31 · TradingView 原页

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

Pine Script

//@version=6
indicator("Chicken Joe Levels", shorttitle = "Chicken Joe Levels", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
 
// ######################################################################################################################################
// ######################################################################################################################################
il_nearN    = input.int(2, "IL · Gaps shown above AND below price", minval = 1, maxval = 8, group = "Chicken Joe Levels", display = display.none)
il_minPct   = input.int(50, "IL · Only gaps with a 1-day return chance of at least %", minval = 0, maxval = 100, group = "Chicken Joe Levels", display = display.none)
il_showSess = input.bool(true, "IL · Session levels (Asia / London / NY / prior day)", group = "Chicken Joe Levels", display = display.none)
il_showVwap = input.bool(true, "IL · VWAP", group = "Chicken Joe Levels", display = display.none)
il_showTrend = input.bool(false, "IL · Trendlines + shape", group = "Chicken Joe Levels", display = display.none)
il_pivLen   = input.int(5, "IL · Swing strength (bars each side)", minval = 2, maxval = 20, group = "Chicken Joe Levels", display = display.none)
il_showAll  = input.bool(true, "IL · Show STRONG unfilled gaps back in time (drawn from the candle that made it)", group = "Chicken Joe Levels", display = display.none)
il_strongX  = input.float(0.40, "IL · Strong = gap size at least x ATR of its timeframe (the biggest third)", minval = 0.0, step = 0.05, group = "Chicken Joe Levels", display = display.none)
il_maxDraw  = input.int(12, "IL · Most strong unfilled gaps drawn (nearest first)", minval = 2, maxval = 100, group = "Chicken Joe Levels", display = display.none)
il_shrink   = input.bool(true, "IL · Shrink a gap to its unfilled part once price trades into it", group = "Chicken Joe Levels", display = display.none)
// price, ▼ resistance above). SHADE = STRENGTH: the higher the measured chance price comes back and holds, the darker the box.
il_colM15 = input.color(#29B6F6, "IL · 15m gaps", group = "Chicken Joe Levels", display = display.none)
il_colH1 = input.color(#AB47BC, "IL · 1h gaps", group = "Chicken Joe Levels", display = display.none)
il_colH4 = input.color(#FF9800, "IL · 4h gaps", group = "Chicken Joe Levels", display = display.none)
il_colD1 = input.color(#FFEB3B, "IL · Daily gaps", group = "Chicken Joe Levels", display = display.none)
 
// ================= VWAP (09:30 ET session)
il_inRth  = not na(time(timeframe.period, "0930-1600", "America/New_York"))
il_newRth = il_inRth and not il_inRth[1]
var float il_sPV = na
var float il_sV  = na
if il_newRth
    il_sPV := 0.0
    il_sV  := 0.0
if il_inRth and not na(il_sV)
    il_sPV += hlc3 * volume
    il_sV  += volume
il_vw = il_inRth and il_sV > 0 ? il_sPV / il_sV : na
plot(na, "VWAP (off)", color = color.new(color.orange, 10), linewidth = 1, style = plot.style_linebr, display = display.pane)
 
 
// ================= session levels: the last COMPLETED Asia / London / NY session's high + low, prior RTH close, today's open (ET)
il_f_in(s) => not na(time(timeframe.period, s, "America/New_York"))
il_inAsia = il_f_in("2000-0000")
il_inLdn  = il_f_in("0200-0500")
il_inNy   = il_f_in("0930-1600")
var float il_aH = na
var float il_aL = na
var float il_aHc = na
var float il_aLc = na
var float il_lH = na
var float il_lL = na
var float il_lHc = na
var float il_lLc = na
var float il_nH = na
var float il_nL = na
var float il_nC = na
var float il_pdH = na
var float il_pdL = na
var float il_pdC = na
var float il_tOpen = na
if il_inAsia and not il_inAsia[1]
    il_aH := high
    il_aL := low
else if il_inAsia
    il_aH := math.max(il_aH, high)
    il_aL := math.min(il_aL, low)
if not il_inAsia and il_inAsia[1]
    il_aHc := il_aH
    il_aLc := il_aL
if il_inLdn and not il_inLdn[1]
    il_lH := high
    il_lL := low
else if il_inLdn
    il_lH := math.max(il_lH, high)
    il_lL := math.min(il_lL, low)
if not il_inLdn and il_inLdn[1]
    il_lHc := il_lH
    il_lLc := il_lL
if il_inNy and not il_inNy[1]
    if not na(il_nH)
        il_pdH := il_nH
        il_pdL := il_nL
        il_pdC := il_nC
    il_nH := high
    il_nL := low
    il_tOpen := open
else if il_inNy
    il_nH := math.max(il_nH, high)
    il_nL := math.min(il_nL, low)
if il_inNy
    il_nC := close
 
// ================= point of control: the 5-pt price bin with the most volume since 09:30 ET, and yesterday's final one
var map<int, float> il_prof = map.new<int, float>()
var float il_poc = na
var float il_pocV = 0.0
var float il_pdPoc = na
if il_newRth
    il_pdPoc := il_poc
    map.clear(il_prof)
    il_pocV := 0.0
    il_poc := na
if il_inRth
    int bn = int(math.floor(close / 5.0))
    float v2 = nz(map.get(il_prof, bn)) + volume
    map.put(il_prof, bn, v2)
    if v2 > il_pocV
        il_pocV := v2
        il_poc := bn * 5.0 + 2.5
 
// ================= measured gap lookup (fvg_return.py LOOKUP)
il_f_cuts(i) => i == 0 ? array.from(0.21, 0.39, 0.60, 0.94) : i == 1 ? array.from(0.17, 0.33, 0.54, 0.91) : i == 2 ? array.from(0.20, 0.35, 0.53, 0.82) : array.from(0.19, 0.38, 0.55, 0.84)
il_f_fmed(i) => i == 0 ? 0.65 : i == 1 ? 0.32 : i == 2 ? 0.43 : 0.72
il_f_lo(i)   => i == 0 ? array.from(97, 96, 95, 93, 88) : i == 1 ? array.from(98, 94, 92, 92, 81) : i == 2 ? array.from(93, 90, 75, 73, 56) : array.from(77, 64, 38, 18, 20)
il_f_hi(i)   => i == 0 ? array.from(99, 96, 95, 93, 84) : i == 1 ? array.from(96, 93, 89, 84, 69) : i == 2 ? array.from(92, 86, 76, 74, 60) : array.from(91, 70, 36, 31, 27)
il_f_name(i) => i == 0 ? "15m" : i == 1 ? "1h" : i == 2 ? "4h" : "D"
il_f_tfcol(i) => i == 0 ? il_colM15 : i == 1 ? il_colH1 : i == 2 ? il_colH4 : il_colD1
il_f_bucket(cuts, d) =>
    int b = 0
    for k = 0 to 3
        if d > array.get(cuts, k)
            b := k + 1
    b
 
// a gap reported only after its third candle CLOSED (every value one bar back + lookahead_on = no repaint)
il_f_gap() =>
    a    = ta.atr(14)[1]
    rng  = high[2] - low[2]
    clv  = rng > 0 ? (2 * close[2] - high[2] - low[2]) / rng : 0.0
    vm   = ta.sma(volume, 20)[2]
    rv   = vm > 0 ? volume[2] / vm : 1.0
    bull = low[1] > high[3]
    bear = high[1] < low[3]
    lo   = bull ? high[3] : bear ? high[1] : na
    hi   = bull ? low[1] : bear ? low[3] : na
    dir  = bull ? 1 : bear ? -1 : 0
    [dir, lo, hi, a, clv * rv * dir]
 
[il_d0, il_lo0, il_hi0, il_a0, il_f0] = request.security(syminfo.tickerid, "15",  il_f_gap(), lookahead = barmerge.lookahead_on)
[il_d1, il_lo1, il_hi1, il_a1, il_f1] = request.security(syminfo.tickerid, "60",  il_f_gap(), lookahead = barmerge.lookahead_on)
[il_d2, il_lo2, il_hi2, il_a2, il_f2] = request.security(syminfo.tickerid, "240", il_f_gap(), lookahead = barmerge.lookahead_on)
[il_d3, il_lo3, il_hi3, il_a3, il_f3] = request.security(syminfo.tickerid, "D",   il_f_gap(), lookahead = barmerge.lookahead_on)
il_chartSec = timeframe.in_seconds()
// RSI at the gap (fvg_visits.py): 1-min RSI(14) oriented with the gap; HIGH = momentum still on the gap's side = holds better.
// 15m gaps: measured bounce odds (11% / 18% / 20% by tercile, both halves). 1h / 4h / D: too few RTH gaps to measure -> a with/against tag only.
il_rsiArr = request.security_lower_tf(syminfo.tickerid, "1", ta.rsi(close, 14))
il_rsiC = ta.rsi(close, 14)          // on the chart, every bar (a ta.* call inside a ternary is unreliable in Pine)
il_rsi1 = array.size(il_rsiArr) > 0 ? array.last(il_rsiArr) : il_rsiC
 
type il_Gap
    int   tf
    int   dir
    float lo
    float hi
    float atr
    float flow
    float pct
    int   visits
    bool  away
    int   x0
    float nearCur          // the unfilled edge: moves into the gap as price trades into it
 
// strength 0..1: the measured return chance (50% -> 0, 100% -> 1); with none, the gap's size in ATR (0.4x -> 0, 1.2x -> 1); a POC inside +0.15
il_f_str(il_Gap g, bool pocIn) =>
    float s0 = not na(g.pct) ? (g.pct - 50.0) / 50.0 : ((g.hi - g.lo) / g.atr - 0.4) / 0.8
    math.max(0.0, math.min(1.0, s0 + (pocIn ? 0.15 : 0.0)))
 
var il_gaps = array.new<il_Gap>()
il_f_add(tf, dir, lo, hi, a, fl) =>
    if dir != 0 and not na(lo) and not na(hi) and hi > lo and a > 0
        array.push(il_gaps, il_Gap.new(tf, dir, lo, hi, a, fl, na, 0, true, bar_index, dir > 0 ? hi : lo))
        if array.size(il_gaps) > 300
            array.shift(il_gaps)
if ta.change(time("15")) != 0 and il_chartSec <= 900
    il_f_add(0, il_d0, il_lo0, il_hi0, il_a0, il_f0)
if ta.change(time("60")) != 0 and il_chartSec <= 3600
    il_f_add(1, il_d1, il_lo1, il_hi1, il_a1, il_f1)
if ta.change(time("240")) != 0 and il_chartSec <= 14400
    il_f_add(2, il_d2, il_lo2, il_hi2, il_a2, il_f2)
if ta.change(time("D")) != 0 and il_chartSec <= 86400
    il_f_add(3, il_d3, il_lo3, il_hi3, il_a3, il_f3)
 
// a chart ABOVE a gap's timeframe (e.g. 15m gaps on a 1h chart): rebuild that timeframe's candles inside each chart candle and find the
// gaps there, so they are not lost; each is drawn from the chart candle it formed in (the flow push is not rebuilt -> the 'low flow' odds)
[il_h15, il_l15, il_c15] = request.security_lower_tf(syminfo.tickerid, il_chartSec > 900 ? "15" : timeframe.period, [high, low, close])
[il_h60, il_l60, il_c60] = request.security_lower_tf(syminfo.tickerid, il_chartSec > 3600 ? "60" : timeframe.period, [high, low, close])
var float[] il_SH15 = array.new_float()
var float[] il_SL15 = array.new_float()
var float[] il_ST15 = array.new_float()
var float[] il_SP15 = array.new_float(1, na)
var float[] il_SH60 = array.new_float()
var float[] il_SL60 = array.new_float()
var float[] il_ST60 = array.new_float()
var float[] il_SP60 = array.new_float(1, na)
il_f_scanL(tf, hs, ls, cs, H, L, T, P) =>
    n = array.size(hs)
    if n > 0
        for i = 0 to n - 1
            h = array.get(hs, i)
            l = array.get(ls, i)
            c = array.get(cs, i)
            pc = array.get(P, 0)
            atrPrev = array.size(T) >= 14 ? array.avg(T) : na
            array.push(H, h)
            array.push(L, l)
            if array.size(H) > 3
                array.shift(H)
                array.shift(L)
            if array.size(H) == 3 and not na(atrPrev)
                if array.get(L, 2) > array.get(H, 0)
                    il_f_add(tf, 1, array.get(H, 0), array.get(L, 2), atrPrev, 0.0)
                else if array.get(H, 2) < array.get(L, 0)
                    il_f_add(tf, -1, array.get(H, 2), array.get(L, 0), atrPrev, 0.0)
            array.push(T, na(pc) ? h - l : math.max(h, pc) - math.min(l, pc))
            if array.size(T) > 14
                array.shift(T)
            array.set(P, 0, c)
if il_chartSec > 900
    il_f_scanL(0, il_h15, il_l15, il_c15, il_SH15, il_SL15, il_ST15, il_SP15)
if il_chartSec > 3600
    il_f_scanL(1, il_h60, il_l60, il_c60, il_SH60, il_SL60, il_ST60, il_SP60)
 
// a gap stays until a candle CLOSES through its far edge; every return to it is a VISIT (an event)
il_gapTouched = false
if array.size(il_gaps) > 0
    for k = array.size(il_gaps) - 1 to 0
        g = array.get(il_gaps, k)
        near = g.dir > 0 ? g.hi : g.lo
        far  = g.dir > 0 ? g.lo : g.hi
        if (g.dir > 0 and close < far) or (g.dir < 0 and close > far)
            array.remove(il_gaps, k)
        else
            if g.dir > 0 and low < g.nearCur
                g.nearCur := math.max(low, far)
            if g.dir < 0 and high > g.nearCur
                g.nearCur := math.min(high, far)
            if ((g.dir > 0 and low <= near) or (g.dir < 0 and high >= near)) and g.away
                g.visits += 1
                g.away := false
                if g.tf >= 1
                    il_gapTouched := true
            if not g.away and (g.dir > 0 ? high - near : near - low) >= 0.5 * g.atr
                g.away := true
            if g.visits == 0
                b = il_f_bucket(il_f_cuts(g.tf), math.abs(close - near) / g.atr)
                g.pct := g.flow > il_f_fmed(g.tf) ? array.get(il_f_hi(g.tf), b) : array.get(il_f_lo(g.tf), b)
 
// ================= trendlines through the last two swings, and the shape
il_ph = ta.pivothigh(high, il_pivLen, il_pivLen)
il_pl = ta.pivotlow(low, il_pivLen, il_pivLen)
var float il_hY1 = na
var int il_hX1 = na
var float il_hY2 = na
var int il_hX2 = na
var float il_lY1 = na
var int il_lX1 = na
var float il_lY2 = na
var int il_lX2 = na
if not na(il_ph)
    il_hY1 := il_hY2
    il_hX1 := il_hX2
    il_hY2 := il_ph
    il_hX2 := bar_index - il_pivLen
if not na(il_pl)
    il_lY1 := il_lY2
    il_lX1 := il_lX2
    il_lY2 := il_pl
    il_lX2 := bar_index - il_pivLen
il_atrC   = ta.atr(14)
il_hSlope = na(il_hX1) or il_hX2 == il_hX1 ? na : (il_hY2 - il_hY1) / (il_hX2 - il_hX1)
il_lSlope = na(il_lX1) or il_lX2 == il_lX1 ? na : (il_lY2 - il_lY1) / (il_lX2 - il_lX1)
il_upLine = na(il_hSlope) ? na : il_hY2 + il_hSlope * (bar_index - il_hX2)
il_dnLine = na(il_lSlope) ? na : il_lY2 + il_lSlope * (bar_index - il_lX2)
il_flat   = 0.03 * il_atrC                         // a slope under 3% of an ATR per bar reads as flat
il_f_shape(hs, ls) =>
    string s = ""
    if not na(hs) and not na(ls)
        hf = math.abs(hs) < il_flat
        lf = math.abs(ls) < il_flat
        conv = hs < ls - il_flat * 0.5
        div = hs > ls + il_flat * 0.5
        if hf and ls > il_flat
            s := "ascending triangle"
        else if lf and hs < -il_flat
            s := "descending triangle"
        else if hs < -il_flat and ls > il_flat
            s := "symmetric triangle"
        else if hs > il_flat and ls > il_flat and conv
            s := "rising wedge"
        else if hs < -il_flat and ls < -il_flat and conv
            s := "falling wedge"
        else if div
            s := "broadening"
        else if hs > il_flat and ls > il_flat
            s := "channel up"
        else if hs < -il_flat and ls < -il_flat
            s := "channel down"
        else
            s := "range"
    s
il_shape = il_f_shape(il_hSlope, il_lSlope)
il_newShape = il_shape != "" and il_shape != il_shape[1] and (not na(il_ph) or not na(il_pl))
 
il_breakUp = not na(il_upLine) and close > il_upLine and close[1] <= il_upLine[1]
il_breakDn = not na(il_dnLine) and close < il_dnLine and close[1] >= il_dnLine[1]
il_vwUp    = il_showVwap and not na(il_vw) and close > il_vw and close[1] <= il_vw[1]
il_vwDn    = il_showVwap and not na(il_vw) and close < il_vw and close[1] >= il_vw[1]
 
// ================= drawing: redraw only on the last bar (nothing piles up)
var line il_tU = na
var line il_tD = na
var box[] il_gb = array.new<box>()
var label[] il_gl = array.new<label>()
var line[] il_ll = array.new<line>()
var table il_tb = table.new(position.top_right, 1, 1, bgcolor = color.new(color.black, 80))
il_f_lv(y, txt, c) =>
    if not na(y)
        array.push(il_ll, line.new(bar_index - 8, y, bar_index + 16, y, color = color.new(c, 35), style = line.style_solid, width = 1))
        array.push(il_gl, label.new(bar_index + 15, y, txt, style = label.style_none, textcolor = c, size = size.small))
// the session level is drawn only if it is among the 4 nearest to price (so far levels do not clutter)
il_f_near4(y) =>
    int closer = 0
    for v in array.from(il_aHc, il_aLc, il_lHc, il_lLc, il_pdH, il_pdL, il_pdC, il_tOpen, il_inNy ? il_nH : na, il_inNy ? il_nL : na)
        if not na(v) and not na(y) and math.abs(v - close) < math.abs(y - close)
            closer += 1
    closer < 4
if barstate.islast
    line.delete(il_tU)
    line.delete(il_tD)
    if il_showTrend and not na(il_upLine) and not na(il_hX1)
        il_tU := line.new(il_hX1, il_hY1, bar_index, il_upLine, extend = extend.right, color = color.new(color.red, 30), width = 1)
    if il_showTrend and not na(il_dnLine) and not na(il_lX1)
        il_tD := line.new(il_lX1, il_lY1, bar_index, il_dnLine, extend = extend.right, color = color.new(color.teal, 30), width = 1)
    for b in il_gb
        box.delete(b)
    for l in il_gl
        label.delete(l)
    for l in il_ll
        line.delete(l)
    array.clear(il_gb)
    array.clear(il_gl)
    array.clear(il_ll)
    // the nearest nearN qualifying gaps above and below price
    above = array.new<il_Gap>()
    below = array.new<il_Gap>()
    for g in il_gaps
        if g.pct >= il_minPct or g.visits > 0
            if (g.lo + g.hi) / 2 > close
                array.push(above, g)
            else
                array.push(below, g)
    drawn = array.new<il_Gap>()
    for side = 0 to 1
        src = side == 0 ? above : below
        for n = 1 to il_nearN
            int best = -1
            float bd = 1e18
            if array.size(src) > 0
                for k = 0 to array.size(src) - 1
                    g = array.get(src, k)
                    d = math.abs(close - (g.lo + g.hi) / 2)
                    if d < bd
                        bd := d
                        best := k
            if best >= 0
                g = array.remove(src, best)
                col = il_f_tfcol(g.tf)
                pocIn = (not na(il_poc) and il_poc >= g.lo and il_poc <= g.hi) or (not na(il_pdPoc) and il_pdPoc >= g.lo and il_pdPoc <= g.hi)
                st = il_f_str(g, pocIn)
                orsi = g.dir > 0 ? il_rsi1 : 100 - il_rsi1
                string rtag = g.tf == 0 ? " | bounce " + str.tostring(orsi <= 36 ? 11 : orsi <= 43 ? 18 : 20) + "%" : (orsi >= 50 ? " | RSI with" : " | RSI against")
                string tag = (pocIn ? " POC" : "") + (g.visits > 0 ? " " + str.tostring(g.visits) + "x" : "")
                array.push(drawn, g)
                gTop = il_shrink and g.dir > 0 ? g.nearCur : g.hi   // bull: price came DOWN into it -> what is left is lo .. nearCur
                gBot = il_shrink and g.dir < 0 ? g.nearCur : g.lo   // bear: price came UP into it -> what is left is nearCur .. hi
                array.push(il_gb, box.new(math.max(g.x0, bar_index - 9900), gTop, bar_index + 18, gBot, extend = extend.right, border_color = color.new(col, 60 - 35 * st), border_width = 1, bgcolor = color.new(col, 93 - 25 * st)))   // a ray from the candle that made the gap: every tap stays visible
                ly = (g.lo + g.hi) / 2
                bool clash = false
                for glab in il_gl
                    if math.abs(label.get_y(glab) - ly) < 0.35 * g.atr
                        clash := true
                if not clash
                    array.push(il_gl, label.new(bar_index + 5, (g.lo + g.hi) / 2, (g.dir > 0 ? "▲ " : "▼ ") + il_f_name(g.tf) + (na(g.pct) ? "" : " " + str.tostring(g.pct) + "%") + tag, style = label.style_none, textcolor = col, size = size.normal))
    // EVERY OTHER UNFILLED GAP, back in time (like Nephew_Sam's FVG/iFVG): from the candle that made it, to the right until a candle
    // closes through its far edge; unlabelled and fainter; the nearest first, up to maxDraw
    if il_showAll
        rest = array.new<il_Gap>()
        for g in il_gaps
            bool dup = false
            for dg in drawn
                if dg.x0 == g.x0 and dg.lo == g.lo and dg.hi == g.hi and dg.tf == g.tf
                    dup := true
            if not dup and (g.hi - g.lo) / g.atr >= il_strongX
                array.push(rest, g)
        cnt = 0
        while array.size(rest) > 0 and cnt < il_maxDraw
            int best = 0
            float bd = 1e18
            for k = 0 to array.size(rest) - 1
                gg = array.get(rest, k)
                d = math.abs(close - (gg.lo + gg.hi) / 2)
                if d < bd
                    bd := d
                    best := k
            g = array.remove(rest, best)
            col = il_f_tfcol(g.tf)
            st = il_f_str(g, false)
            gTop = il_shrink and g.dir > 0 ? g.nearCur : g.hi   // bull: price came DOWN into it -> what is left is lo .. nearCur
            gBot = il_shrink and g.dir < 0 ? g.nearCur : g.lo   // bear: price came UP into it -> what is left is nearCur .. hi
            array.push(il_gb, box.new(math.max(g.x0, bar_index - 9900), gTop, bar_index + 6, gBot, extend = extend.right, border_color = color.new(col, 85 - 25 * st), border_width = 1, bgcolor = color.new(col, 96 - 16 * st)))
            cnt += 1
    if false
        if il_f_near4(il_aHc)
            il_f_lv(il_aHc, "Asia H", color.fuchsia)
        if il_f_near4(il_aLc)
            il_f_lv(il_aLc, "Asia L", color.fuchsia)
        if il_f_near4(il_lHc)
            il_f_lv(il_lHc, "London H", color.aqua)
        if il_f_near4(il_lLc)
            il_f_lv(il_lLc, "London L", color.aqua)
        if il_f_near4(il_pdH)
            il_f_lv(il_pdH, "PD H", color.gray)
        if il_f_near4(il_pdL)
            il_f_lv(il_pdL, "PD L", color.gray)
        if il_f_near4(il_pdC)
            il_f_lv(il_pdC, "PD close", color.silver)
        if il_f_near4(il_tOpen)
            il_f_lv(il_tOpen, "NY open", color.yellow)
        if il_f_near4(il_inNy ? il_nH : na)
            il_f_lv(il_inNy ? il_nH : na, "NY H", color.orange)
        if il_f_near4(il_inNy ? il_nL : na)
            il_f_lv(il_inNy ? il_nL : na, "NY L", color.orange)
    if il_showTrend
        table.cell(il_tb, 0, 0, (il_shape == "" ? "no shape yet" : il_shape) + (il_breakUp ? "  | BREAK UP" : il_breakDn ? "  | BREAK DOWN" : ""), text_color = color.white, text_size = size.normal)
 
// ================= events: a small marker + an alert, nothing else
plotshape(il_showTrend and il_breakUp, "Trendline break up", shape.triangleup, location.belowbar, color.teal, size = size.tiny, display = display.pane)
plotshape(il_showTrend and il_breakDn, "Trendline break down", shape.triangledown, location.abovebar, color.red, size = size.tiny, display = display.pane)
alertcondition(il_breakUp, "Trendline break UP", "Chicken Joe Levels: close above the swing-high trendline")
alertcondition(il_breakDn, "Trendline break DOWN", "Chicken Joe Levels: close below the swing-low trendline")
alertcondition(il_gapTouched, "Gap visited", "Chicken Joe Levels: price came back to a 1h/4h/D gap")
alertcondition(il_newShape, "New shape", "Chicken Joe Levels: a new shape formed")
alertcondition(il_vwUp or il_vwDn, "VWAP cross", "Chicken Joe Levels: close crossed VWAP")
 
// ######################################################################################################################################
// ####  PART 2 -- SWEEP + DELIVERY CHECKLIST v4 (unchanged code)
// ######################################################################################################################################
// information / confluence only (never a target); the prior-day POC off the map; only the latest two 30-min swing highs / lows; HH / LL guard;
// v1 (SWEEP_DELIVERY_CHECKLIST.pine) is untouched. v2 = the DAY MAP from 18:00 ET, AREA strength, level-REACTION signals and a PLAN box.
//  - entry = a level REACTION: RESPECT (sweep through, close back inside, displacement away) -> trade away;
//    DISRESPECT (close through with a new FVG, no pullback inside 3 bars) -> trade the RETEST. Never at the open, never in chop.
//  - every plan has a DESTINATION: the next map level >= 2x stop and >= 40 pts. No destination = no signal. No scalps.
// Needs a TradingView plan with footprint charts (Premium+) and, for the per-second big prints, seconds data; otherwise the footprint rows are the fallback.
// NOTHING here is a proven edge. Context only. Approximations are listed in SWEEP_DELIVERY_CHECKLIST_v2_NOTES.md.
 
// ================= inputs
// -- day map
showProf   = input.bool(true,  "Prior-week / prior-day RTH profile (VAH / POC / VAL)", group="Sweep + Delivery", display = display.none)
showHL     = input.bool(true,  "Prior-day RTH H / L / close, prior-week H / L", group="Sweep + Delivery", display = display.none)
showSess   = input.bool(true,  "Asia (18:00-03:00), London (03:00-09:30), overnight (21:00-09:30) H / L", group="Sweep + Delivery", display = display.none)
showOpens  = input.bool(true,  "Midnight open and 09:30 open", group="Sweep + Delivery", display = display.none)
showVwap   = input.bool(true,  "RTH VWAP", group="Sweep + Delivery", display = display.none)
showDev    = input.bool(true,  "Developing RTH VAH / POC / VAL", group="Sweep + Delivery", display = display.none)
drawPdPoc  = input.bool(true,  "Draw the prior-day POC", group="Sweep + Delivery")
showPdPoc  = input.bool(false, "Prior-day POC on the map", group="Sweep + Delivery", display = display.none)
showSw30   = input.bool(true,  "30-min swing highs / lows: only the latest 2 of each", group="Sweep + Delivery", display = display.none)
useAsiaAtm = input.bool(true,  "Asia ATM range (18:00-19:00 ET)", group="Sweep + Delivery", display = display.none)
showNodes  = input.bool(true, "LVN / HVN lines (same as the dashboard: current RTH session profile, 1-pt rows)", group="Sweep + Delivery", display = display.none)
vpBin      = input.float(2.0,  "Profile bin (price units; weekly profile uses 4x)", minval=0.25, step=0.25, group="Sweep + Delivery", display = display.none)
devMinMin  = input.int(30,     "Developing profile starts N minutes after 09:30", minval=0, group="Sweep + Delivery", display = display.none)
brkMult    = input.float(1.0,  "BROKEN = close beyond a level by >= this x median 1m bar", step=0.25, group="Sweep + Delivery", display = display.none)
med1m      = input.bool(true,  "Median bar from 1m bars (off = from chart bars)", group="Sweep + Delivery", display = display.none)
mapLeft    = input.int(150,    "Map lines start this many bars back", minval=20, group="Sweep + Delivery", display = display.none)
labSizeS   = input.string("small", "Level label size", options=["tiny", "small", "normal"], group="Sweep + Delivery", display = display.none)
labSize    = labSizeS == "tiny" ? size.small : labSizeS == "normal" ? size.large : size.normal
labRight   = input.int(240, "Label distance right of the last bar, in bars (match your chart right margin)", minval=0, maxval=490, group="Sweep + Delivery", display = display.none)
labMerge   = input.float(2.2, "Label spacing (% of the visible price range; close levels stack upward)", minval=0, step=0.2, group="Sweep + Delivery", display = display.none)
// -- areas
areaTol    = input.float(0.5,  "Area = levels within this x median bar of each other", step=0.25, group="Sweep + Delivery", display = display.none)
minArea    = input.int(2,      "Minimum distinct level families for a signal (A = 2, A+ = 3; a defended big-print bubble is a family)", minval=1, maxval=6, group="Sweep + Delivery", display = display.none)
// -- signals
useRespect = input.bool(true,  "RESPECT signals (sweep, close back, displacement away)", group="Sweep + Delivery", display = display.none)
useDisresp = input.bool(true,  "DISRESPECT signals (close through + FVG, signal on the retest)", group="Sweep + Delivery", display = display.none)
dispK      = input.float(1.0,  "Displacement bar body >= this x median bar", step=0.25, group="Sweep + Delivery", display = display.none)
chopMult   = input.float(8.0,  "Chop = 60-bar range narrower than this x median bar", step=0.5, group="Sweep + Delivery", display = display.none)
retestMax  = input.int(90,     "Retest window after a disrespect break (bars)", minval=5, group="Sweep + Delivery", display = display.none)
noPocEnt   = input.bool(true,  "No RESPECT entry at a POC (price is drawn to it)", group="Sweep + Delivery", display = display.none)
driveOn    = input.bool(true,  "Drive guard: no fade >= 15 min into a session against a >= 4-bar move from the session open whose extreme is <= 10 bars old (absorption exempts)", group="Sweep + Delivery", display = display.none)
deadOn     = input.bool(true,  "Dead-tape guard: no signal when 30-bar volume < half its ~2-session average AND chop", group="Sweep + Delivery", display = display.none)
structOn   = input.bool(true,  "Structure guard (no long while the last 3 5m swing highs AND lows descend; mirror)", group="Sweep + Delivery", display = display.none)
hhOn       = input.bool(true,  "HH / LL guard: last 5m swing high above the one before = no short; a lower 5m swing low = no long", group="Sweep + Delivery", display = display.none)
winOn      = input.bool(true,  "Only the trade windows: NY 09:35-15:44, London 03:00-03:59, Asia 19:00-19:59, ATM sweep 21:00-22:59 ET", group="Sweep + Delivery", display = display.none)
confirmReq = input.string("off", "Require ICT confirmation on RESPECT signals", options=["off", "iFVG", "CISD", "either"], group="Sweep + Delivery", tooltip="iFVG = a close through a gap of the opposite colour. CISD = change in state of delivery: an up-close candle closes above the open of the run of down-close candles before it (mirror). Both are tagged on the signal either way.", display = display.none)
confN      = input.int(3,      "Confirmation must have printed within N bars", minval=1, group="Sweep + Delivery", display = display.none)
oneAtATime = input.bool(true,  "One open signal per direction (no doubling down)", group="Sweep + Delivery", display = display.none)
cooldownMin = input.int(60,    "Minutes before another signal in the same direction", minval=0, group="Sweep + Delivery", display = display.none)
freshMin   = input.int(60,     "Fresh pool take window (minutes), check 1", minval=5, group="Sweep + Delivery", display = display.none)
volMult    = input.float(1.5,  "Volume multiple, check 4", step=0.1, group="Sweep + Delivery", display = display.none)
minScore   = input.int(0,      "Only signals with at least this many of the 5 checks (0 = info only)", minval=0, maxval=5, group="Sweep + Delivery", display = display.none)
// -- plan
padPts     = input.float(2.0,  "Stop pad beyond the area / sweep extreme (price units)", step=0.25, group="Sweep + Delivery", display = display.none)
minStopMed = input.float(3.0,  "Stop floor (x median 1m bar)", step=0.5, group="Sweep + Delivery", display = display.none)
minRR      = input.float(2.0,  "Target at least this x the stop", step=0.25, group="Sweep + Delivery", display = display.none)
minTgtPts  = input.float(50.0, "Target at least this many points (no scalps; the script: max(50, 2 x stop))", step=1.0, group="Sweep + Delivery", display = display.none)
tp1Mode    = input.string("halfway entry -> target", "TP1", options=["halfway area -> target", "halfway entry -> target"], group="Sweep + Delivery", tooltip="Halfway between the LEVELS (e.g. VAH and POC), not between the fill and the target", display = display.none)
pocStop    = input.bool(true,  "A POC on the stop side inside stop + 1 bar pushes the stop 1 median bar beyond it", group="Sweep + Delivery", display = display.none)
asiaSweep  = input.bool(true,  "Asia sweep: a rejected Asia / overnight high targets the Asia / overnight low (mirror)", group="Sweep + Delivery", display = display.none)
showHist   = input.bool(true,  "Label resolved past signals (TP1 half + BE, runner to target)", group="Sweep + Delivery", display = display.none)
// -- HTF delivery, flow, gamma (from v1)
showHtfFvg = input.bool(true,  "1h / 4h unmitigated FVGs", group="Sweep + Delivery", display = display.none)
fvgMax     = input.int(4,      "Max FVGs per timeframe", minval=1, maxval=8, group="Sweep + Delivery", display = display.none)
deltaTf    = input.string("1", "Fallback delta resolution when footprint is unavailable (lower timeframe)", options=["1", "30S", "15S", "10S", "5S", "1S"], group="Sweep + Delivery", tooltip="Used only when request.footprint returns na. Finer = closer to real tape delta; if the chart goes blank pick 1.", display = display.none)
showBarDots = input.bool(false, "Legacy bar-delta dots (big BAR vs 20-bar average, with delta number)", group="Sweep + Delivery", display = display.none)
bigMult    = input.float(2.5,  "Legacy dots: bar volume >= this x the 20-bar average", step=0.25, group="Sweep + Delivery", display = display.none)
showAbsorb = input.bool(true,  "Absorption diamond (volume > 2x average, range < 0.6x average)", group="Sweep + Delivery", display = display.none)
fpTicks    = input.int(1,      "Footprint ticks per row (fallback rows + real delta)", minval=1, group="Sweep + Delivery", display = display.none)
showBubbles = input.bool(true, "Big-print bubbles (lot size) + DEFENDED test", group="Sweep + Delivery", display = display.none)
bigSym     = input.string("CME_MINI:NQ1!", "Parent symbol read for prints (MNQ chart -> NQ; MES -> CME_MINI:ES1!)", group="Sweep + Delivery", display = display.none)
bigNyLots  = input.int(75,     "NQ: lots in one print, NY 09:30-16:00 ET", minval=1, group="Sweep + Delivery", display = display.none)
bigOffLots = input.int(50,     "NQ: lots in one print, outside NY", minval=1, group="Sweep + Delivery", display = display.none)
bigEsLots  = input.int(200,    "ES: lots in one print (all hours)", minval=1, group="Sweep + Delivery", display = display.none)
secMult    = input.float(4.0,  "1-second volume must be >= this x the lot size (measured on NQ ticks: x1 = 17% real prints, x3 = 67%, x4 = 76%, x6 = 88%)", minval=1, step=0.5, group="Sweep + Delivery", display = display.none)
bubBars    = input.int(5,      "DEFENDED = price does not trade through the bubble for this many bars", minval=1, group="Sweep + Delivery", display = display.none)
bubThru    = input.float(0.5,  "Run-through = beyond the bubble price by this x median bar", step=0.25, group="Sweep + Delivery", display = display.none)
greyRun    = input.bool(false, "Run-through bubbles: grey them (off = remove)", group="Sweep + Delivery", display = display.none)
bubLifeMin = input.int(120,    "A defended bubble counts toward area strength for this many minutes", minval=5, group="Sweep + Delivery", display = display.none)
bubMax     = input.int(40,    "Bubbles kept (oldest dropped)", minval=20, maxval=400, group="Sweep + Delivery", display = display.none)
gexOn      = input.bool(true,  "Gamma levels (typed by hand each morning)", group="Sweep + Delivery", display = display.none)
gexFlip    = input.float(0.0,  "Gamma flip (chart price units, 0 = off)", group="Sweep + Delivery", display = display.none)
gexCall    = input.float(0.0,  "Call wall", group="Sweep + Delivery", display = display.none)
gexPut     = input.float(0.0,  "Put wall", group="Sweep + Delivery", display = display.none)
gexBasis   = input.float(0.0,  "Basis to add (MNQ price minus NDX spot) if you typed NDX levels", group="Sweep + Delivery", display = display.none)
gexRegimeIn = input.string("auto (VIX proxy)", "Dealer gamma environment", options=["auto (VIX proxy)", "positive (damped)", "negative (amplified)"], group="Sweep + Delivery", tooltip="Auto = a PROXY from the VIX term structure (VIX vs VIX3M) and the prior-day VIX move. Pick positive / negative yourself to override.", display = display.none)
 
tz = "America/New_York"
NL = 32
NF = 14            // level families (0-11 map levels, 12 = defended big-print bubble, 13 = 30-min swings)
NB = 2000          // profile bins
HALF = 1000        // bin index of the anchor price
 
// ================= clock (ET minute of day)
hm       = hour(time, tz) * 60 + minute(time, tz)
inAsia   = hm >= 1080 or hm < 180
inLondon = hm >= 180 and hm < 570
inRth    = hm >= 570 and hm < 960
onWin    = hm >= 1260 or hm < 570
inAtm    = hm >= 1080 and hm < 1140
newSess  = hm >= 1080 and (nz(hm[1], 0) < 1080 or time - nz(time[1], time) > 4 * 3600000)
first5   = (hm >= 1080 and hm < 1085) or (hm >= 180 and hm < 185) or (hm >= 570 and hm < 575)
macro    = minute >= 50 or minute <= 10
botWin   = (hm >= 575 and hm <= 944) or (hm >= 180 and hm < 240) or (hm >= 1140 and hm < 1200) or (hm >= 1260 and hm < 1380)
 
med1     = request.security(syminfo.tickerid, "1", ta.median(high - low, 390), lookahead=barmerge.lookahead_off)
medC     = ta.median(high - low, 390)
medNow   = med1m ? med1 : medC
med      = nz(medNow[1], 0.0)          // read at the PRIOR close
 
// ================= level slots (price, name, family, state, side, pool kind)
// state: 0 live, 1 BROKEN, 2 HELD.  side: +1 price was above the level, -1 below.  pool kind: +1 high pool, -1 low pool, 0 none.
var float[]  lvP  = array.new_float(NL, na)
var int[]    lvS  = array.new_int(NL, 0)
var int[]    lvD  = array.new_int(NL, 1)
var string[] lvN  = array.from("PW VAH", "PW POC", "PW VAL", "PD VAH", "PD POC", "PD VAL", "PDH", "PDL", "PD close", "PWH", "PWL", "AsiaH", "AsiaL", "LonH", "LonL", "ONH", "ONL", "Mid open", "0930 open", "VWAP", "dev VAH", "dev POC", "dev VAL", "gamma flip", "call wall", "put wall", "ATM-H", "ATM-L", "SwH", "SwH2", "SwL", "SwL2")
var int[]    lvF  = array.from(0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 9, 9, 9, 10, 10, 10, 11, 11, 13, 13, 13, 13)
var int[]    lvHL = array.from(0, 0, 0, 0, 0, 0, 1, -1, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 1, 1, -1, -1)
var bool[]   fSeen = array.new_bool(NF, false)
// big-print bubble ledger: price, lots, side, print bar, state (0 pending, 1 DEFENDED, 2 run through), label
var float[] dP = array.new_float()
var float[] dV = array.new_float()
var int[]   dS = array.new_int()
var int[]   dB = array.new_int()
var int[]   dState = array.new_int()
var label[] dL = array.new_label()
var float[] agP = array.new_float()
var float[] agV = array.new_float()
var int[]   agS = array.new_int()
var float[]  arA  = array.new_float(2, na)
var float[]  bC   = array.new_float(4, 0.0)     // best candidate per category: 0 respect-long 1 respect-short 2 break-up 3 break-down
var float[]  bP   = array.new_float(4, 0.0)
var float[]  bLo  = array.new_float(4, 0.0)
var float[]  bHi  = array.new_float(4, 0.0)
var float[]  bI   = array.new_float(4, 0.0)
// profiles
var float[] dv = array.new_float(NB, 0.0)
var float[] wv = array.new_float(NB, 0.0)
var int dMin = NB
var int dMax = -1
var int wMin = NB
var int wMax = -1
var float dBase = na
var float wBase = na
// history of virtual trades
var float[] hE  = array.new_float()
var float[] hS  = array.new_float()
var float[] hP  = array.new_float()
var float[] hT  = array.new_float()
var float[] hBk = array.new_float()
var int[]   hD  = array.new_int()
var int[]   hB  = array.new_int()
var int[]   hSt = array.new_int()
var int hWins = 0
var int hLoss = 0
var float hSumR = 0.0
// last-signal info
var line[] mapLn = array.new_line()
var label[] mapLb = array.new_label()
var int[]    lastBar = array.new_int(2, -1000000)
var float[]  lastF = array.new_float(8, na)
var string[] lastS = array.new_string(3, "")
var bool[]   lastB = array.new_bool(5, false)
var int lastDir = 0
 
bubLife = math.max(1, math.round(bubLifeMin * 60 / timeframe.in_seconds()))
 
// ================= functions (no ta.*, no request.* inside)
setLv(int i, float p) =>
    float old = array.get(lvP, i)
    bool chg = na(old) != na(p)
    if not na(old) and not na(p)
        chg := math.abs(p - old) > syminfo.mintick * 0.5
    if chg
        array.set(lvP, i, p)
        array.set(lvS, i, 0)
        array.set(lvD, i, close >= nz(p, close) ? 1 : -1)
    0
 
areaOf(int i, float tol, bool useB) =>
    float p = array.get(lvP, i)
    array.fill(fSeen, false)
    float cnt = 0.0
    float lo = p
    float hi = p
    for j = 0 to NL - 1
        float q = array.get(lvP, j)
        if not na(q)
            if math.abs(q - p) <= tol
                int f = array.get(lvF, j)
                if not array.get(fSeen, f)
                    array.set(fSeen, f, true)
                    cnt += 1.0
                lo := math.min(lo, q)
                hi := math.max(hi, q)
    if useB and array.size(dP) > 0
        for k = 0 to array.size(dP) - 1
            if array.get(dState, k) == 1 and bar_index - array.get(dB, k) <= bubLife and math.abs(array.get(dP, k) - p) <= tol
                if not array.get(fSeen, 12)
                    array.set(fSeen, 12, true)
                    cnt += 1.0
    array.set(arA, 0, lo)
    array.set(arA, 1, hi)
    cnt
 
dropOldest() =>
    label.delete(array.shift(dL))
    array.shift(dP)
    array.shift(dV)
    array.shift(dS)
    array.shift(dB)
    array.shift(dState)
    0
 
bubSize(float lots, float thr) =>
    float r = lots / thr
    r < 2.0 ? size.tiny : r < 4.0 ? size.small : size.normal
 
consider(int k, float cnt, float lo, float hi, float p, int idx) =>
    float cur = array.get(bC, k)
    if cnt > cur or (cnt == cur and math.abs(p - close) < math.abs(array.get(bP, k) - close))
        array.set(bC, k, cnt)
        array.set(bP, k, p)
        array.set(bLo, k, lo)
        array.set(bHi, k, hi)
        array.set(bI, k, idx)
    0.0
 
f_bin(float p, float base, float bin) =>
    math.max(0, math.min(NB - 1, int(math.round((p - base) / bin)) + HALF))
 
f_px(int idx, float base, float bin) =>
    base + (idx - HALF) * bin
 
vpAdd(float[] v, int i0, int i1, float vol) =>
    float share = vol / (i1 - i0 + 1)
    for j = i0 to i1
        array.set(v, j, array.get(v, j) + share)
    0
 
// POC = largest bin (lowest on ties); value area = 70% of volume grown from the POC one bin at a time toward the larger neighbour
vpCalc(float[] v, int i0, int i1) =>
    int poc = -1
    int hiI = -1
    int loI = -1
    if i1 >= i0 and i0 >= 0
        float tot = 0.0
        float mx = -1.0
        for j = i0 to i1
            float x = array.get(v, j)
            tot += x
            if x > mx
                mx := x
                poc := j
        if tot > 0
            float acc = mx
            hiI := poc
            loI := poc
            while acc < 0.7 * tot and (loI > i0 or hiI < i1)
                float up = -1.0
                if hiI < i1
                    up := array.get(v, hiI + 1)
                float dn = -1.0
                if loI > i0
                    dn := array.get(v, loI - 1)
                if up >= dn
                    hiI += 1
                    acc += up
                else
                    loI -= 1
                    acc += dn
        else
            poc := -1
    [poc, hiI, loI]
 
openCount(int d) =>
    int n = 0
    if array.size(hD) > 0
        for k = 0 to array.size(hD) - 1
            if array.get(hD, k) == d
                n += 1
    n
 
famCol(int f) =>
    f == 0 ? color.yellow : f == 1 ? color.orange : f == 2 ? color.new(color.orange, 20) : f == 3 ? color.new(color.yellow, 30) : f == 4 ? color.aqua : f == 5 ? color.fuchsia : f == 6 ? color.purple : f == 7 ? color.silver : f == 8 ? color.white : f == 9 ? color.new(color.blue, 10) : f == 10 ? color.red : f == 13 ? color.teal : color.lime
 
// ================= VIX / gamma (v1)
vix1  = request.security("CBOE:VIX", "D", close[1], lookahead=barmerge.lookahead_on)
vix0  = request.security("CBOE:VIX", "D", close[2], lookahead=barmerge.lookahead_on)
vix3m = request.security("CBOE:VIX3M", "D", close[1], lookahead=barmerge.lookahead_on)
vixAvg = request.security("CBOE:VIX", "D", ta.sma(close, 20)[1], lookahead=barmerge.lookahead_on)
vixC  = request.security("CBOE:VIX", "D", close, lookahead=barmerge.lookahead_on)
vixP  = request.security("CBOE:VIX", "D", close[1], lookahead=barmerge.lookahead_on)
vixPr = request.security("CBOE:VIX", "D", ta.percentrank(close, 252), lookahead=barmerge.lookahead_on)
backw = not na(vix1) and not na(vix3m) and vix1 > vix3m
spike = not na(vix1) and not na(vix0) and vix1 > vix0 * 1.08 and vix1 > vixAvg
gexRegime = gexRegimeIn == "auto (VIX proxy)" ? (backw or spike ? "negative (amplified)" : "positive (damped)") : gexRegimeIn
regimeSrc = gexRegimeIn == "auto (VIX proxy)" ? " (auto proxy)" : " (set by you)"
vixChg = vixC - vixP
vixTxt = na(vixC) ? "n/a" : str.tostring(vixC, "#.0") + (vixChg < 0 ? " v " : " ^ ") + str.tostring(math.abs(vixChg), "#.0") + " | pct " + str.tostring(vixPr, "#")
fl = gexFlip > 0 ? gexFlip + gexBasis : 0.0
cw = gexCall > 0 ? gexCall + gexBasis : 0.0
pw = gexPut > 0 ? gexPut + gexBasis : 0.0
 
// prior week H / L
[pwh, pwl] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead=barmerge.lookahead_on)
 
// ================= raw session state (updated with THIS bar; the slots are refreshed after the signals are read)
var float asH = na
var float asL = na
var float lonH = na
var float lonL = na
var float onH = na
var float onL = na
var float atmH = na
var float atmL = na
var float midO = na
var float opn = na
var float rthH = na
var float rthL = na
var float pdH = na
var float pdL = na
var float pdC = na
var float pdPoc = na
var float[] nodeHv = array.new_float()
var float[] nodeLv = array.new_float()
var float[] nv = array.new_float(2000, 0.0)
var float nvBase = na
[nvH, nvL, nvV] = request.security_lower_tf(syminfo.tickerid, "1", [high, low, volume])
var int nvMin = 2000
var int nvMax = -1
var float pdVah = na
var float pdVal = na
var float pwPoc = na
var float pwVah = na
var float pwVal = na
var float dvPoc = na
var float dvVah = na
var float dvVal = na
var float sumPV = 0.0
var float sumV = 0.0
var float vwapV = na
var int rthStartT = na
 
if newSess
    asH := high
    asL := low
    atmH := high
    atmL := low
    lonH := na
    lonL := na
    onH := na
    onL := na
    midO := na
    opn := na
else
    if inAsia
        asH := na(asH) ? high : math.max(asH, high)
        asL := na(asL) ? low : math.min(asL, low)
    if inAtm
        atmH := na(atmH) ? high : math.max(atmH, high)
        atmL := na(atmL) ? low : math.min(atmL, low)
    if inLondon
        lonH := na(lonH) ? high : math.max(lonH, high)
        lonL := na(lonL) ? low : math.min(lonL, low)
    if onWin
        onH := na(onH) ? high : math.max(onH, high)
        onL := na(onL) ? low : math.min(onL, low)
if hm < nz(hm[1], 0)
    midO := open
 
rthStart = inRth and not inRth[1]
rthEnd   = (not inRth) and inRth[1]
if rthStart
    rthH := high
    rthL := low
    opn := open
    sumPV := 0.0
    sumV := 0.0
    rthStartT := time
    array.fill(dv, 0.0)
    dMin := NB
    dMax := -1
    dBase := open
    dvPoc := na
    dvVah := na
    dvVal := na
if inRth
    rthH := math.max(nz(rthH, high), high)
    rthL := math.min(nz(rthL, low), low)
    sumPV += hlc3 * nz(volume)
    sumV += nz(volume)
    vwapV := sumV > 0 ? sumPV / sumV : na
    if na(wBase)
        wBase := open
    int d0 = f_bin(low, dBase, vpBin)
    int d1 = f_bin(high, dBase, vpBin)
    vpAdd(dv, d0, d1, nz(volume))
    dMin := math.min(dMin, d0)
    dMax := math.max(dMax, d1)
    int w0 = f_bin(low, wBase, vpBin * 4)
    int w1 = f_bin(high, wBase, vpBin * 4)
    vpAdd(wv, w0, w1, nz(volume))
    wMin := math.min(wMin, w0)
    wMax := math.max(wMax, w1)
 
// developing profile every bar (every 5th bar on 1m to bound the cost) and once at the RTH close for the prior-day profile
devEvery = timeframe.in_seconds() >= 300 ? 1 : 5
devReady = inRth and not na(rthStartT) and (time - rthStartT) >= devMinMin * 60000
calcNow  = (devReady and bar_index % devEvery == 0) or rthEnd
[dpI, dhI, dlI] = vpCalc(dv, calcNow ? dMin : 1, calcNow ? dMax : 0)
if calcNow and dpI >= 0 and not na(dBase)
    dvPoc := f_px(dpI, dBase, vpBin)
    dvVah := f_px(dhI, dBase, vpBin)
    dvVal := f_px(dlI, dBase, vpBin)
if rthEnd
    pdH := rthH
    pdL := rthL
    pdC := nz(close[1], close)
    if dpI >= 0 and not na(dBase)
        pdPoc := dvPoc
        pdVah := dvVah
        pdVal := dvVal
 
// new week: finalise the prior-week RTH profile, clear the accumulator
newWk = ta.change(time("W")) != 0
[wpI, whI, wlI] = vpCalc(wv, newWk ? wMin : 1, newWk ? wMax : 0)
if newWk
    if wpI >= 0 and not na(wBase)
        pwPoc := f_px(wpI, wBase, vpBin * 4)
        pwVah := f_px(whI, wBase, vpBin * 4)
        pwVal := f_px(wlI, wBase, vpBin * 4)
    array.fill(wv, 0.0)
    wMin := NB
    wMax := -1
    wBase := na
 
// ================= 5m swing structure (3 confirmed swing highs and lows, known at the prior close)
[ph5, pl5, pt5] = request.security(syminfo.tickerid, "5", [ta.pivothigh(high, 2, 2), ta.pivotlow(low, 2, 2), time], lookahead=barmerge.lookahead_off)
var float[] swHi = array.new_float()
var float[] swLo = array.new_float()
var int lastPivT = 0
if not na(pt5) and pt5 != lastPivT
    lastPivT := pt5
    if not na(ph5)
        array.push(swHi, ph5)
        if array.size(swHi) > 3
            array.shift(swHi)
    if not na(pl5)
        array.push(swLo, pl5)
        if array.size(swLo) > 3
            array.shift(swLo)
bool strDn = false
bool strUp = false
if array.size(swHi) == 3 and array.size(swLo) == 3
    strDn := array.get(swHi, 0) > array.get(swHi, 1) and array.get(swHi, 1) > array.get(swHi, 2) and array.get(swLo, 0) > array.get(swLo, 1) and array.get(swLo, 1) > array.get(swLo, 2)
    strUp := array.get(swHi, 0) < array.get(swHi, 1) and array.get(swHi, 1) < array.get(swHi, 2) and array.get(swLo, 0) < array.get(swLo, 1) and array.get(swLo, 1) < array.get(swLo, 2)
bool hhS = array.size(swHi) >= 2 and array.get(swHi, array.size(swHi) - 1) > array.get(swHi, array.size(swHi) - 2)
bool llL = array.size(swLo) >= 2 and array.get(swLo, array.size(swLo) - 1) < array.get(swLo, array.size(swLo) - 2)
strBlockL = (structOn and strDn) or (hhOn and llL)
strBlockS = (structOn and strUp) or (hhOn and hhS)
 
[ph30, pl30, pt30] = request.security(syminfo.tickerid, "30", [ta.pivothigh(high, 2, 2), ta.pivotlow(low, 2, 2), time], lookahead=barmerge.lookahead_off)
var float[] sw30H = array.new_float()
var float[] sw30L = array.new_float()
var int lastP30 = 0
if newSess
    array.clear(sw30H)
    array.clear(sw30L)
if not na(pt30) and pt30 != lastP30
    lastP30 := pt30
    if not na(ph30)
        array.push(sw30H, ph30)
        if array.size(sw30H) > 2
            array.shift(sw30H)
    if not na(pl30)
        array.push(sw30L, pl30)
        if array.size(sw30L) > 2
            array.shift(sw30L)
 
// ================= HTF FVGs (1h, 4h) from v1
var box[] bx1 = array.new_box()
var box[] bx4 = array.new_box()
var float[] lo1 = array.new_float()
var float[] hi1 = array.new_float()
var int[] dr1 = array.new_int()
var float[] lo4 = array.new_float()
var float[] hi4 = array.new_float()
var int[] dr4 = array.new_int()
[b1h, b1l, b1t, new1] = request.security(syminfo.tickerid, "60", [high[3], low[1], low[3], ta.change(time("60")) != 0 ? 1 : 0], lookahead=barmerge.lookahead_off)
[a1h, a1l, a1t, new1b] = request.security(syminfo.tickerid, "60", [high[1], low[3], high[3], ta.change(time("60")) != 0 ? 1 : 0], lookahead=barmerge.lookahead_off)
[b4h, b4l, b4t, new4] = request.security(syminfo.tickerid, "240", [high[3], low[1], low[3], ta.change(time("240")) != 0 ? 1 : 0], lookahead=barmerge.lookahead_off)
[a4h, a4l, a4t, new4b] = request.security(syminfo.tickerid, "240", [high[1], low[3], high[3], ta.change(time("240")) != 0 ? 1 : 0], lookahead=barmerge.lookahead_off)
addGap(boxes, los, his, drs, bot, top, dir, col) =>
    array.push(los, bot)
    array.push(his, top)
    array.push(drs, dir)
    array.push(boxes, box.new(bar_index, top, bar_index + 20, bot, bgcolor=color.new(col, 85), border_color=col, extend=extend.right))
    if array.size(boxes) > fvgMax
        box.delete(array.shift(boxes))
        array.shift(los)
        array.shift(his)
        array.shift(drs)
if showHtfFvg
    if new1 == 1 and b1l > b1h
        addGap(bx1, lo1, hi1, dr1, b1h, b1l, 1, color.green)
    if new1b == 1 and a1h < a1l
        addGap(bx1, lo1, hi1, dr1, a1h, a1l, -1, color.red)
    if new4 == 1 and b4l > b4h
        addGap(bx4, lo4, hi4, dr4, b4h, b4l, 1, color.teal)
    if new4b == 1 and a4h < a4l
        addGap(bx4, lo4, hi4, dr4, a4h, a4l, -1, color.maroon)
mitigate(boxes, los, his, drs) =>
    i = array.size(boxes) - 1
    while i >= 0
        d = array.get(drs, i)
        if (d == 1 and close < array.get(los, i)) or (d == -1 and close > array.get(his, i))
            box.delete(array.get(boxes, i))
            array.remove(boxes, i)
            array.remove(los, i)
            array.remove(his, i)
            array.remove(drs, i)
        i -= 1
mitigate(bx1, lo1, hi1, dr1)
mitigate(bx4, lo4, hi4, dr4)
inGap(los, his, drs, dir, px) =>
    r = false
    if array.size(los) > 0
        for i = 0 to array.size(los) - 1
            r := r or (array.get(drs, i) == dir and px >= array.get(los, i) and px <= array.get(his, i))
    r
 
// ================= chart-timeframe patterns: FVG, iFVG inversion (v1), CISD
fvgUp = low > high[2]
fvgDn = high < low[2]
var float bullBot = na
var float bearTop = na
if low > high[2] and close[1] > open[1]
    bullBot := high[2]
if high < low[2] and close[1] < open[1]
    bearTop := low[2]
shortInv = not na(bullBot) and close < bullBot and close[1] >= bullBot
longInv  = not na(bearTop) and close > bearTop and close[1] <= bearTop
if shortInv
    bullBot := na
if longInv
    bearTop := na
int rdn = 0
int rup = 0
bool runD = true
bool runU = true
for k = 1 to 8
    if runD and close[k] < open[k]
        rdn := k
    else
        runD := false
    if runU and close[k] > open[k]
        rup := k
    else
        runU := false
cisdL = rdn >= 2 and close > open and close > open[rdn]
cisdS = rup >= 2 and close < open and close < open[rup]
ifL = nz(ta.barssince(longInv), 999) <= confN
ifS = nz(ta.barssince(shortInv), 999) <= confN
cdL = nz(ta.barssince(cisdL), 999) <= confN
cdS = nz(ta.barssince(cisdS), 999) <= confN
confL = confirmReq == "off" or (confirmReq == "iFVG" and ifL) or (confirmReq == "CISD" and cdL) or (confirmReq == "either" and (ifL or cdL))
confS = confirmReq == "off" or (confirmReq == "iFVG" and ifS) or (confirmReq == "CISD" and cdS) or (confirmReq == "either" and (ifS or cdS))
 
// ================= STEP 1: read the map as it stood at the PRIOR close, with THIS bar's prices
lo3 = ta.lowest(low, 3)
hi3 = ta.highest(high, 3)
cl3 = ta.lowest(close, 3)
ch3 = ta.highest(close, 3)
chHi = ta.highest(high, 60)[1]
chLo = ta.lowest(low, 60)[1]
chR  = chHi - chLo
chopOn = not na(chR) and med > 0 and chR < chopMult * med
volX = volume / ta.sma(volume, 20)[1]
var float sOpen = na
var int sBar = na
bool sStart = (hm == 1080 or hm == 180 or hm == 570) and hm != nz(hm[1], -1)
if sStart or na(sOpen)
    sOpen := open
    sBar := bar_index
sAge = bar_index - nz(sBar, bar_index)
drv = close[1] - nz(sOpen, close)
var float sH = na
var float sL = na
var int sHB = na
var int sLB = na
if sStart or na(sH)
    sH := high
    sL := low
    sHB := bar_index
    sLB := bar_index
else
    if high > sH
        sH := high
        sHB := bar_index
    if low < sL
        sL := low
        sLB := bar_index
sessHiAgo = bar_index - sHB
sessLoAgo = bar_index - sLB
absE = volume > 2.0 * ta.sma(volume, 20)[1] and (high - low) < 0.6 * ta.sma(high - low, 20)[1]
absRecent = absE or absE[1] or absE[2]
driveUp = driveOn and sAge >= 15 and drv >= 4 * med and sessHiAgo <= 10
driveDn = driveOn and sAge >= 15 and -drv >= 4 * med and sessLoAgo <= 10
v30 = math.sum(volume, 30)[1]
v30avg = ta.sma(v30, 2000)
deadTape = deadOn and not na(v30avg) and v30 < 0.5 * v30avg and chopOn
bodyUp = (close - open) >= dispK * med
bodyDn = (open - close) >= dispK * med
tolA = areaTol * med
thr  = brkMult * med
 
//  1. per-second bars of the PARENT symbol (request.security_lower_tf, "1S"): a second's side = close vs open (vs the prior second's close on a tie; the first second of a bar with a tie is skipped);
//  2. same-side seconds are summed per price tick (the second's close) inside the chart bar; a sum >= the lot threshold is a big print at that price;
//  3. no seconds data on the plan / history: request.footprint rows of the chart symbol (buy or sell volume at a price row >= threshold; MNQ/MES chart contracts / 10 = parent lots).
isEs   = str.contains(str.upper(bigSym), "ES1")
bigThr = isEs ? float(bigEsLots) : (inRth ? float(bigNyLots) : float(bigOffLots))
fpMult = (syminfo.root == "MNQ" or syminfo.root == "MES") ? 10.0 : 1.0
footprint fp = request.footprint(fpTicks, 70, 300)
float buyV = na
float sellV = na
if not na(fp)
    buyV := fp.buy_volume()
    sellV := fp.sell_volume()
float fpTot = buyV + sellV
[sC, sO, sV] = request.security_lower_tf(bigSym, "1S", [close, open, volume])
 
array.clear(agP)
array.clear(agV)
array.clear(agS)
int nSec = array.size(sV)
if showBubbles
    if nSec > 0
        for i = 0 to nSec - 1
            float vv = nz(array.get(sV, i))
            if vv > 0
                float c0 = array.get(sC, i)
                float o0 = array.get(sO, i)
                int sd = 0
                if c0 > o0
                    sd := 1
                else if c0 < o0
                    sd := -1
                else if i > 0
                    float pc = array.get(sC, i - 1)
                    sd := c0 > pc ? 1 : c0 < pc ? -1 : 0
                if sd != 0 and vv >= secMult * bigThr
                    float pk = math.round(c0 / syminfo.mintick) * syminfo.mintick
                    int fi = -1
                    if array.size(agP) > 0
                        for j = 0 to array.size(agP) - 1
                            if fi < 0 and array.get(agS, j) == sd
                                fi := j
                    if fi < 0
                        array.push(agP, pk)
                        array.push(agV, vv)
                        array.push(agS, sd)
                    else if vv > array.get(agV, fi)
                        array.set(agP, fi, pk)
                        array.set(agV, fi, vv)
    else if not na(fp)
        for row in fp.rows()
            float px = (row.up_price() + row.down_price()) / 2
            float br = row.buy_volume() / fpMult
            float sr = row.sell_volume() / fpMult
            for sdx = 0 to 1
                float vr = sdx == 0 ? br : sr
                int sgn = sdx == 0 ? 1 : -1
                if vr >= bigThr
                    int fj = -1
                    if array.size(agP) > 0
                        for j = 0 to array.size(agP) - 1
                            if fj < 0 and array.get(agS, j) == sgn
                                fj := j
                    if fj < 0
                        array.push(agP, px)
                        array.push(agV, vr)
                        array.push(agS, sgn)
                    else if vr > array.get(agV, fj)
                        array.set(agP, fj, px)
                        array.set(agV, fj, vr)
 
// 1. judge the pending bubbles with this bar (reads: the bar just closed), 2. then add this bar's prints
bool defBuyAr = false
bool defSellAr = false
if showBubbles and barstate.isconfirmed and med > 0 and array.size(dP) > 0
    for k = array.size(dP) - 1 to 0
        if array.get(dState, k) == 0 and bar_index > array.get(dB, k)
            float px0 = array.get(dP, k)
            int sb0 = array.get(dS, k)
            float lots0 = array.get(dV, k)
            bool thru = sb0 > 0 ? low < px0 - bubThru * med : high > px0 + bubThru * med
            label lb0 = array.get(dL, k)
            if thru
                if greyRun
                    array.set(dL, k, label.new(array.get(dB, k), px0, "", style=label.style_circle, color=color.new(color.gray, 85), size=size.tiny))
                    array.set(dState, k, 2)
                else
                    if not na(lb0)
                        label.delete(lb0)
                    array.remove(dP, k)
                    array.remove(dV, k)
                    array.remove(dS, k)
                    array.remove(dB, k)
                    array.remove(dState, k)
                    array.remove(dL, k)
            else if bar_index - array.get(dB, k) >= bubBars
                array.set(dState, k, 1)
                array.set(dL, k, label.new(array.get(dB, k), px0, "", style=label.style_circle, color=color.new(sb0 > 0 ? color.lime : color.red, 35), size=bubSize(lots0, bigThr), tooltip=str.tostring(lots0, "#") + " lots " + (sb0 > 0 ? "buy" : "sell") + " @ " + str.tostring(px0, "#.00") + " DEFENDED"))
                bool atAr = false
                for i = 0 to NL - 1
                    float q = array.get(lvP, i)
                    if not atAr and not na(q) and math.abs(q - px0) <= tolA
                        if areaOf(i, tolA, true) >= minArea
                            atAr := true
                if atAr
                    if sb0 > 0
                        defBuyAr := true
                    else
                        defSellAr := true
if showBubbles and barstate.isconfirmed and array.size(agP) > 0
    for j = 0 to array.size(agP) - 1
        float lots = array.get(agV, j)
        if lots >= bigThr
            int sd2 = array.get(agS, j)
            float px2 = array.get(agP, j)
            label lb = na
            array.push(dP, px2)
            array.push(dV, lots)
            array.push(dS, sd2)
            array.push(dB, bar_index)
            array.push(dState, 0)
            array.push(dL, lb)
            if array.size(dP) > bubMax
                dropOldest()
 
array.fill(bC, 0.0)
array.fill(bP, 0.0)
array.fill(bLo, 0.0)
array.fill(bHi, 0.0)
array.fill(bI, 0.0)
bool took = false
for i = 0 to NL - 1
    float p = array.get(lvP, i)
    if not na(p) and med > 0
        int sd = array.get(lvD, i)
        float ex = (close - p) * sd
        if thr > 0 and ex <= -thr
            array.set(lvS, i, 1)
            array.set(lvD, i, -sd)
        else if ex > 0 and (sd > 0 ? low <= p : high >= p)
            array.set(lvS, i, 2)
        int hl = array.get(lvHL, i)
        int fam = array.get(lvF, i)
        bool frm = (fam == 4 and inAsia) or (fam == 5 and inLondon) or (fam == 6 and onWin)
        if hl != 0 and not frm
            took := took or (hl > 0 ? high >= p : low <= p)
        if p >= lo3 - tolA and p <= hi3 + tolA
            float cnt = areaOf(i, tolA, true)
            float aLo = array.get(arA, 0)
            float aHi = array.get(arA, 1)
            if cnt >= minArea
                if lo3 < aLo - syminfo.mintick and cl3 >= aLo and bodyUp and close > math.max(high[1], high[2])
                    consider(0, cnt, aLo, aHi, p, i)
                if hi3 > aHi + syminfo.mintick and ch3 <= aHi and bodyDn and close < math.min(low[1], low[2])
                    consider(1, cnt, aLo, aHi, p, i)
                if close > aHi and close[1] <= aHi and fvgUp and bodyUp
                    consider(2, cnt, aLo, aHi, p, i)
                if close < aLo and close[1] >= aLo and fvgDn and bodyDn
                    consider(3, cnt, aLo, aHi, p, i)
 
var int lastTake = na
if took
    lastTake := time
freshTake = not na(lastTake) and (time - lastTake) <= freshMin * 60000
 
// ---- the signal builder: stop, TP1, destination, checks, plan box, history. Returns true when a plan with a destination exists.
fire(int dir, string kind, float ext, float cnt, float p, bool cf1, bool cf2, int ix) =>
    bool ok = false
    float entry = close
    float stop = dir > 0 ? ext - padPts : ext + padPts
    float minRisk = minStopMed * med
    float risk = (entry - stop) * dir
    if risk < minRisk
        stop := entry - dir * minRisk
        risk := minRisk
    if pocStop
        for i = 0 to NL - 1
            if i == 1 or i == 4 or i == 19 or i == 21
                float q0 = array.get(lvP, i)
                if not na(q0)
                    float d0 = (entry - q0) * dir
                    if d0 > 0 and d0 <= risk + med
                        risk := math.max(risk, d0 + med)
                        stop := entry - dir * risk
    float need = math.max(minRR * risk, minTgtPts)
    float best = 1e10
    int bi = -1
    for i = 0 to NL - 1
        float q = array.get(lvP, i)
        if not na(q)
            float d = (q - entry) * dir
            bool infoOnly = i == 4 or i == 19 or (i >= 23 and i <= 25)
            if d >= need and d < best and not infoOnly
                best := d
                bi := i
    if asiaSweep and kind == "RESPECT"
        int tj = dir < 0 and ix == 11 ? 12 : dir < 0 and ix == 15 ? 16 : dir > 0 and ix == 12 ? 11 : dir > 0 and ix == 16 ? 15 : -1
        if tj >= 0
            float qs = array.get(lvP, tj)
            if not na(qs) and (qs - entry) * dir >= risk
                best := (qs - entry) * dir
                bi := tj
    if bi >= 0
        float tp1 = entry + dir * best / 2
        if tp1Mode == "halfway area -> target"
            float tA = (p + entry + dir * best) / 2
            if (tA - entry) * dir > syminfo.mintick
                tp1 := tA
        float tgt = entry + dir * best
        float rr = best / risk
        bool c1 = freshTake
        bool c2 = inGap(lo1, hi1, dr1, dir, ext) or inGap(lo4, hi4, dr4, dir, ext)
        bool c3 = cnt >= 3
        bool c4 = volX >= volMult
        bool c5 = not macro
        int sc = (c1 ? 1 : 0) + (c2 ? 1 : 0) + (c3 ? 1 : 0) + (c4 ? 1 : 0) + (c5 ? 1 : 0)
        if sc >= minScore and (not winOn or botWin)
            ok := true
            string tag = (cf1 ? " +iFVG" : "") + (cf2 ? " +CISD" : "")
            string area = cnt >= 3 ? "A+" : "A"
            string tnm = array.get(lvN, bi)
            array.set(lastF, 0, entry)
            array.set(lastF, 1, stop)
            array.set(lastF, 2, tp1)
            array.set(lastF, 3, tgt)
            array.set(lastF, 4, rr)
            array.set(lastF, 5, cnt)
            array.set(lastF, 6, risk)
            array.set(lastS, 0, kind + tag)
            array.set(lastS, 1, tnm)
            array.set(lastB, 0, c1)
            array.set(lastB, 1, c2)
            array.set(lastB, 2, c3)
            array.set(lastB, 3, c4)
            array.set(lastB, 4, c5)
            array.set(lastBar, dir > 0 ? 0 : 1, bar_index)
            array.push(hE, entry)
            array.push(hS, stop)
            array.push(hP, tp1)
            array.push(hT, tgt)
            array.push(hBk, 0.0)
            array.push(hD, dir)
            array.push(hB, bar_index)
            array.push(hSt, 0)
    ok
 
// ---- pending DISRESPECT breaks: cancel on a pullback inside 3 bars, a close back through the far edge, or age
var bool pendL = false
var float pLHi = na
var float pLLo = na
var float pLP = na
var float pLC = na
var int pLBar = na
var bool pendS = false
var float pSHi = na
var float pSLo = na
var float pSP = na
var float pSC = na
var int pSBar = na
if pendL
    int ageL = bar_index - pLBar
    if close < pLLo or ageL > retestMax or (ageL <= 3 and close <= pLHi)
        pendL := false
if pendS
    int ageS = bar_index - pSBar
    if close > pSHi or ageS > retestMax or (ageS <= 3 and close >= pSLo)
        pendS := false
 
pocLike(int i) =>
    i == 1 or i == 4 or i == 19 or i == 21
chopBlk(float p, int i) =>
    bool r = false
    if chopOn
        if pocLike(i)
            r := p >= chLo and p <= chHi
        else
            r := p >= chLo + 0.25 * chR and p <= chLo + 0.75 * chR
    r
 
cdBars = math.max(1, math.round(cooldownMin * 60 / timeframe.in_seconds()))
okL = (not oneAtATime or openCount(1) == 0) and bar_index - array.get(lastBar, 0) > cdBars
okS = (not oneAtATime or openCount(-1) == 0) and bar_index - array.get(lastBar, 1) > cdBars
gate = barstate.isconfirmed and not first5 and med > 0 and bar_index > 70 and not deadTape
 
bool sigRL = false
bool sigRS = false
bool sigDL = false
bool sigDS = false
bool fired = false
// RESPECT long / short
if useRespect and gate and not fired and okL and not strBlockL and confL and array.get(bC, 0) >= minArea
    int ix = int(array.get(bI, 0))
    if not chopBlk(array.get(bP, 0), ix) and not (noPocEnt and pocLike(ix)) and not (driveDn and not absRecent)
        sigRL := fire(1, "RESPECT", math.min(lo3, array.get(bLo, 0)), array.get(bC, 0), array.get(bP, 0), ifL, cdL, ix)
        fired := sigRL
if useRespect and gate and not fired and okS and not strBlockS and confS and array.get(bC, 1) >= minArea
    int ix = int(array.get(bI, 1))
    if not chopBlk(array.get(bP, 1), ix) and not (noPocEnt and pocLike(ix)) and not (driveUp and not absRecent)
        sigRS := fire(-1, "RESPECT", math.max(hi3, array.get(bHi, 1)), array.get(bC, 1), array.get(bP, 1), ifS, cdS, ix)
        fired := sigRS
// DISRESPECT: retest of the broken area after the 3-bar hold
if useDisresp and gate and not fired and pendL and okL and not strBlockL and (bar_index - pLBar) > 3
    if low <= pLHi + tolA and close > pLHi and close > open and not chopBlk(pLP, 0)
        sigDL := fire(1, "DISRESPECT", math.min(pLLo, low), pLC, pLP, ifL, cdL, -1)
        fired := sigDL
        if sigDL
            pendL := false
if useDisresp and gate and not fired and pendS and okS and not strBlockS and (bar_index - pSBar) > 3
    if high >= pSLo - tolA and close < pSLo and close < open and not chopBlk(pSP, 0)
        sigDS := fire(-1, "DISRESPECT", math.max(pSHi, high), pSC, pSP, ifS, cdS, -1)
        fired := sigDS
        if sigDS
            pendS := false
// arm new breaks (a signal fires only on the retest, never on the break bar)
if useDisresp and barstate.isconfirmed and not pendL and array.get(bC, 2) >= minArea
    pendL := true
    pLHi := array.get(bHi, 2)
    pLLo := array.get(bLo, 2)
    pLP := array.get(bP, 2)
    pLC := array.get(bC, 2)
    pLBar := bar_index
if useDisresp and barstate.isconfirmed and not pendS and array.get(bC, 3) >= minArea
    pendS := true
    pSHi := array.get(bHi, 3)
    pSLo := array.get(bLo, 3)
    pSP := array.get(bP, 3)
    pSC := array.get(bC, 3)
    pSBar := bar_index
if sigRL or sigDL
    lastDir := 1
if sigRS or sigDS
    lastDir := -1
 
// ================= virtual trade ledger: stop first on a shared bar; at TP1 half comes off and the stop moves to BE from the NEXT bar
if array.size(hE) > 0
    for k = array.size(hE) - 1 to 0
        float e0 = array.get(hE, k)
        float s0 = array.get(hS, k)
        float p0 = array.get(hP, k)
        float t0 = array.get(hT, k)
        float bk = array.get(hBk, k)
        int dd = array.get(hD, k)
        int b0 = array.get(hB, k)
        int stg = array.get(hSt, k)
        if bar_index > b0
            float r0 = math.abs(e0 - s0)
            bool done = false
            float res = 0.0
            if stg == 0
                bool stopHit = dd > 0 ? low <= s0 : high >= s0
                bool tp1Hit = dd > 0 ? high >= p0 : low <= p0
                if stopHit
                    res := -1.0
                    done := true
                else if tp1Hit
                    array.set(hSt, k, 1)
                    array.set(hBk, k, 0.5 * math.abs(p0 - e0) / r0)
            else
                bool beHit = dd > 0 ? low <= e0 : high >= e0
                bool tgHit = dd > 0 ? high >= t0 : low <= t0
                if beHit
                    res := bk
                    done := true
                else if tgHit
                    res := bk + 0.5 * math.abs(t0 - e0) / r0
                    done := true
            if not done and bar_index - b0 > 600
                res := stg == 1 ? bk + 0.5 * (close - e0) * dd / r0 : (close - e0) * dd / r0
                done := true
            if done
                hSumR += res
                if res > 0
                    hWins += 1
                else if res < 0
                    hLoss += 1
                if false
                    label.new(bar_index, close, (res >= 0 ? "+" : "") + str.tostring(res, "#.0") + "R", style=dd > 0 ? label.style_label_down : label.style_label_up, color=res > 0 ? color.new(color.green, 40) : res < 0 ? color.new(color.red, 40) : color.new(color.gray, 40), textcolor=color.white, size=size.small)
                array.remove(hE, k)
                array.remove(hS, k)
                array.remove(hP, k)
                array.remove(hT, k)
                array.remove(hBk, k)
                array.remove(hD, k)
                array.remove(hB, k)
                array.remove(hSt, k)
 
var line pocLn = na
var label pocLb = na
if barstate.islast
    line.delete(pocLn)
    label.delete(pocLb)
    if false
        pocLn := line.new(bar_index - 300, pdPoc, bar_index + 15, pdPoc, color=color.new(color.orange, 0), style=line.style_dashed, width=1)
        pocLb := label.new(bar_index + 15, pdPoc, "PD POC " + str.tostring(pdPoc, format.mintick), style=label.style_none, textcolor=color.orange, size=size.normal)
 
// ================= STEP 2: refresh the slots with this bar's raw state (a changed price resets BROKEN / HELD)
setLv(0, float(na))
setLv(1, float(na))
setLv(2, float(na))
setLv(3, float(na))
setLv(4, float(na))
setLv(5, float(na))
setLv(6, float(na))
setLv(7, float(na))
setLv(8, float(na))
setLv(9, float(na))
setLv(10, float(na))
setLv(11, showSess ? asH : float(na))
setLv(12, showSess ? asL : float(na))
setLv(13, showSess ? lonH : float(na))
setLv(14, showSess ? lonL : float(na))
setLv(15, showSess ? onH : float(na))
setLv(16, showSess ? onL : float(na))
setLv(17, float(na))
setLv(18, float(na))
setLv(19, float(na))
setLv(20, float(na))
setLv(21, float(na))
setLv(22, float(na))
setLv(23, float(na))
setLv(24, float(na))
setLv(25, float(na))
setLv(26, float(na))
setLv(27, float(na))
setLv(28, float(na))
setLv(29, float(na))
setLv(30, float(na))
setLv(31, float(na))
 
// ================= order flow: REAL bar delta from the footprint (Real Delta Dots), else the lower-timeframe up/down approximation
[c1m, o1m, v1m] = request.security_lower_tf(syminfo.tickerid, deltaTf, [close, open, volume])
approxDelta = 0.0
if array.size(c1m) > 0
    for i = 0 to array.size(c1m) - 1
        approxDelta += (array.get(c1m, i) > array.get(o1m, i) ? 1 : array.get(c1m, i) < array.get(o1m, i) ? -1 : 0) * array.get(v1m, i)
haveFp = not na(fpTot)
barDelta = haveFp ? buyV - sellV : approxDelta
totVol = haveFp ? fpTot : nz(volume)
var float cumDelta = 0.0
if ta.change(time("D")) != 0 or na(cumDelta)
    cumDelta := 0.0
cumDelta += barDelta
deltaShare = totVol > 0 ? barDelta / totVol : 0.0
avgVol = ta.sma(totVol, 20)[1]
absorb = showAbsorb and totVol > 2.0 * avgVol and (high - low) < 0.6 * ta.sma(high - low, 20)[1]
bigBar = showBarDots and totVol >= bigMult * avgVol
plotshape(bigBar and barDelta > 0, "legacy big buying bar", shape.circle, location.belowbar, color.new(color.lime, 0), size=size.small, display = display.pane)
plotshape(bigBar and barDelta < 0, "legacy big selling bar", shape.circle, location.abovebar, color.new(color.red, 0), size=size.small, display = display.pane)
if bigBar and barDelta > 0
    label.new(bar_index, low, str.tostring(math.abs(barDelta), "#"), style=label.style_label_up, color=color.new(color.lime, 100), textcolor=color.lime, size=size.normal)
if bigBar and barDelta < 0
    label.new(bar_index, high, str.tostring(math.abs(barDelta), "#"), style=label.style_label_down, color=color.new(color.red, 100), textcolor=color.red, size=size.normal)
plotshape(absorb, "absorption", shape.diamond, location.belowbar, color.new(color.gray, 20), size=size.tiny, display = display.pane)
divBull = low <= ta.lowest(low, 20)[1] and barDelta > 0
divBear = high >= ta.highest(high, 20)[1] and barDelta < 0
plotshape(divBull, "delta divergence (bull)", shape.circle, location.belowbar, color.new(color.lime, 30), size=size.tiny, display = display.pane)
plotshape(divBear, "delta divergence (bear)", shape.circle, location.abovebar, color.new(color.red, 30), size=size.tiny, display = display.pane)
gexSide = fl > 0 ? (close >= fl ? "above flip (damped)" : "below flip (amplified)") : gexRegime
 
// ================= draw the map on the last bar only (fresh objects each time: no stale lines, no label-limit eviction of the map)
if barstate.islast
    while array.size(mapLn) > 0
        line.delete(array.pop(mapLn))
    while array.size(mapLb) > 0
        label.delete(array.pop(mapLb))
    float tolD = areaTol * math.max(med, syminfo.mintick)
    float[] lbP = array.new_float()
    string[] lbT = array.new_string()
    color[] lbC = array.new_color()
    for i = 0 to NL - 1
        float p = array.get(lvP, i)
        if not na(p)
            int st = array.get(lvS, i)
            int fam = array.get(lvF, i)
            color col = famCol(fam)
            float cnt = areaOf(i, tolD, true)
            string ar = cnt >= 3 ? " A+" : cnt >= 2 ? " A" : ""
            string stx = st == 1 ? " BROKEN" : st == 2 ? " HELD" : ""
            array.push(mapLn, line.new(bar_index - mapLeft, p, bar_index, p, extend=extend.right, color=st == 1 ? color.new(col, 60) : col, style=st == 1 ? line.style_dashed : st == 2 ? line.style_solid : line.style_dotted, width=1))
            array.push(lbP, p)
            array.push(lbT, array.get(lvN, i) + stx + ar + " " + str.tostring(p, "#.00"))
            array.push(lbC, st == 1 ? color.new(col, 30) : col)
    // labels never print on top of each other
    if false
        // the visible price range (the bars on screen, at most 3000 back): a label is ~2.5% of the pane tall, so merge on that share, not on points
        float vHi = high
        float vLo = low
        for b = 0 to math.min(3000, bar_index)
            if time[b] < chart.left_visible_bar_time
                break
            vHi := math.max(vHi, high[b])
            vLo := math.min(vLo, low[b])
        for q = 0 to array.size(lbP) - 1
            float lp = array.get(lbP, q)
            if lp <= vHi * 1.02 and lp >= vLo * 0.98
                vHi := math.max(vHi, lp)
                vLo := math.min(vLo, lp)
        float stepPts = (vHi - vLo) * labMerge / 100.0
        int[] ix = array.sort_indices(lbP, order.ascending)
        // chart.right_visible_bar_time stops at the last REAL bar, so on the live edge the labels go labRight bars into the empty space at the right
        // (next to the price scale); scrolled back into history, they sit at the right edge of what is on screen
        bool scrolled = chart.right_visible_bar_time < time
        float yPrev = na
        for j = 0 to array.size(ix) - 1
            int q = array.get(ix, j)
            float pq = array.get(lbP, q)
            // a STACKED LADDER: each level keeps its own short label; one that would overlap the label below it is nudged up just enough
            float yq = na(yPrev) ? pq : math.max(pq, yPrev + stepPts)
            label lb = scrolled ? label.new(chart.right_visible_bar_time, yq, array.get(lbT, q), xloc=xloc.bar_time, style=label.style_label_lower_right, color=chart.bg_color, textcolor=array.get(lbC, q), size=labSize) : label.new(bar_index + labRight, yq, array.get(lbT, q), xloc=xloc.bar_index, style=label.style_label_lower_right, color=chart.bg_color, textcolor=array.get(lbC, q), size=labSize)
            array.push(mapLb, lb)
            yPrev := yq
 
// ================= table
showTable  = input.bool(false, "Full checklist table (off = one small SCORE line)", group="Sweep + Delivery", display = display.none)
var table T = table.new(position.top_right, 2, 28, bgcolor=color.new(color.black, 40), border_width=0)
tick(b) => b ? "YES" : "no"
cl(r, a, b, ca = color.white, cb = color.white) =>
    if showTable or r == 0
        table.cell(T, 0, r, a, text_color=ca, text_size=size.small)
        table.cell(T, 1, r, b, text_color=cb, text_size=size.small)
if barstate.islast
    int nHit = 0
    for k = 0 to 4
        nHit += array.get(lastB, k) ? 1 : 0
    cl(0, "Last signal: " + (lastDir > 0 ? "LONG " : lastDir < 0 ? "SHORT " : "-") + array.get(lastS, 0), "SCORE " + str.tostring(nHit) + " / 5", color.white, nHit >= 4 ? color.lime : nHit >= 3 ? color.yellow : color.red)
    cl(1, "Area (A=2 families, A+=3)", na(array.get(lastF, 5)) ? "-" : str.tostring(array.get(lastF, 5), "#") + " families", color.white, color.aqua)
    cl(2, "Pool taken < " + str.tostring(freshMin) + "m", tick(array.get(lastB, 0)), color.white, array.get(lastB, 0) ? color.lime : color.red)
    cl(3, "In a 1h/4h FVG (delivery)", tick(array.get(lastB, 1)), color.white, array.get(lastB, 1) ? color.lime : color.red)
    cl(4, "Area is A+ (3+ families)", tick(array.get(lastB, 2)), color.white, array.get(lastB, 2) ? color.lime : color.red)
    cl(5, "Volume >= " + str.tostring(volMult) + "x", tick(array.get(lastB, 3)), color.white, array.get(lastB, 3) ? color.lime : color.red)
    cl(6, "Outside xx:50-xx:10", tick(array.get(lastB, 4)), color.white, array.get(lastB, 4) ? color.lime : color.red)
    cl(7, "Plan: entry (signal close) / stop", na(array.get(lastF, 0)) ? "-" : str.tostring(array.get(lastF, 0), "#.00") + " / " + str.tostring(array.get(lastF, 1), "#.00") + " (" + str.tostring(array.get(lastF, 6), "#") + ")", color.white, color.white)
    cl(8, "TP1 / target", na(array.get(lastF, 2)) ? "-" : str.tostring(array.get(lastF, 2), "#.00") + " / " + str.tostring(array.get(lastF, 3), "#.00") + " " + array.get(lastS, 1), color.white, color.lime)
    cl(9, "R:R", na(array.get(lastF, 4)) ? "-" : str.tostring(array.get(lastF, 4), "#.0"), color.white, color.lime)
    cl(10, "Median 1m bar / stop floor", str.tostring(med, "#.00") + " / " + str.tostring(minStopMed * med, "#.0"), color.white, color.white)
    cl(11, "Chop (60-bar range < " + str.tostring(chopMult) + " bars)", chopOn ? "CHOP: edges only" : "no", color.white, chopOn ? color.orange : color.lime)
    cl(12, "5m structure", strDn ? "DOWN (no longs)" : strUp ? "UP (no shorts)" : "mixed", color.white, strDn ? color.red : strUp ? color.green : color.gray)
    cl(13, "Pending break (retest)", pendL ? "LONG retest" : pendS ? "SHORT retest" : "-", color.white, color.yellow)
    cl(14, "VIX (day chg | 252d pct)", vixTxt, color.white, vixChg < 0 ? color.lime : color.orange)
    cl(15, "Dealer gamma", gexRegime == "positive (damped)" ? "POSITIVE: damped, ping-pong value" + regimeSrc : "NEGATIVE: amplified, breaks run" + regimeSrc, color.white, gexRegime == "positive (damped)" ? color.lime : gexRegime == "negative (amplified)" ? color.red : color.gray)
    cl(16, "Price vs gamma flip", gexSide, color.white, color.aqua)
    cl(17, "Bar delta (up-down)", str.tostring(barDelta, "#") + " (" + str.tostring(deltaShare * 100, "#") + "%)", color.white, barDelta >= 0 ? color.lime : color.red)
    cl(18, "Session cum delta", str.tostring(cumDelta, "#"), color.white, cumDelta >= 0 ? color.lime : color.red)
    cl(19, "Delta divergence at 20-bar extreme", divBull ? "BULL" : divBear ? "BEAR" : "-", color.white, divBull ? color.lime : divBear ? color.red : color.gray)
    cl(20, "Past signals (half at TP1, BE, runner)", str.tostring(hWins) + " W / " + str.tostring(hLoss) + " L" + (hWins + hLoss > 0 ? " (" + str.tostring(100 * hWins / (hWins + hLoss), "#") + "%)" : "") + "  sumR " + str.tostring(hSumR, "#.0"), color.white, hSumR >= 0 ? color.lime : color.red)
    int nDef = 0
    int nPend = 0
    if array.size(dP) > 0
        for k = 0 to array.size(dP) - 1
            if array.get(dState, k) == 1 and bar_index - array.get(dB, k) <= bubLife
                nDef += 1
            if array.get(dState, k) == 0
                nPend += 1
    cl(21, "Big prints >= " + str.tostring(bigThr, "#") + " lots (" + (nSec > 0 ? "1S seconds" : haveFp ? "footprint rows" : "NO DATA") + ")", "DEFENDED " + str.tostring(nDef) + " | pending " + str.tostring(nPend), color.white, nDef > 0 ? color.aqua : color.gray)
    cl(24, "Delta source", haveFp ? "real (footprint)" : "approx (" + deltaTf + " up-down)", color.white, haveFp ? color.lime : color.orange)
    cl(22, "Bias / news / headlines", "read by hand", color.gray, color.gray)
    cl(25, "Drive (no fade against it)", driveUp ? "UP drive: no shorts" : driveDn ? "DOWN drive: no longs" : "-", color.white, driveUp ? color.green : driveDn ? color.red : color.gray)
    cl(26, "Dead tape (no volume + chop)", deadTape ? "DEAD: no trade" : "no", color.white, deadTape ? color.orange : color.lime)
    cl(23, "UNTESTED as edge - context only", "", color.orange, color.white)
 
// ================= alerts (one per signal type)
sigIfvg = ((sigRL or sigDL) and ifL) or ((sigRS or sigDS) and ifS)
sigCisd = ((sigRL or sigDL) and cdL) or ((sigRS or sigDS) and cdS)
alertcondition(sigRL, "RESPECT long", "Chicken Joe: RESPECT LONG at an area (sweep, close back, displacement).")
alertcondition(sigRS, "RESPECT short", "Chicken Joe: RESPECT SHORT at an area (sweep, close back, displacement).")
alertcondition(sigDL, "DISRESPECT long (retest)", "Chicken Joe: DISRESPECT LONG - broke up through an area with a new FVG, now retesting it.")
alertcondition(sigDS, "DISRESPECT short (retest)", "Chicken Joe: DISRESPECT SHORT - broke down through an area with a new FVG, now retesting it.")
alertcondition(defBuyAr, "Defended BUY bubble at an area", "Chicken Joe: a big BUY print held (price did not trade through it) at a map area.")
alertcondition(defSellAr, "Defended SELL bubble at an area", "Chicken Joe: a big SELL print held (price did not trade through it) at a map area.")
alertcondition(sigIfvg, "Signal with iFVG confirmation", "Chicken Joe: a signal printed with an iFVG inversion inside the confirmation window.")
alertcondition(sigCisd, "Signal with CISD confirmation", "Chicken Joe: a signal printed with a change in state of delivery inside the confirmation window.")
 
 
f_nodes(float[] v_, int mn, int mx, float base) =>
    // HVN: local max over +-5 rows, top 3 by volume, >= 5 rows apart
    int n = mx - mn + 1
    float[] sm = array.new_float(n, 0.0)
    float[] pos = array.new_float()
    for i = 0 to n - 1
        float acc = 0.0
        int cnt = 0
        for j = math.max(0, i - 1) to math.min(n - 1, i + 1)
            acc += array.get(v_, mn + j)
            cnt += 1
        array.set(sm, i, acc / cnt)
        if acc > 0
            array.push(pos, acc / cnt)
    float med = array.size(pos) > 0 ? array.median(pos) : 0.0
    float[] nlvP = array.new_float()
    float[] nlvS = array.new_float()
    for i = 2 to n - 3
        float v = array.get(sm, i)
        float wmin = v
        for j = i - 2 to i + 2
            wmin := math.min(wmin, array.get(sm, j))
        if v <= wmin and v < 0.35 * med
            float lft = 0.0
            for j = math.max(0, i - 5) to i - 1
                lft := math.max(lft, array.get(sm, j))
            float rgt = 0.0
            for j = i + 1 to math.min(n - 1, i + 5)
                rgt := math.max(rgt, array.get(sm, j))
            if lft >= 2 * v and rgt >= 2 * v
                array.push(nlvP, base + (mn + i - 1000))
                array.push(nlvS, v)
    float[] lvK = array.new_float()
    if array.size(nlvS) > 0
        int[] oL = array.sort_indices(nlvS, order.ascending)
        for k in oL
            float px = array.get(nlvP, k)
            bool ok = true
            for q in lvK
                if math.abs(q - px) <= 2
                    ok := false
            if ok and array.size(lvK) < 10
                array.push(lvK, px)
    float[] nhvP = array.new_float()
    float[] nhvS = array.new_float()
    for i = 0 to n - 1
        float v = array.get(sm, i)
        float wmax = 0.0
        for j = math.max(0, i - 5) to math.min(n - 1, i + 5)
            wmax := math.max(wmax, array.get(sm, j))
        if v > 0 and v >= wmax
            array.push(nhvP, base + (mn + i - 1000))
            array.push(nhvS, v)
    float[] hvK = array.new_float()
    if array.size(nhvS) > 0
        int[] oH = array.sort_indices(nhvS, order.descending)
        for k in oH
            float px = array.get(nhvP, k)
            bool ok = true
            for q in hvK
                if math.abs(q - px) < 5
                    ok := false
            if ok and array.size(hvK) < 3
                array.push(hvK, px)
    [hvK, lvK]
nvEt = hour(time, "America/New_York") * 60 + minute(time, "America/New_York")
nvSes = nvEt >= 570 and nvEt < 1020 ? 2 : nvEt >= 120 and nvEt < 570 ? 1 : 0
var float[] pnyHv = array.new_float()
var float[] pnyLv = array.new_float()
if nvSes != nz(nvSes[1], -1)
    if nz(nvSes[1], -1) == 2 and nvMax - nvMin >= 12 and not na(nvBase)
        [h_, l_] = f_nodes(nv, nvMin, nvMax, nvBase)
        pnyHv := h_
        pnyLv := l_
    array.fill(nv, 0.0)
    nvBase := math.round(open)
    nvMin := 2000
    nvMax := -1
if not na(nvBase)
    int m1 = array.size(nvH)
    if m1 > 0
        for q = 0 to m1 - 1
            int n0 = math.max(0, math.min(1999, int(math.round(array.get(nvL, q) - nvBase)) + 1000))
            int n1 = math.max(0, math.min(1999, int(math.round(array.get(nvH, q) - nvBase)) + 1000))
            vpAdd(nv, n0, n1, nz(array.get(nvV, q)))
            nvMin := math.min(nvMin, n0)
            nvMax := math.max(nvMax, n1)
// ================= LVN / HVN lines (current session + prior NY during NY), redrawn on the last bar
var line[] nodeLn = array.new_line()
var label[] nodeLb = array.new_label()
if barstate.islast
    for l in nodeLn
        line.delete(l)
    for b in nodeLb
        label.delete(b)
    array.clear(nodeLn)
    array.clear(nodeLb)
    if showNodes and nvMax - nvMin >= 12 and not na(nvBase)
        [hvK, lvK] = f_nodes(nv, nvMin, nvMax, nvBase)
        // lines for every node; labels merged onto one row when two nodes sit within 12 pts (no stacked text)
        float[] lbY = array.new_float()
        string[] lbT = array.new_string()
        color[] lbC = array.new_color()
        float[] allY = array.new_float()
        int[] allT = array.new_int()     // 0 HVN, 1 LVN, 2 pNY HVN, 3 pNY LVN
        for y in hvK
            array.push(allY, y)
            array.push(allT, 0)
        for y in lvK
            array.push(allY, y)
            array.push(allT, 1)
        if nvSes == 2
            for y in pnyHv
                array.push(allY, y)
                array.push(allT, 2)
            for y in pnyLv
                array.push(allY, y)
                array.push(allT, 3)
        for k = 0 to array.size(allY) - 1
            int tp = array.get(allT, k)
            bool isH = tp == 0 or tp == 2
            float y = array.get(allY, k)
            array.push(nodeLn, line.new(bar_index - 60, y, bar_index + 20, y, color=isH ? color.new(color.lime, 30) : color.new(color.gray, 20), style=isH ? line.style_solid : line.style_dotted, width=1))
            string t = (tp >= 2 ? "pNY " : "") + (isH ? "HVN " : "LVN ") + str.tostring(y, "#.00")
            int hit = -1
            for q = 0 to array.size(lbY) - 1
                if array.size(lbY) > 0 and math.abs(array.get(lbY, q) - y) < 12
                    hit := q
            if hit >= 0
                array.set(lbT, hit, array.get(lbT, hit) + " · " + t)
            else
                array.push(lbY, y)
                array.push(lbT, t)
                array.push(lbC, isH ? color.lime : color.silver)
        // session highs / lows: small text on the line, to the right of the HVN/LVN labels
        string[] sesN = array.from("Asia H", "Asia L", "London H", "London L", "ON H", "ON L")
        for si = 0 to 5
            float sp = array.get(lvP, 11 + si)
            if not na(sp)
                array.push(nodeLb, label.new(bar_index + 45, sp, array.get(sesN, si), style=label.style_label_left, color=color.new(color.black, 100), textcolor=famCol(array.get(lvF, 11 + si)), size=size.small))
        if array.size(lbY) > 0
            for q = 0 to array.size(lbY) - 1
                array.push(nodeLb, label.new(bar_index + 20, array.get(lbY, q), array.get(lbT, q), style=label.style_label_left, color=color.new(color.black, 100), textcolor=array.get(lbC, q), size=size.normal))

← 返回列表