Sphinx KVP - Key Levels, VIX & Psychology

TheHermeticTrader · study · 1385 行 · 点赞 21 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================
// Sphinx KVP - Key Levels, VIX & Psychology   v1.2.2
// ------------------------------------------------------------
// v1.2.2
//   - Exposure bars per wall, as in DOL+G: call exposure extends right
//     of a centre axis, put exposure left, both on one scale, with an
//     open interest bar at half height beneath. Square-root scaling by
//     default so one dominant strike does not flatten the rest. Bar
//     height follows the visible price range, so it holds at any zoom.
//     Needs inline magnitudes in the string (strike:mag:oi).
//
// v1.2.1
//   - STALE GAMMA. The export's T field (unix time) is read; if the
//     string predates the current 18:00 open, the 0DTE board has
//     expired. Its walls, flip and net GEX are dropped, the regime
//     falls back to the volatility read, and the panel says to paste
//     today's string. 7D / 30D walls are kept. Strings without a T
//     field can be dated with the 'Gamma string pasted on' input.
//   - Key zone radius has a floor in points, so a wall and a DOL level
//     a quarter point either side of the ATR-based radius no longer
//     switch a zone on and off.
//   - Losses and cooldown count per CME trading day (18:00 to 18:00),
//     not per calendar day. The checklist stays on the calendar date.
//   - DOL levels break as soon as price trades beyond them. A wick
//     through that comes back inside before the bar closes is still a
//     sweep; price currently beyond the level is a break, immediately.
//
// v1.2.0
//   - VIX SELF-CALIBRATES. Each completed 18:00 day records what
//     actually happened next to what the average day and VIX
//     predicted. From that the script learns:
//       * how much VIX usually over-prices the day on this chart,
//         and shows an adjusted expectation alongside the raw one;
//       * what a normal VIX / average-day ratio looks like, so
//         'bigger day than avg' fires only in the top 20% of recent
//         days rather than against a fixed 1.15.
//     Until 20 days are recorded it uses the fixed thresholds and
//     says 'calibrating'. Fixed mode remains selectable.
//   - Forecast check row: average error of the average day and of
//     VIX against the real range, so the lookback choice can be
//     judged on this instrument instead of assumed.
//   - Average day lookback back to 20, matching Range Budget.
//
// v1.1.0
//   - Panel rewritten in plain language. Same numbers, clearer names.
//   - Average day now defaults to a 30-day lookback.
//   - Power of 3 daily candles to the right of price: D-2, D-1 and
//     today, built from the 18:00 NY open, each with an open tick so
//     the move above and below the open reads at a glance.
//
// v1.0.2
//   - Inputs no longer print in the status line (display.none).
//     The gamma string alone ran across the chart and covered
//     the panel.
//
// v1.0.1
//   - FIX: inducement could pair a wall with liquidity inside its own
//     key zone (CW/PW 7745 -> 4hH 7747). The minimum gap is now the
//     larger of the tick setting and the confluence radius, so the
//     liquidity has to sit genuinely beyond the obvious level.
//   - Regime row flags when net GEX and flip side disagree, as in
//     DOL+G: 'NEG - walls break (net) ! flip POS'.
//
// v1.0.0
// One question per layer:
//   Range budget - how much of today's move is already paid for?
//   Volatility   - how big a day is the options market pricing?
//   Gamma / DOL  - where are the levels, and will dealers let
//                  price through them?
//   Psychology   - am I in a state to take the trade, and am I
//                  early?
//
// SELF-CONTAINED so it runs for users without Sphinx DOL+G or
// Sphinx Range Budget on the chart. The context math is a lean
// copy of both:
//   - Budget: 18:00 NY anchor, median DR of completed days,
//     constant intraday.
//   - Gamma: same string format as DOL+G, pasted unchanged. Only
//     the parse, regime resolution and level set are carried.
//     Magnitude bars, harvester and state boxes stay in DOL+G.
//   - DOL: same naked / swept / broken state machine. Asia runs
//     18:00-03:00 and London 03:00-08:30, matching Range Budget.
//
// DR REQUEST uses expr[1] with lookahead_on, so historical and
// realtime bars both read the DR through yesterday. Range Budget
// v2.3.1 uses [1] with lookahead_off, which on HISTORICAL bars
// reads one day further back. Realtime values agree.
//
// IMPLIED BUDGET locks at the 18:00 anchor from the last available
// print of the volatility index, which at 18:00 is the prior
// session close:  index / 100 / sqrt(252) x anchor open.
// Like the DR it does not move intraday.
//
// GAMMA IS OPTIONAL. With it off, or on with the string blank, the
// regime falls back to a volatility read (VIX9D/VIX term structure,
// implied/historical ratio, VVIX) and is labelled as such, and the
// budget projections stand in for walls when building key zones.
//
// INDUCEMENT IS STRUCTURAL, not a percentage. The nearest obvious
// level (a wall, or a DOL level) with a NAKED liquidity level
// beyond it, inside the remaining budget, is flagged. The zone ends
// when that liquidity is swept; a close back inside within the
// reclaim window is the event worth waiting for. If the budget
// cannot reach the liquidity, nothing is flagged - the obvious
// level may simply be the level.
//
// NO PRICE VERDICTS. Every prompt describes the operator's position
// relative to the context, never where price will go.
//
// PINE CANNOT SEE FILLS. Losses are logged by setting a time in the
// Losses group; the checklist counts only when its date is today.
// Alerts snapshot inputs when they are created, so cooldown and
// loss-limit states are on-chart only. Intraday charts only.
// ============================================================
 
indicator('Sphinx KVP - Key Levels, VIX & Psychology', 'Sphinx KVP', overlay = true, max_lines_count = 150, max_labels_count = 100, max_boxes_count = 150, max_bars_back = 2000)
 
TZ = 'America/New_York'
VER = 'v1.2.2'
 
// ============================================================
// === INPUTS ===
// ============================================================
g_b = 'Range Budget  (anchor 18:00 NY)'
i_method = input.string('Median', 'Average day method', options = ['Median', 'Mean (SMA)', 'EMA'], group = g_b, display = display.none)
i_len = input.int(20, 'Average day lookback (days)', minval = 3, maxval = 120, group = g_b, display = display.none)
i_manual = input.float(0.0, 'Manual DR override (points)', minval = 0, group = g_b, tooltip = 'Pin the denominator when a regime break has outrun the window. Zero disables.', display = display.none)
i_warn = input.float(70.0, 'Caution above (% used)', minval = 1, group = g_b, display = display.none)
i_exh = input.float(100.0, 'Exhausted above (% used)', minval = 1, group = g_b, display = display.none)
i_room = input.string('DR (historical)', 'Room and reach measured against', options = ['DR (historical)', 'Implied (VIX)', 'Larger of the two'], group = g_b, tooltip = 'Sets the projections, the Room row, whether a key zone is inside budget, and whether an inducement target is reachable. DR matches Sphinx Range Budget. Falls back to DR when no implied value is available.', display = display.none)
 
g_v = 'Volatility'
i_vix_on = input.bool(true, 'Use volatility indices', group = g_v, tooltip = 'Requests CBOE indices. Free data is delayed. That does not affect the implied budget, which locks at 18:00 from the prior close, but live term structure and VVIX readings will lag.', display = display.none)
i_vix_es = input.string('VIX (30D)', 'ES implied move from', options = ['VIX (30D)', 'VIX1D'], group = g_v, tooltip = 'VIX1D prices the current day only. Its closing print may not represent the NEXT day, which is what an 18:00 lock needs, so VIX is the default until that is checked against your own data.', display = display.none)
i_vix_sym = input.string('', 'Index symbol override', group = g_v, tooltip = 'Blank = automatic: ES VIX or VIX1D, NQ VXN, RTY RVX, GC GVZ, anything else VIX. Enter e.g. CBOE:VXN to force one.', display = display.none)
i_ts_back = input.float(1.00, 'Backwardation: VIX9D / VIX at or above', minval = 0.5, maxval = 2.0, step = 0.01, group = g_v, display = display.none)
i_ts_cont = input.float(0.95, 'Contango: VIX9D / VIX at or below', minval = 0.5, maxval = 2.0, step = 0.01, group = g_v, display = display.none)
i_cal_mode = input.string('Auto (calibrated)', 'Bigger / quieter day thresholds', options = ['Auto (calibrated)', 'Fixed'], group = g_v, display = display.none, tooltip = 'Auto: the script records every completed day and flags a bigger day only when VIX vs the average day is in the top slice of the calibration window, and a quieter day only in the bottom slice. VIX normally prices above what actually happens, so a fixed ratio fires too often.\n\nUntil the minimum number of days is recorded, Auto uses the fixed values below and the panel says calibrating.')
i_cal_n = input.int(60, '  Calibration window (days)', minval = 20, maxval = 250, group = g_v, display = display.none)
i_cal_min = input.int(20, '  Minimum days before auto applies', minval = 10, maxval = 100, group = g_v, display = display.none)
i_cal_hi = input.int(80, '  Bigger day: ratio above percentile', minval = 50, maxval = 99, group = g_v, display = display.none)
i_cal_lo = input.int(20, '  Quieter day: ratio below percentile', minval = 1, maxval = 50, group = g_v, display = display.none)
i_ir_hi = input.float(1.30, 'Fixed: bigger day at VIX / avg day', minval = 1.0, maxval = 3.0, step = 0.05, group = g_v, display = display.none)
i_ir_lo = input.float(0.85, 'Fixed: quieter day at VIX / avg day', minval = 0.1, maxval = 1.0, step = 0.05, group = g_v, display = display.none)
i_vvix_spk = input.float(8.0, 'VVIX spike (% above its 18:00 value)', minval = 1.0, maxval = 50.0, step = 0.5, group = g_v, display = display.none)
 
