Price

Kantisam0 · study · 1332 行 · 点赞 29 · TradingView 原页

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

Pine Script

//@version=6
indicator("Time", overlay = true, max_lines_count = 500, max_labels_count = 200, max_boxes_count = 300)
// 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.17 (2026-09-11): simplify the active test stack to HTF/LTF only.
// Structure now owns the parent-rotation close projections: the prior 15m close
// projects through the next 15m rotation on an exact 5m chart, and the prior 1H
// close projects through the next hourly rotation on an exact 15m chart. Both
// visuals are clipped to the newest named-session OB open through its existing
// three-hour post-close timing-window end and have independent editable styles.
// Remove the top-right OB lifecycle status key and reduce the Analysis bridge to
// the two HTF/LTF lanes that remain in use. Both state rows display continuously.
// 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"
int HOUR_MS = 60 * 60 * 1000
int FIFTEEN_MIN_MS = 15 * 60 * 1000
int DAY_MS = 24 * HOUR_MS
type OBVisualState
    float obHigh
    float obLow
    int obStartTime
    int obLastClose
    int obOwner
string G_OB = "Opening-box history / current study"
bool showOB = input.bool(true, "Show OB boxes", tooltip = "Shows the retained Tokyo/London/New York 30-minute opening boxes.", group = G_OB)
int obHistoryCount = input.int(3, "OB boxes to display", minval = 1, maxval = 30, tooltip = "Retains this many completed/current 30-minute opening boxes in chronological order. The same count applies on 1m–15m charts and the fixed-5m-derived 1H display.", group = G_OB)
string obBoundaryStyleInput = input.string("Solid", "OB boundary / border style", options = ["Solid", "Dashed", "Dotted"], group = G_OB)
string obBoundaryStyle = obBoundaryStyleInput == "Dashed" ? line.style_dashed : obBoundaryStyleInput == "Dotted" ? line.style_dotted : line.style_solid
string tokyoOB = input.session("0900-0930", "Tokyo OB (Tokyo time)", group = G_OB)
string londonOB = input.session("0800-0830", "London OB (London time)", group = G_OB)
string newYorkOB = input.session("0930-1000", "New York OB (New York time)", group = G_OB)
color tokyoOBColor = input.color(color.new(color.rgb(78, 54, 161), 25), "Tokyo OB", group = G_OB)
color londonOBColor = input.color(color.new(color.rgb(216, 109, 145), 25), "London OB", group = G_OB)
color newYorkOBColor = input.color(color.new(color.rgb(116, 157, 239), 25), "New York OB", group = G_OB)
string G_DETAILS_V44 = "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
string G_EMAS = "EMA SETTINGS"
bool ema1ShowWeekly = input.bool(true, "W", tooltip = "Show EMA 1 on the exact Weekly chart.", group = G_EMAS, inline = "ema1Visibility")
bool ema1ShowEightHour = input.bool(true, "8H", tooltip = "Show EMA 1 on the exact 8-hour chart.", group = G_EMAS, inline = "ema1Visibility")
bool ema1ShowFifteenMinute = input.bool(false, "15m", tooltip = "Show EMA 1 on the exact 15-minute chart.", group = G_EMAS, inline = "ema1Visibility")
bool ema1ShowEntry = input.bool(false, "Entry", tooltip = "Show EMA 1 on Entry charts below 15 minutes.", group = G_EMAS, inline = "ema1Visibility")
string ema1Timeframe = input.timeframe("5", "EMA 1 calculation timeframe", group = G_EMAS)
float ema1Source = input.source(close, "EMA 1 source", group = G_EMAS)
int ema1Length = input.int(96, "EMA 1 length", minval = 1, group = G_EMAS)
color ema1Color = input.color(color.rgb(91, 156, 246), "EMA 1 color", group = G_EMAS)
int ema1Width = input.int(1, "EMA 1 width", minval = 1, maxval = 4, group = G_EMAS)
string ema1StyleInput = input.string("Solid", "EMA 1 style", options = ["Solid", "Dashed", "Dotted"], group = G_EMAS)
ema1Style = ema1StyleInput == "Dashed" ? plot.linestyle_dashed : ema1StyleInput == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
bool ema2ShowWeekly = input.bool(true, "W", tooltip = "Show EMA 2 on the exact Weekly chart.", group = G_EMAS, inline = "ema2Visibility")
bool ema2ShowEightHour = input.bool(true, "8H", tooltip = "Show EMA 2 on the exact 8-hour chart.", group = G_EMAS, inline = "ema2Visibility")
bool ema2ShowFifteenMinute = input.bool(false, "15m", tooltip = "Show EMA 2 on the exact 15-minute chart.", group = G_EMAS, inline = "ema2Visibility")
bool ema2ShowEntry = input.bool(true, "Entry", tooltip = "Show EMA 2 on Entry charts below 15 minutes.", group = G_EMAS, inline = "ema2Visibility")
string ema2Timeframe = input.timeframe("1", "EMA 2 calculation timeframe", group = G_EMAS)
float ema2Source = input.source(close, "EMA 2 source", group = G_EMAS)
int ema2Length = input.int(96, "EMA 2 length", minval = 1, group = G_EMAS)
color ema2Color = input.color(color.rgb(91, 156, 246), "EMA 2 color", group = G_EMAS)
int ema2Width = input.int(1, "EMA 2 width", minval = 1, maxval = 4, group = G_EMAS)
string ema2StyleInput = input.string("Solid", "EMA 2 style", options = ["Solid", "Dashed", "Dotted"], group = G_EMAS)
ema2Style = ema2StyleInput == "Dashed" ? plot.linestyle_dashed : ema2StyleInput == "Dotted" ? plot.linestyle_dotted : plot.linestyle_solid
string G_WEEKLY_TF = "WEEKLY TF SETTING"
int weeklyChartYearlyPeriodsToShow = input.int(30, "Completed Yearly ranges on Weekly", minval = 1, maxval = 60, tooltip = "Number of completed native Yearly high/low ranges and matching Yearly borders retained on the exact Weekly chart.", 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 showYearlySeparatorsWeekly = input.bool(true, "Show Yearly separators", tooltip = "Uses the Yearly range color, width, style, and history count on the exact Weekly chart.", group = G_WEEKLY_TF)
bool showPreviousYearCloseOnWeekly = input.bool(true, "Show prior Yearly close", tooltip = "On the exact Weekly chart, projects each completed native Yearly close across the following Yearly period.", 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
int weeklyChartQuarterlyPeriodsToShow = input.int(2, "Completed Quarterly ranges on Weekly", minval = 1, maxval = 12, tooltip = "Independent number of completed native Quarterly high/low ranges retained on the exact Weekly chart.", 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 showQuarterlySeparatorsWeekly = input.bool(true, "Show Quarterly separators", tooltip = "Uses the Quarterly range color, width, style, and history count on the exact Weekly chart.", group = G_WEEKLY_TF)
string G_EIGHT_HOUR_TF = "8HR TF SETTING"
bool showMonthlyRangesOnDaily = input.bool(true, "Show completed Monthly highs/lows", tooltip = "On the exact Daily and 8-hour charts, draws each completed native Monthly candle's high and low across that completed month.", group = G_EIGHT_HOUR_TF)
int visibleMonthlyRangeCount = input.int(12, "Completed Monthly ranges to display", minval = 1, maxval = 24, tooltip = "Controls retained Monthly range and separator periods on the exact Daily and 8-hour charts.", 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 showMonthlySeparatorsEightHour = input.bool(true, "Show Monthly separators", tooltip = "Uses the Monthly range color, width, style, and history count on the Daily and 8-hour charts.", group = G_EIGHT_HOUR_TF)
bool showPreviousMonthClose = input.bool(true, "Show prior Monthly close", tooltip = "On the exact 8-hour chart, projects each completed Monthly close across the following native Monthly period.", 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
int weeklyRangesOn8HCount = input.int(2, "Completed Weekly ranges on 8H", minval = 1, maxval = 12, tooltip = "Independent number of completed native Weekly high/low ranges retained on the exact 8-hour chart.", group = G_EIGHT_HOUR_TF)
bool showWeeklyRangesOn8H = input.bool(true, "Show completed Weekly highs/lows", group = G_EIGHT_HOUR_TF)
color c8 = input.color(color.white, "Weekly range color", tooltip = "Controls completed Weekly ranges on the exact 8H chart and the matching custom-8H ranges on lower charts.", 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 showWeeklySeparatorsEightHour = input.bool(true, "Show Weekly separators", tooltip = "Uses the Weekly range color, width, style, and history count on the exact 8-hour chart.", group = G_EIGHT_HOUR_TF)
string G_FIFTEEN_MINUTE_TF = "15 MIN TF SETTING"
int visibleDRangeCount = input.int(30, "Completed Daily ranges to display", minval = 1, maxval = 60, tooltip = "Selects how many completed Daily high/low pairs and matching Daily separators remain visible on supported intraday charts.", 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 showDailySeparatorsFifteenMinute = input.bool(true, "Show Daily separators", tooltip = "Uses the Daily range color, width, style, and history count on supported 15-minute-section charts.", group = G_FIFTEEN_MINUTE_TF)
bool showPreviousDayClose = input.bool(true, "Show prior Daily close", tooltip = "On the exact 15-minute chart, each displayed Daily period carries the close of its immediately preceding Daily period.", group = G_FIFTEEN_MINUTE_TF)
int previousDayCloseDaysToShow = input.int(30, "Daily close days to display", minval = 1, maxval = 30, tooltip = "Includes the active current day. Larger counts may require raising Canonical 1m history bars so the older Daily periods are available.", 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 custom 8H highs/lows", tooltip = "Controls completed custom-8H ranges on supported lower chart timeframes.", group = G_FIFTEEN_MINUTE_TF)
int visible8HRangeCount = input.int(2, "Completed 8H ranges to display", minval = 1, maxval = 30, tooltip = "Display-only history limit for completed custom-8H high/low pairs on supported intraday charts.", 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 showEightHourSeparatorsFifteenMinute = input.bool(true, "Show 8H separators", tooltip = "Uses the 8H range color, width, style, and history count on supported 15-minute-section charts.", group = G_FIFTEEN_MINUTE_TF)
bool showWeekdayLabels = input.bool(true, "Show Monday-Friday labels", tooltip = "Places each available trading-day name at the bottom of the exact 15-minute chart in one fixed horizontal row. Exchange holidays create no synthetic label; 24/7 crypto also includes Saturday and Sunday.", 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"], group = G_FIFTEEN_MINUTE_TF)
string G_FIFTEEN_AND_UNDER = "ENTRY TF SETTING (<15 MIN)"
bool entryShow1HRanges = input.bool(true, "Show completed 1H highs/lows", group = G_FIFTEEN_AND_UNDER)
int entryVisible1HRangeCount = input.int(12, "Completed 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 entryShow1HSeparators = input.bool(true, "Show 1H separators", tooltip = "Uses the 1H range color, width, style, and history count on Entry charts.", group = G_FIFTEEN_AND_UNDER)
bool entryShowPrevious1HClose = input.bool(true, "Show prior 1H close", tooltip = "Projects each completed native one-hour close across the following one-hour period on every Entry chart below 15 minutes.", 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 show15MRanges = input.bool(true, "Show completed 15m highs/lows", tooltip = "Draws each completed native 15-minute candle's high and low on the exact 1-minute chart only.", group = G_FIFTEEN_AND_UNDER)
int visible15MRangeCount = input.int(12, "Completed 15m ranges to display", minval = 1, maxval = 60, group = G_FIFTEEN_AND_UNDER)
color range15MColor = input.color(color.rgb(95, 95, 95), "15m range color", group = G_FIFTEEN_AND_UNDER)
int range15MWidth = input.int(1, "15m range width", minval = 1, maxval = 4, group = G_FIFTEEN_AND_UNDER)
string range15MStyleInput = input.string("Dotted", "15m range style", options = ["Solid", "Dashed", "Dotted"], group = G_FIFTEEN_AND_UNDER)
int range15MStyleCode = range15MStyleInput == "Dashed" ? 2 : range15MStyleInput == "Dotted" ? 1 : 0
bool show15MSeparators = input.bool(true, "Show 15m separators", tooltip = "Uses the 15m range color, width, style, and history count on the exact 1-minute chart.", group = G_FIFTEEN_AND_UNDER)
bool showPrevious15MClose = input.bool(true, "Show prior 15m close", tooltip = "On the exact 1-minute chart, each 15-minute period carries the close of the immediately preceding native 15-minute candle.", group = G_FIFTEEN_AND_UNDER)
int previous15MClosePeriodsToShow = input.int(12, "15m close periods to display", minval = 1, maxval = 60, group = G_FIFTEEN_AND_UNDER)
color previous15MCloseColor = input.color(color.rgb(21, 49, 128), "Prior 15m close color", group = G_FIFTEEN_AND_UNDER)
int previous15MCloseWidth = input.int(2, "Prior 15m close width", minval = 1, maxval = 4, group = G_FIFTEEN_AND_UNDER)
string previous15MCloseStyleInput = input.string("Solid", "Prior 15m close style", options = ["Solid", "Dashed", "Dotted"], group = G_FIFTEEN_AND_UNDER)
string previous15MCloseStyle = previous15MCloseStyleInput == "Dashed" ? line.style_dashed : previous15MCloseStyleInput == "Dotted" ? line.style_dotted : line.style_solid
string G_SEPARATORS = "Structural separators"
bool extendStructuralSeparatorsFullHeight = input.bool(false, "Extend separators full height", tooltip = "When enabled, every enabled H/L separator extends through the full chart pane. When disabled, each separator remains limited to its matching completed range's high and low.", group = G_SEPARATORS)
f_ob_visuals_5m() =>
    int sourceMinutesNow = hour(time, TZ) * 60 + minute(time, TZ)
    int sourceSession8 = sourceMinutesNow >= 900 and sourceMinutesNow < 1320 ? 1 : sourceMinutesNow >= 1320 or sourceMinutesNow < 360 ? 2 : sourceMinutesNow >= 360 and sourceMinutesNow < 840 ? 3 : 0
    bool sourceInTokyoOB = not na(time(timeframe.period, tokyoOB, "Asia/Tokyo"))
    bool sourceInLondonOB = not na(time(timeframe.period, londonOB, "Europe/London"))
    bool sourceInNewYorkOB = not na(time(timeframe.period, newYorkOB, "America/New_York"))
    bool sourceInCurrentOB = sourceSession8 == 1 ? sourceInTokyoOB : sourceSession8 == 2 ? sourceInLondonOB : sourceSession8 == 3 ? sourceInNewYorkOB : false
    bool sourceOBStarts = sourceInCurrentOB and (bar_index == 0 or not sourceInCurrentOB[1])
    var float sourceOBHigh = na
    var float sourceOBLow = na
    var int sourceOBStart = na
    var int sourceOBLastClose = na
    var int sourceOBOwner = 0
    var bool sourceOBStarted = false
    if sourceOBStarts
        sourceOBHigh := high
        sourceOBLow := low
        sourceOBStart := time
        sourceOBLastClose := time_close
        sourceOBOwner := sourceSession8
        sourceOBStarted := true
    else if sourceInCurrentOB and sourceOBStarted
        sourceOBHigh := math.max(sourceOBHigh, high)
        sourceOBLow := math.min(sourceOBLow, low)
        sourceOBLastClose := time_close
    OBVisualState.new(sourceOBHigh, sourceOBLow, sourceOBStart, sourceOBLastClose, sourceOBOwner)
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) =>
    string separatorExtend = extendStructuralSeparatorsFullHeight ? 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) =>
    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 = extendStructuralSeparatorsFullHeight ? 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]]
float chartTimeframeSeconds = timeframe.in_seconds()
bool weeklyEMAChartMatch = timeframe.isweekly and timeframe.multiplier == 1
bool eightHourEMAChartMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds == 8 * 60 * 60
bool fifteenMinuteEMAChartMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds == 15 * 60
bool entryEMAChartMatch = 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 showEMA1OnChart = (weeklyEMAChartMatch and ema1ShowWeekly) or (eightHourEMAChartMatch and ema1ShowEightHour) or (fifteenMinuteEMAChartMatch and ema1ShowFifteenMinute) or (entryEMAChartMatch and ema1ShowEntry)
bool showEMA2OnChart = (weeklyEMAChartMatch and ema2ShowWeekly) or (eightHourEMAChartMatch and ema2ShowEightHour) or (fifteenMinuteEMAChartMatch and ema2ShowFifteenMinute) or (entryEMAChartMatch and ema2ShowEntry)
float ema1Value = showEMA1OnChart ? request.security(syminfo.tickerid, ema1Timeframe, ta.ema(ema1Source, ema1Length), gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off) : na
float ema2Value = showEMA2OnChart ? request.security(syminfo.tickerid, ema2Timeframe, ta.ema(ema2Source, ema2Length), gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off) : na
bool dailyChartTimeframeMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds >= 15 * 60 and chartTimeframeSeconds <= 4 * 60 * 60
bool previousDayCloseChartTimeframeMatch = fifteenMinuteEMAChartMatch
bool isExactDailyChart = timeframe.isdaily and timeframe.multiplier == 1
bool isExactEightHourChart = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds == 8 * 60 * 60
bool isExactWeeklyChart = timeframe.isweekly and timeframe.multiplier == 1
bool isMonthlyContextChart = isExactDailyChart or isExactEightHourChart
bool showOBDetailVisualsOnChart = not na(chartTimeframeSeconds) and chartTimeframeSeconds <= 15 * 60
bool showOBOneHourVisuals = not na(chartTimeframeSeconds) and chartTimeframeSeconds == 60 * 60
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 = 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 weekdayLabelMidpointTime = weekdayLabelsSupportedChart and not na(nativeDayStart) and not na(nativeDayEnd) ? nativeDayStart + int((nativeDayEnd - nativeDayStart) / 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 weekdayLabelCenterBar = showWeekdayLabels and weekdayLabelsSupportedChart and (weekdayLabelCrossesMidpoint or weekdayLabelFirstAfterMidpoint)
int weekdayLabelDay = weekdayLabelCenterBar ? dayofweek(sevenDayMarket ? nativeDayStart : nativeDayEnd) : 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)
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
if 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)
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
            f_push_range(dLines, runDT, not na(runDTE) ? runDTE : time, 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 = isExactEightHourChart and (barstate.isfirst or newWeek)
if newWeeklyEightHourContext and showWeeklyRangesOn8H and not na(canonicalWH1) and not na(canonicalWL1) and not na(canonicalWT1) and not na(canonicalWT2)
    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)
bool newYearlyWeeklyContext = isExactWeeklyChart and (barstate.isfirst or newYear)
if newYearlyWeeklyContext and not na(canonicalYH1) and not na(canonicalYL1) and not na(canonicalYT1) and not na(canonicalYT2)
    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)
int currentYearReferenceStart = isExactWeeklyChart ? time("12M") : na
int currentYearReferenceEnd = isExactWeeklyChart ? time_close("12M") : na
bool previousYearCloseAvailable = showPreviousYearCloseOnWeekly and isExactWeeklyChart 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 = isExactWeeklyChart and (barstate.isfirst or newQuarter)
if newQuarterlyWeeklyContext and not na(canonicalQH1) and not na(canonicalQL1) and not na(canonicalQT1) and not na(canonicalQT2)
    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)
bool newMonthlyDailyContext = isMonthlyContextChart and (barstate.isfirst or newMonth)
if newMonthlyDailyContext and showMonthlyRangesOnDaily and not na(canonicalMH1) and not na(canonicalML1) and not na(canonicalMT1) and not na(canonicalMT2)
    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)
int currentMonthReferenceStart = isMonthlyContextChart ? time("M") : na
int currentMonthReferenceEnd = isMonthlyContextChart ? time_close("M") : na
bool previousMonthCloseAvailable = showPreviousMonthClose and isExactEightHourChart 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 := canonicalPrevDayClose
else if newDay
    currentDayPreviousClose := close[1]
// One fixed-5m object supplies exact OB geometry.
OBVisualState fixedOBState5m = request.security(syminfo.tickerid, "5", f_ob_visuals_5m(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float fixedOBHigh5m = na
float fixedOBLow5m = na
int fixedOBStart5m = na
int fixedOBLastClose5m = na
int fixedOBOwner5m = 0
if not na(fixedOBState5m)
    fixedOBHigh5m := fixedOBState5m.obHigh
    fixedOBLow5m := fixedOBState5m.obLow
    fixedOBStart5m := fixedOBState5m.obStartTime
    fixedOBLastClose5m := fixedOBState5m.obLastClose
    fixedOBOwner5m := fixedOBState5m.obOwner
bool range15MChartTimeframeMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds == 60
[completed15MHigh, completed15MLow, completed15MPreviousClose, completed15MCloseTime] = request.security(syminfo.tickerid, "15", [high[1], low[1], close[1], time_close[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
bool newCompleted15M = range15MChartTimeframeMatch and not na(completed15MCloseTime) and (barstate.isfirst or ta.change(completed15MCloseTime) != 0)
var array<line> fifteenMinuteRangeLines = array.new_line()
var array<line> fifteenMinuteSeparatorLines = array.new_line()
var array<line> previous15MCloseLines = array.new_line()
if newCompleted15M and show15MRanges and not na(completed15MHigh) and not na(completed15MLow)
    f_push_range(fifteenMinuteRangeLines, completed15MCloseTime - FIFTEEN_MIN_MS, completed15MCloseTime, completed15MHigh, completed15MLow, range15MColor, range15MWidth, range15MStyleCode, visible15MRangeCount)
    if show15MSeparators
        string fifteenMinuteSeparatorExtend = extendStructuralSeparatorsFullHeight ? extend.both : extend.none
        line fifteenMinuteSeparator = line.new(completed15MCloseTime, completed15MLow, completed15MCloseTime, completed15MHigh, xloc = xloc.bar_time, extend = fifteenMinuteSeparatorExtend, color = range15MColor, width = range15MWidth, style = range15MStyleCode == 2 ? line.style_dashed : range15MStyleCode == 1 ? line.style_dotted : line.style_solid)
        array.push(fifteenMinuteSeparatorLines, fifteenMinuteSeparator)
        while array.size(fifteenMinuteSeparatorLines) > visible15MRangeCount
            line.delete(array.shift(fifteenMinuteSeparatorLines))
if newCompleted15M and showPrevious15MClose and not na(completed15MPreviousClose)
    int current15MReferenceStart = time("15")
    int current15MReferenceEnd = time_close("15")
    if not na(current15MReferenceStart) and not na(current15MReferenceEnd)
        array.push(previous15MCloseLines, line.new(current15MReferenceStart, completed15MPreviousClose, current15MReferenceEnd, completed15MPreviousClose, xloc = xloc.bar_time, extend = extend.none, color = previous15MCloseColor, width = previous15MCloseWidth, style = previous15MCloseStyle))
        while array.size(previous15MCloseLines) > previous15MClosePeriodsToShow
            line.delete(array.shift(previous15MCloseLines))
bool range1HHostSupported = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds <= 60 * 60
bool entryRange1HChartTimeframeMatch = entryEMAChartMatch and range1HHostSupported
[completed1HHigh, completed1HLow, completed1HPreviousClose, completed1HClose] = request.security(syminfo.tickerid, "60", [high[1], low[1], close[1], time_close[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
bool newCompleted1H = range1HHostSupported and not na(completed1HClose) and (barstate.isfirst or ta.change(completed1HClose) != 0)
var array<line> oneHourRangeLines = array.new_line()
var array<line> oneHourSeparatorLines = array.new_line()
var array<line> previous1HCloseLines = array.new_line()
if newCompleted1H and entryShow1HRanges and entryRange1HChartTimeframeMatch and not na(completed1HHigh) and not na(completed1HLow)
    f_push_range(oneHourRangeLines, completed1HClose - HOUR_MS, completed1HClose, completed1HHigh, completed1HLow, entryRange1HColor, entryRange1HWidth, entryRange1HStyleCode, entryVisible1HRangeCount)
if newCompleted1H and entryShow1HRanges and entryShow1HSeparators and entryRange1HChartTimeframeMatch and not na(completed1HHigh) and not na(completed1HLow)
    f_push_separator_borders(oneHourSeparatorLines, completed1HClose - HOUR_MS, completed1HClose, completed1HHigh, completed1HLow, entryRange1HColor, entryRange1HWidth, entryRange1HStyleCode == 2 ? line.style_dashed : entryRange1HStyleCode == 1 ? line.style_dotted : line.style_solid, entryVisible1HRangeCount)
if newCompleted1H and entryEMAChartMatch and entryShowPrevious1HClose and entryRange1HChartTimeframeMatch and not na(completed1HPreviousClose)
    int current1HReferenceStart = time("60")
    int current1HReferenceEnd = time_close("60")
    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 session8 = minutesNow >= 900 and minutesNow < 1320 ? 1 : minutesNow >= 1320 or minutesNow < 360 ? 2 : minutesNow >= 360 and minutesNow < 840 ? 3 : 0
int sessionStartHour = session8 == 1 ? 15 : session8 == 2 ? 22 : 6
int sessionStartDayOffset = session8 == 2 and hh < 6 ? -1 : 0
int session8Start = session8 == 0 ? na : timestamp(TZ, year(time, TZ), month(time, TZ), dayofmonth(time, TZ) + sessionStartDayOffset, sessionStartHour, 0)
int session8End = session8 == 0 ? na : session8Start + (session8 == 1 ? 7 : 8) * HOUR_MS
bool new8 = session8 != 0 and (na(session8Start[1]) or session8Start != session8Start[1])
bool range8ChartTimeframeMatch = timeframe.isintraday and not na(chartTimeframeSeconds) and chartTimeframeSeconds >= 15 * 60 and chartTimeframeSeconds <= 4 * 60 * 60
var float live8H = na
var float live8L = na
var int live8T1 = na
var int live8T2 = na
var array<line> eightHourRangeLines = array.new_line()
var array<line> eightHourSeparatorLines = array.new_line()
if session8 != 0
    if new8
        if show8H and range8ChartTimeframeMatch and not na(live8H) and not na(live8L) and not na(live8T1) and not na(live8T2)
            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)
        live8H := high
        live8L := low
        live8T1 := session8Start
        live8T2 := session8End
    else
        live8H := math.max(nz(live8H, high), high)
        live8L := math.min(nz(live8L, low), low)
// Named-session OB visuals remain independent from the MTF fact table. Their
// host-chart engine is only needed through 15m; exact 1H uses the fixed-5m
// renderer below, and higher charts do not display OB detail visuals.
bool localOBEngineNeeded = showOBDetailVisualsOnChart
bool inTokyoOB = localOBEngineNeeded and not na(time(timeframe.period, tokyoOB, "Asia/Tokyo"))
bool inLondonOB = localOBEngineNeeded and not na(time(timeframe.period, londonOB, "Europe/London"))
bool inNewYorkOB = localOBEngineNeeded and not na(time(timeframe.period, newYorkOB, "America/New_York"))
bool inCurrentOB = session8 == 1 ? inTokyoOB : session8 == 2 ? inLondonOB : session8 == 3 ? inNewYorkOB : false
bool currentOBStarts = inCurrentOB and (bar_index == 0 or not inCurrentOB[1])
var float obHigh = na
var float obLow = na
var int obStartTime = na
var bool obStarted = false
var box obRangeBox = na
var array<box> obRangeBoxHistory = array.new_box()
var array<line> previousDayCloseLines = array.new_line()
var int renderedPreviousDayCloseStart = na
var box oneHourOBRangeBox = na
var array<box> oneHourOBRangeBoxHistory = array.new_box()
var int renderedOneHourOBStart = na
if new8
    obHigh := na
    obLow := na
    obStartTime := na
    obStarted := false
    // Detach the current pointer without deleting the completed historical OB.
    // The rolling array below owns deletion when a fourth box is created.
    obRangeBox := na
if currentOBStarts
    // Keep the selected number of actual 30-minute OB boxes. This pointer detachment
    // also covers session changes that do not share the custom-8H reset bar.
    obRangeBox := na
    color activeOBColor = session8 == 1 ? tokyoOBColor : session8 == 2 ? londonOBColor : newYorkOBColor
    obHigh := high
    obLow := low
    obStartTime := time
    obStarted := true
    if showOB and showOBDetailVisualsOnChart
        bool completedRangeOverlayVisible = (show15MRanges and range15MChartTimeframeMatch) or (entryShow1HRanges and entryRange1HChartTimeframeMatch)
        color activeOBBorderColor = completedRangeOverlayVisible ? color.new(activeOBColor, 100) : activeOBColor
        obRangeBox := box.new(obStartTime, obHigh, time_close, obLow, xloc = xloc.bar_time, border_color = activeOBBorderColor, border_width = structureWidth, border_style = obBoundaryStyle, bgcolor = color.new(activeOBColor, 82))
        array.push(obRangeBoxHistory, obRangeBox)
        while array.size(obRangeBoxHistory) > obHistoryCount
            box.delete(array.shift(obRangeBoxHistory))
if inCurrentOB and obStarted
    obHigh := math.max(obHigh, high)
    obLow := math.min(obLow, low)
    if not na(obRangeBox)
        box.set_right(obRangeBox, time_close)
        box.set_top(obRangeBox, obHigh)
        box.set_bottom(obRangeBox, obLow)
// 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 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
 
// Exact-1H OB renderer. The 30-minute box is derived from the same fixed
// 5-minute request and remains display-only.
bool oneHourOBContextChanged = showOBOneHourVisuals and not na(fixedOBStart5m) and (na(renderedOneHourOBStart) or fixedOBStart5m != renderedOneHourOBStart)
if oneHourOBContextChanged
    color fixedOBColor = fixedOBOwner5m == 1 ? tokyoOBColor : fixedOBOwner5m == 2 ? londonOBColor : newYorkOBColor
    bool isNewYorkOneHourOB = fixedOBOwner5m == 3
    int oneHourOBVisualStart = isNewYorkOneHourOB ? time : fixedOBStart5m
    int oneHourOBVisualEnd = isNewYorkOneHourOB ? time_close : fixedOBLastClose5m
    oneHourOBRangeBox := na
    if showOB and not na(fixedOBHigh5m) and not na(fixedOBLow5m) and not na(fixedOBLastClose5m)
        color fixedOBBorderColor = entryShow1HRanges and entryRange1HChartTimeframeMatch ? color.new(fixedOBColor, 100) : fixedOBColor
        oneHourOBRangeBox := box.new(oneHourOBVisualStart, fixedOBHigh5m, oneHourOBVisualEnd, fixedOBLow5m, xloc = xloc.bar_time, border_color = fixedOBBorderColor, border_width = structureWidth, border_style = obBoundaryStyle, bgcolor = color.new(fixedOBColor, 82))
        array.push(oneHourOBRangeBoxHistory, oneHourOBRangeBox)
        while array.size(oneHourOBRangeBoxHistory) > obHistoryCount
            box.delete(array.shift(oneHourOBRangeBoxHistory))
    renderedOneHourOBStart := fixedOBStart5m
bool oneHourOBIsRendered = showOBOneHourVisuals and not na(fixedOBStart5m) and fixedOBStart5m == renderedOneHourOBStart
if oneHourOBIsRendered and not na(oneHourOBRangeBox) and not na(fixedOBHigh5m) and not na(fixedOBLow5m) and not na(fixedOBLastClose5m)
    if fixedOBOwner5m != 3
        box.set_right(oneHourOBRangeBox, fixedOBLastClose5m)
    box.set_top(oneHourOBRangeBox, fixedOBHigh5m)
    box.set_bottom(oneHourOBRangeBox, fixedOBLow5m)
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 = weekdayLabelColor, size = size.tiny)
plotshape(weekdayLabelDay == dayofweek.monday and weekdayLabelSizeInput == "Small", "Monday label — Small", shape.labelup, location.bottom, weekdayLabelBackground, text = "Monday", textcolor = weekdayLabelColor, size = size.small)
plotshape(weekdayLabelDay == dayofweek.monday and weekdayLabelSizeInput == "Normal", "Monday label — Normal", shape.labelup, location.bottom, weekdayLabelBackground, text = "Monday", textcolor = weekdayLabelColor, size = size.normal)
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.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.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.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(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.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)
plot(ema1Value, "EMA 1", color = ema1Color, linewidth = ema1Width, style = plot.style_line, linestyle = ema1Style)
plot(ema2Value, "EMA 2", color = ema2Color, linewidth = ema2Width, style = plot.style_line, linestyle = ema2Style)

← 返回列表