Wave Atlas Elliott 1-5 + ABC

IlSeparatio369 · study · 1366 行 · 点赞 26 · TradingView 原页

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

Pine Script

//@version=6
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 IlSeparatio369
// License text: https://www.mozilla.org/MPL/2.0/
indicator("IlSeparatio Wave Atlas - Elliott 1–5 + ABC", "Wave Atlas Elliott", overlay=true, scale=scale.none, max_lines_count=64, max_labels_count=48, max_boxes_count=2)
 
// Automatic mode follows a confirmed bullish impulse. The BTC study is a
// dated reconstruction of two competing counts from the same October 2025 top.
mode = input.string("Automatic", "Mode", options=["Automatic", "BTC cycle study"], group="Count", tooltip="Automatic uses the current instrument and timeframe. BTC cycle study fixes the historical anchors on standard time-based BITSTAMP:BTCUSD charts. Signals and audit windows use your chart interval.")
pivotBars = input.int(3, "Pivot bars per side", minval=1, maxval=30, group="Count", tooltip="A raw pivot needs this many bars on its right. It is locked only when a qualifying opposite pivot is accepted.")
atrFilter = input.float(1.5, "Minimum swing (ATR)", minval=0, maxval=20, step=0.25, group="Count", tooltip="Uses ATR(14) on the raw pivot bar. Increase this to filter smaller legs.")
acceptBars = input.int(2, "Closes to accept a break", minval=2, maxval=5, group="Break and retest", tooltip="Consecutive closes below the A low after applying the optional ATR buffer.")
acceptAtr = input.float(0.15, "Break buffer (ATR)", minval=0, maxval=3, step=0.05, group="Break and retest", tooltip="An acceptance close must be below A by more than this fraction of current ATR(14).")
retestAtr = input.float(0.15, "Retest distance (ATR)", minval=0, maxval=2, step=0.05, group="Break and retest", tooltip="After acceptance, the bar's high must get within this distance of A and its close must stay below A.")
layout = input.string("Research", "Dashboard layout", options=["Compact", "Research", "Audit", "Benchmark"], group="Display", tooltip="Compact shows the core count, Research shows wave geometry, Audit shows target outcomes, and Benchmark shows the symmetric price test and its journal.")
showResearch = input.bool(true, "Show price and time analysis", group="Display", tooltip="Shows projection prices, price-time geometry, correction depth, and completed annual candles in the BTC study.")
showFan = input.bool(true, "Show price and time paths", group="Display", tooltip="Three dashed paths join the B anchor and hypothetical C endpoints. The paths illustrate log-price scenarios and calendar-time assumptions.")
structureView = input.string("Structure only", "Confirmed structure", options=["When no live A/B", "Structure only", "Off"], group="Display", tooltip="Automatic mode. Structure only shows chart-native, confirmed bullish and bearish impulses and their zigzag corrections. The fallback option displays structure when the original count has no live A/B. Alerts and audit use the original count.")
structurePivotBars = input.int(2, "Structure pivot bars per side", minval=1, maxval=20, group="Display", tooltip="Separate display setting. A swing requires closed bars on the right and is locked when an opposite pivot qualifies. The original audit pivot input remains separate.")
structureNoiseMode = input.string("Robust", "Swing noise filter", options=["Robust", "Manual"], group="Elliott precision", tooltip="Robust mode uses the larger of the median true ranges at the two pivot anchors. It ignores individual range spikes more readily than an average and scales to the chart interval. Manual uses the ATR and bar-spacing settings alone.")
structureNoiseMultiple = input.float(0.75, "Median range multiplier", minval=0.0, maxval=5.0, step=0.05, group="Elliott precision", tooltip="Minimum reversal as a multiple of the larger trailing 21-bar median true range at either pivot. This is a swing filter, not a measure of predictive accuracy.")
structureFlat = input.bool(false, "Allow flat-shaped corrections", group="Elliott precision", tooltip="Adds price-only flat-shaped candidates when B retraces 90% to 138% of A. Confirmation requires C to extend beyond A. Internal 3-3-5 subdivisions are not tested.")
showElliottProjection = input.bool(false, "Show pending C reference levels", group="Elliott precision", tooltip="After B locks, projects 1.000 and 1.618 times A from B in the correction direction. Levels are geometric references and are retired when C resolves or the candidate invalidates.")
structureMinAtr = input.float(0.0, "Minimum opposite swing (ATR)", minval=0, maxval=10, step=0.1, group="Display", tooltip="Filters small alternating swings using ATR(14) at the incoming pivot. Zero disables the filter.")
structureMinBars = input.int(1, "Minimum bars between opposite pivots", minval=1, maxval=100, group="Display", tooltip="Minimum spacing between opposite pivots on the chart interval.")
structureHistory = input.int(18, "Locked swings to show", minval=6, maxval=28, group="Display", tooltip="Recent locked swings kept on this chart interval. The last numbered cycle also stays visible, subject to chart drawing limits.")
showDevelopingLeg = input.bool(true, "Show developing swing", group="Display", tooltip="Dotted line to the current unlocked pivot and, when different, to the latest closed price. It can change after a close and never issues a wave alert.")
showInvalidCount = input.bool(false, "Keep invalidated wave drawings", group="Display", tooltip="Keep the last numbered impulse and partial correction visible after zigzag invalidation.")
showElliottResearch = input.bool(false, "Show research panels in Elliott view", group="Display", tooltip="Shows the original correction research and audit panels alongside Elliott structure.")
structureYearlyFast = input.bool(true, "Use one bar per side on yearly charts", group="Display", tooltip="Uses a shorter pivot window on 12-month charts, where history is often sparse. The opposite-pivot lock and five-wave rules still apply.")
showRoad = input.bool(false, "Show continuation levels and BTC milestones", group="Display", tooltip="Annotates the confirmed A and B levels. In BTC cycle study, adds the previous cycle low and the midpoint of your custom zone.")
showMarkers = input.bool(true, "Show new confirmation markers", group="Display", tooltip="Dots mark break acceptance, a rejected retest, and a reclaim on the bars that closed with those facts.")
showHelp = input.bool(true, "Show on-chart help", group="Display", tooltip="Hover on the dashboard, path, and milestone labels to learn how each component is calculated.")
showValidation = input.bool(true, "Show forward audit", group="Forward audit", tooltip="Freezes a fully formed count on a closed bar. The next bar's open determines whether the case is eligible.")
auditFrom = input.time(timestamp("16 Nov 2026 00:00 +0000"), "First eligible close (UTC)", group="Forward audit", tooltip="The default starts after the dated BTC study snapshot. Earlier dates support historical research and can include reconstructed or fitted cases.")
auditHorizon = input.int(36, "Outcome window (chart bars)", minval=2, maxval=300, group="Forward audit", tooltip="Includes the opening bar. A target wick must occur before the B level is touched and before the window expires.")
showPaired = input.bool(true, "Show matched 3-target study", group="Forward audit", tooltip="Compares 0.786, 1.000 and 1.272 log-leg targets on the same completed cases with the same entry, B boundary, and horizon.")
showFrozen = input.bool(false, "Show frozen audit levels", group="Forward audit", tooltip="Draws the issued target and B boundary plus the reference opening price when known. Extends only while the latest case is pending.")
showData = input.bool(false, "Show audit fields in Data Window", group="Forward audit", tooltip="Displays the values and event flags recorded at each confirmed chart close. Rule settings and chart series determine the sample.")
showRace = input.bool(false, "Show frozen benchmark corridor", group="Directional benchmark", tooltip="Plots the benchmark's fixed reference open and its mirrored price boundaries. These levels are a scoring reference.")
raceMinTicks = input.int(2, "Minimum ticks on each side", minval=1, maxval=100, group="Directional benchmark", tooltip="Skips corridors where rounding leaves either side less than this many instrument ticks from the open.")
raceMaxSkew = input.float(5.0, "Maximum log-width imbalance (%)", minval=0.1, maxval=25.0, step=0.5, group="Directional benchmark", tooltip="After tick rounding, compares the difference between the two log distances with the larger one. A case beyond the limit is skipped.")
auditMinimum = input.int(30, "Minimum scored cases", minval=10, maxval=200, group="Forward audit", tooltip="Below this number the rate is tagged Unvalidated. A larger sample does not remove serial dependence or selection bias.")
showOverlap = input.bool(false, "Shade overlapping C projections", group="Display", tooltip="Intersection of the two 0.786 to 1.272 Wave A log-extension bands. Teal shading represents geometric agreement between dependent counts.")
showLedger = input.bool(false, "Show last six count events", group="Display", tooltip="Lists the latest close-confirmed count events and prices. The audit evaluates frozen cases independently.")
showArchive = input.bool(true, "Show earlier count", group="Display", tooltip="Shows the smaller correction in teal. Its lower low may also serve as A of the larger amber correction.")
showProjection = input.bool(true, "Show equal log-leg projection", group="Display", tooltip="Projects C with the same percentage decline as A. The projected price is a geometric reference.")
showZone = input.bool(false, "Show custom Wave 2 zone (BTC study)", group="Display", tooltip="Plots your editable price zone across 2028. It represents your large Wave 2 thesis.")
studyOrigin = input.float(2, "BTC study Wave 1 origin", minval=0.01, group="Count", tooltip="Starting price for your long-range Wave 1. A confirmed bar with a low below it invalidates the bullish impulse premise.")
zoneLow = input.float(700, "Zone lower price", minval=0.01, group="Display", tooltip="One edge of your theoretical larger Wave 2 endpoint. The script sorts both edges.")
zoneHigh = input.float(1000, "Zone upper price", minval=0.01, group="Display", tooltip="The other edge of your theoretical larger Wave 2 endpoint. It also feeds the required log-move calculation.")
jsonAlerts = input.bool(false, "Send dynamic JSON alerts", group="Alerts", tooltip="Select Any alert() function call in TradingView. Events use closed candles.")
 
color teal = #39C9B4
color amber = #E9B568
color silver = #A5B4C9
color panel = #171F2D
color muted = #95A5B9
 
type Swing
    float price
    int at
    int side
 
type Count
    Swing a = na
    Swing b = na
    Swing c = na
    int state = 0
    bool archived = false
 
type StructurePivot
    float price
    int at
    int index
    int side
    int lockedAt
    int lockedOn
    float noiseRange
 
type ClosePoint
    int at
    int index
    float price
 
// Swing objects are immutable by convention. Replacing the open swing
// changes its array slot. A returned locked swing keeps its original values.
type Race
    int issueBar = na
    int issueAt = na
    int entryAt = na
    int finishAt = na
    int serial = 0
    int regime = 0
    float c = na
    float b = na
    float atrAtIssue = na
    float entry = na
    float lower = na
    float upper = na
    float skew = na
    float widthAtr = na
    int result = 0
 
type RaceRecord
    int serial
    int closedAt
    int result
    int regime
    int bars
 
acceptSwing(array<Swing> swings, Swing incoming, float threshold) =>
    Swing locked = na
    int size = array.size(swings)
    if size == 0
        array.push(swings, incoming)
    else
        Swing tail = array.get(swings, size - 1)
        if incoming.at > tail.at
            float directedMove = (incoming.price - tail.price) * incoming.side
            if incoming.side == tail.side
                if directedMove > 0
                    array.set(swings, size - 1, incoming)
            else if directedMove > 0 and directedMove >= threshold
                locked := tail
                array.push(swings, incoming)
                if array.size(swings) > 7
                    array.shift(swings)
    locked
 
