CBC_OrderBlocksLib

Victoriasuss7 · library · 2041 行 · 点赞 1 · 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/
//@version=6
 
// Order Blocks helper library — extracted from CBC v4.85 (wCBC) to move these box-array utilities
// out of the main script's compiled-token budget, since Pine's CE10117 ceiling applies only to the
// main script; a published library compiles separately and doesn't count against it. These three
// functions are pure box-array utilities with no dependency on any of CBC's own internal state — all
// context (colors, counts, coordinates) is passed in as parameters — which is what makes them safe to
// pull out without touching CBC's own logic at all.
//
// v3 (09/09/2026): added 6 small pure-parameter formatting/string helpers moved out of the main CBC
// script for the same reason (CE10117 budget relief) — f_order3, f_price_vs_emas, f_struct_abbrev,
// f_prox_crossing, f_prox_approaching, f_fmt_ny_time. None of these touch CBC's own internal state;
// f_prox_crossing/f_prox_approaching now take their distance thresholds as explicit parameters
// (previously read the main script's own input.float globals directly, which a library can't do),
// and f_fmt_ny_time hardcodes "America/New_York" internally since that was always a fixed constant,
// never a user input.
//
// v4 (09/09/2026): added 4 more pure helpers for the same reason — f_status_pos (table-position
// string -> position.*), f_table_text_size (size-label string -> size.*), f_chart_tf_disp (chart
// timeframe -> display string, e.g. "15m"), f_htf_tf_disp (a timeframe string -> the same display
// format). All 4 only ever read their own parameters plus Pine's built-in timeframe.*/size.*/
// position.* namespaces — none of them touch any of CBC's own state. f_chart_tf_disp/f_htf_tf_disp
// are renamed from the main script's chart_tf_disp()/htf_tf_disp() purely for naming consistency
// with the rest of this library's f_-prefixed exports — no functional difference.
//
// v5 (09/10/2026): added 6 more pure-parameter helpers for the same reason (CE10117 relief round 3,
// main script over by 771 at v6.39) — f_prox_latch_name, f_htf_anchor_long, f_htf_anchor_short,
// f_level_label_text, f_apn, f_aplus_pivot_dist. Three of these (f_level_label_text, f_apn,
// f_aplus_pivot_dist) originally read the main script's own input.* globals directly (show_level_name/
// show_level_price, aplus_pivot_dist, aplus_pivot_dist_override) — a library can't do that, so each
// gained an explicit parameter for whatever it used to read from outer scope, same adaptation already
// used for f_prox_crossing/f_prox_approaching in v3. f_htf_anchor_long/f_htf_anchor_short read only
// bar_index/time[]/low[]/high[] — Pine's own built-in series, available from library scope the same
// way f_obAdd already reads high[_idx]/low[_idx]/bar_index — so no parameter changes needed for those
// two beyond their existing signature.
//
// v6 (09/13/2026): added f_paLabel — a pure box/label-style helper (coords/text/color/size all passed
// in as parameters, no CBC-internal state) for the new Price Action Structure (Internal/Swing HH/HL/
// LH/LL) markers. Same proven-safe category as f_obAdd/f_htfObAdd: creates one label per call, no
// array management needed (unlike Order Blocks' boxes) since these markers are meant to persist as a
// historical record on the chart rather than being deleted/managed.
//
// v13 (09/15/2026): added f_orbRetestMarker — a pure box+label helper for the 6 near-identical ORB
// Retest marker call sites (Pass/Flip/Fail-from, both directions) in the main script, each of which
// was a hand-written box.new()+label.new() pair differing only in y-offset/half-height/border color/
// tooltip text — all now passed in as parameters. Same proven-safe "pass state in as parameters,
// create inside, no CBC-internal state read" category as f_obAdd/f_paLabel/f_levelLabel above. Added
// as part of a CE10117 token-budget trim (100606/100256) alongside a main-script loop consolidation
// for the Session ORB Cross feature's 3 named-session branches.
//
// v15 (09/17/2026): added f_fmt_ny_time_sec — a seconds-resolution sibling of f_fmt_ny_time, per
// direct request ("can the time in the tooltip include seconds"). Scoped to tooltips ONLY, confirmed
// via follow-up: the Status table, Historical Bar Panel, and alert emails all keep using the existing
// minute-only f_fmt_ny_time unchanged, so their display format doesn't shift for anyone. This new
// function is a straight copy of f_fmt_ny_time's body with one added ":SS" segment (zero-padded same
// way H/MM already are) — same "America/New_York" hardcoded internally, same na-guard returning "—".
// Main script call sites updated: the LTF CBC Reversal triangle tooltip, the confirmed HTF CBC Flip
// dot's "Confirmed: " tooltip line (shared with the HTF Reversal gold-dot tooltip), and the
// anticipatory HTF CBC Flip dot's "Fired: " tooltip line — all 3 are pure tooltip-only call sites (no
// Status table cell, Historical Bar Panel row, or alert email reuses them), confirmed via grep before
// changing anything.
//
// v16 (09/17/2026): CE10117 relief (100457/100256, over by 201) — the v7.08 LTF CBC Reversal tooltip
// was the newest, priciest piece of inline string-building in the main script (a brand-new multi-part
// tooltip= argument -- ticker + label text + a ternary + a timestamp call -- where none existed
// before v7.08). Moved that whole tooltip-string assembly into this library as f_ltf_reversal_tooltip,
// same proven-safe "pass state in as parameters, build/return string, no CBC-internal state read"
// category as f_vwap_flip_warning/f_pivot_flip_warning above (ticker/is_bull/t are all passed in; it
// calls this library's own f_fmt_ny_time_sec internally, no cross-library dependency). Main script
// call site collapses from a full inline concatenation to a single function call.
//
// v17 (09/17/2026): CE10117 relief round 2, same report (100333/100256, over by 77 after v16's fix
// brought it down from 201). Two more small moves, both flagged as "next targets" in the main script's
// own v7.10 changelog: (1) f_htf_is_reversal — the small boolean expression behind the v7.08
// htf_reversal named var (bull/bear OR, a bar-count subtraction, an equality check) moved here as a
// pure 4-parameter function; the main script still keeps its own local htf_reversal var (it's read at
// 2 sites there) but that var's right-hand side is now one function call instead of the full inline
// expression. (2) f_htf_reversal_note — the static "⚠ HTF Reversal..." tooltip string itself, with no
// parameters at all, so the main script calls it instead of carrying the string literal. Same
// proven-safe "pure parameters/no parameters in, CBC-internal state never read" category as
// f_ltf_reversal_tooltip above.
//
// v18 (09/18/2026, SUPERSEDED by v19 below): first CE10117 relief attempt for v7.14 (main script
// reported 100551/100256, over by 295) — added an array-based f_resolve_flip_early. This made the
// main script's count WORSE (100582, up from 100551): wrapping every read/write of the 6 dot/arrow
// tracking vars in array.get()/array.set() at ~9 touch points cost more than the resolver logic it
// replaced ever did. Left in the file history here as a record of what NOT to do — v19 replaced this
// signature entirely with a scalar version plus 2 new draw-site exports, see below.
//
// v19 (09/18/2026): CE10117 relief round 2 for v7.14/v7.15 (v7.14 reported 100582/100256, over by 326
// — worse than v7.13's original 100551). Reworked f_resolve_flip_early back to 8 plain scalar
// parameters (label/pred/wait for the dot, same 3 for the arrow, plus the confirmed direction and the
// live HTF bar identity) instead of arrays — a single call now resolves both the dot's and the arrow's
// pending prediction and returns a 2-value tuple (each one's new wait-time) for the main script to
// reassign onto its own persistent vars. More importantly, added 2 new exports that move the actual
// DRAW-SITE label.new() calls into the library, not just the resolver: f_flip_early_dot (builds the
// anticipatory dot's full tooltip — ticker + direction + seconds-before-close + a timestamp call +
// EMA-distance string + an optional detailed-snapshot line — and creates the label) and
// f_flip_early_arrow (builds the anticipatory arrow's label, with its own y-offset/color/style
// ternaries). This is the same proven-safe "pass state in as parameters, no CBC-internal state read"
// category as f_orbRetestMarker/f_paLabel/f_levelLabel above — the main script's call sites now just
// assign the returned label directly, same ":= label.new(...)" idiom pointed at a function call.
//
// v20 (09/19/2026): CE10117 relief for v7.18 (main script reported 104160/100256, over by 3904).
// Added f_next_two_levels — the entire "next two levels" scan for the CBC main script's Next Target
// Levels / Next Stop Levels Status-table rows (items 3/4 of its Pre-Trade Checklist), moved here as
// a pure 4-parameter function: a price array, a matching label array, the live trade-direction bool,
// and the current close. No CBC-internal state read beyond what's passed in — generalized to any
// pool size via array.size() rather than a hardcoded count, so the main script can grow its level
// pool later without needing this function touched again. Same proven-safe "pass state in as
// parameters, build/return values" category as f_vwap_flip_warning/f_pivot_flip_warning above.
//
// To use: publish this script as a library (Pine Editor -> Publish script -> Library), then in the
// main CBC script replace the import line's username placeholder with your own TradingView username
// and the version number with whatever this publishes as (starts at 1).
library("CBC_OrderBlocksLib", overlay = true)
 
// Creates a new LTF order-block box, anchored via a bar_index offset (_idx = bars back from the
// current bar), and pushes it onto _boxes — trimming the oldest box if the per-side cap (_max) is
// exceeded.
export f_obAdd(box[] _boxes, int _idx, color _col, int _max) =>
    array.push(_boxes, box.new(left = bar_index - _idx, top = high[_idx], right = bar_index, bottom = low[_idx], border_color = color.new(_col, 40), bgcolor = _col, extend = extend.right))
    if array.size(_boxes) > _max
        box.delete(array.shift(_boxes))
 
// Creates a new HTF order-block box, anchored with explicit time bounds (_leftT/_rightT) instead of a
// bar_index offset, since bar_index doesn't map to HTF candle widths — same push/trim behavior as
// f_obAdd otherwise.
export f_htfObAdd(box[] _boxes, int _leftT, float _top, int _rightT, float _bot, color _col, int _max) =>
    array.push(_boxes, box.new(left = _leftT, top = _top, right = _rightT, bottom = _bot, xloc = xloc.bar_time, border_color = color.new(_col, 40), bgcolor = _col, extend = extend.right))
    if array.size(_boxes) > _max
        box.delete(array.shift(_boxes))
 
// Mitigation check for either LTF or HTF order-block boxes: deletes and removes any box the current
// bar's wick has traded back through (low below the box's bottom for a bullish box, high above the
// box's top for a bearish one).
// Updates one swing-pivot "unbroken high/low" state pair given this bar's fresh pivot values (na if no
// new pivot formed). Used for both LTF and HTF Order Blocks — same 4-line update pattern, now shared
// instead of duplicated at each call site, and moved out of the main script's CE10117 budget entirely.
export f_obUpdateSwing(float _pivHi, float _pivLo, float _swHi, bool _swHiBroken, float _swLo, bool _swLoBroken) =>
    float swHi = not na(_pivHi) ? _pivHi : _swHi
    bool swHiBroken = not na(_pivHi) ? false : _swHiBroken
    float swLo = not na(_pivLo) ? _pivLo : _swLo
    bool swLoBroken = not na(_pivLo) ? false : _swLoBroken
    [swHi, swHiBroken, swLo, swLoBroken]
 
export f_obManage(box[] _boxes, bool _isBull) =>
    if array.size(_boxes) > 0
        for i = array.size(_boxes) - 1 to 0
            box bx = array.get(_boxes, i)
            if _isBull ? low < box.get_bottom(bx) : high > box.get_top(bx)
                array.remove(_boxes, i)
                box.delete(bx)
 
// Orders 3 (value, label) pairs ascending and renders them as "label<label<label", starring whichever
// label matches star_label. Used for the "ema9 < ema20 < price" style ordering lines in alert emails.
export f_order3(float v1, string l1, float v2, string l2, float v3, string l3, string star_label) =>
    string s1 = (l1 == star_label ? "*" : "") + l1 + " " + str.tostring(v1, "#.##") + (l1 == star_label ? "*" : "")
    string s2 = (l2 == star_label ? "*" : "") + l2 + " " + str.tostring(v2, "#.##") + (l2 == star_label ? "*" : "")
    string s3 = (l3 == star_label ? "*" : "") + l3 + " " + str.tostring(v3, "#.##") + (l3 == star_label ? "*" : "")
    string result = ""
    if v1 <= v2 and v2 <= v3
        result := s1 + "<" + s2 + "<" + s3
    else if v1 <= v3 and v3 <= v2
        result := s1 + "<" + s3 + "<" + s2
    else if v2 <= v1 and v1 <= v3
        result := s2 + "<" + s1 + "<" + s3
    else if v2 <= v3 and v3 <= v1
        result := s2 + "<" + s3 + "<" + s1
    else if v3 <= v1 and v1 <= v2
        result := s3 + "<" + s1 + "<" + s2
    else
        result := s3 + "<" + s2 + "<" + s1
    result
 
// Classifies price relative to two EMAs regardless of which one is higher: "Above Both", "Below Both", or "Between".
export f_price_vs_emas(float price, float ema_a, float ema_b) =>
    float lo = math.min(ema_a, ema_b)
    float hi = math.max(ema_a, ema_b)
    string result = price > hi ? "Above Both" : price < lo ? "Below Both" : "Between"
    result
 
// Abbreviates a Structure classification string ("Higher High" -> "HH", etc.) for compact table display.
export f_struct_abbrev(string s) =>
    string result = s == "Higher High" ? "HH" : s == "Lower High" ? "LH" : s == "Higher Low" ? "HL" : s == "Lower Low" ? "LL" : s
    result
 
// Level Proximity Alerts (ported from CBC Wire): returns a formatted bullet-text string if price
// is within the CROSSING distance of level_val, else "". "Crossing" here means "currently very
// close to" the level (either side), not a directional cross event like the existing VWAP
// Break/EMA 200 Break alert types. Distance thresholds are passed in since a library can't read the
// main script's own input.float values directly.
export f_prox_crossing(float price, float level_val, string level_name, float crossing_dist) =>
    string result = ""
    if not na(level_val)
        float dist = math.abs(price - level_val)
        if dist <= crossing_dist
            string dir_word = price > level_val ? "above" : "below"
            result := level_name + " Crossing (" + str.tostring(dist, "#.##") + " points " + dir_word + " Price, " + level_name + ": " + str.tostring(level_val, "#.##") + ")"
    result
 
// Same, but for the wider APPROACHING band (farther than crossing distance, within approaching
// distance). Only called when a full crossing pass has already found nothing.
export f_prox_approaching(float price, float level_val, string level_name, float crossing_dist, float approach_dist) =>
    string result = ""
    if not na(level_val)
        float dist = math.abs(price - level_val)
        if dist > crossing_dist and dist <= approach_dist
            string dir_word = price > level_val ? "above" : "below"
            result := level_name + " Approaching (" + str.tostring(dist, "#.##") + " points " + dir_word + " Price, " + level_name + ": " + str.tostring(level_val, "#.##") + ")"
    result
 
// Formats a UTC ms timestamp as "M/D H:MM ET" in New York time. Used for "last flip" displays
// (Status table, Historical Bar Panel, alert email) so they all read the same way. Hardcodes
// "America/New_York" internally — this was always a fixed constant in the main script, never a
// user input, so no need to pass it in.
export f_fmt_ny_time(int t) =>
    string result = na(t) ? "—" : str.tostring(month(t, "America/New_York"), "#") + "/" + str.tostring(dayofmonth(t, "America/New_York"), "#") + " " + (hour(t, "America/New_York") < 10 ? "0" : "") + str.tostring(hour(t, "America/New_York"), "#") + ":" + (minute(t, "America/New_York") < 10 ? "0" : "") + str.tostring(minute(t, "America/New_York"), "#") + " ET"
    result
 
// v15: seconds-resolution sibling of f_fmt_ny_time above, for tooltip-only call sites that want more
// precision than the shared minute-only format (Status table/Historical Bar Panel/alert emails keep
// using f_fmt_ny_time unchanged). Identical structure, with one added zero-padded ":SS" segment.
export f_fmt_ny_time_sec(int t) =>
    string result = na(t) ? "—" : str.tostring(month(t, "America/New_York"), "#") + "/" + str.tostring(dayofmonth(t, "America/New_York"), "#") + " " + (hour(t, "America/New_York") < 10 ? "0" : "") + str.tostring(hour(t, "America/New_York"), "#") + ":" + (minute(t, "America/New_York") < 10 ? "0" : "") + str.tostring(minute(t, "America/New_York"), "#") + ":" + (second(t, "America/New_York") < 10 ? "0" : "") + str.tostring(second(t, "America/New_York"), "#") + " ET"
    result
 
// v55: replaces v54's f_fmt_ny_time_hm(t) (single-time "H:MM") -- per direct follow-up ("make it
// 9:30-45 or in another case 9:45-10"), the Pivot Points table's Price row now wants a compact OPEN-
// CLOSE range instead of a single time. Format, per the two examples given: "H:MM-mm" when the close
// falls in the SAME hour as the open (e.g. "9:30-45" -- open 9:30, close 9:45, only the close minutes
// repeated); "H:MM-H2" or "H:MM-H2:mm2" when the close falls in a DIFFERENT hour (e.g. "9:45-10" --
// open 9:45, close 10:00, close minutes are exactly :00 so dropped entirely and only the new hour
// shows; a close at e.g. 10:15 would read "9:45-10:15", minutes shown since they're non-zero). No
// month/day/seconds/" ET" -- same narrow-cell reasoning that motivated v54's now-superseded helper.
export f_fmt_ny_time_range(int t_open, int t_close) =>
    int open_h = hour(t_open, "America/New_York")
    int open_m = minute(t_open, "America/New_York")
    int close_h = hour(t_close, "America/New_York")
    int close_m = minute(t_close, "America/New_York")
    string open_str = str.tostring(open_h, "#") + ":" + (open_m < 10 ? "0" : "") + str.tostring(open_m, "#")
    string close_str = close_h == open_h ? (close_m < 10 ? "0" : "") + str.tostring(close_m, "#") : close_m == 0 ? str.tostring(close_h, "#") : str.tostring(close_h, "#") + ":" + (close_m < 10 ? "0" : "") + str.tostring(close_m, "#")
    string result = (na(t_open) or na(t_close)) ? "—" : open_str + "-" + close_str
    result
 
// v16: builds the LTF CBC Reversal triangle's full tooltip string (ticker header, direction label,
// fixed explainer text, seconds-resolution timestamp via f_fmt_ny_time_sec above) — moved out of the
// main script's CE10117 budget since it's pure string assembly from 3 passed-in parameters, no
// CBC-internal state read.
export f_ltf_reversal_tooltip(string tkr, bool is_bull, int t) =>
    tkr + " —\n• LTF CBC Reversal: " + (is_bull ? "LONG" : "SHORT") + " — flipped, then flipped again on the very next bar\n" + f_fmt_ny_time_sec(t)
 
// v17 (09/17/2026): CE10117 relief round 2, same report (100333/100256, over by 77 after v16's fix
// brought it down from 201). Two more small moves, both flagged as "next targets" in the main script's
// own v7.10 changelog: (1) f_htf_is_reversal — the small boolean expression behind the v7.08
// htf_reversal named var (bull/bear OR, a bar-count subtraction, an equality check) moved here as a
// pure 4-parameter function; the main script still keeps its own local htf_reversal var (it's read at
// 2 sites there) but that var's right-hand side is now one function call instead of the full inline
// expression. (2) f_htf_reversal_note — the static "⚠ HTF Reversal..." tooltip string itself, with no
// parameters at all, so the main script calls it instead of carrying the string literal. Same
// proven-safe "pure parameters/no parameters in, CBC-internal state never read" category as
// f_ltf_reversal_tooltip above.
export f_htf_is_reversal(bool flip_bull, bool flip_bear, int close_n, int last_flip_bar_n) =>
    (flip_bull or flip_bear) and (close_n - last_flip_bar_n == 1)
 
export f_htf_reversal_note() =>
    "⚠ HTF Reversal — flipped, then flipped again on the very next HTF bar"
 
