CQ_(0)_[PRICE ACTION / CALCULATED LEVELS] v1

CQuevedo345 · study · 2286 行 · 点赞 53 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CQuevedo345
 
// Carlos Quevedo ◯
// Scpecial Characters: ↑ ↓ → ↔ ↨ © ▲ ▼ ✔ Δ 《 》 ⇶ ⇒ ⇔ ⇵ ↧ ↦ ↤ ↙ ↘ ↖ ↗  ↤ ↥ ↦ ↧ ⇆ ⇅ ⇈ ⇉ ⇊ ⇑ ⇒ ⇓ ⇗ ⇘ ■➙ ➘ ➚ ↷ ⇝ ↴ ↱ ↳ ≤ ≥
//                      ↑ ↓ → ↔ ↨ ©  ➚  ➘ ✔ Δ 《 》 ⇶ ⇒ ⇔ ⇵ ↧ ↦ ↥ ↤ ↙ ➘  ➚ ↖ ↤ ↥ ↦ ↧ ⇆ ⇅ ⇈ ⇉ ⇊ ⇑ ⇒ ⇓ ⇗ ⇘ ➙ ➘ ➚ ↷ ⇝ ↴ ↱ ↳
//                     ≤ ≥ ≡ ~ ꭍ ⸗ ○ ▫ ◌ ▬ ▲ ▼ ► ◄ ▪ ■ □ ⌂ ₿ ↘ 〰〰〰〰〰〰〰〰〰
//                     ┌└ ┘┐   🔀  💰💵💶💴💸🏧🧾📤📥🚙🛩️🏁🏳️🚩🚧🚦🚥▶️⏹️〰️✔️☑️🔝🔚🚀🛫🛬📌📋📈📉🪙💳🔋🪫🎯🎢🛝🐻🐻‍❄️
//                     🟢🔴🟠🐂🐻🎫🧸📱🖥️🖱️💾📹🏧⭕🛑📵❌❗❓❎✅🌐Ⓜ️🕡🕞🕛🕘🕠🕝🕚🕗🕣🕟🕜🕙📢🎤🔒🔓🗝️🧰
//                     🛜🆗🆙🆓#️⃣*️⃣0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣🔟🔢⏹️⏸️⏺️⏯️⏮️⏭️⏩⏪🔀🔁🔂◀️🔼🔽▶️⏬⏫⏏️⬆️⬇️➡️⬅️↘️↙️↖️↗️↕️↔️🔄️↪️↩️⤴️⤵️ℹ️🔤
//                     🔜🔙🔝🔚✔️➕➖✖️💲➖✖️🟰➗ ©️ ®️ ™️🔘🟩🟥🟧🟦⬛🟪⬜🟨◼️◻️◾🔶🔘🔹🔷🔺🔻🔲🔳💭🗯️💬🗨️
//                     | ¦ ⌈⌉ ⌊⌋ ⁞ ⁝ ⁘ ° ª º ⁔ ‿ ⁀ ⁐ – ⏓ ⏖ ⏔ ⏒ ⏑ ⌀ ⌁ ฿ ↜ ↝ ↞ ↥ ↺ ↻ ↷ ↶ ▢ ▣ ▤ ▥ ▦ ▧ ▨ ▩
//                     ◊ ▬ ▮ ▭ ▯ ▰ ▲ ▴ ▱ △ ▵ ◀ ◄ ◂ ▷ ▻ ▹ ◆ ▼▲▽△ ▾ ◇ ▽ ▿ ● ¯  ░ ▒ ▓ ▌▐ ▄ ▀
//                     ◌ ◍ ◎ ●⨀ ◓ ◒ ◙ ◚ ◛ ◖ ◐ ◕ ◜◝ ◟◞ ◡ ◥ ◤  ◢ ◣  ◧ ◨ ◘ ◩ ◪ ¯ _ Ɣ Ʌ ʭ ˪ ˬ ˆ ˭ • ↕ ─ │ ┌┐ └┘ ├ ┤ ┬ ┴ ┼ ☺ ☻
//                   ⌌⌍⌎⌏⌜⌝ ⌞⌟ △▽     ⌜△⌝ ⌞▽⌟    ▭▲▭    ▭▼▭
//                      ⅲ ⋿ ↀ ↇ ↁ ↈ ↂ ∓ √ ∛ ∜ ∕ ∖ ∠ ∡ ∢ ∣ ∤ ∥ ∦ ∧ ∨ ∩ ∪ ∯ ∰ ≇ ≈ ≉  ≌ ≋ ≊ ⋚ ⋛ » « ❶ ❷ ❸ ❹ ❺ ❻ ❼ ❽ ❾ ❿
//                     ⋯ ⋰ ⋱ ⋮ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⨞ ⨝ ⨤ ⨥ ⨢ ⨣ ⨦ ⨺ ⨹ ⨻ ⩵ ⩶ ⩷ ⩸ Ὄ
//                     ⨀ ⨁ ⨂ ⨃ ⨄ ⨅ ⨆ ⨌ ⨞ ⨶ ⨷ ⨸ ⨵ ⨴ ⨳ ⨲ ⨱ ⨰ ⨭⨮ ⨯ ⨬ ⨫ ⨪ ⨧ ⨨ ⨩ ⨦ ⨥ ⨤ ⨟ ⨝  ⨞◨   ⨞《   ⨞⋿   ⨞▢   ⨞◆
//                     ⨈ ⨇ Ο ο ฿ ↺ ↷ ↻ ↸ ↩ ↪ ↯ 😶📍⚓ 📌
//                     ℗ ® © ℃ ℉ ™ № ÷ − Ο ‖ ⟬ ⟭ ⟦ ⟧ ௹ Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ Ⅼ Ⅽ Ⅾ ⅼ ⅽ
//                     ⅟ ↉ ¼ ½ ¾ ⅓ ⅔ ⅕ ⅖ ⅗ ⅘ ⅙ ⅚ ⅐ ⅛ ⅜ ⅝ ⅞ ⅑ ⅒ ₀ ₁ ₂ ₃ ₄ ₅ ₆ ₇ ₈ ₉ ₍₎₊₋₌ ①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⓪⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴⓿❶❷❸❹❺❻❼❽❾❿
 
// MidTerm: 34999,43749,52499,61249,69998,78748,87498,96248,104998,113747,122497,131247,139997
 
//@version=6
indicator('CQ_(0)_[PRICE ACTION / CALCULATED LEVELS] v1', overlay = true, max_lines_count=500, max_boxes_count=500, max_labels_count=500, explicit_plot_zorder = true, max_bars_back = 5000)
 
// ═══════════════════════════════════════════════════════════════════════
// SCRIPT OVERVIEW
// ═══════════════════════════════════════════════════════════════════════
// Three independent price-level subsystems:
//   1. MID/LONG-TERM TARGETS — Mid-Term is now an auto-generated
//      anchor×multiplier ladder (same engine as
//      CQ_(M)_[MID-TERM OBJECTIVE LADDER]); Long-Term is now auto-generated
//      from macro Low→High ranges (same engine as
//      CQ_(MR)_[MACRO RANGE LADDER]). Both (+ current-year and
//      previous-year open axis lines, each independently toggled/colored)
//      extend left from the current bar. The summary table folds all
//      four sources into one ladder, suffixed M/L/Y/PY respectively.
//   2. ENTRY/TARGET EVENTS — two independent "grade" sets (Set 1 / Set 2),
//      each pairing entry prices with target prices at +25/50/100% labels.
//      Set 1 is filled automatically from the zigzag's last CONFIRMED leg
//      (Entry = 40/50/60/100%, Target = 125/160/200%) — zigzag engine
//      from CQ_(U)_Unconfirmed Leg Levels. Set 2 stays manually typed.
//      Label BACKGROUNDS of both sets follow the shared "Label Palette"
//      input (Entry = palette red tone, Target = palette green tone);
//      their LINES keep each set's own Line Color inputs.
//   3. REFERENCE LEVELS — up to 5 fully independent manual price levels,
//      each with its own style, offset, blink timing, and proximity alert.
//      Optionally, the gaps between consecutive levels (1↔2, 2↔3, 3↔4,
//      4↔5) can each be individually shaded with a color gradient built
//      from the two levels' own colors. When either boundary level's
//      Display Mode is set to Interval, the shade blinks in sync — it's
//      only drawn on ticks where BOTH boundary levels are visible.
//
// CAPTION MODE (🪙 C A P T I O N - M O D E group): a global switch for
// how every level's price caption is drawn — Mid/Long-Term, Current/
// Previous-Year Open, Set 1/2 Entry/Target and Reference Levels alike.
//   Labels: the classic pointer labels to the right of each line's end.
//   Boxes:  each caption is a thin box spanning its level's line, from the
//           line's start bar to its label offset. Text is aligned inside
//           it (Right by default, so it ends flush with the line tip) and
//           reads above or below the line per the Side input ("Away From
//           Price" = above for levels at/above close, below for levels
//           under it). Box height scales with price (≈0.001% of the level,
//           at least one tick), so it works on any symbol. Caption text
//           uses each level's own color instead of the black/white
//           contrast color (there's no solid label behind it anymore),
//           unless the global Label Text Color override is on. Boxes get
//           the same dynamic near/mid/far opacity as labels. Reference
//           Level description labels stay as labels in both modes.
//
// TABLE LAYOUT (🪙 T A B L E - L A Y O U T group): both summary tables
// can swap their NOW and ✓ columns (TARGET always stays in the center),
// or be merged into ONE table with a single NOW column (left/right, or
// top/bottom when horizontal), both TARGET columns side by side, and
// the two ladders vertically offset so both NOW values sit on one row.
//
// REDRAW MODEL: every subsystem above is gated by
// `not barstate.isconfirmed and barstate.isrealtime` — i.e. it only
// (re)draws on the live, unclosed bar. Each subsystem keeps a var line[]/
// label[] pair tracking exactly what it drew last tick; f_clearLines/
// f_clearLabels wipe those before every redraw so objects don't pile up
// against the indicator's 500-line/500-label cap. The gradient shading
// additionally tracks var linefill[] state, cleared via f_clearLinefills.
// Box captions (Boxes caption mode) share one var box[] (capBoxes),
// cleared once at the start of every realtime tick via f_clearBoxes —
// every subsystem redraws on every tick, so one shared tracker suffices.
//
// SHARED DRAWING: all three subsystems draw the same visual trio (main
// line + start/dot marker pair + price label), so that trio is built once
// in f_drawStartMarker and wrapped per-subsystem by
// f_drawTermLevel / f_drawEventLevel / f_drawRefLevel below — see the
// SHARED HELPER FUNCTIONS block for details on each.
//
// PERFORMANCE NOTES (v3.1 optimization pass):
//   - yearly_open and prevYearly_open (both '12M' timeframe) are now
//     fetched via ONE request.security tuple call instead of two.
//   - fourHOpenPrice ('240' timeframe) is now only requested when
//     show4HOpen is actually enabled, instead of unconditionally every bar.
//     dailyOpenPrice ('D' timeframe) follows the same rule via show1DOpen.
//   - Both summary tables (Mid/Long-Term and SHORT-TERM) had a redundant
//     "default far-opacity" initialization loop that colored every row,
//     immediately followed by two more loops (idxAbove/idxBelow) that
//     between them ALWAYS re-color every single row anyway (every price is
//     either >= close or < close, so the two sets fully cover every index).
//     That first pass never survived to be seen — it's been removed.
//   - The dominant remaining cost is the per-tick "↤Candle"/"Pivot" start-
//     bar search for Reference Levels (f_nearestObstructionBar /
//     f_nearestPivotBar), which scans back up to refBarsBack bars per
//     level. That cost is proportional to (days-back × 1440 / chart
//     timeframe-in-minutes), so it grows fast on low timeframes. It's
//     already skipped for any level with no price set (na guard inside
//     both functions) and for levels left on "Fixed" mode. On very low
//     timeframes with many "↤Candle"/"Pivot" levels active, lowering
//     "Start N days in the past" (refBarsBackDays) or switching busy
//     levels to "Fixed" mode is the most effective further speed-up —
//     doing that automatically would change the script's behavior, so
//     it's left as a user choice rather than baked in here.
// ═══════════════════════════════════════════════════════════════════════
 
/////////////////////////////////////////////////
////           START MARKERS (ALL)            ///
/////////////////////////////////////////////////
 
startMarkerLength = input.int(1, '─── Bar Length ', minval = 0, maxval = 10, inline = 'sm', group = '🪙 A L L - L E V E L S - S T A R T - M A R K E R S', tooltip = 'Length of the solid tick mark drawn at the start of every level (Mid/Long-Term, Entry/Target, and Reference levels).')
startMarkerWidth  = input.int(1, 'Width', minval = 1, maxval = 10, inline = 'sm', group = '🪙 A L L - L E V E L S - S T A R T - M A R K E R S', tooltip = 'Line thickness of the start tick mark.')
dottedMarkerLength = input.float(0.4, '..... % Length ', minval = 0.1, maxval = 5.0, step = 0.1, inline = 'dm', tooltip = 'Height of the small dotted vertical marker at the start of every level, as a % of price.')
dottedMarkerWidth  = input.int(1, 'Width', minval = 1, maxval = 10, inline = 'dm', tooltip = 'Line thickness of the dotted vertical marker.')
 
/////////////////////////////////////////////////////////////
////        G L O B A L   L A B E L   O F F S E T S        ///
/////////////////////////////////////////////////////////////
// One shared "Labels Offset" input per group, replacing the individual
// per-subsystem offset inputs that used to live inside each group's own
// section (Set 1, Set 2, Mid-Term, Long-Term, and
// each of the 10 Reference Levels each had their own). Every member of a
// group now scrolls to the same bar count, so nudging one input re-aligns
// every label in that group at once instead of hunting down N separate
// inputs scattered across N separate groups.
globalOffsetGroup   = '🪙 G L O B A L - L A B E L - O F F S E T S'
globalOffsetOthers  = input.int(35, 'Labels Offset — Entry-Target Events', minval = 0, maxval = 500, group = globalOffsetGroup, tooltip = 'Bars to the right of the current bar where price labels are placed for Set 1 and Set 2 Entry/Target Events. In Boxes caption mode, right-aligned captions end here.')
globalOffsetRef     = input.int(35, 'Labels Offset — Reference Levels (Ⅰ–Ⅹ)', minval = 0, maxval = 500, group = globalOffsetGroup, tooltip = 'Bars to the right of the current bar where price/description labels are placed for all 10 manual Reference Levels. Replaces what used to be 10 separate "Labels Offset" inputs, one inside each Reference Level group. In Boxes caption mode, right-aligned captions end here.')
globalOffsetMidLong = input.int(45, 'Labels Offset — Mid/Long-Term', minval = 0, maxval = 500, group = globalOffsetGroup, tooltip = 'Bars to the right of the current bar where price labels are placed for the Mid-Term targets, the Long-Term targets, and the Current-Year/Previous-Year Open axis lines. Replaces what used to be two separate offset inputs (Mid Term Offset and Long Term Offset). In Boxes caption mode, right-aligned captions end here.')
 
/////////////////////////////////////////////////////////////
////        L A B E L   T E X T   C O L O R   ( A L L )    ///
/////////////////////////////////////////////////////////////
// One shared text color for every chart label (Mid-Term, Long-Term,
// Current/Previous-Year Open, Set 1/2 Entry/Target, Reference Level price
// and description labels). OFF keeps each label's own automatic text
// color (f_contrastText / marker color / white). The dynamic near/mid/far
// opacity still fades the chosen color, same as before. Summary tables
// keep their own text colors.
labelTextGroup    = '🪙 L A B E L - T E X T - C O L O R'
labelTextOverride = input.bool(false, 'Custom Text Color For All Labels', inline = 'lbltxt', group = labelTextGroup)
labelTextColor    = input.color(color.white, '', inline = 'lbltxt', group = labelTextGroup, tooltip = 'ON: every chart label uses this text color. OFF: each label keeps its own automatic text color (black/white contrast, marker color, or white). Rank-based opacity still applies either way.')
 
// Returns the user-selected label text color when the override is on,
// else the label's own default text color.
f_lblText(_default) =>
    labelTextOverride ? labelTextColor : _default
 
/////////////////////////////////////////////////////////////
////        C A P T I O N   M O D E   ( A L L )            ///
/////////////////////////////////////////////////////////////
// Global switch between pointer labels and box captions for every level's
// price caption — see CAPTION MODE in the SCRIPT OVERVIEW above.
captionGroup = '🪙 C A P T I O N - M O D E'
captionMode  = input.string('Boxes', 'Caption Mode', options = ['Labels', 'Boxes'], inline = 'cap', group = captionGroup)
captionAlign = input.string('Right', 'Align', options = ['Left', 'Center', 'Right'], inline = 'cap', group = captionGroup, tooltip = 'Labels: classic pointer labels to the right of each line\'s end. Boxes: captions ride on the lines themselves, inside a thin box spanning each line from its start bar to its label offset. Align applies to Boxes only: Right ends the text at the label offset, Left starts it at the line\'s start bar.')
captionSide  = input.string('Away From Price', 'Side (Boxes)', options = ['Away From Price', 'Above', 'Below'], group = captionGroup, tooltip = 'Boxes mode only. Away From Price: captions of levels at/above the current price read above their line, levels below it read under their line. Above / Below: every caption on that side of its line.')
 
bool   capBoxMode = captionMode == 'Boxes'
string capHAl     = switch captionAlign
    'Left'   => text.align_left
    'Center' => text.align_center
    => text.align_right
 
////////////////////////////////////////////////////////////
////        R E A C H E D   M A R K E R   ( A L L )        ///
////////////////////////////////////////////////////////////
// Appends a checkmark to every chart price label (Mid-Term, Long-Term, Current/Previous-Year Open, Entry/Target Events,
// and Reference Levels) whose own price has traded through (between a
// bar's high and low) at any point within the lookback below — the same
// "reached" idea already used by the ✓ column in both summary tables,
// applied here to the on-chart labels themselves. Kept as its own
// independent lookback (rather than reusing mltReachedMonths/
// secReachedMonths, which are declared much later in the script where
// the tables' own inputs live) so every label can be marked regardless
// of chart draw order.
reachedMarkGroup  = '🪙 R E A C H E D   M A R K E R'
showReachedMark   = input.bool(true, 'Show ✓ On Reached Labels', group = reachedMarkGroup, tooltip = 'Appends a checkmark to any chart price label whose own price has traded through (between a bar\'s high and low) at any point within the lookback below.')
reachedMarkMonths = input.int(6, 'Reached Lookback (Months)', minval = 1, maxval = 60, group = reachedMarkGroup, tooltip = 'How far back (in months) to check whether a level has been reached, for the ✓ suffix on chart labels.')
 
// Converts a duration in days into an approximate bar count for the
// CURRENT chart timeframe — used everywhere this script needs to turn
// "N months/days back" into a bar count (the ✓-reached lookbacks below
// and refBarsBack further down). timeframe.in_seconds() reports the
// actual seconds-per-bar for any regular chart resolution (seconds,
// minutes, hours, Daily, Weekly, Monthly), so this works correctly on
// every one of them — unlike a raw `days * 1440 / timeframe.multiplier`,
// which silently assumes an intraday-minutes chart: on a Daily/Weekly/
// Monthly chart that produces a bar count in the tens of thousands,
// which then blows past this script's own max_bars_back = 5000 and
// throws a runtime "requested too many historical bars" error the
// moment it feeds a historical-index loop or a ta.highest/ta.lowest
// call below. On non-standard chart types (Range/Renko/Kagi/PnF) where
// timeframe.in_seconds() can return na, the old minutes-based formula
// is kept as a fallback. The result is always clamped to [1, 4999] so
// it's guaranteed to stay inside max_bars_back regardless of timeframe.
f_periodBars(_days) =>
    float _secsPerBar = timeframe.in_seconds(timeframe.period)
    int _bars = na(_secsPerBar) or _secsPerBar <= 0 ?
         int(_days * 1440 / math.max(1, timeframe.multiplier)) :
         int(_days * 86400 / _secsPerBar)
    int(math.min(math.max(_bars, 1), 4999))
 
// Computed unconditionally every bar, same reasoning as mltReachedHigh/Low
// and secReachedHigh/Low further down — ta.highest/ta.lowest should not be
// called conditionally.
reachedMarkBars = f_periodBars(reachedMarkMonths * 30)
reachedMarkHigh = ta.highest(high, reachedMarkBars)
reachedMarkLow  = ta.lowest(low, reachedMarkBars)
 
