Neural Spectrogram Heatmap [AI Cycle Prediction]

Alien_Algorithms · study · 1870 行 · 点赞 135 · TradingView 原页

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

Pine Script

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// For commercial use licensing, contact https://www.tradingview.com/u/Alien_Algorithms/
// © Alien_Algorithms
//@version=6
 
// =============================================================================
//  NEURAL SPECTROGRAM HEATMAP  [Alien_Algorithms]
//
//  Continuous wavelet transform (complex Morlet, cmor8.0-1.0) of detrended
//  log price. The dominant cycle is tracked through time, reconstructed on
//  the price chart and projected forward.
//
//  Engine: each wavelet cell is computed once, when its window completes, on
//  confirmed bars. Each bar's final wave is cached lagW bars later, so an
//  update only recomputes the unfinished edge.
//
//  Forecast: two NeuraLib networks trained walk-forward, one for the period
//  path, one for the phase and amplitude of the coming turns. An output is
//  used only once its out-of-sample record beats the plain projection with
//  95% one-sided confidence. Turn windows come from measured timing errors.
//
//  Libraries:
//    PineCanvas  heatmap field and canvas (5), filled and drawn in 9.3. Fixed
//                dimensions, bar-aligned columns and a fixed value range let
//                unchanged tiles stay cached between updates.
//    OptiPine    FloatRowRings for the final columns, their ridges and peaks,
//                the training rows and the timing errors (8). A Watch decides
//                when the field is rewritten (9.3).
//    NeuraLib    two Sequential models (8.0), scored out of sample before
//                each training pass (8.3, 8.5), queried at the live bar (9.8).
// =============================================================================
 
indicator("Neural Spectrogram Heatmap [AI Cycle Prediction]", shorttitle = "Neural Spectrogram [Alien_Algorithms]", overlay = false, max_boxes_count = 500, max_lines_count = 100, max_labels_count = 150, max_polylines_count = 100, max_bars_back = 3000)
 
import Alien_Algorithms/PineCanvas/1 as pc
import Alien_Algorithms/OptiPine/1 as op
import Alien_Algorithms/NeuraLib/2 as nl
 
// =============================================================================
//  1. INPUTS
// =============================================================================
grpS   = "Scan Range"
periodMin   = input.float(10.0, "Min Period (bars)", minval = 2.0, step = 1.0, group = grpS, tooltip = "Shortest cycle to look for, in bars.")
periodMax   = input.float(45.0, "Max Period (bars)", minval = 4.0, maxval = 150.0, step = 1.0, group = grpS, tooltip = "Longest cycle to look for, in bars. Higher values need more history and load slower.")
bandMinIn   = input.float(0.0,  "Lock Band Min (0 = off)", minval = 0.0, group = grpS, tooltip = "Limits the dominant cycle search to a narrower band. 0 = off.")
bandMaxIn   = input.float(0.0,  "Lock Band Max (0 = off)", minval = 0.0, group = grpS)
if periodMax <= periodMin
    runtime.error("Neural Spectrogram: Max Period must be greater than Min Period.")
 
grpA   = "Analysis"
detrendWinIn= input.float(50.0,  "Detrend Window (0 = auto)", minval = 0.0, maxval = 600.0, group = grpA, tooltip = "How much trend is removed before cycles are measured. 0 = automatic (2 x Max Period).")
tapFactor   = input.float(4.0,  "Wavelet Support", minval = 2.5, maxval = 6.0, step = 0.5, group = grpA, tooltip = "How many cycles the wavelet looks at. Higher gives a smoother heatmap, but more recent bars stay unfinished and more history is needed.")
ridgeSmooth = input.float(8.0,  "Ridge Smoothing (bars)", minval = 0.0, group = grpA, tooltip = "Smooths how the dominant cycle length changes over time.")
sigLevel    = input.float(0.95, "Significance Level", minval = 0.50, maxval = 0.999, step = 0.01, group = grpA, tooltip = "How strict the test is that tells a real cycle from random noise. Higher is stricter.")
liveBw      = input.float(0.2,  "Live Filter Bandwidth", minval = 0.05, maxval = 0.4, step = 0.05, group = grpA, tooltip = "Width of the real-time cycle filter. Narrower is sharper but less stable.")
edgeFuse    = input.bool(true,  "Fuse Live at Edge", group = grpA, tooltip = "Near the last bar the wavelet cannot see far enough ahead. When on, the wave leans on the real-time estimate there.")
 
grpD   = "Display"
displayBars = input.int(800, "History Window (bars)", minval = 40, maxval = 2000, group = grpD, tooltip = "How many recent bars the heatmap and the wave cover.")
nColsIn     = input.int(800,  "Time Resolution (columns)", minval = 6, group = grpD, tooltip = "Number of heatmap columns. More is sharper but slower.")
nRows       = input.int(80,  "Scale Resolution (rows)", minval = 6, group = grpD, tooltip = "Number of cycle length rows in the heatmap.")
voicesPerOct= input.int(14,  "Scale Compute Density (voices/octave)", minval = 4, maxval = 64, group = grpD, tooltip = "How many cycle lengths are computed per doubling; the rows between them are blended. Lower is faster.")
projPeriods = input.float(1.0, "Projection (cycles ahead)", minval = 0.0, maxval = 5.0, step = 0.5, group = grpD, tooltip = "How far ahead to forecast, in cycles. 0 = off.")
 
grpF   = "Cycle Forecast"
useLearned  = input.bool(true, "Learned Forecast (NeuraLib)", group = grpF, tooltip = "Two small neural networks learn on your chart. One forecasts how the cycle length will change, the other corrects the timing and height of the coming highs and lows. Each is used only once it has proven more accurate than the plain forecast. Off = plain forecast.")
trainExtra  = input.int(1000, "Extra Training History (bars)", minval = 0, maxval = 4000, step = 100, group = grpF, tooltip = "Extra history for the networks to learn from. More history gives them a better chance to prove themselves, but loads slower.")
 