saveStructurePivot(array<StructurePivot> pivots, StructurePivot incoming, int lockTime, int lockIndex, float minMove, int minBars, float noiseMultiple, int historySize) =>
    bool locked = false
    int n = array.size(pivots)
    if n == 0
        array.push(pivots, incoming)
    else
        StructurePivot tail = array.last(pivots)
        if incoming.index > tail.index
            float move = (incoming.price - tail.price) * incoming.side
            if move > 0
                if incoming.side == tail.side
                    array.set(pivots, n - 1, incoming)
                else if move >= math.max(minMove, noiseMultiple * math.max(tail.noiseRange, incoming.noiseRange)) and incoming.index - tail.index >= minBars
                    tail.lockedAt := lockTime
                    tail.lockedOn := lockIndex
                    locked := true
                    array.push(pivots, incoming)
                    if array.size(pivots) > historySize + 1
                        array.shift(pivots)
    locked
 
structureImpulse(array<StructurePivot> pivots) =>
    int result = 0
    // Six locked pivots plus one unplotted candidate. Reflect prices for bearish impulses.
    if array.size(pivots) >= 7
        int first = array.size(pivots) - 7
        StructurePivot start = array.get(pivots, first)
        int direction = -start.side
        float p0 = start.price * direction
        float p1 = array.get(pivots, first + 1).price * direction
        float p2 = array.get(pivots, first + 2).price * direction
        float p3 = array.get(pivots, first + 3).price * direction
        float p4 = array.get(pivots, first + 4).price * direction
        float p5 = array.get(pivots, first + 5).price * direction
        if p2 > p0 and p3 > p1 and p4 > p1 and p5 > p3
            float w1 = p1 - p0
            float w3 = p3 - p2
            float w5 = p5 - p4
            if w3 >= math.min(w1, w5)
                result := direction
    result
 
// Strict rising impulse rules plus a higher fifth wave.
isImpulse(array<Swing> swings) =>
    bool valid = false
    if array.size(swings) == 7
        Swing p0 = array.get(swings, 0)
        Swing p1 = array.get(swings, 1)
        Swing p2 = array.get(swings, 2)
        Swing p3 = array.get(swings, 3)
        Swing p4 = array.get(swings, 4)
        Swing p5 = array.get(swings, 5)
        if p0.side == -1 and p0.price > 0 and p2.price > p0.price and p3.price > p1.price and p4.price > p1.price and p5.price > p3.price
            float w1 = p1.price - p0.price
            float w3 = p3.price - p2.price
            float w5 = p5.price - p4.price
            valid := w3 >= math.min(w1, w5)
    valid
 
ready(Count count) =>
    not na(count.a) and not na(count.b)
 
// The wick records swing evidence. Only closing prices change alert states.
updateCount(Count count, float barClose, float barLow) =>
    int event = 0
    if ready(count) and not count.archived and count.state < 3
        if barClose > count.b.price
            count.state := 3
            event := -1
        else if barClose < count.a.price and count.state < 2
            count.state := 2
            event := 1
        else if barLow < count.a.price and count.state == 0
            count.state := 1
    event
 
// Positive directional efficiency means downside dominates the observed
// close-to-close log path. Values range from -1 to +1 when there is movement.
percentText(float value) =>
    na(value) ? "—" : str.tostring(value * 100.0, "0.0") + "%"
 
wilson(int wins, int total) =>
    float lower = na
    float upper = na
    if total > 0
        float z = 1.959963985
        float n = float(total)
        float p = float(wins) / n
        float den = 1.0 + z * z / n
        float mid = (p + z * z / (2.0 * n)) / den
        float halfWidth = z * math.sqrt((p * (1.0 - p) + z * z / (4.0 * n)) / n) / den
        lower := math.max(0.0, mid - halfWidth)
        upper := math.min(1.0, mid + halfWidth)
    [lower, upper]
 
// Event order uses the opening print before an unknown intrabar sequence.
// Values: 1 target, -1 boundary, -2 both (conservative), -3 timeout, 0 unresolved.
auditBar(float target, float boundary, float openPx, float highPx, float lowPx, bool deadline) =>
    int result = 0
    if openPx >= boundary
        result := -1
    else if openPx <= target
        result := 1
    else if highPx >= boundary
        result := lowPx <= target ? -2 : -1
    else if lowPx <= target
        result := 1
    else if deadline
        result := -3
    result
 
scoreText(int hits, int total) =>
    total > 0 ? str.tostring(hits) + " / " + str.tostring(total) + " · " + percentText(float(hits) / float(total)) : "0 / 0 · —"
 
// Sum the smaller binomial tail in log space. Converting very small
// probabilities to decimal is unnecessary for the panel's display precision.
signLogProbability(int down, int up) =>
    int n = down + up
    float logP = na
    if n > 0 and n <= 512
        int tail = math.min(down, up)
        float logTerm = float(n) * math.log(0.5)
        float logTail = logTerm
        if tail > 0
            for k = 1 to tail
                logTerm += math.log(float(n - k + 1) / float(k))
                logTail := logTerm + math.log(1.0 + math.exp(logTail - logTerm))
        logP := math.min(0.0, math.log(2.0) + logTail)
    logP
 
raceText(int result) =>
    switch result
        1 => "Downside first"
        -1 => "Upside first"
        -2 => "Both · order unknown"
        -3 => "Timed out"
        -4 => "Skipped · first open outside"
        -5 => "Skipped · tick geometry"
        => "Waiting"
 
regimeText(int regime) =>
    regime == 1 ? "Elevated ATR" : regime == -1 ? "Normal / lower ATR" : "No ATR baseline"
 
racePct(int down, int up) =>
    int n = down + up
    n > 0 ? percentText(float(down) / float(n)) + " · " + str.tostring(down) + "/" + str.tostring(n) : "— · 0/0"
 
priceText(float value) =>
    na(value) ? "—" : str.tostring(value, format.mintick)
 
stateText(Count count) =>
    string result = "Waiting for A"
    if not na(count.a)
        result := "Waiting for B"
    if ready(count)
        result := switch count.state
            1 => "Lower wick"
            2 => "Close below A"
            3 => "Close above B"
            => "Watching A"
    if count.archived
        result := count.state == 3 ? "Archived · invalidated" : "Archived · lower low"
    result
 
// Each multiplier scales the logarithmic size of A from B. A multiplier
// of 1 projects the same percentage decline as A.
logProjection(Swing top, Count count, float multiplier) =>
    float value = na
    if not na(top) and ready(count)
        if top.price > count.a.price and count.a.price > 0 and count.b.price > 0
            value := count.b.price * math.pow(count.a.price / top.price, multiplier)
    value
 
logMultiple(Swing top, Count count, float target) =>
    float multiple = na
    if not na(top) and ready(count)
        if top.price > count.a.price and count.a.price > 0 and count.b.price > 0 and target > 0
            multiple := math.log(count.b.price / target) / math.log(top.price / count.a.price)
    multiple
 
ratioText(float value) =>
    na(value) ? "—" : str.tostring(value, "#.##") + "×"
 
dateText(int value) =>
    na(value) ? "—" : str.format_time(value, "yyyy-MM-dd", "UTC")
 
utcText(int value) =>
    na(value) ? "—" : str.format_time(value, "yyyy-MM-dd HH:mm", "UTC")
 
jsonString(string value) =>
    string escaped = str.replace_all(value, "\\", "\\\\")
    escaped := str.replace_all(escaped, '"', '\\"')
    escaped := str.replace_all(escaped, "\n", "\\n")
    escaped := str.replace_all(escaped, "\r", "\\r")
    escaped := str.replace_all(escaped, "\t", "\\t")
    '"' + escaped + '"'
 
annualText(int yearValue, float yearOpen, float yearClose) =>
    string result = "—"
    if not na(yearValue) and not na(yearOpen) and not na(yearClose)
        result := str.tostring(yearValue) + (yearClose < yearOpen ? " red" : yearClose > yearOpen ? " green" : " flat")
    result
 
researchRow(table grid, int row, string title, string value, color ink, string hint="") =>
    table.cell(grid, 0, row, title, text_color=muted, text_size=size.small, text_halign=text.align_left, tooltip=showHelp ? hint : "")
    table.cell(grid, 1, row, value, text_color=ink, text_size=size.small, text_halign=text.align_left, tooltip=showHelp ? hint : "")
 
note(array<label> ids, int at, float price, string caption, color ink, string explanation) =>
    array.push(ids, label.new(at, price, caption, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(ink, 80), textcolor=ink, size=size.tiny, tooltip=showHelp ? explanation : ""))
    0
 
pricePath(array<line> ids, array<label> tags, Swing start, float endPrice, int endsAt, color ink, string caption, string hint) =>
    if endPrice > 0 and start.price > 0 and endsAt > start.at
        int previousAt = start.at
        float previousPrice = start.price
        for step = 1 to 4
            float fraction = float(step) / 4.0
            int nextAt = start.at + int(math.round((endsAt - start.at) * fraction))
            float nextPrice = start.price * math.pow(endPrice / start.price, math.pow(fraction, 1.25))
            array.push(ids, line.new(previousAt, previousPrice, nextAt, nextPrice, xloc=xloc.bar_time, color=ink, style=line.style_dashed))
            previousAt := nextAt
            previousPrice := nextPrice
        note(tags, endsAt, endPrice, caption + " " + priceText(endPrice), ink, hint)
    0
 
level(array<line> ids, int leftAt, float price, int rightAt, color ink, string pattern, bool project=false) =>
    if rightAt > leftAt
        array.push(ids, line.new(leftAt, price, rightAt, price, xloc=xloc.bar_time, extend=project ? extend.right : extend.none, color=ink, style=pattern))
    0
 
segment(array<line> ids, Swing left, Swing right, color ink) =>
    array.push(ids, line.new(left.at, left.price, right.at, right.price, xloc=xloc.bar_time, color=ink, width=2))
    0
 
tag(array<label> ids, Swing point, string caption, color ink) =>
    array.push(ids, label.new(point.at, point.price, caption, xloc=xloc.bar_time, color=color.new(ink, 78), textcolor=ink, style=point.side == 1 ? label.style_label_down : label.style_label_up, size=size.small, tooltip="Historical swing location. The count and alerts become available only after confirmation."))
    0
 
drawCount(array<line> lines, array<label> labels, Swing top, Count count, color ink, string suffix, int rightAt, bool projection) =>
    if not na(count.a)
        segment(lines, top, count.a, ink)
        tag(labels, count.a, "A" + suffix, ink)
        if ready(count)
            segment(lines, count.a, count.b, ink)
            tag(labels, count.b, "B" + suffix, ink)
            if not na(count.c)
                segment(lines, count.b, count.c, ink)
                tag(labels, count.c, "C" + suffix, ink)
            if count.state < 3 and not count.archived
                level(lines, count.b.at, count.a.price, rightAt, ink, line.style_dashed, true)
                level(lines, count.b.at, count.b.price, rightAt, ink, line.style_dotted, true)
                float target = logProjection(top, count, 1.0)
                if projection and not na(target)
                    level(lines, count.b.at, target, rightAt, color.new(ink, 35), line.style_dotted, true)
    0
 
structureText(StructurePivot point, StructurePivot previous) =>
    string caption = point.side == 1 ? "H" : "L"
    if not na(previous)
        if point.price == previous.price
            caption := point.side == 1 ? "EQH" : "EQL"
        else if point.side == 1
            caption := point.price > previous.price ? "HH" : "LH"
        else
            caption := point.price > previous.price ? "HL" : "LL"
    caption
 