// Returns ' ✓' when the given price has been reached within the lookback
// above (and the toggle is on), else an empty string — appended directly
// onto a label's own text.
f_reachedSuffix(_price) =>
    (showReachedMark and not na(_price) and _price <= reachedMarkHigh and _price >= reachedMarkLow) ? ' ✓' : ''
 
////////////////////////////////////////////////////
////        SHARED  H E L P E R  FUNCTIONS        ///
////////////////////////////////////////////////////
// Every "level" drawn by this script — Mid/Long-Term targets, Entry/Target events, and Reference Levels — is visually the
// same three-part object: a main line, a start/dot marker pair, and a
// price label. Previously each section duplicated that trio inline
// (5 separate copies). It's now built once and parameterized, and array
// clearing (also duplicated 5x) is two one-line calls.
 
// Deletes and clears every line object in a tracking array before a redraw.
f_clearLines(_arr) =>
    if array.size(_arr) > 0
        for ln in _arr
            line.delete(ln)
        array.clear(_arr)
 
// Deletes and clears every label object in a tracking array before a redraw.
f_clearLabels(_arr) =>
    if array.size(_arr) > 0
        for lb in _arr
            label.delete(lb)
        array.clear(_arr)
 
// Deletes and clears every linefill object in a tracking array before a redraw.
f_clearLinefills(_arr) =>
    if array.size(_arr) > 0
        for lf in _arr
            linefill.delete(lf)
        array.clear(_arr)
 
// Deletes and clears every box object in a tracking array before a redraw.
f_clearBoxes(_arr) =>
    if array.size(_arr) > 0
        for bx in _arr
            box.delete(bx)
        array.clear(_arr)
 
// Solid start-marker tick + dotted vertical marker at the left edge of a level.
f_drawStartMarker(_bar, _price, _color) =>
    startLine = line.new(_bar - startMarkerLength, _price * 0.998, _bar + startMarkerLength, _price * 1.002,
         color = _color, width = startMarkerWidth, style = line.style_solid)
    dotLine = line.new(_bar, _price * (1 - dottedMarkerLength / 100), _bar, _price * (1 + dottedMarkerLength / 100),
         color = _color, width = dottedMarkerWidth, style = line.style_dotted)
    [startLine, dotLine]
 
// Blink/constant visibility helper shared by every "Display Mode" input pair.
f_eventsVisible(_mode, _showSec, _hideSec) =>
    _mode == 'Constant' ? true : (timenow % ((_showSec + _hideSec) * 1000) < _showSec * 1000)
 
// Maps a line-style input string to the actual line.style constant.
f_lineStyle(_style) =>
    _style == 'Dotted' ? line.style_dotted :
     _style == 'Dashed' ? line.style_dashed : line.style_solid
 
// ── DYNAMIC OPACITY (shared by both summary tables AND their matching
// chart lines/labels) ──────────────────────────────────────────────────
// Computes a price level's rank-based opacity %, using the exact same
// near/mid/far convention already used by the Mid/Long-Term and SHORT-TERM
// tables: ranked by distance to `close`, separately among the companion
// levels sitting above close and those sitting below it. The nearest
// level on each side gets _pctNear, the next-nearest gets _pctMid, and
// every other level gets _pctFar. `_companions` must be the same price
// pool a level's own summary-table row is ranked against, so the plotted
// line/label always matches that table's own opacity for the same level.
f_rankPct(_price, _companions, _close, _pctNear, _pctMid, _pctFar) =>
    float _pct = _pctFar
    if not na(_price)
        int _closerCount = 0
        if _price >= _close
            for p in _companions
                if not na(p) and p >= _close and p < _price
                    _closerCount := _closerCount + 1
        else
            for p in _companions
                if not na(p) and p < _close and p > _price
                    _closerCount := _closerCount + 1
        _pct := _closerCount == 0 ? _pctNear : _closerCount == 1 ? _pctMid : _pctFar
    _pct
 
// Parses a comma-separated price-list input into a float array once, so
// downstream consumers (dynamic-opacity ranking, chart drawing, and the
// summary tables) can iterate the numbers directly instead of each
// re-running str.tonumber() on the same strings — every price list here
// was previously reparsed three separate times per tick.
f_parsePrices(_strArr) =>
    _out = array.new_float(0)
    for x in _strArr
        array.push(_out, str.tonumber(x))
    _out
 
// Builds a price ladder from an anchor price and a multiplier array — the
// same anchor×multiplier engine used by CQ_(M)_[MID-TERM OBJECTIVE
// LADDER] — used to auto-generate the Mid-Term target list below instead
// of requiring it to be typed in as a fixed price list. No-ops (returns
// an empty array) while the anchor is unresolved or non-positive.
f_computeLadder(_anchor, _mults) =>
    _out = array.new_float(0)
    if not na(_anchor) and _anchor > 0
        for m in _mults
            if not na(m)
                array.push(_out, _anchor * m)
    _out
 
// Picks black or white text for legibility against a given background
// color, using the standard perceptual-luminance weighting (ITU-R
// BT.601: green reads brightest to the eye, blue darkest). Needed
// because label backgrounds now swing across the FULL opacity range
// (dynamic near/mid/far rank) instead of always sitting at one fixed,
// fairly transparent value — a light/bright background (yellow, light
// green, cyan…) at high opacity needs black text, not the flat white
// every label previously used regardless of its own color.
f_contrastText(_bgColor) =>
    _luminance = (color.r(_bgColor) * 299 + color.g(_bgColor) * 587 + color.b(_bgColor) * 114) / 1000
    _luminance > 150 ? color.black : color.white
 
// Set 1/2 Entry/Target events draw BEFORE the Reference Levels are known
// further down the script, so their rank can't be computed at draw time
// against the FULL SHORT-TERM-Table price pool. Instead,
// f_drawEventLevel/f_drawRefLevel register each
// level's main line + main label + price + base color here; a recolor
// pass placed right after the Reference Levels are drawn (once every
// SHORT-TERM-Table price source is finally known) rewrites each object's
// color via line.set_color/label.set_color with the correct dynamic
// opacity, keeping the object's own base color (hue) unchanged.
// secOpacityLabelColors holds each label's own BACKGROUND hue separately
// from its line hue (secOpacityBaseColors) — Entry/Target labels take
// their background from the Label Palette, while their lines keep the
// set's own Line Color. Reference Levels push the same color to both.
// secOpacityBoxes runs parallel to secOpacityLabels: in Boxes caption
// mode each entry holds the caption box and the label entry is na; in
// Labels mode it's the other way round. The recolor pass skips na ids.
var line[]  secOpacityLines       = array.new_line(0)
var label[] secOpacityLabels      = array.new_label(0)
var box[]   secOpacityBoxes       = array.new_box(0)
var float[] secOpacityPrices      = array.new_float(0)
var color[] secOpacityBaseColors  = array.new_color(0)
var color[] secOpacityLabelColors = array.new_color(0)
var color[] secOpacityTextColors  = array.new_color(0)
 
// Same tracker, for the Mid/Long-Term group (Mid-Term, Long-Term, and the
// Current/Previous-Year Open axis lines) — these draw before
// mltPctNear/mltPctMid/mltPctFar are declared further down the script
// (in the Mid/Long-Term Table inputs), so they need the same
// placeholder-then-recolor treatment.
var line[]  mltOpacityLines      = array.new_line(0)
var label[] mltOpacityLabels     = array.new_label(0)
var box[]   mltOpacityBoxes      = array.new_box(0)
var float[] mltOpacityPrices     = array.new_float(0)
var color[] mltOpacityBaseColors = array.new_color(0)
var color[] mltOpacityTextColors = array.new_color(0)
 
// Every caption box drawn this tick (Boxes caption mode), across all
// subsystems — cleared once at the start of each realtime tick.
var box[]   capBoxes = array.new_box(0)
 
// Box caption for one level (Boxes caption mode): a thin box spanning
// _left → _right on the level's line. Height scales with price (≈0.001%
// of the level, at least one tick). Above: box sits on the line with its
// text bottom-aligned, so the text reads above the line. Below: box
// hangs under the line with its text top-aligned, so it reads below.
// Registered in capBoxes for the next tick's cleanup.
f_capBox(_left, _right, _price, _txt, _bg, _tc, _size) =>
    float _h     = math.max(syminfo.mintick, _price * 0.00001)
    bool  _above = captionSide == 'Above' ? true : captionSide == 'Below' ? false : _price >= close
    bx = box.new(_left, _above ? _price + _h : _price, _right, _above ? _price : _price - _h, border_color = color(na), border_width = 0, bgcolor = _bg, text = _txt, text_size = _size, text_color = _tc, text_halign = capHAl, text_valign = _above ? text.align_bottom : text.align_top)
    array.push(capBoxes, bx)
    bx
 
// Persistent companion price pools, captured at draw time (when the
// underlying price lists are known) for the final recolor pass to reuse
// once the opacity-pct inputs of both tables are known.
var float[] mltCompanionPricesTracked = array.new_float(0)
var float[] secCompanionPricesTracked = array.new_float(0)
// Parallel tag array (same index as secCompanionPricesTracked) recording which
// SHORT-TERM-Table source group each companion price came from — 1 Set 1 Entry,
// 2 Set 2 Entry, 3 Set 1 Target, 4 Set 2 Target, 7 Reference Levels. The final recolor pass uses it to drop any
// group the user has switched OFF in the SHORT-TERM Table settings, so a
// chart line's rank-based opacity is always computed against exactly the
// same pool as its table row.
var int[]   secCompanionGroupsTracked = array.new_int(0)
 
// Pushes one price + its group tag into the SHORT-TERM companion pool.
f_pushSecCompanion(_price, _grp) =>
    if not na(_price)
        array.push(secCompanionPricesTracked, _price)
        array.push(secCompanionGroupsTracked, _grp)
 
// One Mid/Long-Term target level: line extended left + start marker + label.
// Shared by the Mid-Term and Long-Term loops. Line/label opacity starts at
// a neutral placeholder (50) — mltPctNear/mltPctMid/mltPctFar aren't
// declared yet at this point in the script (they live in the Mid/Long-Term
// Table inputs further down), so the real dynamic opacity is applied by
// the recolor pass after those inputs are known — see "DYNAMIC OPACITY —
// FINAL RECOLOR PASS" near the SHORT-TERM Table section. This function
// registers into mltOpacityLines/Labels/Prices/BaseColors for that pass.
// Label text color is caller-supplied via _textColor: Long-Term passes
// f_contrastText(LongTermColor) (auto black/white for legibility against
// its own background), while Mid-Term passes a fixed color.white — either
// is replaced by labelTextColor when the global text-color override is on.
// In Boxes caption mode the caption is a box from the current bar to the
// label offset instead, and its text uses the level's own line color.
f_drawTermLevel(_price, _offset, _lineColor, _lineWidth, _markerColor, _labelPrefix, _labelBgColor, _labelSize, _linesArr, _labelsArr, _textColor) =>
    _txt = f_lblText(capBoxMode ? _lineColor : _textColor)
    ln = line.new(bar_index, _price, bar_index + _offset, _price, extend = extend.left, color = color.new(_lineColor, 50), width = _lineWidth)
    array.push(_linesArr, ln)
    [sM, dM] = f_drawStartMarker(bar_index, _price, _markerColor)
    array.push(_linesArr, sM)
    array.push(_linesArr, dM)
    _capTxt = str.tostring(_price, _labelPrefix + ' $' + '0,000') + f_reachedSuffix(_price)
    label lbl = na
    box   bx  = na
    if capBoxMode
        bx := f_capBox(bar_index, bar_index + _offset, _price, _capTxt, color.new(_labelBgColor, 50), _txt, _labelSize)
    else
        lbl := label.new(last_bar_index + _offset, _price, _capTxt, style = label.style_label_left, color = color.new(_labelBgColor, 50), textcolor = _txt, size = _labelSize, textalign = text.align_left)
        array.push(_labelsArr, lbl)
    if not na(_price)
        array.push(mltOpacityLines, ln)
        array.push(mltOpacityLabels, lbl)
        array.push(mltOpacityBoxes, bx)
        array.push(mltOpacityPrices, _price)
        array.push(mltOpacityBaseColors, _lineColor)
        array.push(mltOpacityTextColors, _txt)
 
// One Entry/Target event level: line + start marker + label with a
// caller-supplied text (so the same function serves both Entry ticks,
// which count up "EVENT 1/2/3…", and Target ticks, which show "+25%/+50%…").
// _color drives the line; _labelColor drives the label background (the
// Label Palette's red tone for Entry, green tone for Target).
// Line/label opacity starts at a neutral placeholder (50), corrected by
// the dynamic-opacity recolor pass after the Reference Levels are drawn
// — this function registers into the secOpacityLines/Labels/Prices/
// BaseColors/LabelColors tracker for that pass.
// In Boxes caption mode the caption is a box spanning the event line
// (bar_index - 48 → label offset) instead of a label.
f_drawEventLevel(_price, _offset, _color, _labelColor, _markerColor, _lineWidth, _labelText, _linesArr, _labelsArr) =>
    _txt = f_lblText(_markerColor)
    ln = line.new(bar_index - 48, _price, bar_index + _offset, _price, color = color.new(_color, 50), width = _lineWidth)
    array.push(_linesArr, ln)
    [sM, dM] = f_drawStartMarker(bar_index - 48, _price, _markerColor)
    array.push(_linesArr, sM)
    array.push(_linesArr, dM)
    _capTxt = _labelText + f_reachedSuffix(_price)
    label lbl = na
    box   bx  = na
    if capBoxMode
        bx := f_capBox(bar_index - 48, bar_index + _offset, _price, _capTxt, color.new(_labelColor, 50), color.new(_txt, 0), size.small)
    else
        lbl := label.new(last_bar_index + _offset, _price, _capTxt, style = label.style_label_left, color = color.new(_labelColor, 50), textcolor = color.new(_txt, 0), size = size.small, textalign = text.align_left)
        array.push(_labelsArr, lbl)
    if not na(_price)
        array.push(secOpacityLines, ln)
        array.push(secOpacityLabels, lbl)
        array.push(secOpacityBoxes, bx)
        array.push(secOpacityPrices, _price)
        array.push(secOpacityBaseColors, _color)
        array.push(secOpacityLabelColors, _labelColor)
        array.push(secOpacityTextColors, _txt)
 
// A full Entry+Target event set (one "grade") from its two price lists.
// Set 1 and Set 2 both call this instead of duplicating the two loops
// (this collapsed ~90 duplicated lines down to one function).
// _targetPcts: ratios matching _targetPrices one-to-one (Set 1 passes
// ulTargetRatios, so its labels read the real 125/160/200% levels). Pass
// an empty array to keep the original 25/50/100… label stepping (Set 2).
// _earlyCount: how many leading entries are labeled EARLY 1, EARLY 2…;
// the rest restart at EVENT 1 (Set 1 passes 2 → EARLY 1, EARLY 2,
// EVENT 1, EVENT 2; Set 2 passes 0 → EVENT 1, 2, 3…).
// _entryLabelColor / _targetLabelColor: label background colors (from
// the Label Palette), independent of the line colors.
f_drawEventSet(_entryPrices, _targetPrices, _targetPcts, _earlyCount, _entryColor, _entryLabelColor, _entryTextColor, _targetColor, _targetLabelColor, _targetTextColor, _offset, _lineWidth, _linesArr, _labelsArr) =>
    count = 1
    for y in _entryPrices
        entryTxt = count <= _earlyCount ? 'EARLY ' + str.tostring(count, '0') : 'EVENT ' + str.tostring(count - _earlyCount, '0')
        f_drawEventLevel(y, _offset, _entryColor, _entryLabelColor, _entryTextColor, _lineWidth, entryTxt + '\n' + str.tostring(y, '$0,000'), _linesArr, _labelsArr)
        count := count + 1
    // Target labels step 25 -> 50 -> 100 -> 125 -> 150…: 75% is deliberately
    // skipped (the += 25 after reaching 75 jumps straight to 100) — original
    // behavior, preserved as-is rather than "fixed", since it may be
    // intentional round-number labeling rather than a bug.
    percentage = 25
    for [i, y] in _targetPrices
        pctTxt = array.size(_targetPcts) > i ? str.tostring(math.round(array.get(_targetPcts, i) * 100), '0') : str.tostring(percentage, '0')
        f_drawEventLevel(y, _offset, _targetColor, _targetLabelColor, _targetTextColor, _lineWidth, '🎯+' + pctTxt + '%' + '\n' + str.tostring(y, '$0,000'), _linesArr, _labelsArr)
        percentage := percentage + 25
        if percentage >= 75
            percentage := percentage + 25
 
// One Reference Level: line (variable style) + start marker + price label +
// optional description label. Line/price-label opacity starts at a
// neutral placeholder (50/70) — secPctNear/secPctMid/secPctFar aren't
// declared yet at this point in the script (they live in the SHORT-TERM
// Table inputs further down), so the real dynamic opacity comes from the
// recolor pass placed after those inputs are known (see "DYNAMIC
// OPACITY — FINAL RECOLOR PASS" near the SHORT-TERM Table section). This
// function registers its main line + price label into secOpacityLines/
// Labels/Prices/BaseColors for that pass; the description label (a
// SHORT-TERM annotation, not "the" level line/label) keeps its original
// fixed opacity. In Boxes caption mode the price caption is a box
// spanning the line (start bar → end bar) with text in the level's own
// color; the description label stays a label in both modes.
f_drawRefLevel(_price, _desc, _color, _width, _style, _futureBars, _startBar, _extendLeft, _linesArr, _labelsArr) =>
    if not na(_price)
        startBar = _startBar
        endBar   = bar_index + _futureBars
        _txt     = f_lblText(capBoxMode ? _color : f_contrastText(_color))
 
        refLine = line.new(startBar, _price, endBar, _price,
                           xloc = xloc.bar_index,
                           extend = _extendLeft ? extend.left : extend.none,
                           color = color.new(_color, 50),
                           width = _width,
                           style = f_lineStyle(_style))
        array.push(_linesArr, refLine)
 
        [markerLine, dotLine] = f_drawStartMarker(startBar, _price, _color)
        array.push(_linesArr, markerLine)
        array.push(_linesArr, dotLine)
 
        _capTxt = str.tostring(_price, '$0,000') + f_reachedSuffix(_price)
        label priceLabel = na
        box   priceBox   = na
        if capBoxMode
            priceBox := f_capBox(startBar, endBar, _price, _capTxt, color.new(_color, 50), _txt, size.small)
        else
            priceLabel := label.new(endBar, _price,
                                   _capTxt,
                                   style = label.style_label_left,
                                   color = color.new(_color, 50),
                                   textcolor = _txt,
                                   size = size.small,
                                   textalign = text.align_left)
            array.push(_labelsArr, priceLabel)
 
        array.push(secOpacityLines, refLine)
        array.push(secOpacityLabels, priceLabel)
        array.push(secOpacityBoxes, priceBox)
        array.push(secOpacityPrices, _price)
        array.push(secOpacityBaseColors, _color)
        array.push(secOpacityLabelColors, _color)
        array.push(secOpacityTextColors, _txt)
 
        if _desc != ''
            descLabel = label.new(endBar + 4, _price * 1.002,
                                  _desc,
                                  style = label.style_label_down,
                                  color = color.new(_color, 70),
                                  textcolor = f_lblText(f_contrastText(_color)),
                                  size = size.tiny,
                                  textalign = text.align_left)
            array.push(_labelsArr, descLabel)
 
// Gradient shading between two reference levels, built from N stacked
// linefill bands so the fill visually blends from _color1 (at _price1) to
// _color2 (at _price2) using color.from_gradient per band — linefill
// itself only accepts one flat color, so the "gradient" is simulated by
// slicing the price gap into bands, each with its own interpolated color.
// Orientation-safe: if _price1 > _price2 the color/price pairing is
// swapped internally so the gradient still runs low-price -> high-price.
// Skips entirely (no-op) if either price is unset (na).
f_drawGradientShade(_price1, _color1, _price2, _color2, _startBar, _endBar, _bands, _transparency, _linesArr, _fillsArr) =>
    if not na(_price1) and not na(_price2)
        float _lo = math.min(_price1, _price2)
        float _hi = math.max(_price1, _price2)
        color _colorLo = _price1 <= _price2 ? _color1 : _color2
        color _colorHi = _price1 <= _price2 ? _color2 : _color1
        for i = 0 to _bands - 1
            float _pA = _lo + (_hi - _lo) * i / _bands
            float _pB = _lo + (_hi - _lo) * (i + 1) / _bands
            color _bandColor = color.from_gradient((i + 0.5) / _bands, 0.0, 1.0, _colorLo, _colorHi)
            lnA = line.new(_startBar, _pA, _endBar, _pA, xloc = xloc.bar_index, color = color.new(_bandColor, 100), width = 1)
            lnB = line.new(_startBar, _pB, _endBar, _pB, xloc = xloc.bar_index, color = color.new(_bandColor, 100), width = 1)
            array.push(_linesArr, lnA)
            array.push(_linesArr, lnB)
            lf = linefill.new(lnA, lnB, color.new(_bandColor, _transparency))
            array.push(_fillsArr, lf)
 