// v19 (09/18/2026): resolves the HTF CBC Flip anticipatory dot's AND the anticipatory arrow's pending
// prediction in one call, 8 plain scalar parameters (v18's array version made the main script's count
// worse — see the changelog note above). For each of the dot/arrow: if it has a pending wait-time AND
// the live HTF bar has moved on past it (meaning the bar it was waiting on has now closed), check
// whether the now-confirmed direction matches what was predicted — if not, delete that label; either
// way the returned wait-time resets to na so the same prediction never resolves twice. Returns a
// 2-tuple (the dot's new wait-time, the arrow's new wait-time) for the caller to reassign onto its own
// persistent vars with :=, since Pine's tuple-declare syntax can't target an existing var directly.
export f_resolve_flip_early(label lbl_dot, float pred_dot, int wait_dot, label lbl_arrow, float pred_arrow, int wait_arrow, float confirmed, int live_t) =>
    int new_wait_dot = wait_dot
    if not na(wait_dot) and live_t != wait_dot
        if confirmed != pred_dot
            label.delete(lbl_dot)
        new_wait_dot := na
    int new_wait_arrow = wait_arrow
    if not na(wait_arrow) and live_t != wait_arrow
        if confirmed != pred_arrow
            label.delete(lbl_arrow)
        new_wait_arrow := na
    [new_wait_dot, new_wait_arrow]
 
// v19: builds and creates the HTF CBC Flip anticipatory DOT's full label — ticker header, direction,
// "within Ns of close" mechanics note, a fired timestamp (via f_fmt_ny_time_sec above), the EMA-
// distance string, and an optional detailed-snapshot line — all passed in as parameters, no
// CBC-internal state read. This was the single most expensive piece of the v7.13 addition (a brand-new
// multi-part tooltip concatenation, same weight-class as the v7.08 LTF Reversal tooltip that needed
// the same treatment at v7.10).
export f_flip_early_dot(string tkr, bool isBull, int secsBeforeClose, int firedT, string emaDist, bool detailed, string snapshot, color col) =>
    string tip = tkr + " —\n• HTF CBC Flip: " + (isBull ? "LONG" : "SHORT") + " (ANTICIPATORY — within " + str.tostring(secsBeforeClose) + "s of HTF bar close, NOT yet confirmed; can revert before close)\nFired: " + f_fmt_ny_time_sec(firedT) + "\n" + emaDist + (detailed ? "\n" + snapshot : "")
    label.new(bar_index, na, text="", tooltip=tip, yloc=yloc.belowbar, style=label.style_circle, size=size.small, color=color.new(col, 50), textcolor=col)
 
// v19: builds and creates the HTF CBC Flip anticipatory ARROW's label — y-offset/color/style all
// picked by a direction ternary, same pattern as the confirmed-arrow draw site this file doesn't touch.
export f_flip_early_arrow(bool isBull, float lo, float hi, color longCol, color shortCol, string sz) =>
    label.new(x=bar_index, y=isBull ? lo - (hi - lo) * 0.35 : hi + (hi - lo) * 0.35, text="", color=isBull ? color.new(longCol, 50) : color.new(shortCol, 50), style=isBull ? label.style_triangleup : label.style_triangledown, size=sz)
 
// Appends ln_txt onto base as a new line (prefixing "\n" only if base already has content). Used
// throughout the alert-email builders to accumulate multi-bullet message bodies one line at a time.
export f_add_line(string base, string ln_txt) =>
    base + (base != "" ? "\n" : "") + ln_txt
 
// Maps a "Top left"/"Bottom right"/etc. settings-panel string to its position.* value, defaulting to
// top_right for anything unrecognized. Used by every table (Status, Pivot, Confluence Cells) to place
// itself from a single position input.
export f_status_pos(string p) =>
    switch p
        "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
        "Bottom right" => position.bottom_right
        => position.top_right
 
// Maps a "Tiny"/"Small"/"Normal"/"Large"/"Huge" settings-panel string to its size.* value, defaulting
// to size.small for anything unrecognized.
export f_table_text_size(string s) =>
    switch s
        "Tiny" => size.tiny
        "Small" => size.small
        "Normal" => size.normal
        "Large" => size.large
        "Huge" => size.huge
        => size.small
 
// Formats the CHART's own timeframe as a short display string ("15m", "1D", "1W", etc., or the raw
// timeframe.period as a fallback). Reads only Pine's built-in timeframe.* namespace, which reflects
// the calling script's own chart context even from inside a library — no CBC state involved.
export f_chart_tf_disp() =>
    string r = timeframe.isminutes ? str.tostring(timeframe.multiplier) + "m" : timeframe.isseconds ? str.tostring(timeframe.multiplier) + "s" : timeframe.isdaily ? str.tostring(timeframe.multiplier) + "D" : timeframe.isweekly ? str.tostring(timeframe.multiplier) + "W" : timeframe.ismonthly ? str.tostring(timeframe.multiplier) + "M" : timeframe.period
    r
 
// Same display-string formatting as f_chart_tf_disp, but for an arbitrary timeframe string passed in
// (used for the HTF/MTF timeframe inputs, which aren't the chart's own timeframe).
export f_htf_tf_disp(string tf) =>
    int sec = timeframe.in_seconds(tf)
    string r = tf
    if not na(sec) and sec > 0
        if sec == 86400
            r := "1D"
        else if sec == 604800
            r := "1W"
        else if sec < 86400 and sec % 3600 == 0
            r := str.tostring(sec / 3600) + "H"
        else if sec < 86400 * 7 and sec % 60 == 0
            r := str.tostring(sec / 60) + "m"
        else
            r := tf
    r
 
// Strips the trailing " Crossing (...)"/" Approaching (...)" detail off a Level Proximity Alerts
// bullet string, leaving just the level's own name — used to detect when the SAME level is still the
// latched proximity match across bars (vs. a different level taking over), without re-parsing the
// full bullet text at every comparison site.
export f_prox_latch_name(string bullet) =>
    string result = bullet
    int sep_c = str.pos(bullet, " Crossing (")
    int sep_a = str.pos(bullet, " Approaching (")
    if not na(sep_c)
        result := str.substring(bullet, 0, sep_c)
    else if not na(sep_a)
        result := str.substring(bullet, 0, sep_a)
    result
 
// Finds the best-matching HTF bar (within max_off bars back) whose time window [t_open, t_close]
// contains this LTF bar's timestamp, and returns an anchor point [bar_index, price] slightly below
// that bar's low — used to place the HTF-flip long-side label/line near the actual HTF candle that
// flipped, not just the current LTF bar. Reads only bar_index/time[]/low[]/high[], Pine's own
// built-in series (available from library scope the same way f_obAdd already reads high[_idx]).
export f_htf_anchor_long(float sig_lo, int t_open, int t_close, int max_off) =>
    int best_off = 0
    float best_err = na
    bool found = false
    for off = 0 to max_off
        if bar_index >= off
            int ot = time[off]
            if not na(ot) and not na(t_open) and not na(t_close) and ot >= t_open and ot <= t_close
                float err = math.abs(low[off] - sig_lo)
                if not found or err < best_err or (err == best_err and off > best_off)
                    best_err := err
                    best_off := off
                    found := true
    int off_use = found ? best_off : 0
    [bar_index - off_use, low[off_use] - (high[off_use] - low[off_use]) * 0.3]
 
// Same as f_htf_anchor_long, but anchors above the matching bar's high — used for the HTF-flip
// short-side label/line.
export f_htf_anchor_short(float sig_hi, int t_open, int t_close, int max_off) =>
    int best_off = 0
    float best_err = na
    bool found = false
    for off = 0 to max_off
        if bar_index >= off
            int ot = time[off]
            if not na(ot) and not na(t_open) and not na(t_close) and ot >= t_open and ot <= t_close
                float err = math.abs(high[off] - sig_hi)
                if not found or err < best_err or (err == best_err and off > best_off)
                    best_err := err
                    best_off := off
                    found := true
    int off_use = found ? best_off : 0
    [bar_index - off_use, high[off_use] + (high[off_use] - low[off_use]) * 0.3]
 
// Formats a reference-level label's text from the level's name and price, honoring the two
// "Show Level Name"/"Level Price" master toggles — used by every YDH/YDL/YDC/PMH/PML/ORB/Pivot label
// across the chart. show_name/show_price are passed in since a library can't read the main script's
// own input.bool globals directly.
export f_level_label_text(string level_name, float level_price, bool show_name, bool show_price) =>
    string result = ""
    if show_name and show_price
        result := level_name + " " + str.tostring(level_price, "#.##")
    else if show_name
        result := level_name
    else if show_price
        result := str.tostring(level_price, "#.##")
    result
 
// A+ Setup - Major Pivot Proximity: appends label to note (comma-joined) if val is within dist points
// of the current close. dist is passed in (was the main script's own aplus_pivot_dist top-level var).
export f_apn(string note, float val, string label, float dist) =>
    not na(val) and math.abs(close - val) <= dist ? note + (note != "" ? ", " : "") + label : note
 
// A+ Setup - Major Pivot Proximity: the effective proximity distance, in points — either the user's
// explicit override, or an auto default based on symbol root (50 for MNQ, 5 otherwise). override_val
// is passed in (was the main script's own aplus_pivot_dist_override input read directly).
export f_aplus_pivot_dist(float override_val) =>
    string root = syminfo.root
    float auto_pts = root == "MNQ" ? 50.0 : 5.0
    override_val > 0 ? override_val : auto_pts
 
// Chart-level label overlap handling (v7.72): groups a set of price values into clusters of mutually
// "close" (within dist points) entries and returns, for each index, the index of its group's leader
// (the lowest index in that group). An index that is its own leader (result[i] == i) is either a
// singleton or the representative of a multi-member group; every other member of a group points to
// that same leader index. Union-by-chaining via relaxation passes (n passes over all pairs guarantees
// full propagation for a chain of up to n entries) — cheap at the ~16-22 levels this is ever called
// with, so no more efficient union-find structure is worth the added complexity here.
export f_level_group_leader(float[] prices, float dist) =>
    int n = array.size(prices)
    int[] leader = array.new_int(n)
    for i = 0 to n - 1
        array.set(leader, i, i)
    for pass = 0 to n - 1
        for i = 0 to n - 2
            for j = i + 1 to n - 1
                if math.abs(array.get(prices, i) - array.get(prices, j)) <= dist
                    int li = array.get(leader, i)
                    int lj = array.get(leader, j)
                    int min_l = math.min(li, lj)
                    if li != min_l
                        array.set(leader, i, min_l)
                    if lj != min_l
                        array.set(leader, j, min_l)
    leader
 
// Chart-level label overlap handling (v7.72): builds the combined text for a merged group of level
// labels (e.g. "PMH / LN ORB-H 4308.4"), honoring the same show_name/show_price toggles as the
// single-level f_level_label_text() above — names joined with " / " when shown, one shared price
// (the group leader's own y, already confirmed within dist of every member) appended when shown.
export f_level_merged_text(string[] names, float price, bool show_name, bool show_price) =>
    string result = ""
    if show_name
        result := array.join(names, " / ")
    if show_price
        result := result + (result != "" ? " " : "") + str.tostring(price, "#.##")
    result
 
// "Potential flop close to VWAP" warning: on a long setup, VWAP should sit comfortably ABOVE the
// flip price (nothing overhead to cap the move); on a short setup, VWAP should sit comfortably BELOW
// it. If VWAP is on the expected side but closer than min_dist points, returns a warning string —
// otherwise "". Does NOT warn when VWAP is on the "wrong" side entirely (dist <= 0); that's a
// different, more severe situation than "close," left for a future check if ever wanted.
export f_vwap_flip_warning(float vwap_val, float flip_price, bool is_long, float min_dist) =>
    string result = ""
    if not na(vwap_val) and not na(flip_price) and not na(min_dist)
        float dist = is_long ? vwap_val - flip_price : flip_price - vwap_val
        if dist > 0 and dist < min_dist
            result := "⚠ Potential flop - close to VWAP (" + str.tostring(dist, "#.##") + " pts)"
    result
 
// "Potential flop close to <pivot level>" warning — same idea as f_vwap_flip_warning above, but
// checks all 6 non-PP Pivot Points levels (R3/R2/R1/S1/S2/S3, packed in piv_vals/piv_lbls the same way
// the main script's Key Level Alert already loops over them) instead of VWAP. Whichever qualifying
// level is on the "overhead" side of the flip price for a long (or "underneath" for a short) AND
// nearest wins — checked by actual value/position relative to price, not by R-vs-S label, since a
// level can in principle sit on either side of price. Returns "" if no level qualifies (none on the
// expected side within min_dist) or PP is the only match (PP is deliberately skipped by label).
export f_pivot_flip_warning(float flip_price, float[] piv_vals, string[] piv_lbls, bool is_long, float min_dist) =>
    string result = ""
    if not na(flip_price) and not na(min_dist)
        float best_dist = 1e10
        string best_lbl = ""
        for i = 0 to array.size(piv_vals) - 1
            string lbl = array.get(piv_lbls, i)
            if lbl != "PP"
                float lvl = array.get(piv_vals, i)
                if not na(lvl)
                    float dist = is_long ? lvl - flip_price : flip_price - lvl
                    if dist > 0 and dist < best_dist
                        best_dist := dist
                        best_lbl := lbl
        if best_lbl != "" and best_dist < min_dist
            result := "⚠ Potential flop - close to " + best_lbl + " (" + str.tostring(best_dist, "#.##") + " pts)"
    result
 
// v6.44 CE10117 relief round: moved 7 more pure, parameter-only (or built-in-only) helpers out of the
// main script — same technique proven safe/effective at v6.18/v6.23/v6.40 (library code compiles
// separately and doesn't count against the main script's budget at all). None of these touch CBC's
// own internal request.security/CBC-state pipeline.
 
// Market session by New York time-of-day ("Asian"/"London"/"New York"). Hardcodes the "America/
// New_York" timezone string directly (was the main script's own ny_tz constant, always this exact
// literal, so no need to thread it through as a parameter).
export f_market_session_et() =>
    int hm = hour(time, "America/New_York") * 60 + minute(time, "America/New_York")
    hm >= 20 * 60 or hm < 3 * 60 ? "Asian" : hm < 9 * 60 + 30 ? "London" : "New York"
 
// Asian OR anchor (8 PM ET open), same "America/New_York" literal as above.
export f_asia_or_open_ms() =>
    int cand = timestamp("America/New_York", year(time, "America/New_York"), month(time, "America/New_York"), dayofmonth(time, "America/New_York"), 20, 0)
    hour(time, "America/New_York") < 3 and time < cand ? cand - 86400000 : cand
 
// Trailing-stop timeframe step-up: 3->15, 15->60, 60->240, else unchanged. Pure — reads only
// timeframe.period (a Pine built-in), no main-script state.
export f_stop_tf() =>
    string ctf = timeframe.period
    ctf == "3" or ctf == "15" ? "3" : ctf == "60" ? "15" : ctf == "240" ? "60" : ctf
 
// Breakeven + step-trail size, auto by symbol root (MES/MGC=5, MNQ=30, M2K=3, other=5) or the main
// script's own manual override if set (passed in — a library can't read the main script's input
// directly).
export f_be_trail_step(float override_val) =>
    string root = syminfo.root
    float auto_pts = root == "MES" or root == "MGC" ? 5.0 : root == "MNQ" ? 30.0 : root == "M2K" ? 3.0 : 5.0
    override_val > 0 ? override_val : auto_pts
 
// VWAP Bounce / flip-warning shared min-distance auto table (MES/MGC=6, M2K=4, MNQ=60, other=6) — pure,
// syminfo.root only.
export f_vwap_bounce_min_dist() =>
    string root = syminfo.root
    root == "MES" or root == "MGC" ? 6.0 : root == "M2K" ? 4.0 : root == "MNQ" ? 60.0 : 6.0
 
// Shared VWAP-near-flip / Pivot-Level-near-flip threshold: the main script's 3 per-symbol overrides
// (MGC/MES/MNQ) passed in, falling back to f_vwap_bounce_min_dist()'s auto table for M2K/other/unset.
export f_flip_warn_min_dist(float mgc_ovr, float mes_ovr, float mnq_ovr) =>
    string root = syminfo.root
    float ovr = root == "MGC" ? mgc_ovr : root == "MES" ? mes_ovr : root == "MNQ" ? mnq_ovr : 0.0
    ovr > 0 ? ovr : f_vwap_bounce_min_dist()
 
// LTF/HTF/MTF tier sort order by ascending timeframe (minutes) — chart_tf/htf_tf/mtf_tf passed in
// since a library can't read the main script's own htf_timeframe/mtf_timeframe inputs directly.
export f_ltf_htf_mtf_order(string htf_tf, string mtf_tf) =>
    array<int> minutes = array.from(int(timeframe.in_seconds() / 60), int(timeframe.in_seconds(htf_tf) / 60), int(timeframe.in_seconds(mtf_tf) / 60))
    array.sort_indices(minutes, order.ascending)
 
// Shared LTF/HTF/MTF status-table row helper (CBC/EMA cloud/Structure rows, both the Status table and
// the — currently commented-out — Historical Bar Panel). Already fully parameterized in the main
// script (no reliance on any of its own globals beyond what's passed in), so this is a pure move with
// no signature changes needed at any call site beyond the obLib. prefix.
export f_add_tf_row(table tbl, int start_row, string label_base,
             string ltf_msg, color ltf_bg,
             string htf_msg, color htf_bg,
             string mtf_msg, color mtf_bg,
             bool show_ltf, bool show_htf, bool show_mtf, bool show_mtf_field,
             string chart_tf, string htf_tf, string mtf_tf,
             color label_bg, color label_txt, color on_txt, string txt_sz,
             array<int> order,
             string ltf_tt = "", string htf_tt = "", string mtf_tt = "") =>
    int r = start_row
    for i = 0 to 2
        int tier = array.get(order, i)
        if tier == 0 and show_ltf
            table.cell(tbl, 0, r, label_base + " (" + chart_tf + ")", bgcolor=label_bg, text_color=label_txt, text_size=txt_sz, text_halign=text.align_left, tooltip=ltf_tt)
            table.cell(tbl, 1, r, ltf_msg, bgcolor=ltf_bg, text_color=on_txt, text_size=txt_sz, text_halign=text.align_right)
            r += 1
        else if tier == 1 and show_htf
            table.cell(tbl, 0, r, label_base + " (" + htf_tf + ")", bgcolor=label_bg, text_color=label_txt, text_size=txt_sz, text_halign=text.align_left, tooltip=htf_tt)
            table.cell(tbl, 1, r, htf_msg, bgcolor=htf_bg, text_color=on_txt, text_size=txt_sz, text_halign=text.align_right)
            r += 1
        else if tier == 2 and show_mtf and show_mtf_field
            table.cell(tbl, 0, r, label_base + " (" + mtf_tf + ")", bgcolor=label_bg, text_color=label_txt, text_size=txt_sz, text_halign=text.align_left, tooltip=mtf_tt)
            table.cell(tbl, 1, r, mtf_msg, bgcolor=mtf_bg, text_color=on_txt, text_size=txt_sz, text_halign=text.align_right)
            r += 1
    r
 
// v6 (09/13/2026): Price Action Structure marker label — creates ONE label per call (no array/
// mitigation management needed, unlike Order Blocks' boxes, since these are meant to persist as a
// historical record on the chart, not be deleted). _isHigh picks the label's pointer direction
// (down-pointing/placed-above for a high pivot, up-pointing/placed-below for a low pivot);
// color=color(na) hides the shape's own fill/border so only the colored text shows, matching a plain
// text-marker look rather than a filled callout box.
export f_paLabel(int _barIdx, float _y, string _txt, color _col, bool _isHigh, string _size) =>
    label.new(_barIdx, _y, _txt, style = _isHigh ? label.style_label_down : label.style_label_up, color = color(na), textcolor = _col, size = _size)
 
// v9 (09/13/2026): CE10117 trim pass — single-row status-table helper, same idiom as f_add_tf_row
// just above but for the ~19 single-row fields (Market, Price, Opening range, VWAP, EMA 200, Fib Zone,
// last-flip/flip-level/pivot rows per tier, Chart, Confluence Score, etc.) that were each writing out
// the identical two table.cell()+increment shape inline in the main script. Pure params only (table
// ref, row index, label/tooltip/value text, the 4 style values that stay constant across a whole
// render pass) — no CBC state read, same proven-safe category as f_obAdd/f_htfObAdd/f_paLabel above.
// Returns the incremented row index so call sites keep the same "r := obLib.f_...' idiom already used
// for f_add_tf_row.
export f_add_status_row(table tbl, int row, string label, string tooltip, string val, color valBg, color labelBg, color labelTxt, color valTxt, string txtSz) =>
    table.cell(tbl, 0, row, label, bgcolor=labelBg, text_color=labelTxt, text_size=txtSz, text_halign=text.align_left, tooltip=tooltip)
    table.cell(tbl, 1, row, val, bgcolor=valBg, text_color=valTxt, text_size=txtSz, text_halign=text.align_right)
    row + 1
 
