Sphinx Compass: 1H Liquidity Sweeps & Premium/Discount

TheHermeticTrader · study · 1116 行 · 点赞 39 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.1
// Sphinx Compass
// v1.7 - Walls drawn as a box by default: a shaded zone of +/- 4 points
//   around the strike over the last 40 candles, out to the label. Height,
//   length and fill are settings; the tick and full-width line remain.
//
// v1.6.1 - LS labels tiny.
//
// v1.6 - Sweep marker renamed LS (liquidity sweep: LS, LS ITH / ITL, LS KEY)
//   and pinned to the left end of its sweep line - above it for a high,
//   below it for a low.
//
// v1.5 - Clean-up. Walls draw as a short tick in the label column with a
//   compact label (CW 0DTE 7650  $1.78B), nothing across the candles; full
//   width is optional. Resting liquidity more than one day budget from price
//   is not drawn. Envelope fills lighter, with a transparency setting. Sweep
//   markers sit clear of an ITH / ITL label on the same candle. Shorter
//   order-flow text in the panel. Gamma walls moved to the top of the
//   settings, so the string is the first thing in the list.
//
// v1.4 - Resting liquidity merged: same-side levels within 10 points (a
//   setting) draw as one pool at the extreme. A level just inside a key swing
//   is folded into it.
//
// v1.3.2 - Pinned to the chart's right price scale, so it can no longer
//   float on a scale of its own when price is dragged.
//
// v1.3.1 - compile fix: gamma wall variables renamed (g_pw clashed with the
//   prior-day candle wick).
//
// v1.3 - Resting liquidity labelled (BSL above highs, SSL below lows, ITH /
//   ITL tagged, price optional) and drawn much brighter: transparency, width
//   and line style are settings.
//
// v1.2 - Call / put wall read from the gamma string (same format as KVP):
//   the biggest-magnitude wall each side on this chart's symbol, from the
//   boards ticked. A manual price still overrides its side.
//
// v1.1 - Only the most recent sweep of a high and of a low stay on the chart.
//   OTE drawn as two lines by default: 50% equilibrium (dashed) and one OTE
//   level (70.5%, solid); the shaded band and extra level are optional.
//   Day candles sit closer to the label column.
//
// v1.0.1 - compile fix: the OTE draw and clear methods now return the OTE
//   object explicitly (CE10235, label vs void from the last if block).
//
// One clean read of the hourly picture:
//   WHERE   - the gold key swing high and low (the dealing range) and the
//             resting liquidity on the structure timeframe.
//   WHEN    - the 1H sweep: a candle that wicks through resting liquidity and
//             CLOSES back inside. A close through is a run, not a sweep.
//   WHICH   - premium / discount from the stretch envelope. Touching the upper
//             band is premium, the lower band discount, everything between is
//             neutral.
//   FLOW    - ITH / ITL labels. A close through the latest ITH turns order
//             flow bullish, through the latest ITL bearish.
//   ENTRY   - primary OTE on the key swing leg, secondary OTE on the latest
//             ITH / ITL leg.
//   SCOPE   - optional call wall and put wall, the daily range budget, and the
//             prior day and today drawn as candles to the right of price.
//
// Everything structural is read from CLOSED structure-timeframe candles, so
// nothing repaints. Use on charts at or below the structure timeframe.
//
//@version=6
indicator('Sphinx Compass', shorttitle = 'Compass', overlay = true, scale = scale.right, max_lines_count = 300, max_labels_count = 300, max_boxes_count = 60, max_bars_back = 1000)
 