g_g = 'Gamma (optional)'
i_gex_on = input.bool(true, 'Use gamma levels', group = g_g, tooltip = 'Off, or on with the string blank: the regime comes from the volatility read and key zones are built from DOL levels and budget projections.', display = display.none)
i_gstr = input.string('', 'Gamma string', group = g_g, tooltip = 'Same format as Sphinx DOL+G, pasted unchanged:\nSYM.DTE:F{flip}|N{net},{call},{put}|CW{strike[:mag[:oi]]},...|PW{...}\nSegments separated by ;', display = display.none)
i_dte0 = input.bool(true, '0DTE', group = g_g, inline = 'gd', display = display.none)
i_dte7 = input.bool(false, '7DTE', group = g_g, inline = 'gd', display = display.none)
i_dte30 = input.bool(true, '30DTE', group = g_g, inline = 'gd', display = display.none)
i_max_rank = input.int(1, 'Walls per side per board (rank)', minval = 1, maxval = 3, group = g_g, display = display.none)
i_mag_keep = input.float(0.30, 'Also admit walls above magnitude ratio', minval = 0.0, maxval = 1.0, step = 0.05, group = g_g, tooltip = 'Uses inline magnitudes only (strike:mag). Same rule as DOL+G.', display = display.none)
i_reg_src = input.string('Auto', 'Regime source', options = ['Auto', 'Net GEX', 'Flip'], group = g_g, display = display.none)
i_gdate = input.time(timestamp('01 Jan 2000 00:00 +0000'), 'Gamma string pasted on (only if no T field)', group = g_g, display = display.none, tooltip = 'Exports carrying a T field (unix time) are dated automatically. For strings without one, set this when you paste; a string dated before the current 18:00 open is treated as expired for 0DTE. Left at the default, no staleness check is made.')
i_netgex = input.float(0.0, 'Net GEX manual fallback ($B)', step = 0.01, group = g_g, tooltip = 'Used only when the string carries no N block for 0DTE.', display = display.none)
 
g_d = 'DOL'
i_pd = input.bool(true, 'Prev day H/L', group = g_d, display = display.none)
i_asia = input.bool(true, 'Asia H/L (18:00-03:00)', group = g_d, display = display.none)
i_lon = input.bool(true, 'London H/L (03:00-08:30)', group = g_d, display = display.none)
i_h4 = input.bool(true, 'Prev 4H candle H/L', group = g_d, display = display.none)
i_pw = input.bool(false, 'Prev week H/L', group = g_d, display = display.none)
i_hide_broken = input.bool(true, 'Mitigate broken levels', group = g_d, tooltip = 'A close beyond a level breaks it; broken levels are dropped. Swept levels (wick, no close beyond) stay.', display = display.none)
 
g_c = 'Key Zones'
i_confl_min = input.float(4.0, 'Confluence radius minimum (points)', minval = 0.0, maxval = 50.0, step = 0.25, group = g_c, display = display.none, tooltip = 'Floor on the radius below. Stops a zone switching on and off when ATR drifts by a fraction of a point.')
i_merge_ticks = input.int(4, 'Merge tolerance (ticks)', minval = 1, maxval = 40, group = g_c, display = display.none)
i_confl_atr = input.float(0.04, 'Confluence radius (x daily ATR)', minval = 0.005, maxval = 0.5, step = 0.005, group = g_c, tooltip = 'A key zone is a group of levels within this radius holding BOTH structure (a wall, or a projection when gamma is off) AND an unbroken DOL level.', display = display.none)
i_prj_conf = input.bool(false, 'Projections count as structure with gamma on', group = g_c, tooltip = 'With gamma off or blank, budget projections always stand in for walls so DOL-only users still get key zones.', display = display.none)
 
g_i = 'Inducement'
i_ind = input.bool(true, 'Show inducement zones', group = g_i, display = display.none)
i_ind_obv = input.string('Walls and DOL', 'Obvious level can be', options = ['Walls and DOL', 'Walls and swept DOL', 'Walls only'], group = g_i, tooltip = 'Which levels count as the obvious turning point. The liquidity beyond it must always be a NAKED DOL level.', display = display.none)
i_ind_gap = input.float(0.50, 'Max gap obvious -> liquidity (x daily ATR)', minval = 0.05, maxval = 3.0, step = 0.05, group = g_i, display = display.none)
i_ind_min = input.int(4, 'Min gap obvious -> liquidity (ticks)', minval = 1, maxval = 400, group = g_i, tooltip = 'Floor only. The confluence radius also applies, so liquidity inside the obvious level\'s own key zone never counts as beyond it.', display = display.none)
i_recl_bars = input.int(3, 'Reclaim window after sweep (bars)', minval = 1, maxval = 30, group = g_i, display = display.none)
 
g_ks = 'Checklist - setup'
i_chk_on = input.bool(true, 'Use pre-session checklist', group = g_ks, display = display.none)
i_use_plan = input.bool(true, 'Ask: trading plan reviewed', group = g_ks, display = display.none)
i_use_prep = input.bool(true, 'Ask: mentally prepared', group = g_ks, display = display.none)
i_use_ml = input.bool(true, 'Ask: max loss set and accepted', group = g_ks, display = display.none)
i_use_sleep = input.bool(true, 'Ask: sleep quality', group = g_ks, display = display.none)
i_sleep_low = input.int(2, 'Low sleep at or below', minval = 1, maxval = 5, group = g_ks, display = display.none)
i_chk_full = input.bool(false, 'Show full checklist in panel', group = g_ks, display = display.none)
 
g_k = 'Checklist - today'
i_chk_date = input.time(timestamp('01 Jan 2000 00:00 +0000'), 'Completed on (set to today)', group = g_k, tooltip = 'The checklist only counts when this date is today (New York). Pick today each session; the time part is ignored. This is what stops yesterday\'s ticks carrying over.', display = display.none)
i_plan = input.bool(false, 'Trading plan reviewed', group = g_k, display = display.none)
i_prep = input.bool(false, 'Mentally prepared to trade', group = g_k, display = display.none)
i_ml = input.bool(false, 'Max daily loss set and accepted', group = g_k, display = display.none)
i_ml_amt = input.float(0.0, 'Max daily loss ($, display only)', minval = 0, group = g_k, display = display.none)
i_sleep = input.int(3, 'Sleep quality (1-5)', minval = 1, maxval = 5, group = g_k, display = display.none)
c1_ok = input.bool(false, '', group = g_k, inline = 'k1', display = display.none)
c1_tx = input.string('', 'Rule 1', group = g_k, inline = 'k1', display = display.none)
c2_ok = input.bool(false, '', group = g_k, inline = 'k2', display = display.none)
c2_tx = input.string('', 'Rule 2', group = g_k, inline = 'k2', display = display.none)
c3_ok = input.bool(false, '', group = g_k, inline = 'k3', display = display.none)
c3_tx = input.string('', 'Rule 3', group = g_k, inline = 'k3', display = display.none)
c4_ok = input.bool(false, '', group = g_k, inline = 'k4', display = display.none)
c4_tx = input.string('', 'Rule 4', group = g_k, inline = 'k4', display = display.none)
c5_ok = input.bool(false, '', group = g_k, inline = 'k5', display = display.none)
c5_tx = input.string('', 'Rule 5', group = g_k, inline = 'k5', display = display.none)
 
g_l = 'Losses & Cooldown'
i_max_losses = input.int(3, 'Stop after losses', minval = 1, maxval = 10, group = g_l, display = display.none)
i_sleep_tight = input.bool(true, 'Low sleep: one fewer loss allowed', group = g_l, display = display.none)
i_cd_min = input.int(5, 'Cooldown after a loss (minutes)', minval = 1, maxval = 60, group = g_l, display = display.none)
i_loss1 = input.time(timestamp('01 Jan 2000 00:00 +0000'), 'Loss 1', group = g_l, tooltip = 'Set to the time of a loss. Slots inside the current CME trading day (18:00 to 18:00 NY) count toward the limit and start the cooldown; older ones are ignored, so nothing needs clearing tomorrow.', display = display.none)
i_loss2 = input.time(timestamp('01 Jan 2000 00:00 +0000'), 'Loss 2', group = g_l, display = display.none)
i_loss3 = input.time(timestamp('01 Jan 2000 00:00 +0000'), 'Loss 3', group = g_l, display = display.none)
i_loss4 = input.time(timestamp('01 Jan 2000 00:00 +0000'), 'Loss 4', group = g_l, display = display.none)
 
g_q = 'Prompts'
i_q_ind = input.bool(true, 'Early entry (inside inducement)', group = g_q, display = display.none)
i_q_chase = input.bool(true, 'Chasing (new extreme past caution)', group = g_q, display = display.none)
i_q_exh = input.bool(true, 'Budget spent', group = g_q, display = display.none)
i_q_neg = input.bool(true, 'Negative gamma at a wall', group = g_q, display = display.none)
 
