Confirmed MTF Support and Resistance Zones

RiccoNewman · study · 2156 行 · 点赞 9 · TradingView 原页

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

Pine Script

//@version=6
indicator("Confirmed MTF Structure Zones v27", "MTF Zones", overlay = true, max_boxes_count = 20, max_lines_count = 40, max_labels_count = 200, dynamic_requests = true, behind_chart = false)
 
// Price-only, confirmed-bar model. Pivot birth is confirmation availability, never pivot time.
// Reloads can differ if the provider revises data or TradingView loads a different history window.
// BEGIN V27 ORGANIZED INPUTS
string settingsMode = input.string("Basic", "Settings mode", options = ["Basic", "Advanced"], group = "01 Everyday", display = display.none, tooltip = "Basic keeps technical calculation controls visible but locked. It does not reset them or replace saved custom values: the indicator keeps using those values. Choose Advanced to edit them. Other dimmed controls need their related feature enabled first. This choice changes editing access only, never zone calculations, priorities, freshness or alerts.")
bool advancedEditing = settingsMode == "Advanced"
string tf1 = input.timeframe("720", "Source 1", group = "01 Everyday", tooltip = "First chart timeframe to study for support and resistance. For example, 12H uses 12-hour candles even when you view a 4-hour chart. Choose the same timeframe as your chart or a longer one. Shorter or repeated choices are ignored.", display = display.none)
string tf2 = input.timeframe("D", "Source 2", group = "01 Everyday", tooltip = "Second chart timeframe to study for support and resistance. Choose a different timeframe, the same length as your chart or longer. Longer candles help find bigger price areas; they also take longer to close and confirm.", display = display.none)
string tf3 = input.timeframe("W", "Source 3", group = "01 Everyday", tooltip = "Third chart timeframe to study for support and resistance. Choose a different timeframe, the same length as your chart or longer. Weekly candles can reveal longer-term areas if enough past candles are loaded.", display = display.none)
string displayMode = input.string("Structure + internal levels", "Zone selection", options = ["Structure + internal levels", "Major + range boundaries", "Major zones", "All ranked zones"], group = "01 Everyday", tooltip = "Choose the map to display. Structure + internal levels shows the main confirmed range and levels inside it. Major + range boundaries adds nearby and broader boundaries to zones with counted bounces or rejections. Major zones shows only zones meeting that defense test. All ranked zones considers all tracked zones. Priority filters and the visible limit still apply; some modes can show few or no zones.", display = display.none)
int globalVisible = input.int(6, "Global maximum visible zones", minval = 2, maxval = 12, group = "01 Everyday", tooltip = "Maximum zones shown when no matching symbol profile is enabled. Higher values show more levels that pass the selected filters; lower values reduce clutter. P1 takes space before P2, then P3, then P4. Hidden or overlapping candidates may leave fewer zones than this limit.", display = display.none)
bool globalP1 = input.bool(true, "P1 Structural range boundaries", group = "01 Everyday", tooltip = "Show P1: main confirmed range boundaries. This hides or shows current zones only; calculations, alerts and optional historical event labels continue. P1 is shown before P2, then P3, then P4. A matching enabled symbol profile replaces these global choices. P1 boundaries appear in Structure + internal levels view.", display = display.none)
bool globalP2 = input.bool(true, "P2 Former boundaries / qualified weekly shelves", group = "01 Everyday", tooltip = "Show P2: former main boundaries or levels backed by large or repeated turns on weekly candles or longer. This hides or shows current zones only; calculations, alerts and optional historical event labels continue. P1 is shown before P2, then P3, then P4. A matching enabled symbol profile replaces these global choices.", display = display.none)
bool globalP3 = input.bool(true, "P3 Confirmed swings / defended shelves", group = "01 Everyday", tooltip = "Show P3: large or repeated turns, or zones with enough counted bounces or rejections. This hides or shows current zones only; calculations, alerts and optional historical event labels continue. P1 is shown before P2, then P3, then P4. A matching enabled symbol profile replaces these global choices.", display = display.none)
bool globalP4 = input.bool(true, "P4 Minor internal levels", group = "01 Everyday", tooltip = "Show P4: other confirmed levels that have not met the P1-P3 strength rules. This hides or shows current zones only; calculations, alerts and optional historical event labels continue. P1 is shown before P2, then P3, then P4. A matching enabled symbol profile replaces these global choices.", display = display.none)
bool showFreshZones = input.bool(true, "Show fresh zones", group = "01 Everyday", tooltip = "Show zones with no separate return counted since they first became available. Earlier candles that formed the zone do not count. Fresh does not mean a level will hold or has never traded before. Hidden zones keep counting visits; P1-P4 ordering is unchanged among zones that pass these choices.", display = display.none)
bool showOnceTested = input.bool(true, "Show zones tested once", group = "01 Everyday", tooltip = "Show zones with exactly one separate return since confirmation. A return means a completed candle on YOUR chart touches or crosses into the zone after price has first spent the selected number of full candles outside it. A touch counts whether price bounces, stalls or breaks through; it is not a successful-retest signal.", display = display.none)
bool showRepeated = input.bool(true, "Show repeatedly tested zones", group = "01 Everyday", tooltip = "Show zones with two or more separate returns since confirmation. Several candles staying inside count as one visit. Repeated visits do not automatically mean exhausted buying or selling. Turn off the other two choices to show only repeatedly tested zones; turn all three off to hide all current zones. Calculations and alerts continue.", display = display.none)
bool nearbyEnabled = input.bool(true, "Limit zones to nearby prices", group = "01 Everyday", tooltip = "Show zones within the distance below, measured from the last completed candle's closing price on YOUR chart. A zone counts if any part of it reaches this nearby area. This only filters the display: zones keep being calculated, visits keep counting, and alerts continue. P2 still appears before P3 and P4 among eligible zones. Turn off to consider distant zones too.", display = display.none)
float nearbyATR = input.float(5.0, "Maximum distance / chart ATR", minval = 0.25, maxval = 100.0, step = 0.25, group = "01 Everyday", tooltip = "Shared default: a symbol profile can still use this value while the global nearby filter is off if that profile enables filtering. Distance allowed above and below the last completed chart candle's closing price. ATR means typical candle movement on YOUR chart. At 5, the nearby area extends 5 ATR each way. Distance is to the nearest edge of a zone, so a wide zone that reaches this area is included. Higher values allow more distant levels. The area updates only after a candle closes; chart timeframe affects its size. Used when filtering is on globally or through the matching symbol profile.", display = display.none)
bool keepMainBoundaries = input.bool(true, "Keep main range boundaries", group = "01 Everyday", tooltip = "Shared default: a symbol profile can still use this value while the global nearby filter is off if that profile enables filtering. Keep the P1 top and bottom of the main range visible even when they are beyond the nearby area, if this view includes the main range. Their priority and freshness visibility choices still apply, and they use visible-zone slots. Turn off to apply the same distance limit to these P1 boundaries. Only affects display; calculations and alerts are unchanged.", display = display.none)
bool showOuter = input.bool(true, "Show broader HTF boundaries", group = "01 Everyday", tooltip = "In Major + range boundaries view, include broader support and resistance outside the nearest levels. Other views do not use this option. The zone limit and priority filters still apply.", active = displayMode == "Major + range boundaries", display = display.none)
string captionLayout = input.string("Linked labels", "Zone caption layout", options = ["Docked list", "Linked labels"], group = "02 Appearance", tooltip = "Linked labels sit beside their zones, with connecting lines when moved to avoid overlap. Docked list puts the labels in fixed rows at the right of the screen, highest price first. Hover either style for explanations. Zone positions and alerts are unchanged.\n\nReading zone labels: P1 is shown before P2, then P3, then P4. Priority controls which levels appear first; it does not predict a bounce. It can change after more candles close or older evidence expires. Internal means a level inside the main range, rather than its top or bottom.", display = display.none)
string captionSize = input.string("Normal", "Label size", options = ["Small", "Normal", "Large"], group = "02 Appearance", tooltip = "Text size for zone labels. Larger text is easier to read but needs more chart space. Zone prices and signals stay the same.", display = display.none)
bool showPriorityTags = input.bool(true, "Show compact priority tags", group = "02 Appearance", tooltip = "Add P1, P2, P3 or P4 to each zone label. P1 is the highest display priority. Turning the tags off changes text only; priority ordering and colors still work.", display = display.none)
bool showFreshnessLabels = input.bool(true, "Show freshness on labels", group = "02 Appearance", tooltip = "Add Fresh, Tested once or Tested N times to each zone's price line. Fresh means no separate return has been counted SINCE this zone was confirmed, not that price has never traded here. This changes text only; the visibility choices in Everyday work independently. Freshness is separate from P1-P4 importance and is not a safety rating.", display = display.none)
bool showLegend = input.bool(true, "Show compact legend", group = "02 Appearance", tooltip = "Show a small summary of the selected view, selected timeframes and displayed zone count. Turn off to free chart space. Calculations and alerts are unchanged.", display = display.none)
bool showEvents = input.bool(false, "Show confirmed event labels", group = "02 Appearance", tooltip = "Show small historical labels for closed-candle events such as breaks, return tests and defended reactions. These are separate from the current zone labels and can add clutter. Turning this off does not disable alerts.", display = display.none)
int eventLimit = input.int(30, "Maximum event labels", minval = 5, maxval = 150, group = "02 Appearance", tooltip = "Maximum historical event labels kept on the chart when Show confirmed event labels is on. Higher values show more past events. Older labels are removed first; calculations and alerts are unchanged.", active = showEvents, display = display.none)
bool showStructuralOrigins = input.bool(true, "Enable zone origins / confirmation", group = "02 Appearance", tooltip = "Master switch for dashed history lines and confirmation diamonds. Dashed lines connect a zone to its starting swing, which was not yet confirmed at that earlier time. Solid zones start when they were first confirmed. Choose tiers below; symbol profiles can override those choices. This switch must be on for any of them to appear.", display = display.none)
bool originP1Lines = input.bool(true, "P1 Origin lines", group = "02 Appearance", inline = "originP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row. P1 markers also control the shared range date in Docked list.", active = showStructuralOrigins, display = display.none)
bool originP1Markers = input.bool(true, "Confirmation markers", group = "02 Appearance", inline = "originP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row. P1 markers also control the shared range date in Docked list.", active = showStructuralOrigins, display = display.none)
bool originP2Lines = input.bool(true, "P2 Origin lines", group = "02 Appearance", inline = "originP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row.", active = showStructuralOrigins, display = display.none)
bool originP2Markers = input.bool(true, "Confirmation markers", group = "02 Appearance", inline = "originP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row.", active = showStructuralOrigins, display = display.none)
bool originP3Lines = input.bool(false, "P3 Origin lines", group = "02 Appearance", inline = "originP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row.", active = showStructuralOrigins, display = display.none)
bool originP3Markers = input.bool(false, "Confirmation markers", group = "02 Appearance", inline = "originP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row.", active = showStructuralOrigins, display = display.none)
bool originP4Lines = input.bool(false, "P4 Origin lines", group = "02 Appearance", inline = "originP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row.", active = showStructuralOrigins, display = display.none)
bool originP4Markers = input.bool(false, "Confirmation markers", group = "02 Appearance", inline = "originP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires Enable zone origins / confirmation. A matching symbol profile can override this row.", active = showStructuralOrigins, display = display.none)
string zoneColorBy = input.string("Importance", "Color by", options = ["Importance", "Role / state"], group = "02 Appearance", tooltip = "Importance uses a separate color for each priority: P1 blue, P2 gold, P3 teal and P4 violet by default. Role / state colors zones by support, resistance and break status instead, so different priorities may share a color. Label text still describes the zone.", display = display.none)
color priorityP1Color = input.color(color.rgb(85, 125, 175), "P1 Structural boundaries", group = "02 Appearance", tooltip = "Color for P1 main confirmed range boundaries, including its zone, label and history annotations. Used only when Color by is Importance. Choose clearly different colors for all four tiers. This changes appearance only.", active = zoneColorBy == "Importance", display = display.none)
color priorityP2Color = input.color(color.rgb(168, 132, 59), "P2 Key structural shelves", group = "02 Appearance", tooltip = "Color for P2 former main boundaries or levels backed by large or repeated turns on weekly candles or longer, including its zone, label and history annotations. Used only when Color by is Importance. Choose clearly different colors for all four tiers. This changes appearance only.", active = zoneColorBy == "Importance", display = display.none)
color priorityP3Color = input.color(color.rgb(32, 145, 157), "P3 Confirmed internal shelves", group = "02 Appearance", tooltip = "Color for P3 large or repeated turns, or zones with enough counted bounces or rejections, including its zone, label and history annotations. Used only when Color by is Importance. Choose clearly different colors for all four tiers. This changes appearance only.", active = zoneColorBy == "Importance", display = display.none)
color priorityP4Color = input.color(color.rgb(156, 95, 191), "P4 Minor internal levels", group = "02 Appearance", tooltip = "Color for P4 other confirmed levels that have not met the P1-P3 strength rules, including its zone, label and history annotations. Used only when Color by is Importance. Choose clearly different colors for all four tiers. This changes appearance only.", active = zoneColorBy == "Importance", display = display.none)
int labelOffset = input.int(12, "Label offset / chart bars", minval = 3, maxval = 100, group = "02 Appearance", tooltip = "How many chart candles to the right of the latest confirmed candle the Linked labels are placed. Higher values put labels farther right. This does not affect Docked list or zone prices.", active = captionLayout == "Linked labels", display = display.none)
float labelGap = input.float(0.5, "Minimum label gap / chart ATR", minval = 0.2, maxval = 3.0, step = 0.1, group = "02 Appearance", tooltip = "Extra vertical separation for Linked labels, measured in typical chart-candle movement (ATR). Higher values spread labels farther apart; lower values keep them closer to their zones. The script also reserves estimated text space to reduce overlap.", active = captionLayout == "Linked labels", display = display.none)
int labelPaneHeight = input.int(550, "Estimated price pane height / pixels", minval = 250, maxval = 1400, step = 50, group = "02 Appearance", tooltip = "Approximate height of the PRICE chart in pixels, excluding panels such as RSI. Pine cannot measure it directly. Lower values reserve more vertical room for Linked labels; higher values pack them closer. Adjust if labels overlap or spread too far. This only affects label placement.", active = captionLayout == "Linked labels", display = display.none)
bool zoneAlertsEnabled = input.bool(true, "Enable events for a TradingView alert", group = "03 Alerts - setup required", tooltip = "This checkbox does not create a running alert. 1) Configure the alert choices below. 2) In TradingView, choose Create alert, select this indicator, then Any alert() function call. 3) Choose notifications or a webhook and click Create. This enables one detailed event message per eligible completed chart candle; on 4H, wait for the 4-hour close. TradingView saves its own copy of the script, symbol, timeframe and settings: recreate the alert after changes. The nine older named alert choices remain independent. This indicator does not place trades or create an external alert for you.", display = display.none)
string zoneAlertScope = input.string("Previously displayed zones", "Zones to watch", options = ["Previously displayed zones", "All tracked zones"], group = "03 Alerts - setup required", tooltip = "Previously displayed zones watches the map selected at the PREVIOUS completed candle, so a break cannot hide its own notification. The current candle can redraw that map afterwards. All tracked zones ignores visible count, nearby-price and chart tier/freshness display choices, but still uses the alert choices below. New zones are seeded silently. Hidden events are not queued for later. Main-range boundaries and extra turning-point levels use approach/visit alerts only; break/retest/failure messages cover the regular tracked zones.", active = zoneAlertsEnabled, display = display.none)
bool alertP1 = input.bool(true, "Alert P1", group = "03 Alerts - setup required", tooltip = "Allow detailed alerts for P1 main-range boundaries. These have approach and visit alerts only. With Previously displayed zones, importance and freshness are read from the map watched at the previous close. This does not change which zones are drawn or any older alert choice.", active = zoneAlertsEnabled, display = display.none)
bool alertP2 = input.bool(true, "Alert P2", group = "03 Alerts - setup required", tooltip = "Allow detailed alerts for P2 zones. Priority means chart importance, not a prediction or safety score. Alert filters are independent of chart visibility choices; Zones to watch controls whether the prior displayed map or all tracked identities is eligible.", active = zoneAlertsEnabled, display = display.none)
bool alertP3 = input.bool(false, "Alert P3", group = "03 Alerts - setup required", tooltip = "Allow detailed alerts for P3 zones. Off reduces notifications for lower-priority levels. This only filters the new detailed alerts; zones and older alert choices are unchanged.", active = zoneAlertsEnabled, display = display.none)
bool alertP4 = input.bool(false, "Alert P4", group = "03 Alerts - setup required", tooltip = "Allow detailed alerts for P4 zones. P4 has not met the stronger promotion rules; it can still matter. Off reduces notifications, without hiding levels or changing older alert choices.", active = zoneAlertsEnabled, display = display.none)
bool alertFresh = input.bool(true, "Alert fresh zones", group = "03 Alerts - setup required", tooltip = "Allow detailed alerts for zones with no separate return counted since confirmation. With Previously displayed zones, freshness is taken from the previous watched map so a first visit does not exclude its own alert. Fresh does not mean guaranteed to hold.", active = zoneAlertsEnabled, display = display.none)
bool alertOnce = input.bool(true, "Alert zones tested once", group = "03 Alerts - setup required", tooltip = "Allow detailed alerts for zones with one counted separate return. Freshness is read before the event candle, so its first visit cannot exclude its own message. Previously displayed zones uses its previous watched map. A visit is not necessarily a bounce or a successful retest.", active = zoneAlertsEnabled, display = display.none)
bool alertRepeated = input.bool(true, "Alert repeatedly tested zones", group = "03 Alerts - setup required", tooltip = "Allow detailed alerts for zones with two or more counted separate returns. Repeated testing is separate from P1-P4 and does not automatically mean a zone is exhausted. Display freshness choices and older alert choices remain independent.", active = zoneAlertsEnabled, display = display.none)
bool alertApproach = input.bool(true, "Approaching a zone", group = "03 Alerts - setup required", tooltip = "Notify when a completed chart candle CLOSES within the approach distance of a zone after being armed farther away. This is a distance notice, not a touch or trade signal. A visit takes precedence if the same candle actually trades into the zone. A new zone already near price is seeded silently; it must first move away before approaching again. Available for regular zones, main-range boundaries and extra turning-point levels.", active = zoneAlertsEnabled, display = display.none)
bool alertVisit = input.bool(true, "New separate visit", group = "03 Alerts - setup required", tooltip = "Notify when a completed candle touches the zone after the required full candles away. Candles lingering inside count as one visit. The candle must actually trade into the zone: a complete gap over it does not count as a visit. Available for regular zones, main-range boundaries and extra turning-point levels. New-zone and first-observation candles never notify.", active = zoneAlertsEnabled, display = display.none)
bool alertBreak = input.bool(true, "Confirmed break", group = "03 Alerts - setup required", tooltip = "Detailed messages when the existing regular-zone model confirms a break with its own timeframe close. Main-range boundaries and extra turning-point levels currently use approach/visit alerts only. This reuses existing break events and does not invent another break rule; the older structural-break alert choices remain independent.", active = zoneAlertsEnabled, display = display.none)
bool alertRetest = input.bool(true, "Successful return test", group = "03 Alerts - setup required", tooltip = "Detailed messages when the existing regular-zone model confirms a successful retest after a confirmed break. A simple visit does not qualify. Main-range boundaries and extra turning-point levels currently use approach/visit alerts only. The older retest choices remain independent.", active = zoneAlertsEnabled, display = display.none)
bool alertFail = input.bool(true, "Failed break or test", group = "03 Alerts - setup required", tooltip = "Detailed messages when the existing regular-zone model marks a pending breach/break as failed. A waiting period expiring is not included. Main-range boundaries and extra turning-point levels currently use approach/visit alerts only. The older setup-failed choice remains independent.", active = zoneAlertsEnabled, display = display.none)
float alertApproachATR = input.float(0.5, "Approach distance / chart ATR", minval = 0.05, maxval = 10.0, step = 0.05, group = "03 Alerts - setup required", tooltip = "Maximum nearest-edge distance from the last completed chart CLOSE for an approaching notice. ATR means typical candle movement on YOUR chart. Higher values notify farther away. The zone must first be armed by full candles away and a close beyond this distance; hovering near it does not repeat the notice.", active = zoneAlertsEnabled and alertApproach, display = display.none)
int alertRearmBars = input.int(1, "Full candles away before another notice", minval = 1, maxval = 20, group = "03 Alerts - setup required", tooltip = "Consecutive completed chart candles wholly above or wholly below a zone before another visit is armed. They must stay on the same side. An approach also needs a close beyond its approach distance before it can rearm. This is a separate alert repeat guard; it does not change the chart freshness count, zone strength, retest state or older alerts.", active = zoneAlertsEnabled and (alertApproach or alertVisit), display = display.none)
bool showNearestPanel = input.bool(false, "Show nearest-zone panel", group = "03 Alerts - setup required", tooltip = "Show a small left-side panel using the latest completed candle and the CURRENT displayed map. It lists the nearest whole band below, nearest whole band above, and any zone containing the close as Inside. Distances use chart ATR. Locations are not confirmed support/resistance roles. Inside is neutral, and this panel gives no entry, stop or reward estimate. It does not change alert scope.", display = display.none)
bool profile1Enabled = input.bool(false, "1 | Enable override", group = "04 Symbol profile 1", tooltip = "Use this profile's visible-zone limit and P1-P4 choices for the exact symbol selected below. Symbols without a matching profile use global defaults. If several enabled profiles match, the first one wins. Profile settings apply only to this indicator instance.", display = display.none)
string profile1Symbol = input.symbol("", "1 | Exact exchange:symbol", group = "04 Symbol profile 1", tooltip = "Choose the exact exchange and symbol for this profile. The same asset on another exchange is a different match. The profile must be enabled. The first enabled matching profile wins; symbols without a matching profile keep global defaults.", active = profile1Enabled, display = display.none)
int profile1Count = input.int(8, "1 | Maximum visible zones", minval = 2, maxval = 12, group = "04 Symbol profile 1", tooltip = "Maximum zones shown for this profile's exact symbol when the profile is enabled and matches. Replaces the global visible limit. Higher values show more levels that pass the selected filters; P1 comes before P2, then P3, then P4. Filtering can leave fewer zones than this limit.", active = profile1Enabled, display = display.none)
bool profile1P1 = input.bool(true, "1 | Show P1", group = "04 Symbol profile 1", inline = "tiers1", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile1Enabled, display = display.none)
bool profile1P2 = input.bool(true, "1 | Show P2", group = "04 Symbol profile 1", inline = "tiers1", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile1Enabled, display = display.none)
bool profile1P3 = input.bool(true, "1 | Show P3", group = "04 Symbol profile 1", inline = "tiers1", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile1Enabled, display = display.none)
bool profile1P4 = input.bool(true, "1 | Show P4", group = "04 Symbol profile 1", inline = "tiers1", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile1Enabled, display = display.none)
string profile1NearbyMode = input.string("Use global", "1 | Nearby price filter", options = ["Use global", "On", "Off"], group = "04 Symbol profile 1", tooltip = "Use global follows Limit zones to nearby prices in Everyday. On enables that filter for this symbol; Off shows eligible distant zones too. Requires this profile to be enabled and match the exact symbol. If several profiles match, only the first enabled match is used. The distance below is independent. This changes display only, not priorities, calculations, visit counts or alerts.", active = profile1Enabled, display = display.none)
float profile1NearbyATR = input.float(0.0, "1 | Nearby distance / chart ATR (0 = global)", minval = 0.0, maxval = 100.0, step = 0.25, group = "04 Symbol profile 1", tooltip = "0 uses the shared Maximum distance / chart ATR. A positive number replaces that distance for this matching profile, even when Nearby price filter is set to Use global. For example, 3 shows zones reaching within 3 typical candle movements (ATR) of the last completed chart close, above or below. Positive values below 0.25 are treated as 0.25. The distance matters only while the effective nearby filter is on. Other symbols keep their own profile or global settings. Keep main range boundaries can be overridden separately below.", active = profile1Enabled and (profile1NearbyMode == "On" or (profile1NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
string profile1KeepMainMode = input.string("Use global", "1 | Keep main range boundaries", options = ["Use global", "On", "Off"], group = "04 Symbol profile 1", tooltip = "Use global follows Keep main range boundaries in Everyday. On keeps this symbol's P1 range top and bottom eligible even outside its nearby price area. Off applies its nearby distance limit to P1 too. Requires this profile to be enabled and match the exact symbol; only the first enabled match is used. P1 and freshness visibility choices still apply, and shown boundaries use visible-zone slots. This separate choice replaces the shared boundary setting for this symbol; nearby on/off and distance choices are unchanged. It has no effect when the nearby filter is off. Display only: calculations, visits and alerts continue.", active = profile1Enabled and (profile1NearbyMode == "On" or (profile1NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
bool profile1OriginsOverride = input.bool(false, "1 | Override origin annotations", group = "04 Symbol profile 1", tooltip = "Off: this symbol uses the global origin-line and confirmation-marker choices. On: use the P1-P4 line and marker switches below. This profile must be enabled, match the exact symbol, and be the first match. The master Enable zone origins / confirmation switch must still be on.", active = profile1Enabled and showStructuralOrigins, display = display.none)
bool profile1OriginP1Lines = input.bool(true, "1 | P1 Origin lines", group = "04 Symbol profile 1", inline = "profile1OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile1OriginP1Markers = input.bool(true, "1 | Confirmation markers", group = "04 Symbol profile 1", inline = "profile1OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile1OriginP2Lines = input.bool(true, "1 | P2 Origin lines", group = "04 Symbol profile 1", inline = "profile1OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile1OriginP2Markers = input.bool(true, "1 | Confirmation markers", group = "04 Symbol profile 1", inline = "profile1OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile1OriginP3Lines = input.bool(false, "1 | P3 Origin lines", group = "04 Symbol profile 1", inline = "profile1OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile1OriginP3Markers = input.bool(false, "1 | Confirmation markers", group = "04 Symbol profile 1", inline = "profile1OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile1OriginP4Lines = input.bool(false, "1 | P4 Origin lines", group = "04 Symbol profile 1", inline = "profile1OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile1OriginP4Markers = input.bool(false, "1 | Confirmation markers", group = "04 Symbol profile 1", inline = "profile1OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile1Enabled and profile1OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2Enabled = input.bool(false, "2 | Enable override", group = "04 Symbol profile 2", tooltip = "Use this profile's visible-zone limit and P1-P4 choices for the exact symbol selected below. Symbols without a matching profile use global defaults. If several enabled profiles match, the first one wins. Profile settings apply only to this indicator instance.", display = display.none)
string profile2Symbol = input.symbol("", "2 | Exact exchange:symbol", group = "04 Symbol profile 2", tooltip = "Choose the exact exchange and symbol for this profile. The same asset on another exchange is a different match. The profile must be enabled. The first enabled matching profile wins; symbols without a matching profile keep global defaults.", active = profile2Enabled, display = display.none)
int profile2Count = input.int(8, "2 | Maximum visible zones", minval = 2, maxval = 12, group = "04 Symbol profile 2", tooltip = "Maximum zones shown for this profile's exact symbol when the profile is enabled and matches. Replaces the global visible limit. Higher values show more levels that pass the selected filters; P1 comes before P2, then P3, then P4. Filtering can leave fewer zones than this limit.", active = profile2Enabled, display = display.none)
bool profile2P1 = input.bool(true, "2 | Show P1", group = "04 Symbol profile 2", inline = "tiers2", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile2Enabled, display = display.none)
bool profile2P2 = input.bool(true, "2 | Show P2", group = "04 Symbol profile 2", inline = "tiers2", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile2Enabled, display = display.none)
bool profile2P3 = input.bool(true, "2 | Show P3", group = "04 Symbol profile 2", inline = "tiers2", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile2Enabled, display = display.none)
bool profile2P4 = input.bool(true, "2 | Show P4", group = "04 Symbol profile 2", inline = "tiers2", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile2Enabled, display = display.none)
string profile2NearbyMode = input.string("Use global", "2 | Nearby price filter", options = ["Use global", "On", "Off"], group = "04 Symbol profile 2", tooltip = "Use global follows Limit zones to nearby prices in Everyday. On enables that filter for this symbol; Off shows eligible distant zones too. Requires this profile to be enabled and match the exact symbol. If several profiles match, only the first enabled match is used. The distance below is independent. This changes display only, not priorities, calculations, visit counts or alerts.", active = profile2Enabled, display = display.none)
float profile2NearbyATR = input.float(0.0, "2 | Nearby distance / chart ATR (0 = global)", minval = 0.0, maxval = 100.0, step = 0.25, group = "04 Symbol profile 2", tooltip = "0 uses the shared Maximum distance / chart ATR. A positive number replaces that distance for this matching profile, even when Nearby price filter is set to Use global. For example, 3 shows zones reaching within 3 typical candle movements (ATR) of the last completed chart close, above or below. Positive values below 0.25 are treated as 0.25. The distance matters only while the effective nearby filter is on. Other symbols keep their own profile or global settings. Keep main range boundaries can be overridden separately below.", active = profile2Enabled and (profile2NearbyMode == "On" or (profile2NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
string profile2KeepMainMode = input.string("Use global", "2 | Keep main range boundaries", options = ["Use global", "On", "Off"], group = "04 Symbol profile 2", tooltip = "Use global follows Keep main range boundaries in Everyday. On keeps this symbol's P1 range top and bottom eligible even outside its nearby price area. Off applies its nearby distance limit to P1 too. Requires this profile to be enabled and match the exact symbol; only the first enabled match is used. P1 and freshness visibility choices still apply, and shown boundaries use visible-zone slots. This separate choice replaces the shared boundary setting for this symbol; nearby on/off and distance choices are unchanged. It has no effect when the nearby filter is off. Display only: calculations, visits and alerts continue.", active = profile2Enabled and (profile2NearbyMode == "On" or (profile2NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
bool profile2OriginsOverride = input.bool(false, "2 | Override origin annotations", group = "04 Symbol profile 2", tooltip = "Off: this symbol uses the global origin-line and confirmation-marker choices. On: use the P1-P4 line and marker switches below. This profile must be enabled, match the exact symbol, and be the first match. The master Enable zone origins / confirmation switch must still be on.", active = profile2Enabled and showStructuralOrigins, display = display.none)
bool profile2OriginP1Lines = input.bool(true, "2 | P1 Origin lines", group = "04 Symbol profile 2", inline = "profile2OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2OriginP1Markers = input.bool(true, "2 | Confirmation markers", group = "04 Symbol profile 2", inline = "profile2OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2OriginP2Lines = input.bool(true, "2 | P2 Origin lines", group = "04 Symbol profile 2", inline = "profile2OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2OriginP2Markers = input.bool(true, "2 | Confirmation markers", group = "04 Symbol profile 2", inline = "profile2OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2OriginP3Lines = input.bool(false, "2 | P3 Origin lines", group = "04 Symbol profile 2", inline = "profile2OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2OriginP3Markers = input.bool(false, "2 | Confirmation markers", group = "04 Symbol profile 2", inline = "profile2OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2OriginP4Lines = input.bool(false, "2 | P4 Origin lines", group = "04 Symbol profile 2", inline = "profile2OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile2OriginP4Markers = input.bool(false, "2 | Confirmation markers", group = "04 Symbol profile 2", inline = "profile2OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile2Enabled and profile2OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3Enabled = input.bool(false, "3 | Enable override", group = "04 Symbol profile 3", tooltip = "Use this profile's visible-zone limit and P1-P4 choices for the exact symbol selected below. Symbols without a matching profile use global defaults. If several enabled profiles match, the first one wins. Profile settings apply only to this indicator instance.", display = display.none)
string profile3Symbol = input.symbol("", "3 | Exact exchange:symbol", group = "04 Symbol profile 3", tooltip = "Choose the exact exchange and symbol for this profile. The same asset on another exchange is a different match. The profile must be enabled. The first enabled matching profile wins; symbols without a matching profile keep global defaults.", active = profile3Enabled, display = display.none)
int profile3Count = input.int(8, "3 | Maximum visible zones", minval = 2, maxval = 12, group = "04 Symbol profile 3", tooltip = "Maximum zones shown for this profile's exact symbol when the profile is enabled and matches. Replaces the global visible limit. Higher values show more levels that pass the selected filters; P1 comes before P2, then P3, then P4. Filtering can leave fewer zones than this limit.", active = profile3Enabled, display = display.none)
bool profile3P1 = input.bool(true, "3 | Show P1", group = "04 Symbol profile 3", inline = "tiers3", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile3Enabled, display = display.none)
bool profile3P2 = input.bool(true, "3 | Show P2", group = "04 Symbol profile 3", inline = "tiers3", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile3Enabled, display = display.none)
bool profile3P3 = input.bool(true, "3 | Show P3", group = "04 Symbol profile 3", inline = "tiers3", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile3Enabled, display = display.none)
bool profile3P4 = input.bool(true, "3 | Show P4", group = "04 Symbol profile 3", inline = "tiers3", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile3Enabled, display = display.none)
string profile3NearbyMode = input.string("Use global", "3 | Nearby price filter", options = ["Use global", "On", "Off"], group = "04 Symbol profile 3", tooltip = "Use global follows Limit zones to nearby prices in Everyday. On enables that filter for this symbol; Off shows eligible distant zones too. Requires this profile to be enabled and match the exact symbol. If several profiles match, only the first enabled match is used. The distance below is independent. This changes display only, not priorities, calculations, visit counts or alerts.", active = profile3Enabled, display = display.none)
float profile3NearbyATR = input.float(0.0, "3 | Nearby distance / chart ATR (0 = global)", minval = 0.0, maxval = 100.0, step = 0.25, group = "04 Symbol profile 3", tooltip = "0 uses the shared Maximum distance / chart ATR. A positive number replaces that distance for this matching profile, even when Nearby price filter is set to Use global. For example, 3 shows zones reaching within 3 typical candle movements (ATR) of the last completed chart close, above or below. Positive values below 0.25 are treated as 0.25. The distance matters only while the effective nearby filter is on. Other symbols keep their own profile or global settings. Keep main range boundaries can be overridden separately below.", active = profile3Enabled and (profile3NearbyMode == "On" or (profile3NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
string profile3KeepMainMode = input.string("Use global", "3 | Keep main range boundaries", options = ["Use global", "On", "Off"], group = "04 Symbol profile 3", tooltip = "Use global follows Keep main range boundaries in Everyday. On keeps this symbol's P1 range top and bottom eligible even outside its nearby price area. Off applies its nearby distance limit to P1 too. Requires this profile to be enabled and match the exact symbol; only the first enabled match is used. P1 and freshness visibility choices still apply, and shown boundaries use visible-zone slots. This separate choice replaces the shared boundary setting for this symbol; nearby on/off and distance choices are unchanged. It has no effect when the nearby filter is off. Display only: calculations, visits and alerts continue.", active = profile3Enabled and (profile3NearbyMode == "On" or (profile3NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
bool profile3OriginsOverride = input.bool(false, "3 | Override origin annotations", group = "04 Symbol profile 3", tooltip = "Off: this symbol uses the global origin-line and confirmation-marker choices. On: use the P1-P4 line and marker switches below. This profile must be enabled, match the exact symbol, and be the first match. The master Enable zone origins / confirmation switch must still be on.", active = profile3Enabled and showStructuralOrigins, display = display.none)
bool profile3OriginP1Lines = input.bool(true, "3 | P1 Origin lines", group = "04 Symbol profile 3", inline = "profile3OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3OriginP1Markers = input.bool(true, "3 | Confirmation markers", group = "04 Symbol profile 3", inline = "profile3OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3OriginP2Lines = input.bool(true, "3 | P2 Origin lines", group = "04 Symbol profile 3", inline = "profile3OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3OriginP2Markers = input.bool(true, "3 | Confirmation markers", group = "04 Symbol profile 3", inline = "profile3OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3OriginP3Lines = input.bool(false, "3 | P3 Origin lines", group = "04 Symbol profile 3", inline = "profile3OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3OriginP3Markers = input.bool(false, "3 | Confirmation markers", group = "04 Symbol profile 3", inline = "profile3OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3OriginP4Lines = input.bool(false, "3 | P4 Origin lines", group = "04 Symbol profile 3", inline = "profile3OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile3OriginP4Markers = input.bool(false, "3 | Confirmation markers", group = "04 Symbol profile 3", inline = "profile3OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile3Enabled and profile3OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4Enabled = input.bool(false, "4 | Enable override", group = "04 Symbol profile 4", tooltip = "Use this profile's visible-zone limit and P1-P4 choices for the exact symbol selected below. Symbols without a matching profile use global defaults. If several enabled profiles match, the first one wins. Profile settings apply only to this indicator instance.", display = display.none)
string profile4Symbol = input.symbol("", "4 | Exact exchange:symbol", group = "04 Symbol profile 4", tooltip = "Choose the exact exchange and symbol for this profile. The same asset on another exchange is a different match. The profile must be enabled. The first enabled matching profile wins; symbols without a matching profile keep global defaults.", active = profile4Enabled, display = display.none)
int profile4Count = input.int(8, "4 | Maximum visible zones", minval = 2, maxval = 12, group = "04 Symbol profile 4", tooltip = "Maximum zones shown for this profile's exact symbol when the profile is enabled and matches. Replaces the global visible limit. Higher values show more levels that pass the selected filters; P1 comes before P2, then P3, then P4. Filtering can leave fewer zones than this limit.", active = profile4Enabled, display = display.none)
bool profile4P1 = input.bool(true, "4 | Show P1", group = "04 Symbol profile 4", inline = "tiers4", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile4Enabled, display = display.none)
bool profile4P2 = input.bool(true, "4 | Show P2", group = "04 Symbol profile 4", inline = "tiers4", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile4Enabled, display = display.none)
bool profile4P3 = input.bool(true, "4 | Show P3", group = "04 Symbol profile 4", inline = "tiers4", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile4Enabled, display = display.none)
bool profile4P4 = input.bool(true, "4 | Show P4", group = "04 Symbol profile 4", inline = "tiers4", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile4Enabled, display = display.none)
string profile4NearbyMode = input.string("Use global", "4 | Nearby price filter", options = ["Use global", "On", "Off"], group = "04 Symbol profile 4", tooltip = "Use global follows Limit zones to nearby prices in Everyday. On enables that filter for this symbol; Off shows eligible distant zones too. Requires this profile to be enabled and match the exact symbol. If several profiles match, only the first enabled match is used. The distance below is independent. This changes display only, not priorities, calculations, visit counts or alerts.", active = profile4Enabled, display = display.none)
float profile4NearbyATR = input.float(0.0, "4 | Nearby distance / chart ATR (0 = global)", minval = 0.0, maxval = 100.0, step = 0.25, group = "04 Symbol profile 4", tooltip = "0 uses the shared Maximum distance / chart ATR. A positive number replaces that distance for this matching profile, even when Nearby price filter is set to Use global. For example, 3 shows zones reaching within 3 typical candle movements (ATR) of the last completed chart close, above or below. Positive values below 0.25 are treated as 0.25. The distance matters only while the effective nearby filter is on. Other symbols keep their own profile or global settings. Keep main range boundaries can be overridden separately below.", active = profile4Enabled and (profile4NearbyMode == "On" or (profile4NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
string profile4KeepMainMode = input.string("Use global", "4 | Keep main range boundaries", options = ["Use global", "On", "Off"], group = "04 Symbol profile 4", tooltip = "Use global follows Keep main range boundaries in Everyday. On keeps this symbol's P1 range top and bottom eligible even outside its nearby price area. Off applies its nearby distance limit to P1 too. Requires this profile to be enabled and match the exact symbol; only the first enabled match is used. P1 and freshness visibility choices still apply, and shown boundaries use visible-zone slots. This separate choice replaces the shared boundary setting for this symbol; nearby on/off and distance choices are unchanged. It has no effect when the nearby filter is off. Display only: calculations, visits and alerts continue.", active = profile4Enabled and (profile4NearbyMode == "On" or (profile4NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
bool profile4OriginsOverride = input.bool(false, "4 | Override origin annotations", group = "04 Symbol profile 4", tooltip = "Off: this symbol uses the global origin-line and confirmation-marker choices. On: use the P1-P4 line and marker switches below. This profile must be enabled, match the exact symbol, and be the first match. The master Enable zone origins / confirmation switch must still be on.", active = profile4Enabled and showStructuralOrigins, display = display.none)
bool profile4OriginP1Lines = input.bool(true, "4 | P1 Origin lines", group = "04 Symbol profile 4", inline = "profile4OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4OriginP1Markers = input.bool(true, "4 | Confirmation markers", group = "04 Symbol profile 4", inline = "profile4OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4OriginP2Lines = input.bool(true, "4 | P2 Origin lines", group = "04 Symbol profile 4", inline = "profile4OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4OriginP2Markers = input.bool(true, "4 | Confirmation markers", group = "04 Symbol profile 4", inline = "profile4OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4OriginP3Lines = input.bool(false, "4 | P3 Origin lines", group = "04 Symbol profile 4", inline = "profile4OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4OriginP3Markers = input.bool(false, "4 | Confirmation markers", group = "04 Symbol profile 4", inline = "profile4OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4OriginP4Lines = input.bool(false, "4 | P4 Origin lines", group = "04 Symbol profile 4", inline = "profile4OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile4OriginP4Markers = input.bool(false, "4 | Confirmation markers", group = "04 Symbol profile 4", inline = "profile4OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile4Enabled and profile4OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5Enabled = input.bool(false, "5 | Enable override", group = "04 Symbol profile 5", tooltip = "Use this profile's visible-zone limit and P1-P4 choices for the exact symbol selected below. Symbols without a matching profile use global defaults. If several enabled profiles match, the first one wins. Profile settings apply only to this indicator instance.", display = display.none)
string profile5Symbol = input.symbol("", "5 | Exact exchange:symbol", group = "04 Symbol profile 5", tooltip = "Choose the exact exchange and symbol for this profile. The same asset on another exchange is a different match. The profile must be enabled. The first enabled matching profile wins; symbols without a matching profile keep global defaults.", active = profile5Enabled, display = display.none)
int profile5Count = input.int(8, "5 | Maximum visible zones", minval = 2, maxval = 12, group = "04 Symbol profile 5", tooltip = "Maximum zones shown for this profile's exact symbol when the profile is enabled and matches. Replaces the global visible limit. Higher values show more levels that pass the selected filters; P1 comes before P2, then P3, then P4. Filtering can leave fewer zones than this limit.", active = profile5Enabled, display = display.none)
bool profile5P1 = input.bool(true, "5 | Show P1", group = "04 Symbol profile 5", inline = "tiers5", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile5Enabled, display = display.none)
bool profile5P2 = input.bool(true, "5 | Show P2", group = "04 Symbol profile 5", inline = "tiers5", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile5Enabled, display = display.none)
bool profile5P3 = input.bool(true, "5 | Show P3", group = "04 Symbol profile 5", inline = "tiers5", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile5Enabled, display = display.none)
bool profile5P4 = input.bool(true, "5 | Show P4", group = "04 Symbol profile 5", inline = "tiers5", tooltip = "Choose which priorities this matching enabled profile shows: P1 = main range boundaries; P2 = former boundaries or levels supported by weekly turns; P3 = large or repeated turns, or levels with counted bounces or rejections; P4 = other confirmed levels. These replace global tier choices. P1 is selected before P2, then P3, then P4. Hiding a tier does not stop its calculations or alerts.", active = profile5Enabled, display = display.none)
string profile5NearbyMode = input.string("Use global", "5 | Nearby price filter", options = ["Use global", "On", "Off"], group = "04 Symbol profile 5", tooltip = "Use global follows Limit zones to nearby prices in Everyday. On enables that filter for this symbol; Off shows eligible distant zones too. Requires this profile to be enabled and match the exact symbol. If several profiles match, only the first enabled match is used. The distance below is independent. This changes display only, not priorities, calculations, visit counts or alerts.", active = profile5Enabled, display = display.none)
float profile5NearbyATR = input.float(0.0, "5 | Nearby distance / chart ATR (0 = global)", minval = 0.0, maxval = 100.0, step = 0.25, group = "04 Symbol profile 5", tooltip = "0 uses the shared Maximum distance / chart ATR. A positive number replaces that distance for this matching profile, even when Nearby price filter is set to Use global. For example, 3 shows zones reaching within 3 typical candle movements (ATR) of the last completed chart close, above or below. Positive values below 0.25 are treated as 0.25. The distance matters only while the effective nearby filter is on. Other symbols keep their own profile or global settings. Keep main range boundaries can be overridden separately below.", active = profile5Enabled and (profile5NearbyMode == "On" or (profile5NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
string profile5KeepMainMode = input.string("Use global", "5 | Keep main range boundaries", options = ["Use global", "On", "Off"], group = "04 Symbol profile 5", tooltip = "Use global follows Keep main range boundaries in Everyday. On keeps this symbol's P1 range top and bottom eligible even outside its nearby price area. Off applies its nearby distance limit to P1 too. Requires this profile to be enabled and match the exact symbol; only the first enabled match is used. P1 and freshness visibility choices still apply, and shown boundaries use visible-zone slots. This separate choice replaces the shared boundary setting for this symbol; nearby on/off and distance choices are unchanged. It has no effect when the nearby filter is off. Display only: calculations, visits and alerts continue.", active = profile5Enabled and (profile5NearbyMode == "On" or (profile5NearbyMode == "Use global" and nearbyEnabled)), display = display.none)
bool profile5OriginsOverride = input.bool(false, "5 | Override origin annotations", group = "04 Symbol profile 5", tooltip = "Off: this symbol uses the global origin-line and confirmation-marker choices. On: use the P1-P4 line and marker switches below. This profile must be enabled, match the exact symbol, and be the first match. The master Enable zone origins / confirmation switch must still be on.", active = profile5Enabled and showStructuralOrigins, display = display.none)
bool profile5OriginP1Lines = input.bool(true, "5 | P1 Origin lines", group = "04 Symbol profile 5", inline = "profile5OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5OriginP1Markers = input.bool(true, "5 | Confirmation markers", group = "04 Symbol profile 5", inline = "profile5OriginP1", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP1 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation. P1 markers also control the shared range date in Docked list.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5OriginP2Lines = input.bool(true, "5 | P2 Origin lines", group = "04 Symbol profile 5", inline = "profile5OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5OriginP2Markers = input.bool(true, "5 | Confirmation markers", group = "04 Symbol profile 5", inline = "profile5OriginP2", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP2 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5OriginP3Lines = input.bool(false, "5 | P3 Origin lines", group = "04 Symbol profile 5", inline = "profile5OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5OriginP3Markers = input.bool(false, "5 | Confirmation markers", group = "04 Symbol profile 5", inline = "profile5OriginP3", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP3 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5OriginP4Lines = input.bool(false, "5 | P4 Origin lines", group = "04 Symbol profile 5", inline = "profile5OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
bool profile5OriginP4Markers = input.bool(false, "5 | Confirmation markers", group = "04 Symbol profile 5", inline = "profile5OriginP4", tooltip = "Origin lines: draw a dashed line back to the earlier turning high or low that led to this zone.\nConfirmation markers: show a diamond where enough candles had closed for the indicator to first draw the zone. Solid zones start there too.\nP4 is the zone's priority today; it may have been different when the zone appeared. Requires this matching profile's Override origin annotations and the master Enable zone origins / confirmation.", active = profile5Enabled and profile5OriginsOverride and showStructuralOrigins, display = display.none)
int strength = input.int(3, "Pivot left/right strength", minval = 1, maxval = 20, group = "05 Advanced calculations", tooltip = "Candles required on EACH side of a high or low before it is accepted as a turning point (a swing). With 3, three candles must finish after the turn before it can be confirmed. The result appears on a closed chart candle. Higher values find fewer, bigger turns and take longer.", active = advancedEditing, display = display.none)
int atrLength = input.int(14, "Source ATR length", minval = 2, maxval = 100, group = "05 Advanced calculations", tooltip = "Candles used to measure typical price movement, called ATR (Average True Range). This is measured on each selected timeframe and your chart. A higher value averages more candles and changes more slowly. It can affect zone widths, break distances and strength checks.", active = advancedEditing, display = display.none)
float widthATR = input.float(0.20, "Zone half-width / source ATR", minval = 0.02, maxval = 1.0, step = 0.01, group = "05 Advanced calculations", tooltip = "How far each edge of a new zone extends from its turning price, measured in typical candle movement (ATR) on that timeframe. At 0.20, each edge is 0.20 ATR away, so the full width is 0.40 ATR. Higher values make wider zones. Existing zone edges stay fixed.", active = advancedEditing, display = display.none)
float mergeATR = input.float(0.25, "Evidence merge distance / source ATR", minval = 0.0, maxval = 1.0, step = 0.05, group = "05 Advanced calculations", tooltip = "How close a new turning point must be to add support to an existing zone instead of creating a separate one. The price areas must also overlap. Distance is measured in typical candle movement (ATR) on that timeframe. Higher values combine more nearby turns; the older zone edges stay fixed.", active = advancedEditing, display = display.none)
int capacity = input.int(40, "Maximum retained zones", minval = 10, maxval = 60, group = "05 Advanced calculations", tooltip = "Maximum zones remembered by the indicator, including ones hidden from view. Higher values remember more levels but do not show more on screen; use Maximum visible zones for that. When full, a stronger new zone can replace a weaker one that is not protected by an active break or test. This can change alerts.", active = advancedEditing, display = display.none)
float breakATR = input.float(0.10, "Break buffer / chart ATR", minval = 0.0, maxval = 1.0, step = 0.01, group = "05 Advanced calculations", tooltip = "Extra distance beyond a zone that a candle on YOUR chart must close before a possible break is recorded. Measured in typical chart-candle movement (ATR). Higher values ignore more small overshoots. The zone also needs a close from its own confirmation timeframe before a return can count as a successful retest.", active = advancedEditing, display = display.none)
int timeout = input.int(40, "Retest timeout / chart bars", minval = 2, maxval = 500, group = "05 Advanced calculations", tooltip = "How many candles on YOUR chart price has to return and successfully test a zone after a confirmed break. This return is called a retest. Higher values allow more time. When time runs out the waiting test ends, but the zone can remain visible.", active = advancedEditing, display = display.none)
int localTimeout = input.int(40, "Local breach timeout / chart bars", minval = 2, maxval = 500, group = "05 Advanced calculations", tooltip = "How many candles on YOUR chart to wait for the zone's confirmation timeframe to close beyond the zone after a possible break. Higher values allow more time. If no confirmation arrives, that possible-break check ends.", active = advancedEditing, display = display.none)
int cooldown = input.int(5, "Reaction cooldown / chart bars", minval = 1, maxval = 100, group = "05 Advanced calculations", tooltip = "Minimum candles on YOUR chart between counted bounces or rejections at one zone. Higher values prevent several nearby candles from looking like many separate successful tests. This affects zone strength, not its width.", active = advancedEditing, display = display.none)
int defenseWindow = input.int(6, "Defense confirmation window / chart bars", minval = 1, maxval = 50, group = "05 Advanced calculations", tooltip = "After price touches a zone, how many candles on YOUR chart it has to move far enough away for a bounce or rejection to count. Higher values allow slower reactions; lower values require a quicker response.", active = advancedEditing, display = display.none)
float defenseATR = input.float(0.75, "Defended departure / birth source ATR", minval = 0.25, maxval = 3.0, step = 0.05, group = "05 Advanced calculations", tooltip = "How far price must move away after touching a zone for a bounce or rejection to count. Measured in typical candle movement (ATR) on the zone's original timeframe, saved when it was created. Higher values require bigger moves and usually count fewer reactions.", active = advancedEditing, display = display.none)
int evidenceAge = input.int(300, "Rejection evidence lifetime / chart bars", minval = 20, maxval = 2000, group = "05 Advanced calculations", tooltip = "How long a counted bounce or rejection helps a zone qualify as important, in candles on YOUR chart. Higher values keep older reactions useful for longer; lower values focus on recent reactions. This can change the zone's priority and whether it is shown.", active = advancedEditing, display = display.none)
string outerMinTF = input.timeframe("D", "Broader boundary minimum evidence TF", group = "05 Advanced calculations", tooltip = "Smallest timeframe allowed to back an extra broader boundary in Major + range boundaries view. For example, D requires daily candles or longer. Higher choices show fewer, longer-term boundaries. Requires Show broader HTF boundaries; HTF means a higher timeframe.", active = advancedEditing and showOuter and displayMode == "Major + range boundaries", display = display.none)
int outerDepth = input.int(2, "Broader boundary depth / nonoverlapping zones", minval = 1, maxval = 4, group = "05 Advanced calculations", tooltip = "Which separate level to consider on each side in Major + range boundaries view: 1 looks at the nearest, 2 can look one level farther away, and so on. Requires Show broader HTF boundaries. This does not automatically add that many zones.", active = advancedEditing and showOuter and displayMode == "Major + range boundaries", display = display.none)
string structureTF = input.timeframe("D", "Structural range governing timeframe", group = "05 Advanced calculations", tooltip = "Candle size used to confirm a break of the MAIN trading range. The indicator chooses the shortest selected timeframe at least this long, or the longest selected timeframe if all are shorter. Longer choices take longer to confirm. Individual zones keep their own break-confirmation timeframe.", active = advancedEditing, display = display.none)
int structureDays = input.int(90, "Structural origin horizon / calendar days", minval = 20, maxval = 365, group = "05 Advanced calculations", tooltip = "How far back to look for turning highs and lows when choosing the main range and higher-priority levels, in calendar days. Higher values let older price history matter for longer. Lower values focus on recent turns and can leave no suitable main range.", active = advancedEditing, display = display.none)
float prominenceATR = input.float(1.0, "Single daily swing prominence / origin ATR", minval = 0.5, maxval = 3.0, step = 0.1, group = "05 Advanced calculations", tooltip = "How large a daily-or-longer turning point must be to matter on its own. Measured against typical candle movement (ATR) when the turn formed. Higher values require a more obvious turn. Alternatively, two separate large turns near the same price can qualify together.", active = advancedEditing, display = display.none)
float rangeSpanATR = input.float(3.0, "Minimum parent span / larger origin ATR", minval = 1.0, maxval = 10.0, step = 0.5, group = "05 Advanced calculations", tooltip = "Minimum distance between the proposed main range top and bottom, measured in typical candle movement (ATR). The larger of the two saved movement measurements is used. Higher values require a wider range; lower values allow a narrower range.", active = advancedEditing, display = display.none)
float structureBufferATR = input.float(0.10, "Parent break buffer / anchor ATR", minval = 0.0, maxval = 1.0, step = 0.05, group = "05 Advanced calculations", tooltip = "Extra distance past the main range edge needed to confirm a break. Measured in typical candle movement (ATR) saved at its boundaries. Higher values ignore more small overshoots. A candle on the main range's confirmation timeframe must close beyond this extra distance.", active = advancedEditing, display = display.none)
int structureHalfLife = input.int(30, "Structural strength half-life / calendar days", minval = 5, maxval = 180, group = "05 Advanced calculations", tooltip = "How quickly older turning points lose weight when choosing the main range. After this many calendar days, the age-dependent part of their score is halved. Higher values keep old turns competitive longer; lower values favor recent turns. Stored turning prices do not move.", active = advancedEditing, display = display.none)
float extraRegistryGapATR = input.float(1.0, "Extra swing shelf spacing / chart ATR", minval = 0.0, maxval = 3.0, step = 0.1, group = "05 Advanced calculations", tooltip = "Minimum space between an extra level found from turning points and a zone already shown, measured in typical chart-candle movement (ATR). Higher values hide more closely packed extra levels. Lower values can show more nearby levels; overlapping ones are still excluded.", active = advancedEditing, display = display.none)
int freshnessSeparationBars = input.int(1, "Full candles away before another visit", minval = 1, maxval = 20, group = "05 Advanced calculations", tooltip = "Completed candles on YOUR chart that must stay entirely above or entirely below the zone before a later touch can count as a new visit. These candles must be consecutive and on the same side. Higher values combine nearby contacts into fewer visits. The zone's confirmation candle is ignored. Changing chart timeframe or loaded history can change reconstructed counts. A new main range starts its own count; priority changes and support/resistance changes do not reset it.", active = advancedEditing, display = display.none)
bool showDashboard = input.bool(false, "Show validation dashboard", group = "06 Diagnostics", tooltip = "Show a troubleshooting table with loaded history, counts and model checks. Leave off for a clean chart. It does not change which zones are calculated.", display = display.none)
bool showHierarchyCandidates = input.bool(false, "Debug ranked role-shelf candidates", group = "06 Diagnostics", tooltip = "Show a technical ranking table for troubleshooting zone selection. Leave off for normal use. This does not change zone detection, priority or alerts.", display = display.none)
bool details = input.bool(false, "Show selected zone details", group = "06 Diagnostics", tooltip = "Add selected-zone troubleshooting rows to the validation dashboard. Requires Show validation dashboard; the ranked-candidates debug view takes precedence. Leave off for normal use.", active = showDashboard and not showHierarchyCandidates, display = display.none)
bool traceEnabled = input.bool(false, "Enable zone-history trace", group = "06 Diagnostics", tooltip = "Show an optional troubleshooting history for a price you choose below. It explains creation, merging, replacement and current display filtering. It reconstructs events from loaded closed candles; it is not a trade signal and does not alter zones or alerts.", display = display.none)
float traceTarget = input.price(0.0, "Target price", group = "06 Diagnostics", tooltip = "Price to investigate, in this symbol's normal price units. Enter the level you expected to see. Use only with Enable zone-history trace. Zero is a valid price, not an off switch. Change this when switching to another symbol.", active = traceEnabled, display = display.none)
int traceToleranceTicks = input.int(2, "Pivot tolerance / minimum ticks", minval = 0, maxval = 100, group = "06 Diagnostics", tooltip = "How close a turning price must be to the target to begin following its history, in minimum price increments (ticks). Higher values include more nearby turns. Zones containing the target are also followed. This only changes the troubleshooting history.", active = traceEnabled, display = display.none)
int traceLimit = input.int(500, "Maximum retained trace records", minval = 20, maxval = 1000, group = "06 Diagnostics", tooltip = "Maximum troubleshooting records kept while the trace is on. Higher values preserve more events; oldest records are dropped when full. This does not increase the number of calculated or visible zones.", active = traceEnabled, display = display.none)
int tracePage = input.int(1, "History page / latest first", minval = 1, maxval = 50, group = "06 Diagnostics", tooltip = "Page of troubleshooting events, 20 per page, newest first. Higher page numbers show older stored events. The current-zones rows explain what is shown now, not what was shown under earlier settings. Reconstructed history can differ if the data provider or loaded history changes.", active = traceEnabled, display = display.none)
bool showAlertDebug = input.bool(false, "Show alert candidate history", group = "06 Diagnostics", tooltip = "Show up to 20 recent raw event candidates and numeric checks for troubleshooting. Historical candidates are not proof that a message was sent: displayed-zone history is not reconstructed. Only real-time completed candles can send the new detailed message. Hidden or filtered candidates are never saved up for later delivery. No external TradingView alert is created by this switch.", display = display.none)
// END V27 ORGANIZED INPUTS
 
 
// Display profiles are instance-local defaults, not account-wide TradingView preferences.
// New inputs are appended so existing saved input indices remain compatible.
// Importance colors are presentation-only; role/state remains explicit in captions and line styles.
// Append annotation controls: existing saved input IDs remain unchanged.
 
// Per-symbol annotation overrides are appended; all prior saved input IDs are retained.
 
 
 
 
 
f_profileMatch(bool enabled, string symbol) =>
    enabled and str.length(symbol) > 0 and str.upper(ticker.standard(symbol)) == str.upper(ticker.standard(syminfo.tickerid))
int activeProfile = f_profileMatch(profile1Enabled, profile1Symbol) ? 1 : f_profileMatch(profile2Enabled, profile2Symbol) ? 2 : f_profileMatch(profile3Enabled, profile3Symbol) ? 3 : f_profileMatch(profile4Enabled, profile4Symbol) ? 4 : f_profileMatch(profile5Enabled, profile5Symbol) ? 5 : 0
int visible = activeProfile == 1 ? profile1Count : activeProfile == 2 ? profile2Count : activeProfile == 3 ? profile3Count : activeProfile == 4 ? profile4Count : activeProfile == 5 ? profile5Count : globalVisible
bool showP1 = activeProfile == 1 ? profile1P1 : activeProfile == 2 ? profile2P1 : activeProfile == 3 ? profile3P1 : activeProfile == 4 ? profile4P1 : activeProfile == 5 ? profile5P1 : globalP1
bool showP2 = activeProfile == 1 ? profile1P2 : activeProfile == 2 ? profile2P2 : activeProfile == 3 ? profile3P2 : activeProfile == 4 ? profile4P2 : activeProfile == 5 ? profile5P2 : globalP2
bool showP3 = activeProfile == 1 ? profile1P3 : activeProfile == 2 ? profile2P3 : activeProfile == 3 ? profile3P3 : activeProfile == 4 ? profile4P3 : activeProfile == 5 ? profile5P3 : globalP3
bool showP4 = activeProfile == 1 ? profile1P4 : activeProfile == 2 ? profile2P4 : activeProfile == 3 ? profile3P4 : activeProfile == 4 ? profile4P4 : activeProfile == 5 ? profile5P4 : globalP4
 
// Resolve the same first matching profile for all display controls. No later-profile fallback.
bool overrideOrigins = activeProfile == 1 ? profile1OriginsOverride : activeProfile == 2 ? profile2OriginsOverride : activeProfile == 3 ? profile3OriginsOverride : activeProfile == 4 ? profile4OriginsOverride : activeProfile == 5 ? profile5OriginsOverride : false
bool effectiveOriginP1Lines = overrideOrigins ? (activeProfile == 1 ? profile1OriginP1Lines : activeProfile == 2 ? profile2OriginP1Lines : activeProfile == 3 ? profile3OriginP1Lines : activeProfile == 4 ? profile4OriginP1Lines : activeProfile == 5 ? profile5OriginP1Lines : originP1Lines) : originP1Lines
bool effectiveOriginP1Markers = overrideOrigins ? (activeProfile == 1 ? profile1OriginP1Markers : activeProfile == 2 ? profile2OriginP1Markers : activeProfile == 3 ? profile3OriginP1Markers : activeProfile == 4 ? profile4OriginP1Markers : activeProfile == 5 ? profile5OriginP1Markers : originP1Markers) : originP1Markers
bool effectiveOriginP2Lines = overrideOrigins ? (activeProfile == 1 ? profile1OriginP2Lines : activeProfile == 2 ? profile2OriginP2Lines : activeProfile == 3 ? profile3OriginP2Lines : activeProfile == 4 ? profile4OriginP2Lines : activeProfile == 5 ? profile5OriginP2Lines : originP2Lines) : originP2Lines
bool effectiveOriginP2Markers = overrideOrigins ? (activeProfile == 1 ? profile1OriginP2Markers : activeProfile == 2 ? profile2OriginP2Markers : activeProfile == 3 ? profile3OriginP2Markers : activeProfile == 4 ? profile4OriginP2Markers : activeProfile == 5 ? profile5OriginP2Markers : originP2Markers) : originP2Markers
bool effectiveOriginP3Lines = overrideOrigins ? (activeProfile == 1 ? profile1OriginP3Lines : activeProfile == 2 ? profile2OriginP3Lines : activeProfile == 3 ? profile3OriginP3Lines : activeProfile == 4 ? profile4OriginP3Lines : activeProfile == 5 ? profile5OriginP3Lines : originP3Lines) : originP3Lines
bool effectiveOriginP3Markers = overrideOrigins ? (activeProfile == 1 ? profile1OriginP3Markers : activeProfile == 2 ? profile2OriginP3Markers : activeProfile == 3 ? profile3OriginP3Markers : activeProfile == 4 ? profile4OriginP3Markers : activeProfile == 5 ? profile5OriginP3Markers : originP3Markers) : originP3Markers
bool effectiveOriginP4Lines = overrideOrigins ? (activeProfile == 1 ? profile1OriginP4Lines : activeProfile == 2 ? profile2OriginP4Lines : activeProfile == 3 ? profile3OriginP4Lines : activeProfile == 4 ? profile4OriginP4Lines : activeProfile == 5 ? profile5OriginP4Lines : originP4Lines) : originP4Lines
bool effectiveOriginP4Markers = overrideOrigins ? (activeProfile == 1 ? profile1OriginP4Markers : activeProfile == 2 ? profile2OriginP4Markers : activeProfile == 3 ? profile3OriginP4Markers : activeProfile == 4 ? profile4OriginP4Markers : activeProfile == 5 ? profile5OriginP4Markers : originP4Markers) : originP4Markers
 
f_originLineVisible(int priority) =>
    showStructuralOrigins and (priority == 1 ? effectiveOriginP1Lines : priority == 2 ? effectiveOriginP2Lines : priority == 3 ? effectiveOriginP3Lines : priority == 4 ? effectiveOriginP4Lines : false)
 
f_confirmationVisible(int priority) =>
    showStructuralOrigins and (priority == 1 ? effectiveOriginP1Markers : priority == 2 ? effectiveOriginP2Markers : priority == 3 ? effectiveOriginP3Markers : priority == 4 ? effectiveOriginP4Markers : false)
 
f_priorityColor(int priority) =>
    priority == 1 ? priorityP1Color : priority == 2 ? priorityP2Color : priority == 3 ? priorityP3Color : priorityP4Color
 
// Visible-chart prices drive presentation only. Ignore the open candle and the axis scale;
// labels therefore cannot expand their own spacing in an autoscale feedback loop.
var float captionViewLow = na
var float captionViewHigh = na
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time and barstate.isconfirmed
    captionViewLow := na(captionViewLow) ? low : math.min(captionViewLow, low)
    captionViewHigh := na(captionViewHigh) ? high : math.max(captionViewHigh, high)
 
// Optional passive lifecycle ledger. Appended inputs preserve all existing input IDs.
 
// BEGIN V22 FRESHNESS INPUTS (append-only: existing saved input IDs stay unchanged)
// END V22 FRESHNESS INPUTS
 
// BEGIN V23 NEARBY INPUTS
// END V23 NEARBY INPUTS
 
// BEGIN V24 SYMBOL NEARBY INPUTS
// END V24 SYMBOL NEARBY INPUTS
 
// BEGIN V25 SYMBOL MAIN BOUNDARY INPUTS
// END V25 SYMBOL MAIN BOUNDARY INPUTS
 
// BEGIN V26 ZONE ALERT INPUTS
// END V26 ZONE ALERT INPUTS
 
// BEGIN V24 SYMBOL NEARBY RESOLUTION
string selectedNearbyMode = activeProfile == 1 ? profile1NearbyMode : activeProfile == 2 ? profile2NearbyMode : activeProfile == 3 ? profile3NearbyMode : activeProfile == 4 ? profile4NearbyMode : activeProfile == 5 ? profile5NearbyMode : "Use global"
float selectedNearbyATR = activeProfile == 1 ? profile1NearbyATR : activeProfile == 2 ? profile2NearbyATR : activeProfile == 3 ? profile3NearbyATR : activeProfile == 4 ? profile4NearbyATR : activeProfile == 5 ? profile5NearbyATR : 0.0
bool effectiveNearbyEnabled = selectedNearbyMode == "Use global" ? nearbyEnabled : selectedNearbyMode == "On"
float effectiveNearbyATR = selectedNearbyATR > 0.0 ? math.max(0.25, selectedNearbyATR) : nearbyATR
string nearbySettingsSource = "mode " + (activeProfile > 0 and selectedNearbyMode != "Use global" ? "profile " + str.tostring(activeProfile) : "global") + "; distance " + (activeProfile > 0 and selectedNearbyATR > 0.0 ? "profile " + str.tostring(activeProfile) : "global")
// END V24 SYMBOL NEARBY RESOLUTION
 
// BEGIN V25 SYMBOL MAIN BOUNDARY RESOLUTION
string selectedKeepMainMode = activeProfile == 1 ? profile1KeepMainMode : activeProfile == 2 ? profile2KeepMainMode : activeProfile == 3 ? profile3KeepMainMode : activeProfile == 4 ? profile4KeepMainMode : activeProfile == 5 ? profile5KeepMainMode : "Use global"
bool effectiveKeepMainBoundaries = selectedKeepMainMode == "Use global" ? keepMainBoundaries : selectedKeepMainMode == "On"
string keepMainSettingsSource = "P1 exception " + (effectiveKeepMainBoundaries ? "on" : "off") + " from " + (activeProfile > 0 and selectedKeepMainMode != "Use global" ? "profile " + str.tostring(activeProfile) : "global")
// END V25 SYMBOL MAIN BOUNDARY RESOLUTION
 
// role: +1 support/-1 resistance; pending: local direction, structural gates retests.
type Zone
    int id
    float lo
    float hi
    float scale
    int bornTime
    int bornBar
    int lastEvidence
    int observations
    int mask
    int role
    int govSlot
    string govTF
    float govSeconds
    int pending = 0
    bool structural = false
    int breachBar = na
    int breachTime = na
    int structuralBar = na
    int lastGovClose = 0
    float breakBuffer = 0.0
    int rejections = 0
    int failedDefenses = 0
    int lastDefenseBar = -100000
    bool touching = false
    bool defending = false
    int defenseRole = 0
    int defenseStart = na
    float defenseBuffer = 0.0
    array<int> rejectionBars = na
 
type SwingCluster
    int id
    int kind
    float lo
    float hi
    float scale
    int bornTime
    int lastOriginStart
    int lastOriginEnd
    int independentAvailable
    int mask
    float bestProm
    float dailyProm
    int tests
    int strongTests
 
type OriginEvent
    int kind
    int start
    int finish
 
type SwingBirthOrigin
    int id
    int start
    int finish
    float price
    int firstConfirm
    string sourceTF
 
type MapLevel
    float lo
    float hi
    int born
    color tint
    string heading
    string evidence
    string status
    string tooltip
    bool dashed
    int priority = 4
    SwingBirthOrigin origin = na
    string freshnessKey = "" // V22 presentation-only visit identity
 
// BEGIN V22 FRESHNESS TYPE
// Independent visit clock; never reads defense counts or changes model evidence.
type FreshVisit
    int born
    int visits = 0
    int outsideSide = 0
    int outsideBars = 0
    bool armed = false
    int lastBar = na
// END V22 FRESHNESS TYPE
 
// BEGIN V26 ZONE ALERT TYPES
type ZoneNotice
    string key
    string event
    float lo
    float hi
    int role
    string sourceTF
    int stamp
    int priority = 0
    int visits = 0
    bool delivered = false
 
type ZoneWatch
    string key
    float lo
    float hi
    int born
    int role
    string sourceTF
    int priority = 4
    int visits = 0
    int side = 0
    int away = 0
    bool touchArmed = false
    bool approachArmed = false
    int lastBar = na
    int lastSeen = na
    float previousClose = na
// END V26 ZONE ALERT TYPES
 
type RoleEvidence
    int id
    int lastBreakDir = 0
    int lastBreakTime = 0
    bool held = false
    int lastRetestDir = 0
    int lastRetestTime = 0
    int prevPending = 0
    bool prevStructural = false
    int prevStructuralBar = na
 
type FormerBoundary
    int swingId
    float lo
    float hi
    float scale
    int kind
    int mask
    int availableTime
 
type ParentOriginView
    int rangeBorn
    int lowId
    int highId
    SwingBirthOrigin low
    SwingBirthOrigin high
 
// BEGIN V22 FRESHNESS STATE
var map<string, FreshVisit> freshness = map.new<string, FreshVisit>()
// END V22 FRESHNESS STATE
 
// BEGIN V26 ZONE ALERT STATE
var map<string, ZoneWatch> zoneWatches = map.new<string, ZoneWatch>()
var map<string, ZoneWatch> priorWatchedMap = map.new<string, ZoneWatch>()
var array<ZoneNotice> noticeQueue = array.new<ZoneNotice>()
var array<ZoneNotice> noticeHistory = array.new<ZoneNotice>()
// raw candidates, delivered events, batches, last batch events, omitted events
var array<int> noticeCounters = array.new_int(5, 0)
var table nearestZonePanel = table.new(position.middle_left, 2, 4, bgcolor = color.new(color.black, 15))
var table noticeDebug = table.new(position.bottom_center, 2, 22, bgcolor = color.new(color.black, 12))
// END V26 ZONE ALERT STATE
 
var array<Zone> zones = array.new<Zone>()
var array<int> seenTimes = array.new_int(3, 0)
var array<int> sourceCounts = array.new_int(3, 0)
var array<label> eventLabels = array.new<label>()
var array<box> boxes = array.new<box>()
var array<line> lines = array.new<line>()
var array<label> captions = array.new<label>()
var int nextId = 0
var int created = 0
var int breaks = 0
var int localBreaches = 0
var int localExpiries = 0
var int rejectionCount = 0
var int defenseFailures = 0
var int retired = 0
var int rejectedAdmissions = 0
var int majorCount = 0
var int retests = 0
var int failures = 0
var int expiries = 0
var int historyStart = time
var int snapshotTime = na
var int snapshotBar = na
var float snapshotClose = na
var float snapshotATR = na
var float digest = 0.0
var array<SwingCluster> swings = array.new<SwingCluster>()
var array<OriginEvent> originEvents = array.new<OriginEvent>()
var array<int> structuralSeenTimes = array.new_int(3, 0)
var array<string> brokenPairs = array.new_string()
var int nextSwingId = 0
var int swingRetired = 0
var SwingCluster parentLow = na
var SwingCluster parentHigh = na
var bool parentActive = false
var int parentLowId = 0
var int parentHighId = 0
var int parentBorn = na
var int parentBornBar = na
var int parentGovSlot = 0
var string parentGovTF = ""
var int parentLastClose = 0
var float parentBuffer = 0.0
var int structuralResetTime = 0
var bool ageReseedPending = false
var int parentBreaks = 0
var int parentExpiries = 0
var int parentFormations = 0
var float structureDigest = 0.0
var map<int, RoleEvidence> roleEvidence = map.new<int, RoleEvidence>()
var array<FormerBoundary> formerBoundaries = array.new<FormerBoundary>()
var int keyRoleCount = 0
var float hierarchyDigest = 0.0
// Presentation metadata only: bounded one-to-one with retained zones, immutable after birth.
var map<int, SwingBirthOrigin> zoneBirthOrigins = map.new<int, SwingBirthOrigin>()
var map<int, SwingBirthOrigin> swingBirthOrigins = map.new<int, SwingBirthOrigin>()
var ParentOriginView parentOrigins = na
float chartATR = ta.atr(atrLength)
float chartSeconds = timeframe.in_seconds()
float sec1 = timeframe.in_seconds(tf1)
float sec2 = timeframe.in_seconds(tf2)
float sec3 = timeframe.in_seconds(tf3)
bool valid1 = sec1 >= chartSeconds
bool valid2 = sec2 >= chartSeconds and sec2 != sec1
bool valid3 = sec3 >= chartSeconds and sec3 != sec1 and sec3 != sec2
 
if not chart.is_standard
    runtime.error("Use a standard time-based candle chart. Synthetic candles are not supported.")
 
// Source tuples offset pivots and ATR together; no unfinished HTF data is consumed.
f_source(string tf, bool enabled, float seconds) =>
    float ph = ta.pivothigh(high, strength, strength)
    float pl = ta.pivotlow(low, strength, strength)
    float a = ta.atr(atrLength)
    float outH = na
    float outL = na
    float outA = na
    int outT = na
    float outC = na
    int outO = na
    int originStart = time[strength]
    int originFinish = time_close[strength]
    float originATR = a[strength]
    float leftLow = ta.lowest(low[strength], strength + 1)
    float rightLow = ta.lowest(low, strength + 1)
    float leftHigh = ta.highest(high[strength], strength + 1)
    float rightHigh = ta.highest(high, strength + 1)
    float highProm = not na(ph) and originATR > 0 ? math.min(ph - leftLow, ph - rightLow) / originATR : na
    float lowProm = not na(pl) and originATR > 0 ? math.min(leftHigh - pl, rightHigh - pl) / originATR : na
    int outOrigin = na
    int outFinish = na
    float outOriginATR = na
    float outHP = na
    float outLP = na
    if enabled
        if seconds == chartSeconds
            outH := ph
            outL := pl
            outA := a
            outT := time_close
            outC := close
            outO := time
            outOrigin := originStart
            outFinish := originFinish
            outOriginATR := originATR
            outHP := highProm
            outLP := lowProm
        else
            [h, l, v, t, c, o, origin, finish, oa, hp, lp] = request.security(syminfo.tickerid, tf, [ph[1], pl[1], a[1], time_close[1], close[1], time[1], originStart[1], originFinish[1], originATR[1], highProm[1], lowProm[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
            outH := h
            outL := l
            outA := v
            outT := t
            outC := c
            outO := o
            outOrigin := origin
            outFinish := finish
            outOriginATR := oa
            outHP := hp
            outLP := lp
    [outH, outL, outA, outT, outC, outO, outOrigin, outFinish, outOriginATR, outHP, outLP]
 
[h1, l1, a1, t1, c1, o1, p1, q1, pa1, hp1, lp1] = f_source(tf1, valid1, sec1)
[h2, l2, a2, t2, c2, o2, p2, q2, pa2, hp2, lp2] = f_source(tf2, valid2, sec2)
[h3, l3, a3, t3, c3, o3, p3, q3, pa3, hp3, lp3] = f_source(tf3, valid3, sec3)
 
f_votes(int mask) =>
    (mask % 2) + (int(math.floor(mask / 2)) % 2) + (int(math.floor(mask / 4)) % 2)
 
f_has(int mask, int source) =>
    int(math.floor(mask / math.pow(2, source))) % 2 == 1
f_maxTF(Zone z) =>
    math.max(f_has(z.mask, 0) ? sec1 : 0.0, math.max(f_has(z.mask, 1) ? sec2 : 0.0, f_has(z.mask, 2) ? sec3 : 0.0))
f_recentRejections(Zone z) =>
    int count = 0
    if array.size(z.rejectionBars) > 0
        for j = 0 to array.size(z.rejectionBars) - 1
            if snapshotBar - array.get(z.rejectionBars, j) <= evidenceAge
                count += 1
    count
f_rejectionMass(Zone z) =>
    float mass = 0.0
    if array.size(z.rejectionBars) > 0
        for j = 0 to array.size(z.rejectionBars) - 1
            mass += math.max(0.0, 1.0 - (snapshotBar - array.get(z.rejectionBars, j)) / float(evidenceAge))
    mass
f_major(Zone z) =>
    float highestTF = f_maxTF(z)
    int count = f_recentRejections(z)
    highestTF >= 86400 and count >= (highestTF >= 604800 ? 1 : 2)
f_tfName(string tf, float seconds) =>
    seconds < 60 ? str.tostring(seconds, "#") + "s" : seconds < 3600 ? str.tostring(seconds / 60, "#.##") + "m" : seconds < 86400 ? (seconds % 3600 == 0 ? str.tostring(seconds / 3600, "#") + "H" : str.tostring(seconds / 60, "#.##") + "m") : (tf == "D" ? "1D" : tf == "W" ? "1W" : tf == "M" ? "1M" : tf)
f_provenance(Zone z) =>
    string sources = f_has(z.mask, 0) ? f_tfName(tf1, sec1) : ""
    if f_has(z.mask, 1)
        sources += (str.length(sources) > 0 ? "+" : "") + f_tfName(tf2, sec2)
    if f_has(z.mask, 2)
        sources += (str.length(sources) > 0 ? "+" : "") + f_tfName(tf3, sec3)
    sources
f_score(Zone z) =>
    float recent = 0.5 / (1.0 + (snapshotBar - z.lastEvidence) / 100.0)
    float tfWeight = 2.0 * math.sqrt(math.min(f_maxTF(z) / 86400.0, 7.0))
    math.max(0.0, 3.0 * f_rejectionMass(z) + tfWeight + 0.25 * math.min(z.observations, 4) + recent - 1.25 * math.min(z.failedDefenses, 4))
f_retention(Zone z) =>
    float distance = math.abs(snapshotClose - (z.lo + z.hi) * 0.5) / snapshotATR
    f_score(z) - math.min(distance * 0.03, 3.0)
 
// V16 passive diagnostic state. Separate namespaces avoid Zone / SwingCluster ID collisions.
type ZoneTraceRecord
    int delivered
    string identity
    string eventName
    string detail
var array<ZoneTraceRecord> traceRecords = array.new<ZoneTraceRecord>()
var array<string> traceWatch = array.new_string()
var array<int> traceDropped = array.new_int(1, 0)
f_traceKey(string registry, int id) =>
    registry + "#" + str.tostring(id)
f_traceNear(float p) =>
    not na(p) and math.abs(p - traceTarget) <= syminfo.mintick * traceToleranceTicks + syminfo.mintick * 0.000001
f_traceGeometry(float lo, float hi) =>
    traceTarget >= lo and traceTarget <= hi
f_traceDate(int stamp) =>
    na(stamp) ? "unknown" : str.format_time(stamp, "yyyy-MM-dd HH:mm", "UTC")
f_trace(string registry, int id, string action, float p, int origin, int finish, string tf, float lo, float hi, string reason, bool keepWatching) =>
    string key = f_traceKey(registry, id)
    bool nearPivot = f_traceNear(p)
    bool geometry = f_traceGeometry(lo, hi)
    bool watched = array.includes(traceWatch, key)
    if traceEnabled and barstate.isconfirmed and (nearPivot or geometry or watched)
        if keepWatching and not watched
            array.push(traceWatch, key)
        string focus = nearPivot ? "near pivot" : geometry ? "target in frozen band" : "followed ID"
        string detail = focus + " | pivot " + str.tostring(p, format.mintick) + " " + tf + " | origin " + f_traceDate(origin) + " to " + f_traceDate(finish) + " | band " + str.tostring(lo, format.mintick) + " - " + str.tostring(hi, format.mintick) + " | " + reason
        array.push(traceRecords, ZoneTraceRecord.new(time_close, key, action, detail))
        if array.size(traceRecords) > traceLimit
            array.shift(traceRecords)
            array.set(traceDropped, 0, array.get(traceDropped, 0) + 1)
    0
f_traceForget(string registry, int id) =>
    int index = array.indexof(traceWatch, f_traceKey(registry, id))
    if index >= 0
        array.remove(traceWatch, index)
    0
f_traceBirth(SwingBirthOrigin birth) =>
    na(birth) ? "birth unavailable" : "frozen birth " + str.tostring(birth.price, format.mintick) + " " + birth.sourceTF + " " + f_traceDate(birth.start) + " to " + f_traceDate(birth.finish) + "; delivered " + f_traceDate(birth.firstConfirm)
 
// Existing boundaries never change. Nearby new pivots add evidence only.
f_ingest(float p, float a, int source, int id, int origin, int finish) =>
    int added = 0
    int removed = 0
    int rejected = 0
    if not na(p) and not na(a) and a > 0
        float w = math.max(syminfo.mintick, a * widthATR)
        int match = -1
        float nearest = 1e30
        if array.size(zones) > 0
            for i = 0 to array.size(zones) - 1
                Zone z = array.get(zones, i)
                float distance = math.abs(p - (z.lo + z.hi) * 0.5)
                bool overlap = p + w >= z.lo and p - w <= z.hi
                if overlap and distance <= math.max(a, z.scale) * mergeATR and distance < nearest
                    nearest := distance
                    match := i
        if match >= 0
            Zone z = array.get(zones, match)
            string traceTF = f_tfName(source == 0 ? tf1 : source == 1 ? tf2 : tf3, source == 0 ? sec1 : source == 1 ? sec2 : sec3)
            f_trace("Z", z.id, "MERGE", p, origin, finish, traceTF, z.lo, z.hi, "incoming #" + str.tostring(id) + "; frozen geometry unchanged; " + f_traceBirth(map.contains(zoneBirthOrigins, z.id) ? map.get(zoneBirthOrigins, z.id) : na), true)
            z.observations += 1
            z.lastEvidence := bar_index
            int bit = int(math.pow(2, source))
            if not f_has(z.mask, source)
                z.mask += bit
        else
            string gov = source == 0 ? tf1 : source == 1 ? tf2 : tf3
            float seconds = source == 0 ? sec1 : source == 1 ? sec2 : sec3
            Zone candidate = Zone.new(id, p - w, p + w, a, time_close, bar_index, bar_index, 1, int(math.pow(2, source)), close >= p ? 1 : -1, source, gov, seconds)
            candidate.rejectionBars := array.new_int()
            int traceReplacement = 0
            float traceWeakScore = na
            bool admit = array.size(zones) < capacity
            if not admit
                int weakest = -1
                float weakScore = 1e30
                for i = 0 to array.size(zones) - 1
                    Zone old = array.get(zones, i)
                    // Pending local/structural setups are protected; all-pending means reject.
                    if old.pending == 0
                        float value = f_retention(old)
                        if value < weakScore
                            weakScore := value
                            weakest := i
                traceWeakScore := weakest >= 0 ? weakScore : na
                if weakest >= 0 and f_retention(candidate) > weakScore
                    Zone originEvicted = array.get(zones, weakest)
                    traceReplacement := originEvicted.id
                    SwingBirthOrigin traceBirth = map.contains(zoneBirthOrigins, originEvicted.id) ? map.get(zoneBirthOrigins, originEvicted.id) : na
                    f_trace("Z", originEvicted.id, "RETIRE", na, na, na, "", originEvicted.lo, originEvicted.hi, "capacity replacement by Z#" + str.tostring(id) + "; old retention " + str.tostring(weakScore, "#.000") + "; incoming " + str.tostring(f_retention(candidate), "#.000") + "; " + f_traceBirth(traceBirth), false)
                    f_traceForget("Z", originEvicted.id)
                    map.remove(zoneBirthOrigins, originEvicted.id)
                    array.remove(zones, weakest)
                    admit := true
                    removed := 1
            if admit
                array.push(zones, candidate)
                map.put(zoneBirthOrigins, id, SwingBirthOrigin.new(id, origin, finish, p, time_close, f_tfName(gov, seconds)))
                f_trace("Z", id, "CREATE", p, origin, finish, f_tfName(gov, seconds), candidate.lo, candidate.hi, "retention " + str.tostring(f_retention(candidate), "#.000") + (traceReplacement > 0 ? "; replaced Z#" + str.tostring(traceReplacement) : "; free capacity"), true)
                added := 1
            else
                f_trace("Z", id, "REJECT", p, origin, finish, f_tfName(gov, seconds), candidate.lo, candidate.hi, "capacity admission failed; incoming retention " + str.tostring(f_retention(candidate), "#.000") + (na(traceWeakScore) ? "; all retained zones protected/pending" : "; weakest eligible retention " + str.tostring(traceWeakScore, "#.000") + "; incoming must be strictly stronger"), false)
                rejected := 1
    [added, removed, rejected]
 
// Presentation-only captions: internal map headings/status still drive the existing model.
f_captionHeading(string heading) =>
    string captionText = str.replace_all(heading, "STRUCTURAL RANGE", "RANGE")
    captionText := str.replace_all(captionText, "ROLE-REVERSAL", "RETESTED")
    captionText := str.replace_all(captionText, "KEY INTERNAL", "KEY")
    captionText := str.replace_all(captionText, "KEY CONFIRMED", "KEY")
    captionText := str.replace_all(captionText, "OUTER HTF", "BROADER")
    captionText := str.replace_all(captionText, "INTERNAL ", "")
    str.replace_all(captionText, "CONFIRMED ", "")
 
f_captionStatus(string status) =>
    string captionText = str.replace_all(status, "Structural down | retest pending", "Break below | Awaiting retest")
    captionText := str.replace_all(captionText, "Structural up | retest pending", "Break above | Awaiting retest")
    captionText := str.replace_all(captionText, "Local down | await ", "Possible break below | Wait ")
    captionText := str.replace_all(captionText, "Local up | await ", "Possible break above | Wait ")
    captionText := str.replace_all(captionText, " close", "")
    captionText := str.replace_all(captionText, "Confirmed flip retest", "Retest passed")
    captionText := str.replace_all(captionText, "Break held | no retest", "Break holds")
    captionText := str.replace_all(captionText, "Tracked ", "Last role: ")
    captionText := str.replace_all(captionText, "High cluster: ", "Nearby highs: ")
    captionText := str.replace_all(captionText, "Low cluster: ", "Nearby lows: ")
    captionText := str.replace_all(captionText, " swings", "")
    str.replace_all(captionText, "Prominent confirmed swing", "Large confirmed turn")
 
f_eventCaption(string message) =>
    message == "local breach" ? "Possible break" : message == "structural break" ? "Break confirmed" : message == "failed breach/break" ? "Break/test failed" : message == "local breach timeout" ? "Break wait ended" : message == "retest timeout" ? "Retest wait ended" : message == "support retest" ? "Support tested" : message == "resistance retest" ? "Resistance tested" : message == "defended rejection" ? "Bounce/rejection" : message
 
// BEGIN V26 ZONE ALERT JOURNAL
f_noticeRecord(string key, string event, float lo, float hi, int role, string sourceTF) =>
    ZoneNotice notice = ZoneNotice.new(key, event, lo, hi, role, sourceTF, time_close)
    array.push(noticeQueue, notice)
    array.push(noticeHistory, notice)
    if array.size(noticeHistory) > 20
        array.shift(noticeHistory)
    array.set(noticeCounters, 0, array.get(noticeCounters, 0) + 1)
f_noticeLegacy(Zone z, string message) =>
    string event = message == "structural break" ? (z.pending == 1 ? "Break above confirmed" : "Break below confirmed") : message == "support retest" ? "Support retest passed" : message == "resistance retest" ? "Resistance retest passed" : message == "failed breach/break" ? "Break/test failed" : ""
    if event != ""
        f_noticeRecord("Z:" + str.tostring(z.id), event, z.lo, z.hi, z.role, f_tfName(z.govTF, z.govSeconds))
// END V26 ZONE ALERT JOURNAL
 
f_event(Zone z, string message, color c) =>
    f_noticeLegacy(z, message) // V26 journal independent of historical-label switch
    if showEvents
        string help = message == "local breach" ? "A chart candle closed beyond the zone and its break buffer. This records a possible break. Confirmation also needs the zone's own timeframe to close beyond it; that may happen on the same chart candle." : message == "structural break" ? "A candle on this zone's confirmation timeframe closed beyond it, confirming a break. A later return to the zone can now count as a retest." : message == "failed breach/break" ? "Price closed back through the zone in the wrong direction, so the pending break or return test failed." : message == "local breach timeout" ? "The possible break was not confirmed by a close on the zone's own timeframe before time ran out." : message == "retest timeout" ? "The confirmed break did not get a successful return test before its waiting period ended." : message == "support retest" ? "After a confirmed upward break, price returned to the zone and closed back above it: a successful support test." : message == "resistance retest" ? "After a confirmed downward break, price returned to the zone and closed back below it: a successful resistance test." : "Price touched the zone, then moved far enough away before time ran out to count as a bounce or rejection."
        label mark = label.new(time_close, (z.lo + z.hi) * 0.5, "#" + str.tostring(z.id) + " " + f_eventCaption(message), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(c, 15), textcolor = color.white, size = size.small, tooltip = help + " This event uses closed candles. The zone number is a troubleshooting reference, not a strength score.")
        array.push(eventLabels, mark)
        if array.size(eventLabels) > eventLimit
            label.delete(array.shift(eventLabels))
 
// Separate causal swing model: source-origin evidence is not a post-confirmation defense.
f_swingTF(SwingCluster z) =>
    math.max(f_has(z.mask, 0) ? sec1 : 0.0, math.max(f_has(z.mask, 1) ? sec2 : 0.0, f_has(z.mask, 2) ? sec3 : 0.0))
f_swingEvidence(SwingCluster z) =>
    string sources = f_has(z.mask, 0) ? f_tfName(tf1, sec1) : ""
    if f_has(z.mask, 1)
        sources += (str.length(sources) > 0 ? "+" : "") + f_tfName(tf2, sec2)
    if f_has(z.mask, 2)
        sources += (str.length(sources) > 0 ? "+" : "") + f_tfName(tf3, sec3)
    sources
f_swingScore(SwingCluster z) =>
    float age = math.max(0.0, (snapshotTime - z.lastOriginEnd) / 86400000.0)
    float base = 2.0 * math.min(z.bestProm, 4.0) + 1.5 * math.min(z.tests - 1, 3) + 2.0 * math.sqrt(math.min(f_swingTF(z) / 86400.0, 7.0))
    base * math.pow(0.5, age / float(structureHalfLife)) + 2.0 / (1.0 + age / 30.0)
f_swingQualified(SwingCluster z) =>
    bool recent = snapshotTime - z.lastOriginEnd <= structureDays * 86400000.0
    recent and (z.dailyProm >= prominenceATR or (z.strongTests >= 2 and f_swingTF(z) >= 43200))
f_swingIngest(float p, float a, float prominence, int kind, int origin, int finish, int source, int id) =>
    int removed = 0
    float seconds = source == 0 ? sec1 : source == 1 ? sec2 : sec3
    if not na(p) and not na(a) and a > 0 and not na(prominence) and seconds >= 43200
        float width = math.max(syminfo.mintick, a * widthATR)
        int match = -1
        float nearest = 1e30
        if array.size(swings) > 0
            for i = 0 to array.size(swings) - 1
                SwingCluster old = array.get(swings, i)
                float distance = math.abs(p - (old.lo + old.hi) * 0.5)
                if old.kind == kind and p + width >= old.lo and p - width <= old.hi and distance <= math.max(a, old.scale) * 0.30 and distance < nearest
                    match := i
                    nearest := distance
        bool sameMove = false
        if array.size(originEvents) > 0
            for event in originEvents
                if event.kind == kind and origin < event.finish and finish > event.start
                    sameMove := true
        if match >= 0
            SwingCluster old = array.get(swings, match)
            string traceTF = f_tfName(source == 0 ? tf1 : source == 1 ? tf2 : tf3, seconds)
            f_trace("S", old.id, "MERGE", p, origin, finish, traceTF, old.lo, old.hi, "incoming S#" + str.tostring(id) + "; frozen geometry unchanged; " + f_traceBirth(map.contains(swingBirthOrigins, old.id) ? map.get(swingBirthOrigins, old.id) : na), true)
            old.bestProm := math.max(old.bestProm, prominence)
            old.dailyProm := seconds >= 86400 ? math.max(old.dailyProm, prominence) : old.dailyProm
            if not f_has(old.mask, source)
                old.mask += int(math.pow(2, source))
            bool oppositeBetween = false
            if array.size(originEvents) > 0
                for event in originEvents
                    if event.kind == -kind and event.start >= old.lastOriginEnd and event.finish <= origin
                        oppositeBetween := true
            // Stale/out-of-order HTF observations can upgrade evidence, never refresh recency/tests.
            if origin >= old.lastOriginEnd and origin > old.lastOriginStart and not sameMove and oppositeBetween
                old.tests += 1
                old.strongTests += prominence >= 0.75 ? 1 : 0
                old.lastOriginStart := origin
                old.lastOriginEnd := finish
                old.independentAvailable := time_close
        else
            if array.size(swings) >= 80
                int weakest = -1
                float weakScore = 1e30
                for i = 0 to array.size(swings) - 1
                    SwingCluster old = array.get(swings, i)
                    if old.id != parentLowId and old.id != parentHighId
                        float score = f_swingScore(old) - (snapshotTime - old.lastOriginEnd) / 86400000.0 * 0.05
                        if score < weakScore
                            weakScore := score
                            weakest := i
                if weakest >= 0
                    SwingCluster originEvicted = array.get(swings, weakest)
                    f_trace("S", originEvicted.id, "RETIRE", na, na, na, "", originEvicted.lo, originEvicted.hi, "registry capacity replacement by S#" + str.tostring(id) + "; weakest age-adjusted score " + str.tostring(weakScore, "#.000") + "; " + f_traceBirth(map.contains(swingBirthOrigins, originEvicted.id) ? map.get(swingBirthOrigins, originEvicted.id) : na), false)
                    f_traceForget("S", originEvicted.id)
                    map.remove(swingBirthOrigins, originEvicted.id)
                    array.remove(swings, weakest)
                    removed := 1
            if array.size(swings) < 80
                array.push(swings, SwingCluster.new(id, kind, p - width, p + width, a, time_close, origin, finish, time_close, int(math.pow(2, source)), prominence, seconds >= 86400 ? prominence : 0.0, 1, prominence >= 0.75 ? 1 : 0))
                string originTF = source == 0 ? tf1 : source == 1 ? tf2 : tf3
                map.put(swingBirthOrigins, id, SwingBirthOrigin.new(id, origin, finish, p, time_close, f_tfName(originTF, seconds)))
                f_trace("S", id, "CREATE", p, origin, finish, f_tfName(originTF, seconds), p - width, p + width, "registry; prominence " + str.tostring(prominence, "#.000") + " origin ATR", true)
            else
                f_trace("S", id, "REJECT", p, origin, finish, f_tfName(source == 0 ? tf1 : source == 1 ? tf2 : tf3, seconds), p - width, p + width, "registry full; protected parents prevent replacement", false)
        array.push(originEvents, OriginEvent.new(kind, origin, finish))
        if array.size(originEvents) > 256
            array.shift(originEvents)
    else if traceEnabled and not na(p) and f_traceNear(p)
        f_trace("S", id, "REJECT", p, origin, finish, f_tfName(source == 0 ? tf1 : source == 1 ? tf2 : tf3, seconds), p, p, "registry eligibility failed: missing/nonpositive origin ATR, missing prominence, or source below 12H", false)
    removed
f_governingSlot() =>
    float desired = timeframe.in_seconds(structureTF)
    array<float> seconds = array.from(valid1 ? sec1 : na, valid2 ? sec2 : na, valid3 ? sec3 : na)
    int chosen = 0
    float nearest = 1e30
    float fallback = -1.0
    int fallbackSlot = 0
    for s = 0 to 2
        float value = array.get(seconds, s)
        if not na(value)
            if value >= desired and value < nearest
                nearest := value
                chosen := s
            if value > fallback
                fallback := value
                fallbackSlot := s
    nearest == 1e30 ? fallbackSlot : chosen
// Causal hierarchy metadata is read-only to the legacy break/retest engine.
f_rememberBoundary(SwingCluster z) =>
    int match = -1
    if array.size(formerBoundaries) > 0
        for i = 0 to array.size(formerBoundaries) - 1
            if array.get(formerBoundaries, i).swingId == z.id
                match := i
    FormerBoundary profile = FormerBoundary.new(z.id, z.lo, z.hi, z.scale, z.kind, z.mask, time_close)
    if match >= 0
        array.set(formerBoundaries, match, profile)
    else
        array.push(formerBoundaries, profile)
        if array.size(formerBoundaries) > 40
            array.shift(formerBoundaries)
    0
f_keyFacts(Zone z) =>
    bool former = false
    bool weeklySwing = false
    float swingStrength = 0.0
    if array.size(formerBoundaries) > 0
        for profile in formerBoundaries
            float distance = math.abs((z.lo + z.hi - profile.lo - profile.hi) * 0.5)
            bool nearby = z.lo <= profile.hi and z.hi >= profile.lo and distance <= math.max(z.scale, profile.scale) * 0.50
            if nearby and snapshotTime - profile.availableTime <= structureDays * 86400000.0
                former := true
    if array.size(swings) > 0
        for swing in swings
            float distance = math.abs((z.lo + z.hi - swing.lo - swing.hi) * 0.5)
            bool nearby = z.lo <= swing.hi and z.hi >= swing.lo and distance <= math.max(z.scale, swing.scale) * 0.50
            if nearby and f_swingQualified(swing)
                swingStrength := math.max(swingStrength, f_swingScore(swing))
                weeklySwing := weeklySwing or f_swingTF(swing) >= 604800
    bool important = former or swingStrength > 0 or f_major(z)
    int significance = former ? 3 : weeklySwing ? 2 : important ? 1 : 0
    [significance, swingStrength]
// BEGIN V22 FRESHNESS HELPERS
f_freshZoneKey(int id) =>
    "Z:" + str.tostring(id)
f_freshSwingKey(int id) =>
    "S:" + str.tostring(id)
f_freshParentKey(int kind) =>
    "P:" + str.tostring(parentBorn) + ":" + str.tostring(parentLowId) + ":" + str.tostring(parentHighId) + ":" + str.tostring(kind)
f_freshCount(string key) =>
    map.contains(freshness, key) ? map.get(freshness, key).visits : 0
f_freshVisible(string key) =>
    int count = f_freshCount(key)
    count == 0 ? showFreshZones : count == 1 ? showOnceTested : showRepeated
f_freshCaption(string key) =>
    int count = f_freshCount(key)
    count == 0 ? "Fresh" : count == 1 ? "Tested once" : "Tested " + str.tostring(count) + "×"
f_freshBadge(string key) =>
    showFreshnessLabels ? " | " + f_freshCaption(key) : ""
f_freshTooltip(string key, int born, bool mainRange) =>
    int count = f_freshCount(key)
    "\nFreshness: " + f_freshCaption(key) + " — " + str.tostring(count) + " separate return" + (count == 1 ? "" : "s") + " since " + (mainRange ? "this main range was confirmed" : "this zone first became available") + " on " + str.format_time(born, "yyyy-MM-dd HH:mm", "UTC") + " UTC. Visits count even without a bounce; not a safety rating."
f_freshUpdate(string key, int born, float lo, float hi) =>
    if not map.contains(freshness, key)
        map.put(freshness, key, FreshVisit.new(born))
    FreshVisit visit = map.get(freshness, key)
    // Caller is closed-candle only. Guard duplicate delivery and ignore availability candle.
    if time_close > visit.born and (na(visit.lastBar) or visit.lastBar != bar_index)
        bool intersects = high >= lo and low <= hi
        int outsideSide = low > hi ? 1 : high < lo ? -1 : 0
        if intersects
            if visit.armed
                visit.visits += 1
            visit.armed := false
            visit.outsideBars := 0
            visit.outsideSide := 0
        else
            visit.outsideBars := outsideSide == visit.outsideSide ? visit.outsideBars + 1 : 1
            visit.outsideSide := outsideSide
            visit.armed := visit.outsideBars >= freshnessSeparationBars
        visit.lastBar := bar_index
    map.put(freshness, key, visit)
// END V22 FRESHNESS HELPERS
 
// BEGIN V23 NEARBY HELPERS
f_nearVisible(float lo, float hi, bool main = false) =>
    // Snapshot changes only on confirmed chart candles. Nearest-edge gap includes overlap.
    float gap = math.max(math.max(lo - snapshotClose, snapshotClose - hi), 0.0)
    not effectiveNearbyEnabled or (main and effectiveKeepMainBoundaries) or (not na(snapshotClose) and not na(snapshotATR) and gap <= effectiveNearbyATR * snapshotATR)
// END V23 NEARBY HELPERS
 
// BEGIN V26 ZONE ALERT WATCH HELPERS
f_noticeStep(ZoneWatch watch) =>
    if time_close > watch.born and (na(watch.lastBar) or watch.lastBar != bar_index)
        bool touches = high >= watch.lo and low <= watch.hi
        int outside = low > watch.hi ? 1 : high < watch.lo ? -1 : 0
        float gap = math.max(math.max(watch.lo - snapshotClose, snapshotClose - watch.hi), 0.0)
        // Seed is handled by f_noticeTrack. A full price gap is not an OHLC touch.
        if touches
            if watch.touchArmed
                f_noticeRecord(watch.key, "New separate visit", watch.lo, watch.hi, watch.role, watch.sourceTF)
            watch.touchArmed := false
            watch.approachArmed := false
            watch.away := 0
            watch.side := 0
        else
            watch.away := outside == watch.side ? watch.away + 1 : 1
            watch.side := outside
            if watch.away >= alertRearmBars
                watch.touchArmed := true
                if gap > alertApproachATR * snapshotATR
                    watch.approachArmed := true
            if watch.approachArmed and gap <= alertApproachATR * snapshotATR
                f_noticeRecord(watch.key, "Approaching", watch.lo, watch.hi, watch.role, watch.sourceTF)
                watch.approachArmed := false
        watch.lastBar := bar_index
    watch
f_noticeTrack(string key, float lo, float hi, int born, int role, string sourceTF) =>
    bool first = not map.contains(zoneWatches, key)
    ZoneWatch watch = first ? ZoneWatch.new(key, lo, hi, born, role, sourceTF) : map.get(zoneWatches, key)
    if first
        // First observation is a silent baseline, including zones born in proximity.
        watch.lastBar := bar_index
    else
        watch := f_noticeStep(watch)
    watch.lastSeen := bar_index
    watch.previousClose := snapshotClose
    map.put(zoneWatches, key, watch)
    watch
f_noticePriorityAllowed(int p) =>
    p == 1 ? alertP1 : p == 2 ? alertP2 : p == 3 ? alertP3 : alertP4
f_noticeFreshAllowed(int count) =>
    count == 0 ? alertFresh : count == 1 ? alertOnce : alertRepeated
f_noticeEventAllowed(string event) =>
    event == "Approaching" ? alertApproach : event == "New separate visit" ? alertVisit : str.contains(event, "confirmed") ? alertBreak : str.contains(event, "passed") ? alertRetest : alertFail
f_noticeType(string key) =>
    str.startswith(key, "Z:") ? "regular zone" : str.startswith(key, "S:") ? "extra swing level" : "main-range boundary"
f_noticeMessage(ZoneNotice event, ZoneWatch watched) =>
    string role = event.role == 1 ? "support" : event.role == -1 ? "resistance" : "inside/transition"
    syminfo.tickerid + " | chart " + f_tfName(timeframe.period, chartSeconds) + " | " + event.key + " " + f_noticeType(event.key) + " | P" + str.tostring(watched.priority) + " | " + str.tostring(event.lo, format.mintick) + "-" + str.tostring(event.hi, format.mintick) + " | " + role + " | source " + event.sourceTF + " | freshness before candle: " + (watched.visits == 0 ? "Fresh" : watched.visits == 1 ? "Tested once" : "Tested " + str.tostring(watched.visits) + " times") + " | " + event.event + " | confirmed " + str.format_time(event.stamp, "yyyy-MM-dd HH:mm", "UTC") + " UTC"
// END V26 ZONE ALERT WATCH HELPERS
 
f_priorityEnabled(int priority) =>
    priority == 1 ? showP1 : priority == 2 ? showP2 : priority == 3 ? showP3 : showP4
f_zonePriority(Zone z) =>
    [significance, swingStrength] = f_keyFacts(z)
    significance >= 2 ? 2 : significance == 1 ? 3 : 4
f_zoneVisible(Zone z) =>
    f_priorityEnabled(f_zonePriority(z)) and f_freshVisible(f_freshZoneKey(z.id)) and f_nearVisible(z.lo, z.hi)
f_registryPriority(SwingCluster z) =>
    f_swingTF(z) >= 604800 ? 2 : 3
f_registryVisible(SwingCluster z) =>
    f_priorityEnabled(f_registryPriority(z)) and f_freshVisible(f_freshSwingKey(z.id)) and f_nearVisible(z.lo, z.hi)
// Read-only explanation of the existing classification. Never feeds model or selection.
f_tooltipTF(string tf, float seconds) =>
    str.endswith(tf, "M") ? (tf == "M" ? "1" : str.replace_all(tf, "M", "")) + "-month" : seconds >= 604800 and seconds % 604800 == 0 ? str.tostring(seconds / 604800, "#") + "-week" : seconds >= 86400 and seconds % 86400 == 0 ? str.tostring(seconds / 86400, "#") + "-day" : seconds >= 3600 and seconds % 3600 == 0 ? str.tostring(seconds / 3600, "#") + "-hour" : seconds >= 60 and seconds % 60 == 0 ? str.tostring(seconds / 60, "#") + "-minute" : str.tostring(seconds, "#") + "-second"
 
f_swingPriorityEvidence(SwingCluster z) =>
    bool prominent = z.dailyProm >= prominenceATR
    string basis = prominent ? "A daily-or-longer turn is large enough on its own: " + str.tostring(z.dailyProm, "#.00") + " times typical candle movement (ATR); the minimum is " + str.tostring(prominenceATR, "#.00") + "." : str.tostring(z.strongTests) + " separate large turns occurred near this price (at least 2 needed, using 12-hour candles or longer)."
    basis + " Timeframes: " + f_swingEvidence(z) + "; " + str.tostring(z.tests) + " turning points in this area. For a new selection, the latest turn in this group must be within the last " + str.tostring(structureDays) + " calendar days to qualify."
f_zonePriorityExplanation(Zone z, int priority) =>
    string reason = "A confirmed level that has not met the P2 or P3 strength rules: it is not near a recent main-range boundary and has neither large/repeated nearby turns nor enough recent bounces or rejections."
    int formerIndex = -1
    int newestBoundary = 0
    if array.size(formerBoundaries) > 0
        for i = 0 to array.size(formerBoundaries) - 1
            FormerBoundary profile = array.get(formerBoundaries, i)
            float distance = math.abs((z.lo + z.hi - profile.lo - profile.hi) * 0.5)
            bool nearby = z.lo <= profile.hi and z.hi >= profile.lo and distance <= math.max(z.scale, profile.scale) * 0.50
            if nearby and snapshotTime - profile.availableTime <= structureDays * 86400000.0 and (formerIndex < 0 or profile.availableTime > newestBoundary)
                formerIndex := i
                newestBoundary := profile.availableTime
    int swingIndex = -1
    float bestScore = -1.0
    if array.size(swings) > 0
        for i = 0 to array.size(swings) - 1
            SwingCluster swing = array.get(swings, i)
            float distance = math.abs((z.lo + z.hi - swing.lo - swing.hi) * 0.5)
            bool nearby = z.lo <= swing.hi and z.hi >= swing.lo and distance <= math.max(z.scale, swing.scale) * 0.50
            bool relevant = priority != 2 or f_swingTF(swing) >= 604800
            if nearby and relevant and f_swingQualified(swing) and f_swingScore(swing) > bestScore
                swingIndex := i
                bestScore := f_swingScore(swing)
    int recentDefenses = f_recentRejections(z)
    int requiredDefenses = f_maxTF(z) >= 604800 ? 1 : 2
    string defense = "Recent bounces or rejections: " + str.tostring(recentDefenses) + "/" + str.tostring(requiredDefenses) + " needed in the last " + str.tostring(evidenceAge) + " chart candles. These reactions qualify only with daily-or-longer turning points."
    if priority == 2 and formerIndex >= 0
        FormerBoundary profile = array.get(formerBoundaries, formerIndex)
        reason := "Matches a former main-range boundary at " + str.tostring(profile.lo, format.mintick) + " - " + str.tostring(profile.hi, format.mintick) + ", last recorded " + str.format_time(profile.availableTime, "yyyy-MM-dd HH:mm", "UTC") + " UTC, within the last " + str.tostring(structureDays) + " calendar days."
    else if priority == 2 and swingIndex >= 0
        reason := "Large or repeated nearby turns include weekly candles or longer. " + f_swingPriorityEvidence(array.get(swings, swingIndex))
    else if priority == 3
        reason := swingIndex >= 0 ? "Nearby turns are large enough or have repeated often enough to matter. " + f_swingPriorityEvidence(array.get(swings, swingIndex)) : "Price has bounced or turned away from this zone enough times to meet the strength rule."
        if f_major(z)
            reason += " " + defense
    else if priority == 4
        reason += " " + defense
    string matching = priority <= 3 and (formerIndex >= 0 or swingIndex >= 0) ? " The earlier price area overlaps this zone and is close enough to support the match. It can come from a different timeframe." : ""
    "\nWhy P" + str.tostring(priority) + ": " + reason + matching
f_roleTier(Zone z) =>
    int tier = 0
    if map.contains(roleEvidence, z.id)
        RoleEvidence evidence = map.get(roleEvidence, z.id)
        int effective = z.pending != 0 and z.structural ? z.pending : z.role
        bool recent = evidence.lastBreakTime > 0 and snapshotTime - evidence.lastBreakTime <= structureDays * 86400000.0
        if evidence.held and recent and evidence.lastBreakDir == effective
            bool important = f_major(z)
            if not important
                [significance, swingStrength] = f_keyFacts(z)
                important := significance > 0
            if important
                bool retested = evidence.lastRetestDir == evidence.lastBreakDir and evidence.lastRetestTime >= evidence.lastBreakTime
                tier := retested ? 3 : 2
    tier
f_rolePriority(Zone z, int side) =>
    float value = -1.0
    int tier = f_roleTier(z)
    if tier >= 2 and map.contains(roleEvidence, z.id)
        RoleEvidence evidence = map.get(roleEvidence, z.id)
        int desiredRole = side == -1 ? 1 : -1
        // Geometry alone cannot rescue a role invalidated by a confirmed opposing break.
        if evidence.lastBreakDir == desiredRole
            [significance, swingStrength] = f_keyFacts(z)
            float distance = math.abs(snapshotClose - (z.lo + z.hi) * 0.5) / snapshotATR
            float rankStrength = (f_score(z) + swingStrength) / (1.0 + distance * 0.10)
            value := significance * 10000.0 + tier * 1000.0 + math.min(999.0, rankStrength * 10.0)
    value
 
bool localUp = false
bool localDown = false
bool brokeUp = false
bool brokeDown = false
bool retestUp = false
bool retestDown = false
bool failed = false
bool expired = false
bool defenseConfirmed = false
 
// BEGIN V26 ZONE ALERT QUEUE RESET
if barstate.isconfirmed
    array.clear(noticeQueue)
// END V26 ZONE ALERT QUEUE RESET
 
if barstate.isconfirmed
    snapshotTime := time_close
    snapshotBar := bar_index
    snapshotClose := close
    snapshotATR := math.max(nz(chartATR, high - low), syminfo.mintick)
    array<float> hs = array.from(h1, h2, h3)
    array<float> ls = array.from(l1, l2, l3)
    array<float> ats = array.from(a1, a2, a3)
    array<int> ts = array.from(t1, t2, t3)
    array<float> cs = array.from(c1, c2, c3)
    array<int> os = array.from(o1, o2, o3)
    for s = 0 to 2
        int stamp = array.get(ts, s)
        if not na(stamp) and stamp != array.get(seenTimes, s)
            array.set(seenTimes, s, stamp)
            float ph = array.get(hs, s)
            float pl = array.get(ls, s)
            float a = array.get(ats, s)
            if not na(ph) and not na(a) and a > 0
                nextId += 1
                [admitted, evicted, rejected] = f_ingest(ph, a, s, nextId, s == 0 ? p1 : s == 1 ? p2 : p3, s == 0 ? q1 : s == 1 ? q2 : q3)
                created += admitted
                retired += evicted
                rejectedAdmissions += rejected
                array.set(sourceCounts, s, array.get(sourceCounts, s) + 1)
            if not na(pl) and not na(a) and a > 0
                nextId += 1
                [admitted, evicted, rejected] = f_ingest(pl, a, s, nextId, s == 0 ? p1 : s == 1 ? p2 : p3, s == 0 ? q1 : s == 1 ? q2 : q3)
                created += admitted
                retired += evicted
                rejectedAdmissions += rejected
                array.set(sourceCounts, s, array.get(sourceCounts, s) + 1)
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            Zone z = array.get(zones, i)
            bool intersects = low <= z.hi and high >= z.lo
            int govCloseTime = array.get(ts, z.govSlot)
            int govOpenTime = array.get(os, z.govSlot)
            float govClose = array.get(cs, z.govSlot)
            bool freshGovClose = not na(govCloseTime) and govCloseTime != z.lastGovClose
            if freshGovClose
                z.lastGovClose := govCloseTime
            if bar_index > z.bornBar
                bool wasPending = z.pending != 0
                bool localNow = false
                if z.pending == 0
                    float buffer = snapshotATR * breakATR
                    int direction = z.role == 1 and close < z.lo - buffer ? -1 : z.role == -1 and close > z.hi + buffer ? 1 : 0
                    if direction != 0
                        z.pending := direction
                        z.structural := false
                        z.breachBar := bar_index
                        z.breachTime := time_close
                        z.breakBuffer := buffer
                        localNow := true
                        localUp := direction == 1 or localUp
                        localDown := direction == -1 or localDown
                        localBreaches += 1
                        f_event(z, "local breach", color.orange)
                        // Equal-timeframe chart close is itself a confirmed governing close.
                        if z.govSeconds == chartSeconds and time >= z.bornTime
                            z.structural := true
                            z.structuralBar := bar_index
                            brokeUp := direction == 1 or brokeUp
                            brokeDown := direction == -1 or brokeDown
                            breaks += 1
                            f_event(z, "structural break", direction == 1 ? color.teal : color.red)
                else
                    // Chart reclaim failure wins over HTF confirmation, expiry and retest.
                    bool fail = z.pending == 1 ? close < z.lo - z.breakBuffer : close > z.hi + z.breakBuffer
                    if fail
                        z.pending := 0
                        z.structural := false
                        failures += 1
                        failed := true
                        f_event(z, "failed breach/break", color.orange)
                    else if not z.structural
                        if bar_index - z.breachBar > localTimeout
                            z.pending := 0
                            localExpiries += 1
                            expired := true
                            f_event(z, "local breach timeout", color.gray)
                        else
                            // >= permits a source close exactly at the breach close, delivered later.
                            bool sourceEligible = freshGovClose and govOpenTime >= z.bornTime and govCloseTime >= z.breachTime and bar_index > z.breachBar
                            bool sourceBeyond = z.pending == 1 ? govClose > z.hi + z.breakBuffer : govClose < z.lo - z.breakBuffer
                            if sourceEligible and sourceBeyond
                                z.structural := true
                                z.structuralBar := bar_index
                                brokeUp := z.pending == 1 or brokeUp
                                brokeDown := z.pending == -1 or brokeDown
                                breaks += 1
                                f_event(z, "structural break", z.pending == 1 ? color.teal : color.red)
                    else if bar_index > z.structuralBar
                        bool success = intersects and (z.pending == 1 ? close > z.hi : close < z.lo)
                        if bar_index - z.structuralBar > timeout
                            z.role := z.pending
                            z.pending := 0
                            z.structural := false
                            expiries += 1
                            expired := true
                            f_event(z, "retest timeout", color.gray)
                        else if success
                            z.role := z.pending
                            retestUp := z.pending == 1 or retestUp
                            retestDown := z.pending == -1 or retestDown
                            z.pending := 0
                            z.structural := false
                            retests += 1
                            f_event(z, z.role == 1 ? "support retest" : "resistance retest", z.role == 1 ? color.teal : color.red)
                // Directional defense is independent of break state. A failed contact cannot restart
                // on this candle; no reaction is credited from absolute movement or a touch alone.
                if z.defending
                    bool defenseFailed = z.defenseRole == 1 ? close < z.lo - z.defenseBuffer : close > z.hi + z.defenseBuffer
                    bool departed = z.defenseRole == 1 ? close >= z.hi + z.scale * defenseATR : close <= z.lo - z.scale * defenseATR
                    if defenseFailed or localNow
                        z.defending := false
                        z.failedDefenses += 1
                        z.lastDefenseBar := bar_index
                        defenseFailures += 1
                    else if bar_index - z.defenseStart > defenseWindow or wasPending
                        z.defending := false
                        z.lastDefenseBar := bar_index
                    else if departed
                        z.defending := false
                        z.rejections += 1
                        z.lastDefenseBar := bar_index
                        array.push(z.rejectionBars, bar_index)
                        if array.size(z.rejectionBars) > 8
                            array.shift(z.rejectionBars)
                        rejectionCount += 1
                        defenseConfirmed := true
                        f_event(z, "defended rejection", z.defenseRole == 1 ? color.teal : color.red)
                else if localNow and intersects and not z.touching
                    bool approached = z.role == 1 ? close[1] > z.hi : close[1] < z.lo
                    if approached
                        z.failedDefenses += 1
                        z.lastDefenseBar := bar_index
                        defenseFailures += 1
                else if not wasPending and not localNow and z.pending == 0 and intersects and not z.touching and bar_index - z.lastDefenseBar >= cooldown
                    bool approached = z.role == 1 ? close[1] > z.hi : close[1] < z.lo
                    bool oppositeClose = z.role == 1 ? close < z.lo - snapshotATR * breakATR : close > z.hi + snapshotATR * breakATR
                    if approached and not oppositeClose
                        z.defending := true
                        z.defenseRole := z.role
                        z.defenseStart := bar_index
                        z.defenseBuffer := snapshotATR * breakATR
                        // A wick-and-departure on one completed candle is valid, never backdated.
                        bool immediate = z.role == 1 ? close >= z.hi + z.scale * defenseATR : close <= z.lo - z.scale * defenseATR
                        if immediate
                            z.defending := false
                            z.rejections += 1
                            z.lastDefenseBar := bar_index
                            array.push(z.rejectionBars, bar_index)
                            if array.size(z.rejectionBars) > 8
                                array.shift(z.rejectionBars)
                            rejectionCount += 1
                            defenseConfirmed := true
                            f_event(z, "defended rejection", z.role == 1 ? color.teal : color.red)
                z.touching := intersects
    majorCount := 0
    if array.size(zones) > 0
        for z in zones
            if f_major(z)
                majorCount += 1
    // Hash persisted semantic zone fields (text TF alias represented by slot/seconds), plus counters.
    digest := (created * 31.0 + breaks * 37.0 + retests * 41.0 + failures * 43.0 + expiries * 47.0 + localBreaches * 53.0 + localExpiries * 59.0 + rejectionCount * 61.0 + defenseFailures * 67.0 + retired * 71.0 + rejectedAdmissions * 73.0 + nextId * 79.0) % 1000003.0
    for s = 0 to 2
        digest := (digest * 17.0 + array.get(seenTimes, s) % 1000003 + array.get(sourceCounts, s)) % 1000003.0
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            Zone z = array.get(zones, i)
            array<float> fields = array.from(float(z.id), math.round(z.lo / syminfo.mintick), math.round(z.hi / syminfo.mintick), math.round(z.scale / syminfo.mintick), float(z.bornTime), float(z.bornBar), float(z.lastEvidence), float(z.observations), float(z.mask), float(z.role), float(z.govSlot), z.govSeconds, float(z.pending), z.structural ? 1.0 : 0.0, float(nz(z.breachBar, -1)), float(nz(z.breachTime, -1)), float(nz(z.structuralBar, -1)), float(z.lastGovClose), math.round(z.breakBuffer / syminfo.mintick), float(z.rejections), float(z.failedDefenses), float(z.lastDefenseBar), z.touching ? 1.0 : 0.0, z.defending ? 1.0 : 0.0, float(z.defenseRole), float(nz(z.defenseStart, -1)), math.round(z.defenseBuffer / syminfo.mintick))
            for field in fields
                digest := (digest * 17.0 + field % 1000003.0) % 1000003.0
            if array.size(z.rejectionBars) > 0
                for stamp in z.rejectionBars
                    digest := (digest * 17.0 + stamp) % 1000003.0
// Independent confirmed structural registry and regime. Legacy model digest remains untouched.
if barstate.isconfirmed
    array<int> stamps = array.from(t1, t2, t3)
    bool structuralEvidenceNow = false
    array<int> origins = array.from(p1, p2, p3)
    array<int> finishes = array.from(q1, q2, q3)
    array<float> pivotATRs = array.from(pa1, pa2, pa3)
    array<float> highs = array.from(h1, h2, h3)
    array<float> lows = array.from(l1, l2, l3)
    array<float> highProms = array.from(hp1, hp2, hp3)
    array<float> lowProms = array.from(lp1, lp2, lp3)
    array<float> sourceCloses = array.from(c1, c2, c3)
    array<int> sourceOpens = array.from(o1, o2, o3)
    for s = 0 to 2
        int stamp = array.get(stamps, s)
        if not na(stamp) and stamp != array.get(structuralSeenTimes, s)
            array.set(structuralSeenTimes, s, stamp)
            if not na(array.get(highs, s))
                nextSwingId += 1
                structuralEvidenceNow := true
                swingRetired += f_swingIngest(array.get(highs, s), array.get(pivotATRs, s), array.get(highProms, s), 1, array.get(origins, s), array.get(finishes, s), s, nextSwingId)
            if not na(array.get(lows, s))
                nextSwingId += 1
                structuralEvidenceNow := true
                swingRetired += f_swingIngest(array.get(lows, s), array.get(pivotATRs, s), array.get(lowProms, s), -1, array.get(origins, s), array.get(finishes, s), s, nextSwingId)
    bool invalidatedNow = false
    if parentActive
        int stamp = array.get(stamps, parentGovSlot)
        bool fresh = not na(stamp) and stamp != parentLastClose
        if fresh
            parentLastClose := stamp
        float sourceClose = array.get(sourceCloses, parentGovSlot)
        bool eligible = fresh and array.get(sourceOpens, parentGovSlot) >= parentBorn and stamp >= parentBorn and bar_index > parentBornBar
        bool broken = eligible and (sourceClose < parentLow.lo - parentBuffer or sourceClose > parentHigh.hi + parentBuffer)
        bool aged = time_close - parentBorn >= structureDays * 86400000.0 or time_close - parentLow.lastOriginEnd > structureDays * 86400000.0 or time_close - parentHigh.lastOriginEnd > structureDays * 86400000.0
        if broken or aged
            if broken
                f_rememberBoundary(parentLow)
                f_rememberBoundary(parentHigh)
                array.push(brokenPairs, str.tostring(parentLowId) + ":" + str.tostring(parentHighId))
                if array.size(brokenPairs) > 32
                    array.shift(brokenPairs)
                parentBreaks += 1
            else
                parentExpiries += 1
            structuralResetTime := broken ? stamp : structuralResetTime
            ageReseedPending := not broken
            parentActive := false
            parentLowId := 0
            parentHighId := 0
            invalidatedNow := true
    if not parentActive and not invalidatedNow and (structuralEvidenceNow or ageReseedPending) and array.size(swings) > 1
        // Calendar expiry can re-evaluate known recent structure prospectively on the next close.
        // A price break still requires newly confirmed post-break origin evidence.
        ageReseedPending := false
        int bestLow = -1
        int bestHigh = -1
        float bestScore = -1e30
        for i = 0 to array.size(swings) - 1
            SwingCluster lo = array.get(swings, i)
            if lo.kind == -1 and f_swingQualified(lo) and lo.lo <= snapshotClose
                for j = 0 to array.size(swings) - 1
                    SwingCluster hi = array.get(swings, j)
                    float scale = math.max(lo.scale, hi.scale)
                    float span = (hi.lo + hi.hi - lo.lo - lo.hi) * 0.5
                    bool separatedOrigins = lo.lastOriginEnd <= hi.lastOriginStart or hi.lastOriginEnd <= lo.lastOriginStart
                    bool newEvidence = (lo.lastOriginEnd >= structuralResetTime and lo.independentAvailable > structuralResetTime) or (hi.lastOriginEnd >= structuralResetTime and hi.independentAvailable > structuralResetTime)
                    string pair = str.tostring(lo.id) + ":" + str.tostring(hi.id)
                    if hi.kind == 1 and f_swingQualified(hi) and hi.hi >= snapshotClose and span >= scale * rangeSpanATR and separatedOrigins and newEvidence and not array.includes(brokenPairs, pair)
                        float gapDays = math.abs(hi.lastOriginStart - lo.lastOriginStart) / 86400000.0
                        float score = f_swingScore(lo) + f_swingScore(hi) + 0.5 * math.log(1.0 + span / scale) - 0.02 * gapDays
                        if score > bestScore
                            bestScore := score
                            bestLow := i
                            bestHigh := j
        if bestLow >= 0
            parentLow := array.get(swings, bestLow)
            parentHigh := array.get(swings, bestHigh)
            parentLowId := parentLow.id
            parentHighId := parentHigh.id
            parentGovSlot := f_governingSlot()
            parentGovTF := parentGovSlot == 0 ? tf1 : parentGovSlot == 1 ? tf2 : tf3
            parentBorn := time_close
            parentBornBar := bar_index
            parentLastClose := nz(array.get(stamps, parentGovSlot), 0)
            parentBuffer := math.max(parentLow.scale, parentHigh.scale) * structureBufferATR
            parentActive := true
            parentFormations += 1
    structureDigest := (nextSwingId * 31.0 + swingRetired * 37.0 + parentBreaks * 41.0 + parentExpiries * 43.0 + parentFormations * 47.0 + structuralResetTime % 1000003 + parentLowId * 53.0 + parentHighId * 59.0 + nz(parentBorn, 0) % 1000003 + parentGovSlot * 61.0 + parentLastClose % 1000003 + math.round(parentBuffer / syminfo.mintick) + (ageReseedPending ? 67.0 : 0.0) + nz(parentBornBar, 0) * 71.0 + (parentActive ? 73.0 : 0.0) + structureHalfLife * 79.0) % 1000003.0
    for stamp in structuralSeenTimes
        structureDigest := (structureDigest * 17.0 + stamp % 1000003) % 1000003.0
    if array.size(swings) > 0
        for z in swings
            array<float> fields = array.from(float(z.id), float(z.kind), math.round(z.lo / syminfo.mintick), math.round(z.hi / syminfo.mintick), math.round(z.scale / syminfo.mintick), float(z.bornTime), float(z.lastOriginStart), float(z.lastOriginEnd), float(z.independentAvailable), float(z.mask), math.round(z.bestProm * 10000), math.round(z.dailyProm * 10000), float(z.tests), float(z.strongTests))
            for field in fields
                structureDigest := (structureDigest * 17.0 + field % 1000003.0) % 1000003.0
    for event in originEvents
        structureDigest := (structureDigest * 17.0 + event.kind + event.start % 1000003 + event.finish % 1000003) % 1000003.0
    for pair in brokenPairs
        array<string> ids = str.split(pair, ":")
        structureDigest := (structureDigest * 17.0 + str.tonumber(array.get(ids, 0)) * 13.0 + str.tonumber(array.get(ids, 1))) % 1000003.0
// Observe completed legacy transitions without changing a decision, counter, alert or old digest.
if barstate.isconfirmed
    map<int, RoleEvidence> currentEvidence = map.new<int, RoleEvidence>()
    if array.size(zones) > 0
        for z in zones
            RoleEvidence evidence = map.contains(roleEvidence, z.id) ? map.get(roleEvidence, z.id) : RoleEvidence.new(z.id)
            if z.structural and z.structuralBar == snapshotBar
                evidence.lastBreakDir := z.pending
                evidence.lastBreakTime := snapshotTime
                evidence.held := true
            else if evidence.prevStructural and z.pending == 0
                bool intersects = low <= z.hi and high >= z.lo
                bool brokenSideClose = evidence.prevPending == 1 ? close > z.hi : close < z.lo
                bool completedRetest = z.role == evidence.prevPending and snapshotBar - evidence.prevStructuralBar <= timeout and intersects and brokenSideClose
                if completedRetest
                    evidence.lastRetestDir := evidence.prevPending
                    evidence.lastRetestTime := snapshotTime
                else if z.role != evidence.prevPending
                    // A failed structural break cancels it; a failed local counterbreach does not.
                    evidence.held := false
            evidence.prevPending := z.pending
            evidence.prevStructural := z.structural
            evidence.prevStructuralBar := z.structuralBar
            map.put(currentEvidence, z.id, evidence)
    roleEvidence := currentEvidence
    hierarchyDigest := 0.0
    if array.size(zones) > 0
        for z in zones
            RoleEvidence evidence = map.get(roleEvidence, z.id)
            hierarchyDigest := (hierarchyDigest * 17.0 + z.id * 31.0 + evidence.lastBreakDir * 37.0 + evidence.lastBreakTime % 1000003 + (evidence.held ? 41.0 : 0.0) + evidence.lastRetestDir * 43.0 + evidence.lastRetestTime % 1000003 + evidence.prevPending * 47.0 + (evidence.prevStructural ? 53.0 : 0.0) + nz(evidence.prevStructuralBar, -1)) % 1000003.0
    if array.size(formerBoundaries) > 0
        for profile in formerBoundaries
            hierarchyDigest := (hierarchyDigest * 17.0 + profile.swingId * 59.0 + math.round(profile.lo / syminfo.mintick) % 1000003 + math.round(profile.hi / syminfo.mintick) % 1000003 + math.round(profile.scale / syminfo.mintick) % 1000003 + profile.kind * 61.0 + profile.mask * 67.0 + profile.availableTime % 1000003) % 1000003.0
    // Count is a current confirmed-snapshot diagnostic, not a historical signal. Avoid scanning
    // every registry match on every history bar; persisted metadata digest remains independent.
    if barstate.islastconfirmedhistory or barstate.isrealtime
        keyRoleCount := 0
        if array.size(zones) > 0
            for z in zones
                if f_roleTier(z) >= 2
                    keyRoleCount += 1
 
// Presentation-only copies retain the exact birth pivot of each frozen band, never a later test.
if barstate.isconfirmed
    if not parentActive
        parentOrigins := na
    else if na(parentOrigins) or parentOrigins.rangeBorn != parentBorn or parentOrigins.lowId != parentLowId or parentOrigins.highId != parentHighId
        if map.contains(swingBirthOrigins, parentLowId) and map.contains(swingBirthOrigins, parentHighId)
            SwingBirthOrigin lowBirth = map.get(swingBirthOrigins, parentLowId)
            SwingBirthOrigin highBirth = map.get(swingBirthOrigins, parentHighId)
            parentOrigins := ParentOriginView.new(parentBorn, parentLowId, parentHighId, lowBirth.copy(), highBirth.copy())
 
// BEGIN V22 FRESHNESS CLOSED-CANDLE PASS
// Track every retained identity, including hidden candidates; prune retired identities.
// No model score, break/retest state, alert or diagnostic digest reads this sidecar.
if barstate.isconfirmed
    map<string, bool> activeFreshKeys = map.new<string, bool>()
    for z in zones
        string key = f_freshZoneKey(z.id)
        map.put(activeFreshKeys, key, true)
        f_freshUpdate(key, z.bornTime, z.lo, z.hi)
    for z in swings
        string key = f_freshSwingKey(z.id)
        map.put(activeFreshKeys, key, true)
        f_freshUpdate(key, z.bornTime, z.lo, z.hi)
    if parentActive
        string lowKey = f_freshParentKey(-1)
        string highKey = f_freshParentKey(1)
        map.put(activeFreshKeys, lowKey, true)
        map.put(activeFreshKeys, highKey, true)
        f_freshUpdate(lowKey, parentBorn, parentLow.lo, parentLow.hi)
        f_freshUpdate(highKey, parentBorn, parentHigh.lo, parentHigh.hi)
    array<string> oldFreshKeys = map.keys(freshness)
    for key in oldFreshKeys
        if not map.contains(activeFreshKeys, key)
            map.remove(freshness, key)
// END V22 FRESHNESS CLOSED-CANDLE PASS
 
// BEGIN V26 ZONE ALERT CLOSED-CANDLE TRACKING
if barstate.isconfirmed
    // Counts every identity regardless of display/alert filters, with no delayed delivery.
    for z in zones
        f_noticeTrack(f_freshZoneKey(z.id), z.lo, z.hi, z.bornTime, z.role, f_tfName(z.govTF, z.govSeconds))
    for z in swings
        f_noticeTrack(f_freshSwingKey(z.id), z.lo, z.hi, z.bornTime, z.kind == -1 ? 1 : -1, f_swingEvidence(z))
    if parentActive
        f_noticeTrack(f_freshParentKey(-1), parentLow.lo, parentLow.hi, parentBorn, 1, parentGovTF)
        f_noticeTrack(f_freshParentKey(1), parentHigh.lo, parentHigh.hi, parentBorn, -1, parentGovTF)
    // Keep at most one retired generation for its final candle; prune on the next pass.
    array<string> oldNoticeKeys = map.keys(zoneWatches)
    for key in oldNoticeKeys
        ZoneWatch watch = map.get(zoneWatches, key)
        if watch.lastSeen < bar_index
            if watch.lastSeen == bar_index - 1
                watch := f_noticeStep(watch)
                map.put(zoneWatches, key, watch)
            else
                map.remove(zoneWatches, key)
// END V26 ZONE ALERT CLOSED-CANDLE TRACKING
 
// Current map is ranked at the last confirmed snapshot; event history is separate.
var table traceTable = table.new(position.bottom_left, 3, 24, bgcolor = color.new(color.black, 12), border_width = 1)
var table captionDock = table.new(position.middle_right, 2, 13, bgcolor = color.new(color.black, 100), border_width = 0)
var table dashboard = table.new(position.top_right, 2, 29, bgcolor = color.new(color.black, 15), border_width = 1)
var table legend = table.new(position.bottom_right, 1, 2, bgcolor = color.new(color.black, 30))
f_cell(int row, string left, string right) =>
    table.cell(dashboard, 0, row, left, text_color = color.silver, text_size = size.small, text_halign = text.align_left)
    table.cell(dashboard, 1, row, right, text_color = color.white, text_size = size.small, text_halign = text.align_left)
f_tfStatus(string tf, bool valid) =>
    tf + (valid ? " active" : " ignored (lower/duplicate)")
f_conflicts(Zone z, array<int> selected) =>
    bool conflict = false
    if array.size(selected) > 0
        for j = 0 to array.size(selected) - 1
            Zone other = array.get(zones, array.get(selected, j))
            bool overlap = z.lo <= other.hi and z.hi >= other.lo
            float distance = math.abs((z.lo + z.hi - other.lo - other.hi) * 0.5)
            if overlap or distance < snapshotATR * 0.35
                conflict := true
    conflict
 
// Context boundaries are geometric candidates, not newly certified major defenses.
f_rangeCredible(Zone z) =>
    f_maxTF(z) >= 86400 or f_recentRejections(z) >= 1
f_nearestRange(int side, array<int> selected) =>
    int best = -1
    float nearest = 1e30
    if array.size(zones) > 0
        for i = 0 to array.size(zones) - 1
            Zone z = array.get(zones, i)
            bool correctSide = side == -1 ? z.hi < snapshotClose : side == 1 ? z.lo > snapshotClose : z.lo <= snapshotClose and z.hi >= snapshotClose
            // Opposite outer boundaries have separate priority; proximity suppression must not
            // remove the other side of a narrow range. A transition can never displace them.
            bool conflict = side == 0 ? f_conflicts(z, selected) : false
            if correctSide and f_zoneVisible(z) and f_rangeCredible(z) and not array.includes(selected, i) and not conflict
                float distance = side == -1 ? snapshotClose - z.hi : side == 1 ? z.lo - snapshotClose : math.abs(snapshotClose - (z.lo + z.hi) * 0.5)
                if distance < nearest
                    nearest := distance
                    best := i
    best
 
// Count a separate geometric chain: inner candidates already drawn still count toward depth.
// This filters retained evidence only; it adds no data requests and never invents a zone.
f_outerRange(int side) =>
    array<int> chain = array.new_int()
    int outermost = -1
    float minimumTF = timeframe.in_seconds(outerMinTF)
    for depth = 1 to outerDepth
        int best = -1
        float nearest = 1e30
        if array.size(zones) > 0
            for i = 0 to array.size(zones) - 1
                Zone z = array.get(zones, i)
                bool correctSide = side == -1 ? z.hi < snapshotClose : z.lo > snapshotClose
                bool overlaps = false
                if array.size(chain) > 0
                    for prior in chain
                        Zone other = array.get(zones, prior)
                        if z.lo <= other.hi and z.hi >= other.lo
                            overlaps := true
                if correctSide and f_zoneVisible(z) and f_maxTF(z) >= minimumTF and not array.includes(chain, i) and not overlaps
                    float distance = side == -1 ? snapshotClose - z.hi : z.lo - snapshotClose
                    if distance < nearest
                        nearest := distance
                        best := i
        if best >= 0
            array.push(chain, best)
            outermost := best
    outermost
 
f_zoneMap(Zone z, bool supplemental, bool outerContext, bool internal) =>
    int effective = z.pending != 0 and z.structural ? z.pending : z.role
    int spatialRole = z.hi < snapshotClose ? 1 : z.lo > snapshotClose ? -1 : 0
    bool transition = spatialRole == 0 and (supplemental or internal)
    bool major = f_major(z)
    string roleText = effective == 1 ? "SUPPORT" : "RESISTANCE"
    string locationRole = spatialRole == 1 ? "SUPPORT" : spatialRole == -1 ? "RESISTANCE" : "TRANSITION"
    color tint = outerContext ? color.rgb(85, 125, 175) : transition ? color.orange : supplemental or internal ? (spatialRole == 1 ? color.teal : color.red) : effective == 1 ? color.teal : color.red
    string direction = z.pending == 1 ? "up" : "down"
    string status = z.pending == 0 ? "" : z.structural ? "\nStructural " + direction + " | retest pending" : "\nLocal " + direction + " | await " + f_tfName(z.govTF, z.govSeconds) + " close"
    string heading = internal ? (parentActive ? "INTERNAL " : "CONFIRMED ") + locationRole : major ? "MAJOR " + roleText : outerContext ? "OUTER HTF " + locationRole : supplemental ? "RANGE " + locationRole : roleText
    int roleTier = internal and spatialRole != 0 ? f_roleTier(z) : 0
    int geometrySide = spatialRole == 1 ? -1 : 1
    bool keyRole = roleTier >= 2 and f_rolePriority(z, geometrySide) >= 0
    if keyRole
        heading := (roleTier == 3 ? "ROLE-REVERSAL " : parentActive ? "KEY INTERNAL " : "KEY CONFIRMED ") + locationRole
        tint := color.rgb(168, 132, 59)
        if z.pending == 0
            status += roleTier == 3 ? "\nConfirmed flip retest" : "\nBreak held | no retest"
    if (supplemental or outerContext or internal) and (transition or spatialRole != effective)
        status := "\nTracked " + str.lower(roleText) + status
    string tooltip = spatialRole == 1 ? "Support area below price: watch for a bounce if price returns here; it may still break through." : spatialRole == -1 ? "Resistance area above price: watch for selling or a downward rejection if price returns; it may still break through." : "Transition area: price is inside this zone; neither side has clearly taken control."
    int priority = f_zonePriority(z)
    tooltip += f_zonePriorityExplanation(z, priority)
    if internal and not parentActive
        tooltip += "\nThis level is confirmed from closed candles; a main trading range has not yet been found."
    if major
        tooltip += " Major means price has bounced or turned away enough times here, with daily-or-longer turning points also present."
    if keyRole
        tooltip += roleTier == 3 ? " Retested means price broke through, then successfully tested the new side: former resistance can become support, or vice versa." : " Key means a break was confirmed and has not failed. Break holds means no successful return test is recorded yet; visits counted for freshness do not have to be successful retests."
    if outerContext
        tooltip += " Broader means an additional longer-term level outside the nearer levels. It is not necessarily the main range top or bottom."
    if supplemental
        tooltip += " Range means an extra nearby level, not automatically a P1 main-range boundary."
    if spatialRole != effective
        tooltip += " Last role: " + str.lower(roleText) + " describes its last confirmed role. The heading describes where it sits relative to price now. Crossing a zone does not by itself confirm a change from support to resistance or back."
    if z.pending != 0
        tooltip += z.structural ? "\nBreak " + (z.pending == 1 ? "above" : "below") + " means a candle on this zone's confirmation timeframe closed beyond it. Awaiting retest means waiting for price to return and successfully test the new side." : "\nPossible break " + (z.pending == 1 ? "above" : "below") + " means a candle on your chart closed beyond the zone. Wait " + f_tfName(z.govTF, z.govSeconds) + " means waiting for a candle on that timeframe to confirm the break."
    tooltip += "\n" + (f_provenance(z) == f_tfName(z.govTF, z.govSeconds) ? "Based on " + f_tooltipTF(z.govTF, z.govSeconds) + " swing highs or lows." : "Based on swing highs or lows from these timeframes: " + f_provenance(z) + ".") + " A break is confirmed only when a " + f_tooltipTF(z.govTF, z.govSeconds) + " candle closes beyond the zone."
    MapLevel.new(z.lo, z.hi, z.bornTime, tint, heading, f_provenance(z), status, tooltip, z.pending != 0 or outerContext, priority, map.contains(zoneBirthOrigins, z.id) ? map.get(zoneBirthOrigins, z.id) : na, f_freshZoneKey(z.id))
f_parentMap(SwingCluster z) =>
    string side = z.kind == 1 ? "HIGH" : "LOW"
    string status = z.tests >= 2 ? "\n" + (z.kind == 1 ? "High" : "Low") + " cluster: " + str.tostring(z.tests) + " swings" : "\nProminent confirmed swing"
    string tooltip = (z.kind == 1 ? "Top boundary of the main confirmed trading range: watch for resistance here." : "Bottom boundary of the main confirmed trading range: watch for support here.") + "\nWhy P1: this boundary defines the active main range. The complete range was confirmed on " + str.format_time(parentBorn, "yyyy-MM-dd HH:mm", "UTC") + " UTC. A break needs a " + f_tooltipTF(parentGovTF, parentGovSlot == 0 ? sec1 : parentGovSlot == 1 ? sec2 : sec3) + " candle to close past the range edge and its extra break distance."
    tooltip += "\n" + (z.tests >= 2 ? "Nearby highs/lows means several earlier highs or lows near this price. It does not mean price has successfully tested the zone since it appeared." : "Large confirmed turn means an especially large turning high or low, confirmed after later candles closed.") + "\n" + f_swingPriorityEvidence(z)
    MapLevel.new(z.lo, z.hi, parentBorn, color.rgb(85, 125, 175), "STRUCTURAL RANGE " + side, f_swingEvidence(z), status, tooltip, false, 1, not na(parentOrigins) ? (z.kind == 1 ? parentOrigins.high : parentOrigins.low) : na, f_freshParentKey(z.kind))
f_registryInternalMap(SwingCluster z) =>
    bool below = z.hi < snapshotClose
    string side = below ? "SUPPORT" : "RESISTANCE"
    string originKind = z.kind == 1 ? "High" : "Low"
    string status = z.tests >= 2 ? "\n" + originKind + " cluster: " + str.tostring(z.tests) + " swings" : "\nProminent confirmed swing"
    string tooltip = (below ? "Support area below price, based on confirmed turning points." : "Resistance area above price, based on confirmed turning points.")
    int priority = f_registryPriority(z)
    tooltip += "\nWhy P" + str.tostring(priority) + ": the turns are large enough or have repeated often enough to matter" + (priority == 2 ? " and include weekly candles or longer." : "; they come from timeframes shorter than a week.") + " " + f_swingPriorityEvidence(z)
    tooltip += z.tests >= 2 ? " Nearby highs/lows means several earlier turns near this price, not successful tests since the zone appeared." : " Large confirmed turn means an especially large confirmed high or low."
    tooltip += " This is an extra level to watch. The indicator does not track break/retest alerts for this type of level."
    MapLevel.new(z.lo, z.hi, z.bornTime, below ? color.teal : color.red, "INTERNAL " + side, f_swingEvidence(z), status, tooltip, false, priority, map.contains(swingBirthOrigins, z.id) ? map.get(swingBirthOrigins, z.id) : na, f_freshSwingKey(z.id))
f_mapConflict(float lo, float hi, array<MapLevel> map) =>
    bool conflict = false
    if array.size(map) > 0
        for old in map
            if lo <= old.hi and hi >= old.lo
                conflict := true
    conflict
f_registryConflict(float lo, float hi, array<MapLevel> map) =>
    bool conflict = f_mapConflict(lo, hi, map)
    if array.size(map) > 0
        for old in map
            if math.abs((lo + hi - old.lo - old.hi) * 0.5) < snapshotATR * extraRegistryGapATR
                conflict := true
    conflict
f_insideParent(Zone z) =>
    not parentActive or (z.lo > parentLow.hi and z.hi < parentHigh.lo)
// Snapshot-only conflict witnesses reuse the selection predicates on singleton maps.
f_traceMapIdentity(MapLevel level) =>
    string identity = ""
    for candidate in zones
        if candidate.lo == level.lo and candidate.hi == level.hi and candidate.bornTime == level.born
            identity += "Z#" + str.tostring(candidate.id) + " "
    for candidate in swings
        if candidate.lo == level.lo and candidate.hi == level.hi
            identity += "S#" + str.tostring(candidate.id) + " "
    identity + "[" + str.tostring(level.lo, format.mintick) + "-" + str.tostring(level.hi, format.mintick) + "]"
f_traceMapBlockers(float lo, float hi, array<MapLevel> selectedMap, bool registry) =>
    string witnesses = ""
    for level in selectedMap
        array<MapLevel> singleton = array.new<MapLevel>()
        array.push(singleton, level)
        bool blocked = registry ? f_registryConflict(lo, hi, singleton) : f_mapConflict(lo, hi, singleton)
        if blocked
            witnesses += f_traceMapIdentity(level) + (f_mapConflict(lo, hi, singleton) ? " overlap" : " registry spacing") + "; "
    str.length(witnesses) > 0 ? witnesses : "none"
f_traceEarlyBlockers(Zone z, array<int> selectedIndices) =>
    string witnesses = ""
    for index in selectedIndices
        Zone other = array.get(zones, index)
        if other.id != z.id
            array<int> singleton = array.new_int()
            array.push(singleton, index)
            if f_conflicts(z, singleton)
                witnesses += "Z#" + str.tostring(other.id) + " [" + str.tostring(other.lo, format.mintick) + "-" + str.tostring(other.hi, format.mintick) + "]; "
    str.length(witnesses) > 0 ? witnesses : "none"
f_originTooltip(SwingBirthOrigin origin, string boundary) =>
    boundary + " main-range boundary (" + (boundary == "Upper" ? "range top" : "range bottom") + "). This diamond marks this boundary at the time the WHOLE range first became available, after both boundaries were confirmed. Both diamonds share the whole-range confirmation date.\nEarlier turning candle: " + origin.sourceTF + ", " + str.format_time(origin.start, "yyyy-MM-dd HH:mm", "UTC") + " to " + str.format_time(origin.finish, "yyyy-MM-dd HH:mm", "UTC") + " UTC. Turning price: " + str.tostring(origin.price, format.mintick) + ".\nThis turning point was confirmed on " + str.format_time(origin.firstConfirm, "yyyy-MM-dd HH:mm", "UTC") + " UTC. The whole range first became available on " + str.format_time(parentOrigins.rangeBorn, "yyyy-MM-dd HH:mm", "UTC") + " UTC; this can be later than the turning-point confirmation. The solid zone and diamond start at that shared range time. The dashed line only points back to the earlier turn, when the complete range was not yet known. Candle times do not reveal the exact instant of the high or low."
 
// BEGIN V28 SHARED RANGE TOOLTIP
f_rangeConfirmationTooltip() =>
    "Main range confirmed. This one date belongs to BOTH the upper and lower boundaries, even if a display filter hides one of them.\nThe whole range first became available on " + str.format_time(parentOrigins.rangeBorn, "yyyy-MM-dd HH:mm", "UTC") + " UTC. Upper turning point confirmed: " + str.format_time(parentOrigins.high.firstConfirm, "yyyy-MM-dd HH:mm", "UTC") + " UTC. Lower turning point confirmed: " + str.format_time(parentOrigins.low.firstConfirm, "yyyy-MM-dd HH:mm", "UTC") + " UTC.\nThe two turning points can be confirmed at different times. Their earlier confirmation dates are not the date the complete range became available. The solid zones and their diamonds start at the shared range time; dashed lines point back to the earlier turning candles. Hover each diamond to see which boundary it marks."
// END V28 SHARED RANGE TOOLTIP
 
f_zoneOriginTooltip(SwingBirthOrigin origin, int available, string heading) =>
    heading + ". The diamond marks when this zone first became available. Its importance and support/resistance status can change later; the diamond stays at the original confirmation time.\nThe dashed line points back to the starting turning candle, when the zone was not yet confirmed. The solid zone begins at " + str.format_time(available, "yyyy-MM-dd HH:mm", "UTC") + " UTC.\nTurning candle: " + origin.sourceTF + ", " + str.format_time(origin.start, "yyyy-MM-dd HH:mm", "UTC") + " to " + str.format_time(origin.finish, "yyyy-MM-dd HH:mm", "UTC") + " UTC. Turning price: " + str.tostring(origin.price, format.mintick) + ". This turning point was first confirmed on the chart at " + str.format_time(origin.firstConfirm, "yyyy-MM-dd HH:mm", "UTC") + " UTC. These times describe the whole candle; the exact time of its high or low is unknown."
 
if barstate.islast or barstate.islastconfirmedhistory // V26 seed prior confirmed watch map once
    while array.size(boxes) > 0
        box.delete(array.pop(boxes))
    while array.size(lines) > 0
        line.delete(array.pop(lines))
    while array.size(captions) > 0
        label.delete(array.pop(captions))
    table.clear(dashboard, 0, 0, 1, 28)
    table.clear(legend, 0, 0, 0, 1)
    table.clear(captionDock, 0, 0, 1, 12)
    array<int> selected = array.new_int()
    array<MapLevel> map = array.new<MapLevel>()
    int eligible = 0
    int majorShown = 0
    int rangeShown = 0
    int outerShown = 0
    int belowShown = 0
    int aboveShown = 0
    int shownParents = 0 // V22 actual admitted boundaries, not reserved slots
    bool internalMode = displayMode == "Structure + internal levels"
    // P1 parents own their slots. All remaining candidates share one tier-first pass:
    // neither a near-side reservation, transition nor registry fallback can spend a P2 slot.
    if internalMode and parentActive and showP1
        if f_freshVisible(f_freshParentKey(-1)) and f_nearVisible(parentLow.lo, parentLow.hi, true)
            array.push(map, f_parentMap(parentLow))
        if f_freshVisible(f_freshParentKey(1)) and f_nearVisible(parentHigh.lo, parentHigh.hi, true)
            array.push(map, f_parentMap(parentHigh))
    shownParents := array.size(map)
    array<MapLevel> candidates = array.new<MapLevel>()
    array<int> candidateZone = array.new_int()
    array<int> candidateSide = array.new_int()
    array<float> candidateRole = array.new_float()
    array<float> candidateStrength = array.new_float()
    array<float> candidateGap = array.new_float()
    array<bool> consumed = array.new_bool()
    if not na(snapshotClose)
        int lowerOuter = displayMode == "Major + range boundaries" and showOuter ? f_outerRange(-1) : -1
        int upperOuter = displayMode == "Major + range boundaries" and showOuter ? f_outerRange(1) : -1
        if array.size(zones) > 0
            for i = 0 to array.size(zones) - 1
                Zone z = array.get(zones, i)
                bool major = f_major(z)
                bool outer = i == lowerOuter or i == upperOuter
                bool qualifies = internalMode ? (f_rangeCredible(z) or f_roleTier(z) >= 2) and f_insideParent(z) : displayMode == "All ranked zones" or major or (displayMode == "Major + range boundaries" and (f_rangeCredible(z) or outer))
                if qualifies and f_zoneVisible(z)
                    int side = z.hi < snapshotClose ? -1 : z.lo > snapshotClose ? 1 : 0
                    int trackedRole = z.pending != 0 and z.structural ? z.pending : z.role
                    int rankSide = side == 0 ? (trackedRole == 1 ? -1 : 1) : side
                    float gap = side == -1 ? snapshotClose - z.hi : side == 1 ? z.lo - snapshotClose : 0.0
                    array.push(candidates, f_zoneMap(z, displayMode == "Major + range boundaries" and not major and not outer, outer, internalMode))
                    array.push(candidateZone, i)
                    array.push(candidateSide, rankSide)
                    array.push(candidateRole, f_rolePriority(z, rankSide))
                    array.push(candidateStrength, f_score(z) / (1.0 + gap / snapshotATR * 0.15))
                    array.push(candidateGap, gap)
                    array.push(consumed, false)
        if internalMode and parentActive and array.size(swings) > 0
            for z in swings
                bool inside = z.lo > parentLow.hi and z.hi < parentHigh.lo
                int side = z.hi < snapshotClose ? -1 : z.lo > snapshotClose ? 1 : 0
                if inside and side != 0 and f_registryVisible(z) and f_swingQualified(z)
                    float gap = side == -1 ? snapshotClose - z.hi : z.lo - snapshotClose
                    array.push(candidates, f_registryInternalMap(z))
                    array.push(candidateZone, -1)
                    array.push(candidateSide, side)
                    array.push(candidateRole, -1.0)
                    array.push(candidateStrength, f_swingScore(z) / (1.0 + gap / snapshotATR * 0.15))
                    array.push(candidateGap, gap)
                    array.push(consumed, false)
    eligible := array.size(candidates)
    // Lexicographic order is importance, side-valid role evidence, side balance, strength,
    // then gap and stable source order. A lower tier can never outrank a higher tier.
    for slot = 0 to visible - 1
        if array.size(map) < visible and array.size(candidates) > 0
            int best = -1
            int bestPriority = 5
            float bestRole = -2.0
            int bestBalance = 1000
            float bestStrength = -1.0
            float bestGap = 1e30
            for i = 0 to array.size(candidates) - 1
                if not array.get(consumed, i)
                    MapLevel candidate = array.get(candidates, i)
                    int zoneIndex = array.get(candidateZone, i)
                    bool conflict = zoneIndex < 0 ? f_registryConflict(candidate.lo, candidate.hi, map) : internalMode ? f_mapConflict(candidate.lo, candidate.hi, map) : f_conflicts(array.get(zones, zoneIndex), selected)
                    if not conflict
                        int priority = candidate.priority
                        float roleRank = array.get(candidateRole, i)
                        int balance = array.get(candidateSide, i) == -1 ? belowShown : aboveShown
                        float candidateRankStrength = array.get(candidateStrength, i)
                        float gap = array.get(candidateGap, i)
                        bool better = priority < bestPriority or (priority == bestPriority and (roleRank > bestRole or (roleRank == bestRole and (balance < bestBalance or (balance == bestBalance and (candidateRankStrength > bestStrength or (candidateRankStrength == bestStrength and gap < bestGap)))))))
                        if better
                            best := i
                            bestPriority := priority
                            bestRole := roleRank
                            bestBalance := balance
                            bestStrength := candidateRankStrength
                            bestGap := gap
            if best >= 0
                array.set(consumed, best, true)
                MapLevel chosen = array.get(candidates, best)
                array.push(map, chosen)
                int zoneIndex = array.get(candidateZone, best)
                if zoneIndex >= 0
                    array.push(selected, zoneIndex)
                    Zone z = array.get(zones, zoneIndex)
                    bool major = f_major(z)
                    bool outer = str.contains(chosen.heading, "OUTER HTF")
                    majorShown += major ? 1 : 0
                    rangeShown += not major and not outer and not internalMode ? 1 : 0
                    outerShown += outer and not major ? 1 : 0
                belowShown += array.get(candidateSide, best) == -1 ? 1 : 0
                aboveShown += array.get(candidateSide, best) == 1 ? 1 : 0
    // BEGIN V26 ZONE ALERT DISPATCH AND WATCH SNAPSHOT
    if barstate.isconfirmed
        // Only the causal map from the previous completed candle can gate this batch.
        if barstate.isrealtime and zoneAlertsEnabled
            array<string> order = array.new_string()
            array<int> eligibleNotices = array.new_int()
            if array.size(noticeQueue) > 0
                for i = 0 to array.size(noticeQueue) - 1
                    ZoneNotice notice = array.get(noticeQueue, i)
                    bool watched = zoneAlertScope == "Previously displayed zones" ? map.contains(priorWatchedMap, notice.key) : map.contains(zoneWatches, notice.key)
                    if watched
                        ZoneWatch watch = zoneAlertScope == "Previously displayed zones" ? map.get(priorWatchedMap, notice.key) : map.get(zoneWatches, notice.key)
                        if f_noticePriorityAllowed(watch.priority) and f_noticeFreshAllowed(watch.visits) and f_noticeEventAllowed(notice.event)
                            notice.priority := watch.priority
                            notice.visits := watch.visits
                            array.push(eligibleNotices, i)
                            array.push(order, str.tostring(watch.priority) + ":" + notice.key + ":" + notice.event + ":" + str.tostring(i))
            array<int> indices = array.sort_indices(order)
            string payload = "Confirmed zone events | " + syminfo.tickerid + " | chart " + f_tfName(timeframe.period, chartSeconds) + " | watched at previous close\n"
            int included = 0
            int omitted = 0
            for sortedIndex in indices
                ZoneNotice notice = array.get(noticeQueue, array.get(eligibleNotices, sortedIndex))
                ZoneWatch watch = zoneAlertScope == "Previously displayed zones" ? map.get(priorWatchedMap, notice.key) : map.get(zoneWatches, notice.key)
                string entry = f_noticeMessage(notice, watch) + "\n"
                if str.length(payload) + str.length(entry) <= 3200
                    payload += entry
                    included += 1
                    notice.delivered := true
                else
                    omitted += 1
            if included > 0
                if omitted > 0
                    payload += str.tostring(omitted) + " additional eligible events omitted from this bounded message; no later replay."
                alert(payload, alert.freq_once_per_bar_close)
                array.set(noticeCounters, 1, array.get(noticeCounters, 1) + included)
                array.set(noticeCounters, 2, array.get(noticeCounters, 2) + 1)
            array.set(noticeCounters, 3, included)
            array.set(noticeCounters, 4, omitted)
        // Refresh descriptive metadata AFTER dispatch: Fresh-only first visits stay eligible.
        // This expensive priority explanation scan runs only at last-history/live close.
        for z in zones
            string key = f_freshZoneKey(z.id)
            if map.contains(zoneWatches, key)
                ZoneWatch watch = map.get(zoneWatches, key)
                watch.priority := f_zonePriority(z)
                watch.visits := f_freshCount(key)
                watch.role := z.role
                watch.sourceTF := f_tfName(z.govTF, z.govSeconds)
                map.put(zoneWatches, key, watch)
        for z in swings
            string key = f_freshSwingKey(z.id)
            if map.contains(zoneWatches, key)
                ZoneWatch watch = map.get(zoneWatches, key)
                watch.priority := f_registryPriority(z)
                watch.visits := f_freshCount(key)
                watch.sourceTF := f_swingEvidence(z)
                map.put(zoneWatches, key, watch)
        if parentActive
            for kind in array.from(-1, 1)
                string key = f_freshParentKey(kind)
                if map.contains(zoneWatches, key)
                    ZoneWatch watch = map.get(zoneWatches, key)
                    watch.priority := 1
                    watch.visits := f_freshCount(key)
                    map.put(zoneWatches, key, watch)
        map.clear(priorWatchedMap)
        for level in map
            if map.contains(zoneWatches, level.freshnessKey)
                ZoneWatch watch = map.get(zoneWatches, level.freshnessKey).copy()
                watch.priority := level.priority
                watch.visits := f_freshCount(level.freshnessKey)
                map.put(priorWatchedMap, level.freshnessKey, watch)
    // END V26 ZONE ALERT DISPATCH AND WATCH SNAPSHOT
 
    // BEGIN V26 NEAREST PANEL AND CANDIDATE DEBUG
    table.clear(nearestZonePanel, 0, 0, 1, 3)
    if showNearestPanel and not na(snapshotClose)
        int support = -1
        int resistance = -1
        int inside = -1
        float supportGap = 1e20
        float resistanceGap = 1e20
        int insidePriority = 99
        if array.size(map) > 0
            for i = 0 to array.size(map) - 1
                MapLevel level = array.get(map, i)
                if level.hi < snapshotClose and snapshotClose - level.hi < supportGap
                    support := i
                    supportGap := snapshotClose - level.hi
                else if level.lo > snapshotClose and level.lo - snapshotClose < resistanceGap
                    resistance := i
                    resistanceGap := level.lo - snapshotClose
                else if level.lo <= snapshotClose and level.hi >= snapshotClose and level.priority < insidePriority
                    inside := i
                    insidePriority := level.priority
        table.cell(nearestZonePanel, 0, 0, "Nearest displayed zones", text_color = color.white, text_size = size.normal, tooltip = "Current displayed map and last completed chart close. Below and above describe location, not a confirmed role. Inside means the close is within a zone; it is not given a support/resistance direction. Distances use chart ATR, not a trade plan.")
        table.cell(nearestZonePanel, 1, 0, "Closed candle", text_color = color.silver, text_size = size.normal)
        for row = 1 to 3
            int index = row == 1 ? support : row == 2 ? resistance : inside
            string heading = row == 1 ? "Nearest below" : row == 2 ? "Nearest above" : "Inside"
            string value = "None displayed"
            if index >= 0
                MapLevel level = array.get(map, index)
                float gap = row == 1 ? snapshotClose - level.hi : row == 2 ? level.lo - snapshotClose : 0.0
                value := "P" + str.tostring(level.priority) + " " + str.tostring(level.lo, format.mintick) + "-" + str.tostring(level.hi, format.mintick) + " | " + str.tostring(gap / snapshotATR, "#.00") + " ATR"
            table.cell(nearestZonePanel, 0, row, heading, text_color = color.silver, text_size = size.normal)
            table.cell(nearestZonePanel, 1, row, value, text_color = color.white, text_size = size.normal)
    table.clear(noticeDebug, 0, 0, 1, 21)
    if showAlertDebug
        table.cell(noticeDebug, 0, 0, "Raw event candidates", text_color = color.white, text_size = size.tiny, tooltip = "Up to 20 raw candidates reconstructed from closed candles. Historical displayed scope is not reconstructed; a candidate is not proof of a sent message. Sent means this running chart called alert(), not proof of server delivery.")
        table.cell(noticeDebug, 1, 0, "History is not delivery", text_color = color.orange, text_size = size.tiny)
        table.cell(noticeDebug, 0, 1, "Tracked " + str.tostring(map.size(zoneWatches)) + " | prior map " + str.tostring(map.size(priorWatchedMap)), text_color = color.silver, text_size = size.tiny)
        table.cell(noticeDebug, 1, 1, "Candidates " + str.tostring(array.get(noticeCounters, 0)) + " | calls " + str.tostring(array.get(noticeCounters, 2)), text_color = color.silver, text_size = size.tiny)
        if array.size(noticeHistory) > 0
            for row = 0 to array.size(noticeHistory) - 1
                ZoneNotice notice = array.get(noticeHistory, array.size(noticeHistory) - 1 - row)
                table.cell(noticeDebug, 0, row + 2, str.format_time(notice.stamp, "MM-dd HH:mm", "UTC") + " " + notice.key, text_color = color.silver, text_size = size.tiny)
                table.cell(noticeDebug, 1, row + 2, notice.event + (notice.delivered ? " | alert() called" : " | candidate only"), text_color = notice.delivered ? color.teal : color.silver, text_size = size.tiny, tooltip = notice.key + " " + f_noticeType(notice.key) + "; " + str.tostring(notice.lo, format.mintick) + "-" + str.tostring(notice.hi, format.mintick) + "; source " + notice.sourceTF + "; raw candidates are not proof of delivery or historical displayed eligibility.")
    // END V26 NEAREST PANEL AND CANDIDATE DEBUG
 
    // Optional final-map invariant: an omitted candidate may be blocked only by an equal
    // or stronger selected level. Weaker levels are removed before checking its eligibility.
    int priorityInversions = 0
    string priorityCounts = ""
    if traceEnabled
        for tier = 1 to 4
            int count = 0
            for level in map
                count += level.priority == tier ? 1 : 0
            priorityCounts += (tier == 1 ? "" : " | ") + "P" + str.tostring(tier) + "=" + str.tostring(count)
        if array.size(candidates) > 0
            for i = 0 to array.size(candidates) - 1
                if not array.get(consumed, i)
                    MapLevel candidate = array.get(candidates, i)
                    array<MapLevel> strongerMap = array.new<MapLevel>()
                    array<int> strongerIndices = array.new_int()
                    bool weakerShown = false
                    for level in map
                        if level.priority <= candidate.priority
                            array.push(strongerMap, level)
                        else
                            weakerShown := true
                    for index in selected
                        if f_zonePriority(array.get(zones, index)) <= candidate.priority
                            array.push(strongerIndices, index)
                    int zoneIndex = array.get(candidateZone, i)
                    bool blocked = zoneIndex < 0 ? f_registryConflict(candidate.lo, candidate.hi, strongerMap) : internalMode ? f_mapConflict(candidate.lo, candidate.hi, strongerMap) : f_conflicts(array.get(zones, zoneIndex), strongerIndices)
                    priorityInversions += weakerShown and not blocked ? 1 : 0
    // Trace snapshot is deliberately separate from historical events: map is computed only here.
    table.clear(traceTable, 0, 0, 2, 23)
    if traceEnabled
        table.cell(traceTable, 0, 0, "Zone trace " + str.tostring(traceTarget, format.mintick), text_color = color.white, text_size = size.small)
        table.cell(traceTable, 1, 0, "Loaded from " + f_traceDate(historyStart), text_color = color.silver, text_size = size.small)
        table.cell(traceTable, 2, 0, "Priority inversions " + str.tostring(priorityInversions) + " | " + priorityCounts + "\nDropped " + str.tostring(array.get(traceDropped, 0)) + " | kept " + str.tostring(array.size(traceRecords)), text_color = color.silver, text_size = size.small)
        string traceCurrentZ = ""
        string traceCurrentS = ""
        for z in zones
            if array.includes(traceWatch, f_traceKey("Z", z.id)) or f_traceGeometry(z.lo, z.hi)
                bool drawn = false
                for level in map
                    drawn := drawn or (level.lo == z.lo and level.hi == z.hi and level.born == z.bornTime)
                string reason = drawn ? "VISIBLE" : not f_priorityEnabled(f_zonePriority(z)) ? "tier hidden" : not f_freshVisible(f_freshZoneKey(z.id)) ? "freshness category hidden" : not f_nearVisible(z.lo, z.hi) ? "outside nearby range" : displayMode == "Structure + internal levels" and not f_insideParent(z) ? "outside parent" : "not selected: mode eligibility / higher-or-equal priority conflict / tier-first budget"
                int side = z.hi < snapshotClose ? -1 : z.lo > snapshotClose ? 1 : 0
                float gap = side == -1 ? snapshotClose - z.hi : side == 1 ? z.lo - snapshotClose : 0.0
                traceCurrentZ += f_traceKey("Z", z.id) + " " + str.tostring(z.lo, format.mintick) + "-" + str.tostring(z.hi, format.mintick) + " P" + str.tostring(f_zonePriority(z)) + " " + f_freshCaption(f_freshZoneKey(z.id)) + " " + reason + "; strict order P1>P2>P3>P4; shown=" + str.tostring(array.size(map)) + "/" + str.tostring(visible) + "; visibleTier=" + str.tostring(f_zoneVisible(z)) + " insideParent=" + str.tostring(f_insideParent(z)) + " credible=" + str.tostring(f_rangeCredible(z)) + " roleTier=" + str.tostring(f_roleTier(z)) + " roleRank=" + str.tostring(f_rolePriority(z, side), "#.00") + " gap=" + str.tostring(gap, format.mintick) + " retention=" + str.tostring(f_retention(z), "#.00") + "\n" + (drawn ? "" : "Final-map overlap blockers: " + f_traceMapBlockers(z.lo, z.hi, map, false) + " | early-selection blockers: " + f_traceEarlyBlockers(z, selected) + "\n")
        for z in swings
            if array.includes(traceWatch, f_traceKey("S", z.id)) or f_traceGeometry(z.lo, z.hi)
                bool drawn = false
                for level in map
                    drawn := drawn or (level.lo == z.lo and level.hi == z.hi)
                string reason = drawn ? "VISIBLE" : not f_priorityEnabled(f_registryPriority(z)) ? "tier hidden" : not f_freshVisible(f_freshSwingKey(z.id)) ? "freshness category hidden" : not f_nearVisible(z.lo, z.hi) ? "outside nearby range" : not f_swingQualified(z) ? "not qualified / outside horizon" : "not selected: parent / higher-or-equal priority spacing/conflict / tier-first budget"
                bool inside = parentActive and z.lo > parentLow.hi and z.hi < parentHigh.lo
                int side = z.hi < snapshotClose ? -1 : z.lo > snapshotClose ? 1 : 0
                float gap = side == -1 ? snapshotClose - z.hi : side == 1 ? z.lo - snapshotClose : 0.0
                traceCurrentS += f_traceKey("S", z.id) + " " + str.tostring(z.lo, format.mintick) + "-" + str.tostring(z.hi, format.mintick) + " P" + str.tostring(f_registryPriority(z)) + " " + f_freshCaption(f_freshSwingKey(z.id)) + " " + reason + "; strict order P1>P2>P3>P4; shown=" + str.tostring(array.size(map)) + "/" + str.tostring(visible) + " tierEnabled=" + str.tostring(f_registryVisible(z)) + " qualified=" + str.tostring(f_swingQualified(z)) + " insideActiveParent=" + str.tostring(inside) + " side=" + str.tostring(side) + " gap=" + str.tostring(gap, format.mintick) + "\n" + (drawn ? "" : "Final-map overlap/spacing blockers: " + f_traceMapBlockers(z.lo, z.hi, map, true) + "\n")
        table.cell(traceTable, 0, 1, "CURRENT MAP ONLY\n" + f_traceDate(snapshotTime), text_color = color.silver, text_size = size.small)
        table.cell(traceTable, 1, 1, str.length(traceCurrentZ) > 0 ? traceCurrentZ : "No focused retained Z IDs", text_color = color.white, text_size = size.small)
        table.cell(traceTable, 2, 1, str.length(traceCurrentS) > 0 ? traceCurrentS : "No focused registry S IDs", text_color = color.white, text_size = size.small)
        int pages = math.max(1, int(math.ceil(array.size(traceRecords) / 20.0)))
        int page = math.min(tracePage, pages)
        table.cell(traceTable, 0, 2, "Page " + str.tostring(page) + "/" + str.tostring(pages) + " | latest first", text_color = color.white, text_size = size.small)
        table.cell(traceTable, 1, 2, "Z=retained; S=structural registry; map " + str.tostring(array.size(map)) + "/" + str.tostring(visible) + " | registry gap " + str.tostring(snapshotATR * extraRegistryGapATR, format.mintick) + (effectiveNearbyEnabled ? " | nearby " + str.tostring(snapshotClose - effectiveNearbyATR * snapshotATR, format.mintick) + "-" + str.tostring(snapshotClose + effectiveNearbyATR * snapshotATR, format.mintick) + " (" + str.tostring(effectiveNearbyATR, "#.##") + " chart ATR each way)" : " | nearby filter off") + " | " + nearbySettingsSource + "; " + keepMainSettingsSource, text_color = color.silver, text_size = size.small)
        table.cell(traceTable, 2, 2, "Confirmed delivery UTC; origins retrospective. Inversion = omitted mode-eligible candidate with weaker shown and no equal/stronger conflict. Blockers are final-map facts, not selection-order history.", text_color = color.silver, text_size = size.small)
        for row = 0 to 19
            int index = array.size(traceRecords) - 1 - (page - 1) * 20 - row
            if index >= 0
                ZoneTraceRecord event = array.get(traceRecords, index)
                table.cell(traceTable, 0, row + 3, f_traceDate(event.delivered), text_color = color.white, text_size = size.small)
                table.cell(traceTable, 1, row + 3, event.identity + " " + event.eventName, text_color = color.white, text_size = size.small)
                table.cell(traceTable, 2, row + 3, event.detail, text_color = color.silver, text_size = size.small, tooltip = event.detail)
        if array.size(traceRecords) == 0
            table.cell(traceTable, 0, 3, "No matching confirmed lifecycle events in loaded history", text_color = color.silver, text_size = size.small)
    // Sort drawable records for collision layout; parent and zone price anchors stay fixed.
    if array.size(map) > 1
        for i = 0 to array.size(map) - 2
            for j = i + 1 to array.size(map) - 1
                MapLevel left = array.get(map, i)
                MapLevel right = array.get(map, j)
                if left.lo + left.hi > right.lo + right.hi
                    array.set(map, i, right)
                    array.set(map, j, left)
    array<float> labelYs = array.new_float()
    array<float> captionHeights = array.new_float()
    if array.size(map) > 0
        // Bound the visible-candle estimate to the local selected map. Historic spikes must
        // not inflate captions for a compact current range. No axis bounds feed this calculation.
        MapLevel bottomLevel = array.get(map, 0)
        MapLevel topLevel = array.get(map, array.size(map) - 1)
        float mapSpan = math.max(topLevel.hi - bottomLevel.lo, syminfo.mintick * 100)
        float localATR = math.min(snapshotATR, mapSpan / 8.0)
        float viewLow = math.min(nz(captionViewLow, bottomLevel.lo), bottomLevel.lo)
        float viewHigh = math.max(nz(captionViewHigh, topLevel.hi), topLevel.hi)
        float viewSpan = math.min(math.max(viewHigh - viewLow, mapSpan), mapSpan * 1.25 + localATR * 2.0)
        float linePixels = captionSize == "Small" ? 17.0 : captionSize == "Large" ? 25.0 : 21.0
        array<float> gapOffsets = array.new_float()
        array<float> blockMeans = array.new_float()
        array<int> blockCounts = array.new_int()
        float offset = 0.0
        for slot = 0 to array.size(map) - 1
            MapLevel z = array.get(map, slot)
            int lineCount = 1 + array.size(str.split(z.status, "\n"))
            float height = (lineCount * linePixels + 10.0) * viewSpan / labelPaneHeight
            array.push(captionHeights, height)
            float mid = (z.lo + z.hi) * 0.5
            float separation = slot == 0 ? 0.0 : math.max(localATR * labelGap, (array.get(captionHeights, slot - 1) + height) * 0.5)
            offset += separation
            array.push(gapOffsets, offset)
            array.push(blockMeans, mid - offset)
            array.push(blockCounts, 1)
            // Pool adjacent violations: minimum squared displacement subject to clearance.
            // Only colliding groups move; an isolated label stays on its own zone midpoint.
            for mergeAttempt = 0 to slot
                int count = array.size(blockMeans)
                if count > 1
                    float leftMean = array.get(blockMeans, count - 2)
                    float rightMean = array.get(blockMeans, count - 1)
                    if leftMean > rightMean
                        int rightCount = array.pop(blockCounts)
                        int leftCount = array.pop(blockCounts)
                        float rightValue = array.pop(blockMeans)
                        float leftValue = array.pop(blockMeans)
                        array.push(blockMeans, (leftValue * leftCount + rightValue * rightCount) / (leftCount + rightCount))
                        array.push(blockCounts, leftCount + rightCount)
        int labelSlot = 0
        // A positive-price map should not produce captions below zero solely from packing.
        float minimumBase = bottomLevel.lo > 0 ? syminfo.mintick + array.get(captionHeights, 0) * 0.5 : -1e30
        for block = 0 to array.size(blockMeans) - 1
            float blockY = math.max(array.get(blockMeans, block), minimumBase)
            for member = 0 to array.get(blockCounts, block) - 1
                array.push(labelYs, blockY + array.get(gapOffsets, labelSlot))
                labelSlot += 1
        // Draw fixed zones with their independently packed captions.
        for slot = 0 to array.size(map) - 1
            MapLevel z = array.get(map, slot)
            color drawTint = zoneColorBy == "Importance" ? f_priorityColor(z.priority) : z.tint
            float mid = (z.lo + z.hi) * 0.5
            float labelY = array.get(labelYs, slot)
            // Only selected, visible zones receive guides; no fabricated wick or backdated solid band.
            if (f_originLineVisible(z.priority) or f_confirmationVisible(z.priority)) and not na(z.origin)
                SwingBirthOrigin origin = z.origin
                if not na(origin.start) and not na(origin.finish) and origin.start < z.born and origin.finish <= origin.firstConfirm and origin.firstConfirm <= z.born
                    string originTip = not na(parentOrigins) and (z.freshnessKey == f_freshParentKey(1) or z.freshnessKey == f_freshParentKey(-1)) ? f_originTooltip(origin, z.freshnessKey == f_freshParentKey(1) ? "Upper" : "Lower") : f_zoneOriginTooltip(origin, z.born, f_captionHeading(z.heading))
                    if f_originLineVisible(z.priority)
                        array.push(lines, line.new(origin.start, origin.price, z.born, origin.price, xloc = xloc.bar_time, color = color.new(drawTint, 15), style = line.style_dashed, width = 1))
                    if f_confirmationVisible(z.priority)
                        array.push(captions, label.new(z.born, origin.price, "", xloc = xloc.bar_time, style = label.style_diamond, color = drawTint, size = size.tiny, tooltip = originTip))
            array.push(boxes, box.new(z.born, z.hi, snapshotTime, z.lo, xloc = xloc.bar_time, extend = extend.right, border_color = color.new(drawTint, 45), bgcolor = color.new(drawTint, 90)))
            array.push(lines, line.new(z.born, mid, snapshotTime, mid, xloc = xloc.bar_time, extend = extend.right, color = color.new(drawTint, 15), style = line.style_solid))
            if captionLayout == "Linked labels" and math.abs(labelY - mid) >= syminfo.mintick
                array.push(lines, line.new(snapshotBar + 2, mid, snapshotBar + labelOffset, labelY, xloc = xloc.bar_index, color = color.new(drawTint, 30), width = 1))
            string caption = (showPriorityTags ? "P" + str.tostring(z.priority) + " " : "") + f_captionHeading(z.heading) + " | " + z.evidence + "\n" + str.tostring(z.lo, format.mintick) + " - " + str.tostring(z.hi, format.mintick) + f_freshBadge(z.freshnessKey) + f_captionStatus(z.status)
            string textSize = captionSize == "Small" ? size.small : captionSize == "Large" ? size.large : size.normal
            if captionLayout == "Linked labels"
                array.push(captions, label.new(snapshotBar + labelOffset, labelY, caption, xloc = xloc.bar_index, style = label.style_label_left, color = color.new(drawTint, 25), textcolor = color.white, size = textSize, tooltip = z.tooltip + f_freshTooltip(z.freshnessKey, z.born, z.priority == 1)))
            else
                // Descending prices mirror the chart. Fixed rows have no price-axis collision.
                string dockCaption = (showPriorityTags ? "P" + str.tostring(z.priority) + " " : "") + f_captionHeading(z.heading) + "\n" + str.tostring(z.lo, format.mintick) + " - " + str.tostring(z.hi, format.mintick) + f_freshBadge(z.freshnessKey)
                string dockTip = z.evidence + f_captionStatus(z.status) + "\n" + z.tooltip + f_freshTooltip(z.freshnessKey, z.born, z.priority == 1)
                table.cell(captionDock, 0, array.size(map) - slot, dockCaption, bgcolor = color.new(drawTint, 35), text_color = color.white, text_size = textSize, tooltip = dockTip)
        if captionLayout == "Docked list"
            string profileText = activeProfile == 0 ? "Global display" : "Symbol profile " + str.tostring(activeProfile)
            string dockConfirmation = displayMode == "Structure + internal levels" and parentActive and showP1 and shownParents > 0 and f_confirmationVisible(1) and not na(parentOrigins) ? "\nRange confirmed " + str.format_time(parentOrigins.rangeBorn, "yyyy-MM-dd HH:mm", "UTC") + " UTC" : ""
            table.cell(captionDock, 0, 0, profileText + " | " + str.tostring(array.size(map)) + "/" + str.tostring(visible) + " zones" + dockConfirmation, bgcolor = color.new(color.black, 12), text_color = color.silver, text_size = size.small, tooltip = "Highest-priced zone is at the top. Hover a row to learn what the area means, why it has its priority, and whether a break or return test is confirmed. A symbol profile replaces the global display choices for its exact symbol. The list only changes label placement." + (dockConfirmation != "" ? "\n" + f_rangeConfirmationTooltip() : ""))
            // Transparent screen-space gutter protects captions from axis price badges.
            table.cell(captionDock, 1, 0, "", width = 8, bgcolor = color.new(color.black, 100))
    if showDashboard and details and not showHierarchyCandidates and array.size(selected) > 0
        for slot = 0 to math.min(9, array.size(selected) - 1)
            Zone z = array.get(zones, array.get(selected, slot))
            string state = z.pending == 0 ? "idle" : z.structural ? "structural " + str.tostring(snapshotBar - z.structuralBar) : "local " + str.tostring(snapshotBar - z.breachBar)
            f_cell(19 + slot, "#" + str.tostring(z.id) + " " + state, str.tostring(z.lo, format.mintick) + " / " + str.tostring(z.hi, format.mintick) + " gov=" + f_tfName(z.govTF, z.govSeconds) + " rej=" + str.tostring(f_recentRejections(z)))
    if showLegend
        string sourceSummary = f_tfName(tf1, sec1) + "/" + f_tfName(tf2, sec2) + "/" + f_tfName(tf3, sec3)
        string ignored = valid1 and valid2 and valid3 ? "" : " | some sources ignored"
        table.cell(legend, 0, 0, displayMode + " | " + sourceSummary + " | confirmed" + ignored, text_color = color.white, text_size = size.small, tooltip = "MTF means multiple timeframes. The times shown are the candles used to find zones. Only closed candles update the model. A source is ignored if it is below the chart timeframe or repeats another source. Current labels describe the latest closed-candle state; they are not a history of every past label.")
        // V22 shownParents counts only boundaries admitted by freshness
        string mapCounts = displayMode == "Structure + internal levels" ? (parentActive ? "Frozen parent" + (showP1 ? "" : " (hidden)") + " | " + str.tostring(math.max(0, array.size(map) - shownParents)) + " internal | gov " + parentGovTF : "WAITING for confirmed structural pair | context only") : displayMode == "Major + range boundaries" ? str.tostring(majorShown) + " major + " + str.tostring(rangeShown) + " range + " + str.tostring(outerShown) + " outer | " + str.tostring(majorCount) + " strict major eligible" : str.tostring(array.size(selected)) + " shown / " + str.tostring(eligible) + " eligible"
        bool anyTier = showP1 or showP2 or showP3 or showP4
        string summary = not (showFreshZones or showOnceTested or showRepeated) ? "All freshness categories hidden" : not anyTier ? "All importance tiers hidden" : array.size(map) == 0 and displayMode != "Structure + internal levels" ? "No confirmed levels match this view" : mapCounts + " | fixed zone bounds" + (activeProfile == 0 ? " | global display" : " | symbol profile " + str.tostring(activeProfile))
        table.cell(legend, 0, 1, summary, text_color = color.silver, text_size = size.small, tooltip = "Main range means the confirmed top and bottom boundaries; internal levels sit between them. Fixed zone bounds means those price edges do not move after creation. Waiting means enough qualifying high/low evidence has not yet formed a main range. Global display uses shared defaults; symbol profile uses the first matching enabled profile. Eligible means a zone passes this view's filters, but it can still be hidden by overlap or the visible limit.")
    if showDashboard or showHierarchyCandidates
        f_cell(0, "Confirmed MTF zones", "Snapshot ranking; fixed bounds")
        f_cell(1, "Sources", f_tfStatus(tf1, valid1) + " | " + f_tfStatus(tf2, valid2) + " | " + f_tfStatus(tf3, valid3))
        f_cell(2, "Pivot observations", str.tostring(array.get(sourceCounts, 0)) + " / " + str.tostring(array.get(sourceCounts, 1)) + " / " + str.tostring(array.get(sourceCounts, 2)))
        f_cell(3, "Loaded chart history", str.format_time(historyStart, "yyyy-MM-dd HH:mm", "UTC") + " UTC")
        f_cell(4, "Confirmed snapshot", na(snapshotTime) ? "warming up" : str.format_time(snapshotTime, "yyyy-MM-dd HH:mm", "UTC") + " UTC")
        f_cell(5, "Retained / created / shown", str.tostring(array.size(zones)) + " / " + str.tostring(created) + " / " + str.tostring(array.size(map)))
        f_cell(6, "Structural / retest / fail / timeout", str.tostring(breaks) + " / " + str.tostring(retests) + " / " + str.tostring(failures) + " / " + str.tostring(expiries))
        f_cell(7, "Confirmed state digest", str.tostring(digest, "0"))
        f_cell(8, "Local breach / local expiry", str.tostring(localBreaches) + " / " + str.tostring(localExpiries))
        f_cell(9, "Rejections / failed defenses", str.tostring(rejectionCount) + " / " + str.tostring(defenseFailures))
        f_cell(10, "Retired / refused admission", str.tostring(retired) + " / " + str.tostring(rejectedAdmissions))
        f_cell(11, "Major eligible / retained", str.tostring(majorCount) + " / " + str.tostring(array.size(zones)))
        f_cell(12, "Limits / availability", "Weakest eligible zone retired; " + str.tostring(eventLimit) + " events; pivots delayed " + str.tostring(strength) + " source bars + confirmed delivery")
        f_cell(13, "Structural parent", parentActive ? str.tostring(parentLow.lo, format.mintick) + " / " + str.tostring(parentHigh.hi, format.mintick) + " gov=" + parentGovTF : "WAITING")
        f_cell(14, "Swing registry / retired", str.tostring(array.size(swings)) + " / " + str.tostring(swingRetired))
        f_cell(15, "Range formed / broken / expired", str.tostring(parentFormations) + " / " + str.tostring(parentBreaks) + " / " + str.tostring(parentExpiries))
        f_cell(16, "Structural registry digest", str.tostring(structureDigest, "0"))
        f_cell(17, "Key-role snapshot / former profiles", str.tostring(keyRoleCount) + " / " + str.tostring(array.size(formerBoundaries)))
        f_cell(18, "Role metadata digest", str.tostring(hierarchyDigest, "0"))
    if showHierarchyCandidates and array.size(zones) > 0
        array<int> listed = array.new_int()
        for row = 0 to math.min(9, array.size(zones) - 1)
            int best = -1
            float bestRank = -1e30
            for i = 0 to array.size(zones) - 1
                Zone z = array.get(zones, i)
                if not array.includes(listed, i)
                    int side = z.hi < snapshotClose ? -1 : 1
                    [significance, swingStrength] = f_keyFacts(z)
                    float roleRank = f_rolePriority(z, side)
                    float rank = roleRank >= 0 ? roleRank : significance * 100.0 + f_score(z)
                    if rank > bestRank
                        bestRank := rank
                        best := i
            if best >= 0
                array.push(listed, best)
                Zone z = array.get(zones, best)
                [significance, swingStrength] = f_keyFacts(z)
                int side = z.hi < snapshotClose ? -1 : 1
                string state = z.pending == 0 ? "idle" : z.structural ? "break" : "local"
                f_cell(19 + row, "#" + str.tostring(z.id) + " T" + str.tostring(f_roleTier(z)) + " C" + str.tostring(significance) + " " + state, str.tostring(z.lo, format.mintick) + " / " + str.tostring(z.hi, format.mintick) + " rank=" + str.tostring(f_rolePriority(z, side), "#.0") + (f_insideParent(z) ? "" : " outside parent"))
plot(hierarchyDigest, "Role hierarchy metadata digest", display = display.data_window)
plot(keyRoleCount, "Key role shelves at confirmed snapshot", display = display.data_window)
plot(array.size(formerBoundaries), "Former parent boundary profiles", display = display.data_window)
plot(structureDigest, "Structural registry digest", display = display.data_window)
plot(array.size(swings), "Confirmed swing clusters", display = display.data_window)
plot(parentActive ? 1 : 0, "Structural parent active", display = display.data_window)
plot(parentFormations, "Structural parent formations", display = display.data_window)
plot(parentBreaks, "Structural parent breaks", display = display.data_window)
plot(parentExpiries, "Structural parent expiries", display = display.data_window)
plot(parentActive ? parentLow.lo : na, "Structural range lower boundary", display = display.data_window)
plot(parentActive ? parentHigh.hi : na, "Structural range upper boundary", display = display.data_window)
plot(digest, "Confirmed state digest", display = display.data_window)
plot(created, "Created zones", display = display.data_window)
plot(array.size(zones), "Retained zones", display = display.data_window)
plot(breaks, "Structural breaks", display = display.data_window)
plot(retests, "Confirmed retests", display = display.data_window)
plot(failures, "Failed breaks", display = display.data_window)
plot(expiries, "Retest timeouts", display = display.data_window)
plot(localBreaches, "Local breaches", display = display.data_window)
plot(localExpiries, "Local breach timeouts", display = display.data_window)
plot(rejectionCount, "Defended rejections", display = display.data_window)
plot(defenseFailures, "Failed defenses", display = display.data_window)
plot(retired, "Retired zones", display = display.data_window)
plot(rejectedAdmissions, "Refused candidate admissions", display = display.data_window)
plot(majorCount, "Major eligible zones", display = display.data_window)
// BEGIN V26 ZONE ALERT DIAGNOSTICS
plot(array.get(noticeCounters, 0), "Zone alert raw candidates", display = display.data_window)
plot(array.get(noticeCounters, 1), "Zone alert included events / runtime", display = display.data_window)
plot(array.get(noticeCounters, 2), "Zone alert batch calls / runtime", display = display.data_window)
plot(array.get(noticeCounters, 3), "Zone alert last batch included", display = display.data_window)
plot(array.get(noticeCounters, 4), "Zone alert last batch omitted", display = display.data_window)
// END V26 ZONE ALERT DIAGNOSTICS
 
alertcondition(localUp, "Local upward breach", "{{ticker}}: local upward breach; governing-timeframe confirmation may still be pending.")
alertcondition(localDown, "Local downward breach", "{{ticker}}: local downward breach; governing-timeframe confirmation may still be pending.")
alertcondition(brokeUp, "Structural upward break", "{{ticker}}: governing-timeframe upward zone break confirmed on {{interval}}.")
alertcondition(brokeDown, "Structural downward break", "{{ticker}}: governing-timeframe downward zone break confirmed on {{interval}}.")
alertcondition(retestUp, "Confirmed support retest", "{{ticker}}: broken resistance retested as support on {{interval}}.")
alertcondition(retestDown, "Confirmed resistance retest", "{{ticker}}: broken support retested as resistance on {{interval}}.")
alertcondition(failed, "Zone setup failed", "{{ticker}}: local or structural zone setup failed on {{interval}}.")
alertcondition(expired, "Zone setup window expired", "{{ticker}}: local-confirmation or structural-retest window expired on {{interval}}.")
alertcondition(defenseConfirmed, "Directional rejection confirmed", "{{ticker}}: directional defended zone rejection confirmed on {{interval}}.")

← 返回列表