drawStructure(array<line> strokes, array<label> tags, array<StructurePivot> pivots, int first, int lockedCount, int direction, bool useTime, bool skipFirstTag=false, string correctionType="") =>
    bool isCorrection = correctionType != ""
    string coordinates = useTime ? xloc.bar_time : xloc.bar_index
    color bull = #62D2BA
    color bear = #ED9C92
    for i = first to lockedCount - 1
        StructurePivot point = array.get(pivots, i)
        StructurePivot comparable = i >= 2 ? array.get(pivots, i - 2) : na
        string signal = structureText(point, comparable)
        string caption = direction == 0 or i == 0 ? signal : str.tostring(i) + " · " + signal
        if isCorrection and i > 0
            caption := i == 1 ? "A" : i == 2 ? "B" : "C"
        int pointX = useTime ? point.at : point.index
        color ink = direction == 1 ? bull : direction == -1 ? bear : silver
        if i > first
            StructurePivot previous = array.get(pivots, i - 1)
            int previousX = useTime ? previous.at : previous.index
            color legInk = direction != 0 ? ink : point.price > previous.price ? bull : bear
            array.push(strokes, line.new(previousX, previous.price, pointX, point.price, xloc=coordinates, color=legInk, style=isCorrection ? line.style_dashed : line.style_solid, width=2))
        string seenAt = na(point.lockedAt) ? "bar " + str.tostring(point.lockedOn) : utcText(point.lockedAt) + " UTC"
        string hint = "Swing " + signal + " · " + priceText(point.price) + "\nLocked at " + seenAt + " after an opposite pivot confirmed.\nConfirmation delay: " + str.tostring(point.lockedOn - point.index) + " chart bars."
        if isCorrection
            hint += "\nLocked correction pivot " + caption + " · " + correctionType + "."
            if i >= 2
                float lengthA = math.abs(array.get(pivots, 1).price - array.first(pivots).price)
                float legLength = math.abs(point.price - array.get(pivots, i - 1).price)
                hint += "\n" + caption + " length / A length: " + str.tostring(legLength / lengthA, "0.###") + "×"
        else if direction != 0
            StructurePivot fifth = array.get(pivots, lockedCount - 1)
            string waveKnown = na(fifth.lockedAt) ? "bar " + str.tostring(fifth.lockedOn) : utcText(fifth.lockedAt) + " UTC"
            hint += "\nFive-wave structure recognized at " + waveKnown + "."
            if i > 0
                StructurePivot previous = array.get(pivots, i - 1)
                float magnitude = math.abs(point.price - previous.price)
                int referenceWave = i == 4 ? 3 : 1
                if i > 1
                    float referenceLength = math.abs(array.get(pivots, referenceWave).price - array.get(pivots, referenceWave - 1).price)
                    hint += "\nLength / Wave " + str.tostring(referenceWave) + ": " + str.tostring(magnitude / referenceLength, "0.###") + "×"
                hint += "\nLeg duration: " + str.tostring(point.index - previous.index) + " chart bars."
        if not skipFirstTag or i != first
            array.push(tags, label.new(pointX, point.price, caption, xloc=coordinates, style=point.side == 1 ? label.style_label_down : label.style_label_up, color=color.new(panel, 10), textcolor=ink, size=size.small, tooltip=showHelp ? hint : ""))
    0
 
bool btcStudy = mode == "BTC cycle study"
bool timeBased = not timeframe.isticks
bool btcChart = timeBased and syminfo.prefix == "BITSTAMP" and syminfo.ticker == "BTCUSD"
bool enabled = chart.is_standard and (not btcStudy or btcChart)
bool coarseStudy = enabled and btcStudy and timeframe.in_seconds() > timeframe.in_seconds("1W")
float rawHigh = ta.pivothigh(high, pivotBars, pivotBars)
float rawLow = ta.pivotlow(low, pivotBars, pivotBars)
int structureWidth = structureYearlyFast and timeframe.ismonthly and timeframe.multiplier == 12 ? 1 : structurePivotBars
float structureHigh = ta.pivothigh(high, structureWidth, structureWidth)
float structureLow = ta.pivotlow(low, structureWidth, structureWidth)
var array<StructurePivot> structurePivots = array.new<StructurePivot>()
var array<StructurePivot> completedImpulse = array.new<StructurePivot>()
var int completedDirection = 0
var array<StructurePivot> correction = array.new<StructurePivot>()
var bool correctionInvalid = false
var string correctionType = "Awaiting B geometry"
var string correctionFailure = ""
var ClosePoint closeLegStart = na
var ClosePoint closeLegEnd = na
var int closeLegDirection = 0
float atr = ta.atr(14)
float medianRange = ta.median(ta.tr(true), 21)
float atrShare = close > 0 ? atr / close : na
float atrShareBaseline = ta.ema(atrShare, 34)[1]
float raceTick = syminfo.mintick
var array<Swing> swings = array.new<Swing>()
var array<Swing> impulse = array.new<Swing>()
var Swing top = na
var Count early = Count.new()
var Count larger = Count.new()
var bool topInvalid = false
var bool originInvalid = false
var float originPrice = na
var int availableAt = na
var int trackedBAt = na
var int acceptedAt = na
var int breakStreak = 0
var bool breakActive = false
var bool retested = false
var float confirmedPrice = na
var int pathBAt = na
var float pathFirst = na
var float pathPrevious = na
var float pathLength = 0.0
var int pathSteps = 0
var int seenTopAt = na
var int seenBAt = na
var int auditIssue = na
var int issuedAt = na
var int entryAt = na
var int resolvedAt = na
var float bestClose = na
var float worstClose = na
var int hitBars = 0
var int lastHitBars = na
var int auditSkippedOpen = 0
var int auditSkippedSetup = 0
var Race race = Race.new()
var array<RaceRecord> raceJournal = array.new<RaceRecord>()
var int raceSerial = 0
var int raceDown = 0
var int raceUp = 0
var int raceTies = 0
var int raceTimeout = 0
var int raceSkipOpen = 0
var int raceSkipTick = 0
var int raceConcurrent = 0
var array<int> raceRegimeDown = array.new_int(3, 0)
var array<int> raceRegimeUp = array.new_int(3, 0)
var int pairIssue = na
var float pairB = na
var array<float> pairTargets = array.new_float(3, na)
var array<int> pairOutcomes = array.new_int(3, 0)
var array<int> pairHits = array.new_int(3, 0)
var int pairCompleted = 0
var int pairSkipped = 0
var int largerKnownAt = na
var int breakAttempts = 0
var int breakReclaims = 0
var float maxCloseThrough = 0.0
var float auditTarget = na
var float auditBoundary = na
var float auditEntry = na
var int auditWins = 0
var int auditBoundaryLosses = 0
var int auditTimeouts = 0
var int auditAmbiguous = 0
var int auditConcurrent = 0
var string lastAudit = "Waiting for eligible close"
var array<string> ledgerNames = array.new_string()
var array<int> ledgerTimes = array.new_int()
var array<float> ledgerCloses = array.new_float()
var int lastConfirmedAt = na
int largerEvent = 0
bool topEvent = false
bool originEvent = false
bool acceptEvent = false
bool retestEvent = false
bool failedEvent = false
bool auditIssued = false
bool auditHit = false
bool auditMiss = false
int raceEvent = 0
 
// Automatic and tick charts do not use the BTC-only calendar request.
[yr1, yo1, yc1, yr4, yo4, yc4, yr8, yo8, yc8, yr12, yo12, yc12] = if btcStudy and enabled
    request.security(syminfo.tickerid, "12M", [year[1], open[1], close[1], year[4], open[4], close[4], year[8], open[8], close[8], year[12], open[12], close[12]], lookahead=barmerge.lookahead_on)
else
    [int(na), float(na), float(na), int(na), float(na), float(na), int(na), float(na), float(na), int(na), float(na), float(na)]
 
// The fixed anchors are available from the original weekly cutoff. A long
// developing bar may display them after observing a completed weekly sub-bar.
// This preview supplies no price observations, count events or audit cases.
int studyAvailable = timestamp("GMT+0", 2026, 10, 5, 0, 0)
int previewAt = na
if coarseStudy
    array<int> finishedWeeks = request.security_lower_tf(syminfo.tickerid, "1W", time_close[1], ignore_invalid_timeframe=true)
    if barstate.islast and not barstate.isconfirmed and na(top) and array.size(finishedWeeks) > 0
        int latestWeekClose = array.last(finishedWeeks)
        if not na(latestWeekClose) and latestWeekClose >= studyAvailable
            previewAt := latestWeekClose
 
bool chartClosed = enabled and barstate.isconfirmed
bool studyCloseEligible = time >= studyAvailable or time_close == studyAvailable
bool processClose = chartClosed and (not btcStudy or studyCloseEligible)
bool showStudyAnchors = enabled and btcStudy and na(top) and ((chartClosed and time_close >= studyAvailable) or not na(previewAt))
 
if chartClosed
    lastConfirmedAt := time_close
    confirmedPrice := processClose ? close : na
if showStudyAnchors
    top := Swing.new(126272.0, timestamp("GMT+0", 2025, 10, 6, 0, 0), 1)
    originPrice := studyOrigin
    availableAt := studyAvailable
    if not na(previewAt)
        lastConfirmedAt := previewAt
        confirmedPrice := na
    Swing july = Swing.new(57734.63, timestamp("GMT+0", 2026, 6, 29, 0, 0), -1)
    early := Count.new(Swing.new(59930.0, timestamp("GMT+0", 2026, 2, 2, 0, 0), -1), Swing.new(82833.0, timestamp("GMT+0", 2026, 5, 4, 0, 0), 1), july, 1, true)
    larger := Count.new(july, Swing.new(87373.64, timestamp("GMT+0", 2026, 9, 21, 0, 0), 1))
 