g_mb = 'Exposure bars'
i_mb = input.bool(true, 'Show exposure bars', group = g_mb, display = display.none, tooltip = 'One bar per wall, to the right of the level lines. Call exposure right of the centre axis, put exposure left, same scale, so the lean IS the net. Purple beneath is open interest: a long OI bar under a short exposure bar is a real position; a short OI bar under a long exposure bar is size that exists mainly because price is near the strike.')
i_mb_len = input.int(16, 'Bar length at the largest wall (bars)', minval = 4, maxval = 80, group = g_mb, display = display.none)
i_mb_gap = input.int(2, 'Gap after level lines (bars)', minval = 0, maxval = 30, group = g_mb, display = display.none)
i_mb_h = input.float(0.012, 'Bar half-height (x visible range)', minval = 0.002, maxval = 0.1, step = 0.002, group = g_mb, display = display.none)
i_mb_sqrt = input.bool(true, 'Square-root scaling', group = g_mb, display = display.none, tooltip = 'On: compresses the largest wall so smaller ones stay readable. Off: length exactly proportional.')
i_mb_op = input.int(35, 'Bar opacity', minval = 0, maxval = 90, group = g_mb, display = display.none)
col_oi = input.color(color.new(#ab47bc, 0), 'Open interest', group = g_mb, display = display.none)
 
g_p3 = 'Power of 3 candles'
i_p3 = input.bool(true, 'Show daily candles', group = g_p3, display = display.none, tooltip = 'D-2, D-1 and today, each built from the 18:00 NY open to the next 18:00, drawn at true price to the right of the chart. The tick across each candle is its open, so the move above and below the open is visible directly.')
i_p3_off = input.int(60, 'Offset from last bar (bars)', minval = 5, maxval = 300, group = g_p3, display = display.none, tooltip = 'Keep this larger than the right offset plus the label width, or the candles will sit under the level labels.')
i_p3_gap = input.int(8, 'Spacing (bars)', minval = 3, maxval = 60, group = g_p3, display = display.none)
i_p3_w = input.int(4, 'Body width (bars)', minval = 1, maxval = 20, group = g_p3, display = display.none)
i_p3_lbl = input.bool(true, 'Candle labels', group = g_p3, display = display.none)
col_p3u = input.color(color.new(#26a69a, 0), 'Up', group = g_p3, inline = 'p3', display = display.none)
col_p3d = input.color(color.new(#ef5350, 0), 'Down', group = g_p3, inline = 'p3', display = display.none)
col_p3o = input.color(color.new(#787b86, 0), 'Open tick', group = g_p3, inline = 'p3', display = display.none)
 
g_x = 'Display'
i_draw_lvls = input.bool(true, 'Draw key levels', group = g_x, tooltip = 'Turn off when Sphinx DOL+G is on the same chart. Key zones and inducement still draw.', display = display.none)
i_draw_prj = input.bool(false, 'Draw budget projections', group = g_x, display = display.none)
i_back = input.int(40, 'Zone length back (bars)', minval = 5, maxval = 500, group = g_x, display = display.none)
i_pad = input.int(12, 'Right offset (bars)', minval = 0, maxval = 100, group = g_x, display = display.none)
i_stagger = input.int(10, 'Label stagger (bars)', minval = 0, maxval = 60, group = g_x, display = display.none)
col_dol = input.color(color.new(#787b86, 0), 'DOL', group = g_x, inline = 'x1', display = display.none)
col_cw = input.color(color.new(#ef5350, 0), 'CW', group = g_x, inline = 'x1', display = display.none)
col_pw = input.color(color.new(#26a69a, 0), 'PW', group = g_x, inline = 'x1', display = display.none)
col_flip = input.color(color.new(#ffd54f, 0), 'Flip', group = g_x, inline = 'x2', display = display.none)
col_prj = input.color(color.new(#f57c00, 0), 'Projection', group = g_x, inline = 'x2', display = display.none)
col_zone = input.color(color.new(#ffb300, 80), 'Key zone', group = g_x, inline = 'x3', display = display.none)
col_ind = input.color(color.new(#ab47bc, 82), 'Inducement', group = g_x, inline = 'x3', display = display.none)
i_pos = input.string('Top Right', 'Panel position', options = ['Top Right', 'Top Left', 'Middle Right', 'Bottom Right', 'Bottom Left'], group = g_x, display = display.none)
i_txt = input.string('Small', 'Panel text', options = ['Tiny', 'Small', 'Normal', 'Large'], group = g_x, display = display.none)
 
// ============================================================
// === HELPERS ===
// ============================================================
f0(x) =>
    na(x) ? '-' : str.tostring(x, '#')
f2(x) =>
    na(x) ? '-' : str.tostring(x, '#.##')
fp(x) =>
    na(x) ? '-' : str.tostring(x, format.mintick)
 
gauge(p) =>
    n = math.min(10, math.max(0, math.round(nz(p) / 10)))
    s = ''
    for i = 0 to 9 by 1
        s := s + (i < n ? '█' : '░')
    s
 
_dkey(t) =>
    year(t, TZ) * 10000 + month(t, TZ) * 100 + dayofmonth(t, TZ)
 
// CME trading day: 18:00 NY belongs to the NEXT calendar day.
_tdkey(t) =>
    _dkey(t + 6 * 3600000)
 
_mmss(ms) =>
    int _s = math.max(0, math.floor(ms / 1000))
    str.tostring(math.floor(_s / 60)) + ':' + str.tostring(_s % 60, '00')
 
_txtsz = i_txt == 'Tiny' ? size.tiny : i_txt == 'Normal' ? size.normal : i_txt == 'Large' ? size.large : size.small
_tbpos = i_pos == 'Top Left' ? position.top_left : i_pos == 'Middle Right' ? position.middle_right : i_pos == 'Bottom Right' ? position.bottom_right : i_pos == 'Bottom Left' ? position.bottom_left : position.top_right
 
c_red = color.new(#ef5350, 0)
c_amb = color.new(#f9a825, 0)
c_grn = color.new(#26a69a, 0)
c_org = color.new(#ff7043, 0)
c_gry = color.new(#787b86, 0)
 
// ============================================================
// === SYMBOL & VOLATILITY SOURCE ===
// ============================================================
_tk = syminfo.ticker
chartSym = str.contains(_tk, 'RTY') or str.contains(_tk, 'M2K') ? 'RTY' : str.contains(_tk, 'NQ') ? 'NQ' : str.contains(_tk, 'GC') ? 'GC' : str.contains(_tk, 'ES') ? 'ES' : ''
_autoVol = chartSym == 'NQ' ? 'CBOE:VXN' : chartSym == 'RTY' ? 'CBOE:RVX' : chartSym == 'GC' ? 'CBOE:GVZ' : i_vix_es == 'VIX1D' ? 'CBOE:VIX1D' : 'CBOE:VIX'
volSym = i_vix_sym != '' ? i_vix_sym : _autoVol
volName = str.replace_all(volSym, 'CBOE:', '')
 
// Requested on the chart timeframe with gaps off, so a chart bar with
// no index print carries the last one. At 18:00 that is the prior
// session close. ignore_invalid_symbol keeps the script running for
// users without access to an index.
_rv = request.security(volSym, timeframe.period, close, ignore_invalid_symbol = true)
_rvix = request.security('CBOE:VIX', timeframe.period, close, ignore_invalid_symbol = true)
_r9d = request.security('CBOE:VIX9D', timeframe.period, close, ignore_invalid_symbol = true)
_rvvix = request.security('CBOE:VVIX', timeframe.period, close, ignore_invalid_symbol = true)
vm = i_vix_on ? _rv : float(na)
vx = i_vix_on ? _rvix : float(na)
v9 = i_vix_on ? _r9d : float(na)
vvx = i_vix_on ? _rvvix : float(na)
 
// ============================================================
// === DAILY DATA ===
// ============================================================
atr_d = request.security(syminfo.tickerid, 'D', ta.atr(14)[1], lookahead = barmerge.lookahead_on)
atrD = na(atr_d) ? ta.atr(14) * 3 : atr_d
 
_drF() =>
    _r = high - low
    [ta.sma(_r, i_len)[1], ta.percentile_nearest_rank(_r, i_len, 50)[1], ta.ema(_r, i_len)[1]]
[dr_mean, dr_med, dr_ema] = request.security(syminfo.tickerid, 'D', _drF(), lookahead = barmerge.lookahead_on)
 
[pdh, pdl] = request.security(syminfo.tickerid, 'D', [high[1], low[1]], lookahead = barmerge.lookahead_on)
[h4h, h4l] = request.security(syminfo.tickerid, '240', [high[1], low[1]], lookahead = barmerge.lookahead_on)
[pwh, pwl] = request.security(syminfo.tickerid, 'W', [high[1], low[1]], lookahead = barmerge.lookahead_on)
 
// Visible price range, for exposure bar height. Moves with zoom and
// scroll, so the bars keep the same visual weight at any scale.
_tfms = timeframe.in_seconds() * 1000
_visN = _tfms > 0 ? math.max(10, math.min(2000, int((chart.right_visible_bar_time - chart.left_visible_bar_time) / _tfms))) : 300
_visRange = ta.highest(high, _visN) - ta.lowest(low, _visN)
 
// ============================================================
// === ANCHOR 18:00 NY ===
// ============================================================
_mod = hour(time, TZ) * 60 + minute(time, TZ)
mins_since = _mod >= 1080 ? _mod - 1080 : _mod + 360
gap_reset = time - time[1] > 43200000
new_anchor = barstate.isfirst or mins_since < nz(mins_since[1], 100000) or gap_reset
 
var float a_px = na
var float a_hi = na
var float a_lo = na
var int a_bar = na
var int a_time = na
 
// Completed 18:00-to-18:00 days for the Power of 3 candles. Captured
// here, before the anchor values below are reset for the new day.
var float p1o = na
var float p1h = na
var float p1l = na
var float p1c = na
var float p2o = na
var float p2h = na
var float p2l = na
var float p2c = na
// Calibration history. dayImpl / dayDR hold the previous bar's values
// here, because they are updated further down, after the budget is
// computed - so on the first bar of a new day they still describe
// the day that just ended.
var float dayImpl = na
var float dayDR = na
var array<float> hAct = array.new_float()
var array<float> hImp = array.new_float()
var array<float> hDR = array.new_float()
var float calHi = na
var float calLo = na
var float calOver = na
var float calErrDR = na
var float calErrIV = na
var int calN = 0
if new_anchor and not na(a_px) and a_hi - a_lo > 0
    array.push(hAct, a_hi - a_lo)
    array.push(hImp, nz(dayImpl, -1.0))
    array.push(hDR, nz(dayDR, -1.0))
    while array.size(hAct) > i_cal_n
        array.shift(hAct)
        array.shift(hImp)
        array.shift(hDR)
    _rIV = array.new_float()
    _rOv = array.new_float()
    float _eD = 0.0
    int _nD = 0
    float _eI = 0.0
    int _nI = 0
    for _k = 0 to array.size(hAct) - 1 by 1
        float _act = array.get(hAct, _k)
        float _imp = array.get(hImp, _k)
        float _drk = array.get(hDR, _k)
        if _drk > 0
            _eD += math.abs(_drk - _act) / _act
            _nD += 1
        if _imp > 0
            _eI += math.abs(_imp - _act) / _act
            _nI += 1
            array.push(_rOv, _imp / _act)
            if _drk > 0
                array.push(_rIV, _imp / _drk)
    calN := array.size(_rIV)
    calErrDR := _nD > 0 ? _eD / _nD * 100.0 : float(na)
    calErrIV := _nI > 0 ? _eI / _nI * 100.0 : float(na)
    calOver := array.size(_rOv) > 0 ? array.median(_rOv) : float(na)
    calHi := calN > 0 ? array.percentile_nearest_rank(_rIV, i_cal_hi) : float(na)
    calLo := calN > 0 ? array.percentile_nearest_rank(_rIV, i_cal_lo) : float(na)
 
if new_anchor and not na(a_px)
    p2o := p1o
    p2h := p1h
    p2l := p1l
    p2c := p1c
    p1o := a_px
    p1h := a_hi
    p1l := a_lo
    p1c := close[1]
 
if new_anchor
    a_px := open
    a_hi := high
    a_lo := low
    a_bar := bar_index
    a_time := time
else
    a_hi := na(a_hi) ? high : math.max(a_hi, high)
    a_lo := na(a_lo) ? low : math.min(a_lo, low)
 
// Volatility locked at the anchor. Late-filled only if the index had
// no value at the anchor bar (start of chart history).
var float v_lock = na
var float vvix_lock = na
if new_anchor
    v_lock := vm
    vvix_lock := vvx
else
    if na(v_lock)
        v_lock := vm
    if na(vvix_lock)
        vvix_lock := vvx
 
// ============================================================
// === BUDGET ===
// ============================================================
adr_auto = i_method == 'Mean (SMA)' ? dr_mean : i_method == 'EMA' ? dr_ema : dr_med
adr = i_manual > 0 ? i_manual : adr_auto
impl = not na(v_lock) and v_lock > 0 and not na(a_px) ? v_lock / 100.0 / math.sqrt(252) * a_px : float(na)
day_rng = a_hi - a_lo
_drOk = not na(adr) and adr > 0
_ivOk = not na(impl) and impl > 0
pct_used = _drOk ? day_rng / adr * 100.0 : float(na)
pct_iv = _ivOk ? day_rng / impl * 100.0 : float(na)
iv_ratio = _drOk and _ivOk ? impl / adr : float(na)
 
_budRaw = i_room == 'Implied (VIX)' ? impl : i_room == 'Larger of the two' ? (_ivOk and _drOk ? math.max(impl, adr) : _drOk ? adr : impl) : adr
bud = not na(_budRaw) and _budRaw > 0 ? _budRaw : _drOk ? adr : float(na)
budTag = _ivOk and bud == impl ? 'IV' : 'DR'
dayImpl := impl
dayDR := adr
calReady = i_cal_mode == 'Auto (calibrated)' and calN >= i_cal_min
irHi = calReady ? calHi : i_ir_hi
irLo = calReady ? calLo : i_ir_lo
implAdj = _ivOk and not na(calOver) and calOver > 0 and calN >= i_cal_min ? impl / calOver : float(na)
 
proj_hi = na(bud) ? float(na) : a_lo + bud
proj_lo = na(bud) ? float(na) : a_hi - bud
rem_up = proj_hi - close
rem_dn = close - proj_lo
 
// ============================================================
// === VOLATILITY READ ===
// ============================================================
ts9 = not na(v9) and not na(vx) and vx > 0 ? v9 / vx : float(na)
tsTxt = na(ts9) ? '-' : ts9 >= i_ts_back ? 'BACKWARD' : ts9 <= i_ts_cont ? 'CONTANGO' : 'FLAT'
vvChg = not na(vvx) and not na(vvix_lock) and vvix_lock > 0 ? (vvx / vvix_lock - 1.0) * 100.0 : float(na)
vvSpike = not na(vvChg) and vvChg >= i_vvix_spk
 
// -1 trend lean: short-dated fear above 30-day, a bigger day priced
//    than recent days have delivered, or VVIX spiking.
// +1 range lean: a quieter day priced than recent days, or contango
//    with implied not above historical.
bool _volTrend = (not na(ts9) and ts9 >= i_ts_back) or (not na(iv_ratio) and iv_ratio >= irHi) or vvSpike
bool _volRange = (not na(iv_ratio) and iv_ratio <= irLo) or (not na(ts9) and ts9 <= i_ts_cont and (na(iv_ratio) or iv_ratio < 1.0))
volLean = _volTrend ? -1 : _volRange ? 1 : 0
 
// ============================================================
// === DOL STATE  (2 naked / 1 swept / 0 broken) ===
// ============================================================
_ccl = barstate.isconfirmed ? close : close[1]
// v1.2.1: a level breaks as soon as price is trading beyond it - live
// price on the realtime bar, not the last confirmed close. Realtime var
// state is re-evaluated each tick from the last committed bar, so a
// wick through that returns inside before the close ends as a sweep.
_stH(lvl, st) =>
    na(lvl) ? st : close > lvl ? 0 : high >= lvl ? math.min(st, 1) : st
_stL(lvl, st) =>
    na(lvl) ? st : close < lvl ? 0 : low <= lvl ? math.min(st, 1) : st
 
in_asia = _mod >= 1080 or _mod < 180
in_lon = _mod >= 180 and _mod < 510
 
var float asH = na
var float asL = na
var float asH_p = na
var float asL_p = na
var float loH = na
var float loL = na
var float loH_p = na
var float loL_p = na
var int s_asH = 2
var int s_asL = 2
var int s_loH = 2
var int s_loL = 2
var int s_pdh = 2
var int s_pdl = 2
var int s_h4h = 2
var int s_h4l = 2
var int s_pwh = 2
var int s_pwl = 2
 
if in_asia and not in_asia[1]
    asH := high
    asL := low
else if in_asia
    asH := na(asH) ? high : math.max(asH, high)
    asL := na(asL) ? low : math.min(asL, low)
if not in_asia and in_asia[1]
    asH_p := asH
    asL_p := asL
    s_asH := 2
    s_asL := 2
 
if in_lon and not in_lon[1]
    loH := high
    loL := low
else if in_lon
    loH := na(loH) ? high : math.max(loH, high)
    loL := na(loL) ? low : math.min(loL, low)
if not in_lon and in_lon[1]
    loH_p := loH
    loL_p := loL
    s_loH := 2
    s_loL := 2
 
newDay = ta.change(time('D')) != 0
newWk = ta.change(time('W')) != 0
new4h = ta.change(time('240')) != 0
if newDay
    s_pdh := 2
    s_pdl := 2
if newWk
    s_pwh := 2
    s_pwl := 2
if new4h
    s_h4h := 2
    s_h4l := 2
 
s_pdh := _stH(pdh, s_pdh)
s_pdl := _stL(pdl, s_pdl)
s_pwh := _stH(pwh, s_pwh)
s_pwl := _stL(pwl, s_pwl)
s_h4h := _stH(h4h, s_h4h)
s_h4l := _stL(h4l, s_h4l)
s_asH := _stH(asH_p, s_asH)
s_asL := _stL(asL_p, s_asL)
s_loH := _stH(loH_p, s_loH)
s_loL := _stL(loL_p, s_loL)
 
// ============================================================
// === GAMMA PARSE  (once; the string is an input) ===
//   Split on the FIRST colon only, fields identified by prefix.
//   Same rules as DOL+G v2.12.1 onward.
// ============================================================
var array<float> gP = array.new_float()
var array<bool> gC = array.new_bool()
var array<float> gR = array.new_float()
var array<string> gN = array.new_string()
var array<string> gD = array.new_string()
var array<float> gO = array.new_float()
var float g_flip = na
var float g_net = na
var float g_T = na
 
_inlineMax(arr) =>
    float _mx = 0.0
    int _n = array.size(arr)
    if _n > 0
        for _i = 0 to _n - 1 by 1
            _tt = str.split(array.get(arr, _i), ':')
            if array.size(_tt) >= 2
                _m = str.tonumber(array.get(_tt, 1))
                if not na(_m)
                    _mx := math.max(_mx, math.abs(_m))
    _mx
 
if barstate.isfirst and i_gex_on and chartSym != '' and str.length(i_gstr) > 0
    _segs = str.split(str.replace_all(i_gstr, ' ', ''), ';')
    int _ns = array.size(_segs)
    if _ns > 0
        for _si = 0 to _ns - 1 by 1
            string _seg = array.get(_segs, _si)
            _cix = str.pos(_seg, ':')
            if not na(_cix) and _cix > 0
                string _head = str.substring(_seg, 0, _cix)
                string _body = str.substring(_seg, _cix + 1)
                _dpr = str.split(_head, '.')
                if array.size(_dpr) >= 2
                    if array.get(_dpr, 0) == chartSym
                        string _dte = array.get(_dpr, 1)
                        _ppr = str.split(_body, '|')
                        string _cwp = ''
                        string _pwp = ''
                        float _flp = na
                        float _nt = na
                        int _nf = array.size(_ppr)
                        if _nf > 0
                            for _fi = 0 to _nf - 1 by 1
                                string _fld = array.get(_ppr, _fi)
                                if str.startswith(_fld, 'CW')
                                    _cwp := _fld
                                else if str.startswith(_fld, 'PW')
                                    _pwp := _fld
                                else if str.startswith(_fld, 'N')
                                    _nv = str.split(str.substring(_fld, 1), ',')
                                    if array.size(_nv) >= 1
                                        _nt := str.tonumber(array.get(_nv, 0))
                                else if str.startswith(_fld, 'F')
                                    _flp := str.tonumber(str.substring(_fld, 1))
                                else if str.startswith(_fld, 'T')
                                    float _tv = str.tonumber(str.substring(_fld, 1))
                                    if not na(_tv)
                                        _tv := _tv > 100000000000 ? _tv : _tv * 1000
                                        g_T := na(g_T) ? _tv : math.max(g_T, _tv)
                        if _dte == '0'
                            g_flip := _flp
                            g_net := _nt
                        bool _on = _dte == '0' and i_dte0 or _dte == '7' and i_dte7 or _dte == '30' and i_dte30
                        if _on
                            for _side = 0 to 1 by 1
                                string _txt = _side == 0 ? _cwp : _pwp
                                if str.length(_txt) > 2
                                    _arr = str.split(str.substring(_txt, 2), ',')
                                    float _mx = _inlineMax(_arr)
                                    int _nw = array.size(_arr)
                                    if _nw > 0
                                        for _wi = 0 to _nw - 1 by 1
                                            _tok = str.split(array.get(_arr, _wi), ':')
                                            float _v = str.tonumber(array.get(_tok, 0))
                                            float _inl = array.size(_tok) >= 2 ? str.tonumber(array.get(_tok, 1)) : float(na)
                                            float _mw = not na(_inl) and _mx > 0 ? math.abs(_inl) / _mx : float(na)
                                            if not na(_v) and (_wi < i_max_rank or not na(_mw) and _mw >= i_mag_keep)
                                                array.push(gP, _v)
                                                array.push(gC, _side == 0)
                                                array.push(gR, na(_inl) ? 0.0 : math.abs(_inl))
                                                array.push(gN, (_side == 0 ? 'CW.' : 'PW.') + _dte)
                                                array.push(gD, _dte)
                                                array.push(gO, array.size(_tok) >= 3 ? nz(str.tonumber(array.get(_tok, 2))) : 0.0)
 
// ============================================================
// === REGIME ===
//   Gamma when available (net GEX, else flip, on a closing basis).
//   Otherwise the volatility lean, labelled so it is never read as
//   a dealer-positioning claim.
// ============================================================
// Staleness: the string is dated by its T field, else by the input.
// A string from before the current 18:00 open carries an expired 0DTE
// board. Only evaluated where the string can actually be stale - the
// bars after it was exported.
float gDate = not na(g_T) ? g_T : i_gdate > timestamp('02 Jan 2000 00:00 +0000') ? float(i_gdate) : float(na)
gStale = i_gex_on and str.length(i_gstr) > 0 and not na(gDate) and not na(a_time) and gDate < a_time
_flipEff = gStale ? float(na) : g_flip
gexWalls = i_gex_on and array.size(gP) > 0
_netRaw = gStale ? float(na) : g_net
_netEff = not na(_netRaw) ? _netRaw : i_netgex != 0 and not gStale ? i_netgex : float(na)
_regFlip = na(_flipEff) ? 0 : _ccl > _flipEff ? 1 : -1
_regNet = na(_netEff) or _netEff == 0 ? 0 : _netEff > 0 ? 1 : -1
_useNet = i_reg_src == 'Net GEX' or i_reg_src == 'Auto' and _regNet != 0
_gexSig = not i_gex_on ? 0 : _useNet ? _regNet : _regFlip
regFromGex = _gexSig != 0
regSig = regFromGex ? _gexSig : volLean
regSrc = regFromGex ? (_useNet ? 'net' : 'flip') : 'vol'
regTxt = regFromGex ? (regSig == 1 ? 'Calm - dealers dampen moves' : 'Fast - dealers amplify moves') : regSig == 1 ? 'Range day lean' : regSig == -1 ? 'Trend day lean' : 'Neutral'
// Net exposure and flip side disagree: same flag as DOL+G.
regSplit = regFromGex and _regNet != 0 and _regFlip != 0 and _regNet != _regFlip
prjCounts = not gexWalls or i_prj_conf
 
// ============================================================
// === LEVEL POOL ===
//   cT: 0 DOL, 1 call wall, 2 put wall, 3 projection
// ============================================================
var array<float> cP = array.new_float()
var array<string> cK = array.new_string()
var array<int> cT = array.new_int()
var array<int> cS = array.new_int()
var array<float> cR = array.new_float()
var array<float> cO = array.new_float()
 
_push(p, k, t, s, r, o) =>
    array.push(cP, p)
    array.push(cK, k)
    array.push(cT, t)
    array.push(cS, s)
    array.push(cR, r)
    array.push(cO, o)
    true
 
_dol(lvl, k, st) =>
    bool _ok = not na(lvl) and (not i_hide_broken or st != 0)
    if _ok
        _push(lvl, k, 0, st, 0.0, 0.0)
    _ok
 
// merge nodes (one drawn level each)
var array<float> nP = array.new_float()
var array<string> nK = array.new_string()
var array<string> nDn = array.new_string()
var array<bool> nG = array.new_bool()
var array<bool> nD = array.new_bool()
var array<bool> nNk = array.new_bool()
var array<bool> nPj = array.new_bool()
var array<bool> nCWd = array.new_bool()
var array<float> nRC = array.new_float()
var array<float> nRP = array.new_float()
var array<float> nOI = array.new_float()
 
// confluence groups
var array<float> zLo = array.new_float()
var array<float> zHi = array.new_float()
var array<bool> zS = array.new_bool()
var array<bool> zD = array.new_bool()
var array<string> zN = array.new_string()
 
_obvOK(j) =>
    bool _w = array.get(nG, j)
    bool _dd = array.get(nD, j)
    bool _nkk = array.get(nNk, j)
    _w or i_ind_obv == 'Walls and DOL' and _dd or i_ind_obv == 'Walls and swept DOL' and _dd and not _nkk
 
// inducement state, carried across bars
var float iO_dn = na
var float iT_dn = na
var string iON_dn = ''
var string iTN_dn = ''
var int iSw_dn = na
var float iO_up = na
var float iT_up = na
var string iON_up = ''
var string iTN_up = ''
var int iSw_up = na
 
// per-bar results
float zU_lo = na
float zU_hi = na
string zU_n = ''
float zD_lo = na
float zD_hi = na
string zD_n = ''
string atZ = ''
 
bool evEnter = false
bool evRecl = false
bool evFail = false
bool evZone = false
evExh = not na(pct_used) and pct_used >= i_exh and nz(pct_used[1]) < i_exh
 
var array<line> dL = array.new_line()
var array<label> dB = array.new_label()
var array<box> dX = array.new_box()
var table tb = table.new(_tbpos, 2, 32, border_width = 0)
 
put(_r, _k, _v, _cv) =>
    table.cell(tb, 0, _r, _k, text_color = color.gray, text_size = _txtsz, text_halign = text.align_left)
    table.cell(tb, 1, _r, _v, text_color = _cv, text_size = _txtsz, text_halign = text.align_left)
 
// ============================================================
// === MAIN (last bar) ===
// ============================================================
if barstate.islast
    // ---------- pool ----------
    array.clear(cP)
    array.clear(cK)
    array.clear(cT)
    array.clear(cS)
    array.clear(cR)
    array.clear(cO)
    if i_pd
        _dol(pdh, 'PDH', s_pdh)
        _dol(pdl, 'PDL', s_pdl)
    if i_asia
        _dol(asH_p, 'AsH', s_asH)
        _dol(asL_p, 'AsL', s_asL)
    if i_lon
        _dol(loH_p, 'LoH', s_loH)
        _dol(loL_p, 'LoL', s_loL)
    if i_h4
        _dol(h4h, '4hH', s_h4h)
        _dol(h4l, '4hL', s_h4l)
    if i_pw
        _dol(pwh, 'PWH', s_pwh)
        _dol(pwl, 'PWL', s_pwl)
    if gexWalls
        for _gi = 0 to array.size(gP) - 1 by 1
            if gStale and array.get(gD, _gi) == '0'
                continue
            _push(array.get(gP, _gi), array.get(gN, _gi), array.get(gC, _gi) ? 1 : 2, -1, array.get(gR, _gi), array.get(gO, _gi))
    if prjCounts and not na(proj_hi)
        _push(proj_hi, 'PrjH', 3, -1, 0.0, 0.0)
        _push(proj_lo, 'PrjL', 3, -1, 0.0, 0.0)
 
    // ---------- merge pass (sorted linear grouping) ----------
    array.clear(nP)
    array.clear(nK)
    array.clear(nDn)
    array.clear(nG)
    array.clear(nD)
    array.clear(nNk)
    array.clear(nPj)
    array.clear(nCWd)
    array.clear(nRC)
    array.clear(nRP)
    array.clear(nOI)
    int _np = array.size(cP)
    float _mtol = i_merge_ticks * syminfo.mintick
    if _np > 0
        _idx = array.sort_indices(cP, order.ascending)
        float _sum = 0.0
        int _cnt = 0
        string _k = ''
        string _dn = ''
        bool _g = false
        bool _d = false
        bool _nk = false
        bool _pj = false
        float _rc = 0.0
        float _rp = 0.0
        int _nc = 0
        int _npw = 0
        float _oi = 0.0
        float _prev = na
        for _q = 0 to _np - 1 by 1
            int _i = array.get(_idx, _q)
            float _p = array.get(cP, _i)
            if _q > 0 and _p - _prev > _mtol
                array.push(nP, math.round(_sum / _cnt / syminfo.mintick) * syminfo.mintick)
                array.push(nK, _k)
                array.push(nDn, _dn)
                array.push(nG, _g)
                array.push(nD, _d)
                array.push(nNk, _nk)
                array.push(nPj, _pj)
                array.push(nCWd, _rc > 0 or _rp > 0 ? _rc >= _rp : _nc >= _npw)
                array.push(nRC, _rc)
                array.push(nRP, _rp)
                array.push(nOI, _oi)
                _oi := 0.0
                _sum := 0.0
                _cnt := 0
                _k := ''
                _dn := ''
                _g := false
                _d := false
                _nk := false
                _pj := false
                _rc := 0.0
                _rp := 0.0
                _nc := 0
                _npw := 0
            _sum += _p
            _cnt += 1
            _oi += array.get(cO, _i)
            int _ty = array.get(cT, _i)
            string _kn = array.get(cK, _i)
            _k := _k == '' ? _kn : str.contains(_k, _kn) ? _k : _k + '/' + _kn
            if _ty == 0
                int _st = array.get(cS, _i)
                _dn := _dn == '' ? _kn : _dn + '/' + _kn
                _d := _d or _st >= 1
                _nk := _nk or _st == 2
            else if _ty == 1
                _g := true
                _nc += 1
                _rc += array.get(cR, _i)
            else if _ty == 2
                _g := true
                _npw += 1
                _rp += array.get(cR, _i)
            else
                _pj := true
            _prev := _p
        array.push(nP, math.round(_sum / _cnt / syminfo.mintick) * syminfo.mintick)
        array.push(nK, _k)
        array.push(nDn, _dn)
        array.push(nG, _g)
        array.push(nD, _d)
        array.push(nNk, _nk)
        array.push(nPj, _pj)
        array.push(nCWd, _rc > 0 or _rp > 0 ? _rc >= _rp : _nc >= _npw)
        array.push(nRC, _rc)
        array.push(nRP, _rp)
        array.push(nOI, _oi)
 
    // ---------- confluence groups (complete linkage) ----------
    array.clear(zLo)
    array.clear(zHi)
    array.clear(zS)
    array.clear(zD)
    array.clear(zN)
    int _nn = array.size(nP)
    if _nn > 0
        float _ctol = math.max(i_confl_atr * atrD, i_confl_min)
        float _gmin = na
        for _j = 0 to _nn - 1 by 1
            float _pz = array.get(nP, _j)
            bool _isS = array.get(nG, _j) or array.get(nPj, _j)
            bool _isD = array.get(nD, _j)
            if _j == 0 or _pz - _gmin > _ctol
                array.push(zLo, _pz)
                array.push(zHi, _pz)
                array.push(zS, _isS)
                array.push(zD, _isD)
                array.push(zN, array.get(nK, _j))
                _gmin := _pz
            else
                int _gz = array.size(zLo) - 1
                array.set(zHi, _gz, _pz)
                array.set(zS, _gz, array.get(zS, _gz) or _isS)
                array.set(zD, _gz, array.get(zD, _gz) or _isD)
                array.set(zN, _gz, array.get(zN, _gz) + '/' + array.get(nK, _j))
 
    // ---------- nearest key zones ----------
    float _zpad = 2 * syminfo.mintick
    int _nz = array.size(zLo)
    if _nz > 0
        for _z = 0 to _nz - 1 by 1
            if array.get(zS, _z) and array.get(zD, _z)
                float _lo = array.get(zLo, _z)
                float _hi = array.get(zHi, _z)
                if close >= _lo - _zpad and close <= _hi + _zpad
                    atZ := array.get(zN, _z)
                else if _lo > close
                    if na(zU_lo) or _lo < zU_lo
                        zU_lo := _lo
                        zU_hi := _hi
                        zU_n := array.get(zN, _z)
                else
                    if na(zD_hi) or _hi > zD_hi
                        zD_lo := _lo
                        zD_hi := _hi
                        zD_n := array.get(zN, _z)
    evZone := not na(zU_lo) and high >= zU_lo - _zpad and high[1] < zU_lo - _zpad or not na(zD_hi) and low <= zD_hi + _zpad and low[1] > zD_hi + _zpad
 
    // ---------- inducement ----------
    float _gap = i_ind_gap * atrD
    // v1.0.1: the liquidity must sit OUTSIDE the obvious level's own
    // confluence radius. A target two points past the wall is the same
    // zone, not a level beyond it.
    float _gmn = math.max(i_ind_min * syminfo.mintick, math.max(i_confl_atr * atrD, i_confl_min))
 
    // manage the active zone BELOW price
    if not na(iT_dn)
        bool _stillDn = false
        if _nn > 0
            for _j = 0 to _nn - 1 by 1
                if array.get(nNk, _j) and math.abs(array.get(nP, _j) - iT_dn) <= _mtol
                    _stillDn := true
                    break
        if na(iSw_dn)
            if low <= iT_dn
                iSw_dn := bar_index
            else if not _stillDn or close > iO_dn + _gap
                iO_dn := na
                iT_dn := na
                iON_dn := ''
                iTN_dn := ''
        if not na(iSw_dn) and not na(iT_dn) and barstate.isconfirmed
            if close > iT_dn
                evRecl := true
                alert('KVP ' + chartSym + ': ' + iTN_dn + ' ' + fp(iT_dn) + ' swept and reclaimed', alert.freq_once_per_bar_close)
                iO_dn := na
                iT_dn := na
                iON_dn := ''
                iTN_dn := ''
                iSw_dn := na
            else if bar_index - iSw_dn >= i_recl_bars
                evFail := true
                iO_dn := na
                iT_dn := na
                iON_dn := ''
                iTN_dn := ''
                iSw_dn := na
 
    // manage the active zone ABOVE price
    if not na(iT_up)
        bool _stillUp = false
        if _nn > 0
            for _j = 0 to _nn - 1 by 1
                if array.get(nNk, _j) and math.abs(array.get(nP, _j) - iT_up) <= _mtol
                    _stillUp := true
                    break
        if na(iSw_up)
            if high >= iT_up
                iSw_up := bar_index
            else if not _stillUp or close < iO_up - _gap
                iO_up := na
                iT_up := na
                iON_up := ''
                iTN_up := ''
        if not na(iSw_up) and not na(iT_up) and barstate.isconfirmed
            if close < iT_up
                evRecl := true
                alert('KVP ' + chartSym + ': ' + iTN_up + ' ' + fp(iT_up) + ' swept and reclaimed', alert.freq_once_per_bar_close)
                iO_up := na
                iT_up := na
                iON_up := ''
                iTN_up := ''
                iSw_up := na
            else if bar_index - iSw_up >= i_recl_bars
                evFail := true
                iO_up := na
                iT_up := na
                iON_up := ''
                iTN_up := ''
                iSw_up := na
 
    // search for new zones: nearest obvious level, then the nearest
    // NAKED liquidity beyond it, within the gap and inside the budget
    if i_ind and na(iT_dn) and _nn > 1
        int _io = -1
        for _j = _nn - 1 to 0
            if array.get(nP, _j) <= close and _obvOK(_j)
                _io := _j
                break
        if _io > 0
            float _po = array.get(nP, _io)
            for _j = _io - 1 to 0
                float _pt = array.get(nP, _j)
                if _po - _pt > _gap
                    break
                if array.get(nNk, _j) and _po - _pt >= _gmn and (na(proj_lo) or _pt >= proj_lo)
                    iO_dn := _po
                    iT_dn := _pt
                    iON_dn := array.get(nK, _io)
                    iTN_dn := array.get(nDn, _j)
                    break
 
    if i_ind and na(iT_up) and _nn > 1
        int _iu = -1
        for _j = 0 to _nn - 1
            if array.get(nP, _j) > close and _obvOK(_j)
                _iu := _j
                break
        if _iu >= 0 and _iu < _nn - 1
            float _po = array.get(nP, _iu)
            for _j = _iu + 1 to _nn - 1
                float _pt = array.get(nP, _j)
                if _pt - _po > _gap
                    break
                if array.get(nNk, _j) and _pt - _po >= _gmn and (na(proj_hi) or _pt <= proj_hi)
                    iO_up := _po
                    iT_up := _pt
                    iON_up := array.get(nK, _iu)
                    iTN_up := array.get(nDn, _j)
                    break
 
    bool _inDn = not na(iT_dn) and na(iSw_dn) and close <= iO_dn and close > iT_dn
    bool _inUp = not na(iT_up) and na(iSw_up) and close >= iO_up and close < iT_up
    bool _entDn = not na(iT_dn) and low <= iO_dn and low[1] > iO_dn
    bool _entUp = not na(iT_up) and high >= iO_up and high[1] < iO_up
    if _entDn or _entUp
        evEnter := true
        string _em = _entDn ? iON_dn + ' ' + fp(iO_dn) + ' - liquidity at ' + iTN_dn + ' ' + fp(iT_dn) + ' not taken' : iON_up + ' ' + fp(iO_up) + ' - liquidity at ' + iTN_up + ' ' + fp(iT_up) + ' not taken'
        alert('KVP ' + chartSym + ': early - ' + _em, alert.freq_once_per_bar)
 
    // ---------- psychology ----------
    int _today = _dkey(timenow)
    int _tday = _tdkey(timenow)
    bool chkToday = _dkey(i_chk_date) == _today
    _lt = array.from(i_loss1, i_loss2, i_loss3, i_loss4)
    int nLoss = 0
    int lastLoss = 0
    for _li = 0 to 3 by 1
        int _t = array.get(_lt, _li)
        if _tdkey(_t) == _tday
            nLoss += 1
            lastLoss := math.max(lastLoss, _t)
    bool lowSleep = i_use_sleep and i_sleep <= i_sleep_low
    int maxL = math.max(1, i_max_losses - (lowSleep and i_sleep_tight ? 1 : 0))
    int cdLeft = lastLoss > 0 ? lastLoss + i_cd_min * 60000 - timenow : 0
    bool stopped = nLoss >= maxL
    bool inCd = not stopped and cdLeft > 0
 
    ckN = array.new_string()
    ckB = array.new_bool()
    if i_use_plan
        array.push(ckN, 'Trading plan reviewed')
        array.push(ckB, i_plan)
    if i_use_prep
        array.push(ckN, 'Mentally prepared')
        array.push(ckB, i_prep)
    if i_use_ml
        array.push(ckN, 'Max loss' + (i_ml_amt > 0 ? ' $' + str.tostring(i_ml_amt, '#') : '') + ' set and accepted')
        array.push(ckB, i_ml)
    if c1_tx != ''
        array.push(ckN, c1_tx)
        array.push(ckB, c1_ok)
    if c2_tx != ''
        array.push(ckN, c2_tx)
        array.push(ckB, c2_ok)
    if c3_tx != ''
        array.push(ckN, c3_tx)
        array.push(ckB, c3_ok)
    if c4_tx != ''
        array.push(ckN, c4_tx)
        array.push(ckB, c4_ok)
    if c5_tx != ''
        array.push(ckN, c5_tx)
        array.push(ckB, c5_ok)
    int _nck = array.size(ckN)
    string nextItem = ''
    if i_chk_on and _nck > 0
        if not chkToday
            nextItem := 'set checklist date to today'
        else
            for _ci = 0 to _nck - 1 by 1
                if not array.get(ckB, _ci)
                    nextItem := array.get(ckN, _ci)
                    break
    bool cleared = nextItem == ''
 
    string stTxt = 'CLEARED'
    color stCol = c_grn
    if stopped
        stTxt := 'STOP - loss limit ' + str.tostring(nLoss) + '/' + str.tostring(maxL)
        stCol := c_red
    else if inCd
        stTxt := 'COOLDOWN ' + _mmss(cdLeft) + ' - step away, get some air'
        stCol := c_org
    else if not cleared
        stTxt := 'NOT CLEARED - ' + nextItem
        stCol := c_red
    else if lowSleep
        stTxt := 'CLEARED - low sleep, A+ only'
        stCol := c_amb
 
    // ---------- behaviour prompt (first that applies) ----------
    bool _atWall = false
    if _nn > 0
        for _j = 0 to _nn - 1 by 1
            if array.get(nG, _j) and math.abs(array.get(nP, _j) - close) <= 2 * _mtol
                _atWall := true
                break
    string prompt = ''
    if i_q_ind and _inDn
        prompt := 'Early - ' + iTN_dn + ' ' + fp(iT_dn) + ' below not taken yet'
    else if i_q_ind and _inUp
        prompt := 'Early - ' + iTN_up + ' ' + fp(iT_up) + ' above not taken yet'
    else if i_q_ind and not na(iSw_dn)
        prompt := iTN_dn + ' swept - wait for the close back above ' + fp(iT_dn)
    else if i_q_ind and not na(iSw_up)
        prompt := iTN_up + ' swept - wait for the close back below ' + fp(iT_up)
    else if i_q_chase and not na(pct_used) and pct_used >= i_warn and (high >= a_hi or low <= a_lo)
        prompt := 'Chasing? New extreme at ' + f0(pct_used) + '% of budget'
    else if i_q_exh and not na(pct_used) and pct_used >= i_exh
        prompt := 'Budget spent - A+ only'
    else if i_q_neg and regFromGex and regSig == -1 and _atWall
        prompt := 'NEG gamma at a wall - let it prove itself'
 
    // ---------- drawing ----------
    if array.size(dL) > 0
        for _o = 0 to array.size(dL) - 1 by 1
            line.delete(array.get(dL, _o))
    if array.size(dB) > 0
        for _o = 0 to array.size(dB) - 1 by 1
            label.delete(array.get(dB, _o))
    if array.size(dX) > 0
        for _o = 0 to array.size(dX) - 1 by 1
            box.delete(array.get(dX, _o))
    array.clear(dL)
    array.clear(dB)
    array.clear(dX)
 
    int _xr = bar_index + i_pad
    int _xl = math.max(0, bar_index - i_back)
    int _xa = na(a_bar) ? _xl : math.max(a_bar, bar_index - 4500)
 
    // exposure bar scale: one scale for calls and puts, OI on its own
    float _mxR = 0.0
    float _mxO = 0.0
    if _nn > 0
        for _j = 0 to _nn - 1 by 1
            if array.get(nG, _j)
                _mxR := math.max(_mxR, math.max(array.get(nRC, _j), array.get(nRP, _j)))
                _mxO := math.max(_mxO, array.get(nOI, _j))
    bool _bars = i_mb and _mxR > 0
    int _half = math.max(2, math.round(i_mb_len / 2.0))
    int _xmid = _xr + i_mb_gap + _half
    int _xlb = _bars ? _xr + i_mb_gap + i_mb_len + 2 : _xr
    float _bh = not na(_visRange) and _visRange > 0 ? _visRange * i_mb_h : atrD * 0.02
 
    if _bars
        float _axLo = na
        float _axHi = na
        for _j = 0 to _nn - 1 by 1
            if array.get(nG, _j)
                float _pb = array.get(nP, _j)
                float _rc = array.get(nRC, _j)
                float _rp = array.get(nRP, _j)
                float _oj = array.get(nOI, _j)
                _axLo := na(_axLo) ? _pb : math.min(_axLo, _pb)
                _axHi := na(_axHi) ? _pb : math.max(_axHi, _pb)
                float _fc = _rc / _mxR
                float _fp = _rp / _mxR
                int _lc = _rc > 0 ? math.max(1, math.round((i_mb_sqrt ? math.sqrt(_fc) : _fc) * _half)) : 0
                int _lp = _rp > 0 ? math.max(1, math.round((i_mb_sqrt ? math.sqrt(_fp) : _fp) * _half)) : 0
                if _lc > 0
                    color _cc = color.new(col_cw, i_mb_op)
                    array.push(dX, box.new(_xmid, _pb + _bh, _xmid + _lc, _pb - _bh, border_color = _cc, border_width = 1, bgcolor = _cc))
                if _lp > 0
                    color _cp = color.new(col_pw, i_mb_op)
                    array.push(dX, box.new(_xmid - _lp, _pb + _bh, _xmid, _pb - _bh, border_color = _cp, border_width = 1, bgcolor = _cp))
                if _oj > 0 and _mxO > 0
                    float _fo = _oj / _mxO
                    int _lo2 = math.max(1, math.round((i_mb_sqrt ? math.sqrt(_fo) : _fo) * _half))
                    color _co = color.new(col_oi, math.min(95, i_mb_op + 15))
                    array.push(dX, box.new(_xmid, _pb - _bh, _xmid + _lo2, _pb - _bh * 1.55, border_color = _co, border_width = 1, bgcolor = _co))
        if not na(_axLo) and _axHi > _axLo
            array.push(dL, line.new(_xmid, _axLo, _xmid, _axHi, color = color.new(color.gray, 55), width = 1))
 
    if i_draw_lvls and _nn > 0
        float _lg = 0.02 * atrD
        float _lp = na
        int _col = 0
        for _j = 0 to _nn - 1 by 1
            bool _gw = array.get(nG, _j)
            bool _hasDol = array.get(nDn, _j) != ''
            if _gw or _hasDol
                float _pl = array.get(nP, _j)
                color _c = _gw ? (array.get(nCWd, _j) ? col_cw : col_pw) : col_dol
                string _sty = _gw or array.get(nNk, _j) ? line.style_solid : array.get(nD, _j) ? line.style_dashed : line.style_dotted
                array.push(dL, line.new(_xa, _pl, _xr, _pl, color = _c, width = _gw ? 2 : 1, style = _sty))
                _col := not na(_lp) and math.abs(_pl - _lp) < _lg ? (_col + 1) % 3 : 0
                _lp := _pl
                string _lt2 = str.replace_all(str.replace_all(array.get(nK, _j), '/PrjH', ''), '/PrjL', '')
                array.push(dB, label.new(_xlb + _col * i_stagger, _pl, _lt2, style = label.style_label_left, color = color.new(color.black, 100), textcolor = _c, size = size.small))
 
    if i_gex_on and not na(_flipEff)
        array.push(dL, line.new(_xa, _flipEff, _xr, _flipEff, color = col_flip, width = 1, style = line.style_dotted))
        array.push(dB, label.new(_xlb, _flipEff, 'flip', style = label.style_label_left, color = color.new(color.black, 100), textcolor = col_flip, size = size.tiny))
 
    if i_draw_prj and not na(proj_hi)
        array.push(dL, line.new(_xa, proj_hi, _xr, proj_hi, color = col_prj, width = 1, style = line.style_dashed))
        array.push(dL, line.new(_xa, proj_lo, _xr, proj_lo, color = col_prj, width = 1, style = line.style_dashed))
        array.push(dB, label.new(_xr, proj_hi, 'Prj ' + budTag, style = label.style_label_left, color = color.new(color.black, 100), textcolor = col_prj, size = size.tiny))
        array.push(dB, label.new(_xr, proj_lo, 'Prj ' + budTag, style = label.style_label_left, color = color.new(color.black, 100), textcolor = col_prj, size = size.tiny))
 
    if not na(zU_lo)
        array.push(dX, box.new(_xl, zU_hi + _zpad, _xr, zU_lo - _zpad, border_color = color.new(col_zone, 40), border_width = 1, bgcolor = col_zone))
        array.push(dB, label.new(_xl, zU_hi + _zpad, 'KEY', style = label.style_label_lower_left, color = color.new(color.black, 100), textcolor = color.new(col_zone, 0), size = size.tiny))
    if not na(zD_hi)
        array.push(dX, box.new(_xl, zD_hi + _zpad, _xr, zD_lo - _zpad, border_color = color.new(col_zone, 40), border_width = 1, bgcolor = col_zone))
        array.push(dB, label.new(_xl, zD_lo - _zpad, 'KEY', style = label.style_label_upper_left, color = color.new(color.black, 100), textcolor = color.new(col_zone, 0), size = size.tiny))
 
    if i_ind and not na(iT_dn)
        array.push(dX, box.new(_xl, iO_dn, _xr, iT_dn, border_color = color.new(col_ind, 60), border_width = 1, border_style = line.style_dashed, bgcolor = col_ind))
        array.push(dL, line.new(_xl, iT_dn, _xr, iT_dn, color = color.new(col_ind, 0), width = 2, style = line.style_dashed))
        array.push(dB, label.new(_xl, iT_dn, (na(iSw_dn) ? 'wait: ' : 'swept: ') + iTN_dn, style = label.style_label_upper_left, color = color.new(color.black, 100), textcolor = color.new(col_ind, 0), size = size.small))
    if i_ind and not na(iT_up)
        array.push(dX, box.new(_xl, iT_up, _xr, iO_up, border_color = color.new(col_ind, 60), border_width = 1, border_style = line.style_dashed, bgcolor = col_ind))
        array.push(dL, line.new(_xl, iT_up, _xr, iT_up, color = color.new(col_ind, 0), width = 2, style = line.style_dashed))
        array.push(dB, label.new(_xl, iT_up, (na(iSw_up) ? 'wait: ' : 'swept: ') + iTN_up, style = label.style_label_lower_left, color = color.new(color.black, 100), textcolor = color.new(col_ind, 0), size = size.small))
 
    // ---------- Power of 3 candles ----------
    if i_p3
        int _hw = math.max(1, math.round(i_p3_w / 2))
        int _b0 = bar_index + i_p3_off
        for _ci = 0 to 2 by 1
            float _o = _ci == 0 ? p2o : _ci == 1 ? p1o : a_px
            float _h = _ci == 0 ? p2h : _ci == 1 ? p1h : a_hi
            float _l = _ci == 0 ? p2l : _ci == 1 ? p1l : a_lo
            float _c = _ci == 0 ? p2c : _ci == 1 ? p1c : close
            if not na(_o) and not na(_h) and not na(_l) and not na(_c)
                int _x = _b0 + _ci * i_p3_gap
                color _pc = _c >= _o ? col_p3u : col_p3d
                float _top = math.max(_o, _c)
                float _bot = math.min(_o, _c)
                float _pd = _top == _bot ? syminfo.mintick * 0.5 : 0.0
                array.push(dL, line.new(_x, _h, _x, _l, color = _pc, width = 1))
                array.push(dX, box.new(_x - _hw, _top + _pd, _x + _hw, _bot - _pd, border_color = _pc, border_width = 1, border_style = _ci == 2 ? line.style_dashed : line.style_solid, bgcolor = color.new(_pc, _ci == 2 ? 55 : 25)))
                array.push(dL, line.new(_x - _hw - 1, _o, _x + _hw + 1, _o, color = col_p3o, width = 2))
                if i_p3_lbl
                    string _tg = _ci == 0 ? 'D-2' : _ci == 1 ? 'D-1' : 'TODAY'
                    string _tx = _tg + '\n' + f0(_h - _l) + ' pts\n▲' + f0(_h - _o) + ' ▼' + f0(_o - _l)
                    array.push(dB, label.new(_x, _l, _tx, style = label.style_label_up, color = color.new(color.black, 100), textcolor = color.gray, size = size.tiny))
 
    // ---------- panel ----------
    table.clear(tb, 0, 0, 1, 31)
    color _hbg = color.new(color.gray, 85)
    table.cell(tb, 0, 0, 'Sphinx KVP', text_color = color.gray, text_size = _txtsz, bgcolor = _hbg, text_halign = text.align_left)
    table.cell(tb, 1, 0, (chartSym == '' ? syminfo.ticker : chartSym) + '  ' + VER, text_color = color.gray, text_size = _txtsz, bgcolor = _hbg, text_halign = text.align_left)
    int rw = 1
    table.cell(tb, 0, rw, 'Status', text_color = color.gray, text_size = _txtsz, text_halign = text.align_left)
    table.cell(tb, 1, rw, stTxt, text_color = color.white, bgcolor = color.new(stCol, 25), text_size = _txtsz, text_halign = text.align_left)
    rw += 1
    if i_chk_on
        put(rw, 'Losses today', str.tostring(nLoss) + ' of ' + str.tostring(maxL) + (i_use_sleep ? '   ·   sleep ' + str.tostring(i_sleep) + '/5' : ''), stopped ? c_red : lowSleep ? c_amb : color.gray)
        rw += 1
        if i_chk_full and _nck > 0
            for _ci = 0 to _nck - 1 by 1
                bool _done = chkToday and array.get(ckB, _ci)
                put(rw, _done ? '  ✓' : '  ✗', array.get(ckN, _ci), _done ? c_grn : c_red)
                rw += 1
    string _srcTx = regFromGex ? (_useNet ? 'gamma, net' : 'gamma, flip') : 'from VIX'
    if gStale
        table.cell(tb, 0, rw, 'Gamma', text_color = color.gray, text_size = _txtsz, text_halign = text.align_left)
        table.cell(tb, 1, rw, 'From before the 18:00 open - 0DTE expired, paste today\'s string', text_color = color.white, bgcolor = color.new(c_red, 25), text_size = _txtsz, text_halign = text.align_left)
        rw += 1
    put(rw, 'Market mode', regTxt + '  (' + _srcTx + ')' + (regSplit ? '  ⚠ mixed: price ' + (_regFlip == 1 ? 'above' : 'below') + ' flip' : ''), regSig == 1 ? c_grn : regSig == -1 ? c_red : color.gray)
    rw += 1
    color _gc = na(pct_used) ? color.gray : pct_used >= i_exh ? c_red : pct_used >= i_warn ? c_amb : c_grn
    put(rw, gauge(pct_used), 'Range used ' + f0(day_rng) + ' of ' + f0(adr) + ' pts  (' + f0(pct_used) + '%)', _gc)
    rw += 1
    put(rw, 'Avg day (' + str.tostring(i_len) + 'd)', i_manual > 0 ? f0(adr) + ' pts  (manual)' : f0(adr) + ' pts', color.gray)
    rw += 1
    if _ivOk
        float _dv = _drOk ? (iv_ratio - 1.0) * 100.0 : float(na)
        string _vw = na(iv_ratio) ? '' : iv_ratio >= irHi ? 'bigger day than usual' : iv_ratio <= irLo ? 'quieter day than usual' : 'about normal'
        put(rw, volName + ' expects', f0(impl) + ' pts' + (na(implAdj) ? '' : '  (~' + f0(implAdj) + ' real)') + '  ·  ' + _vw + (na(_dv) ? '' : ' (' + (_dv >= 0 ? '+' : '') + f0(_dv) + '%)'), na(iv_ratio) ? color.gray : iv_ratio >= irHi ? c_red : iv_ratio <= irLo ? c_grn : color.gray)
        rw += 1
        string _fc = calN < i_cal_min ? 'calibrating (' + str.tostring(calN) + ' of ' + str.tostring(i_cal_min) + ' days)' : 'avg day off ' + f0(calErrDR) + '%  ·  VIX off ' + f0(calErrIV) + '%  ·  VIX runs ' + (calOver >= 1 ? '+' : '') + f0((calOver - 1.0) * 100.0) + '% vs real  (' + str.tostring(calN) + 'd)'
        put(rw, 'Forecast check', _fc, color.gray)
        rw += 1
    put(rw, 'Room ▲ / ▼', f0(rem_up) + ' / ' + f0(rem_dn) + ' pts' + (budTag == 'IV' ? '  (VIX)' : ''), color.gray)
    rw += 1
    if i_vix_on
        string _tsP = tsTxt == 'BACKWARD' ? 'Stressed - near-term fear' : tsTxt == 'CONTANGO' ? 'Calm' : tsTxt == 'FLAT' ? 'Edgy' : '-'
        string _vvP = na(vvChg) ? '' : '  ·  VVIX ' + (vvSpike ? 'rising fast' : 'steady') + ' (' + (vvChg >= 0 ? '+' : '') + f0(vvChg) + '%)'
        put(rw, volName + ' ' + f2(vm), _tsP + _vvP, vvSpike or tsTxt == 'BACKWARD' ? c_red : tsTxt == 'CONTANGO' ? c_grn : color.gray)
        rw += 1
    if atZ != ''
        put(rw, 'At key level', atZ, c_amb)
        rw += 1
    put(rw, 'Next key ▲', na(zU_lo) ? '-' : fp(zU_lo) + '  ' + zU_n + (not na(proj_hi) and zU_lo > proj_hi ? '  beyond budget' : ''), na(zU_lo) ? color.gray : not na(proj_hi) and zU_lo > proj_hi ? color.gray : c_amb)
    rw += 1
    put(rw, 'Next key ▼', na(zD_hi) ? '-' : fp(zD_hi) + '  ' + zD_n + (not na(proj_lo) and zD_hi < proj_lo ? '  beyond budget' : ''), na(zD_hi) ? color.gray : not na(proj_lo) and zD_hi < proj_lo ? color.gray : c_amb)
    rw += 1
    if i_ind
        put(rw, 'Don\'t fade ▲', na(iT_up) ? '-' : na(iSw_up) ? iON_up + ' ' + fp(iO_up) + '  ·  wait for ' + iTN_up + ' ' + fp(iT_up) : iTN_up + ' swept  ·  wait for close back below ' + fp(iT_up), na(iT_up) ? color.gray : color.new(col_ind, 0))
        rw += 1
        put(rw, 'Don\'t fade ▼', na(iT_dn) ? '-' : na(iSw_dn) ? iON_dn + ' ' + fp(iO_dn) + '  ·  wait for ' + iTN_dn + ' ' + fp(iT_dn) : iTN_dn + ' swept  ·  wait for close back above ' + fp(iT_dn), na(iT_dn) ? color.gray : color.new(col_ind, 0))
        rw += 1
    if prompt != ''
        table.cell(tb, 0, rw, 'Heads up', text_color = color.gray, text_size = _txtsz, text_halign = text.align_left)
        table.cell(tb, 1, rw, prompt, text_color = color.white, bgcolor = color.new(c_amb, 35), text_size = _txtsz, text_halign = text.align_left)
 
// ============================================================
// === ALERTS ===
//   Structure alerts only. Alerts snapshot inputs at creation, so
//   losses, cooldown and the checklist are deliberately chart-only.
//   Re-create alerts after pasting a new gamma string.
// ============================================================
alertcondition(evEnter, 'KVP: entered inducement', 'Price entered an inducement zone - the liquidity beyond the obvious level has not been taken')
alertcondition(evRecl, 'KVP: sweep and reclaim', 'Inducement liquidity swept and closed back inside')
alertcondition(evFail, 'KVP: sweep without reclaim', 'Inducement liquidity swept, no reclaim inside the window')
alertcondition(evZone, 'KVP: key zone reached', 'Price reached the nearest key zone')
alertcondition(evExh, 'KVP: budget exhausted', 'Daily range budget fully consumed')
 
// ============================================================
// === DATA WINDOW ===
// ============================================================
plot(pct_used, 'Budget used % (DR)', display = display.data_window)
plot(pct_iv, 'Budget used % (IV)', display = display.data_window)
plot(adr, 'DR', display = display.data_window)
plot(impl, 'Implied budget', display = display.data_window)
plot(iv_ratio, 'Implied / DR', display = display.data_window)
plot(ts9, 'VIX9D / VIX', display = display.data_window)
plot(vvChg, 'VVIX % vs 18:00', display = display.data_window)
plot(regSig, 'Regime (1 / 0 / -1)', display = display.data_window)
plot(volLean, 'Vol lean (1 / 0 / -1)', display = display.data_window)
plot(irHi, 'Bigger-day threshold', display = display.data_window)
plot(irLo, 'Quieter-day threshold', display = display.data_window)
plot(calOver, 'VIX / real range (median)', display = display.data_window)
plot(implAdj, 'VIX expects, adjusted', display = display.data_window)
plot(calN, 'Calibration days', display = display.data_window)

← 返回列表