// Weekly open — used only by the SHORT-TERM Table's automatic 1W Open row.
sundayOpen = request.security(syminfo.tickerid, 'W', open, lookahead = barmerge.lookahead_on)
 
// Cleared once each realtime tick, before any subsystem registers into
// the cross-subsystem dynamic-opacity tracker (secOpacityLines/Labels/
// Prices/BaseColors, see the SHARED HELPER FUNCTIONS block) so it never
// mixes entries from different ticks. secCompanionPricesTracked is then
// rebuilt incrementally by the Set 1/2 Entry/Target and Reference Levels
// blocks below. Every caption box from the previous tick (capBoxes) is
// deleted here too, since every subsystem redraws its captions below.
if not barstate.isconfirmed and barstate.isrealtime
    f_clearBoxes(capBoxes)
    array.clear(secOpacityLines)
    array.clear(secOpacityLabels)
    array.clear(secOpacityBoxes)
    array.clear(secOpacityPrices)
    array.clear(secOpacityBaseColors)
    array.clear(secOpacityLabelColors)
    array.clear(secOpacityTextColors)
    array.clear(secCompanionPricesTracked)
    array.clear(secCompanionGroupsTracked)
 
////////////////////////////////////////////
////        ENTRY / TARGET EVENTS        ///
////////////////////////////////////////////
// Two fully independent copies of the same idea ("Set 1" = shorter/noisier
// 4H grade, "Set 2" = larger/cleaner 4H grade): a list of entry prices and
// a list of target prices, each pair drawn via f_drawEventSet. Target
// labels count 25%, 50%, 100%, 125%, 150%… — see the percentage stepping
// note inside f_drawEventSet above (75% is intentionally skipped).
// Each set also has its own blink/constant Display Mode, independent of
// the Reference Levels' Display Mode inputs below.
 
// INPUTS
// yearly_open and prevYearly_open both pull the '12M' series — merged
// into ONE request.security tuple call instead of two separate calls
// (prevYearly_open just reads one bar further back, open[1], on that
// same higher-timeframe series).
[yearly_open, prevYearly_open] = request.security(syminfo.tickerid, '12M', [open, open[1]], lookahead = barmerge.lookahead_on)
 
showSet1 = input.bool(true, '    PLOT [4H SHORTER GRADE (More Noise)]', group = '🪙 E N T R Y - A N D - T A R G E T - E V E N T S', tooltip = 'Show/hide the Set 1 Entry/Target event lines and labels.')
 
// === Palette Definitions ===
// Shared label-background scheme for BOTH Set 1 and Set 2 Entry/Target
// event labels: Entry labels use colorRed, Target labels use colorGreen.
// Only the label backgrounds follow this palette — event lines keep each
// set's own Line Color inputs, and the dynamic near/mid/far opacity still
// fades the palette color (its transparency is always overridden by the
// recolor pass, so the fallback colorRed's built-in 100 transparency does
// not make labels invisible).
palette = input.string('Classic', '    🎨 Label Palette', options = ['Classic', 'Ocean', 'Sunset', 'Neon', 'Monochrome', 'Desert', 'Oldbook', 'OldWest', 'Default'], group = '🪙 E N T R Y - A N D - T A R G E T - E V E N T S', tooltip = 'Background color scheme for the Entry and Target event labels of both Set 1 and Set 2. Entry labels use the palette\'s red tone, Target labels its green tone. Lines keep their own Line Color inputs. "Default" uses the bright fallback colors.')
colorGreen = palette == 'Classic' ? color.rgb(0, 57, 55) : palette == 'Ocean' ? color.rgb(0, 54, 93) : palette == 'Sunset' ? color.rgb(102, 61, 0) : palette == 'Neon' ? color.rgb(0, 80, 145) : palette == 'Monochrome' ? color.rgb(117, 117, 117) : palette == 'Desert' ? color.rgb(0, 39, 35) : palette == 'Oldbook' ? color.rgb(63, 73, 7) : palette == 'OldWest' ? color.rgb(63, 77, 3) : color.rgb(0, 255, 191)
colorRed   = palette == 'Classic' ? color.rgb(72, 0, 0)  : palette == 'Ocean' ? color.rgb(0, 20, 85) : palette == 'Sunset' ? color.rgb(35, 34, 32) : palette == 'Neon' ? color.rgb(42, 45, 51) : palette == 'Monochrome' ? color.rgb(65, 65, 65) : palette == 'Desert' ? color.rgb(61, 37, 0) : palette == 'Oldbook' ? color.rgb(49, 43, 5)    : palette == 'OldWest' ? color.rgb(49, 10, 0) : color.rgb(255, 0, 0, 100)
 
event_entry_Color   = input.color(color.rgb(0, 38, 255),   title = '    Line Color', inline = 'entry', tooltip = 'Color of the Set 1 Entry event lines (and their SHORT-TERM Table rows). Label backgrounds follow the Label Palette.')
event_entry_tColor  = input.color(color.rgb(52, 197, 255), title = '    Text Color', inline = 'entry', tooltip = 'Marker/text color of the Set 1 Entry event lines and labels.')
 
event_target_Color   = input.color(color.rgb(40, 143,   0), title = '    Line Color', inline = 'target', tooltip = 'Color of the Set 1 Target event lines (and their SHORT-TERM Table rows). Label backgrounds follow the Label Palette.')
event_target_tColor  = input.color(color.rgb(72, 255, 0),   title = '    Text Color', inline = 'target', tooltip = 'Marker/text color of the Set 1 Target event lines and labels.')
 
// ── AUTO LEVELS FROM THE LAST CONFIRMED LEG (Set 1) ─────────────────────
// Zigzag engine ported from CQ_(U)_Unconfirmed Leg Levels (same as the
// Phase Counter). ulZ holds pivots newest first: ulZ[0] is the newest
// pivot, which can still shift while price keeps making new extremes, so
// the leg ending there is unconfirmed. The last CONFIRMED leg is the one
// before it, from ulZ[4] (leg start) to ulZ[2] (leg end) — both of its
// pivots are locked in, because a newer pivot in the opposite direction
// (ulZ[0]) already exists. Set 1 is always filled from this leg:
// Entry = 40/50/60/100%, Target = 125/160/200% (rounded to whole
// numbers). The levels only change when a new pivot confirms the next leg.
ulPeriod = input.int(45, '    Auto Levels — ZigZag Period', minval = 2, inline = 'ulauto', group = '🪙 E N T R Y - A N D - T A R G E T - E V E N T S', tooltip = 'Lookback length in bars of the zigzag whose last CONFIRMED leg (the pivot-to-pivot leg before the still-developing one) feeds the auto Entry/Target levels. Runs on the chart timeframe.')
ulInvert = input.bool(false, 'Invert', inline = 'ulauto', group = '🪙 E N T R Y - A N D - T A R G E T - E V E N T S', tooltip = 'On: 0% = leg start, 100% = leg end (last confirmed pivot), so 125/160/200 project forward in the leg\'s direction.\nOff (default): 0% = leg end (last confirmed pivot), 100% = leg start, so 40/50/60 read as retracements and 125/160/200 extend beyond the leg start.')
 
ulPh = ta.highestbars(high, ulPeriod) == 0 ? high : na
ulPl = ta.lowestbars(low, ulPeriod) == 0 ? low : na
 
var int ulDir = 0
ulPrevDir = ulDir
ulDir := not na(ulPh) and na(ulPl) ? 1 : not na(ulPl) and na(ulPh) ? -1 : ulDir
 
var ulZ = array.new_float()   // [price0, time0, price1, time1, ...] newest first
if not na(ulPh) or not na(ulPl)
    ulV = ulDir == 1 ? ulPh : ulPl
    if ulDir != ulPrevDir
        ulZ.unshift(time)
        ulZ.unshift(ulV)
    else if not (not na(ulPh) and not na(ulPl)) and ulZ.size() > 0 and (ulDir == 1 ? ulV > ulZ.get(0) : ulV < ulZ.get(0))
        ulZ.set(0, ulV)
        ulZ.set(1, time)
 
var ulEntryRatios  = array.from(0.40, 0.50, 0.60, 1.00)
var ulTargetRatios = array.from(1.25, 1.60, 2.00)
 
// Prices of the given ratios on the last confirmed leg (empty until the
// zigzag has at least three pivots). ulZ layout: [price0, time0, price1,
// time1, price2, time2, ...] → ulZ.get(2) = leg end, ulZ.get(4) = leg start.
f_ulLevels(_ratios) =>
    _out = array.new_float(0)
    if ulZ.size() >= 6
        _p0   = ulInvert ? ulZ.get(4) : ulZ.get(2)   // 0% anchor
        _p100 = ulInvert ? ulZ.get(2) : ulZ.get(4)   // 100% anchor
        for r in _ratios
            _out.push(math.round(_p0 + (_p100 - _p0) * r))
    _out
 
// Set 1's own "Offset for Events/Targets" input was removed — Set 1 now
// uses globalOffsetOthers (see the 🪙 G L O B A L - L A B E L - O F F S E T S
// group near the top of the script), the same shared offset as Set 2.
 
// Display modes
set1DisplayMode = input.string('Constant', 'Display Mode', options = ['Constant', 'Interval'], inline = 'edisp1', tooltip = 'Constant = always visible. Interval = blinks on/off using the Show/Hide seconds below.')
set1ShowSeconds = input.int(5, 'Show (sec)', minval = 1, inline = 'edisp1', tooltip = 'Seconds Set 1 stays visible during each blink cycle (Interval display mode only).')
set1HideSeconds = input.int(2, 'Hide (sec)', minval = 1, inline = 'edisp1', tooltip = 'Seconds Set 1 stays hidden during each blink cycle (Interval display mode only).')
 
// --- SET 2: second independent Entry/Target event group ---
showSet2 = input.bool(true, '    PLOT [4H LARGER GRADE (Less Noise)]', group = '🪙 E N T R Y - A N D - T A R G E T - E V E N T S - 2', tooltip = 'Show/hide the Set 2 Entry/Target event lines and labels.')
eventsEntry2  = input.text_area('', '    💶Entry Event [4H LARGER GRADE]',  tooltip = 'Enter prices comma separated without any spaces.', group = '🪙 E N T R Y - A N D - T A R G E T - E V E N T S - 2')
event_entry_Color2   = input.color(color.rgb(0, 38, 255),   title = '    Line Color', inline = 'entry2', tooltip = 'Color of the Set 2 Entry event lines (and their SHORT-TERM Table rows). Label backgrounds follow the Label Palette.')
event_entry_tColor2  = input.color(color.rgb(52, 197, 255), title = '    Text Color', inline = 'entry2', tooltip = 'Marker/text color of the Set 2 Entry event lines and labels.')
 
eventsTarget2 = input.text_area('', '    🎯Event Target (Set 2)', tooltip = 'Enter prices comma separated without any spaces.', group = '🪙 E N T R Y - A N D - T A R G E T - E V E N T S - 2')
event_target_Color2  = input.color(color.rgb(40, 143,   0), title = '    Line Color', inline = 'target2', tooltip = 'Color of the Set 2 Target event lines (and their SHORT-TERM Table rows). Label backgrounds follow the Label Palette.')
event_target_tColor2 = input.color(color.rgb(72, 255, 0),   title = '    Text Color', inline = 'target2', tooltip = 'Marker/text color of the Set 2 Target event lines and labels.')
 
// Set 2's own "Offset for Events/Targets (Set 2)" input was removed for
// the same reason as Set 1's above — it now also uses globalOffsetOthers.
 
// Display modes
set2DisplayMode = input.string('Constant', 'Display Mode', options = ['Constant', 'Interval'], inline = 'edisp2', tooltip = 'Constant = always visible. Interval = blinks on/off using the Show/Hide seconds below.')
set2ShowSeconds = input.int(5, 'Show (sec)', minval = 1, inline = 'edisp2', tooltip = 'Seconds Set 2 stays visible during each blink cycle (Interval display mode only).')
set2HideSeconds = input.int(2, 'Hide (sec)', minval = 1, inline = 'edisp2', tooltip = 'Seconds Set 2 stays hidden during each blink cycle (Interval display mode only).')
 
showMidTerm = input(title='Mid Term ', defval=true, group='🪙 S H O W / H I D E - M I D / L O N G - T E R M', inline = 'mtf', tooltip = 'Show/hide the Mid-Term target lines and labels on the chart. Independent of the Mid/Long-Term summary table, which always includes Mid-Term rows regardless of this toggle.')
showLongTerm = input(title='Long Term ', defval=true, group='🪙 S H O W / H I D E - M I D / L O N G - T E R M', inline = 'mtf', tooltip = 'Show/hide the Long-Term target lines and labels, plus the Current-Year/Previous-Year Open axis lines, on the chart. Independent of the Mid/Long-Term summary table, which always includes Long-Term/Yearly-Open rows regardless of this toggle.')
 
// NOTE: the manual "Line Opacity (50: Darker/90: Lighter)" input
// previously here was removed — Set 1/Set 2 Entry/Target line+label
// opacity is now driven automatically by the same dynamic near/mid/far
// rank-vs-close opacity used by the SHORT-TERM Table (secPctNear/
// secPctMid/secPctFar), so a fixed shared opacity input had nothing
// left to control.
 
MidTermAnchorOverride = input.float(0.0, 'Anchor Override (0 = Year Open)', minval = 0.0, tooltip = 'Leave at 0 to anchor the Mid-Term ladder to the OPEN of the current year (same anchor used by the Current-Year-Open axis line below). Set a price to force a different anchor.', group = '🪙 M I D - T E R M - T A R G E T S ')
MidTermMultipliers = input.text_area('0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6', 'Targets [M I D - T E R M] — Multipliers', tooltip = 'Comma-separated multipliers applied to the anchor above to auto-generate the Mid-Term price ladder — same anchor×multiplier engine as CQ_(M)_[MID-TERM OBJECTIVE LADDER]. Edit, add, or remove freely; replaces what used to be a manually-typed price list.', group = '🪙 M I D - T E R M - T A R G E T S ')
MidTermColor = input.color(color.rgb(255, 200, 0), 'Mid Term Color', tooltip = 'Color of the Mid-Term target lines and labels.')
MidTermWidth = input.int(1, 'Width', inline = 'MidTerm', tooltip = 'Line thickness of the Mid-Term target lines.')
 
// ── LONG-TERM TARGETS — AUTO FROM MACRO RANGES ──────────────────────────
// Ported from CQ_(MR)_[MACRO RANGE LADDER]. Each enabled range (a cycle Low
// and a cycle High, normally the ATH) produces one rung per ratio in the
// Ratio List:   level = Low + ratio × (High − Low)
//   ratio < 1 → retracement inside the range · 1 → the High · > 1 → extension.
// With the ATH toggle on, a range's High follows the symbol's all-time high
// (read from the WEEKLY series, so it covers far more history than a
// low-timeframe chart has loaded), and every extension rung recalculates
// when a new ATH prints. Rungs from DIFFERENT ranges within the tolerance %
// of each other can be merged into one rung at their average price.
// Replaces the former manually-typed Long-Term price list.
ltGroup   = '🪙 L O N G - T E R M  - T A R G E T S '
ltAthAll  = input.bool(false, 'Use Weekly ATH For All Ranges', group = ltGroup, tooltip = 'Overrides the High of every enabled range with the symbol\'s all-time high (highest weekly high). Extension rungs (ratio > 1) then recalculate automatically each time price makes a new ATH. Leave OFF to use each range\'s own High (or its Auto High toggle).')
ltAOn     = input.bool(true, 'Range A', inline = 'ltA0', group = ltGroup)
ltAAuto   = input.bool(false, 'Auto High = ATH', inline = 'ltA0', group = ltGroup, tooltip = 'Range A: the current cycle\'s full range (bear-market low → cycle ATH). Auto High uses the weekly ATH as this range\'s High instead of the High input.')
ltALow    = input.float(15476.0, 'Low', minval = 0, inline = 'ltA1', group = ltGroup)
ltAHigh   = input.float(126199.0, 'High', minval = 0, inline = 'ltA1', group = ltGroup, tooltip = 'Default: Nov 2022 low ≈ 15,476 → Oct 2025 ATH ≈ 126,199. Use the exact weekly wicks of your feed. Skipped if High is not above Low.')
ltBOn     = input.bool(true, 'Range B', inline = 'ltB0', group = ltGroup)
ltBAuto   = input.bool(false, 'Auto High = ATH', inline = 'ltB0', group = ltGroup, tooltip = 'Range B: the secondary crash low that preceded the ATH run. Auto High uses the weekly ATH as this range\'s High.')
ltBLow    = input.float(49000.0, 'Low', minval = 0, inline = 'ltB1', group = ltGroup)
ltBHigh   = input.float(126199.0, 'High', minval = 0, inline = 'ltB1', group = ltGroup, tooltip = 'Default: Aug 2024 low ≈ 49,000 → Oct 2025 ATH ≈ 126,199. Skipped if High is not above Low.')
ltCOn     = input.bool(false, 'Range C', inline = 'ltC0', group = ltGroup)
ltCAuto   = input.bool(false, 'Auto High = ATH', inline = 'ltC0', group = ltGroup, tooltip = 'Range C: prior-cycle reference frame (off by default). Usually leave Auto High OFF.')
ltCLow    = input.float(3122.0, 'Low', minval = 0, inline = 'ltC1', group = ltGroup)
ltCHigh   = input.float(69000.0, 'High', minval = 0, inline = 'ltC1', group = ltGroup, tooltip = 'Default: Dec 2018 low 3,122 → Nov 2021 ATH 69,000 (1.618 = 109,713 · 2.0 = 134,878). Low 3,850 gives 0.618 = 44,113 and 1.5 = 101,575.')
ltRatioTxt = input.string('0.382, 0.5, 0.618, 1, 1.5, 1.618, 2', 'Ratio List', group = ltGroup, tooltip = 'Comma-separated ratios applied to every enabled range. Each produces one rung: Low + ratio × (High − Low). Spaces are ignored; invalid entries are skipped; rungs at or below zero are dropped.')
ltCfMerge = input.bool(true, 'Merge Confluence', inline = 'ltcf', group = ltGroup)
ltCfTol   = input.float(0.75, 'Tolerance %', minval = 0.01, step = 0.05, inline = 'ltcf', group = ltGroup, tooltip = 'Merge Confluence ON: rungs from two or more DIFFERENT ranges within this % of the cluster\'s lowest rung collapse into one rung at their average price (rungs of the same range never merge). OFF: every rung is kept at its own price.')
LongTermAxis = yearly_open
PrevYearlyAxis = prevYearly_open
 
LongTermColor = input.color(color.rgb(0, 85, 255), 'Long Term Label Color', tooltip = 'Color of the Long-Term target lines and labels.')
// NOTE: the "Long Term Text Color" input previously here was removed —
// Mid/Long-Term label text color is now picked automatically via
// f_contrastText for guaranteed legibility against the label's own
// (now dynamically-opaque) background, unless the global
// 🪙 L A B E L - T E X T - C O L O R override is switched on.
LongTermWidth = input.int(2, 'Width', inline = 'LongTerm', tooltip = 'Line thickness of the Long-Term target lines. Also reused for the Entry/Target event lines.')
 
// Current/Previous-year open axis lines — grouped together since they're
// the same idea (a year's open plotted as a line+label) at two different
// anchor points. Each gets its own show toggle + color so either can be
// turned off or restyled independently.
yearlyOpenGroup = '🪙 Y E A R L Y - O P E N - L I N E S'
showCurrentYearlyOpen = input.bool(true, 'Show Current Year Open', inline = 'yopenA', group = yearlyOpenGroup, tooltip = 'Show/hide the current-year open axis line and label.')
CurrentYearlyOpenColor = input.color(color.rgb(131, 255, 59), 'Color', inline = 'yopenA', group = yearlyOpenGroup, tooltip = 'Color of the current-year open axis line and label.')
showPrevYearlyOpen = input.bool(true, 'Show Previous Year Open', inline = 'yopenB', group = yearlyOpenGroup, tooltip = 'Show/hide the previous-year open axis line and label.')
PrevYearlyOpenColor = input.color(color.rgb(0, 255, 128), 'Color', inline = 'yopenB', group = yearlyOpenGroup, tooltip = 'Color of the previous-year open axis line and label.')
 