int elliottEvent = 0
bool elliottImpulseConfirmed = false
if chartClosed and not btcStudy and structureView != "Off"
    // Close-to-close structure keeps sparse or one-way charts readable before two pivots lock.
    if na(closeLegEnd)
        closeLegEnd := ClosePoint.new(time, bar_index, close)
    else if close != closeLegEnd.price
        int stepDirection = close > closeLegEnd.price ? 1 : -1
        if closeLegDirection != stepDirection or (not timeBased and bar_index - closeLegStart.index > 9999)
            closeLegStart := closeLegEnd
        closeLegEnd := ClosePoint.new(time, bar_index, close)
        closeLegDirection := stepDirection
 
    float pivotAtr = atr[structureWidth]
    // Both estimates use only data available on their respective pivot bars.
    float pivotNoise = nz(medianRange[structureWidth], nz(pivotAtr, 0.0))
    float noiseMultiple = structureNoiseMode == "Robust" ? structureNoiseMultiple : 0.0
    float minMove = structureMinAtr == 0 ? 0.0 : pivotAtr * structureMinAtr
    bool newlyLocked = false
    if not na(structureHigh) and na(structureLow)
        newlyLocked := saveStructurePivot(structurePivots, StructurePivot.new(structureHigh, time[structureWidth], bar_index[structureWidth], 1, na, na, pivotNoise), time_close, bar_index, minMove, structureMinBars, noiseMultiple, structureHistory)
    else if not na(structureLow) and na(structureHigh)
        newlyLocked := saveStructurePivot(structurePivots, StructurePivot.new(structureLow, time[structureWidth], bar_index[structureWidth], -1, na, na, pivotNoise), time_close, bar_index, minMove, structureMinBars, noiseMultiple, structureHistory)
    if newlyLocked
        bool completedCorrectionNow = false
        if array.size(correction) > 0 and array.size(correction) < 4 and not correctionInvalid
            StructurePivot point = array.get(structurePivots, array.size(structurePivots) - 2)
            StructurePivot fifth = array.first(correction)
            if point.index > array.last(correction).index
                int step = array.size(correction)
                float directedPrice = point.price * completedDirection
                float fifthPrice = fifth.price * completedDirection
                bool valid = false
                if step == 1
                    valid := point.side == -completedDirection and directedPrice < fifthPrice
                else
                    float aPrice = array.get(correction, 1).price * completedDirection
                    if step == 2
                        float retrace = (directedPrice - aPrice) / (fifthPrice - aPrice)
                        bool flatShape = structureFlat and retrace >= 0.90 and retrace <= 1.38
                        valid := point.side == completedDirection and (flatShape or (directedPrice > aPrice and directedPrice < fifthPrice))
                        if valid
                            correctionType := flatShape ? "Flat geometry" : "Zigzag"
                    else
                        valid := point.side == -completedDirection and directedPrice < aPrice
                if valid
                    array.push(correction, point)
                    elliottEvent := step
                    completedCorrectionNow := step == 3
                else
                    correctionInvalid := true
                    correctionFailure := step == 2 ? (structureFlat ? "B outside permitted retracement" : "B outside A–5 range") : step == 3 ? "C did not extend beyond A" : "A on wrong side of 5"
                    elliottEvent := -1
        int impulseDirection = structureImpulse(structurePivots)
        bool canStartCount = array.size(correction) == 0 or correctionInvalid or array.size(correction) == 4
        if impulseDirection != 0 and canStartCount and not completedCorrectionNow
            // Copy only locked pivots. The seventh pivot remains a replaceable candidate.
            array.clear(completedImpulse)
            int first = array.size(structurePivots) - 7
            for i = 0 to 5
                array.push(completedImpulse, array.get(structurePivots, first + i))
            completedDirection := impulseDirection
            array.clear(correction)
            array.push(correction, array.last(completedImpulse))
            correctionInvalid := false
            correctionType := "Awaiting B geometry"
            correctionFailure := ""
            elliottImpulseConfirmed := true
 
if processClose
    if not btcStudy and not na(atr[pivotBars])
        // A bar qualifying as both pivot high and low has unknown swing order.
        Swing locked = na
        if not na(rawHigh) and na(rawLow)
            locked := acceptSwing(swings, Swing.new(rawHigh, time[pivotBars], 1), atr[pivotBars] * atrFilter)
        else if not na(rawLow) and na(rawHigh)
            locked := acceptSwing(swings, Swing.new(rawLow, time[pivotBars], -1), atr[pivotBars] * atrFilter)
        if not na(locked)
            bool canReplaceTop = na(top) ? true : topInvalid or locked.price > top.price
            bool afterTop = na(top) ? false : locked.at > top.at
            if locked.side == 1 and isImpulse(swings) and canReplaceTop
                top := locked
                topInvalid := false
                originInvalid := false
                Swing start = array.get(swings, 0)
                originPrice := start.price
                availableAt := time_close
                trackedBAt := na
                early := Count.new()
                larger := Count.new()
                array.clear(impulse)
                for i = 0 to 5
                    array.push(impulse, array.get(swings, i))
            else if afterTop and not topInvalid
                if locked.side == -1
                    if na(early.a)
                        early.a := locked
                    else if na(early.b) and locked.price < early.a.price
                        early.a := locked
                    else if ready(early)
                        if locked.at > early.b.at and locked.price < early.a.price and na(larger.b)
                            if na(early.c)
                                early.c := locked
                                early.archived := true
                            if na(larger.a)
                                larger.a := locked
                            else if locked.price < larger.a.price
                                larger.a := locked
                    if ready(larger)
                        if locked.at > larger.b.at and locked.price < larger.a.price and na(larger.c) and larger.state < 3
                            larger.c := locked
                else if not na(early.a) and na(early.b) and locked.price > early.a.price and locked.price < top.price
                    early.b := locked
                else if not na(larger.a) and na(larger.b) and locked.price > larger.a.price and locked.price < top.price
                    larger.b := locked
    if btcStudy and ready(larger) and larger.state < 3 and na(larger.c) and not na(rawLow)
        int lowAt = time[pivotBars]
        if lowAt > larger.b.at and (not coarseStudy or lowAt >= studyAvailable) and rawLow < larger.a.price
            larger.c := Swing.new(rawLow, lowAt, -1)
    if not na(top) and not topInvalid
        if not na(originPrice) and low < originPrice
            originInvalid := true
            topInvalid := true
            originEvent := true
            early.state := 3
            larger.state := 3
        else if close > top.price
            topInvalid := true
            topEvent := true
            early.state := 3
            larger.state := 3
        else
            updateCount(early, close, low)
            largerEvent := updateCount(larger, close, low)
 
    if ready(larger) and larger.state < 3 and not topInvalid
        if na(trackedBAt) or trackedBAt != larger.b.at
            trackedBAt := larger.b.at
            largerKnownAt := time_close
            breakAttempts := 0
            breakReclaims := 0
            maxCloseThrough := 0.0
            acceptedAt := na
            breakStreak := 0
            breakActive := false
            retested := false
        float aFloor = larger.a.price
        if close >= aFloor
            failedEvent := breakActive
            if breakActive
                breakReclaims += 1
            acceptedAt := na
            breakStreak := 0
            breakActive := false
            retested := false
        else
            if not breakActive
                breakAttempts += 1
            breakActive := true
            if aFloor > 0
                maxCloseThrough := math.max(maxCloseThrough, 1.0 - close / aFloor)
            bool clearsBuffer = not na(atr) and close < aFloor - atr * acceptAtr
            breakStreak := clearsBuffer ? math.min(breakStreak + 1, acceptBars) : 0
            if na(acceptedAt) and breakStreak >= acceptBars
                acceptedAt := time_close
                acceptEvent := true
            if not na(acceptedAt) and time_close > acceptedAt and not retested and not na(atr)
                if high >= aFloor - atr * retestAtr
                    retested := true
                    retestEvent := true
 
// The audit resolves existing cases before considering any newly confirmed
// count. A case issued on this close sees OHLC only from the next bar onward.
if processClose
    bool liveCount = not topInvalid and ready(larger) and larger.state < 3
    if liveCount and close > 0
        if na(pathBAt) or pathBAt != larger.b.at
            pathBAt := larger.b.at
            pathFirst := close
            pathPrevious := close
            pathLength := 0.0
            pathSteps := 0
        else
            pathLength += math.abs(math.log(close / pathPrevious))
            pathPrevious := close
            pathSteps += 1
    else
        pathBAt := na
        pathFirst := na
        pathPrevious := na
        pathLength := 0.0
        pathSteps := 0
 
    bool wasAuditing = not na(auditIssue)
    bool wasPaired = not na(pairIssue)
    bool wasRacing = not na(race.issueBar) and race.result == 0
 
    if wasRacing
        int age = bar_index - race.issueBar
        if age == 1
            race.entry := open
            race.entryAt := time
            if open <= race.c or open >= race.b or open <= 0
                raceEvent := -4
            else
                float radius = math.min(math.log(open / race.c), math.log(race.b / open))
                race.lower := math.round_to_mintick(open * math.exp(-radius))
                race.upper := math.round_to_mintick(open * math.exp(radius))
                bool tickFit = race.lower > 0 and race.lower < open and race.upper > open and raceTick > 0
                if tickFit
                    float downWidth = math.log(open / race.lower)
                    float upWidth = math.log(race.upper / open)
                    race.skew := math.abs(downWidth - upWidth) / math.max(downWidth, upWidth)
                    if race.atrAtIssue > 0
                        race.widthAtr := (race.upper - race.lower) / (2.0 * race.atrAtIssue)
                    if math.round((open - race.lower) / raceTick) < raceMinTicks or math.round((race.upper - open) / raceTick) < raceMinTicks or race.skew > raceMaxSkew / 100.0 or race.lower < race.c or race.upper > race.b
                        raceEvent := -5
                else
                    raceEvent := -5
        if age >= 1 and raceEvent == 0
            raceEvent := auditBar(race.lower, race.upper, open, high, low, age >= auditHorizon)
        if raceEvent != 0
            race.result := raceEvent
            race.finishAt := time_close
            int bucket = race.regime + 1
            if raceEvent == 1
                raceDown += 1
                array.set(raceRegimeDown, bucket, array.get(raceRegimeDown, bucket) + 1)
            else if raceEvent == -1
                raceUp += 1
                array.set(raceRegimeUp, bucket, array.get(raceRegimeUp, bucket) + 1)
            else if raceEvent == -2
                raceTies += 1
            else if raceEvent == -3
                raceTimeout += 1
            else if raceEvent == -4
                raceSkipOpen += 1
            else
                raceSkipTick += 1
            array.unshift(raceJournal, RaceRecord.new(race.serial, time_close, raceEvent, race.regime, age))
            if array.size(raceJournal) > 5
                array.pop(raceJournal)
    if wasAuditing
        int age = bar_index - auditIssue
        if age >= 1
            if age == 1
                auditEntry := open
                entryAt := time
                bestClose := open
                worstClose := open
            if age == 1 and (open <= auditTarget or open >= auditBoundary)
                auditSkippedOpen += 1
                lastAudit := "Skipped · open outside bounds"
                auditIssue := na
                resolvedAt := time_close
            else
                int outcome = auditBar(auditTarget, auditBoundary, open, high, low, age >= auditHorizon)
                if outcome == 0
                    bestClose := math.min(bestClose, close)
                    worstClose := math.max(worstClose, close)
                else
                    resolvedAt := time_close
                    auditIssue := na
                    if outcome == 1
                        auditWins += 1
                        hitBars += age
                        lastHitBars := age
                        lastAudit := "Target reached"
                        auditHit := true
                    else
                        auditMiss := true
                        if outcome == -3
                            auditTimeouts += 1
                            lastAudit := "Unsuccessful · time expired"
                        else
                            auditBoundaryLosses += 1
                            if outcome == -2
                                auditAmbiguous += 1
                            lastAudit := outcome == -2 ? "Unsuccessful · both levels touched" : "Unsuccessful · B touched"
 
    // All three rungs share the same issue, next open, B, and horizon.
    // Aggregate once every rung has resolved to keep the denominator paired.
    if wasPaired
        int age = bar_index - pairIssue
        if age == 1 and (open <= array.get(pairTargets, 0) or open >= pairB)
            pairSkipped += 1
            pairIssue := na
        else if age >= 1
            bool allDone = true
            for rung = 0 to 2
                int state = array.get(pairOutcomes, rung)
                if state == 0
                    state := auditBar(array.get(pairTargets, rung), pairB, open, high, low, age >= auditHorizon)
                    array.set(pairOutcomes, rung, state)
                allDone := allDone and state != 0
            if allDone
                pairCompleted += 1
                for rung = 0 to 2
                    if array.get(pairOutcomes, rung) == 1
                        array.set(pairHits, rung, array.get(pairHits, rung) + 1)
                pairIssue := na
 
    if liveCount and time_close >= auditFrom
        bool unseen = na(seenTopAt) or na(seenBAt) or seenTopAt != top.at or seenBAt != larger.b.at
        if unseen
            seenTopAt := top.at
            seenBAt := larger.b.at
            float target = math.round_to_mintick(logProjection(top, larger, 1.0))
            bool validSetup = not na(target) and target > originPrice and close > target and close < larger.b.price
            if wasAuditing
                auditConcurrent += 1
            else if validSetup
                auditIssue := bar_index
                issuedAt := time_close
                entryAt := na
                resolvedAt := na
                auditTarget := target
                auditBoundary := larger.b.price
                auditEntry := na
                bestClose := na
                worstClose := na
                lastHitBars := na
                lastAudit := "Issued · entry at next open"
                auditIssued := true
                if wasRacing
                    raceConcurrent += 1
                else
                    raceSerial += 1
                    race := Race.new()
                    race.issueBar := bar_index
                    race.issueAt := time_close
                    race.serial := raceSerial
                    race.c := target
                    race.b := larger.b.price
                    race.atrAtIssue := atr
                    if not na(atrShare) and not na(atrShareBaseline)
                        race.regime := atrShare > atrShareBaseline ? 1 : -1
                float shallow = math.round_to_mintick(logProjection(top, larger, 0.786))
                float deep = math.round_to_mintick(logProjection(top, larger, 1.272))
                if not wasPaired and not na(shallow) and not na(deep) and shallow < close and shallow > target and target > deep and deep > originPrice
                    pairIssue := bar_index
                    pairB := auditBoundary
                    array.set(pairTargets, 0, shallow)
                    array.set(pairTargets, 1, target)
                    array.set(pairTargets, 2, deep)
                    array.fill(pairOutcomes, 0)
                else
                    pairSkipped += 1
            else
                auditSkippedSetup += 1
                // Preserve the last issued case snapshot and its outcome.
                if na(issuedAt)
                    lastAudit := "Skipped · issue outside bounds"
 
