Time and Price

Kantisam0 · study · 2052 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
indicator("Time and Price", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 300)
// Time and Price V1.00 (2026-11-20): combine the user-supplied current Time
// build with Price V1.49, including its fixed top-right notes panel. Time
// calculations and Price spacing/scaling are unchanged. The combined Price
// history control is bounded to preserve drawing capacity for Time.
// Build V51.56 (2026-11-18): extend the shared IN H/L projection template
// to completed Quarterly, Weekly, and custom 8H inside ranges. Quarter IN
// levels span the next quarter, Week IN levels span the next week, and custom
// 8H IN levels span the next custom 8H block. No new style inputs are added.
// Build V51.55 (2026-11-11): replace the four context-specific IN H/L
// visibility checkboxes with one shared Show IN H/L extensions control.
// The single control and shared style apply to every box and 1H session.
// Build V51.54 (2026-11-11): add independent text-size controls for Year,
// Month, Day, weekday, session-hour, and 1H signal labels. Place each 1H
// signal inside its own completed hourly H/L range near that range's bottom.
// Build V51.53 (2026-11-11): remove Hour 0 from every named session.
// Asia, London, and New York now use the same four-hour Hours 1-4 window
// on all 1m-15m session displays, ranges, separators, labels, and projections.
// Build V51.52 (2026-11-11): replace the four separate IN-extension styles
// with one shared color, width, and line style for every Year, Month, Day,
// and 1H IN high/low projection. Context-specific visibility remains separate.
// Build V51.51 (2026-11-11): fully decouple signal-label text from Monday.
// Add explicit signal text color and size controls used by every signal label;
// Monday color now affects only the Monday weekday plot.
// Build V51.50 (2026-11-11): remove the complete 15m range/separator display
// from the 1m section. Give Year, Month, and Day boxes independent borders and
// give every IN projection context its own color, width, and line style.
// Build V51.49 (2026-11-11): add a TEMPLATES section for projecting every
// qualifying IN signal's high/low across its active Year, Month, or Day black
// box, or across the full exact-1m named-session timing for 1H IN signals.
// Remove Monday range/separator overrides; Monday now changes text color only.
// Build V51.48 (2026-11-11): simplify exact-15m session shading to hours 1-4
// for Asia, London, and New York. Exact 1m retains the complete hour 0-4
// session, labels, signals, ranges, and calculations without timing changes.
// Build V51.47 (2026-11-11): keep hour numbers in one clean row beneath the
// session, matching weekday-label styling, and place hour 1-3 signal text
// inside the shaded session box near its lower edge like black-box signals.
// Build V51.46 (2026-11-11): combine each numbered hour and its optional
// signal into one centered two-line label. Remove the separate signal row;
// hours 0 and 4 remain number-only while hours 1-3 may add a signal below.
// Build V51.45 (2026-11-11): in bounded mode, give every completed numbered
// hour both a left and right separator using that same hour's high/low. This
// closes each hourly range cleanly instead of borrowing the next hour's span.
// Build V51.44 (2026-11-11): when 1m separator extension is off, bound each
// numbered separator to its own completed 1H high/low instead of stretching
// every separator to the combined session high/low. Full-height mode is unchanged.
// Build V51.43 (2026-11-11): show completed 1H signal labels only beneath
// session hours 1, 2, and 3. Hours 0 and 4 retain their normal visuals but
// receive no signal label. Restore all four signal types, including Day 0.
// Build V51.42 (2026-11-11): limit exact-1m completed 1H signal labels to
// IN, OT, and CIB. Day 0 remains enabled for Daily, Monthly, and Yearly ranges.
// Build V51.41 (2026-11-11): add non-repainting IN, OT, Day 0, and CIB labels
// to each section's parent range: 1H on exact 1m, Daily on 15m-4H (including
// 1H), Monthly on the Daily section, and Yearly on the Weekly section.
// Build V51.40 (2026-11-11): extend each named 1m session one hour earlier
// and add centered hour 0 before the existing hours 1-4. Include hour 0 in
// the current-session 1H high/low and prior-close visuals.
// Build V51.39 (2026-11-11): remove the narrow Monday Opening Range feature.
// Add optional Monday styling to the existing full trading-day range and its
// two day borders, with independent checkboxes and shared color/width/style.
// Build V51.38 (2026-11-11): on exact 1m, retain only the newest active/recent
// named session. Delete the prior session shade, numbered separators/labels,
// completed 1H H/L ranges, and prior-1H-close lines when a new session begins.
// The 15m chart keeps its existing three-session shading history.
// Build V51.37 (2026-11-11): remove the complete prior-15m-close feature,
// including its inputs, data field, projection lines, and retained line array.
// Build V51.36 (2026-11-11): make the numbered 1-2-3-4 hour separators use
// the 1H range color, width, and style, matching every other range/separator
// pair. Remove the redundant standalone hour-separator style controls.
// Build V51.35 (2026-11-11): add a configurable 15-minute Opening Range to
// the 15m-4H section, including independent range/separator controls and a
// Monday-only mode. The selected market timezone handles DST automatically.
// Build V51.34 (2026-11-11): standardize every settings section. Each range
// family now begins with independent Show ranges and Show separators toggles,
// followed by count/color/width/style. Move extend and black-box controls last.
// Build V51.33 (2026-11-11): add one black rolling three-range envelope to
// each Year, Month, and Day context. Each outline spans the current forming
// range plus the two immediately previous ranges and tracks their combined H/L.
// Build V51.32 (2026-11-11): reorganize all visual inputs into Weekly, Daily,
// 15m, and 1m chart-timeframe sections. Route intermediate timeframes to the
// matching section and give every section its own full-height separator switch.
// Build V51.31 (2026-11-11): restore completed 1H high/low ranges and
// prior-1H-close projections on exact 1m, but only for numbered Asia, London,
// and New York session hours 1-4. The old 1H boundary borders remain hidden
// on 1m because V51.27's full-height numbered separators replace them.
// Build V51.30 (2026-11-11): on the exact 1-minute chart, suppress Time's
// completed historical 1H high/low ranges, their boundary separators, and
// prior-1H-close projections. Keep the session hours labeled 1-2-3-4 intact.
// Build V51.29 (2026-11-09): match the 1-2-3-4 hour labels to the clean
// weekday-label style: transparent background, black text, and tiny size.
// Build V51.28 (2026-11-09): remove the complete legacy 30-minute opening-box
// system. Delete its inputs, 5m request, local and 1H renderers, and box state.
// Keep the V51.27 session colors and numbered 1-2-3-4 hours unchanged.
// Build V51.27 (2026-11-09): merge Sharing's four-hour Asia, London, and
// New York session colors into Time on exact 15m and 1m charts. Add the
// numbered 1-2-3-4 session-hour boundaries on exact 1m only. All existing
// Time calculations, requests, ranges, OB boxes, and controls are unchanged.
// Build V51.26 (2026-11-04): apply explicit clock-hour alignment universally.
// Every asset now builds :00-:00 buckets in its own exchange timezone and
// rejects incomplete opening/closing blocks before any hourly visual is drawn.
// Build V51.25 (2026-11-04): apply explicit Chicago clock-hour alignment to
// every agricultural root, including livestock. The 08:30-09:00 CT opening
// half hour cannot publish an hourly range, separator, or prior-hour close.
// Non-ag instruments retain native 60m timing.
// Build V51.24 (2026-11-04): scope explicit clock-hour alignment to grains.
// Livestock already behaves correctly with its native day-session rotations,
// so HE/GF/LE and all non-grain instruments retain native 60m bucket timing.
// Build V51.23 (2026-11-04): align the 1m-derived hourly engine to explicit
// Chicago clock hours (:00-:00), not exchange-session-aligned 60m buckets.
// The 08:30 reopen therefore cannot create an hourly boundary or pseudo-hour.
// Build V51.22 (2026-11-04): validate completed hourly ranges from actual 1m
// coverage. Some exchange-partial 60m candles report nominal clock-hour times;
// require source bars near both hour boundaries so 30m/45m blocks are rejected.
// Build V51.21 (2026-11-04): reject partial native-60m candles from hourly
// visuals. Use the requested candle's actual start and close times, and draw
// hourly ranges, separators, and prior closes only when duration is exactly 1H.
// Build V51.20 (2026-11-04): make agricultural weekday labels deterministic.
// Print only on the single 15m bar containing the logical trading-day midpoint
// and guard each period end so no agricultural day can publish twice.
// Build V51.19 (2026-11-04): remove the agricultural hourly special case.
// Every instrument now uses the same native completed-60-minute candles for
// hourly ranges, separators, and prior-hour closes.
// Build V51.18 (2026-11-04): make wheat-family hourly visuals use the same
// native completed-60-minute candles as regular futures. ZW, KE, and MZW no
// longer use the custom day-session hourly accumulator; other logic is unchanged.
// Build V51.17 (2026-11-03): define one logical grain trading day from the
// 19:00 CT Globex reopen through the following 13:20 CT close. Center exactly
// one weekday label in that span instead of accepting separate native midpoints
// for the overnight and daytime session segments.
// Build V51.16 (2026-11-03): center each short-session weekday label between
// the full exchange-defined Daily boundaries, matching regular futures. Keep
// only one label per day while leaving price sampling tied to the day session.
// Build V51.15 (2026-11-03): prevent duplicate weekday labels on short-session
// products. Their labels now use only the Chicago day-session midpoint and no
// longer fall back to the exchange-native overnight midpoint outside that session.
// Build V51.14 (2026-11-03): anchor the grain Asia OB to the actual 19:00 CT
// Globex reopen. A fixed 09:00 Tokyo box occurs at 18:00 CT after U.S. DST ends,
// before grain trading resumes, so it cannot produce an OB on winter charts.
// Grain London and U.S. OBs retain 08:00 London and 08:30 Chicago anchors.
// Build V51.13 (2026-11-03): restore Tokyo and London opening boxes for grain
// futures, whose overnight Globex session trades through those global windows.
// Keep livestock day-session-only so unavailable foreign-session OBs disappear
// naturally from missing bars rather than from a blanket agriculture exclusion.
// Build V51.12 (2026-11-03): preserve the regular-futures Daily presentation
// for short-session products. The Chicago day session still owns sampled H/L
// and close values, while Daily ranges, prior closes, and their single shared
// boundary use the full exchange-defined trading-day geometry. Keep 1H/15m
// rotations anchored at 08:30 CT and retain the U.S.-only OB treatment.
// Build V51.11 (2026-11-03): add automatic Chicago day-session handling for
// grain and livestock futures. Daily, 1H, 15m, close, separator, and U.S. OB
// visuals now exclude off-session data; 1H/15m buckets anchor at 08:30 CT.
// Foreign OBs and generic custom-8H ranges are suppressed on these products.
// Build V51.10 (2026-10-31): remove both EMA systems completely. Time now
// contains no EMA inputs, calculations, security requests, or plotted lines.
// Build V51.09 (2026-10-31): make the exact Daily chart reuse the exact-8H
// higher-timeframe presentation. Daily now shares the 8H EMA visibility,
// completed Weekly H/L ranges and separators, and prior-Monthly-close
// projections. Monthly visuals were already shared; inputs stay unified.
// Build V51.08 (2026-10-30): connect confirmed higher-timeframe EMA samples
// across lower-timeframe chart bars instead of repeating them as stair steps.
// EMA timeframe, source, length, confirmed values, and lookahead remain intact.
// Build V51.07 (2026-10-30): draw both the opening and closing separators for
// every retained completed 1H range on Entry charts so the range is enclosed.
// Build V51.06 (2026-10-30): move the prior-Daily-close controls directly
// below the Daily H/L and separator controls in the 15-minute section, matching
// the Monthly range/close organization used by the 8-hour section.
// Build V51.05 (2026-10-30): place separator ownership beside every H/L range
// family in its timeframe section. Each separator reuses its matching range's
// color, width, style, and retained-history count; remove the global appearance
// inputs while preserving the optional full-height extension control.
// Build V51.04 (2026-10-30): remove the duplicate structural Monthly
// separator layer from Daily and 8H charts. The Monthly H/L range visuals keep
// their own boundaries, styling, routing, and retained-history controls.
// Build V51.03 (2026-10-30): remove the three Monthly separator appearance
// inputs. Applicable Monthly boundaries now use a fixed black, width-1, solid
// style while preserving their existing chart routing and range geometry.
// Build V51.02 (2026-10-30): remove the four Entry chart-timeframe routing
// rows and the completed-1H-separator checkbox. Entry 1H ranges, separators,
// and closes now route automatically to every intraday chart below 15 minutes.
// Build V51.01 (2026-10-30): remove the four Daily-close exclusion slots and
// standardize all close labels. Each close module is now hard-routed only to
// the chart-timeframe section that owns it, with no editable exclusions.
// Build V51.00 (2026-10-30): make completed native-1H H/L ranges exclusive
// to Entry charts below 15 minutes. Remove their duplicate exact-15m controls
// while preserving Entry 1H ranges, separators, and prior-close references.
// Build V50.99 (2026-10-30): simplify the exact-8H Weekly appearance labels
// to Weekly range color, width, and style so they match the Monthly block.
// Build V50.98 (2026-10-30): reorder the exact-8H settings from largest to
// smallest context by placing Monthly H/L and close controls before Weekly H/L.
// This is an input-panel organization change only; behavior and defaults remain.
// Build V50.97 (2026-10-30): consolidate both EMA modules into one dedicated
// settings group. Each EMA now has one calculation/style configuration plus
// simple Weekly, 8H, 15m, and Entry visibility checkboxes. Preserve Entry's
// 1H range, separator, and prior-close controls, with no Daily Entry settings.
// Build V50.96 (2026-10-30): remove Daily close controls from Entry and
// hard-suppress Daily H/L, close, and separator visuals below exact 15m.
// Entry now contains only EMA, completed-1H, and native-15m visual families.
// Build V50.95 (2026-10-30): add independently styled prior-1H close
// references to Entry charts, using the same exact-timeframe routing as 1H ranges.
// Build V50.94 (2026-10-30): simplify Entry range controls to completed 1H
// and native-15m ranges only. Suppress Daily and custom-8H ranges below 15m,
// and add an experimental completed-1H boundary separator on Entry charts.
// Build V50.93 (2026-10-30): give exact-15m and Entry-under-15m independent
// copies of their Daily, custom-8H, completed-1H, and prior-Daily-close visual
// controls. Keep native-15m H/L and close controls in Entry because they render
// on 1m, and keep weekday-label controls in exact-15m where they render.
// Build V50.92 (2026-10-30): organize inputs as OB, Details, then chart-timeframe
// sections. Give Weekly, 8H, exact-15m, and Entry-under-15m independent dual-EMA
// calculations and styles. Move native-15m H/L and close controls into Entry.
// Build V50.91 (2026-10-30): keep prior-Daily-close references off the exact
// 8H chart by matching their host ceiling to the Daily H/L ceiling of 4H.
// Preserve Monthly and last-two-Weekly context on the exact 8H chart.
// Build V50.90 (2026-10-30): move every completed-1H range control into
// the 15-minutes-and-under settings section without changing its behavior.
// Build V50.89 (2026-10-30): raise the fresh-load exact-Weekly prior-Yearly
// close history from two periods to ten while preserving its editable control.
// Build V50.88 (2026-10-30): add prior-Yearly close projections to exact
// Weekly and divide settings into Weekly, 8H, 1H, 15m, and 15m-and-under
// sections. Give Weekly Yearly/Quarterly visuals independent appearance.
// Build V50.87 (2026-10-30): add independent editable two-period defaults
// for Quarterly H/L on Weekly and Weekly H/L on 8H. Keep Monthly context on
// Daily/8H only. Reorder settings as EMAs, OB, H/L, separators, then details,
// with H/L controls flowing from the largest timeframe to the smallest.
// Build V50.86 (2026-10-30): give the exact Weekly chart completed native
// Yearly H/L ranges and borders styled like Daily-on-15m, plus the same full
// Monthly ranges, prior closes, and borders already used on exact 8H.
// Build V50.85 (2026-10-30): rename the TradingView indicator title from
// Structure to Time. Preserve every input, calculation, visual, and limit.
// Build V50.84 (2026-10-30): draw completed native Weekly high/low pairs on
// the exact 8-hour chart. Reuse the custom-8H range color, width, style, and
// history count so Weekly-on-8H matches the 8H-on-15m visual hierarchy.
// Build V50.83 (2026-10-30): treat the exact 8-hour chart like the Daily
// chart for completed Monthly high/low ranges, prior-Monthly-close references,
// and Monthly separators. Preserve every other timeframe and calculation.
// Build V50.82 (2026-10-30): make the user's accepted dual-EMA layout the
// fresh-load default: blue 96 EMA lines, width one, with the supplied 5m/1m
// calculation timeframes and exact enabled/disabled exclusion slots.
// Build V50.81 (2026-10-30): restore completed native Monthly high/low
// ranges and prior-Monthly-close references on the exact Daily chart. Reuse
// the existing Monthly request that owns Daily/Weekly Monthly separators.
// Preserve intraday Daily visuals, Weekly-chart separators, and all analysis.
// Build V50.80 (2026-10-29): publish each new exchange-defined Daily separator
// immediately on the opening realtime bar instead of waiting for that bar close.
// Build V50.79 (2026-10-29): add each prior native 15-minute close across
// the following 15-minute period, visible only on the exact 1-minute chart.
// Build V50.78 (2026-10-29): add completed native 15-minute candle high/low
// ranges with independent history and appearance controls, visible only on 1m.
// Build V50.77 (2026-10-27): expand both EMA modules from four to eight
// editable exact-chart-timeframe exclusions. New slots default disabled.
// Build V50.76 (2026-10-26): raise the default completed-Daily visual history
// from 7 to 30 days so Daily H/L pairs and matching separators remain aligned
// with the existing 30-day prior-close history across normal chart views.
// Build V50.75 (2026-10-26): convert the fixed 1m 96 EMA into a second fully
// configurable EMA. Both EMA blocks now independently control calculation
// timeframe, source, length, appearance, and exact chart-timeframe exclusions.
// Build V50.74 (2026-10-26): when completed 1H ranges are enabled on the
// current chart timeframe, keep OB shading but hide the OB box border so its
// 30-minute top/bottom edges cannot be mistaken for another hourly H/L pair.
// Build V50.73 (2026-10-26): source hourly range prices directly from each
// completed 60-minute candle and render every pair across one full hour.
// Remove the local chart-bar hourly accumulator; keep all controls unchanged.
// Build V50.72 (2026-10-26): align completed 1H high/low ranges to fixed
// clock hours (6-7, 7-8, etc.) instead of exchange-native partial buckets.
// Session gaps create no synthetic prices; available bars fill their clock hour.
// Build V50.71 (2026-10-26): keep the fixed 96 EMA calculated on 1m but
// display it on all chart timeframes except four editable exact exclusions.
// Preserve its styling and every non-EMA behavior.
// Build V50.70 (2026-10-26): add a fixed 96 EMA that calculates and displays
// only on the exact 1-minute chart, with independent source and appearance.
// Keep the existing MTF EMA and all non-EMA behavior unchanged.
// Build V50.69 (2026-10-26): add completed native-1H high/low ranges with
// independent history, color, width, style, and four exact chart-timeframe
// display slots. Keep requests, Analysis, Daily/8H ranges, and OBs unchanged.
// Build V50.68 (2026-10-25): give completed custom-8H ranges their own
// editable color and 1-4 line-width controls. Keep the existing history,
// style, timeframe routing, and every non-8H visual unchanged.
// Build V50.67 (2026-10-25): split unusually long exchange-native Daily
// periods into 24-hour calendar segments. Holiday sessions such as a combined
// Monday/Tuesday futures bar receive the missing separator and independent
// Daily H/L/close spans, while normal sessions and crypto remain unchanged.
// Build V50.66 (2026-10-25): make the weekday plotshape background a fully
// transparent constant instead of deriving it from the editable text color.
// This removes one plot count per label renderer and clears TradingView's
// 64-plot ceiling while preserving every visible label, size, color, and default.
// Build V50.65 (2026-10-25): anchor completed Daily H/L spans to each
// exchange-native Daily period's actual open and close instead of extending to
// the next available chart bar. Closed holidays therefore create no synthetic
// day, while 24/7 crypto keeps distinct Saturday and Sunday periods and labels.
// Preserve every input, default, request, and all non-Daily behavior.
// Build V50.64 (2026-10-23): remove the complete experimental 1-2-3 Daily-
// template isolation mode, including its toggle, visual gates, live current-
// 8H lines, time cutoff, and pre-template candle mask. Restore the exact
// V50.61 normal visual behavior and 59-setting layout.
// Build V50.61 (2026-10-23): show the existing completed-Month separator
// borders on exact Weekly charts as well as exact Daily charts. Preserve the
// same monthly source geometry, 12-month history, appearance controls, and
// optional full-height behavior; add no setting or data request.
// Build V50.60 (2026-10-22): remove the OB-open anchored VWAP completely,
// including its settings, fixed-5m calculation field, segment objects, and
// host-chart timing lifecycle. Preserve all opening boxes and restored 8H
// H/L ranges, including their editable completed-range history count.
// Build V50.59 (2026-10-22): restore completed custom-8H H/L ranges on
// intraday charts through 4H. Restore only the range show/count/color/style
// controls and rolling range state. Keep 8H closes, 8H separators, and the
// structural timeframe-exclusion matrix removed as requested.
// Build V50.58 (2026-10-22): remove the unused prior-15m, custom-8H,
// Weekly, and Monthly close-reference modules completely, including their
// settings, calculations, requests, state, and line objects. The already
// retired 8H/Weekly separators remain absent. Preserve Daily closes, Daily
// H/L and separators, Daily-chart Monthly separators, OB/VWAP, EMA, labels,
// and Details. Replace the former canonical-1m Daily-close path with one
// direct native-Daily request and trim the Monthly tuple to separator data.
// Build V50.57 (2026-10-22): extract the complete Quarter Theory price grid
// into the standalone Levels V1.00 indicator. Structure no longer owns any
// number-level inputs, instrument presets, lines, labels, or last-bar work.
// Build V50.56 (2026-10-22): simplify structural routing to the user's fixed
// workflow. Daily H/L and separators render only on intraday charts through
// 4H; Monthly separators render only on the exact Daily chart. Remove custom
// 8H, Weekly, Monthly, and Monday structural ranges/separators plus their
// timeframe exclusions. Remove current-OB high/low projection lines while
// preserving the opening boxes, anchored VWAP, and close-reference modules.
// Build V50.55 (2026-10-22): tighten the automatic soybean Quarter Theory
// preset from a 50-cent major box to a 20-cent major box. Soybean quarter
// intervals are now 5 cents (20 minimum ticks), while Manual mode and every
// other instrument preset remain unchanged.
// Build V50.54 (2026-10-22): performance-only cleanup. Remove unreachable
// separator paths and unused rolling OHLC state, stop creating invisible
// range/OB objects, avoid repeated setters on fixed close lines, and evaluate
// Quarter Theory instrument classification only on the chart's last bar.
// All inputs, defaults, calculations that feed visuals, and timeframe routing
// remain unchanged, including full support for 1m, 3m, 5m, and 15m charts.
// Build V50.53 (2026-10-22): restrict the weekday label row to exact 15m,
// default Weekly and Monthly H/L plus Weekly separators off, and hard-route
// the retained Monthly separators to the exact Daily chart only.
// Build V50.52 (2026-10-22): add an optional Monday-Friday label row fixed
// to the bottom of intraday and Daily charts. The labels use each trading
// day's first bar and remain outside the price scale in one horizontal row.
// Build V50.51 (2026-10-22): add a separate current-week-only Daily visual
// history option. It resets Daily H/L, separators, Monday borders, and Daily
// close references at each new week; the existing two-week option remains.
// Build V50.50 (2026-10-22): add four exact-chart-timeframe exclusions
// specifically for Weekly separators. Weekly H/L routing remains independent,
// while the existing shared Weekly exclusions continue to hide both visuals.
// Build V50.49 (2026-10-22): add an optional full-height mode for every
// structural separator. The default remains finite range-height borders.
// Enabling the option extends 8H, Daily, Weekly, Monthly, and Monday borders
// through the full pane without changing their timestamps or retained history.
// Build V50.48 (2026-10-22): add a dedicated Nikkei Quarter Theory preset.
// Recognized Nikkei futures and common index aliases use a 2,000-point major
// box, producing 500-point quarter intervals. No input or default changed.
// Build V50.47 (2026-10-21): apply only the user-confirmed fresh-load
// defaults for 8H/Daily structural exclusions and 8H/Daily close references.
// Remove the complete full-session highlight module while preserving the
// Tokyo/London/New York 30-minute opening boxes and every other visual.
// Build V50.46 (2026-10-21): restore the complete settings definition from
// the user's authoritative V50.42 script. Input order, groups, labels, and
// defaults now match that supplied script exactly. Calculations and drawings
// remain unchanged.
// Build V50.45 (2026-10-21): undo the mistaken V50.44 default rollback.
// Keep the V50.43 settings organization and restore its accepted Daily
// structural-visibility and Daily-close defaults exactly. No other input,
// calculation, or drawing behavior changes.
// Build V50.44 (2026-10-21): preserve the V50.43 settings organization while
// restoring every input default to its exact V50.42 value. This repair changes
// defaults only; calculations and drawings remain unchanged.
// Build V50.43 (2026-10-21): promote the accepted fresh-install defaults
// shown in the settings references and reorganize the Inputs menu into a
// numbered visual workflow with clearer labels and separate Weekly/Monthly
// close sections. Calculations and drawing behavior are unchanged.
// Build V50.42 (2026-10-21): extend the optional previous-week-open Daily
// history cutoff to the prior-Daily-close reference lines. The same switch now
// trims Daily H/L, Daily separators, Monday Daily borders, and Daily closes;
// all prices, projection spans, and non-Daily close modules are unchanged.
// Build V50.41 (2026-10-21): add an optional Daily visual-history cutoff.
// When enabled, completed Daily H/L lines, Daily separators, and Monday's Daily
// borders are retained only from the opening of the previous trading week
// forward. The existing count-based history remains authoritative when off.
// Build V50.40 (2026-10-21): add independent exact-chart-timeframe
// exclusions to every close-reference module: prior 15m, custom 8H, Daily,
// Weekly, and Monthly. Existing close prices, projection spans, history counts,
// supported timeframe ceilings, and request sources are unchanged.
// Build V50.39 (2026-10-21): group completed-Monday H/L and separator
// controls in one dedicated settings section. Each component has its own
// show, color, width, and solid/dashed/dotted style controls. Monday
// detection, prices, timeframe routing, and retained history are unchanged.
// Build V50.38 (2026-10-21): remove the complete 1x/2x/3x opening-box
// expansion module from lower-timeframe and exact-1H rendering, including its
// settings and line-object state. Remove the top-center drawdown/trade-limit
// table and settings so Details contains only the ticker and chart timeframe.
// OB boxes, OB high/low projections, anchored VWAP, and all other visuals remain.
// Build V50.37 (2026-10-21): separate completed-Monday horizontal range
// styling from its vertical separator styling. Monday ranges and separators
// now have independent show, color, width, and solid/dashed/dotted controls;
// Monday detection, prices, timeframe routing, and retained history are unchanged.
// Build V50.36 (2026-10-21): remove the HTF fact tracker and the entire active
// breach system, including their settings, tables, line/label rendering, state
// engines, and tracker-only tuple fields. Preserve every independent visual:
// ranges, separators, close references, sessions, OB/VWAP, EMA, and price grid.
// Build V50.35 (2026-10-21): give custom-8H and Weekly close references
// independent editable history counts. Each close count sits directly beside
// its matching completed-range count in Structural levels for quick matching.
// Range histories, close prices, time spans, routing, and all logic are unchanged.
// Build V50.34 (2026-10-21): enforce the established 15-minute ceiling on
// the current OB-open anchored VWAP by removing its exact-1H renderer. The
// exact-1H OB box and expansion grid remain unchanged, and VWAP calculation,
// ownership, timing, and 1m-through-15m rendering remain unchanged.
// Build V50.33 (2026-10-21): add completed custom-8H separator borders and
// project each completed custom-8H close across the following custom-8H block.
// Both visuals share the established 8H history count and timeframe routing,
// while retaining independent visibility and style controls.
// Build V50.32 (2026-10-21): improve the exact-1H New York OB presentation.
// Its prices still come from the unchanged fixed-5m 09:30-10:00 New York
// calculation, but the 30-minute box fills its receiving 1H candle so the
// range remains legible. OB high/low extensions stay limited to <=15m charts.
// Build V50.31 (2026-10-21): tie exact-Daily prior-Weekly and prior-Monthly
// close retention to the existing completed Weekly/Monthly range counts so
// close references, H/L ranges, and separators share one history setting.
// Build V50.30 (2026-10-21): add prior-Weekly and prior-Monthly close
// projections that span the following Week/Month on the exact Daily chart.
// Both modules have independent show, history, color, width, and style inputs
// and deliberately do not use exclusion routing. Also promote the user's
// saved structural, Quarter Theory, 15m-close, Daily-close, and EMA choices to
// script defaults so a fresh indicator instance restores the preferred view.
// Build V50.29 (2026-10-21): add a dedicated DAX Quarter Theory preset.
// FDAX, FDXM, FDXS, and common DAX cash/CFD symbols now use a 1,000-point
// major box with 250-point quarter steps instead of the generic adaptive
// 2,000-point box near current DAX prices. Manual mode and all other presets
// remain unchanged.
// Build V50.28 (2026-10-20): add a dedicated soybean Quarter Theory preset.
// ZS, mini XK, and micro MZS now use a 50-cent major box with 12.5-cent
// quarter steps instead of falling through to the generic adaptive 100-cent
// box near current soybean prices. Manual mode and every other preset remain
// unchanged.
// Build V50.27 (2026-10-20): convert EMA chart-timeframe routing from
// positive inclusion slots to exact-timeframe exclusions. The EMA displays on
// every chart timeframe by default; each enabled Hide slot suppresses it only
// on the selected exact chart timeframe. The master Show EMA switch,
// calculation timeframe, source, length, color, width, and style are unchanged.
// Build V50.26 (2026-10-20): correct the V50.25 separator interpretation.
// Structural separators are finite range-box boundaries again, not full-pane
// lines. On lower host charts including 4H, Monthly separator retention now
// follows the editable completed-Monthly H/L range count instead of remaining
// hard-coded to three boundaries. Daily and Weekly separator retention already
// followed their matching range histories and remains unchanged. No dates,
// styles, timeframe exclusions, requests, or market logic change.
// Build V50.25 (2026-10-20): make Daily, Weekly, and Monthly structural
// separators true full-height vertical lines by extending each boundary in
// both price directions. This corrects the visibly truncated separator spans
// on 4H and other compressed charts without changing separator timestamps,
// retention, timeframe exclusions, colors, widths, styles, or any range and
// classification logic.
// Build V50.24 (2026-10-20): apply the V50.23 exclusion-based chart-
// timeframe model to the Quarter Theory grid. Quarter lines and their labels
// now display on every chart timeframe by default and are hidden only on the
// exact timeframes enabled in four optional Hide slots. Quarter prices,
// instrument presets, sizing, anchoring, styles, and all structure logic stay
// unchanged.
// Build V50.23 (2026-10-20): invert the Structural H/L + separator chart-
// timeframe controls. Each 8H, Daily, Weekly, and Monthly visual family now
// displays automatically on every supported chart timeframe except the exact
// chart timeframes selected in its four optional exclusion slots. This removes
// the former all-timeframes switch and inclusion lists while preserving every
// range, separator, Monday, breach, classification, and request calculation.
// Build V50.22 (2026-10-20): replace the fixed three-opening-box history
// limit with an editable 1–30 box setting. The selected count applies to the
// ordinary 1m–15m OB renderer and the fixed-5m-derived 1H OB renderer. Only
// completed/current 30-minute boxes gain history; projected high/low, range
// expansions, and anchored VWAP remain intentionally newest-OB-only. No OB
// geometry, timing, session, structural, classification, or request changes.
// Build V50.21 (2026-10-20): refine automatic currency Quarter Theory
// sizing. FX now defaults to the theory's Small Quarters: a 100-pip major
// box divided into four 25-pip steps. An editable currency-scale selector
// preserves the original 1000-pip Large Quarters when desired. Pip size is
// derived from the symbol's minimum tick for spot/CFD pairs, with direct and
// inverse-JPY CME currency-futures presets. All non-currency presets and all
// structural, breach, range, fact-table, and request logic remain unchanged.
// Build V50.20 (2026-10-20): add Daily-chart-only layout controls for
// active Weekly and Monthly breach levels. On Daily charts, their lines now
// project farther right and their labels use a separate farther-right offset
// and font size (90 days, 45 days, and Tiny by default). Other chart
// timeframes and all breach prices, states, classifications, and logic remain
// unchanged.
// Build V50.19 (2026-10-20): add an instrument-scaled Quarter Theory price
// grid. The display divides a major price box into four equal quarters, offers
// automatic presets with a price-scale fallback, and provides a manual box
// size/anchor override. Major, half, and quarter lines, labels, surrounding
// box count, and chart timeframes are independently editable. Display only;
// no structural fact, range, breach, OB, VWAP, EMA, or request logic changes.
// Build V50.18 (2026-10-20): make Weekly separators use the exact same
// completed-week start, end, high, low, and editable history count as the
// Weekly H/L ranges. Every retained Weekly range now receives both its left
// and right separator on every selected host timeframe. Display only; all
// structural facts, classifications, and range calculations are unchanged.
// Build V50.17 (2026-10-20): add independent H/L and separator visibility
// switches for Daily, Weekly, and Monthly structure, plus exact chart-timeframe
// filters for 8H, Daily, Weekly, and Monthly visuals. Remove the hard-coded
// one-hour separator ceiling so selected separators work on 4H and any other
// selected chart timeframe. Display only; all structural facts are unchanged.
// Build V50.16 (2026-10-12): include exact 1-minute charts in the default
// full-session highlight display set. The four enabled defaults are now 1m,
// 5m, 15m, and 1H; all slots remain editable. Opening-box behavior, session
// timing, retained history, fact-table data, and every calculation are unchanged.
// Build V50.15 (2026-10-12): rename the two editable top-center discipline
// captions from per-session limits to per-day limits. These remain display-only
// values; no P&L, trade-count, range, breach, or fact-table logic changes.
// Build V50.14 (2026-10-12): on the Daily chart, give every retained
// completed Monthly range its own exact left/right separators. Monthly
// boundary history now follows the editable Monthly range count instead of
// retaining only the newest three vertical boundaries on Daily.
// Build V50.13 (2026-10-11): replace the seven-day Friday reset with an
// editable rolling Daily range/separator history of up to 60 completed days.
// Mondays remain independently styled full boxes inside that rolling history.
// No fact, classification, breach, OB, session, or close-reference logic changes.
// Build V50.12 (2026-10-09): draw completed Weekly and Monthly high/low
// pairs directly when each parent period closes on the Daily chart. This
// removes the Daily-only last-bar rebuild that could leave separators visible
// without the horizontal highs/lows. Also allow the active Weekly and Monthly
// breach lines on Daily while keeping Daily/8H breach lines excluded there.
// Counts, breach calculations, and established styles are kept.
// Build V50.11 (2026-10-09): make the Daily chart an explicit host for
// completed Weekly and Monthly range visuals. Reconstruct both range pairs
// from their native parent periods and draw their established Weekly/Monthly
// separators on Daily, while keeping Daily and 8H ranges hidden there.
// Fact-table classifications, breach logic, OB/VWAP, EMA, sessions, and all
// lower-timeframe behavior are unchanged.
// Build V50.10 (2026-10-08): remove the derived MTF/LTF conclusion layer.
// The bottom-center MTF/LTF key, Monthly/Weekly aligned/unaligned calculation,
// overextension/rolling calculation, and Daily/8H LTF conclusion are removed.
// Keep the bottom-right MTF fact table (Cur, Prev, BO, First), classifications,
// breach visuals, ranges, sessions, OB/VWAP, EMA, and close references.
// Build V50.09 (2026-10-08): extend the display-only prior-15m-close
// projection from exact 5-minute charts to exact 1-minute charts as well.
// Give these lines their own editable color in addition to the established
// width and style controls. Canonical close sourcing, OB timing-window
// clipping, Analysis, MTF/LTF state, and every other visual are unchanged.
// Build V50.08 (2026-10-02): add a display-only Show LTF State row toggle
// to the integrated bottom-center MTF/LTF key. The master key switch and MTF
// row remain unchanged; disabling the new input clears only the visible LTF
// row. LTF calculations, tracker values, Analysis, and every visual are unchanged.
// Build V50.07 (2026-10-02): add completed-Month vertical separators that
// mirror the established completed-Week separator behavior. Each boundary
// spans the adjoining Monthly high/low context, retains the latest three
// boundaries, follows the existing separator display/timeframe gate, and has
// independent color, width, and solid/dashed/dotted settings. Display only;
// Analysis, MTF/LTF, ranges, OB, sessions, VWAP, EMA, and requests are unchanged.
// Build V50.06 (2026-10-02): add display-only Tokyo/Asia, London, and
// New York full-session range highlights separate from the existing 30-minute
// opening boxes. Defaults use 09:00-18:00 Asia/Tokyo, 08:00-17:00
// Europe/London, and 08:00-17:00 America/New_York so Pine handles regional
// daylight-saving changes through the named timezones. Session visibility,
// time windows, colors/opacity, border style/width, retained history, and four
// chart-timeframe display slots are editable. No Analysis, MTF/LTF, OB, VWAP,
// range, breach, parent-close, Daily-close, EMA, or request logic changes.
// Build V50.05 (2026-10-02): extend the canonical previous-Daily-close
// reference from the active day to a configurable rolling history. Each
// intraday Daily period receives the close of its immediately preceding Daily
// period from the existing canonical 1m engine. Retain 1-30 days (default 3),
// including the active current day. This is display-only; V50.04 Analysis,
// requests, 15m-close projections, OB/VWAP, and every state rule are unchanged.
// Build V50.04 (2026-09-25): reduce the canonical 1-minute history default
// and minimum from 50,000 to 5,000 bars while retaining the adjustable
// 100,000-bar maximum. Five thousand 1m bars cover about 83 continuous hours,
// enough for the current/previous custom-8H rotations and their short rolling
// state. Raise the setting when older replay/history must be reconstructed.
// Analysis rules and all V50.03 visuals, including 15m-close projections, are
// unchanged.
// Build V50.03 (2026-09-25): restore only the prior-15m-close projection on
// the exact 5-minute chart. The existing canonical 1m engine supplies each
// completed 15m close, which projects across the next 15m rotation, inherits
// the newest named-session OB color, and remains clipped to that OB's timing
// window. Add one editable canonical-1m previous-Daily-close line spanning only
// the active current day. The 1H-on-15m system stays removed; both additions
// are display-only, and V50.02 Analysis/performance is unchanged.
// Build V50.02 (2026-09-23): consolidate duplicate D/W/M request contexts,
// fold First-signal reconstruction into the existing canonical 1m pass, and
// rebuild Daily-hosted Monthly drawings only once per new chart bar. Source
// timeframes, history, classifications, state ownership, and visuals are
// unchanged; this is a performance-only refactor.
// Build V50.01 (2026-09-23): guard the fixed-5m OBVisualState returned by
// request.security before reading its fields. TradingView can return an
// undefined object on the first historical bar; the guard keeps those values
// na until the first valid object arrives and prevents runtime error RE10041.
// Display and Analysis behavior are otherwise unchanged from V50.00.
// Build V50.00 (2026-09-23): restore the complete V48.31 Analysis engine and
// its MTF tracker, MTF/LTF summary, active breach system, and classifications.
// Retain the accepted visual changes made afterward: no parent-close lines,
// fixed-5m named-session OB geometry on the exact 1H chart, and a separately
// configurable four-sided completed-Monday range box.
// Build V48.31 (2026-09-23): rename the bottom-center HTF State header to
// MTF State. This is a display-text-only change; alignment and LTF logic are
// unchanged.
// Build V48.30 (2026-09-23): make the completed-Month range-count setting
// authoritative on the Daily chart. Daily-hosted Monthly visuals now retain a
// separate native-value cache and rebuild the latest requested 1-12 completed
// ranges on the last bar, so July remains visible beside August when the input
// is 2. Other chart-timeframe visuals and all state logic are unchanged.
// Build V48.29 (2026-09-19): clarify the inherited Daily-close fallback in
// the integrated LTF key. When both the current Daily and live Current 8H
// relations are Inside, prior Daily BOC/BDC now displays as INSIDE BOC or
// INSIDE BDC. This is a text-only clarification; state codes, colors, source
// selection, HTF/LTF logic, and every other calculation are unchanged.
// Build V48.28 (2026-09-17): make the integrated LTF pullback label consume
// the live Current 8H relation when the current Daily range is Inside and the
// previous Daily range closed BO/BD. A newly Inside 8H range now falls back to
// the inherited Daily BOC/BDC instead of retaining an older 8H continuation.
// The canonical 8H memory, tracker, ranges, breaches, HTF alignment, and all
// other state logic are unchanged.
// Build V48.27 (2026-09-14): fix partial/incorrect completed Monthly range
// lines on the Daily chart. Daily-hosted Monthly visuals now use the native
// completed Monthly high, low, start, and end instead of the Daily host's
// potentially partial rolling accumulator. Other chart timeframes and all
// state, classification, breach, HTF/LTF, and permission logic are unchanged.
// Build V48.26 (2026-09-14): add confirmed Outside (`OT`) classification
// for completed custom-8H, Daily, Weekly, and Monthly ranges. OT requires the
// same completed period to trade strictly above the previous range high and
// strictly below its low, then close back within that previous range.
// The following period's Prev cell prints OT in the neutral color. OT is
// classification-only for now: it does not alter HTF alignment, LTF state,
// breach logic, First/BO counters, or any trading permission.
// Build V48.25 (2026-09-12): resolve the current D/W/M and Daily-LTF relation
// from the host-invariant running period high/low plus the canonical close.
// The ordered 1m result is retained only as the tie-breaker when the current
// period has breached both sides, where aggregate OHLC cannot identify which
// side occurred last. This removes the Daily-versus-1H BO/IS discrepancy while
// preserving both-side path ordering and accepted pullback-memory semantics.
// Build V48.24 (2026-09-12): make canonical day/week/month rollovers resilient
// when a higher host chart exposes only the latest lower-timeframe intrabar.
// Persistent owner stamps now detect a changed period on every canonical
// execution, preventing a prior period's BO/BD or First state from leaking into
// the live Daily/Weekly/Monthly candle. Relation, alignment, pullback-memory,
// breach, session, EMA, OB, and VWAP rules are otherwise unchanged.
// Build V48.23 (2026-09-11): calculate the current-session OB-open anchored
// VWAP from fixed 5-minute candles on every supported chart. The 1m-through-15m
// display gate, named-session ownership, three-hour post-close end, color, and
// width remain unchanged; only the VWAP's calculation timeframe is normalized.
// Build V48.22 (2026-09-11): let the single MTF EMA display on any match
// across four independently configurable chart-timeframe slots. Slots 1 and 2
// default enabled for 5m and 15m; optional slots 3 and 4 default disabled for
// 1H and 4H. Calculation timeframe, styling, and display-only isolation remain.
// Build V48.21 (2026-09-11): add one display-only MTF EMA to Structure.
// Its source timeframe and allowed chart-display timeframe are independently
// editable, as are source, length, color, width, and solid/dashed/dotted style.
// Default behavior calculates a 5-minute EMA and shows it only on the 15-minute
// chart. The EMA does not feed any HTF/LTF, range, breach, or session state.
// Build V48.20 (2026-09-11): remove the integrated ATR-grouped Coil module
// and the separate TrendPredator FO candle-color module, including their
// settings, calculations, state arrays, bar coloring, and EMA plots. Canonical
// structural FOH/FOL and active-breach logic remain unchanged because they
// supply the retained HTF/LTF state displays.
// Build V48.19 (2026-09-11): merge the always-visible HTF/LTF summary directly
// into Structure and retire the separate Analysis indicator plus C01/C02 bridge.
// The summary reuses the MTF/HTF tracker's header, bullish, bearish, neutral,
// header-size, and value-size settings so both displays update together.
// Build V48.18 (2026-09-11): make 15m-on-5m close projections inherit the
// exact active Tokyo/London/New York OB color while retaining their OB-open to
// timing-window-end span. Hourly-on-15m close projections now run independently
// of OB timing and retain a rolling 24-hour history. Separate visibility, width,
// and style controls remain; the hourly color remains editable.
// Build V48.08 (2026-09-11): promote the user's working Structure settings
// to source defaults. This changes presentation defaults only: session/range/
// tracker/TrendPredator colors, selected line styles and text sizes, Coil
// defaults, VWAP width, and displayed risk. All controls remain editable and
// no Structure, setup, veto, bridge, OB-lifecycle, or Analysis logic changes.
// Build V48.07 (2026-09-11): keep Previous Monthly FOH/FOL directional when
// Current Monthly is inside. The Monthly neutral bridge now requires the live
// Previous relation and its completed-close snapshot to agree on BO/BD, or an
// explicit Previous Monthly Zero. A visible FOH/FOL can no longer be discarded
// by a hidden stable snapshot, preventing a conflicting Weekly state from
// creating false alignment and downstream setups. All other logic is unchanged.
// Build V48.06 (2026-09-11): show the current named-session OB high and low
// projections on 1m-through-15m charts. Existing new-session ownership cleanup
// still deletes the prior session's two projection lines, so historical OB
// rectangles remain independent and no prior-session high/low projection is
// retained. Setup, veto, bridge, VWAP, expansion, breach, Coil, and
// TrendPredator logic are unchanged.
// Build V48.05 (2026-09-10): give each active 8H/D/W/M breach line the
// same Current/Previous owner used by the HTF tracker. Current has priority;
// otherwise Previous owns the line. A completed range that fakeouts both
// sides can therefore resolve to BD at its low or BO at its high instead of
// leaving an older FOH/FOL line frozen. The existing path-aware breach remains
// the inside/inside fallback. One line per timeframe and all bridge lanes stay
// unchanged.
// Build V48.03 (2026-09-10): expose the integrated TrendPredator FO bar-color
// engine on every supported chart timeframe. Remove the prior 3m-only,
// rotation-trio, OB-print, timing-window, and confirmed-bar display gates.
// One master toggle controls the entire module; category colors and enable
// switches remain editable. Setup, veto, bridge, OB/VWAP, and Coil are unchanged.
// Build V48.02 (2026-09-10): restore the previously integrated TrendPredator
// FO visual module from the user-supplied MPL-2.0 source. Its state engine runs
// continuously on 3m charts, but colors only confirmed candles immediately
// before, at, and after each 15-minute rotation following the OB print through
// the current three-hour timing window. It is display-only: HTF/LTF state,
// setup selection, vetoes, OB/VWAP, Coil, A01-A03, and C01-C07 are unchanged.
// TrendPredator FO portions adapted from Copyright (c) 2025 TC888 under the
// Mozilla Public License 2.0: https://www.mozilla.org/MPL/2.0/
// Build V48.01 (2026-09-10): allow the integrated ATR-grouped Coil to display
// on two independently editable chart timeframes, default 5m and 15m. The
// grouping calculation, four EMA plots, and every non-Coil module are unchanged.
// Build V48.00 (2026-09-10): integrate Coil directly into Structure. Four
// configurable 5m EMAs display on the selected chart timeframe only while
// their highest-to-lowest spread is no greater than an editable multiple of
// the matching 5m ATR. Line-break plots prevent connections across non-coil
// periods. Setup, veto, bridge, OB, VWAP, and Structure visuals are unchanged.
// Build V47.99 (2026-09-10): publish the currently active custom-8H failure
// breach on C07 so Analysis can veto trading into it. C07 carries only an
// active 8H FOH/FOL level and its matching state; ordinary 8H range boundaries
// and active BO/BD states are deliberately excluded. All visuals are unchanged.
// Build V47.98 (2026-09-10): extend only the current-session OB-open anchored
// VWAP display through the 15-minute chart. OB boundary projections and
// 1x/2x/3x expansions remain limited to 1m-through-5m. VWAP ownership, anchor,
// study-window end, canonical facts, setup logic, C01-C06, and styles are unchanged.
// Build V47.96 (2026-09-10): hide every active breach line/label and the
// top-right OB lifecycle status panel on Daily charts. This is display-only;
// canonical breach calculations, setup logic, C01-C06, lower-timeframe
// visuals, and all existing style controls are unchanged.
// Build V47.95 (2026-09-09): simplify Current to the retained trading tools.
// Remove OB timing separators, the live rotation countdown, TrendPredator bar
// coloring, and reversal/continuation OB ownership. Keep HTF structure/tracker,
// three named-session OBs, rolling three-box history, current OB projections
// and 1x/2x/3x expansions, current-session anchored VWAP, status/details/risk
// displays, the three-hour timing gate, and the compact Analysis bridge.
// The bridge is reduced to C01-C06 because Analysis no longer consumes C07.
// All style controls belonging to retained Structure visuals remain editable.
// Build V47.94 (2026-09-09): extend the canonical OB timing window to three
// hours after the 30-minute OB closes (OB open +210 minutes). Current-session
// projections, anchored VWAP, live countdown, separators, Analysis permission,
// rotation zones, and 3m rotation-bar timing inherit that one boundary. The
// final separator remains the timing-window end rather than an entry rotation.
// Build V47.93 (2026-09-09): no Structure calculation or C01-C07 bridge
// change. Analysis adds one master toggle for its active 1-2-(3) vetoes while
// preserving every structural, OB, timing, and display fact here.
// Build V47.92 (2026-09-09): add a live-only countdown to the next 15-minute
// rotation after the OB prints. It cycles through the existing rotations,
// disappears at the established timing-window end, and is suppressed on
// historical/Bar Replay execution by `barstate.isrealtime`. Display only;
// canonical facts, setup logic, Analysis, A01-A03, and C01-C07 are unchanged.
// Build V47.91 (2026-09-09): make the OB-open anchored VWAP current-session
// only. Its line segments are owned by the newest named-session OB and are
// deleted when the next OB starts, while the latest three OB boxes remain.
// VWAP math, study-window length, canonical facts, setup logic, Analysis,
// and the C01-C07 bridge are unchanged.
// Build V47.90 (2026-09-09): align the visible TrendPredator trio to the
// chart candles labeled immediately before, at, and after each rotation.
// TradingView labels a candle by its open time, so the gate now uses `time`
// at rotation -3m/0m/+3m instead of `time_close`. This removes the extra
// second-prior candle and adds the missing first-after candle. Color logic,
// canonical facts, Analysis, setup outputs, and C01-C07 are unchanged.
// Build V47.89 (2026-09-09): integrate the TrendPredator FO bar-color engine
// as a visual-only 3m rotation-window aid. It may color only the 3m candles
// closing one bar before, exactly at, and one bar after each of the five
// post-print 15-minute rotations. No canonical/setup/bridge fact is changed.
// TrendPredator FO module adapted from Copyright (c) 2025 TC888 and retained
// under the Mozilla Public License 2.0: https://mozilla.org/MPL/2.0/
// Build V47.88 (2026-09-09): retain the three most recent named-session OB
// boxes and restore an OB-open anchored VWAP through each timing-window end.
// OB rectangles show through 15m; the newest OB's study details stay <=5m.
// Only the newest OB owns projected high/low, expansion, and separator visuals.
// Canonical facts, setup logic, ownership, and the C01-C07 bridge are unchanged.
// Build V47.87 (2026-09-08): no Structure calculation or bridge change.
// Analysis restores the existing Daily First/8H 3L-3S veto explanation.
// Build V47.86 (2026-09-05): no Structure calculation or bridge change.
// Analysis retains confirmed setup labels for two hours after its timing gate.
// Build V47.85 (2026-09-04): no Structure calculation or bridge change.
// Analysis reports an 8H First block from pre-selection direction gates.
// Build V47.84 (2026-09-04): no Structure calculation or bridge change.
// Analysis now names an exact 8H First-signal directional block in its key.
// Build V47.83 (2026-09-03): no Structure calculation or bridge change.
// Analysis expires rotation-zone objects with their owning OB timing window.
// Build V47.82 (2026-09-03): apply the same 1m-through-5m visibility gate to
// the OB's vertical 15-minute separators, removing their 15m+ chart glitch.
// Build V47.81 (2026-09-03): show the active OB box/high-low only through the
// 5-minute chart. Canonical OB data and the C01-C07 bridge remain unchanged.
// Build V47.80 (2026-09-03): no Structure calculation or bridge change.
// Analysis removes only the same-color seam inside each filled trap zone.
// Build V47.79 (2026-09-03): no Structure calculation or bridge change.
// Analysis adds cosmetic trap-side fills between consecutive rotation pairs.
// Build V47.78 (2026-09-03): no Structure calculation or bridge change.
// Analysis shifts each six-plus-six-minute rotation pair two minutes earlier.
// Build V47.77 (2026-09-03): no Structure calculation or bridge change.
// Analysis now projects the complete direction-colored rotation map as soon as
// a setup direction exists; the existing C01-C07 contract is unchanged.
// Build V47.76 (2026-09-03): publish the active canonical OB high/low on the
// new, used C07 visual lane. Analysis uses it only to bound the manual
// 15-minute rotation windows for whichever canonical session owns the active
// OB (Tokyo, London, or New York); setup calculations remain on C01-C06.
// Build V47.75 (2026-09-03): no Structure or bridge change. Analysis clarifies
// the manual entry checklist sequence around each 15-minute rotation.
// Build V47.74 (2026-09-03): add the current chart timeframe below the ticker
// in the existing middle-right Details panel. Display-only; no bridge or
// structural calculation changes.
// Build V47.73 (2026-09-03): remove timing separators from the forming OB.
// Separators now begin 15 minutes after the 30-minute box prints and continue
// every 15 minutes through the unchanged OB-open +120-minute study end.
// Build V47.72 (2026-09-03): constrain each display-only 15-minute OB timing
// separator to the completed opening-box high and low. Expansion calculations,
// setup facts, timing, and the C01-C06 bridge are unchanged.
// Build V47.71 (2026-09-03): add a display-only opening-box grid. Horizontal
// range expansions now extend through 1x, 2x, and 3x above/below the completed
// box, with independent visibility, color, width, and style for each multiple.
// Eight editable vertical separators mark every 15 minutes from OB open through
// the existing OB-open +120-minute study end. No setup or bridge fact changes.
// Build V47.70 (2026-09-03): compact the active Analysis bridge from eight
// inputs to six. C01 now carries every Boolean state/gate fact, C02 carries
// enums, C03-C05 carry the two completed and one live 8H ranges, and C06
// carries the ordered 1m close plus the only owner time Analysis consumes.
// No HTF/LTF, 1-2-(3), OB ownership, or timing decision is changed.
// Build V47.69 (2026-09-03): remove opposing, round-Number, Average Stop, risk
// veto, Number-length exhaustion, and completed-5m levels from the active
// system. Analysis now connects through C01-C08 only; retired C09-C15 lanes
// are removed. HTF/LTF/setup, OB, and timing remain unchanged.
// Build V47.68 (2026-09-03): retire Analysis' completed-5m validation ledger
// and restore the original raw completed-5m extreme levels in Structure. Each
// white line starts at its owning 5m candle and ends at the OB study-window
// boundary. All setup, veto, opposing, OB, and bridge calculations are intact.
// Build V47.67 (2026-09-03): retire the completed-1m entry layer and A04 from
// Analysis and remove the dependent Strategy from Current.
// Build V47.66 (2026-09-03): add an editable exhaustion veto when the full
// high-to-low travel inside the active rolling three-range 1-2-(3) context
// reaches three quarter-Number lengths. Analysis blocks continuation setups
// after exhaustion while preserving reversal setups away from the move. C02
// bit 9 carries the fact without adding a bridge slot. Analysis also rechecks
// opposing-level alignment on the actual completed 1m entry candle.
// Build V47.65 (2026-09-03): make an OB reversal permanent for the active
// OB session. A Buy-side low sweep stays REVERSAL BUY even after a later
// close above the OB high; a Sell-side high sweep stays REVERSAL SELL even
// after a later close below the OB low. Remove the former REV -> CONT locks.
// Analysis also requires a stored validation level's OB mode to match the
// currently active OB mode before that level may publish an entry.
// Build V47.64 (2026-09-03): restrict ordinary HTF overextension to Daily
// facts that match the established alignment. Bullish alignment may extend
// only from Daily BOC or 3L; bearish only from Daily BDC or 3S. Monthly/Weekly
// remain alignment inputs and their existing rollover logic is unchanged.
// Build V47.63 (2026-09-03): shorten the canonical analysis/validation window
// from OB close +120 minutes to OB close +90 minutes. All window-owned lines,
// flags, status phases, validation, and A04 eligibility share the new end.
// Build V47.62 (2026-09-03): no Structure calculation change. Analysis now
// consumes the canonical Number state already packed in C03 and restores the
// directional trading-against-Numbers setup veto.
// Build V47.61 (2026-09-03): republish the active quarter-Number rung spacing
// on C15 for the separate Strategy. Each A04 fill uses C14 for its frozen
// Average Stop and targets the next strict C15 Number in trade direction.
// Build V47.60 (2026-09-03): publish a stop/room veto when two Average Stops
// exceed the automatic opposing-room distance. Promote requested defaults:
// stop multiplier 0.10, opposing gap 0.30, canonical history 50k, opaque white
// dotted Number grid, and black dotted custom-8H ranges.
// Build V47.59 (2026-09-03): base Average Stop Distance on the arithmetic mean
// of the live current custom-8H range and the two most recently completed
// custom-8H ranges—the three ranges defining current 1-2-(3) context. The
// opposing route and its separate 60-range volatility contract are untouched.
// Build V47.58 (2026-09-03): simplify Average Stop Distance to the current
// printed opening-box range multiplied by the editable stop multiplier. Remove
// all historical OB sampling. The 8H opposing-room calculation is untouched.
// Build V47.57 (2026-09-03): calculate Average Stop Distance from the rolling
// median of completed opening-box ranges for the same named session. Defaults:
// last 10 boxes, minimum 5, multiplier 0.30. The current box joins the sample
// only when it prints. The 8H opposing-room calculation is untouched.
// Build V47.56 (2026-09-03): make the shared canonical 1m calculation depth
// editable and raise its default from 50,000 to 100,000 bars. This extends
// Analysis A04 and the A04-only mapper past the former late-July boundary;
// both canonical 1m requests use the same depth to preserve timeframe parity.
// Build V47.55 (2026-09-03): Analysis no longer invalidates a validated 5m
// level from any later candle close. C12 remains published only to preserve
// the stable C01-C14 bridge layout; all Structure calculations are unchanged.
// Build V47.54 (2026-09-03): the separate Strategy is now an A04-only entry
// mapper. Retire C15 because no stop or Number target is calculated there;
// Structure's C01-C14 Analysis contract and all chart logic are unchanged.
// Build V47.53 (2026-09-03): publish the exact opposing-chain Number rung
// spacing on C15 for the then-separate stop/target strategy. Superseded by
// V47.54; C01-C14 were unchanged.
// Build V47.52 (2026-09-03): keep Structure's C01-C14 contract unchanged while
// Analysis carries pending 1m entry stages into late validation, permits a
// single 1m candle to serve as both breach/retest and entry confirmation, and
// invalidates locked levels only from later completed 15m closes.
// Build V47.51 (2026-09-03): keep Structure's C01-C14 contract unchanged while
// Analysis adds a display-only completed-1m entry-candle state machine from
// its validated levels. Structure still owns no entry or strategy decision.
// Build V47.50 (2026-09-03): pair the unchanged C01-C14 Structure bridge with
// Analysis' fixed-side opposing validation. Average-stop distance remains a
// Structure fact but no longer grants an entry-level validation exception.
// Build V47.49 (2026-09-03): keep the completed-5m facts on C11-C14 but retire
// Structure's duplicate white extreme-level drawings. Analysis is now the
// only layer that may display those levels, after validation.
// Build V47.48 (2026-09-03): restore raw completed-5m bridge facts for the
// validation ledger now owned by Analysis. C11-C14 publish the two current
// extreme-candle levels, their owner times, the latest completed-5m close,
// the automatic average-stop distance, and the current OB start. Structure
// still does not select, validate, lock, or invalidate an entry level.
// Build V47.47 (2026-09-03): promote the owner's displayed Structure input
// configuration to the source defaults. Calculation logic is unchanged.
// Build V47.46 (2026-09-03): move OUTSIDE OF TIMING WINDOW from the top-center
// discipline panel into the existing top-right OB status panel. The Analysis
// window begins when the OB opens; the forming phase remains WAIT FOR PRINT.
// Build V47.45 (2026-09-03): retire the optional Validation layer and its
// C11-C13 bridge exports. Structure and Analysis are the complete Current stack.
// Build V47.44 (2026-09-03): replace the top-center risk caption with editable
// per-session drawdown/trade limits and show when the timing window is closed.
// Build V47.43 (2026-09-03): gate Validation qualification to the completed-OB
// timing window through the existing C02 OB-complete/study-active flags.
// Build V47.42 (2026-09-03): anchor each completed-5m extreme line at its
// actual owner candle instead of the OB open, and publish both owner times for
// the separate Validation layer. Selection, permission, and invalidation do
// not change.
// Build V47.41 (2026-09-03): publish the two completed-5m OB-study candidate
// levels, the canonical study-window-active flag, and each completed 5m close
// for the separate Validation layer. Number state was already present in C03.
// Structure still does not duplicate Analysis setup selection or create an
// entry signal.
// Build V47.36 (2026-09-02): add visual-only upper and lower 1x opening-box
// range expansions for every enabled session. The completed canonical 1m OB
// owns both prices, the newest session replaces the prior pair, and neither
// expansion participates in setup permission or opposing-route construction.
// Build V47.34 (2026-09-02): make each closed-5m extreme-candle level style
// independently editable, with Dashed as the default visual.
// Build V47.33 (2026-09-02): add the canonical current-session OB phase to C02
// and introduce the high-timeframe summary display. On 8H and above, hide
// 8H/Daily and session-detail visuals while retaining Weekly/Monthly structure
// and the MTF key. The top-right panel becomes a lower-timeframe prompt.
// Build V47.32 (2026-09-02): select the two OB-study entry levels from
// completed canonical 5-minute candles. A forming 5-minute candle cannot
// create or move either level, and every host timeframe receives the same
// close-confirmed owners from the existing ordered 1-minute engine.
// Build V47.31 (2026-09-02): remove the OB-open price line and anchored VWAP,
// including their settings and historical line-segment storage. Keep the OB
// high/low, two canonical extreme-candle levels, ownership, and route logic.
// Build V47.30 (2026-09-02): replace the four post-OB time dividers with two
// canonical extreme-candle levels measured from OB open through window end:
// the high of the lowest-low candle and the low of the highest-high candle.
// OB high/low, open line, anchored VWAP, ownership, and routing are preserved.
// Build V47.29 (2026-09-02): keep Zero strictly close-confirmed: FOL->FOH or
// FOH->FOL on two consecutive completed candles. Monthly/Weekly Zero are
// neutral HTF bridges; custom-8H Zero is published to Analysis as a
// two-direction setup context. Daily Zero remains display-only.
// Build V47.28 (2026-09-02): add a confirmed display-only Zero context to the
// M/W/D/8H Prev key. Consecutive completed FOL->FOH or FOH->FOL candles print
// "0" during the following period without changing any permission or setup.
// Build V47.27 (2026-09-02): remove the OB 4.236 exhaustion veto completely.
// Structure no longer calculates or publishes OB fib-hit state. OB ownership,
// the analysis grid, and opposing-route behavior remain unchanged.
// Build V47.26 (2026-09-02): restore canonical OB ownership to the compact
// Analysis key through C02. The display now reports the same completed-box
// owner used by the opposing route; setup permissions and routing are unchanged.
// Build V47.25 (2026-09-02): Replay runtime guard. Keep the ordered Number
// route unchanged while reusing its work buffers, building round rungs in a
// bounded reverse merge, and removing a duplicate 200k-bar 1m range request.
// TOP-DOWN VISUAL TEST (2026-09-02): replace displayed OB fib extensions with
// four 30-minute grid marks after the OB closes, an OB-open line, and an
// OB-open anchored VWAP.
// FOUR-STATE LTF TEST (2026-09-02): publish only IN BO, IN BD, Daily/8H PB
// FAIL or CONT, and INSIDE. A completed Daily breakout close transfers the
// pullback state source from the Daily range to the active 8H range.
if timeframe.isseconds
    runtime.error("Ultimum Base Rebuild supports chart timeframes of 1 minute or higher.")