// "Mid Term Offset" and "Long Term Offset" were previously two separate
// inputs here. Both now read from the shared globalOffsetMidLong input
// (see the 🪙 G L O B A L - L A B E L - O F F S E T S group near the top
// of the script) — that single input also covers the Current-Year/
// Previous-Year Open axis lines below, which used to reuse MidTerm_offset.
 
// NOTE: the manual "ALL TF Label Opacity" input previously here was
// removed for the same reason as LinesOpacity above — Mid-Term,
// Long-Term, and Entry/Target event LABEL opacity are all now driven by
// the same dynamic rank-vs-close opacity as their matching line (and, in
// turn, their matching summary-table row), so a fixed shared label
// opacity input had nothing left to control.
 
// Price Arrays
var aMidTermMults    = str.split(MidTermMultipliers, ',')
var aeventsEntry2  = str.split(eventsEntry2, ',')
var aeventsTarget2 = str.split(eventsTarget2,',')
// Parsed once each — inputs are static, so this never needs to re-run after bar 0. pMidTerm is the
// exception: its own multipliers list (pMidTermMults) is static and
// parsed once here like the rest, but the LADDER ITSELF is computed
// fresh every bar just below, since its anchor (yearly_open, or
// MidTermAnchorOverride) can change when a new year begins.
var float[] pMidTermMults   = f_parsePrices(aMidTermMults)
var float[] pEventsEntry2   = f_parsePrices(aeventsEntry2)
var float[] pEventsTarget2  = f_parsePrices(aeventsTarget2)
 
// Set 1 Entry/Target: auto levels of the last confirmed zigzag leg —
// recomputed every bar (not a "var") so a newly confirmed leg is picked
// up on the bar its pivot confirms.
pEventsEntry  = f_ulLevels(ulEntryRatios)
pEventsTarget = f_ulLevels(ulTargetRatios)
 
// Mid-Term ladder — anchor×multiplier engine (see f_computeLadder above),
// same convention as CQ_(M)_[MID-TERM OBJECTIVE LADDER]. Recomputed
// unconditionally every bar (not a "var", unlike every other price list
// above) because its anchor tracks yearly_open, which itself updates once
// per year rather than staying fixed like a typed-in price list.
MidTermAnchor = MidTermAnchorOverride > 0.0 ? MidTermAnchorOverride : yearly_open
pMidTerm = f_computeLadder(MidTermAnchor, pMidTermMults)
 
// Long-Term ladder — macro-range engine (see the 🪙 L O N G - T E R M
// inputs above). ATH = running max of the WEEKLY high, so it isn't limited
// by how much history the current (lower) chart timeframe has loaded.
ltWeeklyAth = request.security(syminfo.tickerid, 'W', ta.max(high))
 
// Ratio list, parsed once on the first bar (spaces stripped).
var float[] ltRatios = array.new_float(0)
if barstate.isfirst
    for part in str.split(ltRatioTxt, ',')
        float v = str.tonumber(str.replace_all(part, ' ', ''))
        if not na(v)
            array.push(ltRatios, v)
 
// Collects every enabled range's rungs, then (optionally) merges clusters
// of rungs from 2+ different ranges within ltCfTol % into their average.
// Output is rounded to whole dollars, ascending.
f_macroLadder(_ath) =>
    _rawP = array.new_float(0)
    _rawS = array.new_int(0)
    for s = 0 to 2
        bool  _on = s == 0 ? ltAOn : s == 1 ? ltBOn : ltCOn
        float _lo = s == 0 ? ltALow : s == 1 ? ltBLow : ltCLow
        bool  _au = ltAthAll or (s == 0 ? ltAAuto : s == 1 ? ltBAuto : ltCAuto)
        float _hi = _au ? _ath : (s == 0 ? ltAHigh : s == 1 ? ltBHigh : ltCHigh)
        if _on and not na(_hi) and _hi > _lo
            for r in ltRatios
                float _p = _lo + r * (_hi - _lo)
                if _p > 0
                    array.push(_rawP, _p)
                    array.push(_rawS, s)
    _out = array.new_float(0)
    int _n = array.size(_rawP)
    if _n > 0
        _idx = array.sort_indices(_rawP, order.ascending)
        int _i = 0
        while _i < _n
            float _anchor = array.get(_rawP, array.get(_idx, _i))
            int _j = _i + 1
            while _j < _n
                if math.abs(array.get(_rawP, array.get(_idx, _j)) - _anchor) / _anchor * 100 > ltCfTol
                    break
                _j += 1
            bool _hasA = false
            bool _hasB = false
            bool _hasC = false
            for m = _i to _j - 1
                int _src = array.get(_rawS, array.get(_idx, m))
                _hasA := _hasA or _src == 0
                _hasB := _hasB or _src == 1
                _hasC := _hasC or _src == 2
            int _distinct = (_hasA ? 1 : 0) + (_hasB ? 1 : 0) + (_hasC ? 1 : 0)
            if ltCfMerge and _distinct >= 2
                float _sum = 0.0
                for m = _i to _j - 1
                    _sum += array.get(_rawP, array.get(_idx, m))
                array.push(_out, math.round(_sum / (_j - _i)))
            else
                for m = _i to _j - 1
                    array.push(_out, math.round(array.get(_rawP, array.get(_idx, m))))
            _i := _j
    _out
 
// Only the last bar consumes pLongTerm (realtime draw blocks and both
// islast tables), so the ladder is built there and left empty on
// historical bars instead of re-running the collect/sort/merge every bar.
pLongTerm = barstate.islast ? f_macroLadder(ltWeeklyAth) : array.new_float(0)
 
// Tracking arrays
var line[]  set1Lines  = array.new_line(0)
var label[] set1Labels = array.new_label(0)
var line[]  set2Lines  = array.new_line(0)
var label[] set2Labels = array.new_label(0)
 
var line[]  longTermLines  = array.new_line(0)
var label[] longTermLabels = array.new_label(0)
var line[]  midTermLines   = array.new_line(0)
var label[] midTermLabels  = array.new_label(0)
 
// Display price arrays and respective timeframe Central AXIS
if not barstate.isconfirmed and barstate.isrealtime
    f_clearLines(longTermLines)
    f_clearLabels(longTermLabels)
    f_clearLines(midTermLines)
    f_clearLabels(midTermLabels)
    array.clear(mltOpacityLines)
    array.clear(mltOpacityLabels)
    array.clear(mltOpacityBoxes)
    array.clear(mltOpacityPrices)
    array.clear(mltOpacityBaseColors)
    array.clear(mltOpacityTextColors)
 
    // Companion pool for this tick's dynamic-opacity ranking — the exact
    // same sources as the Mid/Long-Term Table (Mid-Term + Long-Term
    // targets, plus the Current/Previous-Year Open axis prices when their
    // own toggle is on). mltPctNear/mltPctMid/mltPctFar (declared further
    // down, in the Mid/Long-Term Table inputs) aren't available yet at
    // this point in the script, so — same as the SHORT-TERM group's
    // Entry-Target/Reference levels — every line/label here draws
    // with a neutral placeholder opacity now and gets its real dynamic
    // opacity from the single recolor pass placed after both tables'
    // opacity inputs are declared (see "DYNAMIC OPACITY — FINAL RECOLOR
    // PASS" near the SHORT-TERM Table section). The companion pool itself
    // IS fully known already, so it's captured now into a persistent
    // array for that later pass to reuse.
    array.clear(mltCompanionPricesTracked)
    for y in pMidTerm
        if not na(y)
            array.push(mltCompanionPricesTracked, y)
    for y in pLongTerm
        if not na(y)
            array.push(mltCompanionPricesTracked, y)
    if showCurrentYearlyOpen
        array.push(mltCompanionPricesTracked, yearly_open)
    if showPrevYearlyOpen
        array.push(mltCompanionPricesTracked, prevYearly_open)
 
    if showLongTerm
        for y in pLongTerm
            f_drawTermLevel(y, globalOffsetMidLong, LongTermColor, LongTermWidth, LongTermColor, 'LT', LongTermColor, size.small, longTermLines, longTermLabels, f_contrastText(LongTermColor))
 
        // Current-year axis line — unique styling (slight slope, upper-left
        // label), kept as its own block rather than folded into
        // f_drawTermLevel. Color is user-selected via CurrentYearlyOpenColor;
        // opacity (placeholder here, corrected by the later recolor pass)
        // will end up the same dynamic rank-vs-close value as its table row.
        // In Boxes caption mode the label becomes a box caption.
        if showCurrentYearlyOpen
            axisTxt = f_lblText(capBoxMode ? CurrentYearlyOpenColor : f_contrastText(CurrentYearlyOpenColor))
            axisLine = line.new(bar_index, LongTermAxis + 1, bar_index + globalOffsetMidLong, LongTermAxis, extend = extend.left, color = color.new(CurrentYearlyOpenColor, 50), width = MidTermWidth)
            array.push(longTermLines, axisLine)
            [axisStart, axisDot] = f_drawStartMarker(bar_index, LongTermAxis, CurrentYearlyOpenColor)
            array.push(longTermLines, axisStart)
            array.push(longTermLines, axisDot)
            axisCap = str.tostring(LongTermAxis, '⨀Y $' + '0,000') + f_reachedSuffix(LongTermAxis)
            label axisLabel = na
            box   axisBox   = na
            if capBoxMode
                axisBox := f_capBox(bar_index, bar_index + globalOffsetMidLong, LongTermAxis, axisCap, color.new(CurrentYearlyOpenColor, 50), axisTxt, size.small)
            else
                axisLabel := label.new(last_bar_index + globalOffsetMidLong, LongTermAxis, axisCap, style = label.style_label_upper_left, color = color.new(CurrentYearlyOpenColor, 50), textcolor = axisTxt, size = size.small, textalign = text.align_left)
                array.push(longTermLabels, axisLabel)
            array.push(mltOpacityLines, axisLine)
            array.push(mltOpacityLabels, axisLabel)
            array.push(mltOpacityBoxes, axisBox)
            array.push(mltOpacityPrices, LongTermAxis)
            array.push(mltOpacityBaseColors, CurrentYearlyOpenColor)
            array.push(mltOpacityTextColors, axisTxt)
 
        // Previous-year axis line — same styling pattern as the current-year
        // axis above, distinguished by its own color and label prefix ('⨀PY').
        if showPrevYearlyOpen
            prevAxisTxt = f_lblText(capBoxMode ? PrevYearlyOpenColor : f_contrastText(PrevYearlyOpenColor))
            prevAxisLine = line.new(bar_index, PrevYearlyAxis + 1, bar_index + globalOffsetMidLong, PrevYearlyAxis, extend = extend.left, color = color.new(PrevYearlyOpenColor, 50), width = MidTermWidth)
            array.push(longTermLines, prevAxisLine)
            [prevAxisStart, prevAxisDot] = f_drawStartMarker(bar_index, PrevYearlyAxis, PrevYearlyOpenColor)
            array.push(longTermLines, prevAxisStart)
            array.push(longTermLines, prevAxisDot)
            prevAxisCap = str.tostring(PrevYearlyAxis, '⨀PY $' + '0,000') + f_reachedSuffix(PrevYearlyAxis)
            label prevAxisLabel = na
            box   prevAxisBox   = na
            if capBoxMode
                prevAxisBox := f_capBox(bar_index, bar_index + globalOffsetMidLong, PrevYearlyAxis, prevAxisCap, color.new(PrevYearlyOpenColor, 50), prevAxisTxt, size.small)
            else
                prevAxisLabel := label.new(last_bar_index + globalOffsetMidLong, PrevYearlyAxis, prevAxisCap, style = label.style_label_upper_left, color = color.new(PrevYearlyOpenColor, 50), textcolor = prevAxisTxt, size = size.small, textalign = text.align_left)
                array.push(longTermLabels, prevAxisLabel)
            array.push(mltOpacityLines, prevAxisLine)
            array.push(mltOpacityLabels, prevAxisLabel)
            array.push(mltOpacityBoxes, prevAxisBox)
            array.push(mltOpacityPrices, PrevYearlyAxis)
            array.push(mltOpacityBaseColors, PrevYearlyOpenColor)
            array.push(mltOpacityTextColors, prevAxisTxt)
 
    if showMidTerm
        for y in pMidTerm
            f_drawTermLevel(y, globalOffsetMidLong, MidTermColor, MidTermWidth, MidTermColor, 'MT', MidTermColor, size.small, midTermLines, midTermLabels, color.white)
 
    // Set 1/2 Entry/Target prices join the SHORT-TERM group's companion
    // pool here — their own arrays are only just built above.
    for y in pEventsEntry
        f_pushSecCompanion(y, 1)
    for y in pEventsEntry2
        f_pushSecCompanion(y, 2)
    for y in pEventsTarget
        f_pushSecCompanion(y, 3)
    for y in pEventsTarget2
        f_pushSecCompanion(y, 4)
 
    // ENTRY + TARGET EVENTS (SET 1) — label backgrounds from the palette
    // (Entry = colorRed, Target = colorGreen).
    f_clearLines(set1Lines)
    f_clearLabels(set1Labels)
    if showSet1 and f_eventsVisible(set1DisplayMode, set1ShowSeconds, set1HideSeconds)
        f_drawEventSet(pEventsEntry, pEventsTarget, ulTargetRatios, 2, event_entry_Color, colorRed, event_entry_tColor, event_target_Color, colorGreen, event_target_tColor, globalOffsetOthers, LongTermWidth, set1Lines, set1Labels)
 
    // ENTRY + TARGET EVENTS (SET 2) — same palette mapping as Set 1.
    f_clearLines(set2Lines)
    f_clearLabels(set2Labels)
    if showSet2 and f_eventsVisible(set2DisplayMode, set2ShowSeconds, set2HideSeconds)
        f_drawEventSet(pEventsEntry2, pEventsTarget2, array.new_float(0), 0, event_entry_Color2, colorRed, event_entry_tColor2, event_target_Color2, colorGreen, event_target_tColor2, globalOffsetOthers, LongTermWidth, set2Lines, set2Labels)
 
////////////////////////////////////////////
////    END ENTRY / TARGET EVENTS        ///
////////////////////////////////////////////
 
 
////////////////////////////////////////////////////////////
//      R A N D O M / R E F E R E N C E  P R I C E S     ///
////////////////////////////////////////////////////////////
// Up to 5 fully independent manual levels (ref1Group…ref5Group), each with
// its own price, color, width, line style, offset, blink timing, and
// alert distance — unlike the other three subsystems, these aren't driven
// by a comma-separated price list. A level with price input left at 0.0
// is treated as "unset" (ref#Price becomes na) and f_drawRefLevel/the
// alertcondition below both no-op for it. Alert conditions live in global
// scope (outside the realtime-only draw block) so they still evaluate on
// confirmed bars, not just while a level is visibly drawn.
 
// --- GLOBAL SETTINGS FOR REFERENCE LEVELS ---
refGlobalGroup = '🪙 R E F E R E N C E - P R I C E - L E V E L S'
refBarsBackDays  = input.int(14, 'Start N days in the past', minval = 1, maxval = 60, group = refGlobalGroup, tooltip = 'The anchor point (in days back) a Fixed-mode Reference Level line extends left from — the line itself continues indefinitely past this point. Also the fallback (and the search range for ↤Candle/Pivot modes) if a level\'s Pivot/↤Candle mode has nothing to latch onto yet.')
refPivotLookback = input.int(5, 'Pivot Lookback (bars each side)', minval = 5, maxval = 100, group = refGlobalGroup, tooltip = 'Bars required on each side of a swing high/low for it to count as a confirmed pivot. Only used by levels set to Pivot mode.')
refPivotPriceTolerance = input.float(250.0, 'Pivot Price Tolerance ($)', minval = 1.0, maxval = 100000.0, group = refGlobalGroup, tooltip = 'When a level\'s Line Start Mode is Pivot, only a confirmed swing high/low priced within this many dollars of the level\'s own price counts as a match for its start bar.')
 
// constant default for the per-level Alert Distance input
const float refAlertDefaultConst  = 250.0
 
// NOTE: an earlier version of the script also had "Default future
// extension (bars)" and "Default alert distance ($)" input controls
// here. Their results were never read anywhere — ref1–ref10 used a
// refDefaultFutureConst/refAlertDefaultConst constant directly as their
// own input defvals instead — so those two inputs did nothing when
// changed, and were removed as dead code. The per-level "Labels Offset"
// input that used refDefaultFutureConst has since been removed in turn,
// replaced by the single globalOffsetRef input in the 🪙 G L O B A L -
// L A B E L - O F F S E T S group near the top of the script, so only
// refAlertDefaultConst (for the per-level Alert Distance input) remains.
 
// Convert days to bars for the current chart timeframe — see f_periodBars
// above (declared in the 🪙 R E A C H E D   M A R K E R section near the
// top of the script) for why this is timeframe-in-seconds-based rather
// than a raw minutes-multiplier formula, and why it's capped at 4999.
refBarsBack = f_periodBars(refBarsBackDays)
 
// Confirmed swing pivot series (high or low). ta.pivothigh/pivotlow only
// return a non-na value on the bar where a pivot gets CONFIRMED — i.e.
// refPivotLookback bars after the actual swing extreme — and that
// returned value is the swing's own price. Indexing pivotHigh[i]/pivotLow[i]
// lets f_nearestPivotBar below walk back through every historical
// confirmation without maintaining a separate array.
pivotHigh = ta.pivothigh(high, refPivotLookback, refPivotLookback)
pivotLow  = ta.pivotlow(low, refPivotLookback, refPivotLookback)
 
// Scans backward through confirmed swing pivots (high and low) for the
// most recent one whose own price fell within _tolerance dollars of
// _price — unlike a plain "nearest in time" pivot, this only matches a
// pivot that also sits near the level's own price. Confirmation bar i
// corresponds to a swing that actually formed refPivotLookback bars
// earlier, so the returned bar is offset back by that lookback. Falls
// back to na (caller then uses the fixed bars-back default) if nothing
// within tolerance is found in the search window.
f_nearestPivotBar(_price, _tolerance, _maxBarsBack) =>
    int _bar = na
    if not na(_price)
        for i = 0 to _maxBarsBack - 1
            ph = pivotHigh[i]
            pl = pivotLow[i]
            if not na(ph) and math.abs(ph - _price) <= _tolerance
                _bar := bar_index - i - refPivotLookback
                break
            if not na(pl) and math.abs(pl - _price) <= _tolerance
                _bar := bar_index - i - refPivotLookback
                break
    _bar
 
// Scans left bar-by-bar from the current bar for the first one whose
// open/close body contains _price — i.e. the nearest candle that would
// visually "obstruct" a horizontal line at that price. Unlike the pivot
// search (chart-structure based, shared across levels), this is specific
// to each level's own price. Falls back to the fixed bars-back count if
// nothing obstructs within the search window. Wicks are ignored — only a candle's
// open/close body counts as an obstruction.
f_nearestObstructionBar(_price, _maxBarsBack) =>
    int _bar = bar_index - _maxBarsBack
    if not na(_price)
        for i = 1 to _maxBarsBack
            bodyTop = math.max(open[i], close[i])
            bodyBottom = math.min(open[i], close[i])
            if bodyBottom <= _price and bodyTop >= _price
                _bar := bar_index - i
                break
    _bar
 
// Resolves a level's own Line Start Mode into an absolute start bar.
// Only runs the scan its own mode actually needs — f_nearestPivotBar and
// f_nearestObstructionBar can each walk thousands of bars (refBarsBack),
// so with 10 ref levels defaulting to '↤Candle', computing the Pivot scan
// unconditionally for all of them (its result then discarded) was pure
// waste on every realtime tick.
f_refStartBar(_price, _mode) =>
    int _result = bar_index - refBarsBack
    if _mode == 'Pivot'
        pivotBar = f_nearestPivotBar(_price, refPivotPriceTolerance, refBarsBack)
        _result := na(pivotBar) ? bar_index - refBarsBack : pivotBar
    else if _mode == '↤Candle'
        _result := f_nearestObstructionBar(_price, refBarsBack)
    _result
 