// v11 (09/14/2026): CE10117 trim pass — reference-level label create-or-update helper. Collapses the
// ~15 near-identical "if na(lbl) -> label.new(...) else -> label.set_x/set_y/set_text/set_textcolor"
// blocks scattered across YDH/YDL/PMH/PML/YDC/LN-H/LN-L/AS-H/AS-L/the Pivot Points loop/the 3 ORB
// session H/L pairs (each already funneling its display TEXT through obLib.f_level_label_text) into
// one call per site. Takes the existing label ref in (na on the first call, already-created after
// that) and returns the label to reassign back to that same var — same "pass state in, mutate/create,
// return it" shape already used by f_obUpdateSwing, just for a single label instead of a swing-state
// tuple. use_bar_time selects xloc.bar_time (the YDH/YDL/PMH/PML/YDC/LN/AS/Pivot group, all anchored to
// a session-start time) vs the default xloc.bar_index (the 3 ORB session pairs, anchored to a bar
// offset) — the one structural difference between the two label groups in the main script. Always
// re-applies textcolor on the update branch even for the ORB group (whose color never actually changes
// bar to bar) — a harmless same-value re-set, done anyway so one function covers every call site
// instead of needing a second variant.
export f_levelLabel(label lbl, int x, float y, string txt, color textcol, string sz, bool use_bar_time) =>
    label result = lbl
    if na(result)
        result := use_bar_time ? label.new(x, y, txt, xloc=xloc.bar_time, color=color.new(color.white, 100), textcolor=textcol, style=label.style_label_left, size=sz) : label.new(x, y, txt, color=color.new(color.white, 100), textcolor=textcol, style=label.style_label_left, size=sz)
    else
        label.set_x(result, x)
        label.set_y(result, y)
        label.set_text(result, txt)
        label.set_textcolor(result, textcol)
    result
 
// v12 (09/14/2026): Equal H&L connecting line — draws a plain dashed segment between the two matched
// pivots (x1/y1 = the earlier pivot, x2/y2 = the newer one) so it's visually clear WHICH prior swing a
// new EQH/EQL label is paired with, instead of just tagging the new pivot in isolation. One-shot,
// historical (no management/deletion), same category as f_paLabel — pure params, no CBC-state read.
export f_eqLine(int x1, float y1, int x2, float y2, color col) =>
    line.new(x1, y1, x2, y2, color=col, width=1, style=line.style_dashed)
 
// v13 (09/15/2026): ORB Retest marker helper — collapses the 6 near-identical box.new()+label.new()
// call sites (Pass/Flip/Fail-from, both directions) in the main script's ORB Retest marker-drawing
// block into one shared function. Each call site previously differed only in y (top/bottom offset),
// half (box half-height), border color, and tooltip text — all now plain parameters, same
// "pass state in, no CBC-internal state read" category as f_obAdd/f_paLabel/f_levelLabel above.
// bar_index is read directly (a Pine built-in, available from library scope the same way f_obAdd
// already reads it) rather than passed in, since it's always "this bar" at every call site.
export f_orbRetestMarker(float y, float half, color bcol, string tip) =>
    box.new(left=bar_index - 1, right=bar_index, top=y + half, bottom=y - half, border_color=bcol, border_width=2, bgcolor=color(na))
    label.new(x=bar_index, y=y, text="", tooltip=tip, color=color.new(color.black, 100), style=label.style_circle, size=size.tiny)
 
// v24 (09/19/2026): two new exports for the CBC main script's Pre-Trade Checklist items 3/4 (Stop/
// Target Structure Checklist) — f_checklist_scan() (12-type level proximity scan) and
// f_render_level_type_checklist() (its table renderer, called once per side). See each export's own
// comment further down for details.
//
// v23 (09/19/2026): new "Confluences Checklist" table export, f_render_confluence_checklist() — see
// its own comment right before the export below. Built directly in the library from the start (per
// this file's own convention #14 about first-time additions), not first added to the main script and
// moved later.
//
// v22 (09/19/2026): COMPILE FIX for a mistake in v21's own edit — the new f_render_confluence_cells()
// export got inserted in the middle of f_next_two_levels() (before its own final
// `[target_txt, stop_txt]` return line instead of after it), so f_next_two_levels() never returned
// and f_render_confluence_cells() ended with an orphaned, undeclared-identifier return line instead
// of its own `true`. Reported by the user as CE10272 "Undeclared identifier target_txt". Fixed by
// moving the `[target_txt, stop_txt]` line back to the end of f_next_two_levels()'s own body (right
// after `stop_txt := "—"`) and leaving f_render_confluence_cells() ending on its own `true`, exactly
// as each function had before this mistake. No other content changed from v21 — same 34-parameter
// f_render_confluence_cells() export.
//
// v21 (09/19/2026): moved f_render_confluence_cells()'s entire body here (see its own comment right
// before the export below) — a CE10117 token-budget trim requested directly by the user ("move stuff
// to library - reduce tokens") after v7.20 still reported 101582/100256.
//
// v20 (09/19/2026): "Next two levels" scan for the CBC main script's Next Target Levels / Next Stop
// Levels Status-table rows (Pre-Trade Checklist items 3/4). Given a pool of levels (price_arr) with
// matching labels (label_arr), the live trade-direction bool (dir_long: true favors levels above
// price, false favors levels below), and the current close (px), returns [target text, stop text] —
// each up to 2 "Label price (±N.N pts)" segments joined by " | ", nearest-first, or "—" if nothing
// qualifies (e.g. every level is na). Targets are the nearest 2 levels on the side dir_long favors;
// stops are the nearest 2 on the opposite side. Mirrors the sort_indices "closest N" pattern already
// used elsewhere in this file's Pivot Points logic. Fully parameterized, no CBC-internal state read —
// generalized to any pool size via array.size(price_arr) rather than a hardcoded count.
export f_next_two_levels(float[] price_arr, string[] label_arr, bool dir_long, float px) =>
    int n = array.size(price_arr)
    var float[] above_dist = array.new_float(n, na)
    var float[] below_dist = array.new_float(n, na)
    for i = 0 to n - 1
        float lvl = array.get(price_arr, i)
        array.set(above_dist, i, (na(lvl) or lvl <= px) ? 1e10 : lvl - px)
        array.set(below_dist, i, (na(lvl) or lvl >= px) ? 1e10 : px - lvl)
    array<int> above_order = array.sort_indices(above_dist, order.ascending)
    array<int> below_order = array.sort_indices(below_dist, order.ascending)
    array<int> target_order = dir_long ? above_order : below_order
    array<int> stop_order = dir_long ? below_order : above_order
    array<float> target_dist = dir_long ? above_dist : below_dist
    array<float> stop_dist = dir_long ? below_dist : above_dist
    // v7.28: distances now carry a sign relative to the live CBC direction, same convention as the
    // Status table's VWAP/EMA200 rows and the Structure Checklist tables -- target segments (the
    // favorable side, always) show "+N.N", stop segments (the opposite side) show "-N.N". Per direct
    // request ("all the points are positive they should be in relation to the direction of cbc").
    string target_txt = ""
    int target_found = 0
    for i = 0 to n - 1
        if target_found < 2
            int ti = array.get(target_order, i)
            float td = array.get(target_dist, ti)
            if td < 1e9
                target_txt := target_txt + (target_found > 0 ? "  |  " : "") + array.get(label_arr, ti) + " " + str.tostring(array.get(price_arr, ti), "#.##") + " (+" + str.tostring(td, "#.#") + " pts)"
                target_found += 1
    if target_found == 0
        target_txt := "—"
    string stop_txt = ""
    int stop_found = 0
    for i = 0 to n - 1
        if stop_found < 2
            int si = array.get(stop_order, i)
            float sd = array.get(stop_dist, si)
            if sd < 1e9
                stop_txt := stop_txt + (stop_found > 0 ? "  |  " : "") + array.get(label_arr, si) + " " + str.tostring(array.get(price_arr, si), "#.##") + " (-" + str.tostring(sd, "#.#") + " pts)"
                stop_found += 1
    if stop_found == 0
        stop_txt := "—"
    [target_txt, stop_txt]
 