string TZ = "America/Los_Angeles"
string SHORT_SESSION_TZ = "America/Chicago"
int HOUR_MS = 60 * 60 * 1000
int FIFTEEN_MIN_MS = 15 * 60 * 1000
int DAY_MS = 24 * HOUR_MS
string contractRoot = syminfo.root
bool isGrainDaySession = contractRoot == "ZC" or contractRoot == "ZW" or contractRoot == "ZS" or contractRoot == "ZM" or contractRoot == "ZL" or contractRoot == "ZO" or contractRoot == "KE" or contractRoot == "ZR" or contractRoot == "MZW"
bool isLivestockDaySession = contractRoot == "GF" or contractRoot == "LE" or contractRoot == "HE"
bool isShortDaySessionProduct = isGrainDaySession or isLivestockDaySession
string shortDaySession = isGrainDaySession ? "0830-1320:23456" : "0830-1305:23456"
int shortDaySessionEndMinutes = isGrainDaySession ? 13 * 60 + 20 : 13 * 60 + 5
string G_WEEKLY_TF = "1 — WEEKLY TF SETTING (2D–1W)"
bool showYearlyRangesWeekly = input.bool(true, "Show Yearly ranges", group = G_WEEKLY_TF)
bool showYearlySeparatorsWeekly = input.bool(true, "Show Yearly separators", group = G_WEEKLY_TF)
int weeklyChartYearlyPeriodsToShow = input.int(30, "Yearly ranges to display", minval = 1, maxval = 60, group = G_WEEKLY_TF)
color yearlyRangeColor = input.color(color.rgb(65, 65, 65), "Yearly range color", group = G_WEEKLY_TF)
int yearlyRangeWidth = input.int(1, "Yearly range width", minval = 1, maxval = 3, group = G_WEEKLY_TF)
string yearlyRangeStyleInput = input.string("Dotted", "Yearly range style", options = ["Solid", "Dashed", "Dotted"], group = G_WEEKLY_TF)
int yearlyRangeStyleCode = yearlyRangeStyleInput == "Dashed" ? 2 : yearlyRangeStyleInput == "Dotted" ? 1 : 0
bool showPreviousYearCloseOnWeekly = input.bool(true, "Show prior Yearly close", group = G_WEEKLY_TF)
int previousYearClosePeriodsToShow = input.int(10, "Yearly close periods to display", minval = 1, maxval = 12, group = G_WEEKLY_TF)
color previousYearCloseColor = input.color(color.rgb(21, 49, 128), "Prior Yearly close color", group = G_WEEKLY_TF)
int previousYearCloseWidth = input.int(2, "Prior Yearly close width", minval = 1, maxval = 4, group = G_WEEKLY_TF)
string previousYearCloseStyleInput = input.string("Solid", "Prior Yearly close style", options = ["Solid", "Dashed", "Dotted"], group = G_WEEKLY_TF)
string previousYearCloseStyle = previousYearCloseStyleInput == "Dashed" ? line.style_dashed : previousYearCloseStyleInput == "Dotted" ? line.style_dotted : line.style_solid
bool showQuarterlyRangesWeekly = input.bool(true, "Show Quarterly ranges", group = G_WEEKLY_TF)
bool showQuarterlySeparatorsWeekly = input.bool(true, "Show Quarterly separators", group = G_WEEKLY_TF)
int weeklyChartQuarterlyPeriodsToShow = input.int(2, "Quarterly ranges to display", minval = 1, maxval = 12, group = G_WEEKLY_TF)
color quarterlyRangeColor = input.color(color.rgb(95, 70, 145), "Quarterly range color", group = G_WEEKLY_TF)
int quarterlyRangeWidth = input.int(1, "Quarterly range width", minval = 1, maxval = 4, group = G_WEEKLY_TF)
string quarterlyRangeStyleInput = input.string("Dotted", "Quarterly range style", options = ["Solid", "Dashed", "Dotted"], group = G_WEEKLY_TF)
int quarterlyRangeStyleCode = quarterlyRangeStyleInput == "Dashed" ? 2 : quarterlyRangeStyleInput == "Dotted" ? 1 : 0
bool showYearlySignalLabels = input.bool(true, "Show Yearly signals: IN / OT / Day 0 / CIB", group = G_WEEKLY_TF)
string yearSignalTextSizeInput = input.string("Tiny", "Year signal text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_WEEKLY_TF)
string yearSignalTextSize = yearSignalTextSizeInput == "Small" ? size.small : yearSignalTextSizeInput == "Normal" ? size.normal : yearSignalTextSizeInput == "Large" ? size.large : size.tiny
bool weeklyExtendSeparatorsFullHeight = input.bool(false, "Extend separators full height", group = G_WEEKLY_TF)
bool showYearThreeRangeBox = input.bool(true, "Black Year box: current + prior 2", group = G_WEEKLY_TF)
 
string G_EIGHT_HOUR_TF = "2 — DAILY TF SETTING (5H–1D)"
bool showMonthlyRangesOnDaily = input.bool(true, "Show Monthly ranges", group = G_EIGHT_HOUR_TF)
bool showMonthlySeparatorsEightHour = input.bool(true, "Show Monthly separators", group = G_EIGHT_HOUR_TF)
int visibleMonthlyRangeCount = input.int(12, "Monthly ranges to display", minval = 1, maxval = 24, group = G_EIGHT_HOUR_TF)
color monthlyRangeColor = input.color(color.rgb(95, 70, 145), "Monthly range color", group = G_EIGHT_HOUR_TF)
int monthlyRangeWidth = input.int(1, "Monthly range width", minval = 1, maxval = 4, group = G_EIGHT_HOUR_TF)
string monthlyRangeStyleInput = input.string("Dotted", "Monthly range style", options = ["Solid", "Dashed", "Dotted"], group = G_EIGHT_HOUR_TF)
int monthlyRangeStyleCode = monthlyRangeStyleInput == "Dashed" ? 2 : monthlyRangeStyleInput == "Dotted" ? 1 : 0
bool showPreviousMonthClose = input.bool(true, "Show prior Monthly close", group = G_EIGHT_HOUR_TF)
int previousMonthCloseMonthsToShow = input.int(12, "Monthly close periods to display", minval = 1, maxval = 24, group = G_EIGHT_HOUR_TF)
color previousMonthCloseColor = input.color(color.rgb(95, 70, 145), "Prior Monthly close color", group = G_EIGHT_HOUR_TF)
int previousMonthCloseWidth = input.int(2, "Prior Monthly close width", minval = 1, maxval = 4, group = G_EIGHT_HOUR_TF)
string previousMonthCloseStyleInput = input.string("Solid", "Prior Monthly close style", options = ["Solid", "Dashed", "Dotted"], group = G_EIGHT_HOUR_TF)
string previousMonthCloseStyle = previousMonthCloseStyleInput == "Dashed" ? line.style_dashed : previousMonthCloseStyleInput == "Dotted" ? line.style_dotted : line.style_solid
bool showWeeklyRangesOn8H = input.bool(true, "Show Weekly ranges", group = G_EIGHT_HOUR_TF)
bool showWeeklySeparatorsEightHour = input.bool(true, "Show Weekly separators", group = G_EIGHT_HOUR_TF)
int weeklyRangesOn8HCount = input.int(2, "Weekly ranges to display", minval = 1, maxval = 12, group = G_EIGHT_HOUR_TF)
color c8 = input.color(color.white, "Weekly range color", group = G_EIGHT_HOUR_TF)
int range8Width = input.int(1, "Weekly range width", minval = 1, maxval = 4, group = G_EIGHT_HOUR_TF)
string range8StyleInput = input.string("Dotted", "Weekly range style", options = ["Solid", "Dashed", "Dotted"], group = G_EIGHT_HOUR_TF)
int range8StyleCode = range8StyleInput == "Dashed" ? 2 : range8StyleInput == "Dotted" ? 1 : 0
bool showMonthlySignalLabels = input.bool(true, "Show Monthly signals: IN / OT / Day 0 / CIB", group = G_EIGHT_HOUR_TF)
string monthSignalTextSizeInput = input.string("Tiny", "Month signal text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_EIGHT_HOUR_TF)
string monthSignalTextSize = monthSignalTextSizeInput == "Small" ? size.small : monthSignalTextSizeInput == "Normal" ? size.normal : monthSignalTextSizeInput == "Large" ? size.large : size.tiny
bool dailyExtendSeparatorsFullHeight = input.bool(false, "Extend separators full height", group = G_EIGHT_HOUR_TF)
bool showMonthThreeRangeBox = input.bool(true, "Black Month box: current + prior 2", group = G_EIGHT_HOUR_TF)
 
string G_FIFTEEN_MINUTE_TF = "3 — 15 MIN TF SETTING (15M–4H)"
bool showDailyRangesFifteenMinute = input.bool(true, "Show Daily ranges", group = G_FIFTEEN_MINUTE_TF)
bool showDailySeparatorsFifteenMinute = input.bool(true, "Show Daily separators", group = G_FIFTEEN_MINUTE_TF)
int visibleDRangeCount = input.int(30, "Daily ranges to display", minval = 1, maxval = 60, group = G_FIFTEEN_MINUTE_TF)
color cD = input.color(color.rgb(65, 65, 65), "Daily range color", group = G_FIFTEEN_MINUTE_TF)
int structureWidth = input.int(1, "Daily range width", minval = 1, maxval = 3, group = G_FIFTEEN_MINUTE_TF)
string rangeDStyleInput = input.string("Dotted", "Daily range style", options = ["Solid", "Dashed", "Dotted"], group = G_FIFTEEN_MINUTE_TF)
int rangeDStyleCode = rangeDStyleInput == "Dashed" ? 2 : rangeDStyleInput == "Dotted" ? 1 : 0
bool showPreviousDayClose = input.bool(true, "Show prior Daily close", group = G_FIFTEEN_MINUTE_TF)
int previousDayCloseDaysToShow = input.int(30, "Daily close periods to display", minval = 1, maxval = 30, group = G_FIFTEEN_MINUTE_TF)
color previousDayCloseColor = input.color(color.rgb(21, 49, 128), "Prior Daily close color", group = G_FIFTEEN_MINUTE_TF)
int previousDayCloseWidth = input.int(2, "Prior Daily close width", minval = 1, maxval = 4, group = G_FIFTEEN_MINUTE_TF)
string previousDayCloseStyleInput = input.string("Solid", "Prior Daily close style", options = ["Solid", "Dashed", "Dotted"], group = G_FIFTEEN_MINUTE_TF)
string previousDayCloseStyle = previousDayCloseStyleInput == "Dashed" ? line.style_dashed : previousDayCloseStyleInput == "Dotted" ? line.style_dotted : line.style_solid
bool show8H = input.bool(true, "Show 8H ranges", group = G_FIFTEEN_MINUTE_TF)
bool showEightHourSeparatorsFifteenMinute = input.bool(true, "Show 8H separators", group = G_FIFTEEN_MINUTE_TF)
int visible8HRangeCount = input.int(2, "8H ranges to display", minval = 1, maxval = 30, group = G_FIFTEEN_MINUTE_TF)
color fifteenMinute8HRangeColor = input.color(color.white, "8H range color", group = G_FIFTEEN_MINUTE_TF)
int fifteenMinute8HRangeWidth = input.int(1, "8H range width", minval = 1, maxval = 4, group = G_FIFTEEN_MINUTE_TF)
string fifteenMinute8HRangeStyleInput = input.string("Dotted", "8H range style", options = ["Solid", "Dashed", "Dotted"], group = G_FIFTEEN_MINUTE_TF)
int fifteenMinute8HRangeStyleCode = fifteenMinute8HRangeStyleInput == "Dashed" ? 2 : fifteenMinute8HRangeStyleInput == "Dotted" ? 1 : 0
bool showWeekdayLabels = input.bool(true, "Show Monday-Friday labels", group = G_FIFTEEN_MINUTE_TF)
color weekdayLabelColor = input.color(color.black, "Weekday text color", group = G_FIFTEEN_MINUTE_TF)
string weekdayLabelSizeInput = input.string("Tiny", "Weekday text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_FIFTEEN_MINUTE_TF)
color mondayLabelColor = input.color(color.black, "Monday text color", group = G_FIFTEEN_MINUTE_TF)
bool showAsiaSessionColor = input.bool(true, "Asia session color", group = G_FIFTEEN_MINUTE_TF, inline = "asia")
color asiaSessionColor = input.color(color.new(color.rgb(255, 193, 7), 86), "Color", group = G_FIFTEEN_MINUTE_TF, inline = "asia")
bool showLondonSessionColor = input.bool(true, "London session color", group = G_FIFTEEN_MINUTE_TF, inline = "london")
color londonSessionColor = input.color(color.new(color.rgb(33, 150, 243), 86), "Color", group = G_FIFTEEN_MINUTE_TF, inline = "london")
bool showNewYorkSessionColor = input.bool(true, "New York session color", group = G_FIFTEEN_MINUTE_TF, inline = "newyork")
color newYorkSessionColor = input.color(color.new(color.rgb(244, 67, 54), 86), "Color", group = G_FIFTEEN_MINUTE_TF, inline = "newyork")
bool showDailySignalLabels = input.bool(true, "Show Daily signals: IN / OT / Day 0 / CIB", group = G_FIFTEEN_MINUTE_TF)
string daySignalTextSizeInput = input.string("Tiny", "Day signal text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_FIFTEEN_MINUTE_TF)
string daySignalTextSize = daySignalTextSizeInput == "Small" ? size.small : daySignalTextSizeInput == "Normal" ? size.normal : daySignalTextSizeInput == "Large" ? size.large : size.tiny
bool fifteenMinuteExtendSeparatorsFullHeight = input.bool(false, "Extend separators full height", group = G_FIFTEEN_MINUTE_TF)
bool showDayThreeRangeBox = input.bool(true, "Black Day box: current + prior 2", group = G_FIFTEEN_MINUTE_TF)
 
string G_FIFTEEN_AND_UNDER = "4 — 1 MIN TF SETTING (1M–14M)"
bool showSessionHourSeparators = input.bool(true, "Show 1-2-3-4 hour separators", group = G_FIFTEEN_AND_UNDER)
string sessionHourTextSizeInput = input.string("Tiny", "Hour number text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_FIFTEEN_AND_UNDER)
string sessionHourTextSize = sessionHourTextSizeInput == "Small" ? size.small : sessionHourTextSizeInput == "Normal" ? size.normal : sessionHourTextSizeInput == "Large" ? size.large : size.tiny
color sessionHourLabelTextColor = color.black
color sessionHourLabelBackground = color.new(color.black, 100)
bool entryShow1HRanges = input.bool(true, "Show 1H ranges", group = G_FIFTEEN_AND_UNDER)
bool entryShow1HSeparators = input.bool(true, "Show 1H separators", group = G_FIFTEEN_AND_UNDER)
int entryVisible1HRangeCount = input.int(12, "1H ranges to display", minval = 1, maxval = 60, group = G_FIFTEEN_AND_UNDER)
color entryRange1HColor = input.color(color.rgb(95, 95, 95), "1H range color", group = G_FIFTEEN_AND_UNDER)
int entryRange1HWidth = input.int(1, "1H range width", minval = 1, maxval = 4, group = G_FIFTEEN_AND_UNDER)
string entryRange1HStyleInput = input.string("Dotted", "1H range style", options = ["Solid", "Dashed", "Dotted"], group = G_FIFTEEN_AND_UNDER)
int entryRange1HStyleCode = entryRange1HStyleInput == "Dashed" ? 2 : entryRange1HStyleInput == "Dotted" ? 1 : 0
bool entryShowPrevious1HClose = input.bool(true, "Show prior 1H close", group = G_FIFTEEN_AND_UNDER)
int entryPrevious1HClosePeriodsToShow = input.int(12, "1H close periods to display", minval = 1, maxval = 60, group = G_FIFTEEN_AND_UNDER)
color entryPrevious1HCloseColor = input.color(color.rgb(21, 49, 128), "Prior 1H close color", group = G_FIFTEEN_AND_UNDER)
int entryPrevious1HCloseWidth = input.int(2, "Prior 1H close width", minval = 1, maxval = 4, group = G_FIFTEEN_AND_UNDER)
string entryPrevious1HCloseStyleInput = input.string("Solid", "Prior 1H close style", options = ["Solid", "Dashed", "Dotted"], group = G_FIFTEEN_AND_UNDER)
string entryPrevious1HCloseStyle = entryPrevious1HCloseStyleInput == "Dashed" ? line.style_dashed : entryPrevious1HCloseStyleInput == "Dotted" ? line.style_dotted : line.style_solid
bool showOneHourSignalLabels = input.bool(true, "Show 1H signals on hours 1-3: IN / OT / Day 0 / CIB", group = G_FIFTEEN_AND_UNDER)
string oneHourSignalTextSizeInput = input.string("Tiny", "1H signal text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_FIFTEEN_AND_UNDER)
string oneHourSignalTextSize = oneHourSignalTextSizeInput == "Small" ? size.small : oneHourSignalTextSizeInput == "Normal" ? size.normal : oneHourSignalTextSizeInput == "Large" ? size.large : size.tiny
bool oneMinuteExtendSeparatorsFullHeight = input.bool(false, "Extend separators full height", group = G_FIFTEEN_AND_UNDER)
string G_TEMPLATES = "5 — TEMPLATES"
color signalTextColor = input.color(color.black, "Signal text color", group = G_TEMPLATES)
color inExtensionColor = input.color(color.rgb(33, 96, 220), "IN extension color", group = G_TEMPLATES)
int inExtensionWidth = input.int(2, "IN extension width", minval = 1, maxval = 4, group = G_TEMPLATES)
string inExtensionStyleInput = input.string("Solid", "IN extension style", options = ["Solid", "Dashed", "Dotted"], group = G_TEMPLATES)
string inExtensionStyle = inExtensionStyleInput == "Dashed" ? line.style_dashed : inExtensionStyleInput == "Dotted" ? line.style_dotted : line.style_solid
bool showINProjections = input.bool(true, "Show IN H/L extensions", group = G_TEMPLATES)
color yearBoxBorderColor = input.color(color.black, "Year box border color", group = G_TEMPLATES)
int yearBoxBorderWidth = input.int(2, "Year box border width", minval = 1, maxval = 4, group = G_TEMPLATES)
string yearBoxBorderStyleInput = input.string("Solid", "Year box border style", options = ["Solid", "Dashed", "Dotted"], group = G_TEMPLATES)
string yearBoxBorderStyle = yearBoxBorderStyleInput == "Dashed" ? line.style_dashed : yearBoxBorderStyleInput == "Dotted" ? line.style_dotted : line.style_solid
color monthBoxBorderColor = input.color(color.black, "Month box border color", group = G_TEMPLATES)
int monthBoxBorderWidth = input.int(2, "Month box border width", minval = 1, maxval = 4, group = G_TEMPLATES)
string monthBoxBorderStyleInput = input.string("Solid", "Month box border style", options = ["Solid", "Dashed", "Dotted"], group = G_TEMPLATES)
string monthBoxBorderStyle = monthBoxBorderStyleInput == "Dashed" ? line.style_dashed : monthBoxBorderStyleInput == "Dotted" ? line.style_dotted : line.style_solid
color dayBoxBorderColor = input.color(color.black, "Day box border color", group = G_TEMPLATES)
int dayBoxBorderWidth = input.int(2, "Day box border width", minval = 1, maxval = 4, group = G_TEMPLATES)
string dayBoxBorderStyleInput = input.string("Solid", "Day box border style", options = ["Solid", "Dashed", "Dotted"], group = G_TEMPLATES)
string dayBoxBorderStyle = dayBoxBorderStyleInput == "Dashed" ? line.style_dashed : dayBoxBorderStyleInput == "Dotted" ? line.style_dotted : line.style_solid
string G_DETAILS_V44 = "6 — DETAILS DISPLAY"
bool showDetailsV44 = input.bool(true, "Show Details", group = G_DETAILS_V44)
string detailsSizeInputV44 = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_DETAILS_V44)
bool showExchangeV44 = input.bool(false, "Include exchange", group = G_DETAILS_V44)
color detailsTextColorV44 = input.color(color.white, "Text color", group = G_DETAILS_V44)
string detailsTextSizeV44 = detailsSizeInputV44 == "Tiny" ? size.tiny : detailsSizeInputV44 == "Normal" ? size.normal : detailsSizeInputV44 == "Large" ? size.large : size.small
f_short_session_ranges_1m() =>
    bool sourceInSession = isShortDaySessionProduct and not na(time(timeframe.period, shortDaySession, SHORT_SESSION_TZ))
    int sourceSessionStart = sourceInSession ? timestamp(SHORT_SESSION_TZ, year(time, SHORT_SESSION_TZ), month(time, SHORT_SESSION_TZ), dayofmonth(time, SHORT_SESSION_TZ), 8, 30) : na
    int sourceSessionEnd = sourceInSession ? timestamp(SHORT_SESSION_TZ, year(time, SHORT_SESSION_TZ), month(time, SHORT_SESSION_TZ), dayofmonth(time, SHORT_SESSION_TZ), int(math.floor(shortDaySessionEndMinutes / 60)), shortDaySessionEndMinutes % 60) : na
    int sourceNativeDayStart = sourceInSession ? time("D") : na
    int sourceNativeDayEnd = sourceInSession ? time_close("D") : na
    int sourceMinutes = hour(time, SHORT_SESSION_TZ) * 60 + minute(time, SHORT_SESSION_TZ)
    int source1HIndex = sourceInSession ? int(math.floor(float(sourceMinutes - 8 * 60 - 30) / 60.0)) : na
    int source1HStart = sourceInSession ? sourceSessionStart + source1HIndex * HOUR_MS : na
    int source1HEnd = sourceInSession ? math.min(source1HStart + HOUR_MS, sourceSessionEnd) : na
    var float activeDayHigh = na
    var float activeDayLow = na
    var float activeDayClose = na
    var int activeDayStart = na
    var int activeDayEnd = na
    var float completedDayHigh = na
    var float completedDayLow = na
    var float completedDayClose = na
    var int completedDayStart = na
    var int completedDayEnd = na
    var float active1HHigh = na
    var float active1HLow = na
    var float active1HClose = na
    var int active1HStart = na
    var int active1HEnd = na
    var float completed1HHigh = na
    var float completed1HLow = na
    var float completed1HClose = na
    var int completed1HStart = na
    var int completed1HEnd = na
    if sourceInSession
        if na(activeDayStart) or sourceNativeDayStart != activeDayStart
            if not na(activeDayStart)
                completedDayHigh := activeDayHigh
                completedDayLow := activeDayLow
                completedDayClose := activeDayClose
                completedDayStart := activeDayStart
                completedDayEnd := activeDayEnd
            activeDayHigh := high
            activeDayLow := low
            activeDayClose := close
            activeDayStart := sourceNativeDayStart
            activeDayEnd := sourceNativeDayEnd
        else
            activeDayHigh := math.max(activeDayHigh, high)
            activeDayLow := math.min(activeDayLow, low)
            activeDayClose := close
        if na(active1HStart) or source1HStart != active1HStart
            if not na(active1HStart)
                completed1HHigh := active1HHigh
                completed1HLow := active1HLow
                completed1HClose := active1HClose
                completed1HStart := active1HStart
                completed1HEnd := active1HEnd
            active1HHigh := high
            active1HLow := low
            active1HClose := close
            active1HStart := source1HStart
            active1HEnd := source1HEnd
        else
            active1HHigh := math.max(active1HHigh, high)
            active1HLow := math.min(active1HLow, low)
            active1HClose := close
    [completedDayHigh, completedDayLow, completedDayClose, completedDayStart, completedDayEnd, completed1HHigh, completed1HLow, completed1HClose, completed1HStart, completed1HEnd, active1HStart, active1HEnd]
f_clock_hour_ranges_1m() =>
    int sourceHourStart = timestamp(syminfo.timezone, year(time, syminfo.timezone), month(time, syminfo.timezone), dayofmonth(time, syminfo.timezone), hour(time, syminfo.timezone), 0)
    int sourceHourEnd = sourceHourStart + HOUR_MS
    var float activeHourHigh = na
    var float activeHourLow = na
    var float activeHourClose = na
    var int activeHourStart = na
    var int activeHourEnd = na
    var int activeFirstBarTime = na
    var int activeLastBarClose = na
    var float completedHourHigh = na
    var float completedHourLow = na
    var float completedHourClose = na
    var int completedHourStart = na
    var int completedHourEnd = na
    var int completedFirstBarTime = na
    var int completedLastBarClose = na
    if na(activeHourStart) or sourceHourStart != activeHourStart
        if not na(activeHourStart)
            completedHourHigh := activeHourHigh
            completedHourLow := activeHourLow
            completedHourClose := activeHourClose
            completedHourStart := activeHourStart
            completedHourEnd := activeHourEnd
            completedFirstBarTime := activeFirstBarTime
            completedLastBarClose := activeLastBarClose
        activeHourHigh := high
        activeHourLow := low
        activeHourClose := close
        activeHourStart := sourceHourStart
        activeHourEnd := sourceHourEnd
        activeFirstBarTime := time
        activeLastBarClose := time_close
    else
        activeHourHigh := math.max(activeHourHigh, high)
        activeHourLow := math.min(activeHourLow, low)
        activeHourClose := close
        activeLastBarClose := time_close
    [completedHourHigh, completedHourLow, completedHourClose, completedHourStart, completedHourEnd, completedFirstBarTime, completedLastBarClose]
f_push_range(array<line> store, int x1, int x2, float hi, float lo, color col, int lineWidth, int styleCode, int maxRanges) =>
    line lh = line.new(x1, hi, x2, hi, xloc = xloc.bar_time, color = col, width = lineWidth, style = styleCode == 2 ? line.style_dashed : styleCode == 1 ? line.style_dotted : line.style_solid)
    line ll = line.new(x1, lo, x2, lo, xloc = xloc.bar_time, color = col, width = lineWidth, style = styleCode == 2 ? line.style_dashed : styleCode == 1 ? line.style_dotted : line.style_solid)
    array.push(store, lh)
    array.push(store, ll)
    while array.size(store) > maxRanges * 2
        line.delete(array.shift(store))
f_push_separator_borders(array<line> store, int x1, int x2, float hi, float lo, color col, int lineWidth, string lineStyle, int maxRanges, bool extendFullHeight) =>
    string separatorExtend = extendFullHeight ? extend.both : extend.none
    line leftBorder = line.new(x1, lo, x1, hi, xloc = xloc.bar_time, extend = separatorExtend, color = col, width = lineWidth, style = lineStyle)
    line rightBorder = line.new(x2, lo, x2, hi, xloc = xloc.bar_time, extend = separatorExtend, color = col, width = lineWidth, style = lineStyle)
    array.push(store, leftBorder)
    array.push(store, rightBorder)
    while array.size(store) > maxRanges * 2
        line.delete(array.shift(store))
f_update_daily_separators(array<line> dailyStore, line sharedBoundary, bool addDailyBoundary, float dayHigh, float dayLow, int currentDayStart, color dayColor, int dayLineWidth, string dayStyle, int maxDailyRanges, bool extendFullHeight) =>
    if addDailyBoundary and not na(sharedBoundary)
        line.set_y1(sharedBoundary, math.min(line.get_y1(sharedBoundary), dayLow))
        line.set_y2(sharedBoundary, math.max(line.get_y2(sharedBoundary), dayHigh))
    line nextSharedBoundary = sharedBoundary
    if addDailyBoundary
        string separatorExtend = extendFullHeight ? extend.both : extend.none
        nextSharedBoundary := line.new(currentDayStart, dayLow, currentDayStart, dayHigh, xloc = xloc.bar_time, extend = separatorExtend, color = dayColor, width = dayLineWidth, style = dayStyle)
        array.push(dailyStore, nextSharedBoundary)
        while array.size(dailyStore) > maxDailyRanges + 1
            line.delete(array.shift(dailyStore))
    nextSharedBoundary
f_native_range_visual_bundle() =>
    [high[1], low[1], close[1], time, time[1]]
f_three_range_box_bundle() =>
    float combinedHigh = math.max(high, math.max(high[1], high[2]))
    float combinedLow = math.min(low, math.min(low[1], low[2]))
    [combinedHigh, combinedLow, time[2], time_close]
f_range_signal_code(float currentHigh, float currentLow, float currentClose, float previousHigh, float previousLow, float previousClose, float baseHigh, float baseLow) =>
    bool validSignalData = not na(currentHigh) and not na(currentLow) and not na(currentClose) and not na(previousHigh) and not na(previousLow) and not na(previousClose) and not na(baseHigh) and not na(baseLow)
    bool currentBreakHigh = validSignalData and currentHigh > previousHigh
    bool currentBreakLow = validSignalData and currentLow < previousLow
    bool currentCloseInside = validSignalData and currentClose <= previousHigh and currentClose >= previousLow
    bool currentHighFakeout = currentBreakHigh and not currentBreakLow and currentCloseInside
    bool currentLowFakeout = currentBreakLow and not currentBreakHigh and currentCloseInside
    bool previousCloseInsideBase = validSignalData and previousClose <= baseHigh and previousClose >= baseLow
    bool previousHighFakeout = validSignalData and previousHigh > baseHigh and previousLow >= baseLow and previousCloseInsideBase
    bool previousLowFakeout = validSignalData and previousLow < baseLow and previousHigh <= baseHigh and previousCloseInsideBase
    bool closeInBreakout = validSignalData and (currentClose > previousHigh or currentClose < previousLow)
    bool outsideRange = currentBreakHigh and currentBreakLow and currentCloseInside
    bool dayZero = (currentHighFakeout and previousLowFakeout) or (currentLowFakeout and previousHighFakeout)
    bool insideRange = not currentBreakHigh and not currentBreakLow and currentCloseInside
    closeInBreakout ? 4 : outsideRange ? 2 : dayZero ? 3 : insideRange ? 1 : 0
f_completed_range_signal_bundle() =>
    int signalCode = f_range_signal_code(high[1], low[1], close[1], high[2], low[2], close[2], high[3], low[3])
    [signalCode, time[1], time_close[1], high[1], low[1]]
f_signal_text(int signalCode) =>
    signalCode == 1 ? "IN" : signalCode == 2 ? "OT" : signalCode == 3 ? "Day 0" : signalCode == 4 ? "CIB" : ""
f_push_signal_label(array<label> store, int periodStart, int periodEnd, float labelY, int signalCode, string textSize, int maxLabels) =>
    label resultLabel = na
    if signalCode > 0 and not na(periodStart) and not na(periodEnd) and not na(labelY)
        int midpointTime = periodStart + int((periodEnd - periodStart) / 2)
        resultLabel := label.new(midpointTime, labelY, f_signal_text(signalCode), xloc = xloc.bar_time, yloc = yloc.price, color = color.new(color.black, 100), style = label.style_none, textcolor = signalTextColor, size = textSize)
        array.push(store, resultLabel)
        while array.size(store) > maxLabels
            label.delete(array.shift(store))
    resultLabel
f_set_signal_label_row(array<label> store, float rangeTop, float rangeBottom, float rowFraction) =>
    int updatedLabels = 0
    if array.size(store) > 0 and not na(rangeTop) and not na(rangeBottom)
        float labelY = rangeBottom + math.max((rangeTop - rangeBottom) * rowFraction, syminfo.mintick * 10)
        for labelIndex = 0 to array.size(store) - 1
            label.set_y(array.get(store, labelIndex), labelY)
            updatedLabels += 1
    updatedLabels
f_clear_signal_labels(array<label> store) =>
    int deletedLabels = 0
    while array.size(store) > 0
        label.delete(array.shift(store))
        deletedLabels += 1
    deletedLabels
f_trim_signal_labels_to_box(array<label> store, int boxLeftTime) =>
    int trimmedLabels = 0
    while array.size(store) > 0 and not na(boxLeftTime) and label.get_x(array.get(store, 0)) < boxLeftTime
        label.delete(array.shift(store))
        trimmedLabels += 1
    trimmedLabels
f_push_in_projection(array<line> lineStore, array<int> originStore, int originStart, float insideHigh, float insideLow, int projectionStart, int projectionEnd, color projectionColor, int projectionWidth, string projectionStyle, int maxPeriods) =>
    int addedLines = 0
    if not na(originStart) and not na(insideHigh) and not na(insideLow) and not na(projectionStart) and not na(projectionEnd)
        array.push(lineStore, line.new(projectionStart, insideHigh, projectionEnd, insideHigh, xloc = xloc.bar_time, extend = extend.none, color = projectionColor, width = projectionWidth, style = projectionStyle))
        array.push(lineStore, line.new(projectionStart, insideLow, projectionEnd, insideLow, xloc = xloc.bar_time, extend = extend.none, color = projectionColor, width = projectionWidth, style = projectionStyle))
        array.push(originStore, originStart)
        addedLines := 2
        while array.size(originStore) > maxPeriods
            array.shift(originStore)
            line.delete(array.shift(lineStore))
            line.delete(array.shift(lineStore))
    addedLines
f_trim_in_projections_to_box(array<line> lineStore, array<int> originStore, int boxLeftTime) =>
    int removedLines = 0
    while array.size(originStore) > 0 and not na(boxLeftTime) and array.get(originStore, 0) < boxLeftTime
        array.shift(originStore)
        line.delete(array.shift(lineStore))
        line.delete(array.shift(lineStore))
        removedLines += 2
    removedLines
f_update_in_projection_span(array<line> lineStore, int projectionStart, int projectionEnd) =>
    int updatedLines = 0
    if array.size(lineStore) > 0 and not na(projectionStart) and not na(projectionEnd)
        for projectionLineIndex = 0 to array.size(lineStore) - 1
            line projectionLine = array.get(lineStore, projectionLineIndex)
            line.set_x1(projectionLine, projectionStart)
            line.set_x2(projectionLine, projectionEnd)
            updatedLines += 1
    updatedLines
f_clear_in_projections(array<line> lineStore, array<int> originStore) =>
    int deletedLines = 0
    while array.size(lineStore) > 0
        line.delete(array.shift(lineStore))
        deletedLines += 1
    array.clear(originStore)
    deletedLines
f_update_three_range_box(box existingBox, bool visible, int leftTime, int rightTime, float topPrice, float bottomPrice, color borderColor, int borderWidth, string borderStyle) =>
    box resultBox = existingBox
    bool validBox = visible and not na(leftTime) and not na(rightTime) and not na(topPrice) and not na(bottomPrice)
    if validBox
        if na(resultBox)
            resultBox := box.new(leftTime, topPrice, rightTime, bottomPrice, xloc = xloc.bar_time, extend = extend.none, border_color = borderColor, border_width = borderWidth, border_style = borderStyle, bgcolor = color.new(color.black, 100))
        else
            box.set_left(resultBox, leftTime)
            box.set_right(resultBox, rightTime)
            box.set_top(resultBox, topPrice)
            box.set_bottom(resultBox, bottomPrice)
            box.set_border_color(resultBox, borderColor)
            box.set_border_width(resultBox, borderWidth)
            box.set_border_style(resultBox, borderStyle)
    else if not na(resultBox)
        box.delete(resultBox)
        resultBox := na
    resultBox
float chartTimeframeSeconds = timeframe.in_seconds()
bool exactFifteenMinuteChartMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds == 15 * 60
bool entryChartTimeframeMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds < 15 * 60
bool activeShowPreviousDayClose = showPreviousDayClose
int activePreviousDayCloseDaysToShow = previousDayCloseDaysToShow
color activePreviousDayCloseColor = previousDayCloseColor
int activePreviousDayCloseWidth = previousDayCloseWidth
string activePreviousDayCloseStyle = previousDayCloseStyle
bool dailyChartTimeframeMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds >= 15 * 60 and chartTimeframeSeconds <= 4 * 60 * 60
bool previousDayCloseChartTimeframeMatch = dailyChartTimeframeMatch
bool isExactDailyChart = timeframe.isdaily and timeframe.multiplier == 1
bool isExactWeeklyChart = timeframe.isweekly and timeframe.multiplier == 1
bool weeklyChartTimeframeMatch = isExactWeeklyChart or (timeframe.isdaily and timeframe.multiplier > 1)
bool dailySectionChartTimeframeMatch = isExactDailyChart or (timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds > 4 * 60 * 60)
[shortCompletedDayHigh, shortCompletedDayLow, shortCompletedDayClose, shortCompletedDayStart, shortCompletedDayEnd, shortCompleted1HHigh, shortCompleted1HLow, shortCompleted1HClose, shortCompleted1HStart, shortCompleted1HEnd, shortActive1HStart, shortActive1HEnd] = request.security(syminfo.tickerid, "1", f_short_session_ranges_1m(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
bool inShortDaySessionOnChart = isShortDaySessionProduct and timeframe.isintraday and not na(time(timeframe.period, shortDaySession, SHORT_SESSION_TZ))
int localShortDayStart = inShortDaySessionOnChart ? timestamp(SHORT_SESSION_TZ, year(time, SHORT_SESSION_TZ), month(time, SHORT_SESSION_TZ), dayofmonth(time, SHORT_SESSION_TZ), 8, 30) : na
int localShortDayEnd = inShortDaySessionOnChart ? timestamp(SHORT_SESSION_TZ, year(time, SHORT_SESSION_TZ), month(time, SHORT_SESSION_TZ), dayofmonth(time, SHORT_SESSION_TZ), int(math.floor(shortDaySessionEndMinutes / 60)), shortDaySessionEndMinutes % 60) : na
int rawNativeDayStart = timeframe.isintraday ? time("D") : na
int rawNativeDayEnd = timeframe.isintraday ? time_close("D") : na
bool extendedHolidayDay = timeframe.isintraday and not na(rawNativeDayStart) and not na(rawNativeDayEnd) and rawNativeDayEnd - rawNativeDayStart > 36 * HOUR_MS
int nativeDaySegmentIndex = extendedHolidayDay ? int(math.max(0.0, math.floor(float(time - rawNativeDayStart) / DAY_MS))) : 0
int nativeDayStart = extendedHolidayDay ? rawNativeDayStart + nativeDaySegmentIndex * DAY_MS : rawNativeDayStart
int nativeDayEnd = extendedHolidayDay ? math.min(nativeDayStart + DAY_MS, rawNativeDayEnd) : rawNativeDayEnd
bool newDay = isShortDaySessionProduct ? inShortDaySessionOnChart and (barstate.isfirst or na(localShortDayStart[1]) or localShortDayStart != localShortDayStart[1]) : timeframe.isintraday and ta.change(nativeDayStart) != 0
bool newWeek = ta.change(time("W")) != 0
bool newMonth = ta.change(time("M")) != 0
bool newQuarter = ta.change(time("3M")) != 0
bool newYear = ta.change(time("12M")) != 0
bool weekdayLabelsSupportedChart = not na(chartTimeframeSeconds) and chartTimeframeSeconds == 15 * 60
bool sevenDayMarket = syminfo.type == "crypto"
int chartMinutesChicago = hour(time, SHORT_SESSION_TZ) * 60 + minute(time, SHORT_SESSION_TZ)
int grainTradingDayOffset = chartMinutesChicago >= 19 * 60 ? 0 : -1
int grainTradingDayStart = isGrainDaySession and timeframe.isintraday ? timestamp(SHORT_SESSION_TZ, year(time, SHORT_SESSION_TZ), month(time, SHORT_SESSION_TZ), dayofmonth(time, SHORT_SESSION_TZ) + grainTradingDayOffset, 19, 0) : na
int grainTradingDayEnd = isGrainDaySession and timeframe.isintraday ? timestamp(SHORT_SESSION_TZ, year(time, SHORT_SESSION_TZ), month(time, SHORT_SESSION_TZ), dayofmonth(time, SHORT_SESSION_TZ) + grainTradingDayOffset + 1, 13, 20) : na
int weekdayLabelPeriodStart = isGrainDaySession ? grainTradingDayStart : isLivestockDaySession ? localShortDayStart : nativeDayStart
int weekdayLabelPeriodEnd = isGrainDaySession ? grainTradingDayEnd : isLivestockDaySession ? localShortDayEnd : nativeDayEnd
int weekdayLabelMidpointTime = weekdayLabelsSupportedChart and not na(weekdayLabelPeriodStart) and not na(weekdayLabelPeriodEnd) ? weekdayLabelPeriodStart + int((weekdayLabelPeriodEnd - weekdayLabelPeriodStart) / 2) : na
bool weekdayLabelCrossesMidpoint = not na(weekdayLabelMidpointTime) and time <= weekdayLabelMidpointTime and time_close > weekdayLabelMidpointTime
bool weekdayLabelFirstAfterMidpoint = not na(weekdayLabelMidpointTime) and time > weekdayLabelMidpointTime and (barstate.isfirst or newDay or time_close[1] <= weekdayLabelMidpointTime)
bool agriculturalWeekdayLabelCandidate = isShortDaySessionProduct and weekdayLabelCrossesMidpoint
bool standardWeekdayLabelCandidate = not isShortDaySessionProduct and (weekdayLabelCrossesMidpoint or weekdayLabelFirstAfterMidpoint)
var int renderedWeekdayLabelPeriodEnd = na
bool weekdayLabelCenterBar = showWeekdayLabels and weekdayLabelsSupportedChart and (agriculturalWeekdayLabelCandidate or standardWeekdayLabelCandidate) and not na(weekdayLabelPeriodEnd) and (na(renderedWeekdayLabelPeriodEnd) or weekdayLabelPeriodEnd != renderedWeekdayLabelPeriodEnd)
if weekdayLabelCenterBar
    renderedWeekdayLabelPeriodEnd := weekdayLabelPeriodEnd
int weekdayLabelDay = weekdayLabelCenterBar ? dayofweek(sevenDayMarket ? nativeDayStart : weekdayLabelPeriodEnd) : na
// Native Monthly values provide complete Daily-hosted Monthly context and
// separator geometry without depending on partial Daily-host history.
[canonicalMH1, canonicalML1, canonicalMC1, canonicalMT1, canonicalMT2] = request.security(syminfo.tickerid, "M", f_native_range_visual_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[canonicalQH1, canonicalQL1, canonicalQC1, canonicalQT1, canonicalQT2] = request.security(syminfo.tickerid, "3M", f_native_range_visual_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[canonicalWH1, canonicalWL1, canonicalWC1, canonicalWT1, canonicalWT2] = request.security(syminfo.tickerid, "W", f_native_range_visual_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[canonicalYH1, canonicalYL1, canonicalYC1, canonicalYT1, canonicalYT2] = request.security(syminfo.tickerid, "12M", f_native_range_visual_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[yearThreeRangeHigh, yearThreeRangeLow, yearThreeRangeStart, yearThreeRangeEnd] = request.security(syminfo.tickerid, "12M", f_three_range_box_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[monthThreeRangeHigh, monthThreeRangeLow, monthThreeRangeStart, monthThreeRangeEnd] = request.security(syminfo.tickerid, "M", f_three_range_box_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[dayThreeRangeHigh, dayThreeRangeLow, dayThreeRangeStart, dayThreeRangeEnd] = request.security(syminfo.tickerid, "D", f_three_range_box_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[yearSignalCode, yearSignalStart, yearSignalEnd, yearSignalHigh, yearSignalLow] = request.security(syminfo.tickerid, "12M", f_completed_range_signal_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[quarterSignalCode, quarterSignalStart, quarterSignalEnd, quarterSignalHigh, quarterSignalLow] = request.security(syminfo.tickerid, "3M", f_completed_range_signal_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[monthSignalCode, monthSignalStart, monthSignalEnd, monthSignalHigh, monthSignalLow] = request.security(syminfo.tickerid, "M", f_completed_range_signal_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[weekSignalCode, weekSignalStart, weekSignalEnd, weekSignalHigh, weekSignalLow] = request.security(syminfo.tickerid, "W", f_completed_range_signal_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[daySignalCode, daySignalStart, daySignalEnd, daySignalHigh, daySignalLow] = request.security(syminfo.tickerid, "D", f_completed_range_signal_bundle(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
var box yearThreeRangeBox = na
var box monthThreeRangeBox = na
var box dayThreeRangeBox = na
yearThreeRangeBox := f_update_three_range_box(yearThreeRangeBox, showYearThreeRangeBox and weeklyChartTimeframeMatch, yearThreeRangeStart, yearThreeRangeEnd, yearThreeRangeHigh, yearThreeRangeLow, yearBoxBorderColor, yearBoxBorderWidth, yearBoxBorderStyle)
monthThreeRangeBox := f_update_three_range_box(monthThreeRangeBox, showMonthThreeRangeBox and dailySectionChartTimeframeMatch, monthThreeRangeStart, monthThreeRangeEnd, monthThreeRangeHigh, monthThreeRangeLow, monthBoxBorderColor, monthBoxBorderWidth, monthBoxBorderStyle)
dayThreeRangeBox := f_update_three_range_box(dayThreeRangeBox, showDayThreeRangeBox and dailyChartTimeframeMatch, dayThreeRangeStart, dayThreeRangeEnd, dayThreeRangeHigh, dayThreeRangeLow, dayBoxBorderColor, dayBoxBorderWidth, dayBoxBorderStyle)
var array<label> yearlySignalLabels = array.new_label()
var array<label> monthlySignalLabels = array.new_label()
var array<label> dailySignalLabels = array.new_label()
var int renderedYearSignalStart = na
var int renderedMonthSignalStart = na
var int renderedDaySignalStart = na
bool yearlySignalsVisible = showYearlySignalLabels and showYearThreeRangeBox and weeklyChartTimeframeMatch
bool monthlySignalsVisible = showMonthlySignalLabels and showMonthThreeRangeBox and dailySectionChartTimeframeMatch
bool dailySignalsVisible = showDailySignalLabels and showDayThreeRangeBox and dailyChartTimeframeMatch
if yearlySignalsVisible and not na(yearSignalStart) and (na(renderedYearSignalStart) or yearSignalStart != renderedYearSignalStart)
    f_push_signal_label(yearlySignalLabels, yearSignalStart, yearSignalEnd, yearThreeRangeLow, yearSignalCode, yearSignalTextSize, 3)
    renderedYearSignalStart := yearSignalStart
if monthlySignalsVisible and not na(monthSignalStart) and (na(renderedMonthSignalStart) or monthSignalStart != renderedMonthSignalStart)
    f_push_signal_label(monthlySignalLabels, monthSignalStart, monthSignalEnd, monthThreeRangeLow, monthSignalCode, monthSignalTextSize, 3)
    renderedMonthSignalStart := monthSignalStart
if dailySignalsVisible and not na(daySignalStart) and (na(renderedDaySignalStart) or daySignalStart != renderedDaySignalStart)
    f_push_signal_label(dailySignalLabels, daySignalStart, daySignalEnd, dayThreeRangeLow, daySignalCode, daySignalTextSize, 3)
    renderedDaySignalStart := daySignalStart
if yearlySignalsVisible
    f_trim_signal_labels_to_box(yearlySignalLabels, yearThreeRangeStart)
    f_set_signal_label_row(yearlySignalLabels, yearThreeRangeHigh, yearThreeRangeLow, 0.035)
else
    f_clear_signal_labels(yearlySignalLabels)
    renderedYearSignalStart := na
if monthlySignalsVisible
    f_trim_signal_labels_to_box(monthlySignalLabels, monthThreeRangeStart)
    f_set_signal_label_row(monthlySignalLabels, monthThreeRangeHigh, monthThreeRangeLow, 0.035)
else
    f_clear_signal_labels(monthlySignalLabels)
    renderedMonthSignalStart := na
if dailySignalsVisible
    f_trim_signal_labels_to_box(dailySignalLabels, dayThreeRangeStart)
    f_set_signal_label_row(dailySignalLabels, dayThreeRangeHigh, dayThreeRangeLow, 0.035)
else
    f_clear_signal_labels(dailySignalLabels)
    renderedDaySignalStart := na
var array<line> yearlyINProjectionLines = array.new_line()
var array<int> yearlyINProjectionOrigins = array.new_int()
var array<line> monthlyINProjectionLines = array.new_line()
var array<int> monthlyINProjectionOrigins = array.new_int()
var array<line> dailyINProjectionLines = array.new_line()
var array<int> dailyINProjectionOrigins = array.new_int()
var int renderedYearINProjectionStart = na
var int renderedMonthINProjectionStart = na
var int renderedDayINProjectionStart = na
bool yearlyINProjectionVisible = showINProjections and showYearThreeRangeBox and weeklyChartTimeframeMatch
bool monthlyINProjectionVisible = showINProjections and showMonthThreeRangeBox and dailySectionChartTimeframeMatch
bool dailyINProjectionVisible = showINProjections and showDayThreeRangeBox and dailyChartTimeframeMatch
if yearlyINProjectionVisible and not na(yearSignalStart) and (na(renderedYearINProjectionStart) or yearSignalStart != renderedYearINProjectionStart)
    if yearSignalCode == 1
        f_push_in_projection(yearlyINProjectionLines, yearlyINProjectionOrigins, yearSignalStart, yearSignalHigh, yearSignalLow, yearThreeRangeStart, yearThreeRangeEnd, inExtensionColor, inExtensionWidth, inExtensionStyle, 3)
    renderedYearINProjectionStart := yearSignalStart
if monthlyINProjectionVisible and not na(monthSignalStart) and (na(renderedMonthINProjectionStart) or monthSignalStart != renderedMonthINProjectionStart)
    if monthSignalCode == 1
        f_push_in_projection(monthlyINProjectionLines, monthlyINProjectionOrigins, monthSignalStart, monthSignalHigh, monthSignalLow, monthThreeRangeStart, monthThreeRangeEnd, inExtensionColor, inExtensionWidth, inExtensionStyle, 3)
    renderedMonthINProjectionStart := monthSignalStart
if dailyINProjectionVisible and not na(daySignalStart) and (na(renderedDayINProjectionStart) or daySignalStart != renderedDayINProjectionStart)
    if daySignalCode == 1
        f_push_in_projection(dailyINProjectionLines, dailyINProjectionOrigins, daySignalStart, daySignalHigh, daySignalLow, dayThreeRangeStart, dayThreeRangeEnd, inExtensionColor, inExtensionWidth, inExtensionStyle, 3)
    renderedDayINProjectionStart := daySignalStart
if yearlyINProjectionVisible
    f_trim_in_projections_to_box(yearlyINProjectionLines, yearlyINProjectionOrigins, yearThreeRangeStart)
    f_update_in_projection_span(yearlyINProjectionLines, yearThreeRangeStart, yearThreeRangeEnd)
else
    f_clear_in_projections(yearlyINProjectionLines, yearlyINProjectionOrigins)
    renderedYearINProjectionStart := na
if monthlyINProjectionVisible
    f_trim_in_projections_to_box(monthlyINProjectionLines, monthlyINProjectionOrigins, monthThreeRangeStart)
    f_update_in_projection_span(monthlyINProjectionLines, monthThreeRangeStart, monthThreeRangeEnd)
else
    f_clear_in_projections(monthlyINProjectionLines, monthlyINProjectionOrigins)
    renderedMonthINProjectionStart := na
if dailyINProjectionVisible
    f_trim_in_projections_to_box(dailyINProjectionLines, dailyINProjectionOrigins, dayThreeRangeStart)
    f_update_in_projection_span(dailyINProjectionLines, dayThreeRangeStart, dayThreeRangeEnd)
else
    f_clear_in_projections(dailyINProjectionLines, dailyINProjectionOrigins)
    renderedDayINProjectionStart := na
 
// Missing hierarchy levels use the same shared IN extension template. Each
// confirmed inside range projects its H/L through the immediately following
// matching period, while the three most recent projections remain available.
var array<line> quarterlyINProjectionLines = array.new_line()
var array<int> quarterlyINProjectionOrigins = array.new_int()
var array<line> weeklyINProjectionLines = array.new_line()
var array<int> weeklyINProjectionOrigins = array.new_int()
var int renderedQuarterINProjectionStart = na
var int renderedWeekINProjectionStart = na
int currentQuarterProjectionStart = weeklyChartTimeframeMatch ? time("3M") : na
int currentQuarterProjectionEnd = weeklyChartTimeframeMatch ? time_close("3M") : na
int currentWeekProjectionStart = dailySectionChartTimeframeMatch ? time("W") : na
int currentWeekProjectionEnd = dailySectionChartTimeframeMatch ? time_close("W") : na
bool quarterlyINProjectionVisible = showINProjections and showQuarterlyRangesWeekly and weeklyChartTimeframeMatch
bool weeklyINProjectionVisible = showINProjections and showWeeklyRangesOn8H and dailySectionChartTimeframeMatch
if quarterlyINProjectionVisible and not na(quarterSignalStart) and (na(renderedQuarterINProjectionStart) or quarterSignalStart != renderedQuarterINProjectionStart)
    if quarterSignalCode == 1
        f_push_in_projection(quarterlyINProjectionLines, quarterlyINProjectionOrigins, quarterSignalStart, quarterSignalHigh, quarterSignalLow, currentQuarterProjectionStart, currentQuarterProjectionEnd, inExtensionColor, inExtensionWidth, inExtensionStyle, 3)
    renderedQuarterINProjectionStart := quarterSignalStart
if weeklyINProjectionVisible and not na(weekSignalStart) and (na(renderedWeekINProjectionStart) or weekSignalStart != renderedWeekINProjectionStart)
    if weekSignalCode == 1
        f_push_in_projection(weeklyINProjectionLines, weeklyINProjectionOrigins, weekSignalStart, weekSignalHigh, weekSignalLow, currentWeekProjectionStart, currentWeekProjectionEnd, inExtensionColor, inExtensionWidth, inExtensionStyle, 3)
    renderedWeekINProjectionStart := weekSignalStart
if not quarterlyINProjectionVisible
    f_clear_in_projections(quarterlyINProjectionLines, quarterlyINProjectionOrigins)
    renderedQuarterINProjectionStart := na
if not weeklyINProjectionVisible
    f_clear_in_projections(weeklyINProjectionLines, weeklyINProjectionOrigins)
    renderedWeekINProjectionStart := na
 
var array<line> dailySeparatorLines = array.new_line()
var line sharedSeparatorBoundary = na
var float runDH = na
var float runDL = na
var int runDT = na
var int runDTE = na
var array<line> dLines = array.new_line()
var array<line> weeklyRangeLines8H = array.new_line()
var array<line> weeklySeparatorBorders8H = array.new_line()
var array<line> yearlyRangeLinesWeekly = array.new_line()
var array<line> yearlySeparatorBordersWeekly = array.new_line()
var array<line> previousYearCloseLines = array.new_line()
var int renderedPreviousYearCloseStart = na
var array<line> quarterlyRangeLinesWeekly = array.new_line()
var array<line> quarterlySeparatorBordersWeekly = array.new_line()
var array<line> monthlyRangeLines = array.new_line()
var array<line> monthlySeparatorBorders = array.new_line()
var array<line> previousMonthCloseLines = array.new_line()
var int renderedPreviousMonthCloseStart = na
bool newCompletedShortDay = isShortDaySessionProduct and not na(shortCompletedDayEnd) and (barstate.isfirst or ta.change(shortCompletedDayEnd) != 0)
if not isShortDaySessionProduct and newDay and dailyChartTimeframeMatch and showDailySeparatorsFifteenMinute and not na(runDH) and not na(runDL)
    sharedSeparatorBoundary := f_update_daily_separators(dailySeparatorLines, sharedSeparatorBoundary, true, runDH, runDL, not na(nativeDayStart) ? nativeDayStart : time, cD, structureWidth, rangeDStyleCode == 2 ? line.style_dashed : rangeDStyleCode == 1 ? line.style_dotted : line.style_solid, visibleDRangeCount, fifteenMinuteExtendSeparatorsFullHeight)
if isShortDaySessionProduct
    if newCompletedShortDay and dailyChartTimeframeMatch and not na(shortCompletedDayHigh) and not na(shortCompletedDayLow) and not na(shortCompletedDayStart)
        if showDailyRangesFifteenMinute
            f_push_range(dLines, shortCompletedDayStart, shortCompletedDayEnd, shortCompletedDayHigh, shortCompletedDayLow, cD, structureWidth, rangeDStyleCode, visibleDRangeCount)
        if showDailySeparatorsFifteenMinute
            sharedSeparatorBoundary := f_update_daily_separators(dailySeparatorLines, sharedSeparatorBoundary, true, shortCompletedDayHigh, shortCompletedDayLow, not na(nativeDayStart) ? nativeDayStart : time, cD, structureWidth, rangeDStyleCode == 2 ? line.style_dashed : rangeDStyleCode == 1 ? line.style_dotted : line.style_solid, visibleDRangeCount, fifteenMinuteExtendSeparatorsFullHeight)
else
    if barstate.isfirst
        runDH := high
        runDL := low
        runDT := not na(nativeDayStart) ? nativeDayStart : time
        runDTE := not na(nativeDayEnd) ? nativeDayEnd : time_close
    else
        if newDay
            if dailyChartTimeframeMatch
                int completedRunDayEnd = not na(runDTE) ? runDTE : time
                if showDailyRangesFifteenMinute
                    f_push_range(dLines, runDT, completedRunDayEnd, runDH, runDL, cD, structureWidth, rangeDStyleCode, visibleDRangeCount)
            runDH := high
            runDL := low
            runDT := not na(nativeDayStart) ? nativeDayStart : time
            runDTE := not na(nativeDayEnd) ? nativeDayEnd : time_close
        else
            runDH := math.max(runDH, high)
            runDL := math.min(runDL, low)
            runDTE := not na(nativeDayEnd) ? nativeDayEnd : time_close
bool newWeeklyEightHourContext = dailySectionChartTimeframeMatch and (barstate.isfirst or newWeek)
if newWeeklyEightHourContext and not na(canonicalWH1) and not na(canonicalWL1) and not na(canonicalWT1) and not na(canonicalWT2)
    if showWeeklyRangesOn8H
        f_push_range(weeklyRangeLines8H, canonicalWT2, canonicalWT1, canonicalWH1, canonicalWL1, c8, range8Width, range8StyleCode, weeklyRangesOn8HCount)
    if showWeeklySeparatorsEightHour
        f_push_separator_borders(weeklySeparatorBorders8H, canonicalWT2, canonicalWT1, canonicalWH1, canonicalWL1, c8, range8Width, range8StyleCode == 2 ? line.style_dashed : range8StyleCode == 1 ? line.style_dotted : line.style_solid, weeklyRangesOn8HCount, dailyExtendSeparatorsFullHeight)
bool newYearlyWeeklyContext = weeklyChartTimeframeMatch and (barstate.isfirst or newYear)
if newYearlyWeeklyContext and not na(canonicalYH1) and not na(canonicalYL1) and not na(canonicalYT1) and not na(canonicalYT2)
    if showYearlyRangesWeekly
        f_push_range(yearlyRangeLinesWeekly, canonicalYT2, canonicalYT1, canonicalYH1, canonicalYL1, yearlyRangeColor, yearlyRangeWidth, yearlyRangeStyleCode, weeklyChartYearlyPeriodsToShow)
    if showYearlySeparatorsWeekly
        f_push_separator_borders(yearlySeparatorBordersWeekly, canonicalYT2, canonicalYT1, canonicalYH1, canonicalYL1, yearlyRangeColor, yearlyRangeWidth, yearlyRangeStyleCode == 2 ? line.style_dashed : yearlyRangeStyleCode == 1 ? line.style_dotted : line.style_solid, weeklyChartYearlyPeriodsToShow, weeklyExtendSeparatorsFullHeight)
int currentYearReferenceStart = weeklyChartTimeframeMatch ? time("12M") : na
int currentYearReferenceEnd = weeklyChartTimeframeMatch ? time_close("12M") : na
bool previousYearCloseAvailable = showPreviousYearCloseOnWeekly and weeklyChartTimeframeMatch and not na(canonicalYC1) and not na(currentYearReferenceStart) and not na(currentYearReferenceEnd)
bool newPreviousYearClosePeriod = previousYearCloseAvailable and (na(renderedPreviousYearCloseStart) or currentYearReferenceStart != renderedPreviousYearCloseStart)
if newPreviousYearClosePeriod
    array.push(previousYearCloseLines, line.new(currentYearReferenceStart, canonicalYC1, currentYearReferenceEnd, canonicalYC1, xloc = xloc.bar_time, extend = extend.none, color = previousYearCloseColor, width = previousYearCloseWidth, style = previousYearCloseStyle))
    renderedPreviousYearCloseStart := currentYearReferenceStart
    while array.size(previousYearCloseLines) > previousYearClosePeriodsToShow
        line.delete(array.shift(previousYearCloseLines))
bool newQuarterlyWeeklyContext = weeklyChartTimeframeMatch and (barstate.isfirst or newQuarter)
if newQuarterlyWeeklyContext and not na(canonicalQH1) and not na(canonicalQL1) and not na(canonicalQT1) and not na(canonicalQT2)
    if showQuarterlyRangesWeekly
        f_push_range(quarterlyRangeLinesWeekly, canonicalQT2, canonicalQT1, canonicalQH1, canonicalQL1, quarterlyRangeColor, quarterlyRangeWidth, quarterlyRangeStyleCode, weeklyChartQuarterlyPeriodsToShow)
    if showQuarterlySeparatorsWeekly
        f_push_separator_borders(quarterlySeparatorBordersWeekly, canonicalQT2, canonicalQT1, canonicalQH1, canonicalQL1, quarterlyRangeColor, quarterlyRangeWidth, quarterlyRangeStyleCode == 2 ? line.style_dashed : quarterlyRangeStyleCode == 1 ? line.style_dotted : line.style_solid, weeklyChartQuarterlyPeriodsToShow, weeklyExtendSeparatorsFullHeight)
bool newMonthlyDailyContext = dailySectionChartTimeframeMatch and (barstate.isfirst or newMonth)
if newMonthlyDailyContext and not na(canonicalMH1) and not na(canonicalML1) and not na(canonicalMT1) and not na(canonicalMT2)
    if showMonthlyRangesOnDaily
        f_push_range(monthlyRangeLines, canonicalMT2, canonicalMT1, canonicalMH1, canonicalML1, monthlyRangeColor, monthlyRangeWidth, monthlyRangeStyleCode, visibleMonthlyRangeCount)
    if showMonthlySeparatorsEightHour
        f_push_separator_borders(monthlySeparatorBorders, canonicalMT2, canonicalMT1, canonicalMH1, canonicalML1, monthlyRangeColor, monthlyRangeWidth, monthlyRangeStyleCode == 2 ? line.style_dashed : monthlyRangeStyleCode == 1 ? line.style_dotted : line.style_solid, visibleMonthlyRangeCount, dailyExtendSeparatorsFullHeight)
int currentMonthReferenceStart = dailySectionChartTimeframeMatch ? time("M") : na
int currentMonthReferenceEnd = dailySectionChartTimeframeMatch ? time_close("M") : na
bool previousMonthCloseAvailable = showPreviousMonthClose and dailySectionChartTimeframeMatch and not na(canonicalMC1) and not na(currentMonthReferenceStart) and not na(currentMonthReferenceEnd)
bool newPreviousMonthClosePeriod = previousMonthCloseAvailable and (na(renderedPreviousMonthCloseStart) or currentMonthReferenceStart != renderedPreviousMonthCloseStart)
if newPreviousMonthClosePeriod
    array.push(previousMonthCloseLines, line.new(currentMonthReferenceStart, canonicalMC1, currentMonthReferenceEnd, canonicalMC1, xloc = xloc.bar_time, extend = extend.none, color = previousMonthCloseColor, width = previousMonthCloseWidth, style = previousMonthCloseStyle))
    renderedPreviousMonthCloseStart := currentMonthReferenceStart
    while array.size(previousMonthCloseLines) > previousMonthCloseMonthsToShow
        line.delete(array.shift(previousMonthCloseLines))
float canonicalPrevDayClose = request.security(syminfo.tickerid, "D", close[1], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
var float currentDayPreviousClose = na
if barstate.isfirst
    currentDayPreviousClose := isShortDaySessionProduct ? shortCompletedDayClose : canonicalPrevDayClose
else if newDay
    currentDayPreviousClose := isShortDaySessionProduct ? shortCompletedDayClose : close[1]
bool range15MChartTimeframeMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds == 60
bool range1HHostSupported = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds <= 60 * 60
bool entryRange1HChartTimeframeMatch = entryChartTimeframeMatch and range1HHostSupported
[completed1HHigh, completed1HLow, completed1HPreviousClose, completed1HStart, completed1HClose, completed1HFirstBarTime, completed1HLastBarClose] = request.security(syminfo.tickerid, "1", f_clock_hour_ranges_1m(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
bool newCompleted1H = range1HHostSupported and not na(completed1HClose) and (barstate.isfirst or ta.change(completed1HClose) != 0)
int hourlyCoverageToleranceMs = 5 * 60 * 1000
bool completed1HIsFullHour = not na(completed1HStart) and not na(completed1HClose) and not na(completed1HFirstBarTime) and not na(completed1HLastBarClose) and completed1HClose - completed1HStart == HOUR_MS and completed1HFirstBarTime <= completed1HStart + hourlyCoverageToleranceMs and completed1HLastBarClose >= completed1HClose - hourlyCoverageToleranceMs
int completed1HAsiaDay = dayofweek(completed1HStart, "Asia/Tokyo")
int completed1HLondonDay = dayofweek(completed1HStart, "Europe/London")
int completed1HNewYorkDay = dayofweek(completed1HStart, "America/New_York")
int completed1HAsiaHour = hour(completed1HStart, "Asia/Tokyo")
int completed1HLondonHour = hour(completed1HStart, "Europe/London")
int completed1HNewYorkHour = hour(completed1HStart, "America/New_York")
bool completed1HAsiaNumbered = showAsiaSessionColor and completed1HAsiaDay >= dayofweek.monday and completed1HAsiaDay <= dayofweek.friday and completed1HAsiaHour >= 8 and completed1HAsiaHour <= 11
bool completed1HLondonNumbered = showLondonSessionColor and completed1HLondonDay >= dayofweek.monday and completed1HLondonDay <= dayofweek.friday and completed1HLondonHour >= 7 and completed1HLondonHour <= 10
bool completed1HNewYorkNumbered = showNewYorkSessionColor and completed1HNewYorkDay >= dayofweek.monday and completed1HNewYorkDay <= dayofweek.friday and completed1HNewYorkHour >= 8 and completed1HNewYorkHour <= 11
int completed1HSessionOwner = completed1HNewYorkNumbered ? 3 : completed1HLondonNumbered ? 2 : completed1HAsiaNumbered ? 1 : 0
bool completed1HIsNumberedSessionHour = completed1HSessionOwner != 0
int completed1HSessionHourNumber = completed1HSessionOwner == 3 ? completed1HNewYorkHour - 7 : completed1HSessionOwner == 2 ? completed1HLondonHour - 6 : completed1HSessionOwner == 1 ? completed1HAsiaHour - 7 : -1
bool completed1HAllowsSignalLabel = completed1HSessionHourNumber >= 1 and completed1HSessionHourNumber <= 3
int completed1HProjectionSessionStart = completed1HSessionOwner == 1 ? timestamp("Asia/Tokyo", year(completed1HStart, "Asia/Tokyo"), month(completed1HStart, "Asia/Tokyo"), dayofmonth(completed1HStart, "Asia/Tokyo"), 8, 0) : completed1HSessionOwner == 2 ? timestamp("Europe/London", year(completed1HStart, "Europe/London"), month(completed1HStart, "Europe/London"), dayofmonth(completed1HStart, "Europe/London"), 7, 0) : completed1HSessionOwner == 3 ? timestamp("America/New_York", year(completed1HStart, "America/New_York"), month(completed1HStart, "America/New_York"), dayofmonth(completed1HStart, "America/New_York"), 8, 0) : na
int completed1HProjectionSessionEnd = not na(completed1HProjectionSessionStart) ? completed1HProjectionSessionStart + 4 * HOUR_MS : na
bool renderCompleted1HRange = entryRange1HChartTimeframeMatch and (not range15MChartTimeframeMatch or completed1HIsNumberedSessionHour)
var array<line> oneHourRangeLines = array.new_line()
var array<line> oneHourSeparatorLines = array.new_line()
var array<line> previous1HCloseLines = array.new_line()
var array<label> oneHourSignalLabels = array.new_label()
var array<line> oneHourINProjectionLines = array.new_line()
var array<int> oneHourINProjectionOrigins = array.new_int()
var float signalPrevious1HHigh = na
var float signalPrevious1HLow = na
var float signalPrevious1HClose = na
var float signalBase1HHigh = na
var float signalBase1HLow = na
int completed1HSignalCode = 0
if newCompleted1H and completed1HIsFullHour and not na(completed1HHigh) and not na(completed1HLow) and not na(completed1HPreviousClose)
    completed1HSignalCode := f_range_signal_code(completed1HHigh, completed1HLow, completed1HPreviousClose, signalPrevious1HHigh, signalPrevious1HLow, signalPrevious1HClose, signalBase1HHigh, signalBase1HLow)
    signalBase1HHigh := signalPrevious1HHigh
    signalBase1HLow := signalPrevious1HLow
    signalPrevious1HHigh := completed1HHigh
    signalPrevious1HLow := completed1HLow
    signalPrevious1HClose := completed1HPreviousClose
if newCompleted1H and completed1HIsFullHour and entryShow1HRanges and renderCompleted1HRange and not na(completed1HHigh) and not na(completed1HLow)
    f_push_range(oneHourRangeLines, completed1HStart, completed1HClose, completed1HHigh, completed1HLow, entryRange1HColor, entryRange1HWidth, entryRange1HStyleCode, entryVisible1HRangeCount)
if newCompleted1H and completed1HIsFullHour and entryShow1HSeparators and entryRange1HChartTimeframeMatch and not range15MChartTimeframeMatch and not na(completed1HHigh) and not na(completed1HLow)
    f_push_separator_borders(oneHourSeparatorLines, completed1HStart, completed1HClose, completed1HHigh, completed1HLow, entryRange1HColor, entryRange1HWidth, entryRange1HStyleCode == 2 ? line.style_dashed : entryRange1HStyleCode == 1 ? line.style_dotted : line.style_solid, entryVisible1HRangeCount, oneMinuteExtendSeparatorsFullHeight)
if newCompleted1H and completed1HIsFullHour and entryChartTimeframeMatch and entryShowPrevious1HClose and renderCompleted1HRange and not na(completed1HPreviousClose)
    int current1HReferenceStart = timestamp(syminfo.timezone, year(time, syminfo.timezone), month(time, syminfo.timezone), dayofmonth(time, syminfo.timezone), hour(time, syminfo.timezone), 0)
    int current1HReferenceEnd = current1HReferenceStart + HOUR_MS
    if not na(current1HReferenceStart) and not na(current1HReferenceEnd)
        array.push(previous1HCloseLines, line.new(current1HReferenceStart, completed1HPreviousClose, current1HReferenceEnd, completed1HPreviousClose, xloc = xloc.bar_time, extend = extend.none, color = entryPrevious1HCloseColor, width = entryPrevious1HCloseWidth, style = entryPrevious1HCloseStyle))
        while array.size(previous1HCloseLines) > entryPrevious1HClosePeriodsToShow
            line.delete(array.shift(previous1HCloseLines))
int hh = hour(time, TZ)
int mm = minute(time, TZ)
int minutesNow = hh * 60 + mm
int genericSession8 = minutesNow >= 900 and minutesNow < 1320 ? 1 : minutesNow >= 1320 or minutesNow < 360 ? 2 : minutesNow >= 360 and minutesNow < 840 ? 3 : 0
int session8 = isLivestockDaySession ? (inShortDaySessionOnChart ? 3 : 0) : genericSession8
int sessionStartHour = session8 == 1 ? 15 : session8 == 2 ? 22 : 6
int sessionStartDayOffset = session8 == 2 and hh < 6 ? -1 : 0
int session8Start = isLivestockDaySession ? localShortDayStart : session8 == 0 ? na : timestamp(TZ, year(time, TZ), month(time, TZ), dayofmonth(time, TZ) + sessionStartDayOffset, sessionStartHour, 0)
int session8End = isLivestockDaySession ? localShortDayEnd : session8 == 0 ? na : session8Start + (session8 == 1 ? 7 : 8) * HOUR_MS
bool new8 = session8 != 0 and (na(session8Start[1]) or session8Start != session8Start[1])
bool range8ChartTimeframeMatch = not isShortDaySessionProduct and timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds >= 15 * 60 and chartTimeframeSeconds <= 4 * 60 * 60
var float live8H = na
var float live8L = na
var float live8Close = na
var int live8T1 = na
var int live8T2 = na
var float signalPrevious8HHigh = na
var float signalPrevious8HLow = na
var float signalPrevious8HClose = na
var float signalBase8HHigh = na
var float signalBase8HLow = na
var array<line> eightHourRangeLines = array.new_line()
var array<line> eightHourSeparatorLines = array.new_line()
var array<line> eightHourINProjectionLines = array.new_line()
var array<int> eightHourINProjectionOrigins = array.new_int()
int completed8HSignalCode = 0
bool eightHourINProjectionVisible = showINProjections and show8H and range8ChartTimeframeMatch
if not isShortDaySessionProduct and session8 != 0
    if new8
        if not na(live8H) and not na(live8L) and not na(live8Close) and not na(live8T1) and not na(live8T2)
            completed8HSignalCode := f_range_signal_code(live8H, live8L, live8Close, signalPrevious8HHigh, signalPrevious8HLow, signalPrevious8HClose, signalBase8HHigh, signalBase8HLow)
            if range8ChartTimeframeMatch
                if show8H
                    f_push_range(eightHourRangeLines, live8T1, live8T2, live8H, live8L, fifteenMinute8HRangeColor, fifteenMinute8HRangeWidth, fifteenMinute8HRangeStyleCode, visible8HRangeCount)
                if showEightHourSeparatorsFifteenMinute
                    f_push_separator_borders(eightHourSeparatorLines, live8T1, live8T2, live8H, live8L, fifteenMinute8HRangeColor, fifteenMinute8HRangeWidth, fifteenMinute8HRangeStyleCode == 2 ? line.style_dashed : fifteenMinute8HRangeStyleCode == 1 ? line.style_dotted : line.style_solid, visible8HRangeCount, fifteenMinuteExtendSeparatorsFullHeight)
                if eightHourINProjectionVisible and completed8HSignalCode == 1
                    f_push_in_projection(eightHourINProjectionLines, eightHourINProjectionOrigins, live8T1, live8H, live8L, session8Start, session8End, inExtensionColor, inExtensionWidth, inExtensionStyle, 3)
            signalBase8HHigh := signalPrevious8HHigh
            signalBase8HLow := signalPrevious8HLow
            signalPrevious8HHigh := live8H
            signalPrevious8HLow := live8L
            signalPrevious8HClose := live8Close
        live8H := high
        live8L := low
        live8Close := close
        live8T1 := session8Start
        live8T2 := session8End
    else
        live8H := math.max(nz(live8H, high), high)
        live8L := math.min(nz(live8L, low), low)
        live8Close := close
if not eightHourINProjectionVisible
    f_clear_in_projections(eightHourINProjectionLines, eightHourINProjectionOrigins)
 
// Sharing session layer. The supplied California references are the START of
// hour 3. Named market timezones preserve the intended DST behavior. Every
// supported session display uses Hours 1-4 only; newer sessions win overlap.
bool sharingSessionChart = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds >= 60 and chartTimeframeSeconds <= 15 * 60
bool sharingExactOneMinuteChart = range15MChartTimeframeMatch
bool sharingInAsia = sharingSessionChart and not na(time(timeframe.period, "0800-1200:23456", "Asia/Tokyo"))
bool sharingInLondon = sharingSessionChart and not na(time(timeframe.period, "0700-1100:23456", "Europe/London"))
bool sharingInNewYork = sharingSessionChart and not na(time(timeframe.period, "0800-1200:23456", "America/New_York"))
int sharingSessionOwner = showNewYorkSessionColor and sharingInNewYork ? 3 : showLondonSessionColor and sharingInLondon ? 2 : showAsiaSessionColor and sharingInAsia ? 1 : 0
color sharingSessionShade = sharingSessionOwner == 3 ? newYorkSessionColor : sharingSessionOwner == 2 ? londonSessionColor : sharingSessionOwner == 1 ? asiaSessionColor : na
 
var array<box> sharingSessionBoxes = array.new_box()
var box sharingActiveSessionBox = na
var int sharingActiveSessionOwner = 0
var float sharingActiveSessionHigh = na
var float sharingActiveSessionLow = na
var array<line> sharingSessionHourLines = array.new_line()
var array<label> sharingSessionHourLabels = array.new_label()
bool sharingNewSession = sharingSessionOwner != 0 and (barstate.isfirst or sharingSessionOwner != sharingSessionOwner[1])
if sharingNewSession
    if sharingExactOneMinuteChart
        while array.size(sharingSessionBoxes) > 0
            box.delete(array.shift(sharingSessionBoxes))
        while array.size(sharingSessionHourLines) > 0
            line.delete(array.shift(sharingSessionHourLines))
        while array.size(sharingSessionHourLabels) > 0
            label.delete(array.shift(sharingSessionHourLabels))
        while array.size(oneHourSignalLabels) > 0
            label.delete(array.shift(oneHourSignalLabels))
        f_clear_in_projections(oneHourINProjectionLines, oneHourINProjectionOrigins)
        while array.size(oneHourRangeLines) > 0
            line.delete(array.shift(oneHourRangeLines))
        while array.size(previous1HCloseLines) > 0
            line.delete(array.shift(previous1HCloseLines))
    sharingActiveSessionOwner := sharingSessionOwner
    sharingActiveSessionHigh := high
    sharingActiveSessionLow := low
    sharingActiveSessionBox := box.new(time, sharingActiveSessionHigh, time_close, sharingActiveSessionLow, xloc = xloc.bar_time, extend = extend.none, border_color = na, border_width = 0, bgcolor = sharingSessionShade)
    array.push(sharingSessionBoxes, sharingActiveSessionBox)
    int sharingSessionBoxLimit = sharingExactOneMinuteChart ? 1 : 3
    while array.size(sharingSessionBoxes) > sharingSessionBoxLimit
        box.delete(array.shift(sharingSessionBoxes))
else if sharingSessionOwner != 0 and sharingSessionOwner == sharingActiveSessionOwner and not na(sharingActiveSessionBox)
    sharingActiveSessionHigh := math.max(sharingActiveSessionHigh, high)
    sharingActiveSessionLow := math.min(sharingActiveSessionLow, low)
    box.set_right(sharingActiveSessionBox, time_close)
    box.set_top(sharingActiveSessionBox, sharingActiveSessionHigh)
    box.set_bottom(sharingActiveSessionBox, sharingActiveSessionLow)
else if sharingSessionOwner == 0
    sharingActiveSessionBox := na
    sharingActiveSessionOwner := 0
 
int sharingAsiaDay = dayofweek(time, "Asia/Tokyo")
int sharingLondonDay = dayofweek(time, "Europe/London")
int sharingNewYorkDay = dayofweek(time, "America/New_York")
bool sharingAsiaWeekday = sharingAsiaDay >= dayofweek.monday and sharingAsiaDay <= dayofweek.friday
bool sharingLondonWeekday = sharingLondonDay >= dayofweek.monday and sharingLondonDay <= dayofweek.friday
bool sharingNewYorkWeekday = sharingNewYorkDay >= dayofweek.monday and sharingNewYorkDay <= dayofweek.friday
int sharingAsiaHour = hour(time, "Asia/Tokyo")
int sharingLondonHour = hour(time, "Europe/London")
int sharingNewYorkHour = hour(time, "America/New_York")
int sharingAsiaMinute = minute(time, "Asia/Tokyo")
int sharingLondonMinute = minute(time, "Europe/London")
int sharingNewYorkMinute = minute(time, "America/New_York")
bool sharingAsiaBoundary = showAsiaSessionColor and sharingAsiaWeekday and sharingAsiaMinute == 0 and sharingAsiaHour >= 8 and sharingAsiaHour <= 12
bool sharingLondonBoundary = showLondonSessionColor and sharingLondonWeekday and sharingLondonMinute == 0 and sharingLondonHour >= 7 and sharingLondonHour <= 11
bool sharingNewYorkBoundary = showNewYorkSessionColor and sharingNewYorkWeekday and sharingNewYorkMinute == 0 and sharingNewYorkHour >= 8 and sharingNewYorkHour <= 12
if showSessionHourSeparators and sharingExactOneMinuteChart and oneMinuteExtendSeparatorsFullHeight and (sharingAsiaBoundary or sharingLondonBoundary or sharingNewYorkBoundary)
    float sharingHourLineLow = not na(sharingActiveSessionLow) ? sharingActiveSessionLow : low
    float sharingHourLineHigh = not na(sharingActiveSessionHigh) ? sharingActiveSessionHigh : high
    line sharingHourLine = line.new(time, sharingHourLineLow, time, sharingHourLineHigh, xloc = xloc.bar_time, extend = extend.both, color = entryRange1HColor, width = entryRange1HWidth, style = entryRange1HStyleCode == 2 ? line.style_dashed : entryRange1HStyleCode == 1 ? line.style_dotted : line.style_solid)
    array.push(sharingSessionHourLines, sharingHourLine)
    while array.size(sharingSessionHourLines) > 15
        line.delete(array.shift(sharingSessionHourLines))
if showSessionHourSeparators and sharingExactOneMinuteChart and not oneMinuteExtendSeparatorsFullHeight and newCompleted1H and completed1HIsFullHour and completed1HIsNumberedSessionHour and not na(completed1HHigh) and not na(completed1HLow)
    f_push_separator_borders(sharingSessionHourLines, completed1HStart, completed1HClose, completed1HHigh, completed1HLow, entryRange1HColor, entryRange1HWidth, entryRange1HStyleCode == 2 ? line.style_dashed : entryRange1HStyleCode == 1 ? line.style_dotted : line.style_solid, 5, false)
 
bool sharingHourOne = sharingExactOneMinuteChart and ((sharingSessionOwner == 1 and sharingAsiaHour == 8 and sharingAsiaMinute == 30) or (sharingSessionOwner == 2 and sharingLondonHour == 7 and sharingLondonMinute == 30) or (sharingSessionOwner == 3 and sharingNewYorkHour == 8 and sharingNewYorkMinute == 30))
bool sharingHourTwo = sharingExactOneMinuteChart and ((sharingSessionOwner == 1 and sharingAsiaHour == 9 and sharingAsiaMinute == 30) or (sharingSessionOwner == 2 and sharingLondonHour == 8 and sharingLondonMinute == 30) or (sharingSessionOwner == 3 and sharingNewYorkHour == 9 and sharingNewYorkMinute == 30))
bool sharingHourThree = sharingExactOneMinuteChart and ((sharingSessionOwner == 1 and sharingAsiaHour == 10 and sharingAsiaMinute == 30) or (sharingSessionOwner == 2 and sharingLondonHour == 9 and sharingLondonMinute == 30) or (sharingSessionOwner == 3 and sharingNewYorkHour == 10 and sharingNewYorkMinute == 30))
bool sharingHourFour = sharingExactOneMinuteChart and ((sharingSessionOwner == 1 and sharingAsiaHour == 11 and sharingAsiaMinute == 30) or (sharingSessionOwner == 2 and sharingLondonHour == 10 and sharingLondonMinute == 30) or (sharingSessionOwner == 3 and sharingNewYorkHour == 11 and sharingNewYorkMinute == 30))
 
if sharingExactOneMinuteChart and array.size(sharingSessionHourLabels) > 0 and not na(sharingActiveSessionHigh) and not na(sharingActiveSessionLow)
    float sharingLabelOffset = math.max((sharingActiveSessionHigh - sharingActiveSessionLow) * 0.06, syminfo.mintick * 12)
    for sharingLabelIndex = 0 to array.size(sharingSessionHourLabels) - 1
        label.set_y(array.get(sharingSessionHourLabels, sharingLabelIndex), sharingActiveSessionLow - sharingLabelOffset)
bool sharingHourLabelEvent = sharingHourOne or sharingHourTwo or sharingHourThree or sharingHourFour
int sharingHourNumber = sharingHourOne ? 1 : sharingHourTwo ? 2 : sharingHourThree ? 3 : 4
if sharingHourLabelEvent and not na(sharingActiveSessionHigh) and not na(sharingActiveSessionLow)
    float sharingNewLabelOffset = math.max((sharingActiveSessionHigh - sharingActiveSessionLow) * 0.06, syminfo.mintick * 12)
    label sharingHourLabel = label.new(time, sharingActiveSessionLow - sharingNewLabelOffset, str.tostring(sharingHourNumber), xloc = xloc.bar_time, yloc = yloc.price, color = sessionHourLabelBackground, style = label.style_none, textcolor = sessionHourLabelTextColor, size = sessionHourTextSize, textalign = text.align_center)
    array.push(sharingSessionHourLabels, sharingHourLabel)
if sharingExactOneMinuteChart and showOneHourSignalLabels and newCompleted1H and completed1HIsFullHour and completed1HAllowsSignalLabel and completed1HSignalCode > 0 and not na(completed1HHigh) and not na(completed1HLow)
    int oneHourSignalMidpoint = completed1HStart + int((completed1HClose - completed1HStart) / 2)
    float oneHourSignalY = completed1HLow + math.max((completed1HHigh - completed1HLow) * 0.06, syminfo.mintick * 10)
    label oneHourSignalLabel = label.new(oneHourSignalMidpoint, oneHourSignalY, f_signal_text(completed1HSignalCode), xloc = xloc.bar_time, yloc = yloc.price, color = color.new(color.black, 100), style = label.style_none, textcolor = signalTextColor, size = oneHourSignalTextSize, textalign = text.align_center)
    array.push(oneHourSignalLabels, oneHourSignalLabel)
    while array.size(oneHourSignalLabels) > 3
        label.delete(array.shift(oneHourSignalLabels))
if not sharingExactOneMinuteChart or not showOneHourSignalLabels
    f_clear_signal_labels(oneHourSignalLabels)
if sharingExactOneMinuteChart and showINProjections and newCompleted1H and completed1HIsFullHour and completed1HAllowsSignalLabel and completed1HSignalCode == 1 and not na(completed1HProjectionSessionStart) and not na(completed1HProjectionSessionEnd)
    f_push_in_projection(oneHourINProjectionLines, oneHourINProjectionOrigins, completed1HStart, completed1HHigh, completed1HLow, completed1HProjectionSessionStart, completed1HProjectionSessionEnd, inExtensionColor, inExtensionWidth, inExtensionStyle, 3)
if not sharingExactOneMinuteChart or not showINProjections
    f_clear_in_projections(oneHourINProjectionLines, oneHourINProjectionOrigins)
var array<line> previousDayCloseLines = array.new_line()
var int renderedPreviousDayCloseStart = na
// Display-only Daily close history. On the first available intraday bar of
// each Daily period, draw that day's immediately preceding Daily close across
// the full period, then retain only the user-selected number of days.
int currentDayReferenceStart = nativeDayStart
int currentDayReferenceEnd = nativeDayEnd
bool previousDayCloseAvailable = activeShowPreviousDayClose and previousDayCloseChartTimeframeMatch and timeframe.isintraday and (not isShortDaySessionProduct or inShortDaySessionOnChart) and not na(currentDayPreviousClose) and not na(currentDayReferenceStart) and not na(currentDayReferenceEnd)
bool newPreviousDayClosePeriod = previousDayCloseAvailable and (na(renderedPreviousDayCloseStart) or currentDayReferenceStart != renderedPreviousDayCloseStart)
if newPreviousDayClosePeriod
    array.push(previousDayCloseLines, line.new(currentDayReferenceStart, currentDayPreviousClose, currentDayReferenceEnd, currentDayPreviousClose, xloc = xloc.bar_time, extend = extend.none, color = activePreviousDayCloseColor, width = activePreviousDayCloseWidth, style = activePreviousDayCloseStyle))
    renderedPreviousDayCloseStart := currentDayReferenceStart
    while array.size(previousDayCloseLines) > activePreviousDayCloseDaysToShow
        line.delete(array.shift(previousDayCloseLines))
if not activeShowPreviousDayClose or not previousDayCloseChartTimeframeMatch or not timeframe.isintraday
    while array.size(previousDayCloseLines) > 0
        line.delete(array.shift(previousDayCloseLines))
    renderedPreviousDayCloseStart := na
var table detailsPanelV44 = table.new(position.middle_right, 1, 2, border_width = 0)
if barstate.islast
    table.clear(detailsPanelV44, 0, 0, 0, 1)
    if showDetailsV44
        string detailsTickerV44 = showExchangeV44 ? syminfo.prefix + ":" + syminfo.ticker : syminfo.ticker
        string detailsTimeframeV44 = timeframe.isseconds ? str.tostring(timeframe.multiplier) + "S" : timeframe.isintraday ? (timeframe.multiplier < 60 ? str.tostring(timeframe.multiplier) + "M" : timeframe.multiplier % 60 == 0 ? str.tostring(int(timeframe.multiplier / 60)) + "H" : str.tostring(timeframe.multiplier) + "M") : timeframe.isdaily ? str.tostring(timeframe.multiplier) + "D" : timeframe.isweekly ? str.tostring(timeframe.multiplier) + "W" : timeframe.ismonthly ? str.tostring(timeframe.multiplier) + "M" : timeframe.period
        table.cell(detailsPanelV44, 0, 0, detailsTickerV44, text_color = detailsTextColorV44, text_size = detailsTextSizeV44, text_halign = text.align_right)
        table.cell(detailsPanelV44, 0, 1, "TF  " + detailsTimeframeV44, text_color = detailsTextColorV44, text_size = detailsTextSizeV44, text_halign = text.align_right)
color weekdayLabelBackground = color.new(color.black, 100)
plotshape(weekdayLabelDay == dayofweek.monday and weekdayLabelSizeInput == "Tiny", "Monday label — Tiny", shape.labelup, location.bottom, weekdayLabelBackground, text = "Monday", textcolor = mondayLabelColor, size = size.tiny)
plotshape(weekdayLabelDay == dayofweek.monday and weekdayLabelSizeInput == "Small", "Monday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Monday", textcolor = mondayLabelColor, size = size.small)
plotshape(weekdayLabelDay == dayofweek.monday and weekdayLabelSizeInput == "Normal", "Monday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Monday", textcolor = mondayLabelColor, size = size.normal)
plotshape(weekdayLabelDay == dayofweek.monday and weekdayLabelSizeInput == "Large", "Monday label — Large", shape.labelup, location.bottom, weekdayLabelBackground, text = "Monday", textcolor = mondayLabelColor, size = size.large)
plotshape(weekdayLabelDay == dayofweek.tuesday and weekdayLabelSizeInput == "Tiny", "Tuesday label — Tiny", shape.labelup, location.bottom, weekdayLabelBackground, text = "Tuesday", textcolor = weekdayLabelColor, size = size.tiny)
plotshape(weekdayLabelDay == dayofweek.tuesday and weekdayLabelSizeInput == "Small", "Tuesday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Tuesday", textcolor = weekdayLabelColor, size = size.small)
plotshape(weekdayLabelDay == dayofweek.tuesday and weekdayLabelSizeInput == "Normal", "Tuesday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Tuesday", textcolor = weekdayLabelColor, size = size.normal)
plotshape(weekdayLabelDay == dayofweek.tuesday and weekdayLabelSizeInput == "Large", "Tuesday label — Large", shape.labelup, location.bottom, weekdayLabelBackground, text = "Tuesday", textcolor = weekdayLabelColor, size = size.large)
plotshape(weekdayLabelDay == dayofweek.wednesday and weekdayLabelSizeInput == "Tiny", "Wednesday label — Tiny", shape.labelup, location.bottom, weekdayLabelBackground, text = "Wednesday", textcolor = weekdayLabelColor, size = size.tiny)
plotshape(weekdayLabelDay == dayofweek.wednesday and weekdayLabelSizeInput == "Small", "Wednesday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Wednesday", textcolor = weekdayLabelColor, size = size.small)
plotshape(weekdayLabelDay == dayofweek.wednesday and weekdayLabelSizeInput == "Normal", "Wednesday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Wednesday", textcolor = weekdayLabelColor, size = size.normal)
plotshape(weekdayLabelDay == dayofweek.wednesday and weekdayLabelSizeInput == "Large", "Wednesday label — Large", shape.labelup, location.bottom, weekdayLabelBackground, text = "Wednesday", textcolor = weekdayLabelColor, size = size.large)
plotshape(weekdayLabelDay == dayofweek.thursday and weekdayLabelSizeInput == "Tiny", "Thursday label — Tiny", shape.labelup, location.bottom, weekdayLabelBackground, text = "Thursday", textcolor = weekdayLabelColor, size = size.tiny)
plotshape(weekdayLabelDay == dayofweek.thursday and weekdayLabelSizeInput == "Small", "Thursday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Thursday", textcolor = weekdayLabelColor, size = size.small)
plotshape(weekdayLabelDay == dayofweek.thursday and weekdayLabelSizeInput == "Normal", "Thursday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Thursday", textcolor = weekdayLabelColor, size = size.normal)
plotshape(weekdayLabelDay == dayofweek.thursday and weekdayLabelSizeInput == "Large", "Thursday label — Large", shape.labelup, location.bottom, weekdayLabelBackground, text = "Thursday", textcolor = weekdayLabelColor, size = size.large)
plotshape(weekdayLabelDay == dayofweek.friday and weekdayLabelSizeInput == "Tiny", "Friday label — Tiny", shape.labelup, location.bottom, weekdayLabelBackground, text = "Friday", textcolor = weekdayLabelColor, size = size.tiny)
plotshape(weekdayLabelDay == dayofweek.friday and weekdayLabelSizeInput == "Small", "Friday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Friday", textcolor = weekdayLabelColor, size = size.small)
plotshape(weekdayLabelDay == dayofweek.friday and weekdayLabelSizeInput == "Normal", "Friday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Friday", textcolor = weekdayLabelColor, size = size.normal)
plotshape(weekdayLabelDay == dayofweek.friday and weekdayLabelSizeInput == "Large", "Friday label — Large", shape.labelup, location.bottom, weekdayLabelBackground, text = "Friday", textcolor = weekdayLabelColor, size = size.large)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.saturday and weekdayLabelSizeInput == "Tiny", "Saturday label — Tiny", shape.labelup, location.bottom, weekdayLabelBackground, text = "Saturday", textcolor = weekdayLabelColor, size = size.tiny)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.saturday and weekdayLabelSizeInput == "Small", "Saturday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Saturday", textcolor = weekdayLabelColor, size = size.small)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.saturday and weekdayLabelSizeInput == "Normal", "Saturday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Saturday", textcolor = weekdayLabelColor, size = size.normal)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.saturday and weekdayLabelSizeInput == "Large", "Saturday label — Large", shape.labelup, location.bottom, weekdayLabelBackground, text = "Saturday", textcolor = weekdayLabelColor, size = size.large)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.sunday and weekdayLabelSizeInput == "Tiny", "Sunday label — Tiny", shape.labelup, location.bottom, weekdayLabelBackground, text = "Sunday", textcolor = weekdayLabelColor, size = size.tiny)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.sunday and weekdayLabelSizeInput == "Small", "Sunday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Sunday", textcolor = weekdayLabelColor, size = size.small)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.sunday and weekdayLabelSizeInput == "Normal", "Sunday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Sunday", textcolor = weekdayLabelColor, size = size.normal)
plotshape(sevenDayMarket and weekdayLabelDay == dayofweek.sunday and weekdayLabelSizeInput == "Large", "Sunday label — Large", shape.labelup, location.bottom, weekdayLabelBackground, text = "Sunday", textcolor = weekdayLabelColor, size = size.large)
 
// ============================================================================
// PRICE V1.49 MODULE — merged into Time and Price
// ============================================================================
string tpP_G_NOTES = "PRICE — Top-right notes"
bool tpP_showNotesPanel = input.bool(true, "Show fixed notes", group = tpP_G_NOTES)
string tpP_notesPanelText = input.text_area("1. signals (y)(m)(d)(h) & round # levels\n\n2. look back 2 (y)(m)(d)(h)\n\n3. buy low & sell high and never diddle in the middle\n\n4. markets only do 3 things\n\n5. does it look like this? (p/d) (d/p)\n\n6. i only trade in the 3rd hour\n\n7. 3DAY REV /LHF\n\n8. manage your risk (limit orders only)", "Notes", group = tpP_G_NOTES)
color tpP_notesPanelTextColor = input.color(color.black, "Text color", group = tpP_G_NOTES)
color tpP_notesPanelBackground = input.color(color.white, "Background color", tooltip = "Keep this opaque so price levels do not show through the notes.", group = tpP_G_NOTES)
string tpP_notesPanelSizeInput = input.string("Normal", "Text size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = tpP_G_NOTES)
string tpP_notesPanelSize = tpP_notesPanelSizeInput == "Tiny" ? size.tiny : tpP_notesPanelSizeInput == "Small" ? size.small : tpP_notesPanelSizeInput == "Large" ? size.large : tpP_notesPanelSizeInput == "Huge" ? size.huge : size.normal
 
string tpP_G_LEVELS = "PRICE — Quarter Theory grid"
bool tpP_showLevels = input.bool(true, "Show Quarter Theory levels", tooltip = "Draws the major box boundaries and the 25%, 50%, and 75% quarter levels surrounding current price on every chart timeframe.", group = tpP_G_LEVELS)
string tpP_boxMode = input.string("Auto", "Major box-size mode", options = ["Auto", "Manual"], tooltip = "Auto uses the same four-tier fractal for every instrument: Entry charts below 15m use one quarter of the instrument base box, 15m through 1H use the base box, Daily/8H and other sub-weekly charts above 1H use 4x, and Weekly or higher use 16x. Each tier is four times the preceding tier. Manual always uses the exact box size below.", group = tpP_G_LEVELS)
string tpP_currencyScaleInput = input.string("Small Quarters (100 pips)", "Currency grid scale", options = ["Small Quarters (100 pips)", "Large Quarters (1000 pips)"], tooltip = "Used by Auto mode for spot FX, currency CFDs, and recognized CME currency futures.", group = tpP_G_LEVELS)
float tpP_manualBoxSize = input.float(4.0, "Manual major box size", minval = 0.00000001, tooltip = "The full major box before it is divided into four.", group = tpP_G_LEVELS)
float tpP_anchorPrice = input.float(0.0, "Box anchor price", tooltip = "Major box boundaries are measured from this anchor.", group = tpP_G_LEVELS)
int tpP_boxesEachSide = input.int(12, "Completed boxes around active box", minval = 0, maxval = 20, tooltip = "Controls only vertical coverage; prices and spacing never change. In this combined indicator, the maximum is limited to 20 boxes per side (165 Price lines) so Time retains drawing capacity under TradingView's 500-line limit.", group = tpP_G_LEVELS)
bool tpP_showLevelLabels = input.bool(false, "Show level labels", group = tpP_G_LEVELS)
int tpP_labelOffsetBars = input.int(8, "Label offset (bars)", minval = 0, maxval = 100, group = tpP_G_LEVELS)
string tpP_labelSizeInput = input.string("Tiny", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = tpP_G_LEVELS)
color tpP_majorColor = input.color(color.rgb(41, 98, 255), "Major boundary color", group = tpP_G_LEVELS)
int tpP_majorWidth = input.int(2, "Major boundary width", minval = 1, maxval = 4, group = tpP_G_LEVELS)
string tpP_majorStyleInput = input.string("Solid", "Major boundary style", options = ["Solid", "Dashed", "Dotted"], group = tpP_G_LEVELS)
color tpP_halfColor = input.color(color.rgb(41, 98, 255), "Half level color", group = tpP_G_LEVELS)
int tpP_halfWidth = input.int(1, "Half level width", minval = 1, maxval = 4, group = tpP_G_LEVELS)
string tpP_halfStyleInput = input.string("Dashed", "Half level style", options = ["Solid", "Dashed", "Dotted"], group = tpP_G_LEVELS)
color tpP_innerColor = input.color(color.rgb(41, 98, 255), "Quarter level color", group = tpP_G_LEVELS)
int tpP_innerWidth = input.int(1, "Quarter level width", minval = 1, maxval = 4, group = tpP_G_LEVELS)
string tpP_innerStyleInput = input.string("Dotted", "Quarter level style", options = ["Solid", "Dashed", "Dotted"], group = tpP_G_LEVELS)
 
string tpP_majorStyle = tpP_majorStyleInput == "Dashed" ? line.style_dashed : tpP_majorStyleInput == "Dotted" ? line.style_dotted : line.style_solid
string tpP_halfStyle = tpP_halfStyleInput == "Dashed" ? line.style_dashed : tpP_halfStyleInput == "Dotted" ? line.style_dotted : line.style_solid
string tpP_innerStyle = tpP_innerStyleInput == "Dashed" ? line.style_dashed : tpP_innerStyleInput == "Dotted" ? line.style_dotted : line.style_solid
 
tpP_f_adaptive_box(float priceValue) =>
    float minimumBox = syminfo.mintick * 4.0
    float targetBox = math.max(math.abs(priceValue) * 0.04, minimumBox)
    float powerOfTen = math.pow(10.0, math.floor(math.log(targetBox) / math.log(10.0)))
    float normalizedTarget = targetBox / powerOfTen
    float roundedMultiple = normalizedTarget <= 1.0 ? 1.0 : normalizedTarget <= 2.0 ? 2.0 : normalizedTarget <= 4.0 ? 4.0 : normalizedTarget <= 5.0 ? 5.0 : 10.0
    math.max(minimumBox, math.round(roundedMultiple * powerOfTen / syminfo.mintick) * syminfo.mintick)
 
tpP_f_is_fiat_currency_code(string code) =>
    code == "USD" or code == "EUR" or code == "GBP" or code == "JPY" or code == "CHF" or code == "CAD" or code == "AUD" or code == "NZD" or code == "CNH" or code == "CNY" or code == "HKD" or code == "SGD" or code == "SEK" or code == "NOK" or code == "DKK" or code == "MXN" or code == "ZAR" or code == "TRY" or code == "PLN" or code == "HUF" or code == "CZK"
 
tpP_f_currency_pip_size() =>
    syminfo.mintick <= 0.0001 ? 0.0001 : syminfo.mintick <= 0.01 ? 0.01 : syminfo.mintick
 
tpP_f_auto_box(float priceValue) =>
    string root = str.upper(syminfo.root)
    string ticker = str.upper(syminfo.ticker)
    string baseCurrency = str.upper(syminfo.basecurrency)
    string quoteCurrency = str.upper(syminfo.currency)
    bool oilInstrument = root == "CL" or root == "MCL" or root == "BZ" or ticker == "USOIL" or ticker == "UKOIL" or ticker == "WTI" or ticker == "BRENT"
    bool naturalGasInstrument = root == "NG" or root == "QG" or root == "MNG"
    bool cornInstrument = root == "ZC" or root == "YC"
    bool soybeanOilInstrument = root == "ZL"
    bool soybeanMealInstrument = root == "ZM"
    bool soybeanInstrument = root == "ZS" or root == "XK" or root == "MZS"
    bool daxInstrument = root == "FDAX" or root == "FDXM" or root == "FDXS" or ticker == "DAX" or ticker == "GER40" or ticker == "DE40" or ticker == "DEU40" or str.contains(ticker, "GER40") or str.contains(ticker, "DE40")
    bool uk100Instrument = root == "UK100" or root == "FTSE" or root == "UKX" or ticker == "UK100" or ticker == "FTSE" or ticker == "FTSE100" or ticker == "UKX" or str.contains(ticker, "UK100") or str.contains(ticker, "FTSE100")
    bool nikkeiInstrument = root == "NKD" or root == "NIY" or root == "MNK" or root == "MNI" or ticker == "NIKKEI" or ticker == "NI225" or ticker == "N225" or ticker == "JP225" or ticker == "JPN225"
    bool nasdaqInstrument = root == "NQ" or root == "MNQ" or str.contains(ticker, "NDX") or str.contains(ticker, "NAS100") or str.contains(ticker, "USTEC")
    bool dowInstrument = root == "YM" or root == "MYM" or ticker == "DJI" or str.contains(ticker, "US30")
    bool russellInstrument = root == "RTY" or root == "M2K" or ticker == "RUT" or str.contains(ticker, "US2000")
    bool spInstrument = root == "ES" or root == "MES" or ticker == "SPX" or str.contains(ticker, "SPX500") or ticker == "US500"
    bool goldInstrument = root == "GC" or root == "MGC" or ticker == "XAUUSD"
    bool silverInstrument = root == "SI" or root == "SIL" or ticker == "XAGUSD"
    bool copperInstrument = root == "HG" or root == "MHG"
    bool bitcoinInstrument = str.contains(root, "BTC") or str.contains(ticker, "BTC")
    bool etherInstrument = str.contains(root, "ETH") or str.contains(ticker, "ETH")
    bool directCurrencyFuture = root == "6E" or root == "M6E" or root == "E7" or root == "6B" or root == "M6B" or root == "B7" or root == "6A" or root == "M6A" or root == "6C" or root == "M6C" or root == "6S" or root == "M6S" or root == "6N" or root == "M6N"
    bool inverseJpyCurrencyFuture = root == "6J" or root == "M6J" or root == "J7"
    bool fiatPairInstrument = syminfo.type == "forex" or (tpP_f_is_fiat_currency_code(baseCurrency) and tpP_f_is_fiat_currency_code(quoteCurrency)) or directCurrencyFuture or inverseJpyCurrencyFuture
    bool audUsdInstrument = (baseCurrency == "AUD" and quoteCurrency == "USD") or str.contains(ticker, "AUDUSD")
    bool britishPoundInstrument = root == "6B" or root == "M6B" or root == "B7" or (baseCurrency == "GBP" and quoteCurrency == "USD") or str.contains(ticker, "GBPUSD")
    bool canadianDollarInstrument = root == "6C" or root == "M6C" or (baseCurrency == "USD" and quoteCurrency == "CAD") or (baseCurrency == "CAD" and quoteCurrency == "USD") or str.contains(ticker, "USDCAD") or str.contains(ticker, "CADUSD")
    bool newZealandDollarInstrument = root == "6N" or root == "M6N" or (baseCurrency == "NZD" and quoteCurrency == "USD") or str.contains(ticker, "NZDUSD")
    bool swissFrancInstrument = root == "6S" or root == "M6S" or (baseCurrency == "USD" and quoteCurrency == "CHF") or (baseCurrency == "CHF" and quoteCurrency == "USD") or str.contains(ticker, "USDCHF") or str.contains(ticker, "CHFUSD")
    bool euroInstrument = root == "6E" or root == "M6E" or root == "E7" or (baseCurrency == "EUR" and quoteCurrency == "USD") or str.contains(ticker, "EURUSD")
    float currencyPipSize = inverseJpyCurrencyFuture ? 0.000001 : directCurrencyFuture ? 0.0001 : tpP_f_currency_pip_size()
    float currencySmallBox = currencyPipSize * (canadianDollarInstrument ? 25.0 : euroInstrument or swissFrancInstrument ? 100.0 : audUsdInstrument or britishPoundInstrument or newZealandDollarInstrument or inverseJpyCurrencyFuture ? 50.0 : 100.0)
    float currencyBox = tpP_currencyScaleInput == "Large Quarters (1000 pips)" ? currencySmallBox * 10.0 : currencySmallBox
    float nasdaqBaseBox = 500.0
    float selectedBox = oilInstrument ? 4.0 : naturalGasInstrument ? 0.20 : cornInstrument ? 10.0 : soybeanOilInstrument ? 2.0 : soybeanMealInstrument ? 10.0 : soybeanInstrument ? 20.0 : uk100Instrument ? 200.0 : daxInstrument ? 500.0 : nikkeiInstrument ? 2000.0 : nasdaqInstrument ? nasdaqBaseBox : dowInstrument ? 1000.0 : russellInstrument ? 50.0 : spInstrument ? 100.0 : goldInstrument ? 100.0 : silverInstrument ? 2.0 : copperInstrument ? 0.10 : bitcoinInstrument ? tpP_f_adaptive_box(priceValue) : etherInstrument ? 25.0 : fiatPairInstrument ? currencyBox : tpP_f_adaptive_box(priceValue)
    math.max(syminfo.mintick * 4.0, math.round(selectedBox / syminfo.mintick) * syminfo.mintick)
 
tpP_f_clear_grid(array<line> lineStore, array<label> labelStore) =>
    while array.size(lineStore) > 0
        line.delete(array.pop(lineStore))
    while array.size(labelStore) > 0
        label.delete(array.pop(labelStore))
 
var array<line> tpP_gridLines = array.new_line()
var array<label> tpP_gridLabels = array.new_label()
 
if barstate.islast
    float chartSeconds = timeframe.in_seconds()
    bool weeklyOrHigherScaleChart = timeframe.isweekly or timeframe.ismonthly
    bool dailyContextScaleChart = not weeklyOrHigherScaleChart and not na(chartSeconds) and chartSeconds > 60 * 60
    bool entryScaleChart = not na(chartSeconds) and chartSeconds < 15 * 60
    bool levelsVisible = tpP_showLevels and not na(chartSeconds)
    float automaticScaleMultiplier = weeklyOrHigherScaleChart ? 16.0 : dailyContextScaleChart ? 4.0 : entryScaleChart ? 0.25 : 1.0
    float automaticBoxSize = math.max(syminfo.mintick * 4.0, math.round(tpP_f_auto_box(close) * automaticScaleMultiplier / syminfo.mintick) * syminfo.mintick)
    float resolvedBoxSize = tpP_boxMode == "Manual" ? math.max(syminfo.mintick * 4.0, math.round(tpP_manualBoxSize / syminfo.mintick) * syminfo.mintick) : automaticBoxSize
    int effectiveBoxesEachSide = tpP_boxesEachSide
    bool validGrid = levelsVisible and not na(resolvedBoxSize) and resolvedBoxSize > 0
    if not validGrid
        tpP_f_clear_grid(tpP_gridLines, tpP_gridLabels)
    else
        float quarterStep = resolvedBoxSize / 4.0
        float activeBoxFloor = tpP_anchorPrice + math.floor((close - tpP_anchorPrice) / resolvedBoxSize) * resolvedBoxSize
        float firstLevel = activeBoxFloor - effectiveBoxesEachSide * resolvedBoxSize
        int totalSteps = (effectiveBoxesEachSide * 2 + 1) * 4
        int desiredLevels = totalSteps + 1
        int lineStartX = math.max(bar_index - 1, 0)
        string labelSize = tpP_labelSizeInput == "Small" ? size.small : tpP_labelSizeInput == "Normal" ? size.normal : tpP_labelSizeInput == "Large" ? size.large : size.tiny
        for stepIndex = 0 to totalSteps
            float levelPrice = math.round((firstLevel + stepIndex * quarterStep) / syminfo.mintick) * syminfo.mintick
            int positionInBox = stepIndex % 4
            bool isMajor = positionInBox == 0
            bool isHalf = positionInBox == 2
            color activeColor = isMajor ? tpP_majorColor : isHalf ? tpP_halfColor : tpP_innerColor
            int activeWidth = isMajor ? tpP_majorWidth : isHalf ? tpP_halfWidth : tpP_innerWidth
            string activeStyle = isMajor ? tpP_majorStyle : isHalf ? tpP_halfStyle : tpP_innerStyle
            line levelLine = na
            if stepIndex < array.size(tpP_gridLines)
                levelLine := array.get(tpP_gridLines, stepIndex)
            else
                levelLine := line.new(lineStartX, levelPrice, bar_index, levelPrice, xloc = xloc.bar_index, extend = extend.both)
                array.push(tpP_gridLines, levelLine)
            line.set_xy1(levelLine, lineStartX, levelPrice)
            line.set_xy2(levelLine, bar_index, levelPrice)
            line.set_extend(levelLine, extend.both)
            line.set_color(levelLine, activeColor)
            line.set_width(levelLine, activeWidth)
            line.set_style(levelLine, activeStyle)
            if tpP_showLevelLabels
                string prefix = isMajor ? "M" : isHalf ? "Q2" : positionInBox == 1 ? "Q1" : "Q3"
                string labelText = prefix + "  " + str.tostring(levelPrice, format.mintick)
                label levelLabel = na
                if stepIndex < array.size(tpP_gridLabels)
                    levelLabel := array.get(tpP_gridLabels, stepIndex)
                else
                    levelLabel := label.new(bar_index + tpP_labelOffsetBars, levelPrice, labelText, xloc = xloc.bar_index, style = label.style_none)
                    array.push(tpP_gridLabels, levelLabel)
                label.set_xy(levelLabel, bar_index + tpP_labelOffsetBars, levelPrice)
                label.set_text(levelLabel, labelText)
                label.set_textcolor(levelLabel, activeColor)
                label.set_size(levelLabel, labelSize)
        while array.size(tpP_gridLines) > desiredLevels
            line.delete(array.pop(tpP_gridLines))
        if tpP_showLevelLabels
            while array.size(tpP_gridLabels) > desiredLevels
                label.delete(array.pop(tpP_gridLabels))
        else
            while array.size(tpP_gridLabels) > 0
                label.delete(array.pop(tpP_gridLabels))
 
// Fixed screen-space notes panel. Tables remain anchored to the chart corner
// instead of moving with bars or prices.
var table tpP_notesPanel = table.new(position.top_right, 1, 1, frame_width = 0, border_width = 0)
 
if barstate.islast
    if tpP_showNotesPanel
        table.cell(tpP_notesPanel, 0, 0, tpP_notesPanelText, text_color = tpP_notesPanelTextColor, text_size = tpP_notesPanelSize, text_halign = text.align_left, text_valign = text.align_top, bgcolor = tpP_notesPanelBackground)
    else
        table.clear(tpP_notesPanel, 0, 0, 0, 0)

← 返回列表