// --- PER LEVEL INPUTS (UP TO 5) ---
// Each level's inputs are grouped onto three inline rows: Price/Desc keep
// their own lines (long text fields don't compress well); Color+Width+
// Style share one row; Offset+Alert-Distance share one row; Display
// Mode+Show/Hide seconds share one row.
ref1Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅰ ]'
ref1PriceInput   = input.float(0.0, 'Price Level 1', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref1Group)
ref1Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref1Group)
ref1Price        = ref1PriceInput == 0.0 ? na : ref1PriceInput
ref1Color        = input.color(color.rgb(255, 0, 0), 'Color', inline = 'r1a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref1Group)
ref1Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r1a', tooltip = 'Line thickness for this level.', group = ref1Group)
ref1Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r1a', tooltip = 'Line style used to draw this level.', group = ref1Group)
ref1StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r1a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref1Group)
ref1AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r1b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref1Group)
 
ref2Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅱ ]'
ref2PriceInput   = input.float(0.0, 'Price Level 2', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref2Group)
ref2Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref2Group)
ref2Price        = ref2PriceInput == 0.0 ? na : ref2PriceInput
ref2Color        = input.color(color.rgb(255, 0, 0), 'Color', inline = 'r2a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref2Group)
ref2Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r2a', tooltip = 'Line thickness for this level.', group = ref2Group)
ref2Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r2a', tooltip = 'Line style used to draw this level.', group = ref2Group)
ref2StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r2a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref2Group)
ref2AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r2b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref2Group)
 
ref3Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅲ ]'
ref3PriceInput   = input.float(0.0, 'Price Level 3', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref3Group)
ref3Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref3Group)
ref3Price        = ref3PriceInput == 0.0 ? na : ref3PriceInput
ref3Color        = input.color(color.rgb(255, 0, 255), 'Color', inline = 'r3a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref3Group)
ref3Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r3a', tooltip = 'Line thickness for this level.', group = ref3Group)
ref3Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r3a', tooltip = 'Line style used to draw this level.', group = ref3Group)
ref3StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r3a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref3Group)
ref3AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r3b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref3Group)
 
ref4Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅳ ]'
ref4PriceInput   = input.float(0.0, 'Price Level 4', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref4Group)
ref4Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref4Group)
ref4Price        = ref4PriceInput == 0.0 ? na : ref4PriceInput
ref4Color        = input.color(color.rgb(0, 255, 0), 'Color', inline = 'r4a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref4Group)
ref4Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r4a', tooltip = 'Line thickness for this level.', group = ref4Group)
ref4Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r4a', tooltip = 'Line style used to draw this level.', group = ref4Group)
ref4StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r4a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref4Group)
ref4AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r4b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref4Group)
 
ref5Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅴ ]'
ref5PriceInput   = input.float(0.0, 'Price Level 5', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref5Group)
ref5Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref5Group)
ref5Price        = ref5PriceInput == 0.0 ? na : ref5PriceInput
ref5Color        = input.color(color.rgb(255, 128, 0), 'Color', inline = 'r5a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref5Group)
ref5Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r5a', tooltip = 'Line thickness for this level.', group = ref5Group)
ref5Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r5a', tooltip = 'Line style used to draw this level.', group = ref5Group)
ref5StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r5a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref5Group)
ref5AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r5b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref5Group)
 
ref6Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅵ ]'
ref6PriceInput   = input.float(0.0, 'Price Level 6', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref6Group)
ref6Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref6Group)
ref6Price        = ref6PriceInput == 0.0 ? na : ref6PriceInput
ref6Color        = input.color(color.rgb(0, 148, 255), 'Color', inline = 'r6a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref6Group)
ref6Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r6a', tooltip = 'Line thickness for this level.', group = ref6Group)
ref6Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r6a', tooltip = 'Line style used to draw this level.', group = ref6Group)
ref6StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r6a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref6Group)
ref6AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r6b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref6Group)
 
ref7Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅶ ]'
ref7PriceInput   = input.float(0.0, 'Price Level 7', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref7Group)
ref7Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref7Group)
ref7Price        = ref7PriceInput == 0.0 ? na : ref7PriceInput
ref7Color        = input.color(color.rgb(255, 230, 0), 'Color', inline = 'r7a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref7Group)
ref7Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r7a', tooltip = 'Line thickness for this level.', group = ref7Group)
ref7Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r7a', tooltip = 'Line style used to draw this level.', group = ref7Group)
ref7StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r7a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref7Group)
ref7AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r7b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref7Group)
 
ref8Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅷ ]'
ref8PriceInput   = input.float(0.0, 'Price Level 8', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref8Group)
ref8Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref8Group)
ref8Price        = ref8PriceInput == 0.0 ? na : ref8PriceInput
ref8Color        = input.color(color.rgb(0, 255, 200), 'Color', inline = 'r8a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref8Group)
ref8Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r8a', tooltip = 'Line thickness for this level.', group = ref8Group)
ref8Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r8a', tooltip = 'Line style used to draw this level.', group = ref8Group)
ref8StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r8a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref8Group)
ref8AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r8b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref8Group)
 
ref9Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅸ ]'
ref9PriceInput   = input.float(0.0, 'Price Level 9', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref9Group)
ref9Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref9Group)
ref9Price        = ref9PriceInput == 0.0 ? na : ref9PriceInput
ref9Color        = input.color(color.rgb(170, 0, 255), 'Color', inline = 'r9a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref9Group)
ref9Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r9a', tooltip = 'Line thickness for this level.', group = ref9Group)
ref9Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r9a', tooltip = 'Line style used to draw this level.', group = ref9Group)
ref9StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r9a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref9Group)
ref9AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r9b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref9Group)
 
ref10Group = '🪙 R E F E R E N C E - L E V E L - [ Ⅹ ]'
ref10PriceInput   = input.float(0.0, 'Price Level 10', tooltip = 'Manual price for this level. Leave at 0.0 to disable/hide it.', group = ref10Group)
ref10Desc         = input.string('', 'Description (above label)', tooltip = "Optional short text shown just above the level's price label.", group = ref10Group)
ref10Price        = ref10PriceInput == 0.0 ? na : ref10PriceInput
ref10Color        = input.color(color.rgb(190, 190, 190), 'Color', inline = 'r10a', tooltip = "Color used for this level's line, start marker, and price label.", group = ref10Group)
ref10Width        = input.int(2, 'Width', minval = 1, maxval = 10, inline = 'r10a', tooltip = 'Line thickness for this level.', group = ref10Group)
ref10Style        = input.string('Solid', 'Style', options = ['Solid', 'Dotted', 'Dashed'], inline = 'r10a', tooltip = 'Line style used to draw this level.', group = ref10Group)
ref10StartMode    = input.string('↤Candle', 'Line Start Mode', options = ['Fixed', 'Pivot', '↤Candle'], inline = 'r10a2', tooltip = 'How the line\'s left side behaves. Fixed: extends indefinitely left, anchored past the global "Start N days in the past" point. Pivot: stops at the nearest confirmed swing high/low priced within the global Pivot Price Tolerance of this level\'s own price. ↤Candle: stops exactly at the nearest bar to the left whose candle BODY (open/close, not the wick) touches this level\'s price.', group = ref10Group)
ref10AlertDist    = input.float(refAlertDefaultConst, 'Alert Dist ($)', minval = 1.0, maxval = 100000.0, inline = 'r10b', tooltip = 'Triggers the proximity alert when price comes within this many dollars of the level.', group = ref10Group)
 