// v21 (09/19/2026): the entire Confluence Factors cells table (`f_render_confluence_cells()` in the
// CBC main script) moved here as one export — table lifecycle (create/delete/recreate on
// position/row-count change), the 3 per-cell array.from() builds (text/color/tooltip, 10 factors),
// and the draw loop. Fully parameterized — 10 factor bools + 8 "touch" bools (2 of the 10 factors,
// HTF and Cloud, have no separate touch/amber state so only 8 touch params exist), the 4 status
// colors + text color, htf_timeframe/timeframe multiplier for the HTF cell's label, the live
// confluence score/max/threshold, the same-score-different-mix highlight flag, and the 3 display
// settings (use table at all, position string, row count) plus text size. No CBC-internal state read
// beyond what's passed in — same "pass state in as parameters" category as f_next_two_levels above.
// `var table`/`var string`/`var int` locals persist per-call-site across bars exactly as they did when
// this same code lived in the main script — moving a function to a library changes nothing about
// Pine's var/table persistence semantics, only which compiled-token budget the body counts against.
export f_render_confluence_cells(bool use_table, string position, int rows, string text_size,
     color border_col, color frame_col, color bull_col, color neutral_col, color amber_col, color highlight_col, color text_col,
     bool f_htf, bool f_cloud, bool f_zone, bool f_sweep, bool f_volume, bool f_fib, bool f_structure, bool f_level, bool f_flip, bool f_htf_flip,
     bool f_zone_touch, bool f_sweep_touch, bool f_volume_touch, bool f_fib_touch, bool f_structure_touch, bool f_level_touch, bool f_flip_touch, bool f_htf_flip_touch,
     string htf_tf, int ltf_mult, int score, int max_score, int alert_threshold, bool same_score_diff_mask) =>
    var table conf_tbl = na
    var string conf_pos_last = ""
    var int conf_rows_last = 0
    if not use_table
        table.delete(conf_tbl)
        conf_tbl := na
        conf_pos_last := ""
        conf_rows_last := 0
    else
        int conf_rows = math.min(11, math.max(1, rows))
        int conf_cols = int(math.ceil(11.0 / conf_rows))
        if not na(conf_tbl) and (conf_pos_last != position or conf_rows_last != conf_rows)
            table.delete(conf_tbl)
            conf_tbl := na
        if na(conf_tbl)
            conf_tbl := table.new(f_status_pos(position), conf_cols, conf_rows, bgcolor=color.new(#020617, 0), border_color=border_col, border_width=1, frame_color=frame_col, frame_width=2)
            conf_pos_last := position
            conf_rows_last := conf_rows
        array<string> conf_texts = array.from("[" + (f_htf ? "✓" : "✗") + "H" + htf_tf, (f_cloud ? "✓" : "✗") + "Cld", (f_zone ? "✓" : "✗") + "Zn", (f_sweep ? "✓" : "✗") + "Swp" + "]", (f_volume ? "✓" : "✗") + "Vol", (f_fib ? "✓" : "✗") + "Fib", (f_structure ? "✓" : "✗") + "Str", (f_level ? "✓" : "✗") + "Lvl", (f_flip ? "✓" : "✗") + "Flp" + str.tostring(ltf_mult), (f_htf_flip ? "✓" : "✗") + "HFV")
        array<color> conf_colors = array.from(f_htf ? bull_col : neutral_col, f_cloud ? bull_col : neutral_col, f_zone ? bull_col : (f_zone_touch ? amber_col : neutral_col), f_sweep ? bull_col : (f_sweep_touch ? amber_col : neutral_col), f_volume ? bull_col : (f_volume_touch ? amber_col : neutral_col), f_fib ? bull_col : (f_fib_touch ? amber_col : neutral_col), f_structure ? bull_col : (f_structure_touch ? amber_col : neutral_col), f_level ? bull_col : (f_level_touch ? amber_col : neutral_col), f_flip ? bull_col : (f_flip_touch ? amber_col : neutral_col), f_htf_flip ? bull_col : (f_htf_flip_touch ? amber_col : neutral_col))
        array<string> conf_tips = array.from("HTF — the HTF CBC direction agrees with the current LTF direction. Weight: 4.", "Cloud (LTF EMA) — the LTF EMA9/20 cloud agrees with the current direction. Weight: 1.", "Zone — BRSG zone or HTF Flip FVG touch. Amber = touched, but outside the recency window. Weight: 2.", "Sweep — liquidity sweep of the last confirmed HTF swing. Amber = touched, but outside the recency window. Weight: 1.", "Volume Spike on the HTF flip candle. Amber = touched, but its toggle is off. Weight: 1.", "Fib Golden Pocket (50%-61.8%) touch. Amber = touched, but outside the recency window or its toggle is off. Weight: 1.", "HTF Structure Break (BOS/CHoCH). Amber = touched, but its toggle is off. Weight: 1.", "Level — price is currently near a key level. Amber = touched, but its toggle is off (off by default). Weight: 1.", "Flip (LTF) — valid from the LTF's own flip until the next reverse flip. Amber = touched, but its toggle is off (off by default). Weight: 1.", "HTF Flip FVG — true while the current flip's Fair Value Gap remains unfilled; invalidated the instant price trades back into it. Amber = true, but its toggle is off (off by default). Weight: 1.")
        for i = 0 to 10
            table.cell(conf_tbl, i % conf_cols, i / conf_cols, i == 0 ? "S:" + str.tostring(score) + "/" + str.tostring(max_score) : array.get(conf_texts, i - 1), bgcolor=i == 0 ? same_score_diff_mask ? highlight_col : (score >= alert_threshold ? bull_col : neutral_col) : array.get(conf_colors, i - 1), text_color=text_col, text_size=f_table_text_size(text_size), text_halign=text.align_center, tooltip=i == 0 ? "Live Confluence Score — counted factors / max possible (the denominator shrinks if a toggleable factor is switched off above)." : array.get(conf_tips, i - 1))
    true
 
// v23 (09/19/2026): "Confluences Checklist" table for the CBC main script — a second, separate
// confluence display laid out to mirror the user's own Pre-Trade Checklist item 2 ("Confluences")
// exactly: one checkbox square + label per factor, 2 columns x 4 rows (CBC LTF/EMA Cloud LTF/VWAP/
// Structure HTF on the left, CBC HTF/EMA Cloud HTF/EMA20 on the right — the last cell, row 4 col 2,
// is left blank since there are only 7 items). Built as a library export from the start, same "pass
// state in as parameters, no CBC-internal state read" category as f_render_confluence_cells() above.
// 5 of the 7 items reuse existing confluence-factor booleans passed straight through (flip_ltf =
// CBC LTF, cbc_htf = CBC HTF, cloud_ltf = EMA Cloud LTF, cloud_htf = EMA Cloud HTF, structure_htf =
// Structure HTF); VWAP and EMA20 are brand-new checks, computed HERE from raw price/vwap/ema20
// values rather than in the main script, to keep the main-script call site's own token cost to a
// handful of parameter names rather than two extra top-level boolean declarations. "In the direction
// of the trade" means price is on the favorable side of that level for the live LTF CBC direction
// (dir_long): above VWAP/EMA20 when long, below when short. Each item is drawn as 2 cells — a
// checkbox cell (colored bull/neutral, holding a checkmark or nothing) and a plain label cell (fixed
// dark background, no color coding) — 4 columns x 4 rows total. `var table` persists per call site
// across bars exactly as it would in the main script; `var string cl_pos_last` handles delete+rebuild
// on a position change, same pattern as f_render_confluence_cells()'s conf_pos_last above (this
// table's own row/column COUNT never changes, so unlike that one there's no rows-changed branch
// needed here).
// v7.28 (this session's own count, actual published number to be confirmed): unchecked checkbox
// cells now show "✗" instead of a blank string, matching the ✓/✗ convention the compact Confluence
// Factors cells table already uses -- per direct request ("checkbox to left should show"), a blank
// cell gave no visual indication a checkbox was even there when unchecked.
// v7.30: cell colors now reflect each factor's own ACTUAL bull/bear reading (green when that specific
// signal is bullish, red when bearish) instead of a plain agree=green/disagree=gray scheme -- per
// direct request ("if cbc ltf is red bearish in status just make cbc ltf red in the confluence
// table"), matching the Status table's own red-for-bearish/green-for-bullish coloring on the matching
// rows. New params: `bear_col` (the missing 3rd status color -- this function only ever had bull/
// neutral before), `cbc_htf_bull` (the HTF CBC's own raw direction, separate from `cbc_htf`'s
// "agrees with LTF" meaning), `cloud_ltf_bull`/`cloud_htf_bull` (the LTF/HTF EMA cloud's own raw
// direction, separate from `cloud_ltf`/`cloud_htf`'s "agrees" meaning). CBC LTF reuses `dir_long`
// directly for its own color (dir_long IS the live LTF CBC direction). VWAP/EMA20 needed no new
// param -- `vwap_ok`/`ema20_ok` were already direction-relative ("favorable"/"against", same v7.28
// convention as the Status table's own VWAP/EMA200 rows), so their color simply swaps neutral_col for
// bear_col. The ✓/✗ checkmark and its underlying agree/disagree logic are UNCHANGED for every item --
// only the checkbox cell's background color changed; a cell can now show a green background with a
// ✗ (this factor is bullish, but doesn't happen to be the live trade direction) or a red background
// with a ✓ (this factor is bearish AND the live trade direction is short, so it's checked). Structure
// HTF is deliberately left on the old agree=bull_col/disagree=neutral_col scheme -- no clean
// independent "structure is bullish/bearish" boolean was available to pass in without a larger,
// separately-scoped change (see the open item this round's changelog adds).
export f_render_confluence_checklist(bool use_table, string position, string text_size,
     color border_col, color frame_col, color bull_col, color bear_col, color neutral_col, color text_col,
     bool flip_ltf, bool cbc_htf, bool cbc_htf_bull, bool cloud_ltf, bool cloud_ltf_bull, bool cloud_htf, bool cloud_htf_bull, bool structure_htf,
     bool dir_long, float px, float vwap_val, float ema20_val) =>
    var table cl_tbl = na
    var string cl_pos_last = ""
    if not use_table
        table.delete(cl_tbl)
        cl_tbl := na
        cl_pos_last := ""
    else
        if not na(cl_tbl) and cl_pos_last != position
            table.delete(cl_tbl)
            cl_tbl := na
        if na(cl_tbl)
            cl_tbl := table.new(f_status_pos(position), 4, 4, bgcolor=color.new(#020617, 0), border_color=border_col, border_width=1, frame_color=frame_col, frame_width=2)
            cl_pos_last := position
        bool vwap_ok = not na(vwap_val) and (dir_long ? px > vwap_val : px < vwap_val)
        bool ema20_ok = not na(ema20_val) and (dir_long ? px > ema20_val : px < ema20_val)
        string txt_sz = f_table_text_size(text_size)
        color lbl_bg = color.new(#020617, 0)
        table.cell(cl_tbl, 0, 0, flip_ltf ? "✓" : "✗", bgcolor=dir_long ? bull_col : bear_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
        table.cell(cl_tbl, 1, 0, "CBC LTF", bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
        table.cell(cl_tbl, 2, 0, cbc_htf ? "✓" : "✗", bgcolor=cbc_htf_bull ? bull_col : bear_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
        table.cell(cl_tbl, 3, 0, "CBC HTF", bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
        table.cell(cl_tbl, 0, 1, cloud_ltf ? "✓" : "✗", bgcolor=cloud_ltf_bull ? bull_col : bear_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
        table.cell(cl_tbl, 1, 1, "EMA Cloud LTF", bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
        table.cell(cl_tbl, 2, 1, cloud_htf ? "✓" : "✗", bgcolor=cloud_htf_bull ? bull_col : bear_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
        table.cell(cl_tbl, 3, 1, "EMA Cloud HTF", bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
        table.cell(cl_tbl, 0, 2, vwap_ok ? "✓" : "✗", bgcolor=vwap_ok ? bull_col : bear_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
        table.cell(cl_tbl, 1, 2, "VWAP", bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
        table.cell(cl_tbl, 2, 2, ema20_ok ? "✓" : "✗", bgcolor=ema20_ok ? bull_col : bear_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
        table.cell(cl_tbl, 3, 2, "EMA20", bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
        table.cell(cl_tbl, 0, 3, structure_htf ? "✓" : "✗", bgcolor=structure_htf ? bull_col : neutral_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
        table.cell(cl_tbl, 1, 3, "Structure HTF", bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
    true
 
// v24 (09/19/2026): Stop/Target Structure Checklist scan for the CBC main script's Pre-Trade
// Checklist items 3/4 ("Stop/Target is at a real structural level — which type?"). Given a pool of
// scalar levels (price_pool) each tagged with a type id 0-10 (type_pool — see the main script's own
// comment on chk_type_pool for exactly which type each id is), the current price (px), which side to
// look on (want_above: true = levels at/above px, false = at/below), a tolerance (tol), and the two
// HTF order block box arrays, returns an array<bool> of size n_types+1 — index i (0..n_types-1) true
// if ANY pool entry of type i is within tol of px on the requested side; the last index (n_types) is
// the Order Block result, computed separately since boxes aren't scalar prices. For Order Block: bear
// boxes are checked on the "want_above" side (bear OB = resistance, sits above price) and bull boxes
// on the "not want_above" side (bull OB = support, sits below) — a box counts as "near" if px is
// within tol of its top or bottom edge, or already inside it. Pure parameters in, no CBC-internal
// state read, same "pass state in" category as f_next_two_levels/f_render_confluence_cells above.
// v27 (09/20/2026): REWORKED -- v26 originally tried to return a 2nd array (`dist`, alongside the
// existing bool `result`) as a tuple, `[result, dist]`. **Pine does not allow exported library
// functions to return tuples** -- the main script hit CE10172 ("Cannot assign a variable to a
// tuple... the right side must be a function call... returning a tuple") the moment it tried to
// destructure the call, because the compiler treats an exported function as single-return only, even
// though its own body ends in a bracketed multi-value expression. **New standing lesson: never design
// an exported library function around a tuple return -- pick ONE return value (an array, if multiple
// numbers are needed) and derive anything else from it at the call site instead.**
// Fix: this function now returns ONLY `array<float> dist` (size n_types+1) -- the nearest distance in
// points to a level of that type on the requested side (or Order Block's nearest edge distance),
// `na` if no level of that type exists on that side. The `tol` parameter and the bool result are both
// GONE from this function -- whether a given distance counts as "at that level" is now a render-time
// decision (`d <= tol`) made in f_render_level_type_checklist() below, which already receives `tol`
// anyway. This also means the checkbox and the points readout can never disagree with each other --
// they're now computed from the exact same `dist` value at render time instead of two separately
// tracked results from the scan.
export f_checklist_scan(float[] price_pool, int[] type_pool, int n_types, float px, bool want_above, box[] bull_ob, box[] bear_ob) =>
    array<float> dist = array.new_float(n_types + 1, na)
    for i = 0 to array.size(price_pool) - 1
        float lvl = array.get(price_pool, i)
        if not na(lvl)
            bool on_side = want_above ? lvl >= px : lvl <= px
            if on_side
                float d = math.abs(lvl - px)
                int t = array.get(type_pool, i)
                float cur_d = array.get(dist, t)
                if na(cur_d) or d < cur_d
                    array.set(dist, t, d)
    box[] obs = want_above ? bear_ob : bull_ob
    float ob_dist = na
    // v31 (RE10045 fix): "for i = 0 to array.size(obs) - 1" blows up at runtime on any bar where obs
    // is still empty (no order block box formed yet, e.g. early chart history) -- array.size(obs) - 1
    // is -1, and Pine's for loop does NOT just skip when to < from: it infers a DESCENDING loop
    // instead and still executes once with i=0, which then hits array.get(obs, 0) on a 0-length
    // array ("Index 0 is out of bounds, array size is 0"). Guarding the loop behind an explicit
    // array.size(obs) > 0 check avoids the descending-loop inference entirely on the empty-array bar.
    if array.size(obs) > 0
        for i = 0 to array.size(obs) - 1
            box b = array.get(obs, i)
            if not na(b)
                float top = box.get_top(b)
                float bot = box.get_bottom(b)
                float d = px >= bot and px <= top ? 0.0 : (px < bot ? bot - px : px - top)
                if na(ob_dist) or d < ob_dist
                    ob_dist := d
    array.set(dist, n_types, ob_dist)
    dist
 
// v24 (09/19/2026): renders one Stop/Target Structure Checklist table — 12 checkbox+label rows (2
// columns x 6 rows) for the CBC main script, called once per side (stop/target) with a different
// `states` array from f_checklist_scan() above. Labels are fixed (the same 12 types every call), so
// they're built once as a local `var` array rather than passed in as a parameter — this function is
// purpose-built for this one feature, not a generic table renderer. Same var-table position-change
// recreate pattern as f_render_confluence_checklist() above; each of this function's 2 call sites in
// the main script gets its own independent `var table` instance (a library function's persistent
// locals are scoped per lexical call site, same as any other Pine function — this is why the two
// tables don't collide with each other despite sharing one function body).
// v27 (09/20/2026): now takes `dist` (the reworked f_checklist_scan()'s single array<float> return,
// see that function's own v27 note above) plus `tol` directly, instead of a separately-scanned bool
// `states` array -- the checkbox state is now derived right here, at render time, as `not na(d) and d
// <= tol`, so the checkmark and the points readout can never disagree (they come from the same `d`).
// Label cell appends the nearest distance in points -- e.g. "Prior Day H/L  2.3pts" -- when a level of
// that type exists on the requested side at all; a type with no such level (`dist` is `na`) shows just
// its plain label, no points suffix, and its checkbox is naturally unchecked too (na(d) short-circuits
// the state check).
// v7.28: new `favorable` param -- true for the Target table call (this pool is already the favorable
// side, per f_checklist_scan()'s want_above=cbc), false for the Stop table call (the opposite side).
// The points suffix is now signed to match: "+N.Npts" on the Target table, "-N.Npts" on the Stop
// table -- same "positive = favorable, negative = against" convention used everywhere else this round
// (Status table VWAP/EMA200 rows, Next Target/Stop Levels). Per direct request ("all the points are
// positive they should be in relation to the direction of cbc").
// Also: unchecked checkbox cells now show "✗" instead of a blank string, same fix/reasoning as
// f_render_confluence_checklist() above ("checkbox to left should show").
export f_render_level_type_checklist(bool use_table, string position, string text_size, color border_col, color frame_col, color bull_col, color neutral_col, color text_col, float[] dist, float tol, bool favorable) =>
    var table lt_tbl = na
    var string lt_pos_last = ""
    var string[] lt_labels = array.from("Prior Day H/L", "Premarket", "NY ORB", "London ORB", "Asia ORB", "NY Session", "Asia Session", "London Session", "Pivot Point", "Swing H/L", "Equal H/L", "Order Block")
    if not use_table
        table.delete(lt_tbl)
        lt_tbl := na
        lt_pos_last := ""
    else
        if not na(lt_tbl) and lt_pos_last != position
            table.delete(lt_tbl)
            lt_tbl := na
        if na(lt_tbl)
            lt_tbl := table.new(f_status_pos(position), 4, 6, bgcolor=color.new(#020617, 0), border_color=border_col, border_width=1, frame_color=frame_col, frame_width=2)
            lt_pos_last := position
        string txt_sz = f_table_text_size(text_size)
        color lbl_bg = color.new(#020617, 0)
        for i = 0 to 11
            int col = (i % 2) * 2
            int row = i / 2
            float d = array.get(dist, i)
            string lbl_txt = array.get(lt_labels, i) + (na(d) ? "" : "  " + (favorable ? "+" : "-") + str.tostring(d, "#.#") + "pts")
            bool st = not na(d) and d <= tol
            table.cell(lt_tbl, col, row, st ? "✓" : "✗", bgcolor=st ? bull_col : neutral_col, text_color=text_col, text_size=txt_sz, text_halign=text.align_center)
            table.cell(lt_tbl, col + 1, row, lbl_txt, bgcolor=lbl_bg, text_color=text_col, text_size=txt_sz, text_halign=text.align_left)
    true
 
// v25 (09/20/2026): f_render_fib_zone_box() moved to the library — the last of the "next candidate"
// functions flagged back at v21. Its only main-script-only dependency was f_ref_line_style(), which
// takes the main-script-only RefLineStyle enum and returns a plain line.style_* string. Rather than
// exporting the enum type across the library boundary, the main script now precomputes that string
// ONCE (f_ref_line_style(fib_01_line_style)) and passes it in as `fib_01_style` — the enum itself
// never has to cross the import boundary, and the two line.new() calls that used to call
// f_ref_line_style() directly now just reuse the passed-in string. Otherwise a straight body-move,
// same pattern as f_render_confluence_cells()/f_render_confluence_checklist() above: all `var`
// box/line/label state stays inside the function so it's still per-call-site (this function only has
// one call site, so that doesn't matter here, but keeping the pattern consistent).
export f_render_fib_zone_box(bool fib_valid, bool show_fib_zone_box, int fib_zone_box_bars, float fib_zone_top, float fib_zone_bot, bool fib_price_in_zone, string htf_tf_disp_val, float fib_50, float fib_618, color st_bull, color st_neutral, color txt_on, string status_table_text_size, bool show_fib_01_lines, float fib_0, float fib_100, color col_fib_01_lines, string fib_01_style, color txt_fib_01_lines) =>
    var box fib_zone_bx = na
    var line fib_0_ln = na
    var line fib_100_ln = na
    var label fib_0_lbl = na
    var label fib_100_lbl = na
    if not fib_valid
        box.delete(fib_zone_bx)
        fib_zone_bx := na
        line.delete(fib_0_ln)
        fib_0_ln := na
        line.delete(fib_100_ln)
        fib_100_ln := na
        label.delete(fib_0_lbl)
        fib_0_lbl := na
        label.delete(fib_100_lbl)
        fib_100_lbl := na
    else
        int fib_box_left = math.max(0, bar_index - fib_zone_box_bars)
        if not show_fib_zone_box
            box.delete(fib_zone_bx)
            fib_zone_bx := na
        else
            string fib_box_txt_sz = f_table_text_size(status_table_text_size)
            color fib_box_bg = fib_price_in_zone ? color.new(st_bull, 55) : color.new(st_neutral, 55)
            color fib_box_bd = fib_price_in_zone ? st_bull : st_neutral
            string fib_box_txt = "Fib " + htf_tf_disp_val + "  " + str.tostring(fib_50, "#.#") + " / " + str.tostring(fib_618, "#.#") + (fib_price_in_zone ? "  IN" : "")
            if na(fib_zone_bx)
                fib_zone_bx := box.new(left=fib_box_left, top=fib_zone_top, right=bar_index, bottom=fib_zone_bot, border_color=fib_box_bd, border_width=2, bgcolor=fib_box_bg, extend=extend.none, text=fib_box_txt, text_color=txt_on, text_size=fib_box_txt_sz, text_halign=text.align_center, text_valign=text.align_center)
            else
                box.set_left(fib_zone_bx, fib_box_left)
                box.set_right(fib_zone_bx, bar_index)
                box.set_top(fib_zone_bx, fib_zone_top)
                box.set_bottom(fib_zone_bx, fib_zone_bot)
                box.set_bgcolor(fib_zone_bx, fib_box_bg)
                box.set_border_color(fib_zone_bx, fib_box_bd)
                box.set_text(fib_zone_bx, fib_box_txt)
                box.set_text_color(fib_zone_bx, txt_on)
                box.set_text_size(fib_zone_bx, fib_box_txt_sz)
        if not show_fib_01_lines
            line.delete(fib_0_ln)
            fib_0_ln := na
            line.delete(fib_100_ln)
            fib_100_ln := na
            label.delete(fib_0_lbl)
            fib_0_lbl := na
            label.delete(fib_100_lbl)
            fib_100_lbl := na
        else
            if na(fib_0_ln)
                fib_0_ln := line.new(fib_box_left, fib_0, bar_index, fib_0, color=col_fib_01_lines, width=1, style=fib_01_style, extend=extend.none)
                fib_0_lbl := label.new(bar_index, fib_0, "FIB 0", color=color.new(color.white, 100), textcolor=txt_fib_01_lines, style=label.style_label_left, size=size.normal)
            else
                line.set_xy1(fib_0_ln, fib_box_left, fib_0)
                line.set_xy2(fib_0_ln, bar_index, fib_0)
                label.set_xy(fib_0_lbl, bar_index, fib_0)
            if na(fib_100_ln)
                fib_100_ln := line.new(fib_box_left, fib_100, bar_index, fib_100, color=col_fib_01_lines, width=1, style=fib_01_style, extend=extend.none)
                fib_100_lbl := label.new(bar_index, fib_100, "FIB 1", color=color.new(color.white, 100), textcolor=txt_fib_01_lines, style=label.style_label_left, size=size.normal)
            else
                line.set_xy1(fib_100_ln, fib_box_left, fib_100)
                line.set_xy2(fib_100_ln, bar_index, fib_100)
                label.set_xy(fib_100_lbl, bar_index, fib_100)
    true
 
// v7.35 (main script): f_render_pivot_table()'s entire body moved here from the main script for
// CE10117 relief -- it was the largest remaining un-offloaded render function (every other major
// table-render function in this file -- confluence cells, confluence checklist, structure
// checklists, fib zone box -- was already moved in earlier rounds; this one grew significantly at
// v7.33/v7.34, first with the closest-8/PRICE-row/direction-ordering rework then with the 4-
// above/4-below selection split and the new signed-distance middle row). Same proven-safe "pass
// state in as parameters, no CBC-internal state read" category as every prior render-function
// offload -- the persistent `var table piv_tbl` moves into this function along with the body,
// same as f_render_confluence_cells/f_render_fib_zone_box before it. `px`/`htf_bull`/`ltf_bull`
// are the plain values the main script's `close`/`cf_f2_htf_bull`/`cbc` resolve to at the call
// site -- see convention #20 in the project handoff doc for why direction needs BOTH htf_bull
// (column ordering) and ltf_bull (the new row's signed distance) rather than just one.
// v7.37: pool expanded from 9 to 17 slots per direct request ("as orb H ln orb h as orb l ny orb
// l pp pml etc"), made against a screenshot circling the chart's own Reference Levels column
// (PMH/PML, the 3 session Opening Range highs/lows, PP, YDL, etc.). Clarified via AskUserQuestion:
// add these as MORE always-shown candidates (table can grow past 9 columns), not a distance-based
// closest-N pick. New slots 9-16: PMH/PML (premarket high/low) and the 3 sessions' Opening Range
// H/L (NY/London/Asia) -- same values already tracked elsewhere in this file (Reference Levels,
// f_next_two_levels()'s pool), no new computation. Each new slot gets its own dedicated
// table-scoped enable toggle (show_pivot_pmh/pml/ny_orh/ny_orl/ln_orh/ln_orl/as_orh/as_orl),
// deliberately separate from the shared line-visibility toggles (show_pmh/show_ln_orb_hl/etc) --
// same "keep this table's own local pool independently toggleable" reasoning already used for
// YD-H/YD-L at v7.32. PP is no longer guaranteed to be the table's exact middle column once the
// pool grows past the original fixed 3-above/3-below classic-pivot shape (a session ORB level can
// sort anywhere relative to PP) -- this is the accepted, explicitly chosen tradeoff from the
// AskUserQuestion answer ("add them, keep showing everything enabled").
// v7.39: pool expanded from 17 to 21 slots per direct request ("include bsrg if within 4 bars htf
// and htf pivots as seen in image"), made against a screenshot of the BRSG Zone (High/Low
// multiplier) and HTF swing-pivot line settings. New slots 17-20: BRSG-H/BRSG-L (the BRSG zone's
// own high/low price edges, brsg_zone_top/brsg_zone_bot -- same values the on-chart BRSG zone
// shading already uses) and HTF Piv-H/HTF Piv-L (the HTF swing pivot high/low, h_last_hi/h_last_lo
// -- same values the Status table's "Pivot (HTF)" row and f_next_two_levels()'s pool already use).
// BRSG-H/BRSG-L are gated by a single combined enable flag (brsg_show) rather than two separate
// toggles -- the pair is one zone, not two independently meaningful levels, and reads as such on
// the chart's own BRSG Zone setting. Per the literal request ("if within 4 bars htf"), that flag
// is computed in the main script as the existing table-scoped master toggle AND
// htf_bars_since_flip <= 4 -- the exact same recency window this file already uses for the HTF
// Flip confluence factor (v7.31, confluence_use_htf_flip/cf_f9_htf_flip_touch), reused here rather
// than inventing a new threshold. HTF Piv-H/HTF Piv-L get their own separate toggles
// (show_pivot_htf_piv_hi/lo) with no recency condition, matching how every other pool addition in
// this table works (R1-R3/S1-S3/PP/YD-H/YD-L/PMH/PML/session-ORB) -- the request named them
// alongside BRSG but didn't ask for the same 4-bar gating, so they're always-on-when-toggled like
// everything else in the pool.
// v7.40: pool expanded from 21 to 23 slots per direct request ("can the pine script idenify equal
// highs and lows from htf to include i table of pivots"). New slots 21-22: HTF EQH/HTF EQL -- the
// most recent HTF Equal High/Low match price (htf_eqh/htf_eql, computed in the main script from the
// same HTF pivot stream htf_piv_hi/htf_piv_lo above already come from, using the ATR-scaled
// tolerance mechanism the LTF Equal Highs/Lows feature already uses, per the AskUserQuestion answer
// choosing "Same ATR-scaled tolerance as the existing EQH/EQL feature"). Each gets its own dedicated
// toggle (show_pivot_htf_eqh/show_pivot_htf_eql), matching how every other pool addition in this
// table works -- no shared/combined flag, since unlike BRSG-H/BRSG-L these are two independently
// meaningful levels, not one zone's two edges.
// v7.41: pool expanded from 23 to 27 slots per direct follow-up ("show all pivots in table... also
// include LTF pivots and ema200 and vwap"), scoped via AskUserQuestion. New slots 23-26: LTF Piv-H/
// LTF Piv-L (ltf_piv_hi/ltf_piv_lo -- the same LTF swing pivot values the Structure HH/HL/LH/LL
// classifier and the Status table's "Pivot (LTF)" row already use), EMA 200 (ema200_val), and VWAP
// (vwap_val) -- no new computation, same reuse pattern as every prior pool addition. Each gets its
// own dedicated toggle, default true. Also: R2/R3/S2/S3 (pool indices 1/0/5/6) now additionally OR
// in 4 new table-only toggles (show_tbl_r2/r3/s2/s3, default true) alongside their existing
// chart-line toggle and the v7.38 price-based auto-escalation -- any of the three now being true
// shows that level in the table, so "show all pivots" no longer depends on price having moved past
// R1/S1/R2/S2 first. Also: PRICE's own label is now "Price-L"/"Price-S" (was the fixed "PRICE")
// depending on the live LTF CBC direction (ltf_bull), and its own price-row cell (the bottom of the
// 3 rows) now colors st_bull/st_bear by that same direction instead of the shared gold highlight --
// the label/diff rows for that column keep the gold highlight unchanged, only the price-value cell
// changed, per the direct request ("color the price in row 3 under price green if long and red if
// short").
// v7.42: no signature change -- pure render-logic tweak inside the function body (PRICE column's
// row 1 text now "Long"/"Short" instead of "+0.00", both row 1 and row 2 use their own distinct
// vivid green/red instead of the shared st_bull/st_bear). See the render loop's own comment below.
export f_render_pivot_table(bool show_pivot_table, float[] piv_price_arr, string[] piv_labels, bool[] piv_enabled, float ydh, float ydl, bool show_pivot_ydh, bool show_pivot_ydl, float pmh, float pml, bool show_pivot_pmh, bool show_pivot_pml, float ny_orh, float ny_orl, bool show_pivot_ny_orh, bool show_pivot_ny_orl, float ln_orh, float ln_orl, bool show_pivot_ln_orh, bool show_pivot_ln_orl, float as_orh, float as_orl, bool show_pivot_as_orh, bool show_pivot_as_orl, float brsg_top, float brsg_bot, bool brsg_show, float htf_piv_hi, float htf_piv_lo, bool show_pivot_htf_piv_hi, bool show_pivot_htf_piv_lo, float htf_eqh, float htf_eql, bool show_pivot_htf_eqh, bool show_pivot_htf_eql, bool show_tbl_r2, bool show_tbl_r3, bool show_tbl_s2, bool show_tbl_s3, float ltf_piv_hi, float ltf_piv_lo, bool show_pivot_ltf_piv_hi, bool show_pivot_ltf_piv_lo, float ema200_val, float vwap_val, bool show_pivot_ema200, bool show_pivot_vwap, float px, bool htf_bull, int htf_last_flip_t_open, int htf_last_flip_t_close, color col_piv_pp, color col_piv_r, color col_piv_s, color st_highlight, color st_bull, color st_bear, string position, color border_col, color frame_col, string text_size, color txt_on) =>
    var table piv_tbl = na
    if show_pivot_table
        var float[] pivT_price_arr = array.new_float(27, na)
        var string[] pivT_labels = array.new_string(27, "")
        var bool[] pivT_enabled = array.new_bool(27, false)
        var color[] pivT_lblcol = array.new<color>(27, na)
        for pj = 0 to 6
            array.set(pivT_price_arr, pj, array.get(piv_price_arr, pj))
            array.set(pivT_labels, pj, array.get(piv_labels, pj))
            array.set(pivT_enabled, pj, array.get(piv_enabled, pj))
            array.set(pivT_lblcol, pj, pj == 3 ? col_piv_pp : pj < 3 ? col_piv_r : col_piv_s)
        // v7.38: auto-escalation for R2/R3/S2/S3, per direct request ("automatically display i.e.
        // price > r1 and r2 check is off and price is less than r2 to automatically include r2 in
        // the table as a pivot"). R2/R3/S2/S3 can stay toggled off on the chart (their own show_r2/
        // r3/s2/s3 inputs are untouched -- this only affects what the TABLE includes) but the table
        // now pulls each one in automatically once price actually needs it as the next reference
        // level: R2 once price has moved beyond R1, R3 once price has moved beyond R2, S2 once
        // price has moved below S1, S3 once price has moved below S2. This reads each level's own
        // PRICE VALUE directly from piv_price_arr (not its enabled/toggle state), so the escalation
        // still works even when R1/S1 themselves are toggled off -- the underlying pivot values are
        // always computed regardless of display toggle, only their visibility changes. R1/S1/PP are
        // untouched (indices 2/4/3) -- they keep their existing toggle-only inclusion, since they
        // never needed this treatment (R1/S1 are always the immediately-relevant first level).
        float piv_r1_val = array.get(piv_price_arr, 2)
        float piv_r2_val = array.get(piv_price_arr, 1)
        float piv_s1_val = array.get(piv_price_arr, 4)
        float piv_s2_val = array.get(piv_price_arr, 5)
        bool r2_auto = not na(piv_r1_val) and px > piv_r1_val
        bool r3_auto = not na(piv_r2_val) and px > piv_r2_val
        bool s2_auto = not na(piv_s1_val) and px < piv_s1_val
        bool s3_auto = not na(piv_s2_val) and px < piv_s2_val
        // v7.41: table-only always-on toggles OR in alongside the existing chart-toggle copy and
        // the auto-escalation above -- any of the three being true now shows that level.
        array.set(pivT_enabled, 1, array.get(pivT_enabled, 1) or r2_auto or show_tbl_r2)
        array.set(pivT_enabled, 0, array.get(pivT_enabled, 0) or r3_auto or show_tbl_r3)
        array.set(pivT_enabled, 5, array.get(pivT_enabled, 5) or s2_auto or show_tbl_s2)
        array.set(pivT_enabled, 6, array.get(pivT_enabled, 6) or s3_auto or show_tbl_s3)
        array.set(pivT_price_arr, 7, ydh)
        array.set(pivT_labels, 7, "YD-H")
        array.set(pivT_enabled, 7, show_pivot_ydh)
        array.set(pivT_lblcol, 7, col_piv_r)
        array.set(pivT_price_arr, 8, ydl)
        array.set(pivT_labels, 8, "YD-L")
        array.set(pivT_enabled, 8, show_pivot_ydl)
        array.set(pivT_lblcol, 8, col_piv_s)
        array.set(pivT_price_arr, 9, pmh)
        array.set(pivT_labels, 9, "PMH")
        array.set(pivT_enabled, 9, show_pivot_pmh)
        array.set(pivT_lblcol, 9, col_piv_r)
        array.set(pivT_price_arr, 10, pml)
        array.set(pivT_labels, 10, "PML")
        array.set(pivT_enabled, 10, show_pivot_pml)
        array.set(pivT_lblcol, 10, col_piv_s)
        array.set(pivT_price_arr, 11, ny_orh)
        array.set(pivT_labels, 11, "NY OR-H")
        array.set(pivT_enabled, 11, show_pivot_ny_orh)
        array.set(pivT_lblcol, 11, col_piv_r)
        array.set(pivT_price_arr, 12, ny_orl)
        array.set(pivT_labels, 12, "NY OR-L")
        array.set(pivT_enabled, 12, show_pivot_ny_orl)
        array.set(pivT_lblcol, 12, col_piv_s)
        array.set(pivT_price_arr, 13, ln_orh)
        array.set(pivT_labels, 13, "LN OR-H")
        array.set(pivT_enabled, 13, show_pivot_ln_orh)
        array.set(pivT_lblcol, 13, col_piv_r)
        array.set(pivT_price_arr, 14, ln_orl)
        array.set(pivT_labels, 14, "LN OR-L")
        array.set(pivT_enabled, 14, show_pivot_ln_orl)
        array.set(pivT_lblcol, 14, col_piv_s)
        array.set(pivT_price_arr, 15, as_orh)
        array.set(pivT_labels, 15, "AS OR-H")
        array.set(pivT_enabled, 15, show_pivot_as_orh)
        array.set(pivT_lblcol, 15, col_piv_r)
        array.set(pivT_price_arr, 16, as_orl)
        array.set(pivT_labels, 16, "AS OR-L")
        array.set(pivT_enabled, 16, show_pivot_as_orl)
        array.set(pivT_lblcol, 16, col_piv_s)
        array.set(pivT_price_arr, 17, brsg_top)
        array.set(pivT_labels, 17, "BRSG-H")
        array.set(pivT_enabled, 17, brsg_show)
        array.set(pivT_lblcol, 17, col_piv_r)
        array.set(pivT_price_arr, 18, brsg_bot)
        array.set(pivT_labels, 18, "BRSG-L")
        array.set(pivT_enabled, 18, brsg_show)
        array.set(pivT_lblcol, 18, col_piv_s)
        array.set(pivT_price_arr, 19, htf_piv_hi)
        array.set(pivT_labels, 19, "HTF Piv-H")
        array.set(pivT_enabled, 19, show_pivot_htf_piv_hi)
        array.set(pivT_lblcol, 19, col_piv_r)
        array.set(pivT_price_arr, 20, htf_piv_lo)
        array.set(pivT_labels, 20, "HTF Piv-L")
        array.set(pivT_enabled, 20, show_pivot_htf_piv_lo)
        array.set(pivT_lblcol, 20, col_piv_s)
        array.set(pivT_price_arr, 21, htf_eqh)
        array.set(pivT_labels, 21, "HTF EQH")
        array.set(pivT_enabled, 21, show_pivot_htf_eqh)
        array.set(pivT_lblcol, 21, col_piv_r)
        array.set(pivT_price_arr, 22, htf_eql)
        array.set(pivT_labels, 22, "HTF EQL")
        array.set(pivT_enabled, 22, show_pivot_htf_eql)
        array.set(pivT_lblcol, 22, col_piv_s)
        array.set(pivT_price_arr, 23, ltf_piv_hi)
        array.set(pivT_labels, 23, "LTF Piv-H")
        array.set(pivT_enabled, 23, show_pivot_ltf_piv_hi)
        array.set(pivT_lblcol, 23, col_piv_r)
        array.set(pivT_price_arr, 24, ltf_piv_lo)
        array.set(pivT_labels, 24, "LTF Piv-L")
        array.set(pivT_enabled, 24, show_pivot_ltf_piv_lo)
        array.set(pivT_lblcol, 24, col_piv_s)
        array.set(pivT_price_arr, 25, ema200_val)
        array.set(pivT_labels, 25, "EMA200")
        array.set(pivT_enabled, 25, show_pivot_ema200)
        array.set(pivT_lblcol, 25, px > ema200_val ? col_piv_r : col_piv_s)
        array.set(pivT_price_arr, 26, vwap_val)
        array.set(pivT_labels, 26, "VWAP")
        array.set(pivT_enabled, 26, show_pivot_vwap)
        array.set(pivT_lblcol, 26, px > vwap_val ? col_piv_r : col_piv_s)
 
        var bool[] piv_show_final = array.new_bool(27, false)
        for si = 0 to 26
            array.set(piv_show_final, si, array.get(pivT_enabled, si) and not na(array.get(pivT_price_arr, si)))
 
        var float[] piv_final_price = array.new_float(28, na)
        var string[] piv_final_label = array.new_string(28, "")
        var color[] piv_final_lblcol = array.new<color>(28, na)
        int piv_final_n = 0
        for pi = 0 to 26
            if array.get(piv_show_final, pi)
                array.set(piv_final_price, piv_final_n, array.get(pivT_price_arr, pi))
                array.set(piv_final_label, piv_final_n, array.get(pivT_labels, pi))
                array.set(piv_final_lblcol, piv_final_n, array.get(pivT_lblcol, pi))
                piv_final_n := piv_final_n + 1
        // v7.41: PRICE's own label now reads "Price-L"/"Price-S", per direct request ("for price if
        // long change label t Price-L or Price -S if short"). v7.63: switched from the LTF/chart's
        // own live CBC direction to the confirmed HTF CBC direction (last CLOSED HTF bar), per direct
        // follow-up ("the direction should be the htf cbc direction" / "from last closed bar cbc htf
        // direction - clarification should be the direction of the pivot price direction") -- the
        // whole pivot table's price-direction concept (this label, the Long/Short text, the diff
        // sign, the green/red price-column color, and the sort order below) now all follow the same
        // confirmed HTF CBC direction instead of the LTF chart timeframe's own direction.
        string price_lbl_txt = htf_bull ? "Price-L" : "Price-S"
        array.set(piv_final_price, piv_final_n, px)
        array.set(piv_final_label, piv_final_n, price_lbl_txt)
        array.set(piv_final_lblcol, piv_final_n, st_highlight)
        piv_final_n := piv_final_n + 1
 
        float[] piv_sorted_price = array.slice(piv_final_price, 0, piv_final_n)
        array<int> piv_sort_order = array.sort_indices(piv_sorted_price, order.ascending)
        if not htf_bull
            array.reverse(piv_sort_order)
 
        // v7.60 (main script) / v50 (library): FIX RE10039 "Column N is out of table bounds" --
        // this table was created ONCE (guarded by na(piv_tbl), a `var` that persists across bars)
        // with its column count fixed at whatever piv_final_n happened to be on the bar it first
        // drew (math.max(1, piv_final_n)). But piv_final_n is NOT constant -- it depends on which
        // levels are currently enabled/have a non-na price (BRSG zone, R2/R3/S2/S3 auto-escalation,
        // HTF EQH/EQL forming later, etc.), so it can legitimately GROW on a later bar past the
        // column count the table was originally sized for -- exactly what happened at bar 22060
        // (needed column 26, i.e. a 27th column, but the table had only been created with 26).
        // Fix: always allocate the table with the maximum possible column count (28 -- 27 candidate
        // levels, indices 0-26 in pivT_price_arr/pivT_labels/pivT_enabled, PLUS 1 for the PRICE row;
        // piv_final_price/piv_final_label/piv_final_lblcol are already sized 28 for exactly this
        // reason) instead of sizing to whatever piv_final_n was on the first bar. piv_final_n can
        // now only ever be <= the table's own column count, so this can't recur regardless of which
        // levels toggle on/off or auto-escalate over the life of the chart. Unused trailing columns
        // on a lower-count bar are simply never written to by the `for pc = 0 to piv_final_n - 1`
        // loop below -- table.new() leaves unset cells blank, so this has no visual side effect.
        if na(piv_tbl)
            piv_tbl := table.new(f_status_pos(position), 28, 3, bgcolor=color.new(#020617, 0), border_color=border_col, border_width=3, frame_color=frame_col, frame_width=2)
        string piv_txt_sz = text_size == "Tiny" ? size.tiny : text_size == "Small" ? size.small : text_size == "Normal" ? size.normal : text_size == "Large" ? size.large : size.huge
        for pc = 0 to piv_final_n - 1
            int p_idx = array.get(piv_sort_order, pc)
            float p_val = array.get(piv_sorted_price, p_idx)
            string p_lbl = array.get(piv_final_label, p_idx)
            bool p_is_price = p_lbl == "Price-L" or p_lbl == "Price-S"
            float p_diff = htf_bull ? (p_val - px) : (px - p_val)
            color p_row_bg = p_is_price ? st_highlight : px > p_val ? st_bull : st_bear
            // v7.42: per direct follow-up ("also make the price column instead of having 0 in row
            // two change it to long or short - use a different color of red and green to stand out
            // from columns to the right and left, keep cell keep top row orange"). The PRICE
            // column's row 1 (signed-distance, previously always "+0.00" for this column since
            // p_diff is 0 by construction) now shows the plain word "Long"/"Short" instead, and
            // BOTH row 1 and row 2 (the price-value cell, colored by direction since the prior
            // round) use their own distinct, more saturated green/red -- p_price_col_bg -- so the
            // PRICE column visibly stands out from the muted st_bull/st_bear used by every other
            // column to its left/right. Row 0 (the label cell) keeps the shared gold st_highlight
            // unchanged, per "keep cell top row orange."
            color p_price_col_bg = htf_bull ? color.new(#22C55E, 0) : color.new(#EF4444, 0)
            color p_price_row1_bg = p_is_price ? p_price_col_bg : p_row_bg
            color p_price_row2_bg = p_is_price ? p_price_col_bg : p_row_bg
            // v53/v55: PRICE column's row 1 (previously the plain word "Long"/"Short", added v7.42) now
            // shows the direction letter plus the OPEN-CLOSE time range of the candle that confirmed
            // the current HTF CBC direction -- "L 9:30-45" / "S 9:45-10" -- per direct request ("change
            // sort in second row to S-time where the time period of the closing candle. i.e. 9:30
            // candle"), then a follow-up refining the single-time display into a range ("make it
            // 9:30-45 or in another case 9:45-10"). Uses f_fmt_ny_time_range() above against
            // htf_last_flip_t_open/htf_last_flip_t_close, two parameters carrying the OPEN and CLOSE
            // time of the same confirming HTF bar (a candle is conventionally named by its own open
            // time, e.g. "the 9:30 candle" -- htf_last_flip_t_close is distinct from the existing
            // htf_last_flip_t used elsewhere in the main script for the same close-time reading, kept
            // separate per that variable's own v7.70 note).
            string p_row1_txt = p_is_price ? (htf_bull ? "L " : "S ") + f_fmt_ny_time_range(htf_last_flip_t_open, htf_last_flip_t_close) : (p_diff >= 0 ? "+" : "") + str.tostring(p_diff, "#.##")
            table.cell(piv_tbl, pc, 0, p_lbl, bgcolor=array.get(piv_final_lblcol, p_idx), text_color=txt_on, text_size=piv_txt_sz, text_halign=text.align_center)
            table.cell(piv_tbl, pc, 1, p_row1_txt, bgcolor=p_price_row1_bg, text_color=txt_on, text_size=piv_txt_sz, text_halign=text.align_center)
            table.cell(piv_tbl, pc, 2, str.tostring(p_val, "#.##"), bgcolor=p_price_row2_bg, text_color=txt_on, text_size=piv_txt_sz, text_halign=text.align_center)
    true
 
// v41: Auto Trade Setup helpers, moved here from the main script's v7.44 feature at v7.45 purely to
// relieve main-script CE10117 token pressure (reported 103065/100256) -- same "pure-parameter, no-CBC-
// state helper moved to the library" technique already used throughout this file. f_ats_build_candidates
// builds the stop/target candidate pool from the same live pivot values/toggles the Pivot Points table
// itself draws from (BRSG is never one of the parameters, so it can never end up in the returned pool).
// v53: added NY/London/Asia Opening Range High/Low as candidates, per user request -- OR-H/OR-L had
// been absent from this pool since the function was first written (BRSG stays excluded by design).
// f_ats_nearest_above/f_ats_nearest_below scan that pool for the closest qualifying price on either
// side of a given price. All three are pure array/scalar-in, single-value-out (no tuples, per this
// project's standing CE10172 lesson) and carry no CBC state of their own.
export f_ats_build_candidates(float[] piv_price, bool[] piv_enabled, float ydh, bool sh_ydh, float ydl, bool sh_ydl, float pmh, bool sh_pmh, float pml, bool sh_pml, float htf_hi, bool sh_htf_hi, float htf_lo, bool sh_htf_lo, float htf_eqh, bool sh_htf_eqh, float htf_eql, bool sh_htf_eql, float ltf_hi, bool sh_ltf_hi, float ltf_lo, bool sh_ltf_lo, float ema200_val, bool sh_ema200, float vwap_val, bool sh_vwap, float ny_orh, bool sh_ny_orh, float ny_orl, bool sh_ny_orl, float ln_orh, bool sh_ln_orh, float ln_orl, bool sh_ln_orl, float as_orh, bool sh_as_orh, float as_orl, bool sh_as_orl) =>
    float[] out = array.new_float(0)
    for pk = 0 to array.size(piv_enabled) - 1
        if array.get(piv_enabled, pk)
            array.push(out, array.get(piv_price, pk))
    if sh_ydh and not na(ydh)
        array.push(out, ydh)
    if sh_ydl and not na(ydl)
        array.push(out, ydl)
    if sh_pmh and not na(pmh)
        array.push(out, pmh)
    if sh_pml and not na(pml)
        array.push(out, pml)
    if sh_htf_hi and not na(htf_hi)
        array.push(out, htf_hi)
    if sh_htf_lo and not na(htf_lo)
        array.push(out, htf_lo)
    if sh_htf_eqh and not na(htf_eqh)
        array.push(out, htf_eqh)
    if sh_htf_eql and not na(htf_eql)
        array.push(out, htf_eql)
    if sh_ltf_hi and not na(ltf_hi)
        array.push(out, ltf_hi)
    if sh_ltf_lo and not na(ltf_lo)
        array.push(out, ltf_lo)
    if sh_ema200 and not na(ema200_val)
        array.push(out, ema200_val)
    if sh_vwap and not na(vwap_val)
        array.push(out, vwap_val)
    if sh_ny_orh and not na(ny_orh)
        array.push(out, ny_orh)
    if sh_ny_orl and not na(ny_orl)
        array.push(out, ny_orl)
    if sh_ln_orh and not na(ln_orh)
        array.push(out, ln_orh)
    if sh_ln_orl and not na(ln_orl)
        array.push(out, ln_orl)
    if sh_as_orh and not na(as_orh)
        array.push(out, as_orh)
    if sh_as_orl and not na(as_orl)
        array.push(out, as_orl)
    out
 
export f_ats_nearest_above(float px, float[] arr) =>
    float best = na
    if array.size(arr) > 0
        for i = 0 to array.size(arr) - 1
            float v = array.get(arr, i)
            if not na(v) and v > px and (na(best) or v < best)
                best := v
    best
 
export f_ats_nearest_below(float px, float[] arr) =>
    float best = na
    if array.size(arr) > 0
        for i = 0 to array.size(arr) - 1
            float v = array.get(arr, i)
            if not na(v) and v < px and (na(best) or v > best)
                best := v
    best
 
// v58: f_ats_handle_snap() -- CE10295 "main body of the script is too long" relief (reported on v7.76's
// draggable drag-to-snap handles, which had added 4 near-identical multi-line override blocks directly
// in the main script's top-level scope). Collapses each block's "is the handle active, and if so what
// does it snap to" logic into a single library call -- same technique already used throughout this file
// for CE10117 relief (moving pure-parameter, no-CBC-state logic to the library), which also happens to
// be exactly what CE10295's own message suggests ("try wrapping code in functions"). Pure relocation, no
// behavior change: same "handle is nonzero and farther than tol from current" activation check, same
// nearest_above/below-fed-the-handle's-raw-price snap, same "keep current value if inactive or the snap
// comes back na" fallback the 4 inline blocks each had.
export f_ats_handle_snap(float handle, float current, float tol, bool want_above, float[] cand) =>
    float result = current
    if handle != 0.0 and not na(current) and math.abs(handle - current) > tol
        float snap = want_above ? f_ats_nearest_above(handle, cand) : f_ats_nearest_below(handle, cand)
        if not na(snap)
            result := snap
    result
 
// v42: Auto Trade Setup drawing, moved here from the main script at v7.46 for a further CE10117
// reduction (reported 102238/100256 after v7.45's first offload). Same persistent-`var`-inside-an-
// exported-function pattern already proven safe in this file (see f_render_fib_zone_box's
// `var box fib_zone_bx`/etc. above, and f_render_pivot_table's `var table piv_tbl`) — the box/line/
// label refs live INSIDE this function's own persistent state instead of being passed in and back out,
// which sidesteps the "exported functions can't return a tuple" restriction (convention #19) entirely:
// this function only ever needs to return one value, never the 6 drawing-object refs the old inline
// version had to juggle in the main script. Delete-and-recreate-on-every-call lifecycle (one active
// setup at a time) is identical to the old inline version, just relocated.
// v47: restyled per direct request to look closer to TradingView's native "Long/Short position"
// Forecasting drawing tool (a split green/red box with the entry line through the middle, stop at one
// edge, target at the other — screenshot referenced the tool directly). Pine has no API to create that
// native drawing-tool object type itself (confirmed — it's a manual chart tool with no scripting
// access), so this is the closest achievable approximation using box.new()/line.new(): unchanged
// reward_box (green, Entry→Target) + risk_box (red, Entry→Stop) already form the same split-box look
// with entry price running through the middle, target at the far edge, stop at the other. Per direct
// answer ("Closest box/line approximation"), the only change is dropping the old text-info label
// (rr_label, "LONG setup / Entry.. / Stop.. / Target.. / R:R..") entirely so the setup reads as a clean
// drawn shape instead of "a red box with info in it".
// v48: TradingView flagged the now-unused `txt_size` parameter left in the v47 signature (CE10237
// "Unused argument 'txt_size'... Ensure that it utilizes all arguments"). Removed the parameter
// entirely rather than leaving it in place — this function's signature is now 6 params, down from 7.
// The main script's call site and its `trade_setup_txt_size` input (which had nothing left to feed
// once the label was removed at v47) were both removed in the same round; see the v7.57 changelog
// block in the main script.
// v49: same CE10237 warning, now on `is_long` — v47's label removal also left THIS parameter with
// nothing left to consume it (it used to pick "LONG"/"SHORT" text and the label's color; both gone
// since v47). Missed in the v48 pass because only `txt_size` had been reported at that point. Removed
// `is_long` too — signature is now 5 params, down from 6. The main script's `ats_long` local variable
// is still used elsewhere in that call's `if` block (for the stop/target nearest-pivot direction), so
// it stays — only the now-unnecessary 6th argument to this specific call was dropped. Audited every
// remaining parameter (`entry`/`stop`/`target`/`reward_col`/`risk_col`) against the function body below
// this time — all 5 are read by at least one `box.new()`/`line.new()` call, none are dead.
// v59: TP1/SL1/TP2/SL2 line labels, per direct request ("I would like this option when it draws a new
// setup box but not when you load the indicator mark tp1 and tp2 and sl1 and sl2 on the lines"). Four
// new persistent labels (target_lbl/stop_lbl/target2_lbl/stop2_lbl), delete-and-recreate on the SAME
// call as the box/lines they tag -- this function only ever runs when a genuinely new setup is drawn
// (the main script's cooldown-gated trigger `if` block is the only caller), so a label can never appear
// on its own without a fresh box/line draw alongside it; there is no separate "on load" code path to
// guard against. No parameters added -- entry/stop/target/stop2/target2 were already available. This is
// a deliberately minimal per-line tag ("TP1"/"SL1"/"TP2"/"SL2" only), NOT a return of the old v7.56-
// removed `rr_label` (which packed Entry/Stop/Target/R:R text into one combined label) -- different,
// smaller design, per this round's explicit request.
// v60: `new_setup` gate + per-bar TP2/SL2 breach freeze, per direct request ("stop trade setup
// extending to the right when the price breaks tp2 or sl2"). This function now has to run EVERY bar
// (not just on a trigger bar) so it can check the ACTIVE setup's TP2/SL2 against the current bar's
// high/low even on bars where nothing new is firing -- `new_setup` tells it whether THIS call is a
// fresh trigger (draw everything from scratch, same as before) or a routine per-bar check (just look
// for a breach of the ALREADY-drawn setup's TP2/SL2 and, if found, freeze every object's right edge in
// place). The entry/stop/target/stop2/target2 of the currently active setup are now latched into their
// own persistent `var float`s so the freeze check on a non-trigger bar doesn't need them re-passed in
// (the main script passes na for all 5 level params on a non-trigger call). Breach direction is derived
// generically from each level's position relative to entry (no explicit long/short flag needed): a
// target-side level (above entry) breaches on `high >= level`, a stop-side level (below entry) breaches
// on `low <= level`. TP1/SL1 themselves are untouched by this -- only TP2/SL2 gate the freeze, per the
// literal request; if TP2/SL2 aren't shown for a given setup, that setup keeps extending indefinitely,
// same as before this round (no fallback to TP1/SL1 breach was asked for).
export f_ats_draw_setup(bool new_setup, float entry, float stop, float target, color reward_col, color risk_col, bool show_lvl2, float stop2, float target2, color reward2_col, color risk2_col) =>
    var box reward_box = na
    var box risk_box = na
    var box reward_box2 = na
    var box risk_box2 = na
    var line entry_line = na
    var line stop_line = na
    var line target_line = na
    var line stop2_line = na
    var line target2_line = na
    var label target_lbl = na
    var label stop_lbl = na
    var label target2_lbl = na
    var label stop2_lbl = na
    var float active_entry = na
    var float active_target2 = na
    var float active_stop2 = na
    var bool ats_frozen = false
    if new_setup
        box.delete(reward_box)
        box.delete(risk_box)
        box.delete(reward_box2)
        box.delete(risk_box2)
        line.delete(entry_line)
        line.delete(stop_line)
        line.delete(target_line)
        line.delete(stop2_line)
        line.delete(target2_line)
        label.delete(target_lbl)
        label.delete(stop_lbl)
        label.delete(target2_lbl)
        label.delete(stop2_lbl)
        reward_box := box.new(bar_index, math.max(entry, target), bar_index, math.min(entry, target), border_color=color.new(#22C55E, 40), bgcolor=reward_col, extend=extend.right)
        risk_box := box.new(bar_index, math.max(entry, stop), bar_index, math.min(entry, stop), border_color=color.new(#EF4444, 40), bgcolor=risk_col, extend=extend.right)
        entry_line := line.new(bar_index, entry, bar_index, entry, color=color.new(color.white, 20), width=1, style=line.style_dashed, extend=extend.right)
        stop_line := line.new(bar_index, stop, bar_index, stop, color=color.new(#EF4444, 0), width=1, style=line.style_dotted, extend=extend.right)
        target_line := line.new(bar_index, target, bar_index, target, color=color.new(#22C55E, 0), width=1, style=line.style_dotted, extend=extend.right)
        target_lbl := label.new(bar_index, target, "TP1", color=color.new(color.white, 100), textcolor=color.new(#22C55E, 0), style=label.style_label_left, size=size.small)
        stop_lbl := label.new(bar_index, stop, "SL1", color=color.new(color.white, 100), textcolor=color.new(#EF4444, 0), style=label.style_label_left, size=size.small)
        if show_lvl2 and not na(target2)
            reward_box2 := box.new(bar_index, math.max(target, target2), bar_index, math.min(target, target2), border_color=color.new(#22C55E, 55), bgcolor=reward2_col, extend=extend.right)
            target2_line := line.new(bar_index, target2, bar_index, target2, color=color.new(#22C55E, 25), width=1, style=line.style_dotted, extend=extend.right)
            target2_lbl := label.new(bar_index, target2, "TP2", color=color.new(color.white, 100), textcolor=color.new(#22C55E, 25), style=label.style_label_left, size=size.small)
        if show_lvl2 and not na(stop2)
            risk_box2 := box.new(bar_index, math.max(stop, stop2), bar_index, math.min(stop, stop2), border_color=color.new(#EF4444, 55), bgcolor=risk2_col, extend=extend.right)
            stop2_line := line.new(bar_index, stop2, bar_index, stop2, color=color.new(#EF4444, 25), width=1, style=line.style_dotted, extend=extend.right)
            stop2_lbl := label.new(bar_index, stop2, "SL2", color=color.new(color.white, 100), textcolor=color.new(#EF4444, 25), style=label.style_label_left, size=size.small)
        active_entry := entry
        active_target2 := show_lvl2 ? target2 : na
        active_stop2 := show_lvl2 ? stop2 : na
        ats_frozen := false
    else if not ats_frozen and not na(reward_box)
        bool breach = false
        if not na(active_target2)
            breach := active_target2 > active_entry ? high >= active_target2 : low <= active_target2
        if not breach and not na(active_stop2)
            breach := active_stop2 < active_entry ? low <= active_stop2 : high >= active_stop2
        if breach
            box.set_extend(reward_box, extend.none)
            box.set_right(reward_box, bar_index)
            box.set_extend(risk_box, extend.none)
            box.set_right(risk_box, bar_index)
            line.set_extend(entry_line, extend.none)
            line.set_x2(entry_line, bar_index)
            line.set_extend(stop_line, extend.none)
            line.set_x2(stop_line, bar_index)
            line.set_extend(target_line, extend.none)
            line.set_x2(target_line, bar_index)
            if not na(reward_box2)
                box.set_extend(reward_box2, extend.none)
                box.set_right(reward_box2, bar_index)
                line.set_extend(target2_line, extend.none)
                line.set_x2(target2_line, bar_index)
            if not na(risk_box2)
                box.set_extend(risk_box2, extend.none)
                box.set_right(risk_box2, bar_index)
                line.set_extend(stop2_line, extend.none)
                line.set_x2(stop2_line, bar_index)
            ats_frozen := true
    true
 
// v61: on-chart identifier labels for the 4 drag handles THEMSELVES, per direct follow-up ("where is
// the handle to drag? i tried to drag sl2 higher and tp2 went way down"). Root cause: all 4
// input.price() handles default to 0.0 ("inactive/off-chart") and, once set near the current price,
// render as plain TradingView-native lines distinguished only by their Settings-panel title -- nothing
// on the chart itself says "this one is SL2" vs "this one is TP1", so with 4 near-identical lines it's
// very easy to grab the wrong one. (TP2's Automatic value is the next candidate PAST TP1, not past SL1/
// SL2 at all -- so a dramatic TP2 jump right after "dragging SL2" is the signature of having actually
// grabbed the TP1 handle by mistake, since only a TP1 move can move TP2.) This function draws a small
// persistent label directly on each ACTIVE handle's own line (skipped entirely while a handle is still
// at its 0.0 inactive default -- there is nothing to label yet) in a color unique to that handle --
// cyan/orange/purple/yellow -- deliberately different from the green/red TP/SL box and v59 setup-label
// colors so it can never be confused with the real TP1/SL1/TP2/SL2 levels or with each other. Runs
// every bar (unconditional, same pattern as f_ats_draw_setup()'s breach check above) so each label
// tracks its handle's live price the instant it's typed into Settings or dragged.
export f_ats_draw_handles(float tp1_h, float sl1_h, float tp2_h, float sl2_h, bool show_tp2, bool show_sl2) =>
    var label tp1_lbl = na
    var label sl1_lbl = na
    var label tp2_lbl = na
    var label sl2_lbl = na
    if tp1_h != 0.0
        if na(tp1_lbl)
            tp1_lbl := label.new(bar_index, tp1_h, "◆ TP1 HANDLE", color=color.new(color.white, 100), textcolor=color.new(#22D3EE, 0), style=label.style_label_right, size=size.small)
        else
            label.set_xy(tp1_lbl, bar_index, tp1_h)
    else if not na(tp1_lbl)
        label.delete(tp1_lbl)
        tp1_lbl := na
    if sl1_h != 0.0
        if na(sl1_lbl)
            sl1_lbl := label.new(bar_index, sl1_h, "◆ SL1 HANDLE", color=color.new(color.white, 100), textcolor=color.new(#FB923C, 0), style=label.style_label_right, size=size.small)
        else
            label.set_xy(sl1_lbl, bar_index, sl1_h)
    else if not na(sl1_lbl)
        label.delete(sl1_lbl)
        sl1_lbl := na
    if show_tp2 and tp2_h != 0.0
        if na(tp2_lbl)
            tp2_lbl := label.new(bar_index, tp2_h, "◆ TP2 HANDLE", color=color.new(color.white, 100), textcolor=color.new(#C084FC, 0), style=label.style_label_right, size=size.small)
        else
            label.set_xy(tp2_lbl, bar_index, tp2_h)
    else if not na(tp2_lbl)
        label.delete(tp2_lbl)
        tp2_lbl := na
    if show_sl2 and sl2_h != 0.0
        if na(sl2_lbl)
            sl2_lbl := label.new(bar_index, sl2_h, "◆ SL2 HANDLE", color=color.new(color.white, 100), textcolor=color.new(#FACC15, 0), style=label.style_label_right, size=size.small)
        else
            label.set_xy(sl2_lbl, bar_index, sl2_h)
    else if not na(sl2_lbl)
        label.delete(sl2_lbl)
        sl2_lbl := na
    true
 
 
// v43: f_render_status_table() moved from the main script (CE10117 relief round 5) -- the single
// largest remaining local function, ~175 lines / 132 external reads, none of it CBC-internal state
// beyond plain parameters. Keeps its own var table/string/bool state internally (same pattern as
// f_render_pivot_table/f_render_fib_zone_box/f_ats_draw_setup) so it needs no tuple return.
export f_render_status_table(array<string> field_order, float ORHigh_AS, float ORHigh_LN, float ORHigh_NY, float ORLow_AS, float ORLow_LN, float ORLow_NY, float PMH, float PML, float YDH, float YDL, int as_or_open, int ln_or_open, int ny_or_open, float brsg_zone_bot, float brsg_zone_top, bool cbc, string chart_tf_disp_val, string htf_tf_disp_val, string mtf_tf_disp_val, color col_orb_as_lbl, color col_orb_ln_lbl, color col_orb_ny_lbl, int confluence_alert_threshold, int confluence_max_score, int confluence_score, bool confluence_same_score_diff_mask, bool eff_show_chart_info_tbl, bool eff_show_fld_buysell, bool eff_show_fld_conf_summary, bool eff_show_fld_confluence, bool eff_show_fld_flip_level, bool eff_show_fld_last_flip, bool eff_show_fld_next_levels, bool eff_show_fld_stop, bool eff_show_htf_pivots_tbl, bool eff_show_ltf_pivots_tbl, bool eff_show_mtf_pivots_tbl, float ema200, bool ema_bullish, float fib_50, float fib_618, bool fib_price_in_zone, bool fib_valid, float h_last_hi, float h_last_lo, float l_last_hi, float l_last_lo, float m_last_hi, float m_last_lo, int htf_bars_since_flip, int ltf_bars_since_flip, int mtf_bars_since_flip, bool htf_cbc, bool mtf_cbc, float htf_cbc_labels_f, float mtf_cbc_labels_f, bool htf_ema_bullish, bool mtf_ema_bullish, bool htf_enabled, bool mtf_enabled, float htf_flip_price, float ltf_flip_price, float mtf_flip_price, float htf_fvg_bot, float htf_fvg_top, bool htf_fvg_exists, bool htf_in_flip_fvg, string htf_hi_struct, string htf_lo_struct, string ltf_hi_struct, string ltf_lo_struct, string mtf_hi_struct, string mtf_lo_struct, bool htf_last_flip_bull, bool ltf_last_flip_bull, bool mtf_last_flip_bull, int htf_last_flip_t, int ltf_last_flip_t, int mtf_last_flip_t, string htf_stop_method, string htf_timeframe, string mtf_timeframe, float htf_trail_stop, bool ltf_cbc_confirmed, array<string> nl_label, bool or_asian, bool or_london, bool or_ny, float piv_pp, float piv_r1, float piv_r2, float piv_r3, float piv_s1, float piv_s2, float piv_s3, bool show_any_or, bool show_fld_cbc, bool show_fld_ema200, bool show_fld_ema_cloud, bool show_fld_fib_zone, bool show_fld_market, bool show_fld_opening_range, bool show_fld_price, bool show_fld_structure, bool show_fld_vwap, bool show_htf_in_tables, bool show_ltf_in_tables, bool show_mtf_in_tables, bool show_mtf_cbc, bool show_mtf_cloud, bool show_mtf_fliplevel, bool show_mtf_lastflip, bool show_mtf_structure, bool show_status_table, color st_bear, color st_bull, color st_highlight, color st_neutral, string status_field_set, int status_table_header_newlines, string status_table_position, string status_table_text_size, bool status_tbl_collapsed, color tbl_border, color tbl_frame, color tbl_header_bg, color tbl_label_bg, color txt_head, color txt_label, color txt_on, float vwap_value) =>
    var table status_tbl = na
    var string status_tbl_pos_last = ""
    var bool status_tbl_collapsed_last = false
    var string status_field_set_last = ""
    if not show_status_table
        table.delete(status_tbl)
        status_tbl := na
        status_tbl_pos_last := ""
    else
        if not na(status_tbl) and (status_tbl_pos_last != status_table_position or status_tbl_collapsed_last != status_tbl_collapsed or status_field_set_last != status_field_set)
            table.delete(status_tbl)
            status_tbl := na
        if na(status_tbl)
            int fld_grp = (show_ltf_in_tables ? 1 : 0) + (show_htf_in_tables ? 1 : 0) + (show_mtf_in_tables ? 1 : 0)
            status_tbl := table.new(f_status_pos(status_table_position), 2, status_tbl_collapsed ? 1 : math.max(1, (show_fld_market ? 1 : 0) + (show_fld_price ? 1 : 0) + (show_fld_cbc ? fld_grp : 0) + (show_fld_opening_range ? 1 : 0) + (show_fld_ema_cloud ? fld_grp : 0) + (show_fld_vwap ? 1 : 0) + (show_fld_ema200 ? 1 : 0) + (show_fld_structure ? fld_grp : 0) + (eff_show_fld_last_flip ? fld_grp : 0) + (eff_show_fld_stop ? 1 : 0) + (eff_show_fld_buysell ? 1 : 0) + (eff_show_chart_info_tbl ? 1 : 0) + (eff_show_ltf_pivots_tbl ? 1 : 0) + (eff_show_htf_pivots_tbl ? 1 : 0) + (eff_show_mtf_pivots_tbl ? 1 : 0) + (eff_show_fld_flip_level ? fld_grp : 0) + (eff_show_fld_confluence ? 1 : 0) + (show_fld_fib_zone ? 1 : 0) + (eff_show_fld_conf_summary ? 1 : 0) + (eff_show_fld_next_levels ? 2 : 0)), bgcolor=color.new(#020617, 0), border_color=tbl_border, border_width=1, frame_color=tbl_frame, frame_width=2)
            if status_tbl_collapsed
                table.merge_cells(status_tbl, 0, 0, 1, 0)
            status_tbl_collapsed_last := status_tbl_collapsed
            status_tbl_pos_last := status_table_position
            status_field_set_last := status_field_set
        [nl_target_txt, nl_stop_txt] = f_next_two_levels((array.from(YDH, YDL, PMH, PML, ORHigh_NY, ORLow_NY, ORHigh_LN, ORLow_LN, ORHigh_AS, ORLow_AS, l_last_hi, l_last_lo, h_last_hi, h_last_lo, m_last_hi, m_last_lo, ema200, piv_r3, piv_r2, piv_r1, piv_pp, piv_s1, piv_s2, piv_s3)), nl_label, cbc, close)
        cloud_bull = ema_bullish
        // v7.28: vwap_bull/ema200_bull now mean "favorable for the live CBC direction" (cbc ? above :
        // below) instead of a raw, direction-blind "is price above" check -- per direct request
        // ("all the points are positive they should be in relation to the direction of cbc"), made
        // against a screenshot of a bearish setup where these rows still read "Above" with a positive
        // number, which read as bullish-leaning even though the trade context was short.
        vwap_bull = not na(vwap_value) and (cbc ? close > vwap_value : close < vwap_value)
        ema200_bull = not na(ema200) and (cbc ? close > ema200 : close < ema200)
        string mkt_tbl = f_market_session_et()
        float or_f_hi = mkt_tbl == "Asian" ? ORHigh_AS : mkt_tbl == "London" ? ORHigh_LN : ORHigh_NY
        float or_f_lo = mkt_tbl == "Asian" ? ORLow_AS : mkt_tbl == "London" ? ORLow_LN : ORLow_NY
        or_right = st_neutral
        or_msg = "—"
        if not show_any_or
            or_msg := "Off"
        else if not ((mkt_tbl == "Asian" and or_asian) or (mkt_tbl == "London" and or_london) or (mkt_tbl == "New York" and or_ny))
            or_msg := "—"
        else if time < (mkt_tbl == "Asian" ? as_or_open : mkt_tbl == "London" ? ln_or_open : ny_or_open)
            or_msg := "Before open"
        else if na(or_f_hi) or na(or_f_lo)
            or_msg := "Pending"
        else if close > or_f_hi
            or_msg := str.tostring(or_f_hi, "#.##") + "  " + ((close - or_f_hi) >= 0 ? "+" : "") + str.tostring(close - or_f_hi, "#.#") + " pts"
            or_right := st_bull
        else if close < or_f_lo
            or_msg := str.tostring(or_f_lo, "#.##") + "  " + ((close - or_f_lo) >= 0 ? "+" : "") + str.tostring(close - or_f_lo, "#.#") + " pts"
            or_right := st_bear
        else
            or_msg := "In Range"
            or_right := color.new(#000000, 10)
        // v7.28: v_diff/e200_diff are now SIGNED relative to the live CBC direction (positive =
        // favorable, negative = against), not a raw close-vwap/close-ema200 difference. Since
        // vwap_bull/ema200_bull (above) already mean "favorable," they now agree with the sign of
        // v_diff/e200_diff by construction (favorable <=> diff >= 0) -- "Favorable"/"Against" and the
        // +/- sign can never disagree.
        float v_diff = not na(vwap_value) ? (cbc ? close - vwap_value : vwap_value - close) : na
        float e200_diff = not na(ema200) ? (cbc ? close - ema200 : ema200 - close) : na
        tbl_txt_sz = f_table_text_size(status_table_text_size)
        if status_tbl_collapsed
            table.cell(status_tbl, 0, 0, (str.repeat("\n", status_table_header_newlines) + "MapleStax CBC  ·  " + syminfo.ticker), bgcolor=tbl_header_bg, text_color=txt_head, text_size=tbl_txt_sz, text_halign=text.align_center)
        int r = 0
        array<int> tf_order = f_ltf_htf_mtf_order(htf_timeframe, mtf_timeframe)
        for i = 0 to (status_tbl_collapsed ? -1 : array.size(field_order) - 1)
            string fid = array.get(field_order, i)
            if fid == "market" and show_fld_market
                r := f_add_status_row(status_tbl, r, "Market", "Which trading session is currently", mkt_tbl, mkt_tbl == "Asian" ? col_orb_as_lbl : mkt_tbl == "London" ? col_orb_ln_lbl : color.new(col_orb_ny_lbl, 35), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            // v4.61: Price — new Essential-level row per follow-up ("add price to the essential below
            // market"), default order slot 2 so it sits directly under Market. Colored by simple tick
            // direction vs the prior bar's close (green up, red down, gray unchanged) — same st_bull/
            // st_bear/st_neutral used everywhere else in this table, not tied to CBC/HTF direction.
            else if fid == "price" and show_fld_price
                r := f_add_status_row(status_tbl, r, "Price", "Current close. Green/red on an up/down tick vs the prior bar's close, gray when unchanged.", str.tostring(close, "#.##"), close > close[1] ? st_bull : close < close[1] ? st_bear : st_neutral, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "cbc" and show_fld_cbc
                r := f_add_tf_row(status_tbl, r, "CBC",
                                   ((ltf_cbc_confirmed ? "Bullish" : "Bearish") + (ltf_cbc_confirmed != cbc ? "  ⚠ live " + (cbc ? "Bull" : "Bear") : "")), (cbc ? st_bull : st_bear),
                                   (not htf_enabled ? "Off" : na(htf_cbc_labels_f) ? "—" : (htf_cbc_labels_f == 1.0 ? "Bullish" : "Bearish") + (htf_enabled and not na(htf_cbc_labels_f) and ((htf_cbc_labels_f == 1.0) != htf_cbc) ? "  ⚠ live " + (htf_cbc ? "Bull" : "Bear") : "")), (not htf_enabled ? st_neutral : na(htf_cbc_labels_f) ? st_neutral : (htf_cbc_labels_f == 1.0 ? st_bull : st_bear)),
                                   not mtf_enabled ? "Off" : na(mtf_cbc_labels_f) ? "—" : (mtf_cbc_labels_f == 1.0 ? "Bullish" : "Bearish"), not mtf_enabled ? st_neutral : na(mtf_cbc_labels_f) ? st_neutral : (mtf_cbc_labels_f == 1.0 ? st_bull : st_bear),
                                   show_ltf_in_tables, show_htf_in_tables, show_mtf_in_tables, show_mtf_cbc,
                                   chart_tf_disp_val, htf_tf_disp_val, mtf_tf_disp_val,
                                   color.new(#0A1628, 0), color.new(#93C5FD, 0), txt_on, tbl_txt_sz, tf_order,
                                   "Close-Break-Confirmation direction on the", "Same CBC logic, computed on the HTF.", "Same Close-Break-Confirmation logic as")
            else if fid == "or" and show_fld_opening_range
                r := f_add_status_row(status_tbl, r, "Opening range", "Price vs. the current session's Opening", or_msg, or_right, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "cloud" and show_fld_ema_cloud
                r := f_add_tf_row(status_tbl, r, "EMA cloud",
                                   (cloud_bull ? "Bullish" : "Bearish"), (cloud_bull ? st_bull : st_bear),
                                   htf_ema_bullish ? "Bullish" : "Bearish", htf_ema_bullish ? st_bull : st_bear,
                                   mtf_ema_bullish ? "Bullish" : "Bearish", mtf_ema_bullish ? st_bull : st_bear,
                                   show_ltf_in_tables, show_htf_in_tables, show_mtf_in_tables, show_mtf_cloud,
                                   chart_tf_disp_val, htf_tf_disp_val, mtf_tf_disp_val,
                                   tbl_label_bg, txt_label, txt_on, tbl_txt_sz, tf_order,
                                   "Direction of the EMA9/EMA20 cloud on the", "Same EMA9/EMA20 cloud logic as the LTF", "Same EMA9/EMA20 cloud logic as the")
            else if fid == "vwap" and show_fld_vwap
                r := f_add_status_row(status_tbl, r, "VWAP", "Whether price is currently Favorable or Against the live CBC direction, relative to", (not na(vwap_value) ? (vwap_bull ? "Favorable " : "Against ") + (v_diff >= 0 ? "+" : "") + str.tostring(v_diff, "#.#") : "—"), (not na(vwap_value) ? (vwap_bull ? st_bull : st_bear) : st_neutral), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "ema200" and show_fld_ema200
                r := f_add_status_row(status_tbl, r, "EMA 200", "Whether price is currently Favorable or Against the live CBC direction, relative to", (not na(ema200) ? (ema200_bull ? "Favorable " : "Against ") + (e200_diff >= 0 ? "+" : "") + str.tostring(e200_diff, "#.#") : "—"), (not na(ema200) ? (ema200_bull ? st_bull : st_bear) : st_neutral), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            // v4.54: Fib Zone — Essential-level row (own checkbox, not Full-gated, per follow-up),
            // reusing fib_50/fib_618/fib_valid already computed above alongside the Fib confluence
            // factor. v4.61 changed the green/neutral rule to fib_price_in_zone (see below) — no
            // longer tied to the Confluence Score's recency window.
            else if fid == "fibzone" and show_fld_fib_zone
                // v4.61: dropped the "50%"/"61.8%" prefixes and tightened to 1 decimal per follow-up
                // ("shorten to one decimal and get rid of 50 and 61.8 before the values"); color now
                // driven by fib_price_in_zone (simple geometric in-zone check, no recency gate) instead
                // of cf_f10_fib_touch, per follow-up ("should change to green if price is in fib zone").
                r := f_add_status_row(status_tbl, r, "Fib Zone (" + htf_tf_disp_val + ")", "50%-61.8% retracement zone of the last confirmed HTF swing high/low (same swing Liquidity Sweep uses). Green + \"IN\" whenever price is currently between the two levels (unlike the Confluence Score's own Fib factor, this row's color ignores the recency window).", not fib_valid ? "—" : str.tostring(fib_50, "#.#") + " / " + str.tostring(fib_618, "#.#") + (fib_price_in_zone ? "  IN" : ""), fib_price_in_zone ? st_bull : st_neutral, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "structure" and show_fld_structure
                r := f_add_tf_row(status_tbl, r, "Structure",
                                   f_struct_abbrev(ltf_hi_struct) + " / " + f_struct_abbrev(ltf_lo_struct), (ltf_hi_struct == "Higher High" and ltf_lo_struct == "Higher Low") ? st_bull : (ltf_hi_struct == "Lower High" and ltf_lo_struct == "Lower Low") ? st_bear : st_neutral,
                                   f_struct_abbrev(htf_hi_struct) + " / " + f_struct_abbrev(htf_lo_struct), (htf_hi_struct == "Higher High" and htf_lo_struct == "Higher Low") ? st_bull : (htf_hi_struct == "Lower High" and htf_lo_struct == "Lower Low") ? st_bear : st_neutral,
                                   f_struct_abbrev(mtf_hi_struct) + " / " + f_struct_abbrev(mtf_lo_struct), (mtf_hi_struct == "Higher High" and mtf_lo_struct == "Higher Low") ? st_bull : (mtf_hi_struct == "Lower High" and mtf_lo_struct == "Lower Low") ? st_bear : st_neutral,
                                   show_ltf_in_tables, show_htf_in_tables, show_mtf_in_tables, show_mtf_structure,
                                   chart_tf_disp_val, htf_tf_disp_val, mtf_tf_disp_val,
                                   tbl_label_bg, txt_label, txt_on, tbl_txt_sz, tf_order,
                                   "Market structure on the chart's own", "Same Higher High/Lower High/Higher", "Same Higher High/Lower High/Higher")
            // v7.17: compact Confluence Summary row, grouped with Structure (item 2 / Confluences).
            // Same underlying confluence_score/confluence_max_score/confluence_alert_threshold as the
            // full "Confluence Score" row below (item 6 group) — this is just a shorter, earlier-
            // placed duplicate for quick reference while checking item 2, not a separate calculation.
            else if fid == "confsummary" and eff_show_fld_conf_summary
                r := f_add_status_row(status_tbl, r, "Confluence Summary", "Quick-reference copy of the Confluence Score, grouped here with Structure for item 2 of the Pre-Trade Checklist. See the Confluence Score row (and the separate Confluence Factors table) for the full per-factor breakdown.", "S:" + str.tostring(confluence_score) + "/" + str.tostring(confluence_max_score), confluence_score >= confluence_alert_threshold ? st_bull : st_neutral, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "lastflip" and eff_show_fld_last_flip
                if show_ltf_in_tables
                    r := f_add_status_row(status_tbl, r, "CBC (" + chart_tf_disp_val + ") last flip", "Direction and NY timestamp of the last", (na(ltf_last_flip_t) ? "" : (ltf_last_flip_bull ? "LONG  " : "SHORT  ")) + f_fmt_ny_time(ltf_last_flip_t) + "  #" + str.tostring(ltf_bars_since_flip), na(ltf_last_flip_t) ? st_neutral : (ltf_last_flip_bull ? st_bull : st_bear), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
                if show_htf_in_tables
                    r := f_add_status_row(status_tbl, r, "CBC (" + htf_tf_disp_val + ") last flip", "Same as the LTF last-flip row (direction,", (na(htf_last_flip_t) ? "" : (htf_last_flip_bull ? "LONG  " : "SHORT  ")) + f_fmt_ny_time(htf_last_flip_t) + "  #" + str.tostring(htf_bars_since_flip), na(htf_last_flip_t) ? st_neutral : (htf_last_flip_bull ? st_bull : st_bear), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
                if show_mtf_in_tables and show_mtf_lastflip
                    r := f_add_status_row(status_tbl, r, "CBC (" + mtf_tf_disp_val + ") last flip", "Same as the LTF/HTF last-flip rows", (na(mtf_last_flip_t) ? "" : (mtf_last_flip_bull ? "LONG  " : "SHORT  ")) + f_fmt_ny_time(mtf_last_flip_t) + "  #" + str.tostring(mtf_bars_since_flip), na(mtf_last_flip_t) ? st_neutral : (mtf_last_flip_bull ? st_bull : st_bear), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "stop" and eff_show_fld_stop
                r := f_add_status_row(status_tbl, r, "LTF Trailing Stop", "'CBC': prior closed LTF candle's low/high", na(htf_trail_stop) ? "—" : str.tostring(htf_trail_stop, "#.##") + "  " + htf_stop_method, na(htf_trail_stop) ? st_neutral : (cbc ? st_bull : st_bear), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "fliplevel" and eff_show_fld_flip_level
                if show_ltf_in_tables
                    r := f_add_status_row(status_tbl, r, "Flip Level (" + chart_tf_disp_val + ")", "The exact price that would trigger the", na(ltf_flip_price) ? "—" : str.tostring(ltf_flip_price, "#.##") + "  " + (cbc[1] ? "below" : "above"), na(ltf_flip_price) ? st_neutral : (cbc[1] ? st_bear : st_bull), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
                if show_htf_in_tables
                    r := f_add_status_row(status_tbl, r, "Flip Level (" + htf_tf_disp_val + ")", "Same as the LTF Flip Level row, computed", na(htf_flip_price) ? "—" : str.tostring(htf_flip_price, "#.##") + "  " + (htf_cbc[1] ? "below" : "above"), na(htf_flip_price) ? st_neutral : (htf_cbc[1] ? st_bear : st_bull), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
                if show_mtf_in_tables and show_mtf_fliplevel
                    r := f_add_status_row(status_tbl, r, "Flip Level (" + mtf_tf_disp_val + ")", "Same as the LTF/HTF Flip Level rows,", na(mtf_flip_price) ? "—" : str.tostring(mtf_flip_price, "#.##") + "  " + (mtf_cbc[1] ? "below" : "above"), na(mtf_flip_price) ? st_neutral : (mtf_cbc[1] ? st_bear : st_bull), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "entryzone" and eff_show_fld_buysell
                // v4.40: appended the HTF Flip FVG range (htf_fvg_top/bot, same freeze block that
                // feeds the new chart zone) plus an "IN" tag when price is currently trading back
                // inside it (htf_in_flip_fvg) — folded into this existing row rather than a new one.
                r := f_add_status_row(status_tbl, r, "Entry Zone / FVG", "BRSG retracement zone anchored to the", na(brsg_zone_top) ? "—" : (htf_last_flip_bull ? "LONG  " : "SHORT  ") + str.tostring(na(brsg_zone_top) ? na : math.min(brsg_zone_top, brsg_zone_bot), "#.##") + " – " + str.tostring(na(brsg_zone_top) ? na : math.max(brsg_zone_top, brsg_zone_bot), "#.##") + (htf_fvg_exists ? ("  |  FVG " + str.tostring(htf_fvg_bot, "#.##") + "–" + str.tostring(htf_fvg_top, "#.##") + (htf_in_flip_fvg ? " IN" : "")) : ""), na(brsg_zone_top) ? st_neutral : (htf_last_flip_bull ? st_bull : st_bear), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            // v7.17: Next Target/Stop Levels rows, grouped with Entry Zone (items 3/4). Direction
            // comes from the live LTF CBC state (cbc) via f_next_two_levels() above — targets are the
            // nearest 2 levels on the side CBC favors, stops the nearest 2 on the opposite side, each
            // shown with distance in points. Pool is 24 core static levels (see f_next_two_levels
            // comment) — Order Blocks/EQH-EQL deliberately excluded this round.
            else if fid == "next3" and eff_show_fld_next_levels
                r := f_add_status_row(status_tbl, r, "Next Target Levels", "Nearest 2 levels in the direction the live CBC currently favors (item 3 — Entry/Target), with distance in points. Pool: YDH/YDL, PMH/PML, Opening Range sessions, LTF/HTF/MTF swing pivots, EMA 200, classic Pivot Points.", nl_target_txt, cbc ? st_bull : st_bear, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "next4" and eff_show_fld_next_levels
                r := f_add_status_row(status_tbl, r, "Next Stop Levels", "Nearest 2 levels against the direction the live CBC currently favors (item 4 — Risk limit/stop structure), with distance in points. Same level pool as Next Target Levels.", nl_stop_txt, cbc ? st_bear : st_bull, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "chart" and eff_show_chart_info_tbl
                r := f_add_status_row(status_tbl, r, "Chart", "The symbol/ticker this chart is on, plus", syminfo.ticker + "  " + chart_tf_disp_val, st_neutral, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "pivltf" and eff_show_ltf_pivots_tbl
                r := f_add_status_row(status_tbl, r, "Pivot (" + chart_tf_disp_val + ")", "Most recent LTF (chart-timeframe) pivot", (na(l_last_hi) and na(l_last_lo)) ? "—" : "H " + (na(l_last_hi) ? "—" : str.tostring(l_last_hi, "#.##")) + "  /  L " + (na(l_last_lo) ? "—" : str.tostring(l_last_lo, "#.##")), st_neutral, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "pivhtf" and eff_show_htf_pivots_tbl
                r := f_add_status_row(status_tbl, r, "Pivot (" + htf_tf_disp_val + ")", "Most recent HTF pivot high and pivot low", (na(h_last_hi) and na(h_last_lo)) ? "—" : "H " + (na(h_last_hi) ? "—" : str.tostring(h_last_hi, "#.##")) + "  /  L " + (na(h_last_lo) ? "—" : str.tostring(h_last_lo, "#.##")), st_neutral, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            else if fid == "pivmtf" and eff_show_mtf_pivots_tbl
                r := f_add_status_row(status_tbl, r, "Pivot (" + mtf_tf_disp_val + ")", "Most recent MTF pivot high and pivot low", (na(m_last_hi) and na(m_last_lo)) ? "—" : "H " + (na(m_last_hi) ? "—" : str.tostring(m_last_hi, "#.##")) + "  /  L " + (na(m_last_lo) ? "—" : str.tostring(m_last_lo, "#.##")), st_neutral, tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
            // v4.48: combined row for all Confluence Score factors — reuses
            // confluence_score/confluence_max_score/confluence_alert_threshold, already computed
            // above. v4.55: collapsed back down to ONE simple row per follow-up ("Info seems
            // redundant... distinguish the counted ones") — the packed-string breakdown (rows 1-2) and
            // the Info row are both gone. The full per-factor breakdown, now with real per-factor
            // color instead of packed text, lives in the new dedicated Confluence Factors cells table
            // (f_render_confluence_cells() below) — see confluence_use_cells_table. This row just
            // shows the number.
            else if fid == "confluence" and eff_show_fld_confluence
                // v4.101 — same gold "box" flash as f_render_confluence_cells()'s Score cell, for the
                // one bar confluence_same_score_diff_mask is true (score unchanged from the last
                // firing, but a different combination of factors produced it this time).
                r := f_add_status_row(status_tbl, r, "Confluence Score", "Live score across all enabled confluence factors. Green when at/above the alert threshold. See the separate Confluence Factors table for the per-factor breakdown.", "S:" + str.tostring(confluence_score) + "/" + str.tostring(confluence_max_score), confluence_same_score_diff_mask ? st_highlight : (confluence_score >= confluence_alert_threshold ? st_bull : st_neutral), tbl_label_bg, txt_label, txt_on, tbl_txt_sz)
    true
 
// v44: bug fix inside f_ats_draw_setup() (RE10056 runtime error, "Invalid value of the 'size'
// argument ('Small')") -- its label.new() call was passing the raw text_size STRING parameter
// (e.g. "Small") directly as size=, instead of routing it through f_table_text_size() to get the real
// size.* enum value first, same as every other size-taking export in this file already does. One-line
// fix: size=txt_size -> size=f_table_text_size(txt_size). Pre-existing since v7.46 (this function's
// own creation); simply never reached runtime until the main script's token count finally landed under
// budget (v7.49) and the script actually ran far enough to draw this label.
 
// v45: new export for the Auto Trade Setup manual Stop/Target level picker -- per direct follow-up
// ("i wanted the red box to be drawn as a trade setup take profit and stop loss ... as long as I can
// pick from the table"). Maps one of the Pivot Points table's level NAMES (as picked from a settings
// dropdown, e.g. "S2", "HTF EQH") to that level's current price -- pure switch on a string, no
// CBC-internal state, all 18 candidate values passed in as plain float parameters (same pool
// f_ats_build_candidates already draws from). "Automatic (nearest)" is handled at the main-script call
// site (na is returned there without ever reaching this function) so this function's own switch only
// needs to cover the 18 real level names, falling back to na for anything unrecognized.
export f_ats_level_by_name(string name, float r3, float r2, float r1, float pp, float s1, float s2, float s3, float ydh, float ydl, float pmh, float pml, float htfPivH, float htfPivL, float htfEqh, float htfEql, float ltfPivH, float ltfPivL, float ema200v, float vwapv) =>
    switch name
        "R3" => r3
        "R2" => r2
        "R1" => r1
        "PP" => pp
        "S1" => s1
        "S2" => s2
        "S3" => s3
        "YD-H" => ydh
        "YD-L" => ydl
        "PMH" => pmh
        "PML" => pml
        "HTF Piv-H" => htfPivH
        "HTF Piv-L" => htfPivL
        "HTF EQH" => htfEqh
        "HTF EQL" => htfEql
        "LTF Piv-H" => ltfPivH
        "LTF Piv-L" => ltfPivL
        "EMA 200" => ema200v
        "VWAP" => vwapv
        => na
 
// v62: f_ats_compute_trigger() -- CE10295 relief round 4. v7.83's comment-only trim did NOT clear the
// error (user-confirmed), which settles that round's open question: CE10295 counts actual top-level/
// main-body CODE, including everything nested inside a top-level `if` block -- comments never counted.
// The main script's ~50-line trigger `if` block (level-pick fallbacks, stop/target/stop2/target2 math,
// handle-snap overrides) was still sitting directly in the main body even after f_ats_draw_setup()/
// f_ats_handle_snap()/etc. were already offloaded, because an `if` block's contents are NOT a function
// body -- only wrapping the whole sequence in one function call actually shrinks main-body size, exactly
// per the compiler's own hint ("Try wrapping code in functions"). Takes the two trigger conditions, the
// cooldown flag, entry price, all 4 level-pick strings, the candidate pool, every pivot value the level
// picker needs, the flip-candle fallback prices, all 4 drag handles, and the two Show TP2/SL2 toggles;
// writes entry/stop/target/stop2/target2 directly into the caller's `out_call` float[5] array (arrays are
// Pine's only way around "exported functions can't return a tuple" -- convention #19), and returns one
// bool (whether a new setup actually fired) so the main script can still latch its own cooldown timer.
export f_ats_compute_trigger(bool trigger_long, bool trigger_short, bool cooldown_ok, float entry, string stop_pick, string target_pick, string stop2_pick, string target2_pick, float[] cand, float r3, float r2, float r1, float pp, float s1, float s2, float s3, float ydh, float ydl, float pmh, float pml, float htfPivH, float htfPivL, float htfEqh, float htfEql, float ltfPivH, float ltfPivL, float ema200v2, float vwapv2, float flip_lo, float flip_hi, float tp1_handle, float sl1_handle, float tp2_handle, float sl2_handle, bool show_tp2, bool show_sl2, float[] out_call) =>
    bool new_setup = false
    if (trigger_long or trigger_short) and cooldown_ok
        bool ats_long = trigger_long
        float stop_manual = stop_pick == "Automatic (nearest)" ? na : f_ats_level_by_name(stop_pick, r3, r2, r1, pp, s1, s2, s3, ydh, ydl, pmh, pml, htfPivH, htfPivL, htfEqh, htfEql, ltfPivH, ltfPivL, ema200v2, vwapv2)
        float target_manual = target_pick == "Automatic (nearest)" ? na : f_ats_level_by_name(target_pick, r3, r2, r1, pp, s1, s2, s3, ydh, ydl, pmh, pml, htfPivH, htfPivL, htfEqh, htfEql, ltfPivH, ltfPivL, ema200v2, vwapv2)
        float stop = not na(stop_manual) ? stop_manual : (ats_long ? f_ats_nearest_below(entry, cand) : f_ats_nearest_above(entry, cand))
        if na(stop)
            stop := ats_long ? flip_lo : flip_hi
        float target = not na(target_manual) ? target_manual : (ats_long ? f_ats_nearest_above(entry, cand) : f_ats_nearest_below(entry, cand))
        float tol = f_aplus_pivot_dist(0.0)
        if target_pick == "Automatic (nearest)"
            target := f_ats_handle_snap(tp1_handle, target, tol, ats_long, cand)
        if stop_pick == "Automatic (nearest)"
            stop := f_ats_handle_snap(sl1_handle, stop, tol, not ats_long, cand)
        float stop2_manual = stop2_pick == "Automatic (nearest)" ? na : f_ats_level_by_name(stop2_pick, r3, r2, r1, pp, s1, s2, s3, ydh, ydl, pmh, pml, htfPivH, htfPivL, htfEqh, htfEql, ltfPivH, ltfPivL, ema200v2, vwapv2)
        float target2_manual = target2_pick == "Automatic (nearest)" ? na : f_ats_level_by_name(target2_pick, r3, r2, r1, pp, s1, s2, s3, ydh, ydl, pmh, pml, htfPivH, htfPivL, htfEqh, htfEql, ltfPivH, ltfPivL, ema200v2, vwapv2)
        float stop2 = not show_sl2 ? na : not na(stop2_manual) ? stop2_manual : (ats_long ? f_ats_nearest_below(stop, cand) : f_ats_nearest_above(stop, cand))
        float target2 = not show_tp2 ? na : not na(target2_manual) ? target2_manual : (ats_long ? f_ats_nearest_above(target, cand) : f_ats_nearest_below(target, cand))
        if show_tp2 and target2_pick == "Automatic (nearest)" and not na(target2)
            target2 := f_ats_handle_snap(tp2_handle, target2, tol, ats_long, cand)
        if show_sl2 and stop2_pick == "Automatic (nearest)" and not na(stop2)
            stop2 := f_ats_handle_snap(sl2_handle, stop2, tol, not ats_long, cand)
        if not na(stop) and not na(target) and stop != entry and target != entry
            new_setup := true
            array.set(out_call, 0, entry)
            array.set(out_call, 1, stop)
            array.set(out_call, 2, target)
            array.set(out_call, 3, stop2)
            array.set(out_call, 4, target2)
    new_setup
 
// v46: republish-only bump, per direct request to force TradingView to treat this as a fresh publish
// after a suspected Pine Editor paste mismatch on the prior v45 upload (CE10017 "missing enclosing
// character" reported on text that doesn't exist anywhere in the actual v45 source — see the session
// handoff doc for the full back-and-forth). No functional change: zero exports touched, zero logic
// changed, this comment block is the only diff from v45.
 
// v47: f_ats_draw_setup() restyled per direct request/annotated screenshots referencing TradingView's
// native "Long/Short position" Forecasting drawing tool (split green/red box, entry through the
// middle). No scriptable API exists for that native tool, so this is the closest Pine approximation:
// dropped the rr_label text block ("LONG setup / Entry.. / Stop.. / Target.. / R:R..") so the setup is
// just the clean reward_box/risk_box/entry_line/stop_line/target_line shape, no info text. See the
// v47 comment directly above f_ats_draw_setup() for the full explanation. Signature unchanged at the
// time (txt_size param kept but now unused, to avoid a call-site mismatch) — superseded by v48 below.
 
// v48: TradingView compile warning CE10237 ("Unused argument 'txt_size'... Ensure that it utilizes all
// arguments") on the v47 signature — fixed by removing the parameter outright rather than leaving a
// dead one in place. `f_ats_draw_setup()` is now `(float entry, float stop, float target, color
// reward_col, color risk_col, bool is_long)`, 6 params (was 7). Main script's call site updated to
// match (6 args, `trade_setup_txt_size` dropped), and that now-orphaned "Label text size" input
// (`trade_setup_txt_size`) was removed from the main script entirely, since nothing consumes it
// anymore — see the v7.57 changelog block in the main script.
 
// v49: the SAME CE10237 warning, this time on `is_long` — v47's label removal left this parameter
// dead too (it used to pick "LONG"/"SHORT" label text and color), just not caught in the v48 pass
// since only `txt_size` had been reported yet. `f_ats_draw_setup()` is now `(float entry, float stop,
// float target, color reward_col, color risk_col)`, 5 params (was 6). Main script's call site updated
// to match (5 args) — the `ats_long` local variable itself stays in the main script, since it's still
// read elsewhere in that same `if` block for the stop/target direction logic; only the now-unneeded
// argument to THIS call was dropped. See the v7.58 changelog block in the main script.
 
// v50: RUNTIME BUG FIX for RE10039 "Column N is out of table bounds" in f_render_pivot_table(),
// reported at bar 22060 needing column 26 when the table had only been created with 26 columns.
// Root cause: `piv_tbl` (a `var table`, created exactly once, guarded by `if na(piv_tbl)`) had its
// column count fixed at whatever `piv_final_n` happened to be on the FIRST bar it drew
// (`table.new(f_status_pos(position), math.max(1, piv_final_n), 3, ...)`) — but `piv_final_n` is the
// live count of currently-enabled, non-na Pivot Points levels (BRSG zone visibility, R2/R3/S2/S3
// auto-escalation, HTF EQH/EQL only existing once formed, etc. — see v7.38/v7.41), so it can grow on
// a LATER bar past whatever the table was first sized for. Fix: allocate `piv_tbl` with a FIXED
// column count of 28 (27 candidate levels, indices 0-26 across pivT_price_arr/pivT_labels/
// pivT_enabled/pivT_lblcol, plus 1 for the PRICE row — piv_final_price/piv_final_label/
// piv_final_lblcol are already sized 28 for exactly this reason) instead of sizing to `piv_final_n`
// at creation time. This is the true upper bound `piv_final_n` can ever reach on any bar, for any
// combination of toggles, so the mismatch can't recur. Unused trailing columns on a sparser bar are
// simply never written to by the render loop — `table.new()` leaves an unset cell blank, no visual
// side effect. See the v7.60 changelog block in the main script for the full writeup.
 
// v51: `f_render_pivot_table()`'s PRICE row (label, Long/Short text, diff sign, green/red color) now
// follows the `htf_bull` parameter instead of `ltf_bull` in all 4 remaining spots
// (price_lbl_txt/p_diff/p_price_col_bg/p_row1_txt) — the sort order a few lines above was already keyed
// off `htf_bull` (unchanged since v7.35), so the whole table's "pivot price direction" concept is now
// consistently one direction instead of two. Signature left with `ltf_bull` still a parameter (still
// receiving `cbc` from the call site) but no longer read inside the function body. Main script's call
// site also switched its `htf_bull` ARGUMENT from `cf_f2_htf_bull` (a confluence-score variable that
// blends in the live, still-forming HTF bar under certain conditions) to `htf_dir_bull_now` (the
// confirmed, last-CLOSED-HTF-bar direction). See the v7.63 changelog block in the main script for the
// full writeup, including the direct-request quotes.
 
// v52: CE10237 FIX — "unused argument 'ltf_bull'", the SAME warning class that hit `f_ats_draw_setup()`
// twice at v7.57/v7.58 (see those changelog blocks), now on `f_render_pivot_table()`. v51 above switched
// every use inside the function from `ltf_bull` to `htf_bull` but left `ltf_bull` sitting in the
// signature with nothing left reading it — should have been caught by convention #33 ("remove an unused
// parameter in the SAME round it becomes unused") but wasn't, this time on the first pass rather than a
// missed second warning. Reported via the TradingView Pine Editor's "Pine Script compilation error"
// modal, single word "fix". Fix: removed `ltf_bull` from `f_render_pivot_table()`'s signature outright
// (61→60 params). Main script's call site updated to match — dropped the trailing `cbc` argument that
// used to fill that slot (60 args now, same order otherwise). No other behavior change — `cbc` itself
// (the main-script local variable) is untouched and still used elsewhere in the file. See the v7.64
// changelog block in the main script for the full writeup.
 
// v53: `f_ats_build_candidates()` gained NY/London/Asia session Opening Range High/Low as candidates —
// 6 new price/6 new show-toggle parameters (ny_orh/sh_ny_orh/ny_orl/sh_ny_orl, ln_orh/sh_ln_orh/
// ln_orl/sh_ln_orl, as_orh/sh_as_orh/as_orl/sh_as_orl) and 6 matching `if sh_x and not na(x)` push
// blocks, same pattern as every other candidate source in the function. OR-H/OR-L had simply never
// been wired into this function's parameter list before, unlike YDH/YDL and PMH/PML which already
// were. BRSG stays excluded, per the function's existing comment and the user's explicit answer when
// asked. Main script's call site updated to pass the same ORHigh_NY/ORLow_NY/ORHigh_LN/ORLow_LN/
// ORHigh_AS/ORLow_AS values and show_pivot_*_or* toggles the Pivot Points table itself already uses,
// so a session's OR only becomes a candidate when that session's OR row is enabled to show on the
// chart. Signature grew from 26 to 38 parameters; call site argument count matches. See the v7.67
// changelog block in the main script for the full writeup, including the direct-request quotes.
 
// v54: new helper `f_fmt_ny_time_hm(int t)` -- bare "H:MM" NY-time formatter (no month/day, no seconds,
// no " ET"), purpose-built for a narrow table cell where the existing f_fmt_ny_time()/
// f_fmt_ny_time_sec() are too verbose. `f_render_pivot_table()`'s Price row row-1 cell (previously the
// plain word "Long"/"Short") now reads `(htf_bull ? "L " : "S ") + f_fmt_ny_time_hm(htf_last_flip_t_open)`
// instead -- the direction letter plus the confirming HTF candle's own OPEN time (candles are
// conventionally named by their open time, e.g. "the 9:30 candle"). New parameter
// `int htf_last_flip_t_open` added to the signature (60→61 params); main script's call site passes a
// new sibling var of the same name, latched from `sig_htf_t_open` at the same point the existing
// `htf_last_flip_t` (close-time) latches from `sig_htf_t_close` -- kept separate since that existing
// var's close-time meaning, used elsewhere (Status table/Historical Bar Panel/alert email), was not
// asked to change. See the v7.70 changelog block in the main script for the full writeup.
 
// v55: `f_fmt_ny_time_hm(t)` (v54's single-time "H:MM" helper) REPLACED by `f_fmt_ny_time_range(t_open,
// t_close)` -- a compact open-close time RANGE formatter, per direct follow-up on v54's own display
// ("make it 9:30-45 or in another case 9:45-10"): same-hour close repeats just the close minutes
// ("9:30-45"), a close rolling into a new hour shows that hour instead, dropping ":00" when the close
// lands exactly on the hour ("9:45-10"). `f_render_pivot_table()`'s Price row row-1 cell now reads
// `(htf_bull ? "L " : "S ") + f_fmt_ny_time_range(htf_last_flip_t_open, htf_last_flip_t_close)` instead
// of v54's single-open-time display. New parameter `int htf_last_flip_t_close` added to the signature
// (61→62 params) alongside v54's existing `htf_last_flip_t_open`; main script's call site passes the
// EXISTING `htf_last_flip_t` var (already tracking that same bar's close time for other display
// purposes) into the new slot -- no new main-script var needed this round. See the v7.71 changelog
// block in the main script for the full writeup.
 
// v56: chart-level label overlap handling -- two brand-new exports, no existing signature changed.
// `f_level_group_leader(float[] prices, float dist) => int[]` unions price entries within `dist`
// points of each other via chained relaxation passes over all pairs, returning each entry's group-
// leader index (self-leader = singleton or group representative). `f_level_merged_text(string[] names,
// float price, bool show_name, bool show_price) => string` builds the combined label text for a merged
// group (e.g. "PMH / LN ORB-H 4308.4"), honoring the same Show-Name/Show-Price toggles as the existing
// `f_level_label_text()`. Both called from a new post-pass block in the main script, added after its
// existing ORB NY/LN/AS label block -- registers every currently-visible level label (~16-22 of them:
// YDH/YDL/YDC, PMH/PML, 7 pivots, LN-H/L, AS-H/L, 6 ORB levels), groups them by price proximity, and
// `label.set_text()`'s a merged group's leader to the combined text while blanking every other member.
// Distance passed in from a new main-script input, `level_overlap_dist_override` (0 = auto), fed
// straight into the EXISTING `f_aplus_pivot_dist()` export rather than duplicating its MNQ=50/else=5
// auto-by-symbol logic in a third function. See the v7.72 changelog block in the main script for the
// full writeup, including the direct-request quotes and the screenshots that prompted it.
 
// v57: `f_ats_draw_setup()` gained a second, optional TP2/SL2 zone -- 5 new trailing params
// (show_lvl2/stop2/target2/reward2_col/risk2_col), per direct request ("add an option for drawing the
// setup as is but also include one more level for tp and sl - maybe a slightly different shading for
// the tp1 to tp2 and sl1 to sl2"), clarified via AskUserQuestion: TP2/SL2 come from the next-nearest
// qualifying candidate PAST TP1/SL1 in Automatic mode (or their own manual level pickers), and the
// feature is a new toggle, default ON. The function's original 5 params and their drawing are
// completely unchanged -- TP2/SL2 are two NEW persistent box/line pairs (reward_box2/risk_box2/
// target2_line/stop2_line), drawn only when show_lvl2 is true and that level actually resolved (not
// na); a caller passing show_lvl2=false gets byte-for-byte the original single-level drawing. Signature
// grew from 5 to 10 parameters. See the v7.74 changelog block in the main script for the full writeup.
 
// v58: new export `f_ats_handle_snap(float handle, float current, float tol, bool want_above, float[]
// cand) => float` -- CE10295 "main body of the script is too long" relief, reported on v7.76's
// draggable drag-to-snap TP1/SL1/TP2/SL2 handles (4 near-identical multi-line override blocks that had
// been added directly to the main script's top-level scope). Collapses each block's "is the handle
// active, and if so what pivot does it snap to" logic into one library call -- same technique already
// used throughout this file for CE10117 relief (move pure-parameter, no-CBC-state logic to the
// library), and literally what CE10295's own message suggests ("try wrapping code in functions"). No
// existing export's signature changed. Pure relocation, no behavior change from what v7.76 shipped. See
// the v7.77 changelog block in the main script for the full writeup.
 
// v59: `f_ats_draw_setup()` gained 4 new persistent labels -- "TP1"/"SL1"/"TP2"/"SL2" tags drawn
// directly on their respective lines, per direct request ("mark tp1 and tp2 and sl1 and sl2 on the
// lines"). Delete-and-recreate on the SAME call that draws the box/lines, so a label only ever appears
// together with a genuinely new setup draw (this function has exactly one caller: the main script's
// cooldown-gated trigger block) -- no separate "on indicator load" path exists to guard against.
// Signature UNCHANGED (no new parameters) -- entry/stop/target/stop2/target2 were already available.
// Deliberately minimal per-line tags, not a revival of the v7.56-removed combined `rr_label`. See the
// v7.79 changelog block in the main script for the full writeup.
 
// v60: `f_ats_draw_setup()` gained a new FIRST parameter, `bool new_setup`, and now has to be called
// every bar (not just on a trigger bar) so it can check the active setup's TP2/SL2 against the current
// bar's high/low even on bars where nothing new fires. `new_setup=true` reproduces the exact v59 draw
// behavior (all objects, extend=extend.right); `new_setup=false` is a routine per-bar check that, once
// the active setup's TP2 or SL2 is breached, freezes every object's right edge at the breach bar
// (extend.none + set_right/set_x2) and never re-extends until the next genuinely new setup redraws.
// Signature grew from 10 to 11 parameters. Per direct request ("stop trade setup extending to the right
// when the price breaks tp2 or sl2"). See the v7.80 changelog block in the main script for the full
// writeup, including the call-site restructuring this required.
 
// v61: new export `f_ats_draw_handles(float tp1_h, float sl1_h, float tp2_h, float sl2_h, bool
// show_tp2, bool show_sl2) => void` -- draws a small, uniquely-colored "◆ TPx/SLx HANDLE" label right on
// each of the 4 drag-handle input.price() lines whenever that handle is active (non-zero), so the 4
// otherwise-identical draggable lines can finally be told apart on the chart, and skips it entirely
// while a handle is still at its 0.0 default (nothing to label). Fixes the reported "where is the
// handle to drag? i tried to drag sl2 higher and tp2 went way down" -- see the v7.81 changelog block in
// the main script for the full root-cause writeup. No existing export's signature changed.
 
// v62: new export `f_ats_compute_trigger(...)` -- CE10295 relief round 4, after v7.83's comment-only
// trim was reported still showing the error. Settles that round's open question: CE10295 counts actual
// top-level/main-body code (an `if` block's contents included), not comments. Wraps the ENTIRE trigger-
// to-array-fill sequence (level-pick fallbacks, stop/target/stop2/target2 math, all 4 handle-snap
// overrides) that used to sit inline in the main script's ~50-line trigger `if` block into one function
// call. Writes results into the caller's `out_call` float[5] array by reference (arrays sidestep "no
// tuple return" -- convention #19) and returns a single bool. See the v7.84 changelog block in the main
// script for the full writeup and the call-site restructuring this enabled.

← 返回列表