// Both plotted markers and alerts timestamp the closing-bar decision.
bool largerBreak = largerEvent == 1
bool largerReclaim = largerEvent == -1
alertcondition(elliottImpulseConfirmed, "Elliott impulse confirmed", "Wave Atlas: {{ticker}} confirmed waves 1–5 on {{interval}}.")
alertcondition(elliottEvent == 1, "Elliott A confirmed", "Wave Atlas: {{ticker}} confirmed wave A on {{interval}}.")
alertcondition(elliottEvent == 2, "Elliott B confirmed", "Wave Atlas: {{ticker}} confirmed wave B on {{interval}}.")
alertcondition(elliottEvent == 3, "Elliott C confirmed", "Wave Atlas: {{ticker}} completed A–B–C on {{interval}}.")
alertcondition(elliottEvent == -1, "Elliott zigzag invalidated", "Wave Atlas: {{ticker}} invalidated the active ABC candidate on {{interval}}.")
alertcondition(largerBreak, "Larger count: close below A", "Wave Atlas: {{ticker}} closed below the larger A low on {{interval}}.")
alertcondition(largerReclaim, "Larger count: close above B", "Wave Atlas: {{ticker}} closed above the larger B high on {{interval}}.")
alertcondition(topEvent, "Wave 1 top invalidated", "Wave Atlas: {{ticker}} closed above the tracked Wave 1 top on {{interval}}.")
plotshape(largerBreak, title="Close below larger A", style=shape.triangledown, location=location.abovebar, color=amber, size=size.tiny)
plotshape(largerReclaim or topEvent or originEvent, title="Count invalidated", style=shape.xcross, location=location.abovebar, color=silver, size=size.tiny)
plotshape(showMarkers and acceptEvent, title="Break acceptance", style=shape.circle, location=location.belowbar, color=amber, size=size.tiny, text="A", textcolor=amber)
plotshape(showMarkers and retestEvent, title="Rejected retest", style=shape.circle, location=location.abovebar, color=amber, size=size.tiny, text="R", textcolor=amber)
plotshape(showMarkers and failedEvent, title="A reclaimed", style=shape.circle, location=location.belowbar, color=teal, size=size.tiny, text="U", textcolor=teal)
plotshape(showMarkers and auditIssued, title="Audit issued", style=shape.diamond, location=location.abovebar, color=#9EA8F2, size=size.tiny)
plotshape(showMarkers and auditHit, title="Audit target hit", style=shape.diamond, location=location.belowbar, color=teal, size=size.tiny)
plotshape(showMarkers and auditMiss, title="Audit unsuccessful", style=shape.diamond, location=location.belowbar, color=silver, size=size.tiny)
alertcondition(originEvent, "Wave 1 origin breached", "Wave Atlas: {{ticker}} traded below the tracked Wave 1 origin on a confirmed {{interval}} bar.")
alertcondition(acceptEvent, "Break accepted below A", "Wave Atlas: {{ticker}} met the consecutive-close and ATR-buffer rule below A.")
alertcondition(retestEvent, "A retest rejected", "Wave Atlas: {{ticker}} tested A from below after acceptance and closed below it.")
alertcondition(failedEvent, "A break reclaimed", "Wave Atlas: {{ticker}} closed back at or above A after a close beneath it.")
 
string eventName = originEvent ? "wave_1_origin_breached" : topEvent ? "wave_1_top_invalidated" : largerReclaim ? "close_above_larger_b" : failedEvent ? "a_break_reclaimed" : retestEvent ? "a_retest_rejected" : acceptEvent ? "break_accepted" : largerBreak ? "close_below_larger_a" : ""
if eventName != ""
    float trigger = originEvent ? originPrice : topEvent ? top.price : largerReclaim ? larger.b.price : larger.a.price
    array.unshift(ledgerNames, eventName)
    array.unshift(ledgerTimes, time_close)
    array.unshift(ledgerCloses, close)
    if array.size(ledgerNames) > 6
        array.pop(ledgerNames)
        array.pop(ledgerTimes)
        array.pop(ledgerCloses)
    if jsonAlerts
        string payload = '{"event":' + jsonString(eventName) + ',"symbol":' + jsonString(syminfo.tickerid) + ',"timeframe":' + jsonString(timeframe.period) + ',"bar_close_time":' + str.tostring(time_close) + ',"level":' + priceText(trigger) + ',"close":' + priceText(close) + '}'
        alert(payload, alert.freq_once_per_bar_close)
 
// Plot series are intentionally blank on open candles.
bool inspect = showData and enabled and barstate.isconfirmed
plot(inspect ? auditTarget : na, title="Audit · saved C1 target", display=display.data_window)
plot(inspect ? auditBoundary : na, title="Audit · saved B", display=display.data_window)
plot(inspect ? auditEntry : na, title="Audit · saved entry open", display=display.data_window)
plot(inspect ? (auditIssued ? 1 : 0) : na, title="Audit · issued", display=display.data_window)
plot(inspect ? (auditHit ? 1 : auditMiss ? -1 : 0) : na, title="Audit · outcome this bar", display=display.data_window)
plot(inspect ? pairCompleted : na, title="Audit · matched sample size", display=display.data_window)
plot(inspect and not na(auditIssue) ? bar_index - auditIssue : na, title="Audit · bars elapsed", display=display.data_window)
 
plot(inspect ? (na(race.issueBar) ? na : race.serial) : na, title="Benchmark · case ID", display=display.data_window)
plot(inspect ? race.lower : na, title="Benchmark · frozen lower", display=display.data_window)
plot(inspect ? race.upper : na, title="Benchmark · frozen upper", display=display.data_window)
plot(inspect ? raceEvent : na, title="Benchmark · outcome this bar", display=display.data_window)
plot(inspect ? (na(race.issueBar) ? na : race.regime) : na, title="Benchmark · issue volatility regime", display=display.data_window)
 
var array<line> lines = array.new_line()
var array<label> labels = array.new_label()
var box zone = na
var linefill overlapFill = na
var table auditGrid = table.new(position.top_left, 2, 16, bgcolor=panel, border_color=color.new(muted, 75), border_width=1)
var table research = table.new(position.bottom_right, 2, 18, bgcolor=panel, border_color=color.new(muted, 75), border_width=1)
var table ledger = table.new(position.bottom_left, 3, 7, bgcolor=panel, border_color=color.new(muted, 75), border_width=1)
var table dashboard = table.new(position.top_right, 3, 7, bgcolor=panel, border_color=color.new(muted, 75), border_width=1)
 
if barstate.islastconfirmedhistory or (barstate.islast and (barstate.isconfirmed or not na(previewAt)))
    if not na(overlapFill)
        linefill.delete(overlapFill)
        overlapFill := na
    while array.size(lines) > 0
        line.delete(array.pop(lines))
    while array.size(labels) > 0
        label.delete(array.pop(labels))
    if not na(zone)
        box.delete(zone)
        zone := na
    color largerInk = larger.state == 3 ? muted : amber
    color earlyInk = early.state == 3 ? muted : teal
    bool analyzeLarger = enabled and not topInvalid and ready(larger) and larger.state < 3
    float softC = analyzeLarger ? logProjection(top, larger, 0.786) : na
    float equalC = analyzeLarger ? logProjection(top, larger, 1.0) : na
    float deepC = analyzeLarger ? logProjection(top, larger, 1.272) : na
    float earlySoft = analyzeLarger and early.state < 3 ? logProjection(top, early, 0.786) : na
    float earlyDeep = analyzeLarger and early.state < 3 ? logProjection(top, early, 1.272) : na
    float overlapLow = math.max(deepC, earlyDeep)
    float overlapHigh = math.min(softC, earlySoft)
    bool overlaps = not na(overlapLow) and not na(overlapHigh) and overlapLow <= overlapHigh
    bool liveAB = not na(top) and not topInvalid and ((showArchive and ready(early) and not early.archived and early.state < 3) or (ready(larger) and larger.state < 3))
    bool structureActive = enabled and not btcStudy and structureView != "Off" and (structureView == "Structure only" or not liveAB)
    int lockedCount = math.max(0, array.size(structurePivots) - 1)
    int firstStructure = 0
    if structureActive and not timeBased
        while firstStructure < lockedCount and bar_index - array.get(structurePivots, firstStructure).index > 9999
            firstStructure += 1
    int visiblePivots = lockedCount - firstStructure
    bool showCompleted = structureActive and (not correctionInvalid or showInvalidCount) and array.size(completedImpulse) == 6 and (timeBased or bar_index - array.first(completedImpulse).index <= 9999)
    int direction = showCompleted ? completedDirection : 0
    bool showCloseLeg = structureActive and not showCompleted and visiblePivots < 2 and not na(closeLegStart) and (timeBased or bar_index - closeLegStart.index <= 9999)
    if showCompleted
        drawStructure(lines, labels, completedImpulse, 0, 6, completedDirection, timeBased)
        if array.size(correction) > 1
            drawStructure(lines, labels, correction, 0, array.size(correction), 0, timeBased, true, correctionType)
        if showElliottProjection and timeBased and not correctionInvalid and array.size(correction) == 3
            StructurePivot waveB = array.get(correction, 2)
            float waveA = array.get(correction, 1).price - array.first(correction).price
            float equalLeg = math.round_to_mintick(waveB.price + waveA)
            float extendedLeg = math.round_to_mintick(waveB.price + 1.618 * waveA)
            level(lines, waveB.at, equalLeg, lastConfirmedAt, amber, line.style_dotted, true)
            level(lines, waveB.at, extendedLeg, lastConfirmedAt, muted, line.style_dotted, true)
            note(labels, lastConfirmedAt, equalLeg, "C ref · 1.000 A", amber, "Linear A length projected from locked B. The reference ends when C confirms or invalidates.")
            if extendedLeg != equalLeg
                note(labels, lastConfirmedAt, extendedLeg, "C ref · 1.618 A", silver, "Extended linear reference from locked B.")
        int waveEnd = array.last(correction).index
        int nextStructure = firstStructure
        while nextStructure < lockedCount and array.get(structurePivots, nextStructure).index <= waveEnd
            nextStructure += 1
        if nextStructure < lockedCount
            bool connectFromCount = nextStructure > firstStructure and array.get(structurePivots, nextStructure - 1).index == waveEnd
            int drawFrom = connectFromCount ? nextStructure - 1 : nextStructure
            drawStructure(lines, labels, structurePivots, drawFrom, lockedCount, 0, timeBased, connectFromCount)
    else if structureActive and visiblePivots > 0
        drawStructure(lines, labels, structurePivots, firstStructure, lockedCount, 0, timeBased)
    if structureActive and showDevelopingLeg and visiblePivots >= 2
        StructurePivot lastLocked = array.get(structurePivots, lockedCount - 1)
        int fromX = timeBased ? lastLocked.at : lastLocked.index
        StructurePivot candidate = array.last(structurePivots)
        int candidateX = timeBased ? candidate.at : candidate.index
        int toX = timeBased ? time : bar_index
        string coordinates = timeBased ? xloc.bar_time : xloc.bar_index
        color developingInk = candidate.side == 1 ? teal : #ED9C92
        if candidateX > fromX
            array.push(lines, line.new(fromX, lastLocked.price, candidateX, candidate.price, xloc=coordinates, color=developingInk, width=2, style=line.style_dotted))
            if toX > candidateX and not na(confirmedPrice)
                array.push(lines, line.new(candidateX, candidate.price, toX, confirmedPrice, xloc=coordinates, color=color.new(silver, 40), style=line.style_dotted))
    if showCloseLeg
        string coordinates = timeBased ? xloc.bar_time : xloc.bar_index
        color ink = closeLegDirection == 1 ? teal : #ED9C92
        int fromX = timeBased ? closeLegStart.at : closeLegStart.index
        int toX = timeBased ? closeLegEnd.at : closeLegEnd.index
        array.push(lines, line.new(fromX, closeLegStart.price, toX, closeLegEnd.price, xloc=coordinates, color=ink, style=line.style_dotted, width=2))
        string caption = closeLegDirection == 1 ? "Rising close leg" : "Falling close leg"
        string hint = "Closed prices " + priceText(closeLegStart.price) + " → " + priceText(closeLegEnd.price) + "\nThis leg can extend after another candle closes. Numbered impulse waves require locked swings."
        array.push(labels, label.new(toX, closeLegEnd.price, caption, xloc=coordinates, style=label.style_label_left, color=color.new(panel, 10), textcolor=ink, size=size.small, tooltip=showHelp ? hint : ""))
 
    if enabled and not na(top) and not structureActive
        if array.size(impulse) == 6
            for i = 1 to 5
                Swing point = array.get(impulse, i)
                segment(lines, array.get(impulse, i - 1), point, color.new(silver, 30))
                tag(labels, point, str.tostring(i), silver)
        else
            tag(labels, top, "1", silver)
        if showArchive
            drawCount(lines, labels, top, early, earlyInk, "₁", lastConfirmedAt, false)
        drawCount(lines, labels, top, larger, largerInk, "₂", lastConfirmedAt, showProjection)
        if showOverlap and overlaps and lastConfirmedAt > larger.b.at
            line bottom = line.new(larger.b.at, overlapLow, lastConfirmedAt, overlapLow, xloc=xloc.bar_time, extend=extend.right, color=color.new(teal, 40), style=line.style_dotted)
            line ceiling = line.new(larger.b.at, overlapHigh, lastConfirmedAt, overlapHigh, xloc=xloc.bar_time, extend=extend.right, color=color.new(teal, 40), style=line.style_dotted)
            array.push(lines, bottom)
            array.push(lines, ceiling)
            overlapFill := linefill.new(bottom, ceiling, color.new(teal, 89))
        if analyzeLarger and showFan
            int spanA = larger.a.at - top.at
            if spanA > 0
                if softC > originPrice
                    pricePath(lines, labels, larger.b, softC, larger.b.at + int(math.round(spanA * 0.618)), color.new(silver, 25), "C₀.₇₈₆", "Shallow path. 0.786 times Wave A's log-price move, with a time span of 0.618 times A. The curve illustrates the scenario.")
                if equalC > originPrice
                    pricePath(lines, labels, larger.b, equalC, larger.b.at + spanA, amber, "C₁", "Equal log-price drop and equal calendar duration to Wave A. The dashed curve is an illustration, and the endpoint follows the formula.")
                if deepC > originPrice
                    pricePath(lines, labels, larger.b, deepC, larger.b.at + int(math.round(spanA * 1.618)), color.new(amber, 30), "C₁.₂₇₂", "Deep path. 1.272 times Wave A's log-price move with a time span of 1.618 times A. Paths below the Wave 1 origin are suppressed.")
        if analyzeLarger and showRoad
            note(labels, lastConfirmedAt, larger.a.price, "A  " + priceText(larger.a.price), amber, "A is the selloff low. A wick below it records a lower low. Compare the close, ATR buffer, and retest before treating a break as accepted.")
            note(labels, lastConfirmedAt, larger.b.price, "B  " + priceText(larger.b.price), silver, "B is the frozen rebound high. The count closes out above B on a confirmed close. The separate forward audit scores a touch of B as unsuccessful.")
            if btcStudy
                float priorCycleLow = 15479.0
                float zoneMiddle = math.sqrt(zoneLow * zoneHigh)
                level(lines, larger.b.at, priorCycleLow, lastConfirmedAt, silver, line.style_dotted, true)
                note(labels, lastConfirmedAt, priorCycleLow, "2022 low  " + priceText(priorCycleLow), silver, "Previous cycle low used as an intermediate observation level for your macro thesis.")
                note(labels, lastConfirmedAt, zoneMiddle, "Wave 2 zone  " + priceText(math.min(zoneLow, zoneHigh)) + "–" + priceText(math.max(zoneLow, zoneHigh)), teal, "Your projected Wave 2 endpoint range. This label sits at the geometric midpoint.")
        if showZone and btcStudy and not topInvalid
            zone := box.new(timestamp("GMT+0", 2028, 1, 1, 0, 0), math.max(zoneHigh, zoneLow), timestamp("GMT+0", 2029, 1, 1, 0, 0), math.min(zoneHigh, zoneLow), xloc=xloc.bar_time, border_color=amber, border_style=line.style_dotted, bgcolor=color.new(amber, 90), text="Wave 2 target", text_color=amber, text_size=size.tiny)
 
    if enabled and showFrozen and not na(issuedAt)
        int railEnd = na(resolvedAt) ? lastConfirmedAt : resolvedAt
        bool running = not na(auditIssue)
        if railEnd <= issuedAt
            railEnd := issuedAt + 1
        int textAt = running ? lastConfirmedAt : railEnd
        color auditInk = #B4BCFF
        level(lines, issuedAt, auditTarget, railEnd, auditInk, line.style_dashed, running)
        level(lines, issuedAt, auditBoundary, railEnd, auditInk, line.style_dashed, running)
        note(labels, textAt, auditTarget, "Frozen C₁  " + priceText(auditTarget), auditInk, "Audit target fixed at the issue close. A later count can change the main wave projection while this level stays fixed.")
        note(labels, textAt, auditBoundary, "Frozen B  " + priceText(auditBoundary), auditInk, "Audit boundary recorded at issue. The audit treats a touch of B as unsuccessful.")
        if not na(entryAt) and not na(auditEntry)
            level(lines, entryAt, auditEntry, railEnd, auditInk, line.style_dotted, running)
            note(labels, textAt, auditEntry, "Reference open  " + priceText(auditEntry), auditInk, "Opening print on the next bar. An out-of-bounds open skips the case.")
    if enabled and showRace and not na(race.entryAt) and not na(race.lower) and not na(race.upper) and race.result != -5
        bool benchRunning = race.result == 0
        int railEnd = benchRunning ? lastConfirmedAt : race.finishAt
        color lowerInk = #63DAC5
        color upperInk = #CEB1F2
        level(lines, race.entryAt, race.lower, railEnd, lowerInk, line.style_dashed, benchRunning)
        level(lines, race.entryAt, race.upper, railEnd, upperInk, line.style_dashed, benchRunning)
        level(lines, race.entryAt, race.entry, railEnd, silver, line.style_dotted, benchRunning)
        note(labels, railEnd, race.lower, "Benchmark ↓  " + priceText(race.lower), lowerInk, "Lower boundary at the same approximate log distance from the frozen opening price as the upper boundary.")
        note(labels, railEnd, race.upper, "Benchmark ↑  " + priceText(race.upper), upperInk, "Upper boundary is the same log distance from the open before rounding. The Benchmark panel reports the rounding imbalance.")
        note(labels, railEnd, race.entry, "Benchmark open  " + priceText(race.entry), silver, "Both directions start from this next-bar open and share the same deadline.")
    if structureActive
        table.clear(dashboard, 0, 0, 2, 5)
    else
        string status = not enabled ? (btcStudy ? "Use Bitstamp BTCUSD · time-based" : "Use standard candles") : na(top) ? (btcStudy ? "Study not yet available" : "Waiting for impulse") : topInvalid ? (originInvalid ? "Wave 1 origin breached" : "Wave 1 top invalidated") : "Wave 1  " + priceText(top.price)
        table.cell(dashboard, 0, 0, status, text_color=silver, text_size=size.small, tooltip=showHelp ? "Start here. Use standard candles and select BTC cycle study on a time-based BITSTAMP:BTCUSD chart, or use Automatic for another symbol. Signals use the chart interval. Teal is the earlier count. Amber is the larger count. Historical pivot labels are positioned on the swing bars and become known with a delay." : "")
        table.cell(dashboard, 1, 0, showArchive ? "Earlier" : "", text_color=earlyInk, text_size=size.small)
        table.cell(dashboard, 2, 0, "Larger", text_color=largerInk, text_size=size.small)
        table.cell(dashboard, 0, 1, "A low", text_color=muted, text_size=size.small)
        table.cell(dashboard, 1, 1, showArchive and not na(early.a) ? priceText(early.a.price) : "—", text_color=earlyInk, text_size=size.small)
        table.cell(dashboard, 2, 1, not na(larger.a) ? priceText(larger.a.price) : "—", text_color=largerInk, text_size=size.small)
        table.cell(dashboard, 0, 2, "B high", text_color=muted, text_size=size.small)
        table.cell(dashboard, 1, 2, showArchive and ready(early) ? priceText(early.b.price) : "—", text_color=earlyInk, text_size=size.small)
        table.cell(dashboard, 2, 2, ready(larger) ? priceText(larger.b.price) : "—", text_color=largerInk, text_size=size.small)
        table.cell(dashboard, 0, 3, "Last closed bar", text_color=muted, text_size=size.small)
        table.cell(dashboard, 1, 3, enabled and showArchive and not na(top) ? stateText(early) : "—", text_color=earlyInk, text_size=size.small)
        string closeState = enabled and not na(top) ? stateText(larger) : "—"
        if analyzeLarger
            if btcStudy and na(trackedBAt)
                closeState := "Awaiting chart close"
            else if retested
                closeState := "A retest rejected"
            else if not na(acceptedAt)
                closeState := "Break accepted"
            else if not breakActive and larger.state == 2
                closeState := "A reclaimed"
        table.cell(dashboard, 2, 3, closeState, text_color=largerInk, text_size=size.small)
        table.cell(dashboard, 0, 4, "Equal log-leg C", text_color=muted, text_size=size.small)
        table.cell(dashboard, 1, 4, showProjection and showArchive ? priceText(logProjection(top, early, 1.0)) : "—", text_color=earlyInk, text_size=size.small)
        table.cell(dashboard, 2, 4, showProjection and larger.state < 3 ? priceText(logProjection(top, larger, 1.0)) : "—", text_color=largerInk, text_size=size.small)
        table.cell(dashboard, 0, 5, showHelp ? "How to read ⓘ" : "Close-confirmed", text_color=muted, text_size=size.tiny, tooltip=showHelp ? "Read A then B, then check the last closed bar. Triangle = first close below A. A = acceptance. R = rejected retest. U = reclaim. Diamonds track the forward audit. Hover any research or audit row for its formula or rule." : "")
        table.cell(dashboard, 1, 5, "", text_size=size.tiny)
        table.cell(dashboard, 2, 5, btcStudy ? "BTC · " + timeframe.period : "Auto · " + timeframe.period, text_color=muted, text_size=size.tiny)
 
    if structureActive
        string structuralStatus = visiblePivots >= 2 ? "Locked swing map" : showCloseLeg ? "Close leg · updates at close" : "Waiting for price movement"
        if showCompleted
            string stage = switch array.size(correction)
                1 => "Awaiting A"
                2 => "Awaiting B"
                3 => "Awaiting C · " + correctionType
                => "ABC complete · " + correctionType
            structuralStatus := (direction == 1 ? "Bullish 1–5 · " : "Bearish 1–5 · ") + (correctionInvalid ? "Zigzag invalidated" : stage)
        if correctionInvalid and not showCompleted
            structuralStatus := "ABC invalidated · " + correctionFailure
        if visiblePivots > 0
            StructurePivot latestLocked = array.get(structurePivots, lockedCount - 1)
            table.cell(dashboard, 0, 5, "Latest locked swing", text_color=muted, text_size=size.tiny)
            table.cell(dashboard, 1, 5, priceText(latestLocked.price), text_color=silver, text_size=size.small, tooltip=showHelp ? "The dotted leg starts here. It follows an unlocked pivot and the last closed price." : "")
            table.cell(dashboard, 2, 5, str.tostring(bar_index - latestLocked.lockedOn) + " bars ago", text_color=muted, text_size=size.tiny)
        if showCompleted and array.size(correction) == 4 and not correctionInvalid
            StructurePivot waveC = array.last(correction)
            structuralStatus += " · " + str.tostring(bar_index - waveC.lockedOn) + " bars ago"
        table.cell(dashboard, 0, 6, syminfo.ticker + " · " + timeframe.period, text_color=silver, text_size=size.tiny, tooltip=showHelp ? "Uses closed candles on the chart interval. A swing is locked after a qualifying opposing pivot. The latest confirmed 1–5 stays numbered as its A–B–C zigzag forms. Zigzag B stays between A and Wave 5. Optional flat geometry permits a deeper B. C must extend beyond A. Other swings use market structure labels. When fewer than two swings have locked, a dotted leg connects closed prices. Structure is a display layer separate from the original audit and alerts." : "")
        table.cell(dashboard, 1, 6, structuralStatus, text_color=direction == 1 ? teal : direction == -1 ? #ED9C92 : silver, text_size=size.tiny)
        table.cell(dashboard, 2, 6, str.tostring(visiblePivots) + " locked", text_color=muted, text_size=size.tiny)
    else
        table.clear(dashboard, 0, 6, 2, 6)
 
    if structureActive and not showElliottResearch and layout == "Research"
        table.clear(research, 0, 0, 1, 17)
        table.clear(auditGrid, 0, 0, 1, 15)
    if showResearch and layout == "Research" and (not structureActive or showElliottResearch)
        float linearDepth = na
        float logDepth = na
        float paceRatio = na
        int timeEarly = na
        int timeLate = na
        float originDrawdown = na
        float zoneNear = na
        float zoneFar = na
        if enabled and not na(top)
            if top.price > originPrice and originPrice > 0 and confirmedPrice > 0
                linearDepth := (top.price - confirmedPrice) / (top.price - originPrice)
                logDepth := math.log(top.price / confirmedPrice) / math.log(top.price / originPrice)
                originDrawdown := 100.0 * (1.0 - confirmedPrice / top.price)
        if analyzeLarger
            int aSpan = larger.a.at - top.at
            int cElapsed = lastConfirmedAt - larger.b.at
            if aSpan > 0 and cElapsed > 0
                timeEarly := larger.b.at + int(math.round(aSpan * 0.618))
                timeLate := larger.b.at + int(math.round(aSpan * 1.618))
                float paceMultiple = logMultiple(top, larger, confirmedPrice)
                paceRatio := paceMultiple * (float(aSpan) / float(cElapsed))
            if btcStudy
                zoneNear := logMultiple(top, larger, math.max(zoneLow, zoneHigh))
                zoneFar := logMultiple(top, larger, math.min(zoneLow, zoneHigh))
        string ladder = na(equalC) ? "—" : priceText(softC) + " / " + priceText(equalC) + " / " + priceText(deepC)
        string overlapText = overlaps ? priceText(overlapLow) + " to " + priceText(overlapHigh) : "—"
        string depthText = na(logDepth) ? "—" : str.tostring(100 * linearDepth, "#.##") + "% / " + str.tostring(100 * logDepth, "#.##") + "%"
        string windowText = na(timeEarly) ? "—" : dateText(timeEarly) + " to " + dateText(timeLate)
        if not na(timeLate) and lastConfirmedAt > timeLate
            windowText += " · elapsed"
        string burdenText = na(zoneNear) ? "—" : ratioText(zoneNear) + " to " + ratioText(zoneFar) + " A"
        string annualCycle = "—"
        string yearContext = "—"
        if btcStudy and enabled
            annualCycle := annualText(yr12, yo12, yc12) + " · " + annualText(yr8, yo8, yc8) + " · " + annualText(yr4, yo4, yc4)
            yearContext := annualText(yr1, yo1, yc1)
        researchRow(research, 0, "Count available from", utcText(availableAt), silver, "First close on which this Wave 1 count was available on the chart. The preloaded BTC study only activates after its reconstruction cutoff.")
        researchRow(research, 1, "C · 0.786 / 1 / 1.272 A", ladder, amber, "Each C projection equals B times (A low divided by Wave 1 high) raised to the listed multiplier.")
        researchRow(research, 2, "Earlier / larger C overlap", overlapText, teal, "Price intersection of the earlier and larger projection bands. Both counts share the same Wave 1 anchor.")
        researchRow(research, 3, "C time window · UTC", windowText, silver, "Wave B date plus 0.618 to 1.618 times the calendar duration of Wave A.")
        researchRow(research, 4, "C pace vs A", ratioText(paceRatio), silver, "Observed average signed log move per unit of calendar time after B, divided by the Wave A decline per unit of time.")
        researchRow(research, 5, "Log-A legs to custom zone", burdenText, amber, "Log distance from B to both custom-zone edges, divided by the size of Wave A in log-price terms.")
        researchRow(research, 6, "Impulse retrace · linear / log", depthText, silver, "Distance from the Wave 1 peak to the latest close relative to its full advance from the origin, in price and log coordinates.")
        researchRow(research, 7, "Wave 1 origin", priceText(originPrice), silver, "Automatic mode uses the detected impulse origin. BTC study uses your adjustable start price, initially 2 USD.")
        researchRow(research, 8, "Peak to closed price", na(originDrawdown) ? "—" : str.tostring(math.abs(originDrawdown), "0.00") + (originDrawdown < 0 ? "% above" : originDrawdown > 0 ? "% below" : "%"), silver, "Peak-to-latest-confirmed-close move as a percentage of the Wave 1 peak.")
        researchRow(research, 9, "Break acceptance", analyzeLarger ? str.tostring(breakStreak) + " / " + str.tostring(acceptBars) + " closes" : "—", amber, "Consecutive closes below A after applying the configured ATR buffer. A confirmed reclaim re-arms the test.")
        researchRow(research, 10, "4-year lookbacks · closed", annualCycle, silver, "Colors of completed annual bars four, eight, and twelve years back. The weekly chart uses offset yearly data.")
        researchRow(research, 11, "Last completed year", yearContext, silver, "A red annual candle closes below its own yearly open. This row displays the latest completed yearly candle.")
        float aAtr = na
        float bAtr = na
        float pathEfficiency = na
        float requiredPace = na
        if analyzeLarger
            if not na(atr) and atr > 0
                aAtr := (confirmedPrice - larger.a.price) / atr
                bAtr := (larger.b.price - confirmedPrice) / atr
            if pathSteps > 0 and pathLength > 0 and confirmedPrice > 0
                pathEfficiency := math.max(-1.0, math.min(1.0, math.log(pathFirst / confirmedPrice) / pathLength))
            if confirmedPrice > 0 and not na(equalC) and equalC > 0 and not na(timeLate) and timeLate > lastConfirmedAt
                float logWaveA = math.log(top.price / larger.a.price)
                if logWaveA > 0
                    float remainingMove = math.max(0.0, math.log(confirmedPrice / equalC))
                    float durationRatio = float(larger.a.at - top.at) / float(timeLate - lastConfirmedAt)
                    requiredPace := (remainingMove / logWaveA) * durationRatio
        researchRow(research, 12, "To A / to B · ATR", ratioText(aAtr) + " / " + ratioText(bAtr), amber, "Distance from the latest close to each frozen boundary using current ATR(14). A negative value means the price is beyond that boundary.")
        researchRow(research, 13, "Downside path efficiency", percentText(pathEfficiency), teal, "Net down log move divided by all absolute close-to-close log moves since the count first became eligible. Near +100% means steady downside; negative values indicate net upside.")
        researchRow(research, 14, "Required pace to C₁", ratioText(requiredPace), silver, "Remaining average log decline per calendar day needed to reach the equal-leg target by the late edge, expressed relative to Wave A's observed pace. Zero means the latest close is already at or below C₁.")
 
        string role = "—"
        if analyzeLarger and not na(early.c)
            role := early.c.at == larger.a.at and early.c.price == larger.a.price ? "Same pivot · earlier C / larger A" : "Distinct pivots"
        researchRow(research, 15, "Larger count available · UTC", analyzeLarger ? utcText(largerKnownAt) : "—", silver, "The confirmed close when the larger B and its complete A/B count could first be used. Its drawing still starts at the historical swing.")
        researchRow(research, 16, "Shared pivot", role, teal, "Earlier C and larger A can reuse the exact same swing. Later automatic counts can instead settle on distinct troughs.")
        string resilience = analyzeLarger ? str.tostring(breakAttempts) + " / " + str.tostring(breakReclaims) + " · " + percentText(maxCloseThrough) : "—"
        researchRow(research, 17, "A breaks / reclaims · depth", resilience, amber, "Counts separate close-through-A attempts and recoveries. Depth is the largest confirmed close penetration below A, as a share of A, since larger B became available.")
 
    if showValidation and (layout == "Audit" or (layout == "Research" and (not structureActive or showElliottResearch)))
        int scored = auditWins + auditBoundaryLosses + auditTimeouts
        [ciLow, ciHigh] = wilson(auditWins, scored)
        float observedRate = scored > 0 ? float(auditWins) / float(scored) : na
        string auditState = not enabled ? "Inactive on this chart" : scored < auditMinimum ? "Unvalidated" : "Observed sample"
        string liveAudit = not na(auditIssue) ? na(auditEntry) ? "Pending next open" : "Running · " + priceText(auditEntry) : lastAudit
        int elapsedAudit = na(auditIssue) ? 0 : bar_index - auditIssue
        researchRow(auditGrid, 0, "Forward audit", auditState, amber, "The rate counts target hits against scored cases. It is an observed sample, with a minimum case count before the Unvalidated tag clears.")
        researchRow(auditGrid, 1, "Hits / scored", str.tostring(auditWins) + " / " + str.tostring(scored), teal, "Target wick at or below the frozen C₁ projection before a touch of B and within the window. Evaluation starts at the next opening price.")
        researchRow(auditGrid, 2, "Hit rate · 95% interval", percentText(observedRate) + " · " + percentText(ciLow) + " to " + percentText(ciHigh), silver, "Wilson interval under binomial assumptions. Cases can share market conditions, so this interval is descriptive.")
        researchRow(auditGrid, 3, "B touches / timeouts", str.tostring(auditBoundaryLosses) + " / " + str.tostring(auditTimeouts), silver, "A touch of B is unsuccessful in this audit. Expiration is also unsuccessful. The audit is independent of close-based chart count invalidation.")
        researchRow(auditGrid, 4, "Both touched / skipped", str.tostring(auditAmbiguous) + " / " + str.tostring(auditSkippedOpen + auditSkippedSetup), muted, "Both levels touched with the open inside are counted among B-touch failures. The panel separates opening gaps and invalid setups below.")
        researchRow(auditGrid, 5, "Concurrent candidates skipped", str.tostring(auditConcurrent), muted, "A new count detected during an existing case gets logged as skipped for concurrency. The original case keeps its frozen levels.")
        researchRow(auditGrid, 6, "Latest case", liveAudit, silver, "A later wave relabel does not update a frozen audit case. The conditions remain fixed until resolution.")
        researchRow(auditGrid, 7, "C₁ target / B boundary", priceText(auditTarget) + " / " + priceText(auditBoundary), amber, "Frozen at issue. Price is displayed to the instrument's tick precision.")
        researchRow(auditGrid, 8, "Bars elapsed / max", str.tostring(elapsedAudit) + " / " + str.tostring(auditHorizon), muted, "Horizon starts on the next chart bar. The issue bar is zero. The final eligible bar can still hit either level.")
 
        string avgHitBars = auditWins == 0 ? "—" : str.tostring(float(hitBars) / float(auditWins), "0.0")
        float favorable = na(bestClose) or na(auditEntry) or auditEntry <= 0 ? na : 1.0 - bestClose / auditEntry
        float adverse = na(worstClose) or na(auditEntry) or auditEntry <= 0 ? na : worstClose / auditEntry - 1.0
        researchRow(auditGrid, 9, "Favorable / adverse closes", percentText(favorable) + " / " + percentText(adverse), silver, "Maximum favorable and adverse confirmed closing moves from the reference open, excluding the resolving bar. Zero can mean no intervening closed bar.")
        researchRow(auditGrid, 10, "Hit speed · last / mean", (na(lastHitBars) ? "—" : str.tostring(lastHitBars)) + " / " + avgHitBars + " bars", teal, "Opening bar counts as bar one. Mean uses target hits only. Timeouts and B touches remain in the hit-rate denominator.")
        researchRow(auditGrid, 11, "Setup / opening skips", str.tostring(auditSkippedSetup) + " / " + str.tostring(auditSkippedOpen), muted, "Setup skipped at issue for invalid bounds. Opening skip when the actual first open is already at or outside the issued bounds.")
        if layout == "Audit"
            researchRow(auditGrid, 12, "Issue · UTC", utcText(issuedAt), silver, "Confirmed close that fixed the outcome levels.")
            researchRow(auditGrid, 13, "Entry · UTC", utcText(entryAt), silver, "Next bar opening time.")
            researchRow(auditGrid, 14, "Resolution · UTC", utcText(resolvedAt), silver, "Close timestamp when a hit, failure, timeout, or opening skip was recorded.")
            researchRow(auditGrid, 15, "Opening order", "Open → wick order", muted, "On later bars the opening print is evaluated first. When price opens inside and touches both levels, unresolved order is conservatively scored as unsuccessful.")
 
    if showPaired and layout == "Audit"
        string pairedState = not enabled ? "Inactive on this chart" : pairCompleted < auditMinimum ? "Unvalidated" : "Observed sample"
        researchRow(research, 0, "Matched 3-target audit", pairedState, amber, "Same eligible entry and common B boundary. Counts are included only after all three target outcomes resolve.")
        researchRow(research, 1, "Shallow 0.786", scoreText(array.get(pairHits, 0), pairCompleted), silver, "Easier downside target on the same finished cohort.")
        researchRow(research, 2, "Equal 1.000", scoreText(array.get(pairHits, 1), pairCompleted), amber, "Equal Wave A log leg evaluated on the matched subset.")
        researchRow(research, 3, "Deep 1.272", scoreText(array.get(pairHits, 2), pairCompleted), teal, "Deeper target on the same cohort. Its rate can differ from the primary audit's equal-leg rate.")
        researchRow(research, 4, "Matched exclusions", str.tostring(pairSkipped), muted, "Excludes paired issues with infeasible or coinciding prices, an opening outside the shallow-to-B interval, or an already-running matched case.")
        researchRow(research, 5, "Latest matched case", na(pairIssue) ? "No case pending" : "Tracking 3 targets", silver, "A case can keep running after the primary equal-leg case resolves.")
 
    if layout == "Benchmark"
        int decided = raceDown + raceUp
        int resolvedValid = decided + raceTies + raceTimeout
        string statusBench = not enabled ? "Inactive on this chart" : decided < auditMinimum ? "Unvalidated" : "Observed sample"
        float coverage = resolvedValid > 0 ? float(decided) / float(resolvedValid) : na
        float bias = decided > 0 ? float(raceDown - raceUp) / float(decided) : na
        [wilsonLo, wilsonHi] = wilson(raceDown, decided)
        float signLogP = decided >= auditMinimum ? signLogProbability(raceDown, raceUp) : na
        string pText = decided < auditMinimum ? "Below minimum sample" : decided > 512 ? "Above exact-test limit" : signLogP < math.log(0.0001) ? "<0.0001" : str.tostring(math.exp(signLogP), "0.0000")
        string latestBench = na(race.issueBar) ? "Waiting for case" : race.result != 0 ? raceText(race.result) : na(race.entryAt) ? "Waiting for next open" : "Both directions live"
        researchRow(auditGrid, 0, "Symmetric benchmark", statusBench, amber, "Asks whether downside or upside reaches a matched log distance first after the wave setup.")
        researchRow(auditGrid, 1, "Down / up first", str.tostring(raceDown) + " / " + str.tostring(raceUp), teal, "Both directions have the same entry and deadline. Distance differs only within the permitted tick-rounding imbalance.")
        researchRow(auditGrid, 2, "Downside share · 95%", racePct(raceDown, raceUp) + " · " + percentText(wilsonLo) + " to " + percentText(wilsonHi), silver, "Wilson interval among decisive cases. Serial dependence can make this interval optimistic.")
        researchRow(auditGrid, 3, "Signed direction tilt", percentText(bias), silver, "(Downside first minus upside first) divided by decisive cases. Positive favors downside.")
        researchRow(auditGrid, 4, "Ties / timeouts", str.tostring(raceTies) + " / " + str.tostring(raceTimeout), silver, "Ties have unknown intrabar order. Both categories are excluded from the directional sign test.")
        researchRow(auditGrid, 5, "Decisive coverage", percentText(coverage) + " · " + str.tostring(decided) + "/" + str.tostring(resolvedValid), silver, "Decisive cases divided by all valid resolved benchmarks, including ties and timeouts.")
        researchRow(auditGrid, 6, "Exact sign test · two-sided", pText, silver, "Tests a 50/50 split under independent decisive outcomes. Uses an exact binomial tail from the configured minimum through 512 cases.")
        researchRow(auditGrid, 7, "Elevated ATR · downside", racePct(array.get(raceRegimeDown, 2), array.get(raceRegimeUp, 2)), teal, "At issue, ATR(14) divided by close exceeded its prior 34-bar EMA.")
        researchRow(auditGrid, 8, "Normal / lower ATR · downside", racePct(array.get(raceRegimeDown, 0), array.get(raceRegimeUp, 0)), silver, "At issue, ATR(14) divided by close was at or below its prior 34-bar EMA.")
        researchRow(auditGrid, 9, "No ATR baseline · downside", racePct(array.get(raceRegimeDown, 1), array.get(raceRegimeUp, 1)), muted, "Cases with insufficient ATR or baseline history are reported in their own group.")
        researchRow(auditGrid, 10, "Open / tick / concurrent skips", str.tostring(raceSkipOpen) + " / " + str.tostring(raceSkipTick) + " / " + str.tostring(raceConcurrent), muted, "Opening gaps, tick-size or imbalance failures, and overlapping candidates do not enter the benchmark sample.")
        researchRow(auditGrid, 11, "Latest case", latestBench, amber, "The last benchmark remains visible until the next one is issued.")
        researchRow(auditGrid, 12, "Down / up boundaries", priceText(race.lower) + " / " + priceText(race.upper), teal, "Frozen levels after instrument-tick rounding. The shorter log distance from the open to C1 or B sets the common radius.")
        researchRow(auditGrid, 13, "Width / rounding imbalance", ratioText(race.widthAtr) + " ATR · " + percentText(race.skew), silver, "Approximate average one-sided distance in issue ATR units, plus the actual proportional mismatch between the two rounded log widths.")
        researchRow(auditGrid, 14, "Volatility at issue", na(race.issueBar) ? "—" : regimeText(race.regime), silver, "Assignment is frozen at issue and uses a baseline from previous bars.")
        researchRow(auditGrid, 15, "Latest issue / finish · UTC", utcText(race.issueAt) + " / " + utcText(race.finishAt), silver, "The journal below records the most recent five resolved or skipped cases.")
 
        table.cell(ledger, 0, 0, "Case · resolved UTC", text_color=silver, text_size=size.small)
        table.cell(ledger, 1, 0, "Benchmark outcome", text_color=silver, text_size=size.small)
        table.cell(ledger, 2, 0, "Bars", text_color=silver, text_size=size.small)
        for i = 0 to 4
            if i < array.size(raceJournal)
                RaceRecord item = array.get(raceJournal, i)
                string stamp = str.format_time(item.closedAt, "MM-dd HH:mm", "UTC")
                table.cell(ledger, 0, i + 1, "#" + str.tostring(item.serial) + " · " + stamp, text_color=muted, text_size=size.tiny)
                table.cell(ledger, 1, i + 1, raceText(item.result), text_color=item.result == 1 ? teal : silver, text_size=size.tiny, tooltip=showHelp ? regimeText(item.regime) : "")
                table.cell(ledger, 2, i + 1, str.tostring(item.bars), text_color=silver, text_size=size.tiny)
 
    if showLedger and layout != "Compact" and layout != "Benchmark"
        table.cell(ledger, 0, 0, "Close · UTC", text_color=silver, text_size=size.small)
        table.cell(ledger, 1, 0, "Count event", text_color=silver, text_size=size.small)
        table.cell(ledger, 2, 0, "Price", text_color=silver, text_size=size.small)
        for i = 0 to 5
            bool hasEvent = i < array.size(ledgerNames)
            string whenText = hasEvent ? str.format_time(array.get(ledgerTimes, i), "MM-dd HH:mm", "UTC") : "—"
            string whatText = hasEvent ? str.replace_all(array.get(ledgerNames, i), "_", " ") : "—"
            string closeText = hasEvent ? priceText(array.get(ledgerCloses, i)) : "—"
            table.cell(ledger, 0, i + 1, whenText, text_color=muted, text_size=size.tiny)
            table.cell(ledger, 1, i + 1, whatText, text_color=amber, text_size=size.tiny)
            table.cell(ledger, 2, i + 1, closeText, text_color=silver, text_size=size.tiny)

← 返回列表