// ============================================================
// === INPUTS ===
// ============================================================
g_gx = 'Gamma walls'
i_gx = input.bool(true, 'Show call wall / put wall', group = g_gx, tooltip = 'The single highest-magnitude call wall and put wall for this chart. Read from the gamma string, or entered by hand below (a manual price overrides the string for that side).', display = display.none)
i_gstr = input.string('', 'Gamma string', group = g_gx, tooltip = 'Same format as Sphinx KVP and DOL+G, pasted unchanged:\nSYM.DTE:F{flip}|N{net},{call},{put}|CW{strike[:mag[:oi]]},...|PW{...}\nSegments separated by ;\nThe segment for this chart (ES, NQ, RTY, GC) is used; the biggest-magnitude wall on each side across the boards ticked below is drawn. With no magnitudes in the string, the first listed wall is used.', display = display.none)
i_gb0 = input.bool(true, 'Boards: 0DTE', group = g_gx, inline = 'gb', display = display.none)
i_gb7 = input.bool(false, '7DTE', group = g_gx, inline = 'gb', display = display.none)
i_gb30 = input.bool(false, '30DTE', group = g_gx, inline = 'gb', display = display.none)
i_cw = input.float(0.0, 'Manual call wall', minval = 0, step = 0.25, group = g_gx, inline = 'cw', display = display.none)
i_cwm = input.float(0.0, 'size $M', minval = 0, group = g_gx, inline = 'cw', display = display.none)
i_pw = input.float(0.0, 'Manual put wall', minval = 0, step = 0.25, group = g_gx, inline = 'pw', display = display.none)
i_pwm = input.float(0.0, 'size $M', minval = 0, group = g_gx, inline = 'pw', display = display.none)
col_cw = input.color(#ef5350, 'Call', group = g_gx, inline = 'gc', display = display.none)
col_pw = input.color(#26a69a, 'Put', group = g_gx, inline = 'gc', display = display.none)
i_gx_w = input.int(2, 'width', minval = 1, maxval = 5, group = g_gx, inline = 'gc', display = display.none)
i_gx_mode = input.string('Box', 'Wall drawn as', options = ['Box', 'Label lane', 'Full width (faint)'], group = g_gx, tooltip = 'Box: a shaded zone around the strike over the recent candles, running out to the label. Label lane: a short bold tick in the label column only. Full width: a faint dashed line back across the chart.', display = display.none)
i_gx_bh = input.float(4.0, '  Box half-height (points)', minval = 0.25, step = 0.25, group = g_gx, inline = 'gxb', display = display.none)
i_gx_bl = input.int(40, 'length (bars)', minval = 5, maxval = 400, group = g_gx, inline = 'gxb', display = display.none)
i_gx_bt = input.int(80, '  Box fill transparency %', minval = 40, maxval = 98, group = g_gx, display = display.none)
 
g_st = 'Structure'
i_st_tf = input.string('1H', 'Structure timeframe', options = ['1H', '4H'], group = g_st, tooltip = 'The candles the key swings, ITH / ITL and sweeps are read from.', display = display.none)
i_st_def = input.string('ITH/ITL', 'Key swing definition', options = ['ITH/ITL', '3-candle swing'], group = g_st, tooltip = 'What the pullback must be to become the new opposite key swing after a break. ITH/ITL: an intermediate-term swing (a 3-candle swing with a lower swing high, or higher swing low, on each side). 3-candle swing: any swing.', display = display.none)
 
g_key = 'Key swings (gold)'
i_key = input.bool(true, 'Show key swing high / low', group = g_key, tooltip = 'One swing high and one swing low, read from the whole history. A swing only moves when it is taken (a wick counts): taking one side moves the other to the extreme of the leg that broke it, and the taken level stays, dashed, until a new swing forms beyond it.', display = display.none)
c_key = input.color(#ffd700, 'Colour', group = g_key, inline = 'ky', display = display.none)
i_key_w = input.int(2, 'width', group = g_key, minval = 1, maxval = 5, inline = 'ky', display = display.none)
 
g_it = 'ITH / ITL (order flow)'
i_it_lbl = input.bool(true, 'Label ITH / ITL', group = g_it, tooltip = 'ITH: a 3-candle swing high with a lower swing high on each side. ITL: a swing low with a higher swing low on each side. Each label prints when the next swing confirms it. An ITH or ITL on a gold key swing is not labelled - the gold line already marks it.', display = display.none)
i_it_max = input.int(10, '  Keep the most recent (each side)', group = g_it, minval = 1, maxval = 30, display = display.none)
c_ith = input.color(#ef5350, '  ITH', group = g_it, inline = 'it', display = display.none)
c_itl = input.color(#26a69a, 'ITL', group = g_it, inline = 'it', display = display.none)
i_it_mit = input.string('Fade', '  Taken labels', options = ['Fade', 'Remove'], group = g_it, display = display.none)
 
g_sw = '1H liquidity sweeps'
i_sw = input.bool(true, 'Mark sweeps', group = g_sw, tooltip = 'A structure candle that trades through resting liquidity (a swing high or low not yet taken) and CLOSES back inside it. The line runs from the swing to the sweep candle. Gold KEY SWEEP = the key swing was swept; ITH / ITL SWEEP = an intermediate-term swing; sweep = a minor 3-candle swing.', display = display.none)
i_pool = input.bool(true, 'Show resting liquidity', group = g_sw, tooltip = 'Dotted lines on swing highs and lows not yet traded through.', display = display.none)
i_pool_minor = input.bool(true, '  Include minor 3-candle swings', group = g_sw, tooltip = 'Off: only ITH / ITL and the key swings count as liquidity, for lines and sweeps.', display = display.none)
i_pool_max = input.int(5, '  Minor swings kept (each side)', group = g_sw, minval = 1, maxval = 20, display = display.none)
i_sw_run = input.bool(false, 'Also mark runs (closed through)', group = g_sw, display = display.none)
c_swh = input.color(#ff4081, 'High swept', group = g_sw, inline = 'sw', display = display.none)
c_swl = input.color(#00e5ff, 'Low swept', group = g_sw, inline = 'sw', display = display.none)
c_pool = input.color(#e0e0e0, 'Resting', group = g_sw, inline = 'sw', display = display.none)
i_pool_tr = input.int(15, 'Resting liquidity transparency %', minval = 0, maxval = 90, step = 5, group = g_sw, tooltip = '0 = solid. Applies to the lines and their labels. ITH / ITL lines use the ITH / ITL colours.', display = display.none)
i_pool_w = input.int(1, '  Line width', minval = 1, maxval = 4, group = g_sw, inline = 'pw', display = display.none)
i_pool_st = input.string('Dashed', 'style', options = ['Dashed', 'Dotted', 'Solid'], group = g_sw, inline = 'pw', display = display.none)
i_pool_lbl = input.bool(true, 'Label resting liquidity', group = g_sw, tooltip = 'BSL = buy-side liquidity, resting above a swing high (buy stops). SSL = sell-side liquidity, resting below a swing low (sell stops). ITH / ITL pools are tagged. Labels print just right of the last candle.', display = display.none)
i_pool_px = input.bool(true, '  Show price on the label', group = g_sw, display = display.none)
i_pool_reach = input.float(1.0, 'Only levels within (x day budget)', minval = 0, step = 0.1, group = g_sw, tooltip = 'Resting liquidity further from price than this many daily range budgets is not drawn - it is a draw for the week, not today. Sweeps are still marked. 0 = no limit.', display = display.none)
i_pool_mrg = input.float(10.0, 'Merge levels within (points)', minval = 0, step = 0.25, group = g_sw, tooltip = 'Resting liquidity on the same side within this distance is one pool: only the extreme is drawn (the highest BSL, the lowest SSL). A gold key swing counts as part of the cluster, so a pool just inside a key swing is not drawn. 0 = draw every level.', display = display.none)
 
g_bd = 'Envelope (premium / discount)'
i_bd_on = input.bool(true, 'Show envelope', group = g_bd, tooltip = 'An EMA on a fixed timeframe with zones a set number of ATR above and below. Price touching the upper zone is premium, the lower zone discount, anything between is neutral.', display = display.none)
i_bd_tf = input.string('60', '  Timeframe', options = ['15', '30', '60', '240'], group = g_bd, tooltip = 'Used on charts at or below this timeframe. Above it the chart timeframe is used.', display = display.none)
i_bd_blen = input.int(50, '  EMA length', minval = 5, maxval = 500, group = g_bd, display = display.none)
i_bd_alen = input.int(100, '  ATR length', minval = 10, maxval = 500, group = g_bd, display = display.none)
i_bd_ain = input.float(3.0, '  Zone inner edge (x ATR)', minval = 0.25, maxval = 15.0, step = 0.25, group = g_bd, tooltip = 'Touching this edge is premium (upper) or discount (lower).', display = display.none)
i_bd_aout = input.float(6.0, '  Zone outer edge (x ATR)', minval = 0.5, maxval = 20.0, step = 0.25, group = g_bd, display = display.none)
col_bd_up = input.color(#2962ff, 'Premium zone', group = g_bd, inline = 'bd', display = display.none)
col_bd_dn = input.color(#ff6d00, 'Discount zone', group = g_bd, inline = 'bd', display = display.none)
i_bd_mid = input.bool(true, 'Show the mean', group = g_bd, inline = 'bm', display = display.none)
col_bd_mid = input.color(#b0bec5, '', group = g_bd, inline = 'bm', display = display.none)
i_bd_midw = input.int(1, 'width', minval = 1, maxval = 6, group = g_bd, inline = 'bm', display = display.none)
i_bd_midop = input.int(60, 'opacity %', minval = 0, maxval = 100, step = 5, group = g_bd, inline = 'bm', display = display.none)
i_bd_fill = input.int(85, 'Zone fill transparency %', minval = 40, maxval = 98, group = g_bd, tooltip = 'Inner half of each zone. The outer half is 12 points more solid.', display = display.none)
i_bd_bg = input.bool(false, 'Tint the background in premium / discount', group = g_bd, display = display.none)
 
g_o1 = 'OTE primary (key swing leg)'
i_o1 = input.bool(true, 'Show primary OTE', group = g_o1, tooltip = 'Retracement of the gold key swing leg, measured back from the swing that formed last. When a key swing is taken, the leg runs to the extreme beyond it.', display = display.none)
i_ote_eq = input.float(0.5, 'Equilibrium', group = g_o1, minval = 0.1, maxval = 0.9, step = 0.01, display = display.none)
i_ote_lo = input.float(0.62, 'OTE band from', group = g_o1, minval = 0.1, maxval = 0.99, step = 0.005, inline = 'ob', display = display.none)
i_ote_hi = input.float(0.79, 'to', group = g_o1, minval = 0.1, maxval = 0.99, step = 0.005, inline = 'ob', display = display.none)
i_ote_mid = input.float(0.705, 'OTE level', group = g_o1, minval = 0.1, maxval = 0.99, step = 0.005, display = display.none)
i_ote_x = input.bool(false, 'Extra level', group = g_o1, inline = 'ox', display = display.none)
i_ote_xv = input.float(0.68, '', group = g_o1, minval = 0.1, maxval = 0.99, step = 0.005, inline = 'ox', display = display.none)
c_o1 = input.color(color.new(#ffd700, 90), 'Band', group = g_o1, inline = 'o1', display = display.none)
c_o1l = input.color(#ffd700, 'Lines', group = g_o1, inline = 'o1', display = display.none)
i_ote_box = input.bool(false, 'Shade the OTE band (both OTEs)', group = g_o1, tooltip = 'Off: just the 50% equilibrium and the single OTE line.', display = display.none)
 
g_o2 = 'OTE secondary (ITH / ITL leg)'
i_o2 = input.bool(true, 'Show secondary OTE', group = g_o2, tooltip = 'Same ratios as the primary, on the leg between the latest ITH and ITL. A leg up extends with new highs and is dropped if price trades below its ITL (mirror for a leg down).', display = display.none)
c_o2 = input.color(color.new(#90a4ae, 88), 'Band', group = g_o2, inline = 'o2', display = display.none)
c_o2l = input.color(#cfd8dc, 'Lines', group = g_o2, inline = 'o2', display = display.none)
 
 
g_rb = 'Range budget & day candles'
i_rb = input.bool(true, 'Daily range budget', group = g_rb, tooltip = 'How much of a typical session the day has already spent, from the 18:00 reopen.', display = display.none)
i_rb_len = input.int(20, '  Lookback (sessions)', minval = 3, maxval = 120, group = g_rb, display = display.none)
i_rb_method = input.string('EMA', '  Averaging', options = ['EMA', 'Median', 'Mean (SMA)'], group = g_rb, display = display.none)
i_rb_manual = input.float(0.0, '  Manual budget (points)', minval = 0, group = g_rb, tooltip = 'Zero uses the average.', display = display.none)
i_rb_proj = input.bool(true, '  Draw budget high / low', group = g_rb, tooltip = 'Where the session ends if it spends exactly one budget from its low, and from its high.', display = display.none)
c_proj = input.color(#78909c, '  Projection colour', group = g_rb, display = display.none)
i_gc = input.bool(true, 'Day candles (prior day + today)', group = g_rb, tooltip = 'Drawn in the space right of price. Today carries a faint ghost out to the budget high and low.', display = display.none)
i_gc_off = input.int(52, '  Start (bars right of price)', minval = 10, maxval = 400, group = g_rb, display = display.none)
i_gc_w = input.int(4, '  Candle width (bars)', minval = 1, maxval = 12, group = g_rb, display = display.none)
i_gc_sp = input.int(10, '  Spacing (bars)', minval = 3, maxval = 40, group = g_rb, display = display.none)
col_gc_up = input.color(#26a69a, '  Up', group = g_rb, inline = 'gcc', display = display.none)
col_gc_dn = input.color(#ef5350, 'Down', group = g_rb, inline = 'gcc', display = display.none)
col_gc_gh = input.color(#78909c, 'Ghost', group = g_rb, inline = 'gcc', display = display.none)
 
g_dp = 'Display'
i_lbl_off = input.int(30, 'Label column (bars right of price)', group = g_dp, minval = 5, maxval = 200, tooltip = 'Key level, wall, budget and OTE labels print this many bars right of the last candle.', display = display.none)
i_tbl = input.bool(true, 'Show panel', group = g_dp, display = display.none)
i_tbl_pos = input.string('Top Right', '  Position', options = ['Top Right', 'Top Left', 'Middle Right', 'Bottom Right', 'Bottom Left'], group = g_dp, display = display.none)
 
// ============================================================
// === STRUCTURE TIMEFRAME DATA (closed candles only) ===
// ============================================================
st_tf = i_st_tf == '4H' ? '240' : '60'
tfn = i_st_tf
st_itl = i_st_def == 'ITH/ITL'
[h1_h, h1_l, h1_c, h1_t] = request.security(syminfo.tickerid, st_tf, [high[1], low[1], close[1], time[1]], lookahead = barmerge.lookahead_on)
h1_new = timeframe.change(st_tf) and not na(h1_t)
lbl_x = time + i_lbl_off * timeframe.in_seconds() * 1000
lbl_x2 = time + (i_lbl_off + 16) * timeframe.in_seconds() * 1000
 
// ---- ITH / ITL: the middle of three consecutive 3-candle swings ----
_itF() =>
    float _ph = ta.pivothigh(high, 1, 1)
    float _pl = ta.pivotlow(low, 1, 1)
    int _pt = time[1]
    var float _h1 = na
    var float _h2 = na
    var float _h3 = na
    var int _ht2 = na
    var int _ht3 = na
    var float _l1 = na
    var float _l2 = na
    var float _l3 = na
    var int _lt2 = na
    var int _lt3 = na
    float _ith = na
    int _itht = na
    float _itl = na
    int _itlt = na
    if not na(_ph)
        _h1 := _h2
        _h2 := _h3
        _ht2 := _ht3
        _h3 := _ph
        _ht3 := _pt
        if not na(_h1) and _h2 > _h1 and _h2 > _h3
            _ith := _h2
            _itht := _ht2
    if not na(_pl)
        _l1 := _l2
        _l2 := _l3
        _lt2 := _lt3
        _l3 := _pl
        _lt3 := _pt
        if not na(_l1) and _l2 < _l1 and _l2 < _l3
            _itl := _l2
            _itlt := _lt2
    [_ith[1], _itht[1], _itl[1], _itlt[1]]
[it_h, it_ht, it_l, it_lt] = request.security(syminfo.tickerid, st_tf, _itF(), lookahead = barmerge.lookahead_on)
 
// ---- key swings: one high, one low, whole history ----
_keyF() =>
    float _ph = ta.pivothigh(high, 1, 1)
    float _pl = ta.pivotlow(low, 1, 1)
    int _pt = time[1]
    float _pvLo = math.min(low, low[1])
    int _pvLoT = low <= low[1] ? time : time[1]
    float _pvHi = math.max(high, high[1])
    int _pvHiT = high >= high[1] ? time : time[1]
    var float _h1 = na
    var float _h2 = na
    var float _h3 = na
    var int _ht2 = na
    var int _ht3 = na
    var float _l1 = na
    var float _l2 = na
    var float _l3 = na
    var int _lt2 = na
    var int _lt3 = na
    var float _loH2 = na
    var int _loH2T = na
    var float _loH3 = na
    var int _loH3T = na
    var float _hiL2 = na
    var int _hiL2T = na
    var float _hiL3 = na
    var int _hiL3T = na
    if not na(_loH2) and low < _loH2
        _loH2 := low
        _loH2T := time
    if not na(_loH3) and low < _loH3
        _loH3 := low
        _loH3T := time
    if not na(_hiL2) and high > _hiL2
        _hiL2 := high
        _hiL2T := time
    if not na(_hiL3) and high > _hiL3
        _hiL3 := high
        _hiL3T := time
    float _ith = na
    int _ithT = na
    float _itl = na
    int _itlT = na
    if not na(_ph)
        _h1 := _h2
        _h2 := _h3
        _ht2 := _ht3
        _loH2 := _loH3
        _loH2T := _loH3T
        _h3 := _ph
        _ht3 := _pt
        _loH3 := _pvLo
        _loH3T := _pvLoT
        if not na(_h1) and _h2 > _h1 and _h2 > _h3
            _ith := _h2
            _ithT := _ht2
    if not na(_pl)
        _l1 := _l2
        _l2 := _l3
        _lt2 := _lt3
        _hiL2 := _hiL3
        _hiL2T := _hiL3T
        _l3 := _pl
        _lt3 := _pt
        _hiL3 := _pvHi
        _hiL3T := _pvHiT
        if not na(_l1) and _l2 < _l1 and _l2 < _l3
            _itl := _l2
            _itlT := _lt2
    float _ch = st_itl ? _ith : _ph
    int _chT = st_itl ? _ithT : _pt
    float _cl = st_itl ? _itl : _pl
    int _clT = st_itl ? _itlT : _pt
    var float _sh = na
    var int _shT = na
    var bool _shTk = false
    var float _sl = na
    var int _slT = na
    var bool _slTk = false
    var float _legLo = na
    var int _legLoT = na
    var float _legHi = na
    var int _legHiT = na
    if na(_legLo) or low < _legLo
        _legLo := low
        _legLoT := time
    if na(_legHi) or high > _legHi
        _legHi := high
        _legHiT := time
    bool _takeH = not na(_sh) and not _shTk and high > _sh
    bool _takeL = not na(_sl) and not _slTk and low < _sl
    if _takeH
        _shTk := true
        _sl := _legLo
        _slT := _legLoT
        _slTk := false
        _legHi := high
        _legHiT := time
    else if _takeL
        _slTk := true
        _sh := _legHi
        _shT := _legHiT
        _shTk := false
        _legLo := low
        _legLoT := time
    if not na(_ch) and (na(_sh) or _shTk and _ch > _sh)
        _sh := _ch
        _shT := _chT
        _shTk := false
        _legLo := st_itl ? _loH2 : _loH3
        _legLoT := st_itl ? _loH2T : _loH3T
    if not na(_cl) and (na(_sl) or _slTk and _cl < _sl)
        _sl := _cl
        _slT := _clT
        _slTk := false
        _legHi := st_itl ? _hiL2 : _hiL3
        _legHiT := st_itl ? _hiL2T : _hiL3T
    [_sh[1], _shT[1], _shTk[1], _sl[1], _slT[1], _slTk[1]]
[k_sh, k_shT, k_shTk, k_sl, k_slT, k_slTk] = request.security(syminfo.tickerid, st_tf, _keyF(), lookahead = barmerge.lookahead_on)
 
_onKey(float y) =>
    i_key and (not na(k_sh) and math.abs(y - k_sh) < syminfo.mintick * 0.5 or not na(k_sl) and math.abs(y - k_sl) < syminfo.mintick * 0.5)
 
// ============================================================
// === LIQUIDITY POOLS AND SWEEPS ===
// ============================================================
// A pool is a structure-timeframe swing high or low not yet traded through.
// cls 1 = minor 3-candle swing, cls 2 = ITH / ITL.
type Pool
    float p
    int t
    bool hi
    int cls
    line ln
    label it
 
var Pool[] pools = array.new<Pool>()
var label[] poolLb = array.new_label()
var label[] itHist = array.new_label()
var bool[] itHistH = array.new_bool()
// only the most recent sweep of a high and of a low stay on the chart
var line[] swLnH = array.new_line()
var line[] swLnL = array.new_line()
var label swLbH = na
var label swLbL = na
var float[] hb_h = array.new_float()
var float[] hb_l = array.new_float()
var int[] hb_t = array.new_int()
 
// order flow: +1 after a close through the latest ITH, -1 through the latest ITL
var int of_dir = 0
var float of_lvl = na
// last sweep, for the panel
var string ls_txt = ''
var int ls_t = na
var bool ls_hi = false
// key swing state at the previous structure close
var bool kh_tk0 = false
var float kh_p0 = na
var bool kl_tk0 = false
var float kl_p0 = na
// latest confirmed ITH / ITL (secondary OTE leg)
var float last_ith = na
var int last_ith_t = na
var float last_itl = na
var int last_itl_t = na
var int it_last_ht = na
var int it_last_lt = na
 
bool ev_sw_hi = false
bool ev_sw_lo = false
bool ev_ksw_hi = false
bool ev_ksw_lo = false
bool ev_of = false
bool ev_it = false
 
_poolCol(Pool q) =>
    color.new(q.cls == 2 ? (q.hi ? c_ith : c_itl) : c_pool, i_pool_tr)
_poolSty() =>
    i_pool_st == 'Solid' ? line.style_solid : i_pool_st == 'Dotted' ? line.style_dotted : line.style_dashed
_poolVis(Pool q) =>
    q.cls == 2 or i_pool_minor
_retire(Pool q) =>
    if not na(q.ln)
        q.ln.delete()
    if not na(q.it)
        if i_it_mit == 'Remove'
            q.it.delete()
        else
            q.it.set_textcolor(color.new(color.gray, 55))
            itHist.push(q.it)
            itHistH.push(q.hi)
_mark(int x, float y, bool hi, string txt, color c, string sz) =>
    label.new(x, y, txt, xloc = xloc.bar_time, style = hi ? label.style_label_lower_left : label.style_label_upper_left, color = color.new(color.black, 100), textcolor = c, size = sz)
// replace one side's drawn sweep with this candle's lines and marker
_swap(line[] keep, line[] fresh) =>
    while keep.size() > 0
        keep.shift().delete()
    while fresh.size() > 0
        keep.push(fresh.shift())
 
if h1_new
    hb_h.push(h1_h)
    hb_l.push(h1_l)
    hb_t.push(h1_t)
    while hb_h.size() > 400
        hb_h.shift()
        hb_l.shift()
        hb_t.shift()
 
    // ---- 1. sweeps / runs of resting pools by the candle that just closed ----
    line[] tH = array.new_line()
    line[] tL = array.new_line()
    int bH = 0
    float bHp = na
    int bHt = na
    int bL = 0
    float bLp = na
    int bLt = na
    if pools.size() > 0
        for i = pools.size() - 1 to 0
            Pool q = pools.get(i)
            bool hit = q.hi ? h1_h > q.p : h1_l < q.p
            if hit
                bool back = q.hi ? h1_c < q.p : h1_c > q.p
                bool okP = _poolVis(q) and not _onKey(q.p)
                if back and okP and i_sw
                    line _swl = line.new(q.t, q.p, h1_t, q.p, xloc = xloc.bar_time, color = q.hi ? c_swh : c_swl, width = q.cls == 2 ? 2 : 1, style = line.style_solid)
                    if q.hi
                        tH.push(_swl)
                    else
                        tL.push(_swl)
                    if q.hi and (q.cls > bH or q.cls == bH and q.p > nz(bHp))
                        bH := q.cls
                        bHp := q.p
                        bHt := q.t
                    if not q.hi and (q.cls > bL or q.cls == bL and q.p < nz(bLp, 1e12))
                        bL := q.cls
                        bLp := q.p
                        bLt := q.t
                if not back and okP and i_sw and i_sw_run
                    line _swl = line.new(q.t, q.p, h1_t, q.p, xloc = xloc.bar_time, color = color.new(q.hi ? c_swh : c_swl, 65), width = 1, style = line.style_dashed)
                    if q.hi
                        tH.push(_swl)
                    else
                        tL.push(_swl)
                if not back and q.cls == 2
                    int nd = q.hi ? 1 : -1
                    if nd != of_dir
                        ev_of := true
                    of_dir := nd
                    of_lvl := q.p
                _retire(q)
                pools.remove(i)
 
    // ---- 2. key swings taken on this candle ----
    bool kTkH = i_key and k_shTk and not (kh_tk0 and kh_p0 == k_sh) and not na(k_sh)
    bool kTkL = i_key and k_slTk and not (kl_tk0 and kl_p0 == k_sl) and not na(k_sl)
    bool kSwH = kTkH and h1_c < k_sh
    bool kSwL = kTkL and h1_c > k_sl
    if i_sw and not na(k_shT) and (kSwH or kTkH and i_sw_run)
        tH.push(line.new(k_shT, k_sh, h1_t, k_sh, xloc = xloc.bar_time, color = kSwH ? c_key : color.new(c_key, 65), width = kSwH ? 2 : 1, style = kSwH ? line.style_solid : line.style_dashed))
    if i_sw and not na(k_slT) and (kSwL or kTkL and i_sw_run)
        tL.push(line.new(k_slT, k_sl, h1_t, k_sl, xloc = xloc.bar_time, color = kSwL ? c_key : color.new(c_key, 65), width = kSwL ? 2 : 1, style = kSwL ? line.style_solid : line.style_dashed))
    kh_tk0 := k_shTk
    kh_p0 := k_sh
    kl_tk0 := k_slTk
    kl_p0 := k_sl
 
    // ---- 3. one marker per side, the most significant level; it replaces the previous one ----
    if i_sw
        label mH = na
        label mL = na
        if kSwH
            mH := _mark(nz(k_shT, h1_t), k_sh, true, 'LS KEY', c_key, size.tiny)
            ev_ksw_hi := true
            ls_txt := tfn + ' key high ' + str.tostring(k_sh, format.mintick)
        else if bH > 0
            mH := _mark(bHt, bHp, true, bH == 2 ? 'LS ITH' : 'LS', c_swh, size.tiny)
            ls_txt := tfn + (bH == 2 ? ' ITH ' : ' high ') + str.tostring(bHp, format.mintick)
        else if kTkH and i_sw_run
            mH := _mark(nz(k_shT, h1_t), k_sh, true, 'key run', color.new(c_key, 40), size.tiny)
        if kSwL
            mL := _mark(nz(k_slT, h1_t), k_sl, false, 'LS KEY', c_key, size.tiny)
            ev_ksw_lo := true
            ls_txt := tfn + ' key low ' + str.tostring(k_sl, format.mintick)
        else if bL > 0
            mL := _mark(bLt, bLp, false, bL == 2 ? 'LS ITL' : 'LS', c_swl, size.tiny)
            ls_txt := tfn + (bL == 2 ? ' ITL ' : ' low ') + str.tostring(bLp, format.mintick)
        else if kTkL and i_sw_run
            mL := _mark(nz(k_slT, h1_t), k_sl, false, 'key run', color.new(c_key, 40), size.tiny)
        if not na(mH) or tH.size() > 0
            _swap(swLnH, tH)
            if not na(swLbH)
                swLbH.delete()
            swLbH := mH
        if not na(mL) or tL.size() > 0
            _swap(swLnL, tL)
            if not na(swLbL)
                swLbL.delete()
            swLbL := mL
        ev_sw_hi := kSwH or bH > 0
        ev_sw_lo := kSwL or bL > 0
        if ev_sw_hi or ev_sw_lo
            ls_t := h1_t
            ls_hi := ev_sw_hi and not ev_sw_lo
 
    // ---- 4. new 3-candle swing (middle of the last three closed candles) ----
    int n = hb_h.size()
    if n >= 3
        float mh = hb_h.get(n - 2)
        float ml = hb_l.get(n - 2)
        int mt = hb_t.get(n - 2)
        if mh > hb_h.get(n - 3) and mh >= hb_h.get(n - 1)
            Pool q = Pool.new(mh, mt, true, 1, line(na), label(na))
            if i_pool and i_pool_minor
                q.ln := line.new(mt, mh, h1_t, mh, xloc = xloc.bar_time, color = color.new(c_pool, i_pool_tr), width = i_pool_w, style = _poolSty())
            pools.push(q)
        if ml < hb_l.get(n - 3) and ml <= hb_l.get(n - 1)
            Pool q = Pool.new(ml, mt, false, 1, line(na), label(na))
            if i_pool and i_pool_minor
                q.ln := line.new(mt, ml, h1_t, ml, xloc = xloc.bar_time, color = color.new(c_pool, i_pool_tr), width = i_pool_w, style = _poolSty())
            pools.push(q)
 
    // ---- 5. ITH / ITL confirmations upgrade their pool ----
    for side = 0 to 1
        bool isH = side == 0
        float ip = isH ? it_h : it_l
        int itt = isH ? it_ht : it_lt
        int lastT = isH ? it_last_ht : it_last_lt
        if not na(ip) and not na(itt) and itt != nz(lastT)
            ev_it := true
            if isH
                it_last_ht := itt
                last_ith := ip
                last_ith_t := itt
            else
                it_last_lt := itt
                last_itl := ip
                last_itl_t := itt
            int fi = -1
            if pools.size() > 0
                for i = 0 to pools.size() - 1
                    Pool q = pools.get(i)
                    if q.hi == isH and q.t == itt
                        fi := i
                        break
            color tc = isH ? c_ith : c_itl
            string tx = isH ? 'ITH' : 'ITL'
            string st = isH ? label.style_label_down : label.style_label_up
            if fi >= 0
                Pool q = pools.get(fi)
                q.cls := 2
                if i_it_lbl
                    q.it := label.new(itt, ip, tx, xloc = xloc.bar_time, style = st, color = color.new(color.black, 100), textcolor = tc, size = size.tiny)
                if i_pool
                    if na(q.ln)
                        q.ln := line.new(itt, ip, h1_t, ip, xloc = xloc.bar_time, color = _poolCol(q), width = i_pool_w, style = _poolSty())
                    else
                        q.ln.set_color(_poolCol(q))
            else
                // not in the active list: taken already, or not caught as a 3-candle swing
                bool taken = false
                if hb_t.size() > 0
                    for k = hb_t.size() - 1 to 0
                        if hb_t.get(k) <= itt
                            break
                        if isH ? hb_h.get(k) > ip : hb_l.get(k) < ip
                            taken := true
                            break
                if taken
                    if i_it_lbl and i_it_mit == 'Fade'
                        itHist.push(label.new(itt, ip, tx, xloc = xloc.bar_time, style = st, color = color.new(color.black, 100), textcolor = color.new(color.gray, 55), size = size.tiny))
                        itHistH.push(isH)
                else
                    Pool q = Pool.new(ip, itt, isH, 2, line(na), label(na))
                    if i_it_lbl
                        q.it := label.new(itt, ip, tx, xloc = xloc.bar_time, style = st, color = color.new(color.black, 100), textcolor = tc, size = size.tiny)
                    if i_pool
                        q.ln := line.new(itt, ip, h1_t, ip, xloc = xloc.bar_time, color = _poolCol(q), width = i_pool_w, style = _poolSty())
                    pools.push(q)
 
    // ---- 6. caps: oldest minor swings and oldest ITH / ITL drop first ----
    for side = 0 to 1
        bool isH = side == 0
        for c = 1 to 2
            int cap = c == 1 ? i_pool_max : i_it_max
            int cnt = 0
            if pools.size() > 0
                for i = 0 to pools.size() - 1
                    Pool q = pools.get(i)
                    if q.hi == isH and q.cls == c
                        cnt += 1
            while cnt > cap
                int oi = -1
                for i = 0 to pools.size() - 1
                    Pool qo = pools.get(i)
                    if qo.hi == isH and qo.cls == c
                        oi := i
                        break
                if oi < 0
                    break
                Pool qx = pools.get(oi)
                if not na(qx.ln)
                    qx.ln.delete()
                if not na(qx.it)
                    qx.it.delete()
                pools.remove(oi)
                cnt -= 1
    while itHist.size() > i_it_max * 2
        itHist.shift().delete()
        itHistH.shift()
 
// ---- key swing lines ----
var line k_hln = na
var line k_lln = na
var label k_hlb = na
var label k_llb = na
_keyLine(line ln, float y, int x1, int x2, bool tk) =>
    line _l = ln
    string _sty = tk ? line.style_dashed : line.style_solid
    color _c = tk ? color.new(c_key, 50) : c_key
    if na(_l)
        _l := line.new(x1, y, x2, y, xloc = xloc.bar_time, color = _c, width = i_key_w, style = _sty)
    else
        _l.set_xy1(x1, y)
        _l.set_xy2(x2, y)
        _l.set_style(_sty)
        _l.set_color(_c)
    _l
_keyLabel(label lb, int x, float y, string txt, bool tk) =>
    label _b = lb
    color _c = tk ? color.new(c_key, 50) : c_key
    if na(_b)
        _b := label.new(x, y, txt, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = _c, size = size.small)
    else
        _b.set_xy(x, y)
        _b.set_text(txt)
        _b.set_textcolor(_c)
    _b
 
// ============================================================
// === ENVELOPE: PREMIUM / DISCOUNT ===
// ============================================================
_bdF() =>
    [ta.ema(close, i_bd_blen), ta.atr(i_bd_alen)]
_bdTf = timeframe.in_seconds() >= timeframe.in_seconds(i_bd_tf) ? timeframe.period : i_bd_tf
[bd_m, bd_a] = request.security(syminfo.tickerid, _bdTf, _bdF(), lookahead = barmerge.lookahead_off)
bd_ok = i_bd_on and not na(bd_m) and not na(bd_a) and bd_a > 0
bd_z = bd_ok ? (close - bd_m) / bd_a : na
up_in = bd_ok ? bd_m + i_bd_ain * bd_a : na
dn_in = bd_ok ? bd_m - i_bd_ain * bd_a : na
// +1 premium (touching the upper zone), -1 discount, 0 neutral
pd = not bd_ok ? 0 : high >= up_in ? 1 : low <= dn_in ? -1 : 0
_bdP(float k) =>
    bd_ok ? bd_m + k * bd_a : na
_bdMidK = (i_bd_ain + i_bd_aout) / 2.0
plot(bd_ok and i_bd_mid ? bd_m : na, 'Envelope mean', color = color.new(col_bd_mid, 100 - i_bd_midop), linewidth = i_bd_midw)
bd_u1 = plot(_bdP(i_bd_ain), 'Premium inner', color = color.new(col_bd_up, 60))
bd_u2 = plot(_bdP(_bdMidK), 'Premium middle', color = color.new(col_bd_up, 100))
bd_u3 = plot(_bdP(i_bd_aout), 'Premium outer', color = color.new(col_bd_up, 40))
bd_d1 = plot(_bdP(-i_bd_ain), 'Discount inner', color = color.new(col_bd_dn, 60))
bd_d2 = plot(_bdP(-_bdMidK), 'Discount middle', color = color.new(col_bd_dn, 100))
bd_d3 = plot(_bdP(-i_bd_aout), 'Discount outer', color = color.new(col_bd_dn, 40))
fill(bd_u1, bd_u2, color = color.new(col_bd_up, i_bd_fill), title = 'Premium, near half')
fill(bd_u2, bd_u3, color = color.new(col_bd_up, i_bd_fill - 12), title = 'Premium, far half')
fill(bd_d1, bd_d2, color = color.new(col_bd_dn, i_bd_fill), title = 'Discount, near half')
fill(bd_d2, bd_d3, color = color.new(col_bd_dn, i_bd_fill - 12), title = 'Discount, far half')
bgcolor(i_bd_bg and pd == 1 ? color.new(col_bd_up, 92) : i_bd_bg and pd == -1 ? color.new(col_bd_dn, 92) : na, title = 'Premium / discount tint')
 
// ============================================================
// === OTE: PRIMARY (key leg) AND SECONDARY (ITH / ITL leg) ===
// ============================================================
type Ote
    box bx
    line eq
    line md
    line xl
    label lb
 
method wipe(Ote o) =>
    if not na(o.bx)
        o.bx.delete()
        o.bx := box(na)
    if not na(o.eq)
        o.eq.delete()
        o.eq := line(na)
    if not na(o.md)
        o.md.delete()
        o.md := line(na)
    if not na(o.xl)
        o.xl.delete()
        o.xl := line(na)
    if not na(o.lb)
        o.lb.delete()
        o.lb := label(na)
    o
 
_oLvl(float hi, float lo, float r, bool up) =>
    up ? hi - r * (hi - lo) : lo + r * (hi - lo)
 
_oLine(line ln, float y, int x1, int x2, color c, string sty) =>
    line _l = ln
    if na(_l)
        _l := line.new(x1, y, x2, y, xloc = xloc.bar_time, color = c, width = 1, style = sty)
    else
        _l.set_xy1(x1, y)
        _l.set_xy2(x2, y)
        _l.set_color(c)
    _l
 
method draw(Ote o, float hi, float lo, bool up, int x1, color cb, color cl, string tag, int lx) =>
    if i_ote_box
        float b1 = _oLvl(hi, lo, i_ote_lo, up)
        float b2 = _oLvl(hi, lo, i_ote_hi, up)
        if na(o.bx)
            o.bx := box.new(x1, math.max(b1, b2), time, math.min(b1, b2), xloc = xloc.bar_time, bgcolor = cb, border_color = color.new(cl, 60), border_width = 1)
        else
            o.bx.set_lefttop(x1, math.max(b1, b2))
            o.bx.set_rightbottom(time, math.min(b1, b2))
    else if not na(o.bx)
        o.bx.delete()
        o.bx := box(na)
    o.eq := _oLine(o.eq, _oLvl(hi, lo, i_ote_eq, up), x1, time, color.new(cl, 30), line.style_dashed)
    o.md := _oLine(o.md, _oLvl(hi, lo, i_ote_mid, up), x1, time, cl, line.style_solid)
    if i_ote_x
        o.xl := _oLine(o.xl, _oLvl(hi, lo, i_ote_xv, up), x1, time, color.new(cl, 20), line.style_dotted)
    else if not na(o.xl)
        o.xl.delete()
        o.xl := line(na)
    float ly = _oLvl(hi, lo, i_ote_mid, up)
    string tx = tag + ' OTE ' + str.tostring(i_ote_mid * 100, '#.#') + '%  ' + str.tostring(ly, format.mintick)
    if na(o.lb)
        o.lb := label.new(lx, ly, tx, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = cl, size = size.tiny)
    else
        o.lb.set_xy(lx, ly)
        o.lb.set_text(tx)
    o
 
// primary leg: when a key swing is taken, run the leg to the extreme beyond it
var float kRunHi = na
var int kRunHiT = na
var float kRunLo = na
var int kRunLoT = na
if not k_shTk or na(k_sh)
    kRunHi := na
    kRunHiT := na
else
    if na(kRunHi)
        kRunHi := math.max(k_sh, nz(h1_h, high))
        kRunHiT := nz(h1_t, time)
    if high > kRunHi
        kRunHi := high
        kRunHiT := time
if not k_slTk or na(k_sl)
    kRunLo := na
    kRunLoT := na
else
    if na(kRunLo)
        kRunLo := math.min(k_sl, nz(h1_l, low))
        kRunLoT := nz(h1_t, time)
    if low < kRunLo
        kRunLo := low
        kRunLoT := time
p_hi = k_shTk and not na(kRunHi) ? kRunHi : k_sh
p_hiT = k_shTk and not na(kRunHi) ? kRunHiT : k_shT
p_lo = k_slTk and not na(kRunLo) ? kRunLo : k_sl
p_loT = k_slTk and not na(kRunLo) ? kRunLoT : k_slT
p_up = k_shTk ? true : k_slTk ? false : nz(k_shT) > nz(k_slT)
 
// secondary leg: latest ITH and ITL, extended by new extremes, dropped on failure
var float s_hi = na
var int s_hiT = na
var float s_lo = na
var int s_loT = na
var bool s_up = false
var bool s_ok = false
if ev_it and not na(last_ith) and not na(last_itl)
    s_up := last_ith_t > last_itl_t
    s_hi := last_ith
    s_hiT := last_ith_t
    s_lo := last_itl
    s_loT := last_itl_t
    s_ok := s_hi > s_lo
if s_ok
    if s_up
        if high > s_hi
            s_hi := high
            s_hiT := time
        if low < s_lo
            s_ok := false
    else
        if low < s_lo
            s_lo := low
            s_loT := time
        if high > s_hi
            s_ok := false
 
var Ote o1 = Ote.new(box(na), line(na), line(na), line(na), label(na))
var Ote o2 = Ote.new(box(na), line(na), line(na), line(na), label(na))
if barstate.islast
    if i_o1 and not na(p_hi) and not na(p_lo) and not na(p_hiT) and not na(p_loT) and p_hi > p_lo
        o1.draw(p_hi, p_lo, p_up, p_up ? p_hiT : p_loT, c_o1, c_o1l, 'Key', lbl_x)
    else
        o1.wipe()
    if i_o2 and s_ok and not na(s_hiT) and not na(s_loT)
        o2.draw(s_hi, s_lo, s_up, s_up ? s_hiT : s_loT, c_o2, c_o2l, 'ITH/ITL', lbl_x2)
    else
        o2.wipe()
 
// ============================================================
// === GAMMA WALLS ===
// ============================================================
// ---- gamma string: the single biggest call wall and put wall for this chart ----
_tkG = syminfo.ticker
gSym = str.contains(_tkG, 'RTY') or str.contains(_tkG, 'M2K') ? 'RTY' : str.contains(_tkG, 'NQ') ? 'NQ' : str.contains(_tkG, 'GC') ? 'GC' : str.contains(_tkG, 'ES') ? 'ES' : ''
var float gx_cw = na
var float gx_cwm = na
var string gx_cwb = ''
var float gx_pw = na
var float gx_pwm = na
var string gx_pwb = ''
if barstate.isfirst and gSym != '' and str.length(i_gstr) > 0
    float bestC = -1.0
    float bestP = -1.0
    _segs = str.split(str.replace_all(i_gstr, ' ', ''), ';')
    int _ns = _segs.size()
    if _ns > 0
        for _si = 0 to _ns - 1
            string _seg = _segs.get(_si)
            _cix = str.pos(_seg, ':')
            if not na(_cix) and _cix > 0
                _dpr = str.split(str.substring(_seg, 0, _cix), '.')
                if _dpr.size() >= 2 and _dpr.get(0) == gSym
                    string _dte = _dpr.get(1)
                    bool _on = _dte == '0' and i_gb0 or _dte == '7' and i_gb7 or _dte == '30' and i_gb30
                    if _on
                        _ppr = str.split(str.substring(_seg, _cix + 1), '|')
                        if _ppr.size() > 0
                            for _fi = 0 to _ppr.size() - 1
                                string _fld = _ppr.get(_fi)
                                bool _isC = str.startswith(_fld, 'CW')
                                bool _isP = str.startswith(_fld, 'PW')
                                if (_isC or _isP) and str.length(_fld) > 2
                                    _arr = str.split(str.substring(_fld, 2), ',')
                                    if _arr.size() > 0
                                        for _wi = 0 to _arr.size() - 1
                                            _tok = str.split(_arr.get(_wi), ':')
                                            float _v = str.tonumber(_tok.get(0))
                                            float _m = _tok.size() >= 2 ? math.abs(nz(str.tonumber(_tok.get(1)))) : 0.0
                                            // no magnitude: first listed wins (rank order)
                                            float _score = _m > 0 ? _m : _wi == 0 ? 0.0 : -1.0
                                            if not na(_v) and _v > 0
                                                if _isC and _score > bestC
                                                    bestC := _score
                                                    gx_cw := _v
                                                    gx_cwm := _m
                                                    gx_cwb := _dte
                                                if _isP and _score > bestP
                                                    bestP := _score
                                                    gx_pw := _v
                                                    gx_pwm := _m
                                                    gx_pwb := _dte
// manual price overrides the string for that side
w_cw = i_cw > 0 ? i_cw : nz(gx_cw)
w_cwm = i_cw > 0 ? i_cwm : nz(gx_cwm)
w_cwn = i_cw > 0 ? 'CW' : 'CW ' + gx_cwb + 'DTE'
w_pw = i_pw > 0 ? i_pw : nz(gx_pw)
w_pwm = i_pw > 0 ? i_pwm : nz(gx_pwm)
w_pwn = i_pw > 0 ? 'PW' : 'PW ' + gx_pwb + 'DTE'
var line cw_ln = na
var label cw_lb = na
var box cw_bx = na
var line pw_ln = na
var label pw_lb = na
var box pw_bx = na
_wall(line ln, label lb, box bx, float p, float m, string nm, color c) =>
    line _l = ln
    label _b = lb
    box _x = bx
    if not na(_l)
        _l.delete()
    if not na(_b)
        _b.delete()
    if not na(_x)
        _x.delete()
    _l := line(na)
    _b := label(na)
    _x := box(na)
    if i_gx and p > 0
        int bs = timeframe.in_seconds() * 1000
        string ms = m >= 1000 ? str.tostring(m / 1000, '#.##') + 'B' : str.tostring(m, '#') + 'M'
        string tx = nm + '  ' + str.tostring(p, format.mintick) + (m > 0 ? '  $' + ms : '')
        if i_gx_mode == 'Box'
            _x := box.new(time - i_gx_bl * bs, p + i_gx_bh, lbl_x - 2 * bs, p - i_gx_bh, xloc = xloc.bar_time, bgcolor = color.new(c, i_gx_bt), border_color = color.new(c, 25), border_width = 1)
        else if i_gx_mode == 'Label lane'
            _l := line.new(time + (i_lbl_off - 6) * bs, p, lbl_x, p, xloc = xloc.bar_time, color = c, width = i_gx_w + 1, style = line.style_solid)
        else
            _l := line.new(time - 300 * bs, p, lbl_x, p, xloc = xloc.bar_time, color = color.new(c, 60), width = 1, style = line.style_dashed)
        _b := label.new(lbl_x, p, tx, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = c, size = size.tiny)
    [_l, _b, _x]
if barstate.islast
    [a1, a2, a3] = _wall(cw_ln, cw_lb, cw_bx, w_cw, w_cwm, w_cwn, col_cw)
    cw_ln := a1
    cw_lb := a2
    cw_bx := a3
    [b1, b2, b3] = _wall(pw_ln, pw_lb, pw_bx, w_pw, w_pwm, w_pwn, col_pw)
    pw_ln := b1
    pw_lb := b2
    pw_bx := b3
 
// ============================================================
// === DAILY RANGE BUDGET + DAY CANDLES ===
// ============================================================
// The day starts at the 18:00 reopen (the CME daily bar).
rb_roll = timeframe.change('D')
var float rb_hi = na
var float rb_lo = na
var float rb_open = na
var int rb_t0 = na
if rb_roll or na(rb_hi)
    rb_hi := high
    rb_lo := low
    rb_open := open
    rb_t0 := time
else
    rb_hi := math.max(rb_hi, high)
    rb_lo := math.min(rb_lo, low)
_rbF() =>
    _r = high - low
    [ta.sma(_r, i_rb_len)[1], ta.percentile_nearest_rank(_r, i_rb_len, 50)[1], ta.ema(_r, i_rb_len)[1]]
[rb_mean, rb_med, rb_ema] = request.security(syminfo.tickerid, 'D', _rbF(), lookahead = barmerge.lookahead_on)
[pdh, pdl, pdo, pdc] = request.security(syminfo.tickerid, 'D', [high[1], low[1], open[1], close[1]], lookahead = barmerge.lookahead_on)
rb_auto = i_rb_method == 'Mean (SMA)' ? rb_mean : i_rb_method == 'Median' ? rb_med : rb_ema
rb_bud = i_rb_manual > 0 ? i_rb_manual : rb_auto
rb_ok = i_rb and not na(rb_bud) and rb_bud > 0 and not na(rb_hi)
rb_rng = rb_hi - rb_lo
rb_pct = rb_ok ? rb_rng / rb_bud * 100.0 : na
rb_pHi = rb_ok ? rb_lo + rb_bud : na
rb_pLo = rb_ok ? rb_hi - rb_bud : na
 
var line rp_h = na
var line rp_l = na
var label rp_hb = na
var label rp_lb = na
var line g_pw = na
var box g_pb = na
var label g_pl = na
var box g_gh = na
var line g_tw = na
var box g_tb = na
var label g_tl = na
_del(line l) =>
    if not na(l)
        l.delete()
    line(na)
_delB(box b) =>
    if not na(b)
        b.delete()
    box(na)
_delL(label b) =>
    if not na(b)
        b.delete()
    label(na)
if barstate.islast
    rp_h := _del(rp_h)
    rp_l := _del(rp_l)
    rp_hb := _delL(rp_hb)
    rp_lb := _delL(rp_lb)
    if rb_ok and i_rb_proj and not na(rb_t0)
        rp_h := line.new(rb_t0, rb_pHi, lbl_x, rb_pHi, xloc = xloc.bar_time, color = color.new(c_proj, 25), width = 1, style = line.style_dotted)
        rp_l := line.new(rb_t0, rb_pLo, lbl_x, rb_pLo, xloc = xloc.bar_time, color = color.new(c_proj, 25), width = 1, style = line.style_dotted)
        rp_hb := label.new(lbl_x, rb_pHi, 'Budget high ' + str.tostring(rb_pHi, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = c_proj, size = size.tiny)
        rp_lb := label.new(lbl_x, rb_pLo, 'Budget low ' + str.tostring(rb_pLo, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = c_proj, size = size.tiny)
    g_pw := _del(g_pw)
    g_pb := _delB(g_pb)
    g_pl := _delL(g_pl)
    g_gh := _delB(g_gh)
    g_tw := _del(g_tw)
    g_tb := _delB(g_tb)
    g_tl := _delL(g_tl)
    if i_gc
        int hw = math.max(1, int(i_gc_w / 2))
        int xa = bar_index + i_gc_off
        int xb = xa + i_gc_sp
        if not na(pdh) and not na(pdo) and not na(pdc)
            color pc = pdc >= pdo ? col_gc_up : col_gc_dn
            g_pw := line.new(xa, pdh, xa, pdl, color = color.new(pc, 20), width = 1)
            g_pb := box.new(xa - hw, math.max(pdo, pdc), xa + hw, math.min(pdo, pdc), bgcolor = color.new(pc, 55), border_color = color.new(pc, 10), border_width = 1)
            g_pl := label.new(xa, pdl, 'PD  ' + str.tostring(pdh - pdl, '#'), style = label.style_label_up, color = color.new(color.black, 100), textcolor = color.new(pc, 20), size = size.tiny)
        if not na(rb_hi) and not na(rb_open)
            color tc = close >= rb_open ? col_gc_up : col_gc_dn
            if rb_ok and rb_pHi > rb_pLo
                g_gh := box.new(xb - hw, rb_pHi, xb + hw, rb_pLo, bgcolor = color.new(col_gc_gh, 88), border_color = color.new(col_gc_gh, 60), border_width = 1)
            g_tw := line.new(xb, rb_hi, xb, rb_lo, color = color.new(tc, 20), width = 1)
            g_tb := box.new(xb - hw, math.max(rb_open, close), xb + hw, math.min(rb_open, close), bgcolor = color.new(tc, 45), border_color = tc, border_width = 1)
            g_tl := label.new(xb, math.min(rb_lo, nz(rb_pLo, rb_lo)), 'TD  ' + str.tostring(rb_rng, '#') + (rb_ok ? '  ' + str.tostring(rb_pct, '#') + '%' : ''), style = label.style_label_up, color = color.new(color.black, 100), textcolor = color.new(tc, 20), size = size.tiny)
 
// ============================================================
// === RESTING LIQUIDITY + KEY SWING DRAW (needs the budget) ===
// ============================================================
if barstate.islast
    // extend resting liquidity, hide anything sitting on a key swing
    while poolLb.size() > 0
        poolLb.shift().delete()
    int px2 = time + 3 * timeframe.in_seconds() * 1000
    // merge: a pool with a more extreme level on its side within the merge
    // distance (another visible pool or the key swing) is not drawn
    int np = pools.size()
    bool[] hid = array.new_bool(np, false)
    if np > 0
        for i = 0 to np - 1
            Pool q = pools.get(i)
            float kp = q.hi ? k_sh : k_sl
            if i_pool_reach > 0 and not na(rb_bud) and rb_bud > 0 and math.abs(q.p - close) > i_pool_reach * rb_bud
                hid.set(i, true)
            else if i_key and not na(kp) and (q.hi ? kp >= q.p : kp <= q.p) and math.abs(kp - q.p) <= i_pool_mrg
                hid.set(i, true)
            else if i_pool_mrg > 0
                for j = 0 to np - 1
                    Pool r = pools.get(j)
                    if j != i and r.hi == q.hi and _poolVis(r) and math.abs(r.p - q.p) <= i_pool_mrg
                        if (q.hi ? r.p > q.p : r.p < q.p) or r.p == q.p and j > i
                            hid.set(i, true)
                            break
    if np > 0
        for i = 0 to np - 1
            Pool q = pools.get(i)
            bool ok = _onKey(q.p) or hid.get(i)
            if not na(q.ln)
                q.ln.set_x2(px2)
                q.ln.set_color(ok ? color(na) : _poolCol(q))
                if i_pool_lbl and not ok
                    string tx = (q.hi ? 'BSL' : 'SSL') + (q.cls == 2 ? (q.hi ? ' ITH' : ' ITL') : '') + (i_pool_px ? '  ' + str.tostring(q.p, format.mintick) : '')
                    poolLb.push(label.new(px2, q.p, tx, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = _poolCol(q), size = size.tiny))
            if not na(q.it)
                q.it.set_text(_onKey(q.p) ? '' : q.hi ? 'ITH' : 'ITL')
    if itHist.size() > 0
        for i = 0 to itHist.size() - 1
            label b = itHist.get(i)
            b.set_text(_onKey(b.get_y()) ? '' : itHistH.get(i) ? 'ITH' : 'ITL')
    if i_key and not na(k_sh) and not na(k_shT)
        k_hln := _keyLine(k_hln, k_sh, k_shT, time, k_shTk)
        k_hlb := _keyLabel(k_hlb, lbl_x, k_sh, tfn + ' key high ' + str.tostring(k_sh, format.mintick) + (k_shTk ? '  taken' : ''), k_shTk)
    if i_key and not na(k_sl) and not na(k_slT)
        k_lln := _keyLine(k_lln, k_sl, k_slT, time, k_slTk)
        k_llb := _keyLabel(k_llb, lbl_x, k_sl, tfn + ' key low ' + str.tostring(k_sl, format.mintick) + (k_slTk ? '  taken' : ''), k_slTk)
 
// ============================================================
// === PANEL ===
// ============================================================
_pos(string s) =>
    s == 'Top Left' ? position.top_left : s == 'Middle Right' ? position.middle_right : s == 'Bottom Right' ? position.bottom_right : s == 'Bottom Left' ? position.bottom_left : position.top_right
var table tb = table.new(_pos(i_tbl_pos), 2, 6, bgcolor = color.new(#131722, 15), border_width = 1, border_color = color.new(color.gray, 70))
if barstate.islast and i_tbl
    color cg = color.new(color.gray, 25)
    table.cell(tb, 0, 0, 'Compass', text_color = c_key, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 0, tfn + (timeframe.in_seconds() > timeframe.in_seconds(st_tf) ? '  (chart above ' + tfn + ')' : ''), text_color = cg, text_size = size.small, text_halign = text.align_right)
    string zt = not bd_ok ? '-' : pd == 1 ? 'PREMIUM' : pd == -1 ? 'DISCOUNT' : 'Neutral'
    zt := bd_ok ? zt + '  ' + (bd_z >= 0 ? '+' : '') + str.tostring(bd_z, '#.0') + ' ATR' : zt
    color zc = pd == 1 ? col_bd_up : pd == -1 ? col_bd_dn : color.new(color.gray, 60)
    table.cell(tb, 0, 1, 'Zone', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 1, zt, text_color = color.white, bgcolor = color.new(zc, pd == 0 ? 80 : 35), text_size = size.small)
    string ot = of_dir == 1 ? 'Bullish  ITH ' + str.tostring(of_lvl, format.mintick) + ' broken' : of_dir == -1 ? 'Bearish  ITL ' + str.tostring(of_lvl, format.mintick) + ' broken' : '-'
    table.cell(tb, 0, 2, 'Order flow', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 2, ot, text_color = of_dir == 1 ? c_itl : of_dir == -1 ? c_ith : cg, text_size = size.small)
    string st = na(ls_t) ? '-' : ls_txt + '  ' + str.format_time(ls_t, 'EEE HH:mm', 'America/New_York')
    table.cell(tb, 0, 3, 'Last sweep', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 3, st, text_color = na(ls_t) ? cg : ls_hi ? c_swh : c_swl, text_size = size.small)
    color bc = not rb_ok ? color.new(color.gray, 60) : rb_pct >= 100 ? color.new(#ef5350, 35) : rb_pct >= 70 ? color.new(#f9a825, 35) : color.new(#26a69a, 35)
    table.cell(tb, 0, 4, 'Budget', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 4, rb_ok ? str.tostring(rb_rng, '#') + ' of ' + str.tostring(rb_bud, '#') + '  ' + str.tostring(rb_pct, '#') + '%' : '-', text_color = color.white, bgcolor = bc, text_size = size.small)
    table.cell(tb, 0, 5, 'Room up / dn', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 5, rb_ok ? str.tostring(math.max(0, rb_pHi - close), '#') + ' / ' + str.tostring(math.max(0, close - rb_pLo), '#') : '-', text_color = color.white, text_size = size.small)
 
// ============================================================
// === ALERTS ===
// ============================================================
alertcondition(ev_sw_hi, '1H sweep - high', 'Compass: structure candle swept a high and closed back below')
alertcondition(ev_sw_lo, '1H sweep - low', 'Compass: structure candle swept a low and closed back above')
alertcondition(ev_ksw_hi, 'KEY sweep - high', 'Compass: key swing high swept and closed back below')
alertcondition(ev_ksw_lo, 'KEY sweep - low', 'Compass: key swing low swept and closed back above')
alertcondition(pd == 1 and pd[1] != 1, 'Premium touch', 'Compass: price touched the premium zone')
alertcondition(pd == -1 and pd[1] != -1, 'Discount touch', 'Compass: price touched the discount zone')
alertcondition(ev_of, 'Order flow shift', 'Compass: order flow shifted (ITH / ITL closed through)')
 
plot(pd, 'Zone (+1 premium, -1 discount)', color = na, display = display.data_window)
plot(of_dir, 'Order flow', color = na, display = display.data_window)
plot(ev_sw_hi ? -1 : ev_sw_lo ? 1 : 0, 'Sweep', color = na, display = display.data_window)
plot(rb_pct, 'Budget %', color = na, display = display.data_window)

← 返回列表