grpV   = "Visuals"
showHeat    = input.bool(true,  "Scalogram Heatmap", group = grpV)
heatColors  = input.int(30, "Heatmap Colors", minval = 8, maxval = 100, group = grpV, tooltip = "Number of colour levels in the heatmap.")
showCOI     = input.bool(true,  "Cone of Influence", group = grpV)
showDom     = input.bool(true,  "Dominant Ridge & Value", group = grpV, tooltip = "A line through the heatmap at the cycle length the wave follows (solid = final, dotted = may still change), with its current value. An arrow means the cycle sits at the edge of the scan range.")
showLive    = input.bool(true,  "Live Period (causal)", group = grpV, tooltip = "Marks the real-time estimate of the cycle length, as a cross-check.")
showLegend  = input.bool(true,  "Wavelength Colour Key", group = grpV, tooltip = "Colour key for cycle lengths, with the dominant and live values.")
colBg       = input.color(#000000, "Pane Background", group = grpV)
colRidge    = input.color(#39c2d7, "Dominant",  group = grpV)
colTop      = input.color(#e25a5a, "Top",    group = grpV)
colBot      = input.color(#52c46a, "Bottom", group = grpV)
 
grpP   = "Price Overlay (on the price chart)"
showWave     = input.bool(true,  "Reconstructed Cycle Wave", group = grpP, tooltip = "Draws the dominant cycle on the price chart, coloured by its length, with a dot at each past high and low. A dotted line marks where the wave may still change.")
showWaveProj = input.bool(true,  "Projected Path", group = grpP, tooltip = "Dotted forecast of the cycle, with two faint paths for a faster and a slower cycle.")
showTurns    = input.bool(true,  "Projected Turn Windows", group = grpP, tooltip = "Marks when the next highs (red) and lows (green) are due, with a timing window sized by how far past forecasts missed. Hover a label for details.")
turnTol      = input.float(0.12, "Minimum Turn Window (cycles)", minval = 0.02, maxval = 0.5, step = 0.02, group = grpP, tooltip = "Narrowest timing window allowed, as a share of the cycle. Also used until there is a track record.")
waveAmp      = input.float(1.0,  "Wave Amplitude", minval = 0.1, maxval = 5.0, step = 0.1, group = grpP, tooltip = "Height of the cycle wave on price.")
waveSteps    = input.int(8,      "Wave Colour Steps", minval = 1, maxval = 16, group = grpP, tooltip = "How many colour steps the wave is split into. Each step uses two drawing slots.")
waveSmooth   = input.float(1.0,  "Wave Smoothness", minval = 0.0, maxval = 3.0, step = 0.5, group = grpP, tooltip = "Smooths the wave's shape. 0 = raw, higher = a cleaner sine.")
 
// =============================================================================
//  2. CONSTANTS
// =============================================================================
// cmor8.0-1.0: envelope exp(-t^2 / BW), carrier exp(2 pi i CF t), scale = period.
BW        = 8.0
CF        = 1.0
TWO_PI    = 2.0 * math.pi
COI_SCALE = math.sqrt(BW) * CF
 
const int   LIVE_ROWS      = 24
const int   LIVE_THIRD     = 8
const int   MAX_PAST_TURNS = 30
const int   MAX_TURNS      = 12
 
// Period model. Features and targets are dimensionless, so fixed scales suit any symbol.
const int   N_FEAT         = 9
const int   N_TGT          = 4
const int   HIDDEN         = 12
const float LEARN_RATE     = 0.004
const int   MODEL_SEED     = 7
const int   TRAIN_PASSES   = 2
const int   TRAIN_EVERY    = 2       // samples between training passes
const int   MIN_TRAIN      = 24      // samples before the first pass
const int   WARMUP         = 60      // samples before out-of-sample scoring starts
const int   MIN_OOS        = 30      // scored samples before the forecast may be used
const float OOS_WIN        = 120.0   // effective window of the error averages
const float T_SIG          = 1.645   // one-sided 95%
const int   MAX_TRAIN_ROWS = 320     // newest samples in each training batch
// Feature scales, calibrated on BTC 1h, ETH 15m and SOL 4h.
const float TGT_SCALE      = 0.5
const float FS_LEVEL       = 0.4     // log period levels
const float FS_SLOPE       = 0.15    // centroid drift
const float FS_LIVE_SL     = 0.6     // live peak drift
const float FEAT_CLAMP     = 4.0
const float Z_FAN          = 1.2816  // two-sided 80%
const float Z_HALF         = 0.6745  // two-sided 50%
const float PIVOT_MIN      = 0.5     // min swing between past turns, in cycle RMS
 
// Turn model. Targets: (cos d - 1, sin d) of the phase correction d, and the
// scaled log amplitude ratio. Zero output means no correction.
const int   N_TFEAT        = 9
const int   N_TTGT         = 3
const float AMP_SCALE      = 0.7
const int   RMS_LEN        = 100     // EMA length of the final wave's square
const int   ERR_KEEP       = 120     // newest timing errors kept for the 80th percentile
 
// =============================================================================
//  3. HELPERS
// =============================================================================
lerp(float a, float b, float f) => a + (b - a) * f
 
// Period colour scale, blue (short) to red (long).
spectrumColor(float u) =>
    x = math.max(0.0, math.min(1.0, u))
    float r = 0.0
    float g = 0.0
    float b = 0.0
    if x < 0.25
        f = x / 0.25
        r := lerp(30, 0, f)
        g := lerp(110, 210, f)
        b := lerp(240, 230, f)       // blue to cyan
    else if x < 0.5
        f = (x - 0.25) / 0.25
        r := lerp(0, 60, f)
        g := lerp(210, 220, f)
        b := lerp(230, 120, f)       // cyan to green
    else if x < 0.75
        f = (x - 0.5) / 0.25
        r := lerp(60, 240, f)
        g := lerp(220, 225, f)
        b := lerp(120, 50, f)        // green to yellow
    else
        f = (x - 0.75) / 0.25
        r := lerp(240, 255, f)
        g := lerp(225, 60, f)
        b := lerp(50, 60, f)         // yellow to red
    color.rgb(int(math.round(r)), int(math.round(g)), int(math.round(b)))
 
LOG_PMIN  = math.log(periodMin)
LOG_PSPAN = math.log(periodMax) - LOG_PMIN
pcol(float period) =>
    spectrumColor(LOG_PSPAN > 0 ? (math.log(period) - LOG_PMIN) / LOG_PSPAN : 0.5)
 
// Inverse standard normal CDF (Acklam's rational approximation).
normInv(float p) =>
    a1 = -39.6968302866538
    a2 = 220.946098424521
    a3 = -275.928510446969
    a4 = 138.357751867269
    a5 = -30.6647980661472
    a6 = 2.50662827745924
    b1 = -54.4760987982241
    b2 = 161.585836858041
    b3 = -155.698979859887
    b4 = 66.8013118877197
    b5 = -13.2806815528857
    c1 = -0.00778489400243029
    c2 = -0.322396458041136
    c3 = -2.40075827716184
    c4 = -2.54973253934373
    c5 = 4.37466414146497
    c6 = 2.93816398269878
    d1 = 0.00778469570904146
    d2 = 0.32246712907004
    d3 = 2.445134137143
    d4 = 3.75440866190742
    pl = 0.02425
    float z = 0.0
    if p < pl
        q = math.sqrt(-2.0 * math.log(p))
        z := (((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1.0)
    else if p <= 1.0 - pl
        q = p - 0.5
        rr = q * q
        z := (((((a1 * rr + a2) * rr + a3) * rr + a4) * rr + a5) * rr + a6) * q / (((((b1 * rr + b2) * rr + b3) * rr + b4) * rr + b5) * rr + 1.0)
    else
        q = math.sqrt(-2.0 * math.log(1.0 - p))
        z := -(((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1.0)
    z
 
// Chi square inverse CDF via Wilson-Hilferty, given z = normInv(level).
chi2inv(float nu, float z) =>
    h = 2.0 / (9.0 * nu)
    nu * math.pow(math.max(1e-9, 1.0 - h + z * math.sqrt(h)), 3.0)
 
// Clamped, na-safe feature value.
fz(float v) =>
    math.max(-FEAT_CLAMP, math.min(FEAT_CLAMP, nz(v)))
 
smooth01(float e) =>
    e * e * (3.0 - 2.0 * e)
 
fmtPct(float v) =>
    (v >= 0 ? "+" : "") + str.tostring(v * 100.0, "#") + "%"
 
// atan2, result in (-pi, pi].
atan2(float y, float x) =>
    x > 0 ? math.atan(y / x) : x < 0 ? math.atan(y / x) + (y >= 0 ? math.pi : -math.pi) : y > 0 ? 0.5 * math.pi : y < 0 ? -0.5 * math.pi : 0.0
 
wrapPi(float a) =>
    a - TWO_PI * math.floor((a + math.pi) / TWO_PI)
 
// EMA record of d = e_base^2 - e_model^2: [mean, mean square, lag-1 product,
// last d, product count].
pairAdd(array<float> rec, float d, float w) =>
    array.set(rec, 0, array.get(rec, 0) + (d - array.get(rec, 0)) * w)
    array.set(rec, 1, array.get(rec, 1) + (d * d - array.get(rec, 1)) * w)
    float prev = array.get(rec, 3)
    if not na(prev)
        float nC = array.get(rec, 4) + 1.0
        array.set(rec, 2, array.get(rec, 2) + (d * prev - array.get(rec, 2)) * math.max(1.0 / nC, 1.0 / OOS_WIN))
        array.set(rec, 4, nC)
    array.set(rec, 3, d)
 
// t statistic of the mean of d, with n reduced for lag-1 autocorrelation and
// capped by the EMA memory.
pairT(array<float> rec, int n) =>
    float m   = array.get(rec, 0)
    float v   = math.max(array.get(rec, 1) - m * m, 1e-30)
    float rho = math.max(0.0, math.min(0.95, (array.get(rec, 2) - m * m) / v))
    float nE  = math.min(n, 2.0 * OOS_WIN - 1.0) * (1.0 - rho) / (1.0 + rho)
    n >= 2 ? m / math.sqrt(v / math.max(nE, 1.0)) : 0.0
 
// 0.25/0.5/0.25 blur across the rows of a column stored from `base`, edges clamped.
blurAt(array<float> src, int base, int r, int rows) =>
    0.25 * array.get(src, base + math.max(r - 1, 0)) + 0.5 * array.get(src, base + r) + 0.25 * array.get(src, base + math.min(r + 1, rows - 1))
 
// Column ridge: argmax of the blurred magnitude over the band rows, with
// parabolic refinement. Returns a log period, or na.
columnRidge(array<float> src, int base, int rLo, int rHi, int rows, array<float> logPeriods, float dLog) =>
    float bestV = -1.0
    int   bestR = -1
    for r = rLo to rHi
        float v = blurAt(src, base, r, rows)
        if v > bestV
            bestV := v
            bestR := r
    float result = na
    if bestR >= 0
        result := array.get(logPeriods, bestR)
        if bestR > 0 and bestR < rows - 1
            float y0 = blurAt(src, base, bestR - 1, rows)
            float y2 = blurAt(src, base, bestR + 1, rows)
            float dn = y0 - 2.0 * bestV + y2
            if dn < 0
                result += math.max(-0.5, math.min(0.5, 0.5 * (y0 - y2) / dn)) * dLog
    result
 
// Largest blurred magnitude of a column.
columnPeak(array<float> src, int base, int rows) =>
    float pk = na
    for r = 0 to rows - 1
        float v = blurAt(src, base, r, rows)
        if not na(v)
            pk := na(pk) ? v : math.max(pk, v)
    pk
 
// 1 / triangular mean of the column peaks within h of j, limited to lo..hi.
peakGain(array<float> peaks, int j, int lo, int hi, int h) =>
    float acc = 0.0
    float ws  = 0.0
    for k = math.max(lo, j - h) to math.min(hi, j + h)
        float p = array.get(peaks, k)
        if not na(p)
            float w = h + 1.0 - math.abs(k - j)
            acc += w * p
            ws  += w
    acc > 0.0 ? ws / acc : na
 
// Mean ridge log period of ids center-half..center+half, skipping missing ones.
ringSmoothed(op.FloatRowRing ring, int newestId, int center, int half) =>
    float acc = 0.0
    int   cnt = 0
    for j = center - half to center + half
        int off = newestId - j
        if off >= 0
            float v = ring.newestAt(off, 0)
            if not na(v)
                acc += v
                cnt += 1
    cnt > 0 ? acc / cnt : na
 
// Fritsch-Carlson slope at interior knot k.
pchipSlope(array<int> knots, array<float> vals, int k) =>
    float hPrev = array.get(knots, k) - array.get(knots, k - 1)
    float hNext = array.get(knots, k + 1) - array.get(knots, k)
    float dPrev = (array.get(vals, k) - array.get(vals, k - 1)) / hPrev
    float dNext = (array.get(vals, k + 1) - array.get(vals, k)) / hNext
    float w1 = 2.0 * hNext + hPrev
    float w2 = hNext + 2.0 * hPrev
    dPrev * dNext <= 0 ? 0.0 : (w1 + w2) / (w1 / dPrev + w2 / dNext)
 
// PCHIP through (knots, vals), flat past the last knot.
knotSmooth(array<int> knots, array<float> vals, float h) =>
    int n = array.size(knots)
    float result = array.get(vals, n - 1)
    if h <= array.get(knots, 0)
        result := array.get(vals, 0)
    else if h < array.get(knots, n - 1)
        for i = 1 to n - 1
            float x1 = array.get(knots, i)
            if h <= x1
                float x0 = array.get(knots, i - 1)
                float y0 = array.get(vals, i - 1)
                float y1 = array.get(vals, i)
                float hw = x1 - x0
                float m0 = i == 1 ? (y1 - y0) / hw : pchipSlope(knots, vals, i - 1)
                float m1 = i == n - 1 ? 0.0 : pchipSlope(knots, vals, i)
                float s  = (h - x0) / hw
                float s2 = s * s
                float s3 = s2 * s
                result := (2.0 * s3 - 3.0 * s2 + 1.0) * y0 + (s3 - 2.0 * s2 + s) * hw * m0 + (3.0 * s2 - 2.0 * s3) * y1 + (s3 - s2) * hw * m1
                break
    result
 
// First fractional step at which a cumulative phase path reaches `target`.
crossAt(array<float> phiArr, int base, int len, float target) =>
    float result = na
    for h = 1 to len - 1
        float p1 = array.get(phiArr, base + h)
        if p1 >= target
            float p0 = array.get(phiArr, base + h - 1)
            result := h - 1 + (p1 > p0 ? (target - p0) / (p1 - p0) : 0.0)
            break
    result
 
// Appends a row. ring.push(row) does the same but warns that it shadows
// array.push.
pushRow(op.FloatRowRing ring, array<float> row) =>
    ring.writePhysical(ring.reserveRowUnchecked(), row)
 
// Both models train with the same configuration.
modelConfig() =>
    nl.compileConfig()
      .loss(nl.LossKind.huber)
      .optimizer(nl.adamW(LEARN_RATE))
      .trainEveryCall()
      .historyLength(16)
      .clipNorm(1.0)
 
// Trains on every row held in the two rings, oldest first.
trainOnRings(nl.Sequential m, op.FloatRowRing xs, op.FloatRowRing ys, array<float> xBuf, array<float> yBuf) =>
    int rows = xs.rowCount()
    nl.Tensor xT = nl.Tensor.new("x", xs.chronological(xBuf), nl.shapeFromDims(array.from(rows, xs.rowWidth())))
    nl.Tensor yT = nl.Tensor.new("y", ys.chronological(yBuf), nl.shapeFromDims(array.from(rows, ys.rowWidth())))
    nl.Sequential trained = m
    for _ = 1 to TRAIN_PASSES
        trained := trained.trainOnBatch(xT, yT)
    trained
 
// Drawing pools: item i is moved and restyled in place, or created on first
// use. Each returns i + 1. A label pool keeps one placement, price or pane.
poolLabel(array<label> pool, int i, bool onPrice, int x, float y, string txt, string st, color bg, color fg, string sz, string tip) =>
    if i < array.size(pool)
        label lb = array.get(pool, i)
        label.set_xy(lb, x, y)
        label.set_text(lb, txt)
        label.set_style(lb, st)
        label.set_color(lb, bg)
        label.set_textcolor(lb, fg)
        label.set_size(lb, sz)
        label.set_tooltip(lb, tip)
    else if onPrice
        array.push(pool, label.new(x, y, txt, xloc = xloc.bar_index, style = st, color = bg, textcolor = fg, size = sz, tooltip = tip, force_overlay = true))
    else
        array.push(pool, label.new(x, y, txt, xloc = xloc.bar_index, style = st, color = bg, textcolor = fg, size = sz, tooltip = tip))
    i + 1
 
// Price chart boxes without a border.
poolBox(array<box> pool, int i, int x0, float y0, int x1, float y1, color bg) =>
    if i < array.size(pool)
        box b = array.get(pool, i)
        box.set_lefttop(b, x0, y0)
        box.set_rightbottom(b, x1, y1)
        box.set_bgcolor(b, bg)
    else
        array.push(pool, box.new(x0, y0, x1, y1, border_color = color.new(color.black, 100), border_width = 0, bgcolor = bg, xloc = xloc.bar_index, force_overlay = true))
    i + 1
 
// Dotted vertical markers on the price chart, extended both ways.
poolLine(array<line> pool, int i, int x, float y0, float y1, color col) =>
    if i < array.size(pool)
        line ln = array.get(pool, i)
        line.set_xy1(ln, x, y0)
        line.set_xy2(ln, x, y1)
        line.set_color(ln, col)
    else
        array.push(pool, line.new(x, y0, x, y1, xloc = xloc.bar_index, extend = extend.both, color = col, width = 1, style = line.style_dotted, force_overlay = true))
    i + 1
 
trimLabels(array<label> pool, int n) =>
    while array.size(pool) > n
        label.delete(array.pop(pool))
 
trimBoxes(array<box> pool, int n) =>
    while array.size(pool) > n
        box.delete(array.pop(pool))
 
trimLines(array<line> pool, int n) =>
    while array.size(pool) > n
        line.delete(array.pop(pool))
 
// =============================================================================
//  4. SIZING (input-derived, resolved once)
// =============================================================================
sigmaG    = (detrendWinIn > 0 ? detrendWinIn : 2.0 * periodMax) / 4.0
gHalf     = math.max(1, int(math.ceil(3.0 * sigmaG)))
maxK      = int(math.round(tapFactor * periodMax))
FIN_LAG   = maxK + gHalf               // a column is final this many bars after its centre
KSTRIDE   = maxK + 1
 
// Columns are colStep bars wide, centred on bars that are multiples of colStep.
colStep   = math.max(1, int(math.round(displayBars / float(nColsIn))))
nCols     = math.max(6, int(math.ceil(displayBars / float(colStep))))
spanBars  = nCols * colStep
halfStep  = int(math.floor(colStep / 2.0))
 
// Computed rows (cRows) are interpolated onto the display rows (nRows).
octaves   = math.log(periodMax / periodMin) / math.log(2.0)
cRows     = int(math.min(nRows, math.max(6, int(math.ceil(octaves * voicesPerOct)) + 1)))
 
ratioLog  = nRows > 1 ? math.pow(periodMax / periodMin, 1.0 / (nRows - 1)) : 1.0
edge0     = periodMin / math.sqrt(ratioLog)
edgeN     = periodMax * math.sqrt(ratioLog)
dLogP     = math.log(periodMax / periodMin) / math.max(1.0, nRows - 1.0)
dLogLive  = math.log(periodMax / periodMin) / (LIVE_ROWS - 1.0)
 
bandMin   = bandMinIn > 0 ? math.max(bandMinIn, periodMin) : periodMin
bandMax   = bandMaxIn > 0 ? math.min(bandMaxIn, periodMax) : periodMax
bandLo    = bandMin >= bandMax ? periodMin : bandMin
bandHi    = bandMin >= bandMax ? periodMax : bandMax
 
ridgeHalf = math.max(0, int(math.round(ridgeSmooth / colStep / 2.0)))
// Columns are scaled by their peak, smoothed over about one Min Period. The
// column minimum sits on the nulls between bands and jumps from column to column.
scaleHalf = int(math.min(6.0, math.max(1.0, math.round(periodMin / colStep))))
pMid      = math.sqrt(periodMin * periodMax)
logPMid   = math.log(pMid)
// Fixed widths, so final bars stay final.
recHalf   = int(math.min(20.0, math.round(waveSmooth * pMid / 5.0)))
cycHalf   = int(math.min(10.0, math.round(waveSmooth * pMid / 14.0)))
 
// Bars older than lagW are final in every stage.
lagW      = FIN_LAG + (ridgeHalf + 2) * colStep + recHalf + cycHalf
zoneLen   = math.min(displayBars, lagW + 1 + colStep)
PROV      = int(math.ceil(FIN_LAG / float(colStep))) + 2
CAPB      = displayBars + lagW + 64
 
hasProjIn = projPeriods > 0
modelOn   = useLearned and hasProjIn
modelH    = int(math.min(200.0, math.max(8.0, math.ceil(math.max(projPeriods, 0.5) * periodMax))))
hK1       = math.max(1, int(math.round(modelH / 3.0)))
hK2       = math.max(hK1 + 1, int(math.round(2.0 * modelH / 3.0)))
// Period samples are read O_ANCHOR bars back, once all four targets are final.
O_ANCHOR  = FIN_LAG + ridgeHalf * colStep + modelH
SLOPE_LAG = math.max(2, int(math.round(pMid / 2.0)))
trainBars = modelOn ? trainExtra : 0
trainRows = int(math.min(MAX_TRAIN_ROWS, math.max(MIN_TRAIN, math.ceil((spanBars + trainBars) / float(colStep)))))
CAPR      = nCols + int(math.ceil((O_ANCHOR + FIN_LAG + 64) / float(colStep))) + 2 * ridgeHalf + 8
// History the engine needs before the last bar.
needHist  = spanBars + trainBars + FIN_LAG + maxK + gHalf + O_ANCHOR + 8 * colStep
zLevel    = normInv(sigLevel)
 
// Final wave pipeline (8.4).
S2_AGE    = lagW - cycHalf - recHalf
PIPE      = 2 * (recHalf + cycHalf) + 4
// Turn samples (8.5), one every TSTEP bars.
turnOn    = hasProjIn
TSTEP     = math.max(2, int(math.round(pMid / 3.0)))
TPEND     = int(math.ceil(lagW / float(TSTEP))) + 2
EDGE_LEN  = cycHalf + 2 + maxK
EDGE_CAP  = edgeFuse ? 0.85 : 0.0     // max live weight at the edge
 
// Polylines outside the heatmap: COI, wave and glow, projection, ridge and halo.
polyReserve    = (showCOI ? 2 : 0) + (showWave ? 2 * waveSteps : 0) + (hasProjIn and showWaveProj ? 5 : 0) + (showDom ? 4 : 0)
polylineBudget = int(math.max(8, 100 - polyReserve))
heatLevelCount = int(math.min(math.min(heatColors, polylineBudget), nRows * nCols))
 
// =============================================================================
//  5. HEATMAP AND TABLES (built once)
// =============================================================================
// Cells are |W| / scale times the column gain (9.3): about 0..1, clamped above.
var pc.ValueField heatField = pc.valueField(nRows, nCols)
var pc.Canvas     g_heatmap = pc.heatmap(pc.gradient(#0c0a26, #460553, #800080, #ff6600, #ffe600))
  .valueRange(0.0, 1.0)
  .opacity(18.0, 90.0)
  .gamma(1.5)
  .logarithmicY()
  .colorLevels(heatLevelCount)
  .drawingLimit(polylineBudget)
 
var array<float> wG        = array.new_float(gHalf + 1, 0.0)    // Gaussian detrend kernel
var float        wsum      = 0.0
var array<float> periods   = array.new_float(nRows, 0.0)        // display grid
var array<float> logPer    = array.new_float(nRows, 0.0)
var array<float> edges     = array.new_float(nRows + 1, 0.0)
var array<float> rowNorm   = array.new_float(nRows, 0.0)        // p / sum(w^2): red noise normalisation
var array<int>   rowBand   = array.new_int(nRows, 0)            // field band holding each row
var array<int>   rowLocal  = array.new_int(nRows, 0)            // that row's base inside its band
var int          bandRow0  = 0
var int          bandRow1  = nRows - 1
var array<float> cPeriods  = array.new_float(cRows, 0.0)        // compute grid
var array<int>   cRowK     = array.new_int(cRows, 0)
var array<float> kerC      = array.new_float(cRows * KSTRIDE, 0.0)   // w_m cos(w0 m), per row
var array<float> kerS      = array.new_float(cRows * KSTRIDE, 0.0)   // w_m sin(w0 m), per row
var array<int>   mapLo     = array.new_int(nRows, 0)            // display row -> compute rows
var array<int>   mapHi     = array.new_int(nRows, 0)
var array<float> mapFr     = array.new_float(nRows, 0.0)
 
if barstate.isfirst
    float accW = 0.0
    for j = 0 to gHalf
        float w = math.exp(-(j * j) / (2.0 * sigmaG * sigmaG))
        array.set(wG, j, w)
        accW += j == 0 ? w : 2.0 * w
    wsum := accW
 
    for r = 0 to nRows - 1
        float p = periodMin * math.pow(periodMax / periodMin, nRows > 1 ? r / (nRows - 1.0) : 0.0)
        array.set(periods, r, p)
        array.set(logPer, r, math.log(p))
        int   Kr  = int(math.min(maxK, math.round(tapFactor * p)))
        float aGr = 1.0 / (BW * p * p)
        float s2w = 1.0
        for m = 1 to Kr
            s2w += 2.0 * math.exp(-2.0 * aGr * m * m)
        array.set(rowNorm, r, p / s2w)
    for r = 0 to nRows
        array.set(edges, r, edge0 * math.pow(ratioLog, r))
 
    int b0 = -1
    int b1 = -1
    for r = 0 to nRows - 1
        float p = array.get(periods, r)
        if p >= bandLo and p <= bandHi
            b0 := b0 < 0 ? r : b0
            b1 := r
    if b0 < 0
        int rc = int(math.max(0, math.min(nRows - 1, math.round((math.log(math.sqrt(bandLo * bandHi)) - LOG_PMIN) / dLogP))))
        b0 := rc
        b1 := rc
    bandRow0 := b0
    bandRow1 := b1
 
    // Morlet taps per compute row via weight and rotation recurrences.
    for cr = 0 to cRows - 1
        float p = periodMin * math.pow(periodMax / periodMin, cRows > 1 ? cr / (cRows - 1.0) : 0.0)
        int   K = int(math.min(maxK, math.round(tapFactor * p)))
        array.set(cPeriods, cr, p)
        array.set(cRowK, cr, K)
        float aG     = 1.0 / (BW * p * p)
        float cw     = math.cos(TWO_PI / p)
        float sw     = math.sin(TWO_PI / p)
        float wm     = 1.0
        float ratio  = math.exp(-aG)
        float dratio = math.exp(-2.0 * aG)
        float cc     = 1.0
        float ss     = 0.0
        int   kb     = cr * KSTRIDE
        array.set(kerC, kb, 1.0)
        array.set(kerS, kb, 0.0)
        for m = 1 to K
            wm := wm * ratio
            ratio := ratio * dratio
            float nc = cc * cw - ss * sw
            ss := ss * cw + cc * sw
            cc := nc
            array.set(kerC, kb + m, wm * cc)
            array.set(kerS, kb + m, wm * ss)
 
    float mapDen = nRows > 1 ? nRows - 1.0 : 1.0
    for r = 0 to nRows - 1
        float cpos = cRows > 1 ? r * (cRows - 1.0) / mapDen : 0.0
        int lo = int(math.min(cRows - 1, math.floor(cpos)))
        array.set(mapLo, r, lo)
        array.set(mapHi, r, int(math.min(cRows - 1, lo + 1)))
        array.set(mapFr, r, cpos - lo)
 
    // Field rows are written straight into the field's storage bands.
    for bi = 0 to heatField.bandCount() - 1
        int bs  = heatField.bandStart(bi)
        int brs = heatField.bandRows(bi)
        for lr = 0 to brs - 1
            array.set(rowBand, bs + lr, bi)
            array.set(rowLocal, bs + lr, lr * nCols)
 
// Anchor the pane's price scale to the period range.
plot(edge0, "scaleLo", color = color.new(color.gray, 100), display = display.pane, editable = false)
plot(edgeN, "scaleHi", color = color.new(color.gray, 100), display = display.pane, editable = false)
bgcolor(color.new(colBg, 0), editable = false)
 
// =============================================================================
//  6. LIVE BANK AND FORECAST FEATURES (causal, every bar)
// =============================================================================
// Ehlers band-pass bank: live period, edge fusion and model inputs.
// bp = 0.5(1-a)(src - src[2]) + b(1+a)bp[1] - a bp[2]
var array<float> ebp1   = array.new_float(LIVE_ROWS, 0.0)
var array<float> ebp2   = array.new_float(LIVE_ROWS, 0.0)
var array<float> epwr   = array.new_float(LIVE_ROWS, 0.0)
var array<float> eBeta  = array.new_float(LIVE_ROWS, 0.0)
var array<float> eAlpha = array.new_float(LIVE_ROWS, 0.0)
var array<float> eLog   = array.new_float(LIVE_ROWS, 0.0)
if barstate.isfirst
    for i = 0 to LIVE_ROWS - 1
        float pL     = periodMin * math.pow(periodMax / periodMin, i / (LIVE_ROWS - 1.0))
        float gammaB = 1.0 / math.cos(math.min(1.4, 2.0 * TWO_PI * liveBw / pL))
        array.set(eBeta,  i, math.cos(TWO_PI / pL))
        array.set(eAlpha, i, gammaB - math.sqrt(gammaB * gammaB - 1.0))
        array.set(eLog,   i, math.log(pL))
 
liveDiff = nz(hl2 - hl2[2])
float liveMaxP = 0.0
int   liveIdx  = 0
float totPow   = 0.0
float centAcc  = 0.0
float loPow    = 0.0
float hiPow    = 0.0
for i = 0 to LIVE_ROWS - 1
    float alphaB = array.get(eAlpha, i)
    float pbp1   = array.get(ebp1, i)
    float bpv    = 0.5 * (1.0 - alphaB) * liveDiff + array.get(eBeta, i) * (1.0 + alphaB) * pbp1 - alphaB * array.get(ebp2, i)
    float prevP  = array.get(epwr, i)
    float spow   = prevP + (bpv * bpv - prevP) / 5.0
    array.set(ebp2, i, pbp1)
    array.set(ebp1, i, bpv)
    array.set(epwr, i, spow)
    totPow  += spow
    centAcc += spow * array.get(eLog, i)
    loPow   += i < LIVE_THIRD ? spow : 0.0
    hiPow   += i >= LIVE_ROWS - LIVE_THIRD ? spow : 0.0
    if spow > liveMaxP
        liveMaxP := spow
        liveIdx  := i
// Parabolic refinement between bins.
float logLive = array.get(eLog, liveIdx)
if liveIdx > 0 and liveIdx < LIVE_ROWS - 1
    float ly0 = array.get(epwr, liveIdx - 1)
    float ly2 = array.get(epwr, liveIdx + 1)
    float ldn = ly0 - 2.0 * liveMaxP + ly2
    if ldn < 0
        logLive += math.max(-0.5, math.min(0.5, 0.5 * (ly0 - ly2) / ldn)) * dLogLive
liveDom = math.exp(logLive)
// Band-pass phase at the peak bin, from its last two outputs.
float omB   = TWO_PI / math.exp(array.get(eLog, liveIdx))
float psiBp = atan2((array.get(ebp2, liveIdx) - array.get(ebp1, liveIdx) * math.cos(omB)) / math.max(1e-9, math.sin(omB)), array.get(ebp1, liveIdx))
 
// Period model features (dimensionless).
float centLog = totPow > 0 ? centAcc / totPow : logPMid
float atrS    = ta.atr(14)
float atrL    = ta.atr(100)
float powEma  = ta.ema(totPow, 100)
float fLiveF  = fz((logLive - logPMid) / FS_LEVEL)                                     // where the live peak is
float fCentF  = fz((centLog - logPMid) / FS_LEVEL)                                     // where the energy is
float fLiveSl = fz((logLive - logLive[SLOPE_LAG]) / FS_LIVE_SL)                        // peak drift
float fCentSl = fz((centLog - centLog[SLOPE_LAG]) / FS_SLOPE)                          // energy drift
float fConcF  = fz(totPow > 0 ? (math.log(liveMaxP * LIVE_ROWS / totPow) - 1.0) / 0.7 : 0.0)   // how peaked
float fTiltF  = fz(math.log((hiPow + 1e-9 * totPow + 1e-300) / (loPow + 1e-9 * totPow + 1e-300)) / 1.5)   // long vs short energy
float fVolF   = fz(math.log(atrS / atrL) / 0.3)                                       // volatility regime
float fPowF   = fz(math.log((totPow + 1e-300) / (powEma + 1e-300)) / 0.7)             // cycle energy regime
 
// =============================================================================
//  7. DETRENDED SAMPLES
// =============================================================================
// xF / trendF: final detrended log price and trend of bar t - gHalf. The
// newest gHalf bars are padded at update time.
float lc = na
lc := close > 0 ? math.log(close) : nz(lc[1])
engineOn = bar_index >= last_bar_index - needHist
 
float trendF = na
float xF     = na
if engineOn and bar_index >= 2 * gHalf
    float accT = array.get(wG, 0) * lc[gHalf]
    for j = 1 to gHalf
        accT += array.get(wG, j) * (lc[gHalf - j] + lc[gHalf + j])
    trendF := accT / wsum
    xF     := lc[gHalf] - trendF
 
var int firstSample = na    // absolute bar of the first final sample
if na(firstSample) and not na(xF)
    firstSample := bar_index - gHalf
 
// Complex Morlet coefficient at `age` of the samples-by-age array xs, period
// exp(logP), normalised by the weight of the taps present. Wave = |W| cos(angle).
morletAt(array<float> xs, int age, float logP) =>
    float pA     = math.exp(logP)
    float aGA    = 1.0 / (BW * pA * pA)
    int   KA     = int(math.min(maxK, math.round(tapFactor * pA)))
    float cw     = math.cos(TWO_PI / pA)
    float sw     = math.sin(TWO_PI / pA)
    float wr     = array.get(xs, age)
    float wi     = 0.0
    float wm     = 1.0
    float wsumA  = 1.0
    float ratio  = math.exp(-aGA)
    float dratio = math.exp(-2.0 * aGA)
    float cc     = 1.0
    float ss     = 0.0
    int   mFull  = math.min(KA, age)
    for m = 1 to KA
        wm := wm * ratio
        ratio := ratio * dratio
        float nc = cc * cw - ss * sw
        ss := ss * cw + cc * sw
        cc := nc
        float sp = array.get(xs, age + m)
        if m <= mFull
            float sm = array.get(xs, age - m)
            wr += wm * cc * (sp + sm)
            wi += wm * ss * (sp - sm)
            wsumA += wm * 2.0
        else
            wr += wm * cc * sp
            wi += wm * ss * sp
            wsumA += wm
    [wr / wsumA, wi / wsumA]
 
// Triangular polish at the edge, as in 9.6.
edgePolish(array<float> s4, int age) =>
    float acc = 0.0
    float ww  = 0.0
    for q = math.max(0, age - cycHalf) to age + cycHalf
        float wq = 1.0 - math.abs(age - q) / (cycHalf + 1.0)
        acc += wq * array.get(s4, q)
        ww  += wq
    acc / ww
 
// Seam phase and amplitude as 9.9 builds them, with the newest final ridge in
// place of the edge ridge, plus the one-sided complex phase at age 0.
edgeState(array<float> xs, array<float> lv, float rK) =>
    int nS2 = cycHalf + 2 + 2 * recHalf
    array<float> s2 = array.new_float(nS2, 0.0)
    for age = 0 to nS2 - 1
        float lva = array.get(lv, age)
        float ew  = math.max(0.0, math.min(1.0, 1.0 - age / math.max(1.0, 2.0 * math.min(math.exp(rK), math.exp(lva)))))
        float wC  = EDGE_CAP * smooth01(ew)
        array.set(s2, age, (1.0 - wC) * rK + wC * lva)
    array<float> s4 = array.new_float(cycHalf + 2, 0.0)
    float logP0 = na
    float re0   = na
    float im0   = na
    for age = 0 to cycHalf + 1
        float acc = 0.0
        int   lo  = math.max(0, age - recHalf)
        for q = lo to age + recHalf
            acc += array.get(s2, q)
        float s3 = acc / (age + recHalf - lo + 1)
        [re, im] = morletAt(xs, age, s3)
        array.set(s4, age, re)
        if age == 0
            logP0 := s3
            re0   := re
            im0   := im
    float c0  = edgePolish(s4, 0)
    float c1  = edgePolish(s4, 1)
    float om1 = TWO_PI / math.exp(logP0)
    float sOm = math.sin(om1)
    float qd  = math.abs(sOm) > 0.02 ? (c0 + (c0 - c1) - c0 * math.cos(om1)) / sOm : (c0 - c1) / om1
    [-atan2(qd, c0), math.sqrt(c0 * c0 + qd * qd), logP0, atan2(im0, re0), math.sqrt(re0 * re0 + im0 * im0)]
 
// Turn model inputs. Phases are relative to the seam phase.
turnFeatures(array<float> dst, float psiS, float ampS, float psiC, float ampC, float psiB, float rms, float conc) =>
    array.set(dst, 0, math.cos(psiS))
    array.set(dst, 1, math.sin(psiS))
    array.set(dst, 2, math.cos(psiC - psiS))
    array.set(dst, 3, math.sin(psiC - psiS))
    array.set(dst, 4, math.cos(psiB - psiS))
    array.set(dst, 5, math.sin(psiB - psiS))
    array.set(dst, 6, fz(math.log(ampS / rms) / AMP_SCALE))
    array.set(dst, 7, fz(math.log(ampC / rms) / AMP_SCALE))
    array.set(dst, 8, conc)
 
// =============================================================================
//  8. ENGINE (confirmed bars)
// =============================================================================
// ---- 8.0 State ----------------------------------------------------------
// Row cr of column id (centre b = id * colStep) is final at b + K + gHalf, the
// whole column at b + FIN_LAG. Finished rows wait in provRaw until then.
var array<float> provRaw   = array.new_float(PROV * cRows, na)
var array<int>   provBorn  = array.new_int(PROV, -1)   // column id whose row 0 is stored in each slot
var array<float> rawTmp    = array.new_float(cRows, na)
var array<float> colTmp    = array.new_float(nRows, na)
var int newestFinalId = -1
 
// Final columns, one ring row per column.
var op.FloatRowRing colRing   = op.floatRowRing(nCols, nRows, true, na)  // display grid magnitudes
var op.FloatRowRing ridgeRing = op.floatRowRing(CAPR, 1, true, na)      // ridge log period
var op.FloatRowRing peakRing  = op.floatRowRing(nCols, 1, true, na)     // blurred peak
 
// Period path and cycle by bar (% CAPB): 8.4 writes final bars, 9.6 the edge.
var array<float> cacheRec = array.new_float(CAPB, na)   // log period
var array<float> cacheCyc = array.new_float(CAPB, na)   // cycle value
 
// Final wave pipeline rings (% PIPE).
var array<float> pipeS2   = array.new_float(PIPE, na)   // fused log period
var array<float> pipeRe   = array.new_float(PIPE, na)   // raw final wave, real part
var array<float> pipeIm   = array.new_float(PIPE, na)   // and imaginary part
var int   pipeFrom = na      // first bar with a fused period
var int   finFirst = na      // first bar with a polished final value
var float finSqEma = na      // EMA of the final wave's square
float     finRe    = na      // final wave of bar t - lagW
float     finIm    = na
 
// Models. Training rows are kept in rings of the newest trainRows samples.
var nl.Sequential model  = nl.sequential("cycle_period")
var nl.Sequential tModel = nl.sequential("cycle_turns")
if barstate.isfirst and modelOn
    model := nl.sequential("cycle_period")
      .input(array.from(N_FEAT), "cycle_state")
      .dense(HIDDEN, nl.ActivationKind.tanh, "hidden")
      .dense(N_TGT, nl.ActivationKind.linear, "period_path")
      .build(nl.rng(MODEL_SEED))
      .compile(modelConfig())
    tModel := nl.sequential("cycle_turns")
      .input(array.from(N_TFEAT), "edge_state")
      .dense(HIDDEN, nl.ActivationKind.tanh, "hidden")
      .dense(N_TTGT, nl.ActivationKind.linear, "phase_amplitude")
      .build(nl.rng(MODEL_SEED + 1))
      .compile(modelConfig())
 
// Period model samples and scores.
var op.FloatRowRing featRing = op.floatRowRing(trainRows, N_FEAT, true, 0.0)
var op.FloatRowRing tgtRing  = op.floatRowRing(trainRows, N_TGT, true, 0.0)
var array<float> featTmp  = array.new_float(N_FEAT, 0.0)
var array<float> tgtTmp   = array.new_float(N_TGT, 0.0)
var array<float> batchX   = array.new_float()
var array<float> batchY   = array.new_float()
var array<int>   hKnots   = array.from(0, hK1, hK2, modelH)
var array<float> mseM     = array.new_float(N_TGT, 0.0)   // out-of-sample error, model
var array<float> mseB     = array.new_float(N_TGT, 0.0)   // the same for a constant period
var array<float> recP     = array.from(0.0, 0.0, 0.0, float(na), 0.0)   // improvement record
var int  nSamples   = 0
var int  nOOS       = 0
var bool modelReady = false
 
// Turn model samples and scores. Pending samples hold their features and the
// prediction made at their own bar.
var op.FloatRowRing tFeatRing = op.floatRowRing(trainRows, N_TFEAT, true, 0.0)
var op.FloatRowRing tTgtRing  = op.floatRowRing(trainRows, N_TTGT, true, 0.0)
var array<float> tFeatTmp = array.new_float(N_TFEAT, 0.0)
var array<float> tTgtTmp  = array.new_float(N_TTGT, 0.0)
var array<float> tBatchX  = array.new_float()
var array<float> tBatchY  = array.new_float()
var array<int>   pendBar  = array.new_int(TPEND, -1)
var array<float> pendPsi  = array.new_float(TPEND, na)        // seam phase at the sample bar
var array<float> pendAmp  = array.new_float(TPEND, na)        // seam amplitude
var array<float> pendFeat = array.new_float(TPEND * N_TFEAT, 0.0)
var array<float> pendPred = array.new_float(TPEND * N_TTGT, na)
var array<float> xsTmp    = array.new_float()
var array<float> lvTmp    = array.new_float()
var op.FloatRowRing errPhM   = op.floatRowRing(ERR_KEEP, 1)   // |timing error|, learned phase
var op.FloatRowRing errPhAll = op.floatRowRing(ERR_KEEP, 1)   // the same for the seam, every sample
var array<float> errTmp   = array.new_float()
var float msePhM = 0.0
var float msePhB = 0.0
var float mseAmM = 0.0
var float mseAmB = 0.0
var array<float> recT = array.from(0.0, 0.0, 0.0, float(na), 0.0)   // timing improvement record
var array<float> recA = array.from(0.0, 0.0, 0.0, float(na), 0.0)   // height improvement record
var int   nTSamples = 0
var int   nTOOS     = 0
var bool  tReady    = false
 
if barstate.isconfirmed and engineOn and not na(firstSample)
    int t = bar_index
 
    // ---- 8.1 Rows whose window just completed ---------------------------
    // Centre at xF[K], older taps xF[K + m], newer xF[K - m], all final.
    for cr = 0 to cRows - 1
        int K = array.get(cRowK, cr)
        int b = t - K - gHalf
        if b - K >= firstSample and b % colStep == 0
            int   kb = cr * KSTRIDE
            float wr = xF[K]
            float wi = 0.0
            for m = 1 to K
                float sp = xF[K + m]
                float sm = xF[K - m]
                wr += array.get(kerC, kb + m) * (sp + sm)
                wi += array.get(kerS, kb + m) * (sp - sm)
            int id   = int(math.round(b / float(colStep)))
            int slot = id % PROV
            array.set(provRaw, slot * cRows + cr, math.sqrt(wr * wr + wi * wi) / array.get(cPeriods, cr))
            if cr == 0
                array.set(provBorn, slot, id)
 
    // ---- 8.2 Column that just became final ------------------------------
    int bTop = t - FIN_LAG
    if bTop >= 0 and bTop % colStep == 0
        int  id    = int(math.round(bTop / float(colStep)))
        int  slot  = id % PROV
        bool valid = array.get(provBorn, slot) == id and bTop - maxK >= firstSample
        int  sBase = slot * cRows
        for r = 0 to nRows - 1
            float fr = array.get(mapFr, r)
            array.set(colTmp, r, valid ? (1.0 - fr) * array.get(provRaw, sBase + array.get(mapLo, r)) + fr * array.get(provRaw, sBase + array.get(mapHi, r)) : na)
        pushRow(colRing, colTmp)
        ridgeRing.pushValue(valid ? columnRidge(colTmp, 0, bandRow0, bandRow1, nRows, logPer, dLogP) : na)
        peakRing.pushValue(columnPeak(colTmp, 0, nRows))
        newestFinalId := id
 
        // ---- 8.3 Period sample resolved ------------------------------------
        // Anchor a = O_ANCHOR bars back. Targets: smoothed final ridge at
        // a + {0, H/3, 2H/3, H}, relative to the live period at a.
        if modelOn and valid
            int   idT  = id - ridgeHalf
            int   aBar = idT * colStep - modelH
            int   idR  = int(math.floor((aBar - FIN_LAG) / float(colStep)))
            float rKnown = ridgeRing.newestAt(id - idR, 0)
            float lvA  = logLive[O_ANCHOR]
            bool  ok   = not na(rKnown) and not na(lvA) and aBar - math.max(SLOPE_LAG, recHalf) > 0
            if ok
                for k = 0 to N_TGT - 1
                    float f   = (aBar + array.get(hKnots, k)) / float(colStep)
                    int   id0 = int(math.floor(f))
                    int   id1 = math.min(id0 + 1, idT)
                    float v0  = ringSmoothed(ridgeRing, id, id0, ridgeHalf)
                    float v1  = ringSmoothed(ridgeRing, id, id1, ridgeHalf)
                    float tv  = v0 + (v1 - v0) * (f - id0)
                    ok := ok and not na(tv)
                    array.set(tgtTmp, k, fz((tv - lvA) / TGT_SCALE))
            if ok
                array.set(featTmp, 0, fLiveF[O_ANCHOR])
                array.set(featTmp, 1, fCentF[O_ANCHOR])
                array.set(featTmp, 2, fLiveSl[O_ANCHOR])
                array.set(featTmp, 3, fCentSl[O_ANCHOR])
                array.set(featTmp, 4, fConcF[O_ANCHOR])
                array.set(featTmp, 5, fTiltF[O_ANCHOR])
                array.set(featTmp, 6, fVolF[O_ANCHOR])
                array.set(featTmp, 7, fPowF[O_ANCHOR])
                array.set(featTmp, 8, fz((rKnown - logPMid) / FS_LEVEL))
                // Scored before training. Baseline: the fused period at a, with the
                // newest final ridge standing in for the edge ridge.
                if modelReady and nSamples >= WARMUP
                    float accPx = 0.0
                    for age = 0 to recHalf
                        float lvx = logLive[O_ANCHOR + age]
                        float ewx = math.max(0.0, math.min(1.0, 1.0 - age / math.max(1.0, 2.0 * math.min(math.exp(rKnown), math.exp(lvx)))))
                        float wCx = EDGE_CAP * smooth01(ewx)
                        accPx += (1.0 - wCx) * rKnown + wCx * lvx
                    float yBase = fz((accPx / (recHalf + 1) - lvA) / TGT_SCALE)
                    nl.Tensor pr = model.predict(nl.vector(featTmp))
                    float wN = math.max(1.0 / (nOOS + 1), 1.0 / OOS_WIN)
                    float dP = 0.0
                    for k = 0 to N_TGT - 1
                        float yv = array.get(tgtTmp, k)
                        float em = yv - pr.get1d(k)
                        float eb = yv - yBase
                        array.set(mseM, k, array.get(mseM, k) + (em * em - array.get(mseM, k)) * wN)
                        array.set(mseB, k, array.get(mseB, k) + (eb * eb - array.get(mseB, k)) * wN)
                        dP += eb * eb - em * em
                    pairAdd(recP, dP, wN)
                    nOOS += 1
                pushRow(featRing, featTmp)
                pushRow(tgtRing, tgtTmp)
                nSamples += 1
                if nSamples >= MIN_TRAIN and nSamples % TRAIN_EVERY == 0
                    model      := trainOnRings(model, featRing, tgtRing, batchX, batchY)
                    modelReady := true
 
    // ---- 8.4 Final wave, one stage per bar ------------------------------
    // Fused period at S2_AGE, smoothed period and coefficient recHalf later,
    // polished value at lagW.
    int b2 = t - S2_AGE
    if newestFinalId >= 0 and b2 >= 0
        float f2  = b2 / float(colStep)
        int   id2 = int(math.floor(f2))
        float r0  = ringSmoothed(ridgeRing, newestFinalId, id2, ridgeHalf)
        float r1  = ringSmoothed(ridgeRing, newestFinalId, id2 + 1, ridgeHalf)
        array.set(pipeS2, b2 % PIPE, r0 + (r1 - r0) * (f2 - id2))
        if na(pipeFrom)
            pipeFrom := b2
        int b3 = b2 - recHalf
        if b3 - recHalf >= pipeFrom
            float accS = 0.0
            for q = b3 - recHalf to b2
                accS += array.get(pipeS2, q % PIPE)
            float s3  = accS / (2 * recHalf + 1)
            float re3 = na
            float im3 = na
            int   o3  = t - b3 - gHalf          // xF offset of b3
            if not na(s3)
                float pA     = math.exp(s3)
                float aGA    = 1.0 / (BW * pA * pA)
                int   KA     = int(math.min(maxK, math.round(tapFactor * pA)))
                float cw     = math.cos(TWO_PI / pA)
                float sw     = math.sin(TWO_PI / pA)
                float wr     = xF[o3]
                float wi     = 0.0
                float wm     = 1.0
                float wsumA  = 1.0
                float ratio  = math.exp(-aGA)
                float dratio = math.exp(-2.0 * aGA)
                float cc     = 1.0
                float ss     = 0.0
                for m = 1 to KA
                    wm := wm * ratio
                    ratio := ratio * dratio
                    float nc = cc * cw - ss * sw
                    ss := ss * cw + cc * sw
                    cc := nc
                    float sp = xF[o3 + m]
                    float sm = xF[o3 - m]
                    wr += wm * cc * (sp + sm)
                    wi += wm * ss * (sp - sm)
                    wsumA += wm * 2.0
                re3 := wr / wsumA
                im3 := wi / wsumA
                array.set(cacheRec, b3 % CAPB, s3)
            array.set(pipeRe, b3 % PIPE, re3)
            array.set(pipeIm, b3 % PIPE, im3)
            int bP = b3 - cycHalf
            if bP - cycHalf >= pipeFrom + recHalf
                float accR = 0.0
                float accI = 0.0
                float accW = 0.0
                for q = bP - cycHalf to b3
                    float wq = 1.0 - math.abs(bP - q) / (cycHalf + 1.0)
                    accR += wq * array.get(pipeRe, q % PIPE)
                    accI += wq * array.get(pipeIm, q % PIPE)
                    accW += wq
                finRe := accR / accW
                finIm := accI / accW
                if not na(finRe)
                    array.set(cacheCyc, bP % CAPB, finRe)
                    finSqEma := na(finSqEma) ? finRe * finRe : finSqEma + (finRe * finRe - finSqEma) * 2.0 / (RMS_LEN + 1)
                    if na(finFirst)
                        finFirst := bP
 
    // ---- 8.5 Turn samples -----------------------------------------------
    // Resolve the sample from t - lagW, then open a new one. The seam error is
    // recorded on every sample, the model's only where it predicted.
    if turnOn
        int aRes = t - lagW
        if aRes >= 0 and aRes % TSTEP == 0
            int slot = int(aRes / TSTEP) % TPEND
            if array.get(pendBar, slot) == aRes and not na(finRe)
                float psiS = array.get(pendPsi, slot)
                float ampS = array.get(pendAmp, slot)
                float ampF = math.sqrt(finRe * finRe + finIm * finIm)
                if ampF > 0
                    float d = wrapPi(atan2(finIm, finRe) - psiS)
                    errPhAll.pushValue(math.abs(d))
                    if modelOn
                        array.set(tTgtTmp, 0, math.cos(d) - 1.0)
                        array.set(tTgtTmp, 1, math.sin(d))
                        array.set(tTgtTmp, 2, fz(math.log(ampF / ampS) / AMP_SCALE))
                        int pBase = slot * N_TTGT
                        if not na(array.get(pendPred, pBase))
                            float em = wrapPi(d - atan2(array.get(pendPred, pBase + 1), 1.0 + array.get(pendPred, pBase)))
                            float ab = array.get(tTgtTmp, 2)
                            float am = ab - array.get(pendPred, pBase + 2)
                            float wT = math.max(1.0 / (nTOOS + 1), 1.0 / OOS_WIN)
                            msePhM += (em * em - msePhM) * wT
                            msePhB += (d * d - msePhB) * wT
                            mseAmM += (am * am - mseAmM) * wT
                            mseAmB += (ab * ab - mseAmB) * wT
                            pairAdd(recT, d * d - em * em, wT)
                            pairAdd(recA, ab * ab - am * am, wT)
                            errPhM.pushValue(math.abs(em))
                            nTOOS += 1
                        int fBase = slot * N_TFEAT
                        pushRow(tFeatRing, array.slice(pendFeat, fBase, fBase + N_TFEAT))
                        pushRow(tTgtRing, tTgtTmp)
                        nTSamples += 1
                        if nTSamples >= MIN_TRAIN and nTSamples % TRAIN_EVERY == 0
                            tModel := trainOnRings(tModel, tFeatRing, tTgtRing, tBatchX, tBatchY)
                            tReady := true
            array.set(pendBar, slot, -1)
 
        float rK = ridgeRing.newestAt(0, 0)
        if t % TSTEP == 0 and not na(rK) and not na(finSqEma) and finSqEma > 0 and t - EDGE_LEN - gHalf >= firstSample
            // Edge samples by age (padded as 9.1) and live period by age.
            array.clear(xsTmp)
            for a = 0 to gHalf - 1
                float accE = array.get(wG, 0) * lc[a]
                for j = 1 to gHalf
                    accE += array.get(wG, j) * (lc[math.max(0, a - j)] + lc[a + j])
                array.push(xsTmp, lc[a] - accE / wsum)
            for a = gHalf to EDGE_LEN - 1
                array.push(xsTmp, xF[a - gHalf])
            array.clear(lvTmp)
            for age = 0 to cycHalf + 1 + 2 * recHalf
                array.push(lvTmp, nz(logLive[age], logLive))
            [psiS, ampS, logPS, psiC, ampC] = edgeState(xsTmp, lvTmp, rK)
            if ampS > 0 and ampC > 0
                int slot = int(t / TSTEP) % TPEND
                array.set(pendBar, slot, t)
                array.set(pendPsi, slot, psiS)
                array.set(pendAmp, slot, ampS)
                array.set(pendPred, slot * N_TTGT, na)
                if modelOn
                    turnFeatures(tFeatTmp, psiS, ampS, psiC, ampC, psiBp, math.sqrt(finSqEma), fConcF)
                    int fBase = slot * N_TFEAT
                    for k = 0 to N_TFEAT - 1
                        array.set(pendFeat, fBase + k, array.get(tFeatTmp, k))
                    if tReady and nTSamples >= WARMUP
                        nl.Tensor tp = tModel.predict(nl.vector(tFeatTmp))
                        for k = 0 to N_TTGT - 1
                            array.set(pendPred, slot * N_TTGT + k, tp.get1d(k))
 
// =============================================================================
//  9. UPDATE AND RENDER (confirmed bars only)
// =============================================================================
// Polylines cannot be edited and are rebuilt each update. Labels, boxes and
// lines come from pools and are moved in place.
var array<polyline> g_polys  = array.new<polyline>()
var array<label>    g_labels = array.new<label>()   // price chart
var array<label>    g_paneLb = array.new<label>()   // this pane
var array<box>      g_boxes  = array.new<box>()
var array<line>     g_lines  = array.new<line>()
var array<box>      g_legend = array.new<box>()     // created once, then moved
var table           g_table  = na
var op.Watch        g_field  = op.watch()           // column ids behind the field
 
clearPolys() =>
    if array.size(g_polys) > 0
        for pl in g_polys
            polyline.delete(pl)
        array.clear(g_polys)
 
// Update workspace, reused across updates.
var array<float> xw        = array.new_float()                  // detrended samples by age
var array<float> trendEdge = array.new_float(gHalf, 0.0)        // padded trend of the newest gHalf bars
var array<float> provDisp  = array.new_float(PROV * nRows, na)  // unfinished columns, display grid
var array<float> provRidge = array.new_float(PROV, na)
var array<float> provCoi   = array.new_float(PROV, 0.0)
var array<float> colPeak   = array.new_float(nCols, na)         // column peaks, display grid
var array<float> colGain   = array.new_float(nCols, 0.0)        // 1 / smoothed peak
var array<int>   physOf    = array.new_int()
var array<float> finRect   = array.new_float(nRows, 0.0)
var int          finCnt    = 0
var array<float> gRect     = array.new_float(nRows, 0.0)
var array<int>   gCnt      = array.new_int(nRows, 0)
var array<float> rRaw      = array.new_float()
var array<float> rSm       = array.new_float()
var array<float> st2       = array.new_float()                  // fused log period by age
var array<float> pre       = array.new_float()                  // its prefix sums
var array<float> st3       = array.new_float()                  // smoothed log period by age
var array<float> st4       = array.new_float()                  // raw cycle by age
var bool         cacheReady  = false
var float        scaleFsm    = na
var array<float> lP        = array.new_float()                  // forecast log period by step ahead
var array<float> sgArr     = array.new_float()                  // its log sigma
var array<float> phi       = array.new_float()                  // cumulative phase, 5 paths
var array<float> phiWin    = array.new_float()                  // turn window paths
var array<float> zWin      = array.from(Z_FAN, Z_HALF, -Z_HALF, -Z_FAN)        // 80% fast, 50% fast, 50% slow, 80% slow
var array<float> logPhat   = array.new_float(N_TGT, 0.0)
var array<float> sigK      = array.new_float(N_TGT, 0.0)
var array<float> zSet      = array.from(-Z_FAN, -Z_HALF, 0.0, Z_HALF, Z_FAN)   // fastest .. slowest
var array<int>   pivots    = array.new_int()                    // past turns: +age high, -age low
 
doUpdate = barstate.isconfirmed and (barstate.islastconfirmedhistory or barstate.isrealtime)
 
// Alert state (9.10).
bool alLowWin  = false
bool alHighWin = false
var bool winWasOpen = false
var bool winWasTop  = false
 
if doUpdate
    clearPolys()
    if not na(g_table)
        table.delete(g_table)
        g_table := na
    // Pool cursors: price labels, pane labels, boxes, lines.
    int nLb = 0
    int nPl = 0
    int nBx = 0
    int nLn = 0
    int t        = bar_index
    int needBars = spanBars + FIN_LAG + 2 * gHalf + colStep
 
    if t + 1 < needBars or newestFinalId < 0 or colRing.rowCount() == 0
        g_heatmap.clear()
        g_table := table.new(position.middle_center, 1, 1, bgcolor = color.new(#1c2128, 0), border_color = #3a3f46, border_width = 1)
        table.cell(g_table, 0, 0, "Neural Spectrogram\nNeeds ~" + str.tostring(needBars) + " bars of history\n(only " + str.tostring(t + 1) + " available).\nLoad more history, or lower Max Period / History Window.", text_color = color.white, text_size = size.normal)
    else
        int idRight = int(math.floor(t / float(colStep)))          // newest column centre <= t
        int nProv   = math.max(0, math.min(nCols, idRight - newestFinalId))
        int jP      = nCols - nProv                                 // first unfinished display column
        // The full window is only needed until 8.4 covers the display history.
        cacheReady  := cacheReady or (not na(finFirst) and finFirst <= t - displayBars + 1)
        int zLen    = cacheReady ? zoneLen : displayBars
        int lenS4   = zLen + cycHalf
        int lenS2   = lenS4 + recHalf
        int W       = math.max(FIN_LAG + maxK + 1, lenS4 + maxK + 1)
 
        // ---- 9.1 Samples by age: padded edge, then final history ---------
        array.clear(xw)
        for a = 0 to gHalf - 1
            float accE = array.get(wG, 0) * lc[a]
            for j = 1 to gHalf
                accE += array.get(wG, j) * (lc[math.max(0, a - j)] + lc[a + j])
            float tr = accE / wsum
            array.set(trendEdge, a, tr)
            array.push(xw, lc[a] - tr)
        for a = gHalf to W - 1
            array.push(xw, xF[a - gHalf])
 
        // ---- 9.2 Unfinished columns --------------------------------------
        // Finished rows are read back, the rest use the samples available.
        if nProv > 0
            for k = 0 to nProv - 1
                int  id   = newestFinalId + 1 + k
                int  c    = t - id * colStep
                int  slot = id % PROV
                bool born = array.get(provBorn, slot) == id
                array.set(provCoi, k, c / COI_SCALE)
                for cr = 0 to cRows - 1
                    int   K   = array.get(cRowK, cr)
                    float mag = na
                    if born and c >= K + gHalf and id * colStep - K >= firstSample
                        mag := array.get(provRaw, slot * cRows + cr)
                    else
                        int   kb    = cr * KSTRIDE
                        float wr    = array.get(xw, c)
                        float wi    = 0.0
                        int   mFull = math.min(K, c)
                        if mFull >= 1
                            for m = 1 to mFull
                                float sp = array.get(xw, c + m)
                                float sm = array.get(xw, c - m)
                                wr += array.get(kerC, kb + m) * (sp + sm)
                                wi += array.get(kerS, kb + m) * (sp - sm)
                        if K > mFull
                            for m = mFull + 1 to K
                                float sp = array.get(xw, c + m)
                                wr += array.get(kerC, kb + m) * sp
                                wi += array.get(kerS, kb + m) * sp
                        mag := math.sqrt(wr * wr + wi * wi) / array.get(cPeriods, cr)
                    array.set(rawTmp, cr, mag)
                int base = k * nRows
                for r = 0 to nRows - 1
                    float fr = array.get(mapFr, r)
                    array.set(provDisp, base + r, (1.0 - fr) * array.get(rawTmp, array.get(mapLo, r)) + fr * array.get(rawTmp, array.get(mapHi, r)))
                array.set(provRidge, k, columnRidge(provDisp, base, bandRow0, bandRow1, nRows, logPer, dLogP))
 
        // ---- 9.3 Field and global spectrum -------------------------------
        // Full rewrite when a column is born or finalised, otherwise only the
        // unfinished columns. Final columns lie outside the COI.
        bool fullPass = g_field.begin().watchInt(idRight).watchInt(newestFinalId).finish()
        array<float> ringData = colRing.rawView()
        if fullPass
            array.clear(physOf)
            finCnt := 0
            int ringCount = colRing.rowCount()
            if jP > 0
                for j = 0 to jP - 1
                    int off     = newestFinalId - (idRight - (nCols - 1 - j))
                    int logical = ringCount - 1 - off
                    int ph = logical >= 0 ? colRing.physicalRow(logical) : -1
                    if ph >= 0 and na(array.get(ringData, ph * nRows))
                        ph := -1
                    array.push(physOf, ph)
                    finCnt += ph >= 0 ? 1 : 0
                    array.set(colPeak, j, ph >= 0 ? peakRing.newestAt(off, 0) : na)
                // Final columns are scaled from final peaks only, so they hold until the next pass.
                for j = 0 to jP - 1
                    array.set(colGain, j, peakGain(colPeak, j, 0, jP - 1, scaleHalf))
        if nProv > 0
            for k = 0 to nProv - 1
                array.set(colPeak, jP + k, columnPeak(provDisp, k * nRows, nRows))
            for k = 0 to nProv - 1
                array.set(colGain, jP + k, peakGain(colPeak, jP + k, 0, nCols - 1, scaleHalf))
        for r = 0 to nRows - 1
            array<float> cells = heatField.band(array.get(rowBand, r))
            int rowBase = array.get(rowLocal, r)
            int dm = r > 0 ? -1 : 0
            int dp = r < nRows - 1 ? 1 : 0
            if fullPass
                float sq = 0.0
                if jP > 0
                    for j = 0 to jP - 1
                        int ph = array.get(physOf, j)
                        if ph >= 0
                            int   i  = ph * nRows + r
                            float m0 = array.get(ringData, i)
                            array.set(cells, rowBase + j, (0.25 * array.get(ringData, i + dm) + 0.5 * m0 + 0.25 * array.get(ringData, i + dp)) * array.get(colGain, j))
                            sq += m0 * m0
                        else
                            array.set(cells, rowBase + j, na)
                array.set(finRect, r, sq)
            float pRow   = array.get(periods, r)
            float provSq = 0.0
            int   provN  = 0
            if nProv > 0
                for k = 0 to nProv - 1
                    int   i  = k * nRows + r
                    float m0 = array.get(provDisp, i)
                    array.set(cells, rowBase + jP + k, (0.25 * array.get(provDisp, i + dm) + 0.5 * m0 + 0.25 * array.get(provDisp, i + dp)) * array.get(colGain, jP + k))
                    if pRow <= array.get(provCoi, k) and not na(m0)
                        provSq += m0 * m0
                        provN  += 1
            array.set(gRect, r, array.get(finRect, r) + provSq)
            array.set(gCnt, r, finCnt + provN)
 
        int heatLeft = (idRight - nCols + 1) * colStep - halfStep
        if showHeat
            g_heatmap.draw(heatField, heatLeft, heatLeft + spanBars, edge0, edgeN)
        else
            g_heatmap.clear()
 
        // ---- 9.4 Variance, AR(1), dominant cycle, significance -----------
        // One pass of raw sums; the centred forms are recovered algebraically.
        int   Nv     = displayBars + maxK
        int   wLen   = array.size(xw)
        float s1     = 0.0
        float s2     = 0.0
        float sxy    = 0.0
        float xFirst = array.get(xw, 0)
        float xPrev  = xFirst
        for a = 0 to Nv - 1
            float xv = nz(a < wLen ? array.get(xw, a) : xF[a - gHalf])
            s1  += xv
            s2  += xv * xv
            sxy += a > 0 ? xPrev * xv : 0.0
            xPrev := xv
        float mu    = s1 / Nv
        float xVar  = math.max(1e-18, s2 / Nv - mu * mu)
        float xStd  = math.sqrt(xVar)
        float sA    = s1 - xPrev
        float sB    = s1 - xFirst
        float mu2n  = (Nv - 1) * mu * mu
        float c01   = sxy - mu * (sA + sB) + mu2n
        float c00   = s2 - xPrev * xPrev - 2.0 * mu * sA + mu2n
        float c11   = s2 - xFirst * xFirst - 2.0 * mu * sB + mu2n
        float arDen = math.sqrt(math.max(0.0, c00 * c11))
        float alpha = arDen > 0 ? math.max(0.0, math.min(0.99, c01 / arDen)) : 0.0
 
        int   iDom = -1
        float best = -1.0
        for r = bandRow0 to bandRow1
            int cnt = array.get(gCnt, r)
            if cnt > 0 and array.get(gRect, r) / cnt > best
                best := array.get(gRect, r) / cnt
                iDom := r
        float domGlobal = math.sqrt(bandLo * bandHi)
        if iDom >= 0
            domGlobal := array.get(periods, iDom)
            if iDom > 0 and iDom < nRows - 1 and array.get(gCnt, iDom - 1) > 0 and array.get(gCnt, iDom + 1) > 0
                float y0 = array.get(gRect, iDom - 1) / array.get(gCnt, iDom - 1)
                float y2 = array.get(gRect, iDom + 1) / array.get(gCnt, iDom + 1)
                float dn = y0 - 2.0 * best + y2
                if dn < 0
                    domGlobal := math.exp(array.get(logPer, iDom) + math.max(-0.5, math.min(0.5, 0.5 * (y0 - y2) / dn)) * dLogP)
        float logDomG = math.log(domGlobal)
 
        // Torrence & Compo: mean |W|^2 / sum(w^2) against variance x red noise
        // spectrum x chi-square(dof) / dof.
        bool domSig = false
        if iDom >= 0
            float p      = array.get(periods, iDom)
            float pk     = (1.0 - alpha * alpha) / (1.0 + alpha * alpha - 2.0 * alpha * math.cos(TWO_PI / p))
            float naR    = math.max(1, array.get(gCnt, iDom))
            float dof    = math.max(2.0, 2.0 * math.sqrt(1.0 + math.pow(naR * colStep / (2.32 * p), 2.0)))
            float thresh = xVar * pk * chi2inv(dof, zLevel) / dof
            domSig := best * p * array.get(rowNorm, iDom) > thresh
        // Dominant peak at the edge of the search band.
        bool edgeHi = iDom >= 0 and iDom >= bandRow1 - 1
        bool edgeLo = iDom >= 0 and iDom <= bandRow0 + 1
 
        // ---- 9.5 Ridge path per column -----------------------------------
        int idUse = int(math.floor((t - lenS2 + 1) / float(colStep)))
        int idOld = idUse - 1 - ridgeHalf
        int nId   = idRight - idOld + 1
        array.clear(rRaw)
        for i = 0 to nId - 1
            int   id = idOld + i
            float v  = na
            if id <= newestFinalId
                v := ridgeRing.newestAt(newestFinalId - id, 0)
            else
                int k = id - newestFinalId - 1
                v := k < nProv ? array.get(provRidge, k) : na
            array.push(rRaw, v)
        array.clear(rSm)
        for i = 0 to nId - 1
            float accR = 0.0
            int   cntR = 0
            for q = math.max(0, i - ridgeHalf) to math.min(nId - 1, i + ridgeHalf)
                float v = array.get(rRaw, q)
                if not na(v)
                    accR += v
                    cntR += 1
            array.push(rSm, cntR > 0 ? accR / cntR : logDomG)
 
        // ---- 9.6 Per-bar period path and cycle (memoized) ----------------
        // Ridge interpolation, live fusion near the edge, box smoothing, Morlet real
        // part at each bar's period, triangular polish. Only zLen bars are recomputed.
        array.clear(st2)
        for a = 0 to lenS2 - 1
            float f   = (t - a) / float(colStep)
            int   id0 = int(math.floor(f))
            int   i0  = math.max(0, math.min(nId - 1, id0 - idOld))
            int   i1  = math.min(nId - 1, i0 + 1)
            float l1  = array.get(rSm, i0) + (array.get(rSm, i1) - array.get(rSm, i0)) * (f - id0)
            float lv  = nz(logLive[a], logLive)
            float ew  = math.max(0.0, math.min(1.0, 1.0 - a / math.max(1.0, 2.0 * math.min(math.exp(l1), math.exp(lv)))))
            float wC  = EDGE_CAP * smooth01(ew)
            array.push(st2, (1.0 - wC) * l1 + wC * lv)
 
        array.clear(pre)
        array.push(pre, 0.0)
        float run = 0.0
        for a = 0 to lenS2 - 1
            run += array.get(st2, a)
            array.push(pre, run)
        array.clear(st3)
        for a = 0 to lenS4 - 1
            int lo = math.max(0, a - recHalf)
            int hi = math.min(lenS2 - 1, a + recHalf)
            array.push(st3, (array.get(pre, hi + 1) - array.get(pre, lo)) / (hi - lo + 1))
 
        array.clear(st4)
        for a = 0 to lenS4 - 1
            float pA     = math.exp(array.get(st3, a))
            float aGA    = 1.0 / (BW * pA * pA)
            int   KA     = int(math.min(maxK, math.round(tapFactor * pA)))
            float cw     = math.cos(TWO_PI / pA)
            float sw     = math.sin(TWO_PI / pA)
            float wr     = array.get(xw, a)
            float wm     = 1.0
            float wsumA  = 1.0
            float ratio  = math.exp(-aGA)
            float dratio = math.exp(-2.0 * aGA)
            float cc     = 1.0
            float ss     = 0.0
            int   mFull  = math.min(KA, a)
            if mFull >= 1
                for m = 1 to mFull
                    wm := wm * ratio
                    ratio := ratio * dratio
                    float nc = cc * cw - ss * sw
                    ss := ss * cw + cc * sw
                    cc := nc
                    wr += wm * cc * (array.get(xw, a + m) + array.get(xw, a - m))
                    wsumA += wm * 2.0
            if KA > mFull
                for m = mFull + 1 to KA
                    wm := wm * ratio
                    ratio := ratio * dratio
                    float nc = cc * cw - ss * sw
                    ss := ss * cw + cc * sw
                    cc := nc
                    wr += wm * cc * array.get(xw, a + m)
                    wsumA += wm
            array.push(st4, wr / wsumA)
 
        float triDen = cycHalf + 1.0
        for a = 0 to zLen - 1
            float v = array.get(st4, a)
            if cycHalf >= 1
                float accw = 0.0
                float sww  = 0.0
                for q = math.max(0, a - cycHalf) to math.min(lenS4 - 1, a + cycHalf)
                    float wgt = 1.0 - math.abs(a - q) / triDen
                    accw += wgt * array.get(st4, q)
                    sww  += wgt
                v := accw / sww
            int slotB = (t - a) % CAPB
            array.set(cacheRec, slotB, array.get(st3, a))
            array.set(cacheCyc, slotB, v)
        cacheReady := true
 
        float logDom = array.get(st3, 0)
        float dom    = math.exp(logDom)
 
        // ---- 9.7 Wave amplitude on price ---------------------------------
        int   aEdge = int(math.round(0.5 * dom))
        float csq   = 0.0
        int   cn    = 0
        for a = math.min(aEdge, displayBars - 1) to displayBars - 1
            float cv = array.get(cacheCyc, (t - a) % CAPB)
            if not na(cv)
                csq += cv * cv
                cn  += 1
        float cycRMS = cn > 0 ? math.sqrt(csq / cn) : 1.0
        cycRMS := cycRMS < 1e-12 ? 1.0 : cycRMS
        float scaleF = waveAmp * xStd / cycRMS
        scaleFsm := na(scaleFsm) ? scaleF : scaleFsm + (scaleF - scaleFsm) * 0.25
        scaleF   := scaleFsm
        float tr0 = array.get(trendEdge, 0)
        float tr1 = gHalf > 1 ? array.get(trendEdge, 1) : trendF[0]
        float c0  = array.get(cacheCyc, t % CAPB)
        float c1  = array.get(cacheCyc, (t - 1) % CAPB)
 
        // ---- 9.8 Forecast state ------------------------------------------
        float errM = 0.0
        float errB = 0.0
        for k = 0 to N_TGT - 1
            errM += array.get(mseM, k)
            errB += array.get(mseB, k)
        // Learned outputs need 95% one-sided confidence over the plain projection.
        float skill = nOOS >= MIN_OOS and errB > 0 ? 1.0 - math.sqrt(errM / errB) : na
        float tP    = pairT(recP, nOOS)
        bool learnedPath = modelOn and modelReady and not na(skill) and tP >= T_SIG
        if learnedPath
            array.set(featTmp, 0, fLiveF)
            array.set(featTmp, 1, fCentF)
            array.set(featTmp, 2, fLiveSl)
            array.set(featTmp, 3, fCentSl)
            array.set(featTmp, 4, fConcF)
            array.set(featTmp, 5, fTiltF)
            array.set(featTmp, 6, fVolF)
            array.set(featTmp, 7, fPowF)
            array.set(featTmp, 8, fz((ridgeRing.newestAt(0, 0) - logPMid) / FS_LEVEL))
            nl.Tensor pr = model.predict(nl.vector(featTmp))
            for k = 0 to N_TGT - 1
                array.set(logPhat, k, logLive + pr.get1d(k) * TGT_SCALE)
                array.set(sigK, k, math.sqrt(array.get(mseM, k)) * TGT_SCALE)
        else
            for k = 0 to N_TGT - 1
                array.set(sigK, k, nOOS >= MIN_OOS ? math.sqrt(array.get(mseB, k)) * TGT_SCALE : turnTol)
 
        // Turn model at the live bar. Its corrections apply to the drawn seam.
        float tSkill = nTOOS >= MIN_OOS and msePhB > 0 ? 1.0 - math.sqrt(msePhM / msePhB) : na
        float aSkill = nTOOS >= MIN_OOS and mseAmB > 0 ? 1.0 - math.sqrt(mseAmM / mseAmB) : na
        float tT     = pairT(recT, nTOOS)
        float tA     = pairT(recA, nTOOS)
        bool  learnedPhase = modelOn and tReady and not na(tSkill) and tT >= T_SIG
        bool  learnedAmp   = modelOn and tReady and not na(aSkill) and tA >= T_SIG
        float dHat = 0.0                // phase step, radians
        float aHat = 0.0                // log amplitude step
        float rKL  = ridgeRing.newestAt(0, 0)
        if (learnedPhase or learnedAmp) and not na(rKL) and finSqEma > 0
            array.clear(lvTmp)
            for age = 0 to cycHalf + 1 + 2 * recHalf
                array.push(lvTmp, nz(logLive[age], logLive))
            [psiS, ampS, logPS, psiC, ampC] = edgeState(xw, lvTmp, rKL)
            if ampS > 0 and ampC > 0
                turnFeatures(tFeatTmp, psiS, ampS, psiC, ampC, psiBp, math.sqrt(finSqEma), fConcF)
                nl.Tensor tp = tModel.predict(nl.vector(tFeatTmp))
                dHat := atan2(tp.get1d(1), 1.0 + tp.get1d(0))
                aHat := tp.get1d(2) * AMP_SCALE
        // 80th percentile of the phase error in use; turnTol until measured.
        op.FloatRowRing errUse = learnedPhase ? errPhM : errPhAll
        bool  errKnown = errUse.rowCount() >= MIN_OOS
        float q80Psi   = errKnown ? array.percentile_linear_interpolation(errUse.chronological(errTmp), 80) : TWO_PI * turnTol
 
        // Plain-language status for the tooltips.
        string modelTxt = "Cycle length forecast: " + (learnedPath ? "AI, " + str.tostring(skill * 100.0, "#") + "% more accurate than holding it" :
          not modelOn ? "held constant (AI off)" : not modelReady or na(skill) ? "held constant (AI learning)" : "held constant (AI not proven yet)")
        string sigTxt = "Dominant cycle: " + str.tostring(domGlobal, "#.0") + " bars, " + (domSig ? "stronger than random noise" : "not clearly stronger than noise, treat with caution")
        sigTxt += edgeHi ? "\nAt the top of the scan range: the real cycle may be longer. Raise Max Period." :
          edgeLo ? "\nAt the bottom of the scan range: the real cycle may be shorter. Lower Min Period." : ""
        int dimT = domSig ? 0 : 30
        string tLearn = not modelOn ? "" : not tReady or nTOOS < MIN_OOS ? " (AI learning)" : " (AI not proven yet)"
        string turnTxt = "Turn timing: " + (learnedPhase ? "AI, " + str.tostring(tSkill * 100.0, "#") + "% more accurate" : "from the current wave" + tLearn) +
          (errKnown ? "\n80% of past turns landed within " + str.tostring(q80Psi / TWO_PI * dom, "#.0") + " bars" : "") +
          "\nTurn heights: " + (learnedAmp ? "AI, " + str.tostring(aSkill * 100.0, "#") + "% more accurate" : "from the current wave" + tLearn)
 
        // ---- 9.9 Projection: period path, phase paths, turns -------------
        // Five period paths (z from -1.28 to 1.28) integrated to phase. The forecast
        // period blends in over the first third. Turns are crossings of theta + n pi.
        int   projBars   = hasProjIn ? int(math.min(500.0, math.ceil(projPeriods * dom))) : 0
        bool  hasProj    = projBars >= 2
        float pEnd       = dom
        float hFirst     = na
        bool  firstIsTop = false
        float firstL80   = na
        float firstR80   = na
        if hasProj
            int hScan = int(math.min(500.0, projBars + math.ceil(0.75 * periodMax)))
            int L     = hScan + 1
            array.clear(lP)
            array.clear(sgArr)
            for h = 0 to hScan
                float lam = smooth01(math.min(1.0, h / float(hK1)))
                array.push(lP, learnedPath ? (1.0 - lam) * logDom + lam * knotSmooth(hKnots, logPhat, h) : logDom)
                array.push(sgArr, knotSmooth(hKnots, sigK, h))
            array.clear(phi)
            for zi = 0 to 4
                float z    = array.get(zSet, zi)
                float accP = 0.0
                array.push(phi, 0.0)
                for h = 1 to hScan
                    accP += TWO_PI / math.exp(array.get(lP, h) + z * array.get(sgArr, h))
                    array.push(phi, accP)
            pEnd := math.exp(array.get(lP, projBars))
 
            float slope = c0 - c1
            float om1   = array.get(phi, 2 * L + 1)
            float sOm   = math.sin(om1)
            // Seam: y(0) = c0, y(1) = c0 + slope.
            float qd    = math.abs(sOm) > 0.02 ? (c0 + slope - c0 * math.cos(om1)) / sOm : slope / om1
            float amp   = math.sqrt(c0 * c0 + qd * qd)
            float theta = c0 > 0 ? math.atan(qd / c0) : c0 < 0 ? math.atan(qd / c0) + math.pi : (qd >= 0 ? 0.5 * math.pi : -0.5 * math.pi)
            float trSl  = tr0 - tr1
            color fcol  = pcol(math.exp(array.get(lP, int(projBars / 2))))
 
            // Learned phase step and amplitude blend in over hB bars, with the paths kept
            // monotonic. Window paths add the phase error in quadrature.
            float dPsi   = learnedPhase ? dHat : 0.0
            float ampEnd = learnedAmp ? amp * math.exp(aHat) : amp
            float sPsi   = q80Psi / Z_FAN
            // hB keeps the added phase rate under half the cycle's rate.
            float hB     = math.max(3.0, math.max(0.5 * dom, 3.0 * math.abs(dPsi) * dom / TWO_PI))
            // Window paths: 80% fast, 50% fast, 50% slow, 80% slow.
            array.clear(phiWin)
            for i = 0 to 4 * L - 1
                array.push(phiWin, 0.0)
            for h = 1 to hScan
                float pMed = array.get(phi, 2 * L + h)
                float sPer = (array.get(phi, h) - array.get(phi, 4 * L + h)) / (2.0 * Z_FAN)
                float sTot = math.sqrt(sPer * sPer + sPsi * sPsi)
                float sh   = dPsi * smooth01(math.min(1.0, h / hB))
                for zi = 0 to 4
                    array.set(phi, zi * L + h, math.max(array.get(phi, zi * L + h - 1), array.get(phi, zi * L + h) + sh))
                for w = 0 to 3
                    array.set(phiWin, w * L + h, math.max(array.get(phiWin, w * L + h - 1), pMed + sh + array.get(zWin, w) * sTot))
 
            // Projected path: three fading segments coloured by period, plus the 10% and
            // 90% period paths.
            if showWaveProj
                for sg = 0 to 2
                    int hA = int(math.round(sg * projBars / 3.0))
                    int hZ = int(math.round((sg + 1) * projBars / 3.0))
                    if hZ > hA
                        array<chart.point> seg = array.new<chart.point>()
                        for h = hA to hZ
                            float aH = amp + (ampEnd - amp) * smooth01(math.min(1.0, h / hB))
                            array.push(seg, chart.point.from_index(t + h, math.exp(tr0 + trSl * h + scaleF * aH * math.cos(array.get(phi, 2 * L + h) - theta))))
                        color sc = pcol(math.exp(array.get(lP, int((hA + hZ) / 2))))
                        array.push(g_polys, polyline.new(seg, line_color = color.new(sc, math.min(85, dimT + 22 * sg)), line_width = 2, line_style = line.style_dotted, force_overlay = true))
                for zi = 0 to 4 by 4
                    array<chart.point> ghost = array.new<chart.point>()
                    for h = 0 to projBars
                        float aH = amp + (ampEnd - amp) * smooth01(math.min(1.0, h / hB))
                        array.push(ghost, chart.point.from_index(t + h, math.exp(tr0 + trSl * h + scaleF * aH * math.cos(array.get(phi, zi * L + h) - theta))))
                    array.push(g_polys, polyline.new(ghost, line_color = color.new(fcol, math.min(92, 68 + dimT / 2)), line_width = 1, line_style = line.style_dotted, force_overlay = true))
 
            int n0 = int(math.floor(-theta / math.pi)) + 1
            for nIdx = 0 to MAX_TURNS - 1
                int   n      = n0 + nIdx
                float target = theta + n * math.pi
                float hMed   = crossAt(phi, 2 * L, L, target)
                if na(hMed) or hMed > projBars
                    break
                bool  isTop = n % 2 == 0
                float pTurn = math.exp(array.get(lP, int(math.round(hMed))))
                float wMin  = turnTol * pTurn
                float l80   = math.min(nz(crossAt(phiWin, 0, L, target), hMed), hMed - wMin)
                float l50   = math.min(nz(crossAt(phiWin, L, L, target), hMed), hMed - wMin * Z_HALF / Z_FAN)
                float r50   = math.min(500.0, math.max(nz(crossAt(phiWin, 2 * L, L, target), hScan), hMed + wMin * Z_HALF / Z_FAN))
                float r80   = math.min(500.0, math.max(nz(crossAt(phiWin, 3 * L, L, target), hScan), hMed + wMin))
                if nIdx == 0
                    hFirst     := hMed
                    firstIsTop := isTop
                    firstL80   := l80
                    firstR80   := r80
                if showTurns
                    // Timing bars: 80% window faint, 50% window stronger.
                    int   xC    = t + int(math.round(hMed))
                    float aT    = amp + (ampEnd - amp) * smooth01(math.min(1.0, hMed / hB))
                    float logT  = tr0 + trSl * hMed + (isTop ? aT : -aT) * scaleF
                    float halfH = math.max(aT * scaleF, 0.002) * 0.12
                    color tcol  = isTop ? colTop : colBot
                    nBx := poolBox(g_boxes, nBx, t + int(math.round(math.max(1.0, l80))), math.exp(logT + halfH), t + int(math.round(r80)), math.exp(logT - halfH), color.new(tcol, math.min(95, 82 + dimT / 2)))
                    nBx := poolBox(g_boxes, nBx, t + int(math.round(math.max(1.0, l50))), math.exp(logT + halfH), t + int(math.round(r50)), math.exp(logT - halfH), color.new(tcol, math.min(92, 62 + dimT / 2)))
                    nLn := poolLine(g_lines, nLn, xC, math.exp(logT - 0.001), math.exp(logT + 0.001), color.new(tcol, math.min(92, 74 + dimT / 3)))
                    string tip = (isTop ? "Projected HIGH" : "Projected LOW") + " in " + str.tostring(math.round(hMed)) + " bars\n50% chance in bars " + str.tostring(math.round(math.max(1.0, l50))) + " to " + str.tostring(math.round(r50)) + ", 80% in bars " + str.tostring(math.round(math.max(1.0, l80))) + " to " + str.tostring(math.round(r80)) + "\nCycle length then: " + str.tostring(pTurn, "#.0") + " bars (now " + str.tostring(dom, "#.0") + ")\n" + modelTxt + "\n" + turnTxt + "\n" + sigTxt
                    nLb := poolLabel(g_labels, nLb, true, xC, math.exp(isTop ? logT + halfH : logT - halfH), (isTop ? "H " : "L ") + str.tostring(math.round(hMed)), isTop ? label.style_label_down : label.style_label_up, color.new(tcol, 20 + dimT), isTop ? color.white : color.black, size.small, tip)
 
        // ---- 9.10 Alerts ------------------------------------------------
        // Once per window: when the next turn's 80% window opens, or the next turn
        // changes inside it.
        bool winOpen = not na(firstL80) and firstL80 <= 1.0
        if winOpen and (not winWasOpen or firstIsTop != winWasTop)
            alLowWin  := not firstIsTop
            alHighWin := firstIsTop
            alert("Neural Spectrogram: cycle " + (firstIsTop ? "HIGH" : "LOW") + " window open on " + syminfo.ticker + " " + timeframe.period + ": due in " + str.tostring(math.round(hFirst)) + " bars, 80% of such turns land within the next " + str.tostring(math.round(firstR80)) + " bars. Cycle period " + str.tostring(dom, "#.0") + " bars.", alert.freq_once_per_bar)
        winWasOpen := winOpen
        winWasTop  := firstIsTop
 
        // ---- 9.11 Cone of influence: one fill and one boundary -----------
        if showCOI
            array<chart.point> cpts  = array.new<chart.point>()
            array<chart.point> mask  = array.new<chart.point>()
            float lastCoi = edgeN
            for j = 0 to nCols - 1
                int   xc   = (idRight - (nCols - 1 - j)) * colStep
                float coiP = math.min(edgeN, math.max(edge0, (t - xc) / COI_SCALE))
                array.push(cpts, chart.point.from_index(xc, coiP))
                if coiP < edgeN
                    if array.size(mask) == 0
                        array.push(mask, chart.point.from_index(j > 0 ? xc - colStep : xc, edgeN))
                    array.push(mask, chart.point.from_index(xc, coiP))
                    lastCoi := coiP
            if array.size(mask) >= 2
                int xR = heatLeft + spanBars
                array.push(mask, chart.point.from_index(xR, math.max(edge0, math.min(lastCoi, (t - xR) / COI_SCALE))))
                array.push(mask, chart.point.from_index(xR, edgeN))
                array.push(g_polys, polyline.new(mask, closed = true, line_color = color.new(colBg, 100), fill_color = color.new(colBg, 60)))
            array.push(g_polys, polyline.new(cpts, line_color = color.new(color.gray, 40), line_width = 1, line_style = line.style_dotted))
 
        // ---- 9.11b Dominant ridge -----------------------------------------
        // Solid where final, dotted in the repaint zone, over a halo.
        if showDom
            array<chart.point> rFin  = array.new<chart.point>()
            array<chart.point> rLive = array.new<chart.point>()
            int xFin = t - lagW
            for j = 0 to nCols - 1
                int xc = (idRight - (nCols - 1 - j)) * colStep
                if xc >= 0 and xc <= t
                    float lr = array.get(cacheRec, xc % CAPB)
                    if not na(lr)
                        chart.point pt = chart.point.from_index(xc, math.min(edgeN, math.max(edge0, math.exp(lr))))
                        if xc <= xFin
                            array.push(rFin, pt)
                        else
                            if array.size(rLive) == 0 and array.size(rFin) > 0
                                array.push(rLive, array.last(rFin))
                            array.push(rLive, pt)
            array.push(rLive, chart.point.from_index(t, math.min(edgeN, math.max(edge0, dom))))
            if array.size(rFin) >= 2
                array.push(g_polys, polyline.new(rFin, line_color = color.new(colBg, 35), line_width = 5))
                array.push(g_polys, polyline.new(rFin, line_color = color.new(colRidge, 0), line_width = 2))
            if array.size(rLive) >= 2
                array.push(g_polys, polyline.new(rLive, line_color = color.new(colBg, 55), line_width = 5))
                array.push(g_polys, polyline.new(rLive, line_color = color.new(colRidge, 15), line_width = 2, line_style = line.style_dotted))
 
        // ---- 9.12 Colour key and the period markers ----------------------
        int gx0 = heatLeft + spanBars + 8
        int gx1 = gx0 + 3
        if showLegend
            if array.size(g_legend) == 0
                for r = 0 to nRows - 1
                    array.push(g_legend, box.new(gx0, array.get(edges, r + 1), gx1, array.get(edges, r), border_width = 0, bgcolor = pcol(array.get(periods, r)), xloc = xloc.bar_index))
            else
                for bx in g_legend
                    box.set_left(bx, gx0)
                    box.set_right(bx, gx1)
        else if array.size(g_legend) > 0
            for bx in g_legend
                box.delete(bx)
            array.clear(g_legend)
        if showDom
            string dTxt = " " + str.tostring(dom, "#.0") + (edgeHi ? " ▲" : edgeLo ? " ▼" : "") + " "
            string dTip = "Cycle length now: " + str.tostring(dom, "#.0") + " bars" + (hasProj ? "\nIn " + str.tostring(projBars) + " bars: " + str.tostring(pEnd, "#.0") + " bars (" + fmtPct(pEnd / dom - 1.0) + ")" : "") + "\n" + modelTxt + "\n" + turnTxt + "\n" + sigTxt
            nPl := poolLabel(g_paneLb, nPl, false, gx1, math.min(edgeN, math.max(edge0, dom)), dTxt, label.style_label_left, domSig ? color.new(colRidge, 0) : color.new(#3a3f46, 0), domSig ? color.black : color.white, size.small, dTip)
        if showLive
            nPl := poolLabel(g_paneLb, nPl, false, gx0, math.min(edgeN, math.max(edge0, liveDom)), " " + str.tostring(liveDom, "#.0") + " ", label.style_label_right, color.new(#ffd21e, 0), color.black, size.tiny, "Live cycle length: " + str.tostring(liveDom, "#.0") + " bars (real-time estimate)")
 
        // ---- 9.13 Price: cycle wave, past turns, current state -----------
        if showWave
            int curveStep = math.max(1, int(math.ceil(displayBars / 1200.0)))
            for k = 0 to waveSteps - 1
                int pLo = int(math.round(k * (displayBars - 1.0) / waveSteps))
                int pHi = int(math.round((k + 1) * (displayBars - 1.0) / waveSteps))
                if pHi > pLo
                    int   aMid = displayBars - 1 - int(math.round((pLo + pHi) / 2.0))
                    color kcol = pcol(math.exp(array.get(cacheRec, (t - aMid) % CAPB)))
                    array<chart.point> wpts = array.new<chart.point>()
                    int lastW = -1
                    for p = pLo to pHi by curveStep
                        int   aw = displayBars - 1 - p
                        float cv = array.get(cacheCyc, (t - aw) % CAPB)
                        float tw = aw < gHalf ? array.get(trendEdge, aw) : trendF[aw - gHalf]
                        if not na(cv) and not na(tw)
                            array.push(wpts, chart.point.from_index(t - aw, math.exp(tw + cv * scaleF)))
                        lastW := p
                    if lastW < pHi
                        int   ae = displayBars - 1 - pHi
                        float ce = array.get(cacheCyc, (t - ae) % CAPB)
                        float te = ae < gHalf ? array.get(trendEdge, ae) : trendF[ae - gHalf]
                        if not na(ce) and not na(te)
                            array.push(wpts, chart.point.from_index(t - ae, math.exp(te + ce * scaleF)))
                    // glow underlay
                    if array.size(wpts) >= 2
                        array.push(g_polys, polyline.new(wpts, line_color = color.new(kcol, 82), line_width = 7, force_overlay = true))
                        array.push(g_polys, polyline.new(wpts, line_color = kcol, line_width = 2, force_overlay = true))
 
            // Past turns: zigzag on the cycle, threshold PIVOT_MIN x RMS. The extreme at
            // the last bar is skipped.
            array.clear(pivots)
            float thr = PIVOT_MIN * cycRMS
            float hiV = c0
            float loV = c0
            int   hiA = 0
            int   loA = 0
            int   dir = 0
            for a = 1 to displayBars - 1
                float v = array.get(cacheCyc, (t - a) % CAPB)
                if na(v) or array.size(pivots) >= MAX_PAST_TURNS
                    break
                if dir >= 0 and v > hiV
                    hiV := v
                    hiA := a
                if dir <= 0 and v < loV
                    loV := v
                    loA := a
                if dir >= 0 and hiV - v >= thr
                    if hiA > 0
                        array.push(pivots, hiA)
                    dir := -1
                    loV := v
                    loA := a
                else if dir <= 0 and v - loV >= thr
                    if loA > 0
                        array.push(pivots, -loA)
                    dir := 1
                    hiV := v
                    hiA := a
            for pv in pivots
                bool  isHi = pv > 0
                int   a    = math.abs(pv)
                float cm   = array.get(cacheCyc, (t - a) % CAPB)
                float tw   = a < gHalf ? array.get(trendEdge, a) : trendF[a - gHalf]
                string tip = (isHi ? "Cycle high" : "Cycle low") + "\nCycle length " + str.tostring(math.exp(array.get(cacheRec, (t - a) % CAPB)), "#.0") + " bars\n" + str.tostring(a) + " bars ago" + (a < lagW ? "\nMay still shift" : "")
                nLb := poolLabel(g_labels, nLb, true, t - a, math.exp(tw + cm * scaleF), "●", isHi ? label.style_label_down : label.style_label_up, color.new(color.black, 100), color.new(isHi ? colTop : colBot, a < lagW ? 50 : 5), size.small, tip)
 
            // Repaint boundary: bars older than lagW are final.
            if lagW < displayBars
                int   xRp = t - lagW
                float cRp = array.get(cacheCyc, xRp % CAPB)
                float tRp = trendF[lagW - gHalf]
                if not na(cRp) and not na(tRp)
                    float yRp = math.exp(tRp + cRp * scaleF)
                    nLn := poolLine(g_lines, nLn, xRp, yRp * 0.999, yRp * 1.001, color.new(color.gray, 65))
                    nLb := poolLabel(g_labels, nLb, true, xRp, yRp, "may repaint ›", label.style_label_lower_left, color.new(color.black, 100), color.new(color.gray, 20), size.small, "Right of this line the wave and its dots can still change as new bars arrive. Left of it, they are final.")
 
        // Current-state marker.
        string legTxt = na(hFirst) ? "No turn inside the forecast" : (firstIsTop ? "Rising, " : "Falling, ") + str.tostring(math.max(0.0, math.min(100.0, 100.0 * (1.0 - hFirst / (0.5 * dom)))), "#") + "% of the way to the next " + (firstIsTop ? "high" : "low") + ", due in " + str.tostring(math.round(hFirst)) + " bars"
        float chg = pEnd / dom - 1.0
        string trendTxt = hasProj ? "\nCycle length " + (chg < -0.03 ? "shortening" : chg > 0.03 ? "lengthening" : "steady") + ": " + str.tostring(dom, "#.0") + " -> " + str.tostring(pEnd, "#.0") + " bars over the next " + str.tostring(projBars) : ""
        nLb := poolLabel(g_labels, nLb, true, t, math.exp(tr0 + c0 * scaleF), "", label.style_circle, color.new(colRidge, 0), colRidge, size.tiny, "Cycle now: " + str.tostring(dom, "#.0") + " bars\n" + legTxt + trendTxt + "\n" + modelTxt + "\n" + turnTxt + "\n" + sigTxt)
 
    // Pooled drawings this update did not use.
    trimLabels(g_labels, nLb)
    trimLabels(g_paneLb, nPl)
    trimBoxes(g_boxes, nBx)
    trimLines(g_lines, nLn)
 
// =============================================================================
//  10. ALERTS
// =============================================================================
// Fired by 9.10. "Any alert() function call" carries the details.
alertcondition(alLowWin,  "Cycle low window opens",  "Neural Spectrogram: the next projected cycle LOW has entered its 80% timing window.")
alertcondition(alHighWin, "Cycle high window opens", "Neural Spectrogram: the next projected cycle HIGH has entered its 80% timing window.")

← 返回列表