// --- SHADING BETWEEN REFERENCE LEVELS (INDIVIDUALLY TOGGLED) ---
// Each gap (1↔2, 2↔3, 3↔4, 4↔5) is its own on/off switch. The gradient
// blends each pair's own Line/Label colors — see f_drawGradientShade above.
// All Reference Levels are Constant-visibility only (no blink mode), so a
// shade simply draws whenever its own toggle is on and both boundary
// levels have a price set.
refShadeGroup = '🪙 R E F E R E N C E - L E V E L - S H A D I N G'
shade12Enable = input.bool(false, 'Shade Ref Ⅰ ↔ Ref Ⅱ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade23Enable = input.bool(false, 'Shade Ref Ⅱ ↔ Ref Ⅲ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade34Enable = input.bool(false, 'Shade Ref Ⅲ ↔ Ref Ⅳ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade45Enable = input.bool(false, 'Shade Ref Ⅳ ↔ Ref Ⅴ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade56Enable = input.bool(false, 'Shade Ref Ⅴ ↔ Ref Ⅵ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade67Enable = input.bool(false, 'Shade Ref Ⅵ ↔ Ref Ⅶ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade78Enable = input.bool(false, 'Shade Ref Ⅶ ↔ Ref Ⅷ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade89Enable = input.bool(false, 'Shade Ref Ⅷ ↔ Ref Ⅸ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shade9_10Enable = input.bool(false, 'Shade Ref Ⅸ ↔ Ref Ⅹ', tooltip = "Fills the price gap between these two reference levels with a color gradient blended from their own colors.", group = refShadeGroup)
shadeBands = input.int(20, 'Gradient Smoothness (Bands)', minval = 2, maxval = 50, group = refShadeGroup, tooltip = 'More bands = smoother gradient, but each band uses 2 lines + 1 linefill from the shared 500-object budget.')
shadeTransparency = input.int(85, 'Shade Transparency', minval = 50, maxval = 95, group = refShadeGroup, tooltip = 'Higher = more see-through shading. Lower = more opaque.')
 
// --- STORAGE ARRAYS FOR CLEAN REDRAW / BLINKING ---
var line[]  refLines  = array.new_line()
var label[] refLabels = array.new_label()
 
var line[]     shadeLines = array.new_line(0)
var linefill[] shadeFills = array.new_linefill(0)
 
// --- DRAW / UPDATE REFERENCE LEVELS ---
if not barstate.isconfirmed and barstate.isrealtime
    f_clearLines(refLines)
    f_clearLabels(refLabels)
 
    // The last of the two contributions to the SHORT-TERM group's
    // dynamic-opacity companion pool — see the matching pushes in the
    // Set 1/2 Entry/Target section above.
    f_pushSecCompanion(ref1Price, 7)
    f_pushSecCompanion(ref2Price, 7)
    f_pushSecCompanion(ref3Price, 7)
    f_pushSecCompanion(ref4Price, 7)
    f_pushSecCompanion(ref5Price, 7)
    f_pushSecCompanion(ref6Price, 7)
    f_pushSecCompanion(ref7Price, 7)
    f_pushSecCompanion(ref8Price, 7)
    f_pushSecCompanion(ref9Price, 7)
    f_pushSecCompanion(ref10Price, 7)
 
    // Each level resolves its own start bar from its own Line Start Mode.
    ref1StartBar  = f_refStartBar(ref1Price,  ref1StartMode)
    ref2StartBar  = f_refStartBar(ref2Price,  ref2StartMode)
    ref3StartBar  = f_refStartBar(ref3Price,  ref3StartMode)
    ref4StartBar  = f_refStartBar(ref4Price,  ref4StartMode)
    ref5StartBar  = f_refStartBar(ref5Price,  ref5StartMode)
    ref6StartBar  = f_refStartBar(ref6Price,  ref6StartMode)
    ref7StartBar  = f_refStartBar(ref7Price,  ref7StartMode)
    ref8StartBar  = f_refStartBar(ref8Price,  ref8StartMode)
    ref9StartBar  = f_refStartBar(ref9Price,  ref9StartMode)
    ref10StartBar = f_refStartBar(ref10Price, ref10StartMode)
 
    f_drawRefLevel(ref1Price, ref1Desc, ref1Color, ref1Width, ref1Style, globalOffsetRef, ref1StartBar, ref1StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref2Price, ref2Desc, ref2Color, ref2Width, ref2Style, globalOffsetRef, ref2StartBar, ref2StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref3Price, ref3Desc, ref3Color, ref3Width, ref3Style, globalOffsetRef, ref3StartBar, ref3StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref4Price, ref4Desc, ref4Color, ref4Width, ref4Style, globalOffsetRef, ref4StartBar, ref4StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref5Price, ref5Desc, ref5Color, ref5Width, ref5Style, globalOffsetRef, ref5StartBar, ref5StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref6Price, ref6Desc, ref6Color, ref6Width, ref6Style, globalOffsetRef, ref6StartBar, ref6StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref7Price, ref7Desc, ref7Color, ref7Width, ref7Style, globalOffsetRef, ref7StartBar, ref7StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref8Price, ref8Desc, ref8Color, ref8Width, ref8Style, globalOffsetRef, ref8StartBar, ref8StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref9Price, ref9Desc, ref9Color, ref9Width, ref9Style, globalOffsetRef, ref9StartBar, ref9StartMode == 'Fixed', refLines, refLabels)
    f_drawRefLevel(ref10Price, ref10Desc, ref10Color, ref10Width, ref10Style, globalOffsetRef, ref10StartBar, ref10StartMode == 'Fixed', refLines, refLabels)
 
    // --- GRADIENT SHADING BETWEEN CONSECUTIVE REFERENCE LEVELS ---
    f_clearLines(shadeLines)
    f_clearLinefills(shadeFills)
 
    // Each shade spans from the earlier (smaller bar_index) of its two
    // boundary levels' own start bars, so it never gets clipped short by
    // whichever boundary level has the tighter Line Start Mode result.
    if shade12Enable
        f_drawGradientShade(ref1Price, ref1Color, ref2Price, ref2Color, math.min(ref1StartBar, ref2StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade23Enable
        f_drawGradientShade(ref2Price, ref2Color, ref3Price, ref3Color, math.min(ref2StartBar, ref3StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade34Enable
        f_drawGradientShade(ref3Price, ref3Color, ref4Price, ref4Color, math.min(ref3StartBar, ref4StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade45Enable
        f_drawGradientShade(ref4Price, ref4Color, ref5Price, ref5Color, math.min(ref4StartBar, ref5StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade56Enable
        f_drawGradientShade(ref5Price, ref5Color, ref6Price, ref6Color, math.min(ref5StartBar, ref6StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade67Enable
        f_drawGradientShade(ref6Price, ref6Color, ref7Price, ref7Color, math.min(ref6StartBar, ref7StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade78Enable
        f_drawGradientShade(ref7Price, ref7Color, ref8Price, ref8Color, math.min(ref7StartBar, ref8StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade89Enable
        f_drawGradientShade(ref8Price, ref8Color, ref9Price, ref9Color, math.min(ref8StartBar, ref9StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
    if shade9_10Enable
        f_drawGradientShade(ref9Price, ref9Color, ref10Price, ref10Color, math.min(ref9StartBar, ref10StartBar), bar_index + globalOffsetRef, shadeBands, shadeTransparency, shadeLines, shadeFills)
 
// --- ALERT CONDITIONS (GLOBAL SCOPE, CONST MESSAGES) ---
bool ref1Approach = not na(ref1Price) and math.abs(close - ref1Price) <= ref1AlertDist
bool ref2Approach = not na(ref2Price) and math.abs(close - ref2Price) <= ref2AlertDist
bool ref3Approach = not na(ref3Price) and math.abs(close - ref3Price) <= ref3AlertDist
bool ref4Approach = not na(ref4Price) and math.abs(close - ref4Price) <= ref4AlertDist
bool ref5Approach = not na(ref5Price) and math.abs(close - ref5Price) <= ref5AlertDist
bool ref6Approach = not na(ref6Price) and math.abs(close - ref6Price) <= ref6AlertDist
bool ref7Approach = not na(ref7Price) and math.abs(close - ref7Price) <= ref7AlertDist
bool ref8Approach = not na(ref8Price) and math.abs(close - ref8Price) <= ref8AlertDist
bool ref9Approach = not na(ref9Price) and math.abs(close - ref9Price) <= ref9AlertDist
bool ref10Approach = not na(ref10Price) and math.abs(close - ref10Price) <= ref10AlertDist
 
alertcondition(ref1Approach, 'REF LEVEL 1 APPROACH', 'Price is near Reference Level 1.')
alertcondition(ref2Approach, 'REF LEVEL 2 APPROACH', 'Price is near Reference Level 2.')
alertcondition(ref3Approach, 'REF LEVEL 3 APPROACH', 'Price is near Reference Level 3.')
alertcondition(ref4Approach, 'REF LEVEL 4 APPROACH', 'Price is near Reference Level 4.')
alertcondition(ref5Approach, 'REF LEVEL 5 APPROACH', 'Price is near Reference Level 5.')
alertcondition(ref6Approach, 'REF LEVEL 6 APPROACH', 'Price is near Reference Level 6.')
alertcondition(ref7Approach, 'REF LEVEL 7 APPROACH', 'Price is near Reference Level 7.')
alertcondition(ref8Approach, 'REF LEVEL 8 APPROACH', 'Price is near Reference Level 8.')
alertcondition(ref9Approach, 'REF LEVEL 9 APPROACH', 'Price is near Reference Level 9.')
alertcondition(ref10Approach, 'REF LEVEL 10 APPROACH', 'Price is near Reference Level 10.')
 
////////////////////////////////////////////////////////////
////            T A B L E   L A Y O U T                  ///
////////////////////////////////////////////////////////////
// Controls shared by BOTH summary tables.
//   - Column Order: swaps the NOW and ✓ columns of the two separate
//     tables (TARGET always stays in the center).
//   - Merge Both Tables: replaces the two separate tables with ONE table
//     holding a single NOW column (placed on the chosen side), both
//     TARGET columns side by side in the center, and each ladder's own ✓
//     column on its outer edge. The two ladders are vertically offset so
//     that each one's NOW row lands on the SAME table row, and that
//     single NOW cell shows both distances (M/L and S/T) around the
//     current price. A ladder whose own "Show Table" toggle is off is
//     left out of the merged table. The merged table borrows its title
//     and NOW-column backgrounds from the Mid/Long-Term table settings,
//     and each ladder keeps its own header color and opacity settings.
tblLayoutGroup      = '🪙 T A B L E - L A Y O U T'
tblColumnOrder      = input.string('NOW | TARGET | ✓', 'Column Order (Separate Tables)', options = ['NOW | TARGET | ✓', '✓ | TARGET | NOW'], group = tblLayoutGroup, tooltip = 'Swaps the NOW and ✓ columns of both separate tables. TARGET always stays in the center. In Horizontal orientation this swaps the NOW and ✓ rows instead.')
tblMerge            = input.bool(false, 'Merge Both Tables Into One', group = tblLayoutGroup, tooltip = 'Replaces the Mid/Long-Term and SHORT-TERM tables with one table: a single NOW column, both TARGET columns side by side, and each ladder\'s ✓ column on its outer edge. Both NOW values are aligned on the same row.')
tblMergedNowSide    = input.string('Left / Top', 'Merged NOW Column Side', options = ['Left / Top', 'Right / Bottom', 'Split (M/L Left · S/T Right)'], group = tblLayoutGroup, tooltip = 'Left/Top or Right/Bottom: one combined NOW column on that side of the merged table (Left/Right in Vertical, Top/Bottom in Horizontal).\nSplit: each ladder gets its own NOW column hugging its TARGET column — the Mid/Long-Term NOW to the left (top) of the TARGET prices and the SHORT-TERM NOW to the right (bottom). Both stay aligned on the same row.')
tblMergedTitle      = input.string('MID/LONG + SHORT-TERM', 'Merged Table Title', group = tblLayoutGroup, tooltip = 'Title shown in the merged table\'s top row.')
tblMergedOrient     = input.string('Vertical', 'Merged Orientation', options = ['Vertical', 'Horizontal'], group = tblLayoutGroup, tooltip = 'Vertical: columns are NOW/✓/TARGET and each price is a row. Horizontal: those become rows and each price is a column.')
tblMergedPosRaw     = input.string('Top Right', 'Merged Position', options = ['Top Left', 'Top Center', 'Top Right', 'Middle Left', 'Middle Center', 'Middle Right', 'Bottom Left', 'Bottom Center', 'Bottom Right'], group = tblLayoutGroup, tooltip = 'Corner/edge of the chart pane the merged table is anchored to.')
tblMergedSizeRaw    = input.string('Small', 'Merged Text Size', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = tblLayoutGroup, tooltip = 'Base font size of the merged table (far-rank rows still drop to tiny).')
 
////////////////////////////////////////////////////////////
////   M I D / L O N G - T E R M   S U M M A R Y   T A B L E   ///
////////////////////////////////////////////////////////////
// A 3-column table (Vertical) or 3-row table (Horizontal) summarizing
// every Mid-Term + Long-Term target price in one sorted ladder:
//   Col/Row 1 — "NOW": blank on every row except one. Take the nearest
//     target ABOVE close and the nearest target BELOW close, and find the
//     midpoint (50%) between them. If close is above that midpoint, the
//     current price (with a ▼) is printed on the row of the nearest target
//     ABOVE it; if close is at or below the midpoint, the current price
//     (with a ▲) is printed on the row of the nearest target BELOW it. Text
//     color is mltCurrentColorDown (▼ case) or mltCurrentColorUp (▲ case).
//     If close sits beyond every target on one side (no bracketing pair
//     exists), the marker is skipped entirely. Background is fully
//     transparent, so the cell shows nothing but the marker itself.
//   Col/Row 2 — "TARGET": every Mid-Term + Long-Term price merged and
//     sorted highest → lowest (highest at the top row / leftmost column),
//     shaded with that price's own list color (MidTermColor / LongTermColor).
//     Opacity is RANK-based rather than distance-based: the level immediately
//     above the current price and the level immediately below it get
//     mltPctNear (100% by default); the next-nearest level on each side
//     gets mltPctMid (60%); every other level gets mltPctFar (30%). The
//     cell's TEXT uses that same opacity value (not a flat white), so text
//     and background fade together.
//   Col/Row 3 — "✓": a small checkmark if price has traded through that
//     level (between a bar's high and low) at any point in the last
//     mltReachedMonths months. Its cell BACKGROUND is flat, matching the
//     header row's own background (headerBg, driven by the user-selectable
//     mltHeaderColor input) — independent of the TARGET column's per-level
//     shading. The checkmark's own TEXT opacity still follows the same
//     rank-based mltPctNear/mltPctMid/mltPctFar criteria as TARGET.
//   (Columns 1 and 3 swap places when Column Order = '✓ | TARGET | NOW'.)
// Rebuilt on every last bar (same barstate.islast pattern used by other
// CQ table implementations), independent of the realtime-only draw gate
// used by the line/label subsystems above, since a table is a single
// persistent object rather than something that accumulates.
 
mltTableGroup = '🪙 M I D / L O N G - T E R M   T A B L E'
showMltTable        = input.bool(true, 'Show Table', group = mltTableGroup, tooltip = 'Show/hide the Mid/Long-Term summary table entirely.')
mltTableTitle       = input.string('MID/LONG TERM', 'Table Title', group = mltTableGroup, tooltip = 'Short title shown in its own row at the top of this table.')
mltTitleBgColor     = input.color(color.rgb(54, 58, 69, 50), 'Title Background', group = mltTableGroup, tooltip = 'Background color of the title row.')
mltNowBgColor       = input.color(color.rgb(0, 10, 37, 50), 'Now Column Background', group = mltTableGroup, tooltip = 'Background color of the NOW header cell and every NOW-column data cell.')
mltTableOrientation  = input.string('Vertical', 'Orientation', options = ['Vertical', 'Horizontal'], group = mltTableGroup, tooltip = 'Vertical: NOW/TARGET/✓ run as columns and each price is its own row. Horizontal: NOW/TARGET/✓ run as rows and each price is its own column.')
mltTablePositionRaw  = input.string('Bottom Right', 'Position', options = ['Top Left', 'Top Center', 'Top Right', 'Middle Left', 'Middle Center', 'Middle Right', 'Bottom Left', 'Bottom Center', 'Bottom Right'], group = mltTableGroup, tooltip = 'Corner/edge of the chart pane this table is anchored to.')
mltTableSizeRaw      = input.string('Small', 'Text Size', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = mltTableGroup, tooltip = 'Font size used for every cell in this table.')
mltPctNear           = input.int(100, 'Nearest Levels Opacity % — Price Column', minval = 0, maxval = 100, group = mltTableGroup, tooltip = 'Opacity for the Mid/Long-Term level immediately above the current price and the one immediately below it.')
mltPctMid            = input.int(50, 'Next Levels Opacity % — Price Column', minval = 0, maxval = 100, group = mltTableGroup, tooltip = 'Opacity for the second-nearest level above the current price and the second-nearest level below it.')
mltPctFar            = input.int(20, 'Remaining Levels Opacity % — Price Column', minval = 0, maxval = 100, group = mltTableGroup, tooltip = 'Opacity for every other level, beyond the two nearest on each side of the current price.')
mltReachedMonths     = input.int(6, 'Reached Lookback (Months) — ✓ Column', minval = 1, maxval = 60, group = mltTableGroup, tooltip = "A small circle marks a price in the ✓ column if price has traded through it (between a bar's high and low) at any point within this many months.")
mltReachedMarkColor  = input.color(color.rgb(187, 255, 0), '✓ Column Marker Color', group = mltTableGroup, tooltip = 'Color of the ✓ checkmark shown for a row whose price has been reached within the Reached Lookback window above.')
mltCurrentColorUp    = input.color(color.rgb(255, 255, 255), 'Now Column Marker Color (▲ Below Midpoint)', group = mltTableGroup, tooltip = 'Text/arrow color when price sits at or below the midpoint between the nearest target below and nearest target above — the marker is placed on the BELOW target\'s row, with an up arrow.')
mltCurrentColorDown  = input.color(color.rgb(209, 209, 209), 'Now Column Marker Color (▼ Above Midpoint)', group = mltTableGroup, tooltip = 'Text/arrow color when price sits above the midpoint between the nearest target below and nearest target above — the marker is placed on the ABOVE target\'s row, with a down arrow.')
mltHeaderColor       = input.color(color.rgb(3, 19, 54, 60), 'Header Background', group = mltTableGroup, tooltip = 'Background color of the TARGET/✓ header cells and every ✓-column data cell (the ✓ column\'s background stays flat rather than rank-shaded like the TARGET column).')
 
f_mltTablePos(_sel) =>
    switch _sel
        'Top Left' => position.top_left
        'Top Center' => position.top_center
        'Top Right' => position.top_right
        'Middle Left' => position.middle_left
        'Middle Center' => position.middle_center
        'Middle Right' => position.middle_right
        'Bottom Left' => position.bottom_left
        'Bottom Center' => position.bottom_center
        => position.bottom_right
 
f_mltTextSize(_sel) =>
    _sel == 'Tiny' ? size.tiny : _sel == 'Small' ? size.small : _sel == 'Normal' ? size.normal : _sel == 'Large' ? size.large : size.huge
 
mltTablePos  = f_mltTablePos(mltTablePositionRaw)
mltTableSize = f_mltTextSize(mltTableSizeRaw)
 
// Table-layout values shared by both separate tables and the merged one.
// tblNowC/tblChkC are the NOW/✓ column indices (Vertical); tblNowR/tblChkR
// the NOW/✓ row indices (Horizontal, row 0 = title). TARGET stays at
// column 1 / row 2 either way.
tblMergedPos  = f_mltTablePos(tblMergedPosRaw)
tblMergedSize = f_mltTextSize(tblMergedSizeRaw)
tblSwapCols   = tblColumnOrder == '✓ | TARGET | NOW'
tblNowC       = tblSwapCols ? 2 : 0
tblChkC       = tblSwapCols ? 0 : 2
tblNowR       = tblSwapCols ? 3 : 1
tblChkR       = tblSwapCols ? 1 : 3
 
// Computed unconditionally every bar (not inside the islast branch below)
// since ta.highest/ta.lowest should not be called conditionally.
mltReachedBars = f_periodBars(mltReachedMonths * 30)
mltReachedHigh = ta.highest(high, mltReachedBars)
mltReachedLow  = ta.lowest(low, mltReachedBars)
 
// Exported copy of this ladder's finished rows, read by the MERGED
// SUMMARY TABLE at the end of the script. mlxAnchor is the row that
// carries the NOW marker (or, when price is off limits, the row where
// close would sit), used to align both ladders on one NOW row.
// mlxNowDir: 1 = marker on the BELOW row (➕), -1 = on the ABOVE row (➖),
// 0 = no marker (price off limits).
var string[] mlxPriceTxt = array.new_string(0)
var color[]  mlxBg       = array.new_color(0)
var color[]  mlxTxtCol2  = array.new_color(0)
var string[] mlxTxt3     = array.new_string(0)
var color[]  mlxTxtCol3  = array.new_color(0)
var string[] mlxSize     = array.new_string(0)
var int      mlxCount    = 0
var int      mlxAnchor   = 0
var int      mlxNowDir   = 0
var float    mlxNowDiff  = na
var color    mlxNowClr   = na
 
var table mltTable = na
if barstate.islast
    table.delete(mltTable)
    mlxCount  := 0
    mlxNowDir := 0
    if showMltTable
        mltAllPrices = array.new_float(0)
        mltAllColors = array.new_color(0)
        mltAllSuffix = array.new_string(0)
 
        for y in pMidTerm
            if not na(y)
                array.push(mltAllPrices, y)
                array.push(mltAllColors, MidTermColor)
                array.push(mltAllSuffix, 'M')
 
        for y in pLongTerm
            if not na(y)
                array.push(mltAllPrices, y)
                array.push(mltAllColors, LongTermColor)
                array.push(mltAllSuffix, 'L')
 
        // Current/Previous-year open rows — included alongside the Mid/Long
        // Term ladder (same ranking, opacity, and ✓-reached treatment),
        // each following its own show toggle and using its own
        // user-selected color (CurrentYearlyOpenColor / PrevYearlyOpenColor).
        if showCurrentYearlyOpen
            array.push(mltAllPrices, yearly_open)
            array.push(mltAllColors, CurrentYearlyOpenColor)
            array.push(mltAllSuffix, 'Y')
 
        if showPrevYearlyOpen
            array.push(mltAllPrices, prevYearly_open)
            array.push(mltAllColors, PrevYearlyOpenColor)
            array.push(mltAllSuffix, 'PY')
 
        mltCount = array.size(mltAllPrices)
        if mltCount > 0
            // Sort DESCENDING so the highest price lands in row/column 0 —
            // i.e. the highest number sits at the top of the Vertical table
            // (or leftmost in the Horizontal table). Previously ascending,
            // which put the lowest price on top.
            mltSortedIdx = array.sort_indices(mltAllPrices, order.descending)
 
            headerBg = color.new(mltHeaderColor, 20)
 
            rowPriceTxt = array.new_string(mltCount)
            rowPriceVal = array.new_float(mltCount)
            rowColorArr = array.new_color(mltCount)
            rowBgCol2   = array.new_color(mltCount)
            rowTxtCol2  = array.new_color(mltCount)
            rowTxtCol3  = array.new_color(mltCount)
            rowTxt3     = array.new_string(mltCount)
            rowSize     = array.new_string(mltCount, tblMerge ? tblMergedSize : mltTableSize)   // Far-opacity rows drop to tiny
 
            for i = 0 to mltCount - 1
                srcIdx    = array.get(mltSortedIdx, i)
                rowPrice  = array.get(mltAllPrices, srcIdx)
                rowColor  = array.get(mltAllColors, srcIdx)
                rowSuffix = array.get(mltAllSuffix, srcIdx)
                array.set(rowPriceVal, i, rowPrice)
                array.set(rowColorArr, i, rowColor)
                array.set(rowPriceTxt, i, str.tostring(rowPrice, '$0,000') + ' ' + rowSuffix)
 
                // Column 2 ("✓"): small checkmark if price traded through this level
                // (sat between the bar's high and low) within the lookback window.
                reached = rowPrice <= mltReachedHigh and rowPrice >= mltReachedLow
                array.set(rowTxt3, i, reached ? '✓' : '')
 
            // Column 1 ("TARGET") shading: rank each row's distance to
            // `close` separately above/below, then assign opacity by rank —
            // nearest on each side = mltPctNear, next-nearest = mltPctMid,
            // everything else = mltPctFar. Background (rowBgCol2) is built
            // from each price's own list color (MidTermColor /
            // LongTermColor); TEXT (rowTxtCol2) fades with that same
            // opacity. The ✓ column's checkmark text (rowTxtCol3) fades
            // with the same rank-based opacity, using mltReachedMarkColor
            // instead of white, but its BACKGROUND is flat (headerBg)
            // rather than rank-shaded — see the table-render block below.
            // NOTE: every row below is either >= close (idxAbove) or
            // < close (idxBelow) — those two sets always cover every
            // index between them, so a separate "default everything to
            // Far" pass before this would be immediately overwritten for
            // every single row. Removed as dead work.
            idxAbove = array.new_int(0)
            idxBelow = array.new_int(0)
            pxAbove  = array.new_float(0)
            pxBelow  = array.new_float(0)
            for i = 0 to mltCount - 1
                p = array.get(rowPriceVal, i)
                if p >= close
                    array.push(idxAbove, i)
                    array.push(pxAbove, p)
                else
                    array.push(idxBelow, i)
                    array.push(pxBelow, p)
 
            if array.size(idxAbove) > 0
                ordAbove = array.sort_indices(pxAbove, order.ascending)   // nearest to close first
                for r = 0 to array.size(ordAbove) - 1
                    ri  = array.get(idxAbove, array.get(ordAbove, r))
                    pct = r == 0 ? mltPctNear : r == 1 ? mltPctMid : mltPctFar
                    array.set(rowBgCol2, ri, color.new(array.get(rowColorArr, ri), 100 - pct))
                    array.set(rowTxtCol2, ri, color.new(color.white, 100 - pct))
                    array.set(rowTxtCol3, ri, color.new(mltReachedMarkColor, 100 - pct))
                    if r >= 2
                        array.set(rowSize, ri, size.tiny)
 
            if array.size(idxBelow) > 0
                ordBelow = array.sort_indices(pxBelow, order.descending)  // nearest to close first
                for r = 0 to array.size(ordBelow) - 1
                    ri  = array.get(idxBelow, array.get(ordBelow, r))
                    pct = r == 0 ? mltPctNear : r == 1 ? mltPctMid : mltPctFar
                    array.set(rowBgCol2, ri, color.new(array.get(rowColorArr, ri), 100 - pct))
                    array.set(rowTxtCol2, ri, color.new(color.white, 100 - pct))
                    array.set(rowTxtCol3, ri, color.new(mltReachedMarkColor, 100 - pct))
                    if r >= 2
                        array.set(rowSize, ri, size.tiny)
 
            // Export this ladder for the MERGED SUMMARY TABLE. Default
            // anchor = first row below close (clamped to the last row),
            // overwritten below by the actual NOW-marker row when one exists.
            mlxCount    := mltCount
            mlxPriceTxt := rowPriceTxt
            mlxBg       := rowBgCol2
            mlxTxtCol2  := rowTxtCol2
            mlxTxt3     := rowTxt3
            mlxTxtCol3  := rowTxtCol3
            mlxSize     := rowSize
            mlxAnchor   := math.min(array.size(idxAbove), mltCount - 1)
 
            // Column 3 ("NOW"): blank on every row except the one bracketing
            // target closest to the 50% midpoint side close currently sits
            // on. idxAbove/pxAbove and idxBelow/pxBelow (built above) already
            // separate rows by whether their price is >= or < close, so the
            // nearest neighbor on each side is just the smallest gap within
            // each set. If either side has no candidate (close sits beyond
            // every target), the marker is skipped — na guards below leave
            // every rowCurrentTxt entry blank in that case.
            rowCurrentTxt = array.new_string(mltCount, '')
            rowCurrentClr = array.new_color(mltCount, color.new(color.white, 100))
 
            nearestAbovePrice = float(na)
            nearestAboveRow   = int(na)
            if array.size(idxAbove) > 0
                for a = 0 to array.size(idxAbove) - 1
                    p = array.get(pxAbove, a)
                    if na(nearestAbovePrice) or p < nearestAbovePrice
                        nearestAbovePrice := p
                        nearestAboveRow   := array.get(idxAbove, a)
 
            nearestBelowPrice = float(na)
            nearestBelowRow   = int(na)
            if array.size(idxBelow) > 0
                for b = 0 to array.size(idxBelow) - 1
                    p = array.get(pxBelow, b)
                    if na(nearestBelowPrice) or p > nearestBelowPrice
                        nearestBelowPrice := p
                        nearestBelowRow   := array.get(idxBelow, b)
 
            if not na(nearestAbovePrice) and not na(nearestBelowPrice)
                midPoint = (nearestAbovePrice + nearestBelowPrice) / 2.0
                if close > midPoint
                    diffDown = nearestAbovePrice - close
                    array.set(rowCurrentTxt, nearestAboveRow, '➖' + str.tostring(diffDown, '$0,000') + '⁝\n↳ ' + str.tostring(close, '$0,000'))
                    array.set(rowCurrentClr, nearestAboveRow, mltCurrentColorDown)
                    mlxAnchor  := nearestAboveRow
                    mlxNowDir  := -1
                    mlxNowDiff := diffDown
                    mlxNowClr  := mltCurrentColorDown
                else
                    diffUp = close - nearestBelowPrice
                    array.set(rowCurrentTxt, nearestBelowRow, '↱ ' + str.tostring(close, '$0,000') + '\n➕' + str.tostring(diffUp, '$0,000') + '⁝')
                    array.set(rowCurrentClr, nearestBelowRow, mltCurrentColorUp)
                    mlxAnchor  := nearestBelowRow
                    mlxNowDir  := 1
                    mlxNowDiff := diffUp
                    mlxNowClr  := mltCurrentColorUp
 
            // If close sits beyond every target on one side, no bracketing
            // pair exists and every NOW cell above is left blank — flag
            // that in the title so it's clear the table isn't just stale.
            mltNowEmpty = na(nearestAbovePrice) or na(nearestBelowPrice)
            mltDisplayTitle = mltNowEmpty ? mltTableTitle + '\nPrice Off Limits' : mltTableTitle
 
            // Row/column 0 is now a merged title bar (mltTableTitle) spanning
            // the full width (Vertical) or full height (Horizontal) of the
            // table; the NOW/TARGET/✓ header and every data row shift down
            // by one slot to make room for it. NOW and ✓ positions follow
            // tblNowC/tblChkC (Vertical) or tblNowR/tblChkR (Horizontal).
            // Skipped entirely in merged mode (see MERGED SUMMARY TABLE).
            if not tblMerge and mltTableOrientation == 'Vertical'
                mltTable := table.new(mltTablePos, 3, mltCount + 2, border_width = 1, border_color = color.new(color.black, 50))
                table.cell(mltTable, 0, 0, mltDisplayTitle, text_color = color.white, bgcolor = mltTitleBgColor, text_size = mltTableSize)
                table.merge_cells(mltTable, 0, 0, 2, 0)
                table.cell(mltTable, tblNowC, 1, 'NOW', text_color = color.white, bgcolor = mltNowBgColor, text_size = mltTableSize)
                table.cell(mltTable, 1, 1, 'TARGET', text_color = color.white, bgcolor = headerBg, text_size = mltTableSize)
                table.cell(mltTable, tblChkC, 1, '✅', text_color = color.white, bgcolor = headerBg, text_size = mltTableSize)
                for i = 0 to mltCount - 1
                    table.cell(mltTable, tblNowC, i + 2, array.get(rowCurrentTxt, i), text_color = array.get(rowCurrentClr, i), bgcolor = mltNowBgColor, text_size = array.get(rowSize, i), text_halign = tblSwapCols ? text.align_left : text.align_right, tooltip = 'NOW: shows the current price relative to the two nearest Mid-Term/Long-Term/Yearly-Open targets that bracket it (the closest one above and the closest one below). It appears on only ONE row per tick - whichever of those two targets sits on the same side of the halfway point (50%) between them as the current price. If price is at or below that midpoint, it prints on the BELOW target row: an up arrow, the current price, then how many dollars still short of that target. If price is above the midpoint, it prints on the ABOVE target row: how many dollars past that target already, then a down arrow and the current price. Every other row stays blank, and if price sits beyond every target on one side (no bracketing pair), the whole column is blank and the table title adds "Price Off Limits".')
                    table.cell(mltTable, 1, i + 2, array.get(rowPriceTxt, i), text_color = array.get(rowTxtCol2, i), bgcolor = array.get(rowBgCol2, i), text_size = array.get(rowSize, i))
                    table.cell(mltTable, tblChkC, i + 2, array.get(rowTxt3, i), text_color = array.get(rowTxtCol3, i), bgcolor = headerBg, text_size = array.get(rowSize, i))
            else if not tblMerge
                mltTable := table.new(mltTablePos, mltCount + 1, 4, border_width = 1, border_color = color.new(color.black, 50))
                table.cell(mltTable, 0, 0, mltDisplayTitle, text_color = color.white, bgcolor = mltTitleBgColor, text_size = mltTableSize)
                table.merge_cells(mltTable, 0, 0, mltCount, 0)
                table.cell(mltTable, 0, tblNowR, 'NOW', text_color = color.white, bgcolor = mltNowBgColor, text_size = mltTableSize)
                table.cell(mltTable, 0, 2, 'TARGET', text_color = color.white, bgcolor = headerBg, text_size = mltTableSize)
                table.cell(mltTable, 0, tblChkR, '✅', text_color = color.white, bgcolor = headerBg, text_size = mltTableSize)
                for i = 0 to mltCount - 1
                    table.cell(mltTable, i + 1, tblNowR, array.get(rowCurrentTxt, i), text_color = array.get(rowCurrentClr, i), bgcolor = mltNowBgColor, text_size = array.get(rowSize, i), tooltip = 'NOW: shows the current price relative to the two nearest Mid-Term/Long-Term/Yearly-Open targets that bracket it (the closest one above and the closest one below). It appears on only ONE column per tick - whichever of those two targets sits on the same side of the halfway point (50%) between them as the current price. If price is at or below that midpoint, it prints on the BELOW target column: an up arrow, the current price, then how many dollars still short of that target. If price is above the midpoint, it prints on the ABOVE target column: how many dollars past that target already, then a down arrow and the current price. Every other column stays blank, and if price sits beyond every target on one side (no bracketing pair), the whole row is blank and the table title adds "Price Off Limits".')
                    table.cell(mltTable, i + 1, 2, array.get(rowPriceTxt, i), text_color = array.get(rowTxtCol2, i), bgcolor = array.get(rowBgCol2, i), text_size = array.get(rowSize, i))
                    table.cell(mltTable, i + 1, tblChkR, array.get(rowTxt3, i), text_color = array.get(rowTxtCol3, i), bgcolor = headerBg, text_size = array.get(rowSize, i))
 
////////////////////////////////////////////////////////////
////   S H O R T - T E R M   S U M M A R Y   T A B L E    ///
////   ( E N T R Y / T A R G E T / W E E K L Y / R E F )  ///
////////////////////////////////////////////////////////////
// Same NOW/TARGET/✓ design as the Mid/Long-Term table above (rank-based
// opacity, reached-lookback checkmark, midpoint NOW marker with the
// +/- distance-to-level suffix), but built from every OTHER price list
// in the script: Set 1/Set 2 Entry prices, Set 1/Set 2 Target prices,
// and any of the 10 manual Reference Levels left non-zero. Each source
// keeps its OWN list's color (Entry/Target Line Colors, each Ref Level's
// own Color) — only the cell opacity is rank-based, exactly like the
// primary table. A source with nothing entered (empty text area, or a
// Reference Level left at 0.0) simply contributes no rows, so the table
// only ever shows whatever the user has actually populated. Each source
// group (Set 1/2 Entry, Set 1/2 Target, Reference Levels) can also be switched on/off individually in this table's settings.
 
secTableGroup = '🪙 S H O R T - T E R M - T A B L E'
showSecTable        = input.bool(true, 'Show Table', group = secTableGroup, tooltip = 'Show/hide the SHORT-TERM summary table entirely.')
secTableTitle       = input.string('SHORT-TERM LEVELS', 'Table Title', group = secTableGroup, tooltip = 'Short title shown in its own row at the top of this table.')
secTitleBgColor     = input.color(color.rgb(54, 58, 69, 50), 'Title Background', group = secTableGroup, tooltip = 'Background color of the title row.')
secNowBgColor       = input.color(color.rgb(0, 10, 37, 50), 'Now Column Background', group = secTableGroup, tooltip = 'Background color of the NOW header cell and every NOW-column data cell.')
secTableOrientation = input.string('Vertical', 'Orientation', options = ['Vertical', 'Horizontal'], group = secTableGroup, tooltip = 'Vertical: NOW/TARGET/✓ run as columns and each price is its own row. Horizontal: NOW/TARGET/✓ run as rows and each price is its own column.')
secTablePositionRaw = input.string('Top Right', 'Position', options = ['Top Left', 'Top Center', 'Top Right', 'Middle Left', 'Middle Center', 'Middle Right', 'Bottom Left', 'Bottom Center', 'Bottom Right'], group = secTableGroup, tooltip = 'Corner/edge of the chart pane this table is anchored to.')
secTableSizeRaw     = input.string('Small', 'Text Size', options = ['Tiny', 'Small', 'Normal', 'Large', 'Huge'], group = secTableGroup, tooltip = 'Font size used for every cell in this table.')
secPctNear          = input.int(100, 'Nearest Levels Opacity % — Price Column', minval = 0, maxval = 100, group = secTableGroup, tooltip = 'Opacity for the level immediately above the current price and the one immediately below it.')
secPctMid           = input.int(50, 'Next Levels Opacity % — Price Column', minval = 0, maxval = 100, group = secTableGroup, tooltip = 'Opacity for the second-nearest level above the current price and the second-nearest level below it.')
secPctFar           = input.int(20, 'Remaining Levels Opacity % — Price Column', minval = 0, maxval = 100, group = secTableGroup, tooltip = 'Opacity for every other level, beyond the two nearest on each side of the current price.')
secReachedMonths    = input.int(6, 'Reached Lookback (Months) — ✓ Column', minval = 1, maxval = 60, group = secTableGroup, tooltip = "Marks a price in the ✓ column if price has traded through it (between a bar's high and low) at any point within this many months.")
secReachedMarkColor = input.color(color.rgb(187, 255, 0), '✓ Column Marker Color', group = secTableGroup, tooltip = 'Color of the ✓ checkmark shown for a row whose price has been reached within the Reached Lookback window above.')
secCurrentColorUp   = input.color(color.rgb(255, 255, 255), 'Now Column Marker Color (▲ Below Midpoint)', group = secTableGroup, tooltip = 'Text/arrow color when price sits at or below the midpoint between the nearest level below and nearest level above.')
secCurrentColorDown = input.color(color.rgb(209, 209, 209), 'Now Column Marker Color (▼ Above Midpoint)', group = secTableGroup, tooltip = 'Text/arrow color when price sits above the midpoint between the nearest level below and nearest level above.')
secHeaderColor      = input.color(color.rgb(3, 19, 54, 60), 'Header Background', group = secTableGroup, tooltip = 'Background color of the TARGET/✓ header cells and every ✓-column data cell (the ✓ column\'s background stays flat rather than rank-shaded like the TARGET column).')
 
// Price-group selectors — choose which source groups are folded into this
// table (all default ON, matching the previous behavior). Turning a group
// off removes its rows from the table AND from the ranking pool, so the
// near/mid/far opacity, NOW marker and on-chart line/label opacity are all
// computed only against the groups left on. This never hides the group's
// own lines/labels on the chart — use each group's own Plot toggle for that.
secInclEntry1     = input.bool(true, 'Set 1 Entry Events(E1)',  inline = 'secinc1', group = secTableGroup, tooltip = 'Include the Set 1 Entry Event prices in this table.')
secInclTarget1    = input.bool(true, 'Set 1 Targets (T1)', inline = 'secinc1', group = secTableGroup, tooltip = 'Include the Set 1 Target Event prices in this table.')
secInclEntry2     = input.bool(true, 'Set 2 Entry Events(E2)',  inline = 'secinc2', group = secTableGroup, tooltip = 'Include the Set 2 Entry Event prices in this table.')
secInclTarget2    = input.bool(true, 'Set 2 Targets (T2)', inline = 'secinc2', group = secTableGroup, tooltip = 'Include the Set 2 Target Event prices in this table.')
secInclRefs       = input.bool(true, 'Reference Levels (R1–R10)', group = secTableGroup, tooltip = 'Include every non-zero manual Reference Level (Ⅰ–Ⅹ) in this table.')
 
// Maps a companion-pool group tag (see secCompanionGroupsTracked) to its toggle.
f_secGroupOn(_g) =>
    _g == 1 ? secInclEntry1 : _g == 2 ? secInclEntry2 : _g == 3 ? secInclTarget1 : _g == 4 ? secInclTarget2 : secInclRefs
 
// Automatic reference rows — the pre-hardcoded 1D, 1W and 4H opening
// prices. Each one now has its own show toggle + color, so the user
// selects which of them are folded into this table (all default ON,
// matching the previous behavior where 1D/1W were always included).
// They're structural context rather than a user-typed list, so they have
// no on-chart line/label — only a table row, ranked like every other row.
show1DOpen         = input.bool(true, 'Show 1D Open', inline = 'sec1d', group = secTableGroup, tooltip = "Adds the current Daily candle's opening price as a row in this table.")
secDailyOpenColor  = input.color(color.rgb(100, 147, 165), 'Color', inline = 'sec1d', group = secTableGroup, tooltip = "Color for the 1D Open row.")
show1WOpen         = input.bool(true, 'Show 1W Open', inline = 'sec1w', group = secTableGroup, tooltip = "Adds the current Weekly candle's opening price as a row in this table.")
secWeeklyOpenColor = input.color(color.rgb(23, 143, 173), 'Color', inline = 'sec1w', group = secTableGroup, tooltip = "Color for the 1W Open row.")
show4HOpen         = input.bool(true, 'Show 4H Open', inline = 'sec4h', group = secTableGroup, tooltip = "Adds the current 4H candle's opening price as a row in this table.")
sec4HOpenColor     = input.color(color.rgb(165, 160, 95), 'Color', inline = 'sec4h', group = secTableGroup, tooltip = "Color for the 4H Open row.")
 
// ── DYNAMIC OPACITY — FINAL RECOLOR PASS ────────────────────────────────
// Both tables' opacity-pct inputs (mltPctNear/mltPctMid/mltPctFar above,
// secPctNear/secPctMid/secPctFar just above) are only now fully known, so
// this is where every chart line/label tracked by the two "placeholder
// now, recolor here" trackers gets its real dynamic opacity — the same
// near/mid/far rank-vs-close value as its own row in the corresponding
// table — while keeping each object's own base color (hue) untouched.
// Label TEXT fades by that exact same transparency as its background
// (rather than staying fully opaque), so a "far" level's label dims as a
// whole instead of leaving crisp text floating over a barely-visible box.
// mltOpacity* covers Mid-Term/Long-Term/Current-Year-Open/Previous-Year-
// Open; secOpacity* covers Set 1/2 Entry/Target and Reference Levels 1–10 (the plotted subset of the SHORT-TERM Table's
// rows — the automatic 1D/1W/4H Open rows have no chart line/label of
// their own, so they aren't recolored here, only ranked-against).
// SHORT-TERM labels are recolored from secOpacityLabelColors (their own
// background hue — the Label Palette for Entry/Target), not from the
// line hue, so the palette survives this pass. In Boxes caption mode the
// same opacity is applied to each caption box's background and text
// instead (whichever of label/box is na for an entry is skipped).
if not barstate.isconfirmed and barstate.isrealtime
    // Guarded with size > 0: "for i = 0 to array.size(X) - 1" is only
    // safe when X isn't empty. When a tracker is empty (e.g. no
    // Set 1-2/Reference-Level price currently resolves to a non-na value
    // this tick), array.size(X) - 1 evaluates to -1, and since 0 > -1
    // Pine infers a descending step and still runs the loop body once
    // with i = 0 instead of skipping it — straight into an
    // array.get(X, 0) on an empty array. Explicit size checks avoid that.
    if array.size(mltOpacityLines) > 0
        for i = 0 to array.size(mltOpacityLines) - 1
            mltLn      = array.get(mltOpacityLines, i)
            mltLbl     = array.get(mltOpacityLabels, i)
            mltBx      = array.get(mltOpacityBoxes, i)
            mltPrice   = array.get(mltOpacityPrices, i)
            mltColor   = array.get(mltOpacityBaseColors, i)
            mltTxtHue  = array.get(mltOpacityTextColors, i)
            mltPct     = f_rankPct(mltPrice, mltCompanionPricesTracked, close, mltPctNear, mltPctMid, mltPctFar)
            line.set_color(mltLn, color.new(mltColor, 100 - mltPct))
            if not na(mltLbl)
                label.set_color(mltLbl, color.new(mltColor, 100 - mltPct))
                label.set_textcolor(mltLbl, color.new(mltTxtHue, 100 - mltPct))
            if not na(mltBx)
                box.set_bgcolor(mltBx, color.new(mltColor, 100 - mltPct))
                box.set_text_color(mltBx, color.new(mltTxtHue, 100 - mltPct))
 
    if array.size(secOpacityLines) > 0
        // Ranking pool = only the source groups currently included in the
        // SHORT-TERM Table (same pool its own rows are ranked against).
        secFilteredPool = array.new_float(0)
        if array.size(secCompanionPricesTracked) > 0
            for k = 0 to array.size(secCompanionPricesTracked) - 1
                if f_secGroupOn(array.get(secCompanionGroupsTracked, k))
                    array.push(secFilteredPool, array.get(secCompanionPricesTracked, k))
        for i = 0 to array.size(secOpacityLines) - 1
            secLn       = array.get(secOpacityLines, i)
            secLbl      = array.get(secOpacityLabels, i)
            secBx       = array.get(secOpacityBoxes, i)
            secPrice    = array.get(secOpacityPrices, i)
            secColor    = array.get(secOpacityBaseColors, i)
            secLblColor = array.get(secOpacityLabelColors, i)
            secTxtHue   = array.get(secOpacityTextColors, i)
            secPct      = f_rankPct(secPrice, secFilteredPool, close, secPctNear, secPctMid, secPctFar)
            line.set_color(secLn, color.new(secColor, 100 - secPct))
            if not na(secLbl)
                label.set_color(secLbl, color.new(secLblColor, 100 - secPct))
                label.set_textcolor(secLbl, color.new(secTxtHue, 100 - secPct))
            if not na(secBx)
                box.set_bgcolor(secBx, color.new(secLblColor, 100 - secPct))
                box.set_text_color(secBx, color.new(secTxtHue, 100 - secPct))
 
secTablePos  = f_mltTablePos(secTablePositionRaw)
secTableSize = f_mltTextSize(secTableSizeRaw)
 
// Computed unconditionally every bar, same reasoning as mltReachedHigh/Low above.
secReachedBars = f_periodBars(secReachedMonths * 30)
secReachedHigh = ta.highest(high, secReachedBars)
secReachedLow  = ta.lowest(low, secReachedBars)
 
// Daily open price for the automatic table row. Like the 4H open below,
// it's opt-in (show1DOpen) — only pay for this request.security call when
// the row is actually going to be shown. Weekly open reuses sundayOpen
// (already pulled via request.security(..., 'W', ...) above) rather than
// requesting the same series twice.
dailyOpenPrice  = show1DOpen ? request.security(syminfo.tickerid, 'D', open, lookahead = barmerge.lookahead_on) : na
// 4H open is opt-in (show4HOpen) — only pay for this request.security
// call when the row is actually going to be shown, instead of fetching
// it unconditionally on every bar regardless of the toggle.
fourHOpenPrice  = show4HOpen ? request.security(syminfo.tickerid, '240', open, lookahead = barmerge.lookahead_on) : na
 
// Exported copy of this ladder's finished rows for the MERGED SUMMARY
// TABLE — same meaning as the mlx* set above the Mid/Long-Term table.
var string[] stxPriceTxt = array.new_string(0)
var color[]  stxBg       = array.new_color(0)
var color[]  stxTxtCol2  = array.new_color(0)
var string[] stxTxt3     = array.new_string(0)
var color[]  stxTxtCol3  = array.new_color(0)
var string[] stxSize     = array.new_string(0)
var int      stxCount    = 0
var int      stxAnchor   = 0
var int      stxNowDir   = 0
var float    stxNowDiff  = na
var color    stxNowClr   = na
 
var table secTable = na
if barstate.islast
    table.delete(secTable)
    stxCount  := 0
    stxNowDir := 0
    if showSecTable
        secAllPrices = array.new_float(0)
        secAllColors = array.new_color(0)
        secAllSuffix = array.new_string(0)
 
        for y in pEventsEntry
            if secInclEntry1 and not na(y)
                array.push(secAllPrices, y)
                array.push(secAllColors, event_entry_Color)
                array.push(secAllSuffix, 'E1')
 
        for y in pEventsEntry2
            if secInclEntry2 and not na(y)
                array.push(secAllPrices, y)
                array.push(secAllColors, event_entry_Color2)
                array.push(secAllSuffix, 'E2')
 
        for y in pEventsTarget
            if secInclTarget1 and not na(y)
                array.push(secAllPrices, y)
                array.push(secAllColors, event_target_Color)
                array.push(secAllSuffix, 'T1')
 
        for y in pEventsTarget2
            if secInclTarget2 and not na(y)
                array.push(secAllPrices, y)
                array.push(secAllColors, event_target_Color2)
                array.push(secAllSuffix, 'T2')
 
        if secInclRefs and not na(ref1Price)
            array.push(secAllPrices, ref1Price)
            array.push(secAllColors, ref1Color)
            array.push(secAllSuffix, 'R1')
        if secInclRefs and not na(ref2Price)
            array.push(secAllPrices, ref2Price)
            array.push(secAllColors, ref2Color)
            array.push(secAllSuffix, 'R2')
        if secInclRefs and not na(ref3Price)
            array.push(secAllPrices, ref3Price)
            array.push(secAllColors, ref3Color)
            array.push(secAllSuffix, 'R3')
        if secInclRefs and not na(ref4Price)
            array.push(secAllPrices, ref4Price)
            array.push(secAllColors, ref4Color)
            array.push(secAllSuffix, 'R4')
        if secInclRefs and not na(ref5Price)
            array.push(secAllPrices, ref5Price)
            array.push(secAllColors, ref5Color)
            array.push(secAllSuffix, 'R5')
        if secInclRefs and not na(ref6Price)
            array.push(secAllPrices, ref6Price)
            array.push(secAllColors, ref6Color)
            array.push(secAllSuffix, 'R6')
        if secInclRefs and not na(ref7Price)
            array.push(secAllPrices, ref7Price)
            array.push(secAllColors, ref7Color)
            array.push(secAllSuffix, 'R7')
        if secInclRefs and not na(ref8Price)
            array.push(secAllPrices, ref8Price)
            array.push(secAllColors, ref8Color)
            array.push(secAllSuffix, 'R8')
        if secInclRefs and not na(ref9Price)
            array.push(secAllPrices, ref9Price)
            array.push(secAllColors, ref9Color)
            array.push(secAllSuffix, 'R9')
        if secInclRefs and not na(ref10Price)
            array.push(secAllPrices, ref10Price)
            array.push(secAllColors, ref10Color)
            array.push(secAllSuffix, 'R10')
 
        // Automatic 1D / 1W / 4H opens — each independently toggled by its
        // own show input (show1DOpen / show1WOpen / show4HOpen).
        if show1DOpen and not na(dailyOpenPrice)
            array.push(secAllPrices, dailyOpenPrice)
            array.push(secAllColors, secDailyOpenColor)
            array.push(secAllSuffix, '1D')
        if show1WOpen and not na(sundayOpen)
            array.push(secAllPrices, sundayOpen)
            array.push(secAllColors, secWeeklyOpenColor)
            array.push(secAllSuffix, '1W')
        if show4HOpen and not na(fourHOpenPrice)
            array.push(secAllPrices, fourHOpenPrice)
            array.push(secAllColors, sec4HOpenColor)
            array.push(secAllSuffix, '4H')
 
        secCount = array.size(secAllPrices)
        if secCount > 0
            // Sort DESCENDING so the highest price lands in row/column 0,
            // same convention as the Mid/Long-Term table.
            secSortedIdx = array.sort_indices(secAllPrices, order.descending)
 
            secHeaderBg = color.new(secHeaderColor, 20)
 
            secRowPriceTxt = array.new_string(secCount)
            secRowPriceVal = array.new_float(secCount)
            secRowColorArr = array.new_color(secCount)
            secRowBgCol2   = array.new_color(secCount)
            secRowTxtCol2  = array.new_color(secCount)
            secRowTxtCol3  = array.new_color(secCount)
            secRowTxt3     = array.new_string(secCount)
            secRowSize     = array.new_string(secCount, tblMerge ? tblMergedSize : secTableSize)   // Far-opacity rows drop to tiny
 
            for i = 0 to secCount - 1
                srcIdx    = array.get(secSortedIdx, i)
                rowPrice  = array.get(secAllPrices, srcIdx)
                rowColor  = array.get(secAllColors, srcIdx)
                rowSuffix = array.get(secAllSuffix, srcIdx)
                array.set(secRowPriceVal, i, rowPrice)
                array.set(secRowColorArr, i, rowColor)
                array.set(secRowPriceTxt, i, str.tostring(rowPrice, '$0,000') + ' ' + rowSuffix)
 
                // Column 3 ("✓"): traded-through-level checkmark, same rule
                // as the primary table but using this table's own lookback.
                reached = rowPrice <= secReachedHigh and rowPrice >= secReachedLow
                array.set(secRowTxt3, i, reached ? '✓' : '')
 
            // Column 1 ("TARGET") shading: same rank-by-distance-to-close
            // logic as the primary table, using this table's own colors
            // (each row's OWN source color) and this table's own opacity
            // inputs (secPctNear/secPctMid/secPctFar). Same as the
            // Mid/Long-Term table above, there's no separate "default to
            // Far" pass here either — idxAbove/idxBelow together cover
            // every row, so it would only ever be immediately overwritten.
            secIdxAbove = array.new_int(0)
            secIdxBelow = array.new_int(0)
            secPxAbove  = array.new_float(0)
            secPxBelow  = array.new_float(0)
            for i = 0 to secCount - 1
                p = array.get(secRowPriceVal, i)
                if p >= close
                    array.push(secIdxAbove, i)
                    array.push(secPxAbove, p)
                else
                    array.push(secIdxBelow, i)
                    array.push(secPxBelow, p)
 
            if array.size(secIdxAbove) > 0
                secOrdAbove = array.sort_indices(secPxAbove, order.ascending)
                for r = 0 to array.size(secOrdAbove) - 1
                    ri  = array.get(secIdxAbove, array.get(secOrdAbove, r))
                    pct = r == 0 ? secPctNear : r == 1 ? secPctMid : secPctFar
                    array.set(secRowBgCol2, ri, color.new(array.get(secRowColorArr, ri), 100 - pct))
                    array.set(secRowTxtCol2, ri, color.new(color.white, 100 - pct))
                    array.set(secRowTxtCol3, ri, color.new(secReachedMarkColor, 100 - pct))
                    if r >= 2
                        array.set(secRowSize, ri, size.tiny)
 
            if array.size(secIdxBelow) > 0
                secOrdBelow = array.sort_indices(secPxBelow, order.descending)
                for r = 0 to array.size(secOrdBelow) - 1
                    ri  = array.get(secIdxBelow, array.get(secOrdBelow, r))
                    pct = r == 0 ? secPctNear : r == 1 ? secPctMid : secPctFar
                    array.set(secRowBgCol2, ri, color.new(array.get(secRowColorArr, ri), 100 - pct))
                    array.set(secRowTxtCol2, ri, color.new(color.white, 100 - pct))
                    array.set(secRowTxtCol3, ri, color.new(secReachedMarkColor, 100 - pct))
                    if r >= 2
                        array.set(secRowSize, ri, size.tiny)
 
            // Export this ladder for the MERGED SUMMARY TABLE (see the
            // matching block in the Mid/Long-Term table above).
            stxCount    := secCount
            stxPriceTxt := secRowPriceTxt
            stxBg       := secRowBgCol2
            stxTxtCol2  := secRowTxtCol2
            stxTxt3     := secRowTxt3
            stxTxtCol3  := secRowTxtCol3
            stxSize     := secRowSize
            stxAnchor   := math.min(array.size(secIdxAbove), secCount - 1)
 
            // Column 2 ("NOW"): same bracketing-midpoint marker as the
            // primary table, including the +/- distance-to-level suffix.
            secRowCurrentTxt = array.new_string(secCount, '')
            secRowCurrentClr = array.new_color(secCount, color.new(color.white, 100))
 
            secNearestAbovePrice = float(na)
            secNearestAboveRow   = int(na)
            if array.size(secIdxAbove) > 0
                for a = 0 to array.size(secIdxAbove) - 1
                    p = array.get(secPxAbove, a)
                    if na(secNearestAbovePrice) or p < secNearestAbovePrice
                        secNearestAbovePrice := p
                        secNearestAboveRow   := array.get(secIdxAbove, a)
 
            secNearestBelowPrice = float(na)
            secNearestBelowRow   = int(na)
            if array.size(secIdxBelow) > 0
                for b = 0 to array.size(secIdxBelow) - 1
                    p = array.get(secPxBelow, b)
                    if na(secNearestBelowPrice) or p > secNearestBelowPrice
                        secNearestBelowPrice := p
                        secNearestBelowRow   := array.get(secIdxBelow, b)
 
            if not na(secNearestAbovePrice) and not na(secNearestBelowPrice)
                secMidPoint = (secNearestAbovePrice + secNearestBelowPrice) / 2.0
                if close > secMidPoint
                    secDiffDown = secNearestAbovePrice - close
                    array.set(secRowCurrentTxt, secNearestAboveRow, '➖' + str.tostring(secDiffDown, '$0,000') + '⁝\n↳ ' + str.tostring(close, '$0,000'))
                    array.set(secRowCurrentClr, secNearestAboveRow, secCurrentColorDown)
                    stxAnchor  := secNearestAboveRow
                    stxNowDir  := -1
                    stxNowDiff := secDiffDown
                    stxNowClr  := secCurrentColorDown
                else
                    secDiffUp = close - secNearestBelowPrice
                    array.set(secRowCurrentTxt, secNearestBelowRow, '↱ ' + str.tostring(close, '$0,000') + '\n➕' + str.tostring(secDiffUp, '$0,000') + '⁝')
                    array.set(secRowCurrentClr, secNearestBelowRow, secCurrentColorUp)
                    stxAnchor  := secNearestBelowRow
                    stxNowDir  := 1
                    stxNowDiff := secDiffUp
                    stxNowClr  := secCurrentColorUp
 
            // If close sits beyond every level on one side, no bracketing
            // pair exists and every NOW cell above is left blank — flag
            // that in the title so it's clear the table isn't just stale.
            secNowEmpty = na(secNearestAbovePrice) or na(secNearestBelowPrice)
            secDisplayTitle = secNowEmpty ? secTableTitle + '\nPrice Off Limits' : secTableTitle
 
            // Same merged title-bar treatment as the Mid/Long-Term table
            // above — row/column 0 is secTableTitle, and the NOW/TARGET/✓
            // header plus every data row shift down by one slot. NOW/✓
            // positions follow the shared Column Order setting; skipped
            // entirely in merged mode.
            if not tblMerge and secTableOrientation == 'Vertical'
                secTable := table.new(secTablePos, 3, secCount + 2, border_width = 1, border_color = color.new(color.black, 50))
                table.cell(secTable, 0, 0, secDisplayTitle, text_color = color.white, bgcolor = secTitleBgColor, text_size = secTableSize)
                table.merge_cells(secTable, 0, 0, 2, 0)
                table.cell(secTable, tblNowC, 1, 'NOW', text_color = color.white, bgcolor = secNowBgColor, text_size = secTableSize)
                table.cell(secTable, 1, 1, 'TARGET', text_color = color.white, bgcolor = secHeaderBg, text_size = secTableSize)
                table.cell(secTable, tblChkC, 1, '✅', text_color = color.white, bgcolor = secHeaderBg, text_size = secTableSize)
                for i = 0 to secCount - 1
                    table.cell(secTable, tblNowC, i + 2, array.get(secRowCurrentTxt, i), text_color = array.get(secRowCurrentClr, i), bgcolor = secNowBgColor, text_size = array.get(secRowSize, i), text_halign = tblSwapCols ? text.align_left : text.align_right, tooltip = 'NOW: shows the current price relative to the two nearest levels (Entry/Target events, Reference Levels, and the automatic 1D/1W/4H Open rows) that bracket it (the closest one above and the closest one below). It appears on only ONE row per tick - whichever of those two levels sits on the same side of the halfway point (50%) between them as the current price. If price is at or below that midpoint, it prints on the BELOW level\'s row: an up arrow, the current price, then how many dollars still short of that level. If price is above the midpoint, it prints on the ABOVE level\'s row: how many dollars past that level already, then a down arrow and the current price. Every other row stays blank, and if price sits beyond every level on one side (no bracketing pair), the whole column is blank and the table title adds "Price Off Limits".')
                    table.cell(secTable, 1, i + 2, array.get(secRowPriceTxt, i), text_color = array.get(secRowTxtCol2, i), bgcolor = array.get(secRowBgCol2, i), text_size = array.get(secRowSize, i))
                    table.cell(secTable, tblChkC, i + 2, array.get(secRowTxt3, i), text_color = array.get(secRowTxtCol3, i), bgcolor = secHeaderBg, text_size = array.get(secRowSize, i))
            else if not tblMerge
                secTable := table.new(secTablePos, secCount + 1, 4, border_width = 1, border_color = color.new(color.black, 50))
                table.cell(secTable, 0, 0, secDisplayTitle, text_color = color.white, bgcolor = secTitleBgColor, text_size = secTableSize)
                table.merge_cells(secTable, 0, 0, secCount, 0)
                table.cell(secTable, 0, tblNowR, 'NOW', text_color = color.white, bgcolor = secNowBgColor, text_size = secTableSize)
                table.cell(secTable, 0, 2, 'TARGET', text_color = color.white, bgcolor = secHeaderBg, text_size = secTableSize)
                table.cell(secTable, 0, tblChkR, '✅', text_color = color.white, bgcolor = secHeaderBg, text_size = secTableSize)
                for i = 0 to secCount - 1
                    table.cell(secTable, i + 1, tblNowR, array.get(secRowCurrentTxt, i), text_color = array.get(secRowCurrentClr, i), bgcolor = secNowBgColor, text_size = array.get(secRowSize, i), text_halign = text.align_right, tooltip = 'NOW: shows the current price relative to the two nearest levels (Entry/Target events, Reference Levels, and the automatic 1D/1W/4H Open rows) that bracket it (the closest one above and the closest one below). It appears on only ONE column per tick - whichever of those two levels sits on the same side of the halfway point (50%) between them as the current price. If price is at or below that midpoint, it prints on the BELOW level\'s column: an up arrow, the current price, then how many dollars still short of that level. If price is above the midpoint, it prints on the ABOVE level\'s column: how many dollars past that level already, then a down arrow and the current price. Every other column stays blank, and if price sits beyond every level on one side (no bracketing pair), the whole row is blank and the table title adds "Price Off Limits".')
                    table.cell(secTable, i + 1, 2, array.get(secRowPriceTxt, i), text_color = array.get(secRowTxtCol2, i), bgcolor = array.get(secRowBgCol2, i), text_size = array.get(secRowSize, i))
                    table.cell(secTable, i + 1, tblChkR, array.get(secRowTxt3, i), text_color = array.get(secRowTxtCol3, i), bgcolor = secHeaderBg, text_size = array.get(secRowSize, i))
 
////////////////////////////////////////////////////////////////////////////
////  END  S H O R T - T E R M   S U M M A R Y   T A B L E               ///
////  ( E N T R Y / T A R G E T / W E E K L Y / R E F )                  ///                                              ///
////////////////////////////////////////////////////////////////////////////
 
////////////////////////////////////////////////////////////
////      M E R G E D   S U M M A R Y   T A B L E         ///
////////////////////////////////////////////////////////////
// Built only when "Merge Both Tables Into One" is on. Reads the rows
// exported by both tables above (mlx* = Mid/Long-Term, stx* = SHORT-TERM).
// Slot (column in Vertical / row in Horizontal) order:
//   NOW on Left/Top    → NOW | M/L ✓ | M/L TARGET | S/T TARGET | S/T ✓
//   NOW on Right/Bottom→ M/L ✓ | M/L TARGET | S/T TARGET | S/T ✓ | NOW
//   Split              → M/L ✓ | M/L NOW | M/L TARGET | S/T TARGET | S/T NOW | S/T ✓
//     (each split NOW cell uses its own ladder's original NOW text and
//     marker color, still aligned on the shared NOW row)
// NOW-row alignment: each ladder has an anchor row (its NOW-marker row).
// Both ladders are shifted down so their anchors land on the same merged
// row (mgRowR = the larger of the two anchors); the ladder with the
// smaller anchor gets blank padding rows above it. The single NOW cell
// on that row shows the M/L distance, the current price, and the S/T
// distance (➖ = price below that level, ➕ = price above it). Its text
// color follows the M/L marker colors (S/T's when M/L has no marker).
var table mergedTable = na
if barstate.islast
    table.delete(mergedTable)
    if tblMerge and (mlxCount > 0 or stxCount > 0)
        mgMlOn   = mlxCount > 0
        mgStOn   = stxCount > 0
        mgAnchM  = mgMlOn ? mlxAnchor : 0
        mgAnchS  = mgStOn ? stxAnchor : 0
        mgRowR   = math.max(mgAnchM, mgAnchS)
        mgOffM   = mgRowR - mgAnchM
        mgOffS   = mgRowR - mgAnchS
        mgRows   = math.max(mgMlOn ? mgOffM + mlxCount : 0, mgStOn ? mgOffS + stxCount : 0)
        mgVert   = tblMergedOrient == 'Vertical'
        mgNowFirst = tblMergedNowSide == 'Left / Top'
        mgSplit    = tblMergedNowSide == 'Split (M/L Left · S/T Right)'
 
        // Split-mode NOW texts — same format as each separate table's own
        // NOW marker (blank when that ladder is off limits).
        mgMlNowTxt = mlxNowDir == -1 ? '➖' + str.tostring(mlxNowDiff, '$0,000') + '⁝\n↳ ' + str.tostring(close, '$0,000') : mlxNowDir == 1 ? '↱ ' + str.tostring(close, '$0,000') + '\n➕' + str.tostring(mlxNowDiff, '$0,000') + '⁝' : ''
        mgStNowTxt = stxNowDir == -1 ? '➖' + str.tostring(stxNowDiff, '$0,000') + '⁝\n↳ ' + str.tostring(close, '$0,000') : stxNowDir == 1 ? '↱ ' + str.tostring(close, '$0,000') + '\n➕' + str.tostring(stxNowDiff, '$0,000') + '⁝' : ''
 
        // Single NOW cell text (both ladders' NOW values on one row).
        mgMlPart = mlxNowDir == 1 ? 'M/L ➕' + str.tostring(mlxNowDiff, '$0,000') + '⁝' : mlxNowDir == -1 ? 'M/L ➖' + str.tostring(mlxNowDiff, '$0,000') + '⁝' : 'M/L Off Limits'
        mgStPart = stxNowDir == 1 ? 'S/T ➕' + str.tostring(stxNowDiff, '$0,000') + '⁝' : stxNowDir == -1 ? 'S/T ➖' + str.tostring(stxNowDiff, '$0,000') + '⁝' : 'S/T Off Limits'
        mgNowTxt = (mgMlOn ? mgMlPart + '\n' : '') + '⨀ ' + str.tostring(close, '$0,000') + (mgStOn ? '\n' + mgStPart : '')
        mgNowClr = mgMlOn and mlxNowDir != 0 ? mlxNowClr : mgStOn and stxNowDir != 0 ? stxNowClr : color.white
 
        mgOffLimM = mgMlOn and mlxNowDir == 0
        mgOffLimS = mgStOn and stxNowDir == 0
        mgTitle   = mgOffLimM or mgOffLimS ? tblMergedTitle + '\nPrice Off Limits' + (mgOffLimM and mgOffLimS ? '' : mgOffLimM ? ' (M/L)' : ' (S/T)') : tblMergedTitle
 
        // Slot types: 0 NOW (combined), 1 M/L ✓, 2 M/L TARGET, 3 S/T TARGET,
        // 4 S/T ✓, 5 M/L NOW (split), 6 S/T NOW (split).
        mgSlots = array.new_int(0)
        if mgNowFirst
            array.push(mgSlots, 0)
        if mgMlOn
            array.push(mgSlots, 1)
            if mgSplit
                array.push(mgSlots, 5)
            array.push(mgSlots, 2)
        if mgStOn
            array.push(mgSlots, 3)
            if mgSplit
                array.push(mgSlots, 6)
            array.push(mgSlots, 4)
        if not mgNowFirst and not mgSplit
            array.push(mgSlots, 0)
        mgSlotCount = array.size(mgSlots)
 
        mgMlHdrBg = color.new(mltHeaderColor, 20)
        mgStHdrBg = color.new(secHeaderColor, 20)
        mgClear   = color.new(color.black, 100)
        mgNowTip  = 'NOW (merged): both ladders are aligned so their NOW rows coincide. M/L = distance to the bracketing Mid/Long-Term marker level, S/T = distance to the bracketing SHORT-TERM marker level (➖ price is below that level, ➕ price is above it); the middle line is the current price. "Off Limits" means price sits beyond every level of that ladder on one side.'
 
        mergedTable := mgVert ? table.new(tblMergedPos, mgSlotCount, mgRows + 2, border_width = 1, border_color = color.new(color.black, 50)) : table.new(tblMergedPos, mgRows + 1, mgSlotCount + 1, border_width = 1, border_color = color.new(color.black, 50))
        table.cell(mergedTable, 0, 0, mgTitle, text_color = color.white, bgcolor = mltTitleBgColor, text_size = tblMergedSize)
        if mgVert
            table.merge_cells(mergedTable, 0, 0, mgSlotCount - 1, 0)
        else
            table.merge_cells(mergedTable, 0, 0, mgRows, 0)
 
        for s = 0 to mgSlotCount - 1
            mgTyp  = array.get(mgSlots, s)
            mgHTxt = mgTyp == 0 or mgTyp == 5 or mgTyp == 6 ? 'NOW' : mgTyp == 2 ? 'M/L TARGET' : mgTyp == 3 ? 'S/T TARGET' : '✅'
            mgHBg  = mgTyp == 0 or mgTyp == 5 ? mltNowBgColor : mgTyp == 6 ? secNowBgColor : mgTyp <= 2 ? mgMlHdrBg : mgStHdrBg
            if mgVert
                table.cell(mergedTable, s, 1, mgHTxt, text_color = color.white, bgcolor = mgHBg, text_size = tblMergedSize)
            else
                table.cell(mergedTable, 0, s + 1, mgHTxt, text_color = color.white, bgcolor = mgHBg, text_size = tblMergedSize)
            for r = 0 to mgRows - 1
                string mgTxt    = ''
                color  mgTxtCol = color.white
                color  mgBg     = mgClear
                string mgSize   = tblMergedSize
                string mgTip    = ''
                if mgTyp == 0
                    mgBg := mltNowBgColor
                    if r == mgRowR
                        mgTxt    := mgNowTxt
                        mgTxtCol := mgNowClr
                        mgTip    := mgNowTip
                else if mgTyp == 5
                    mgBg := mltNowBgColor
                    if r == mgRowR and mlxNowDir != 0
                        mgTxt    := mgMlNowTxt
                        mgTxtCol := mlxNowClr
                        mgTip    := 'M/L NOW: distance from the current price to the bracketing Mid/Long-Term level on this row (➖ price is below it, ➕ price is above it). Aligned on the same row as the S/T NOW.'
                else if mgTyp == 6
                    mgBg := secNowBgColor
                    if r == mgRowR and stxNowDir != 0
                        mgTxt    := mgStNowTxt
                        mgTxtCol := stxNowClr
                        mgTip    := 'S/T NOW: distance from the current price to the bracketing SHORT-TERM level on this row (➖ price is below it, ➕ price is above it). Aligned on the same row as the M/L NOW.'
                else if mgTyp <= 2
                    iM = r - mgOffM
                    if iM >= 0 and iM < mlxCount
                        mgSize := array.get(mlxSize, iM)
                        if mgTyp == 2
                            mgTxt    := array.get(mlxPriceTxt, iM)
                            mgTxtCol := array.get(mlxTxtCol2, iM)
                            mgBg     := array.get(mlxBg, iM)
                        else
                            mgTxt    := array.get(mlxTxt3, iM)
                            mgTxtCol := array.get(mlxTxtCol3, iM)
                            mgBg     := mgMlHdrBg
                else
                    iS = r - mgOffS
                    if iS >= 0 and iS < stxCount
                        mgSize := array.get(stxSize, iS)
                        if mgTyp == 3
                            mgTxt    := array.get(stxPriceTxt, iS)
                            mgTxtCol := array.get(stxTxtCol2, iS)
                            mgBg     := array.get(stxBg, iS)
                        else
                            mgTxt    := array.get(stxTxt3, iS)
                            mgTxtCol := array.get(stxTxtCol3, iS)
                            mgBg     := mgStHdrBg
                mgHalign = not mgVert ? text.align_center : mgTyp == 0 ? (mgNowFirst ? text.align_right : text.align_left) : mgTyp == 5 ? text.align_right : mgTyp == 6 ? text.align_left : text.align_center
                if mgVert
                    table.cell(mergedTable, s, r + 2, mgTxt, text_color = mgTxtCol, bgcolor = mgBg, text_size = mgSize, text_halign = mgHalign, tooltip = mgTip)
                else
                    table.cell(mergedTable, r + 1, s + 1, mgTxt, text_color = mgTxtCol, bgcolor = mgBg, text_size = mgSize, text_halign = mgHalign, tooltip = mgTip)
 
////////////////////////////////////////////////////////////
////   END  M E R G E D   S U M M A R Y   T A B L E       ///
////////////////////////////////////////////////////////////
 
//EOF

← 返回列表