Aurora Glow [JOAT]

officialjackofalltrades · study · 1388 行 · 点赞 59 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © officialjackofalltrades
//@version=6
indicator("Aurora Glow [JOAT]", "Aurora Glow", overlay = true, explicit_plot_zorder = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 0. SAFETY
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
max_bars_back(time, 5000)
// Scale anchor: a script that only draws boxes / lines / labels can land on its own price scale on a customer's
// chart. One invisible plot pins it to the price scale. display.pane keeps it out of the status line and data window.
plot(close, "Scale anchor (invisible)", color = color.new(#000000, 100), display = display.pane, editable = false)
 
float atrK = ta.atr(14)          // shared ATR for the glow width, the lane gap and every "ATR" number
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7. AURORA INPUTS (declared first so they lead the Settings dialog; the kit blocks follow)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G0 = "Aurora"
float  src      = input.source(close, "Centre line source / EMA length", group = G0, inline = "cl")
int    cLen     = input.int(21, "", minval = 2, maxval = 500, group = G0, inline = "cl",
     tooltip = "The centre line is an EMA of this source and length. The glow is built around it.")
int    cW       = input.int(2, "Centre line width", minval = 1, maxval = 4, group = G0,
     tooltip = "Width of the centre line. It takes the inner hue of the aurora, so it changes colour with the energy-direction score.")
bool   showGlow = input.bool(true, "Glow / layers per side", group = G0, inline = "gl")
int    glowN    = input.int(5, "", minval = 3, maxval = 5, group = G0, inline = "gl",
     tooltip = "How many gradient layers are stacked above and below the centre line (3-5). Each layer is its own gradient and the opacity falls off on a curve, so the light is densest at the centre and thins out to nothing at the outer edge. The hue moves from the inner colour to the outer colour layer by layer.")
float  calmW    = input.float(0.7, "Calm width / energy extra (ATR per side)", minval = 0.1, maxval = 3.0, step = 0.1, group = G0, inline = "wd")
float  extraW   = input.float(1.8, "", minval = 0.0, maxval = 5.0, step = 0.1, group = G0, inline = "wd",
     tooltip = "Width of the glow on each side of the centre line, in ATR(14): calm width + energy (0-1) x extra width. With 0.5 / 1.5 the glow is 0.5 ATR per side at zero energy and 2.0 ATR per side at full energy, before the momentum-side stretch.")
float  stretch  = input.float(0.8, "Momentum-side stretch", minval = 0.0, maxval = 2.0, step = 0.1, group = G0,
     tooltip = "How much further the side the momentum pushes toward reaches: that side is multiplied by (1 + stretch x score strength) and the other side is pulled in a little. 0 = always symmetric.")
int    peakT    = input.int(22, "Glow strength at peak energy", minval = 5, maxval = 90, group = G0,
     tooltip = "Transparency of the glow at the centre line when energy is 100 (lower = stronger). At zero energy the glow is 26 points fainter, so a quiet market is a soft haze and a strong move is a bright band. The Theme Brightness slider scales it.")
 
string G0e = "Energy"
int    eLen     = input.int(200, "Percentile window (bars)", minval = 50, maxval = 1000, group = G0e,
     tooltip = "Energy is the percentile rank (0-100) of the composite momentum against its own last N bars: 78 means it is higher than 78 % of that window. The same window scales the hue score.")
int    rsiLen   = input.int(14, "RSI length / slope bars", minval = 2, maxval = 100, group = G0e, inline = "rs")
int    slopeN   = input.int(3, "", minval = 1, maxval = 20, group = G0e, inline = "rs",
     tooltip = "The speed part of the composite: how many RSI points RSI(length) moved over the last N bars.")
int    volLen   = input.int(20, "Volume average length", minval = 5, maxval = 200, group = G0e,
     tooltip = "The participation part: volume divided by its simple average over this many bars. Symbols without volume use 1.0 (neutral).")
int    eSmooth  = input.int(5, "Energy / hue smoothing", minval = 1, maxval = 30, group = G0e, inline = "sm")
int    hSmooth  = input.int(8, "", minval = 1, maxval = 50, group = G0e, inline = "sm",
     tooltip = "EMA smoothing of the composite before it is ranked (first number) and of the energy-direction score that drives the hue (second number). Higher = calmer, slower colour drift.")
 
string G0c = "Aurora colours"
color  inBullOut = input.color(#2F80ED, "Custom outer bull / bear", group = G0c, inline = "oc")
color  inBearOut = input.color(#6C3CF0, "", group = G0c, inline = "oc",
     tooltip = "The outer hue of each side of the aurora, used by the Custom theme only (the inner hues are Custom bull / bear in the Theme group). Every other theme has its own outer hues.")
 
string G0p = "Plate"
bool   showPlate = input.bool(true, "Data plate at the right end / bars right", group = G0p, inline = "pl")
int    plateOff  = input.int(3, "", minval = 1, maxval = 30, group = G0p, inline = "pl",
     tooltip = "One short plate on the centre line right of the last candle: energy, rising / falling and the full glow width in ATR. The number is how many bars right of the last candle it sits. Every right-edge tag of the map (calm, surge, peak) sits in the same column, and the live rails and zones end one bar before it.")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7b. MAP INPUTS (the mapped layer: calm boxes, surge origin zones, peak levels, outline, tags)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G0k = "Calm boxes (compression)"
bool   showCalm  = input.bool(true, "Calm boxes", group = G0k,
     tooltip = "When energy stays low for a while the market is compressed. A box is drawn over the high / low of those bars in the aurora's mid-hue, tagged 'CALM · 18 bars · 1.2 ATR' (bars in the box · box height in ATR). It grows while candles close inside it; the first close outside freezes it (the tag goes).")
int    calmThr   = input.int(25, "Calm when energy is below / for at least (bars)", minval = 5, maxval = 50, group = G0k, inline = "ck")
int    calmMin   = input.int(10, "", minval = 3, maxval = 100, group = G0k, inline = "ck",
     tooltip = "A calm box starts once energy (0-100) has stayed below the first number for the second number of consecutive closed bars. Lower / longer = fewer, cleaner boxes.")
bool   showCalmR = input.bool(true, "CALM H / CALM L rails after the freeze", group = G0k,
     tooltip = "When a calm box freezes, its high and low continue to the right as thin dotted rails, 'CALM H 27,040.00' in the bear role colour and 'CALM L 26,980.25' in the bull role colour, until a wick trades through them; then the rail stops there as a dim stub with no text. An edge the breakout candle itself traded through gets no rail.")
int    keepCalm  = input.int(3, "Calm boxes kept", minval = 1, maxval = 6, group = G0k,
     tooltip = "The newest calm boxes kept on the chart (the live one included), with their rails. The oldest leaves first.")
 
string G0s = "Surge zones"
bool   showSurge = input.bool(true, "Surge origin zones", group = G0s,
     tooltip = "When energy crosses above the surge level, the bars just before it are the base the surge left from. The base is drawn as a glowing zone in the side colour (bull role when the energy-direction score is positive, bear role when negative), fading to the right, with a solid near edge, a faint dotted far edge and the base candles outlined. Tag: 'SURGE · 92 · 2.1 ATR leg' = peak energy and the leg from the base to the surge's extreme, updated while the surge runs and frozen after. Fresh = bright; tested (price back inside) = dimmer with a dashed edge; broken (a close through the far side) = grey dotted outline, no text.")
int    surgeThr  = input.int(80, "Surge when energy crosses above / ends below", minval = 50, maxval = 98, group = G0s, inline = "sg")
int    surgeEnd  = input.int(60, "", minval = 20, maxval = 95, group = G0s, inline = "sg",
     tooltip = "A surge starts on the closed bar where energy crosses above the first number and keeps running (its peak energy and leg keep updating) until energy closes below the second number. A new surge can only start after the last one ended. The end level is kept at least 1 below the start level.")
int    baseN     = input.int(3, "Base bars before the surge", minval = 1, maxval = 10, group = G0s,
     tooltip = "How many bars before the surge's first bar make its base (the zone covers their high / low).")
float  maxBaseA  = input.float(2.0, "Max base height (ATR)", minval = 0.5, maxval = 10.0, step = 0.1, group = G0s,
     tooltip = "A base taller than this (e.g. one that contains a crash candle) is trimmed to this height from its extreme: the low for a buyers' surge, the high for a sellers' surge.")
float  farAtr    = input.float(12.0, "Retire zones / peaks farther than (ATR)", minval = 0.0, maxval = 200.0, step = 1.0, group = G0s,
     tooltip = "Finished surge zones, broken outlines, peak levels and stubs, and frozen calm boxes farther than this from the close (in ATR) are removed, so an old level far away cannot squash the price scale. 0 = never.")
int    keepSurge = input.int(3, "Live zones kept per side / broken outlines kept", minval = 1, maxval = 5, group = G0s, inline = "sk")
int    keepBroke = input.int(2, "", minval = 0, maxval = 6, group = G0s, inline = "sk",
     tooltip = "Live (fresh or tested) zones kept per side; the oldest leaves first, and a new zone replaces an older one of the same side that it overlaps. Second number: grey outlines of broken zones kept (0 = none).")
 
string G0q = "Peak levels"
bool   showPeaks = input.bool(true, "PEAK H / PEAK L rails", group = G0q,
     tooltip = "The extreme each surge reached (highest high of a buyers' surge, lowest low of a sellers' surge) as a rail from that bar to the right edge: 'PEAK H 27,180.50 · +1.4 ATR' in the bear role colour, 'PEAK L' in the bull role colour, with the signed distance from the close. It follows the surge while it runs; once the surge has ended, the first wick through it stops it as a dim stub with no text.")
int    keepPeaks = input.int(3, "Peak levels kept", minval = 1, maxval = 6, group = G0q,
     tooltip = "Untouched peak rails kept; the oldest leaves first. The same number of swept stubs is kept.")
 
string G0o = "Outline"
bool   showOut   = input.bool(true, "Outline the outer glow edge / strength", group = G0o, inline = "ol")
int    outT      = input.int(35, "", minval = 0, maxval = 90, group = G0o, inline = "ol",
     tooltip = "A crisp thin line on the outermost edge of the glow on each side, in the current outer hue. The number is its transparency at full energy (lower = stronger); it softens in a quiet market and on the side against the momentum.")
int    outW      = input.int(1, "Outline width", minval = 1, maxval = 3, group = G0o)
 
string G0m = "Map look and tags"
int    slabsN    = input.int(6, "Gradient steps", minval = 3, maxval = 10, group = G0m,
     tooltip = "Calm boxes and surge zones are filled with nested boxes (all from the same origin, each one smaller), so the light is densest at the middle of a calm box and at the origin of a surge zone. Each step is one box toward the drawing limit.")
int    zoneT     = input.int(70, "Zone fill strength (transparency)", minval = 40, maxval = 95, group = G0m,
     tooltip = "Transparency of the densest part of a fresh surge zone before Brightness is applied (lower = stronger). Calm boxes are 6 softer, tested zones 12 softer, frozen calm boxes 16 softer.")
string tagSize   = input.string("Small", "Tag size", options = ["Small", "Normal"], group = G0m,
     tooltip = "Text size of every map tag (calm, surge, peak). Hover a tag for its full record.")
float  laneGap   = input.float(0.6, "Tag lane gap (ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = G0m,
     tooltip = "Minimum vertical distance between right-edge tags (the plate included). The gap used is the larger of this many ATR and 1/38 of the price span on the right edge, so a far level stretching the scale cannot squeeze the tags together.")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 1. THEME
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G1 = "Theme"
string theme  = input.string("JOAT Signature", "Theme", group = G1,
     options = ["JOAT Signature", "Midnight Blue / Red", "Aurora Night", "Delta Cyan / Pink", "Paper & Ink", "Lime Ember", "Custom"],
     tooltip = "Named presets. JOAT Signature is the brand pair. Paper & Ink is the clean black / white preset: direction is carried by position and line style, not colour. Custom uses the colour pickers below.")
int    bright = input.int(3, "Brightness", minval = 1, maxval = 5, group = G1,
     tooltip = "1 = faint, 3 = as designed, 5 = vivid. Scales every fill and glow transparency; solid lines and plates stay solid.")
string bgMode = input.string("Auto", "Chart background", options = ["Auto", "Dark", "Light"], group = G1,
     tooltip = "Auto reads the luminance of the chart background and swaps every role so it stays readable on a white chart.")
color  inBull  = input.color(#5CF0D7, "Custom bull / bear",     group = G1, inline = "c1")
color  inBear  = input.color(#B32AC3, "",                       group = G1, inline = "c1")
color  inAcc   = input.color(#FFFFFF, "Custom accent / neutral", group = G1, inline = "c2")
color  inNeu   = input.color(#787B86, "",                       group = G1, inline = "c2")
color  inTxt   = input.color(#D1D4DC, "Custom text / panel",    group = G1, inline = "c3")
color  inPanel = input.color(#0E1116, "",                       group = G1, inline = "c3")
color  inGlow  = input.color(#5CF0D7, "Custom glow",            group = G1, inline = "c4")
 
// f_lum: relative luminance 0..1 of any colour (Rec. 601 weights). Used for light / dark awareness and plate ink.
f_lum(color c) =>
    (0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) / 255.0
 
bool isLight = bgMode == "Light" ? true : bgMode == "Dark" ? false : f_lum(chart.bg_color) > 0.5
bool isMono  = theme == "Paper & Ink"
 
// Roles, resolved once. Defaults = JOAT Signature. Each preset overrides every role, with the white-chart swap.
color cBull   = isLight ? #12B5A0 : #5CF0D7
color cBear   = isLight ? #8E1FA0 : #B32AC3
color cAcc    = isLight ? #131722 : #FFFFFF
color cNeu    = #787B86
color cTxt    = isLight ? #131722 : #D1D4DC
color cPanel  = isLight ? #FFFFFF : #0E1116
color cGlow   = isLight ? #12B5A0 : #5CF0D7
color cCandle = cAcc                       // colour for the "Mono" candle paint (white bodies on black, ink on white)
if theme == "Midnight Blue / Red"
    cBull   := #2962FF
    cBear   := #F23645
    cAcc    := isLight ? #131722 : #FFFFFF
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #D1D4DC
    cPanel  := isLight ? #FFFFFF : #0B0F13
    cGlow   := #2962FF
    cCandle := cAcc
else if theme == "Aurora Night"
    cBull   := isLight ? #00A86B : #00E676
    cBear   := isLight ? #C2185B : #E040FB
    cAcc    := isLight ? #B59A00 : #FDD835
    cNeu    := #5C6BC0
    cTxt    := isLight ? #1A1F2E : #E6F1FF
    cPanel  := isLight ? #F4F6FB : #0A0E17
    cGlow   := isLight ? #0097A7 : #00BCD4   // the outer aurora hue (cyan); bear outer is #7C4DFF
    cCandle := cNeu
else if theme == "Delta Cyan / Pink"
    cBull   := isLight ? #0097A7 : #00E5FF
    cBear   := isLight ? #D81B60 : #FF2E88
    cAcc    := isLight ? #B59A00 : #FFD600
    cNeu    := #6B7280
    cTxt    := isLight ? #111827 : #F8FAFC
    cPanel  := isLight ? #FFFFFF : #111827
    cGlow   := isLight ? #0097A7 : #00E5FF
    cCandle := cNeu
else if theme == "Paper & Ink"
    color ink = isLight ? #111827 : #F0F3FA
    cBull   := ink
    cBear   := ink                            // same ink; bear objects carry direction by DASHED style (kBearStyle)
    cAcc    := #2962FF                        // the one accent: "live / nearest"; #F23645 is reserved for "broken"
    cNeu    := #B2B5BE
    cTxt    := ink
    cPanel  := isLight ? #FFFFFF : #131722
    cGlow   := #2962FF
    cCandle := ink
else if theme == "Lime Ember"
    cBull   := isLight ? #64DD17 : #B2FF59    // below-price liquidity
    cBear   := isLight ? #2962FF : #448AFF    // above-price liquidity
    cAcc    := #FF9800                        // ember: POC / peak row
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #E0E0E0
    cPanel  := isLight ? #FFFFFF : #161A25
    cGlow   := #FF9800
    cCandle := cNeu
else if theme == "Custom"
    cBull   := inBull
    cBear   := inBear
    cAcc    := inAcc
    cNeu    := inNeu
    cTxt    := inTxt
    cPanel  := inPanel
    cGlow   := inGlow
    cCandle := inAcc
 
color  cBroken   = #F23645                                            // grey-or-red for dead things; Paper & Ink "broken"
string kBearStyle = isMono ? line.style_dashed : line.style_solid    // Paper & Ink: direction by style, not hue
int    kPanelT    = isLight ? 8 : 15                                  // panel alpha: 92 % on white, 85 % on dark
 
// f_t: brightness-aware transparency. Scales the OPACITY (100 - t) by 0.5x .. 1.5x so faint things stay faint
// and solid things stay solid; fills (t >= 40) get +4 on a white chart and are floored at 92 in Paper & Ink.
f_t(int t) =>
    float op = 100.0 - t
    float k  = 1.0 + (bright - 3) * 0.25
    float tt = 100.0 - op * k
    if t >= 40
        if isMono
            tt := math.max(tt, 92.0)
        if isLight
            tt += 4.0
    math.min(100, math.max(0, math.round(tt)))
 
// f_ink: black or white text for a solid plate of colour c, by luminance.
f_ink(color c) =>
    f_lum(c) > 0.55 ? #0B0F13 : #FFFFFF
 
// f_grad: 3-stop gradient c1 (t = 0) -> c2 (t = 0.5) -> c3 (t = 1).
f_grad(color c1, color c2, color c3, float t) =>
    float tt = math.min(1.0, math.max(0.0, nz(t, 0.5)))
    tt < 0.5 ? color.from_gradient(tt, 0.0, 0.5, c1, c2) : color.from_gradient(tt, 0.5, 1.0, c2, c3)
 
// Aurora outer hues (this indicator's extra roles). The inner hue of each side is cBull / cBear; the outer layers
// drift toward these, so a bull aurora runs cyan -> azure and a bear aurora magenta -> violet, like a real one.
color cBullOut = isLight ? #1565C0 : #2F80ED
color cBearOut = isLight ? #4527A0 : #6C3CF0
if theme == "Midnight Blue / Red"
    cBullOut := isLight ? #00838F : #00B8D4
    cBearOut := isLight ? #8E24AA : #AB47BC
else if theme == "Aurora Night"
    cBullOut := isLight ? #0097A7 : #00BCD4
    cBearOut := isLight ? #5E35B1 : #7C4DFF
else if theme == "Delta Cyan / Pink"
    cBullOut := isLight ? #1E40AF : #2962FF
    cBearOut := isLight ? #5E35B1 : #7C4DFF
else if theme == "Paper & Ink"
    cBullOut := cBull                         // one ink: the side of the stretch carries the direction
    cBearOut := cBear
else if theme == "Lime Ember"
    cBullOut := isLight ? #00A86B : #00E5A0
    cBearOut := isLight ? #5E35B1 : #7C4DFF
else if theme == "Custom"
    cBullOut := inBullOut
    cBearOut := inBearOut
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4a. LAYOUT — clamps (defined early because the glow and text helpers use them)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_xo: a drawing anchored further back than ~5,000 bars kills the script on a LIVE bar (RE10143) and a Basic
// account only has 5,000 bars anyway. f_xr: nothing may be drawn more than 500 bars ahead.
f_xo(int b) =>
    math.max(b, bar_index - 4990)
f_xr(int b) =>
    math.min(b, bar_index + 490)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 2. GLOW
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_glowBox: N concentric boxes. Halo h (1..layers-1) is padded h * 0.05 ATR outward and fades toward 97;
// the last element of the returned array is the CORE box (fill baseT, 1-px border). Keep the array so the
// retirement helpers can delete all layers together. (Kit block; this indicator glows with fills instead.)
f_glowBox(int x1, float top, int x2, float bot, color c, int layers, int baseT) =>
    array<box> out = array.new<box>()
    int   xl  = f_xo(math.min(x1, x2))
    int   xr  = f_xr(math.max(x1, x2))
    float hi  = math.max(top, bot)
    float lo  = math.min(top, bot)
    float pad = nz(atrK, (hi - lo) * 0.2) * 0.05
    int   n   = math.max(1, layers)
    if n > 1
        for i = 1 to n - 1
            int h  = n - i                                        // outermost first so the core draws on top
            int tH = f_t(math.min(99, baseT + math.round(float(97 - baseT) * h / n)))
            array.push(out, box.new(xl, hi + pad * h, xr, lo - pad * h,
                 border_color = color.new(c, 100), border_width = 1, bgcolor = color.new(c, tH)))
    array.push(out, box.new(xl, hi, xr, lo,
         border_color = color.new(c, f_t(math.max(0, baseT - 50))), border_width = 1, bgcolor = color.new(c, f_t(baseT))))
    out
 
// f_glowLine: a solid core line of `width` with layers-1 wider, fainter halos beneath it. Last element = core.
f_glowLine(int x1, float y1, int x2, float y2, color c, int layers, int width) =>
    array<line> out = array.new<line>()
    int xl = f_xo(x1)
    int xr = f_xr(x2)
    int n  = math.max(1, layers)
    if n > 1
        for i = 1 to n - 1
            int h  = n - i
            int tH = f_t(math.min(99, 70 + math.round(27.0 * h / n)))
            array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, tH), width = math.max(1, width + 2 * h)))
    array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, f_t(0)), width = math.max(1, width)))
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 3. TEXT
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_plate: label on a SOLID plate of colour c, text in f_ink(c). sty = label.style_*, sz = size.*
f_plate(int x, float y, string txt, color c, string sty, string sz) =>
    label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = c, style = sty,
         textcolor = f_ink(c), size = sz)
 
// f_tag: plateless text (transparent background, coloured text). Evolves f_tag of [JOAT] Fibonacci Vault.
f_tag(int x, float y, string txt, color c, string sty, string sz) =>
    label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#000000, 100),
         style = sty, textcolor = c, size = sz)
 
// f_px: price with thousands separators at mintick precision: 24,550.25  /  1.08432  /  —
f_px(float p) =>
    string out = "—"
    if not na(p)
        string s = str.tostring(math.abs(p), format.mintick)
        array<string> parts = str.split(s, ".")
        string ip = array.get(parts, 0)
        string fp = ""
        if array.size(parts) > 1
            fp := "." + array.get(parts, 1)
        string g = ""
        int n = str.length(ip)
        if n > 0
            for i = 0 to n - 1
                g += str.substring(ip, i, i + 1)
                int rem = n - 1 - i
                if rem > 0 and rem % 3 == 0
                    g += ","
        out := (p < 0 ? "-" : "") + g + fp
    out
 
// f_k: compact numbers: 1.2K  3.4M  2.1B  (below 1,000: up to two decimals)
f_k(float v) =>
    string out = "—"
    if not na(v)
        float  a   = math.abs(v)
        string sgn = v < 0 ? "-" : ""
        if a >= 1e9
            out := sgn + str.tostring(a / 1e9, "#.#") + "B"
        else if a >= 1e6
            out := sgn + str.tostring(a / 1e6, "#.#") + "M"
        else if a >= 1e3
            out := sgn + str.tostring(a / 1e3, "#.#") + "K"
        else
            out := sgn + str.tostring(a, "#.##")
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4b. LAYOUT — label lane de-collision + object retirement
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Lane register: every right-edge label (the plate, the live calm tag, CALM H / L rails, SURGE tags, PEAK rails)
// is collected on the last bar into one register (section 15) and placed in one pass: sorted top to bottom, pushed
// apart symmetrically so price order is kept, then a top-down pass guarantees the gap. gap = max(lane gap x ATR,
// span / 38), span = everything drawn at the right edge + the last 300 bars' high / low. With the dashboard Top
// Right, tags in the band it covers are skipped and listed in the dashboard's tooltips instead.
 
// Retirement helpers (kit). Every map layer is capped by its own keep input and retired oldest-first.
f_capBoxes(array<box> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        box.delete(array.shift(a))
f_capLines(array<line> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        line.delete(array.shift(a))
f_capLabels(array<label> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        label.delete(array.shift(a))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 5. DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G2 = "Dashboard"
bool   showDash    = input.bool(true, "Show dashboard", group = G2)
string dashPos     = input.string("Top Right", "Dashboard position", group = G2,
     options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])
string dashSize    = input.string("Small", "Dashboard size", options = ["Tiny", "Small", "Normal", "Large"], group = G2)
bool   dashCompact = input.bool(false, "Compact dashboard", group = G2, tooltip = "Fewer rows for phones: header, the Energy row and the Read line.")
bool   dashTint    = input.bool(true, "Tinted value cells", group = G2, tooltip = "Value cells carry a faint tint of their own colour.")
 
f_pos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.bottom_right
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
// f_dashNew: panel in cPanel at the theme alpha, 1-px neutral frame. Rows = header + data rows + Read line.
f_dashNew(string pos, int cols, int rows) =>
    table.new(f_pos(pos), cols, rows, bgcolor = color.new(cPanel, kPanelT), frame_color = color.new(cNeu, 40),
         frame_width = 1, border_color = color.new(cNeu, 78), border_width = 1)
 
int dashRows = dashCompact ? 3 : 10                // header + 8 rows + Read
var table dash = f_dashNew(dashPos, 2, dashRows)
var array<int> dCur    = array.from(0)     // row cursor (arrays are the only globals a function may mutate)
var array<int> dMerged = array.from(-1)    // row already merged for the Read line
 
// f_dBegin: clear and rewind; call once per last-bar redraw before f_dHead.
f_dBegin() =>
    table.clear(dash, 0, 0, 1, dashRows - 1)
    array.set(dCur, 0, 0)
 
// f_dHead: title band (bold, glow tint) with symbol · timeframe on the right; tip = tooltip on both cells.
f_dHead(string title, string tip) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + title + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             bgcolor = color.new(cGlow, isLight ? 80 : 70), text_formatting = text.format_bold, tooltip = tip)
        table.cell(dash, 1, r, syminfo.ticker + " · " + timeframe.period + " ", text_color = cTxt, text_halign = text.align_right,
             text_size = f_size(dashSize), bgcolor = color.new(cGlow, isLight ? 88 : 80), tooltip = tip)
        array.set(dCur, 0, r + 1)
 
// f_dRow: name | value, value text in valueColor with an optional tint cell (evolves the 51-series f_row / f_pill).
f_dRow(string name, string value, color valueColor, string tip) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + name, text_color = color.new(cTxt, 25), text_halign = text.align_left,
             text_size = f_size(dashSize), tooltip = tip)
        table.cell(dash, 1, r, value + " ", text_color = valueColor, text_halign = text.align_right, text_size = f_size(dashSize),
             bgcolor = dashTint ? color.new(valueColor, isLight ? 90 : 86) : color.new(cPanel, 100), tooltip = tip)
        array.set(dCur, 0, r + 1)
 
// f_dRead: the one-line "Read" sentence, merged across both columns, italic. Always the last row.
f_dRead(string txt) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        if array.get(dMerged, 0) != r
            table.merge_cells(dash, 0, r, 1, r)
            array.set(dMerged, 0, r)
        table.cell(dash, 0, r, " " + txt + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             text_formatting = text.format_italic)
        array.set(dCur, 0, r + 1)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 6. CANDLES
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G4 = "Candles"
string paintMode = input.string("Off", "Candle paint", options = ["Off", "Score", "Mono"], group = G4,
     tooltip = "Off = chart candles (default). Score = bear -> neutral -> bull gradient by the energy-direction score that drives the aurora's hue: grey around balance, full bull colour while buyers push with energy, full bear colour while sellers do. Mono = one colour so the aurora carries all the colour.")
 
// f_candlePaint: na (Off), f_grad(cBear, cNeu, cBull, score) (Score) or cCandle (Mono). Feed it to barcolor().
f_candlePaint(string mode, float score) =>
    color out = na
    if mode == "Score"
        out := f_grad(cBear, cNeu, cBull, score)
    else if mode == "Mono"
        out := cCandle
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 8. ENGINE — centre line, composite momentum, percentile energy, energy-direction score
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
f_clamp(float v, float lo, float hi) =>
    math.min(hi, math.max(lo, v))
 
float centre = ta.ema(src, cLen)
float atrS   = na(atrK) or atrK <= 0 ? syminfo.mintick * 10 : atrK
 
// Composite momentum = speed x participation x range expansion. A product, so the energy is only high when the
// move is fast AND carried by volume AND widening the bars; any one of them missing pulls it down.
float rsi      = ta.rsi(close, rsiLen)
float rsiSlope = nz(rsi - rsi[slopeN])                               // RSI points over slopeN bars (signed)
float volAvg   = ta.sma(volume, volLen)
bool  hasVol   = not na(volume) and not na(volAvg) and volAvg > 0
float relVol   = hasVol ? volume / volAvg : 1.0                      // no volume on the symbol = neutral 1.0
float atrFast  = ta.atr(5)
float atrSlow  = ta.atr(50)
float atrExp   = na(atrFast) or na(atrSlow) or atrSlow <= 0 ? 1.0 : atrFast / atrSlow
float comp     = math.abs(rsiSlope) * math.sqrt(f_clamp(relVol, 0.2, 5.0)) * f_clamp(atrExp, 0.3, 3.0)
float compS    = ta.ema(comp, eSmooth)
 
// Energy: percentile rank 0-100 of the smoothed composite against its own last eLen bars, lightly smoothed.
float energy   = f_clamp(ta.ema(nz(ta.percentrank(compS, eLen), 50.0), 6), 0.0, 100.0)
float e01      = energy / 100.0
 
// Energy-direction score -1..+1: RSI slope, RSI level and the close's side of the centre line, weighted by
// energy (a quiet market drifts toward the blended mid-hue), EMA-smoothed, then scaled against its own recent
// extreme so the hue reaches full colour on every market and timeframe. The close and RSI lead the EMA, so the
// hue usually crosses neutral before the centre line turns.
float dSlope   = f_clamp(rsiSlope / 6.0, -1.0, 1.0)
float dPos     = f_clamp((close - nz(centre, close)) / atrS, -1.0, 1.0)
float dLvl     = f_clamp((nz(rsi, 50.0) - 50.0) / 20.0, -1.0, 1.0)
float dRaw     = (0.40 * dSlope + 0.35 * dPos + 0.25 * dLvl) * (0.35 + 0.65 * e01)
float dSm      = ta.ema(dRaw, hSmooth)
float dRef     = math.max(0.15, nz(ta.highest(math.abs(dSm), eLen), 0.15) * 0.6)
float score    = f_clamp(nz(dSm) / dRef, -1.0, 1.0)
float hueT     = 0.5 + 0.5 * score                                   // 0 = sellers' hue, 1 = buyers' hue
 
// Hue: inner = the side's main colour, outer = its outer hue; both blend straight from bear to bull, so the
// mid-hue around balance is a cool blend of the two (periwinkle in JOAT Signature), not grey.
color cIn  = color.from_gradient(hueT, 0.0, 1.0, cBear, cBull)
color cOut = color.from_gradient(hueT, 0.0, 1.0, cBearOut, cBullOut)
 
// Width per side, in price: ATR x (calm + energy x extra), the momentum side stretched, the other side pulled in.
float upPos   = math.max(score, 0.0)
float dnPos   = math.max(-score, 0.0)
float pullIn  = math.min(0.5, 0.25 * stretch)
float baseW   = (calmW + e01 * extraW) * atrS
// both widths are EMA-smoothed (8 bars) so the glow breathes instead of flickering bar to bar
float upW     = ta.ema(baseW * (1.0 + stretch * upPos) * (1.0 - pullIn * dnPos), 8)
float dnW     = ta.ema(baseW * (1.0 + stretch * dnPos) * (1.0 - pullIn * upPos), 8)
float spanATR = (upW + dnW) / atrS                                   // full glow height, top edge to bottom edge
 
// Glow brightness: transparency at the centre line goes from calmT (energy 0) to peakT (energy 100).
int   calmT  = math.min(97, peakT + 26)
float tIn    = calmT - (calmT - peakT) * e01
bool  glowOn = showGlow and not na(centre)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 9. AURORA PLOTS
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// PLOT COUNT (TradingView limit 64, RE10140; the local compiler does not check it). TradingView counts CALLS, not
// what is visible, so every call below counts whatever the inputs. Rules: plot() 1 with a const colour, 2 with a
// series colour; a gradient fill (series top/bottom values + series top/bottom colours) 4; barcolor() 1;
// alertcondition() 1.
//   scale anchor plot(close), const colour (section 0) ............ 1 x 1 =  1
//   glow axis anchor pC, const colour ............................. 1 x 1 =  1
//   glow edges up 1-4 + down 1-4, const colour .................... 8 x 1 =  8
//   outline up + down (pU5 / pD5 = the OUTERMOST edge, k = glowN),
//     series colour (v1.2: was const, +1 each) .................... 2 x 2 =  4
//   aurora layers up 1-5 + down 1-5, gradient fill ................ 10 x 4 = 40
//   centre line, series colour .................................... 1 x 2 =  2
//   barcolor (candle paint) ....................................... 1 x 1 =  1
//   alertcondition ................................................ none (no signals, no events)
//   TOTAL ......................................................... 57 of 64 (task ceiling 60). The mapped layer
//   (calm boxes, surge zones, peak rails, tags) is boxes / lines / labels and costs no plots. Room left: 3 units,
//   i.e. one series-colour plot + one const plot. A sixth glow layer per side (+10) does not fit.
// pU5 / pD5 carry the OUTERMOST edge whatever glowN is: with glowN < 5 layer 5's fill gets na values from f_layer
// (f_edge(5) is na) and pU4 is na or equal to pU5, so no extra area is filled; with glowN = 5 it is f_edge(5) as before.
 
// f_edge: boundary k of the glow on one side (side 1 = above, -1 = below). k = 0 is the centre line itself.
f_edge(int k, int side) =>
    float w = side == 1 ? upW : dnW
    glowOn and k <= glowN ? centre + side * w * k / glowN : na
 
// f_bc: colour at boundary j: hue moves inner -> outer, opacity falls off as (1 - j/N)^1.6 so the light is densest
// at the centre and reaches nothing at the outer edge; the side AGAINST the momentum is dimmed up to 40 %.
f_bc(int j, int side) =>
    float f   = math.min(1.0, j / float(glowN))
    color hue = color.from_gradient(f, 0.0, 1.0, cIn, cOut)
    float lag = side == 1 ? dnPos : upPos
    float op  = (100.0 - tIn) * math.pow(1.0 - f, 1.15) * (1.0 - 0.4 * lag)
    color.new(hue, f_t(math.min(100, math.max(0, math.round(100.0 - op)))))
 
// f_layer: [top value, bottom value, top colour, bottom colour] for layer k (inner boundary k-1, outer k).
f_layer(int k, int side) =>
    float vIn  = f_edge(k - 1, side)
    float vOut = f_edge(k, side)
    color cI   = f_bc(k - 1, side)
    color cO   = f_bc(k, side)
    float tv   = side == 1 ? vOut : vIn
    float bv   = side == 1 ? vIn : vOut
    color tcl  = side == 1 ? cO : cI
    color bcl  = side == 1 ? cI : cO
    [tv, bv, tcl, bcl]
 
color cHide = color.new(#000000, 100)
 
// Outline colour per side: the current outer hue, opacity (100 - strength) x (0.6 + 0.4 x energy) so it softens in a
// quiet market, and up to 45 % dimmer on the side against the momentum (the same side the glow dims).
f_outCol(int side) =>
    float lag = side == 1 ? dnPos : upPos
    float op  = (100.0 - outT) * (0.6 + 0.4 * e01) * (1.0 - 0.45 * lag)
    showOut ? color.new(cOut, f_t(int(math.min(100, math.max(0, math.round(100.0 - op)))))) : cHide
 
// Invisible anchors first; explicit_plot_zorder keeps every fill UNDER the centre line declared last.
pC  = plot(glowOn ? centre : na, "Glow axis", cHide, display = display.pane, editable = false)
pU1 = plot(f_edge(1, 1),  "Glow edge up 1",   cHide, display = display.pane, editable = false)
pU2 = plot(f_edge(2, 1),  "Glow edge up 2",   cHide, display = display.pane, editable = false)
pU3 = plot(f_edge(3, 1),  "Glow edge up 3",   cHide, display = display.pane, editable = false)
pU4 = plot(f_edge(4, 1),  "Glow edge up 4",   cHide, display = display.pane, editable = false)
pU5 = plot(f_edge(glowN, 1),  "Aurora outline up",   f_outCol(1),  outW, display = display.pane, editable = false)
pD1 = plot(f_edge(1, -1), "Glow edge down 1", cHide, display = display.pane, editable = false)
pD2 = plot(f_edge(2, -1), "Glow edge down 2", cHide, display = display.pane, editable = false)
pD3 = plot(f_edge(3, -1), "Glow edge down 3", cHide, display = display.pane, editable = false)
pD4 = plot(f_edge(4, -1), "Glow edge down 4", cHide, display = display.pane, editable = false)
pD5 = plot(f_edge(glowN, -1), "Aurora outline down", f_outCol(-1), outW, display = display.pane, editable = false)
 
[u1t, u1b, u1tc, u1bc] = f_layer(1, 1)
[u2t, u2b, u2tc, u2bc] = f_layer(2, 1)
[u3t, u3b, u3tc, u3bc] = f_layer(3, 1)
[u4t, u4b, u4tc, u4bc] = f_layer(4, 1)
[u5t, u5b, u5tc, u5bc] = f_layer(5, 1)
[d1t, d1b, d1tc, d1bc] = f_layer(1, -1)
[d2t, d2b, d2tc, d2bc] = f_layer(2, -1)
[d3t, d3b, d3tc, d3bc] = f_layer(3, -1)
[d4t, d4b, d4tc, d4bc] = f_layer(4, -1)
[d5t, d5b, d5tc, d5bc] = f_layer(5, -1)
 
fill(pC,  pU1, u1t, u1b, u1tc, u1bc, title = "Aurora up 1")
fill(pU1, pU2, u2t, u2b, u2tc, u2bc, title = "Aurora up 2")
fill(pU2, pU3, u3t, u3b, u3tc, u3bc, title = "Aurora up 3")
fill(pU3, pU4, u4t, u4b, u4tc, u4bc, title = "Aurora up 4")
fill(pU4, pU5, u5t, u5b, u5tc, u5bc, title = "Aurora up 5")
fill(pC,  pD1, d1t, d1b, d1tc, d1bc, title = "Aurora down 1")
fill(pD1, pD2, d2t, d2b, d2tc, d2bc, title = "Aurora down 2")
fill(pD2, pD3, d3t, d3b, d3tc, d3bc, title = "Aurora down 3")
fill(pD3, pD4, d4t, d4b, d4tc, d4bc, title = "Aurora down 4")
fill(pD4, pD5, d5t, d5b, d5tc, d5bc, title = "Aurora down 5")
 
// The centre line last, so it draws on top of the glow, in the inner hue.
plot(centre, "Centre line", color.new(cIn, f_t(0)), cW)
 
// Candle paint: the energy-direction score (0 = sellers, 0.5 = balance, 1 = buyers). Off by default.
barcolor(f_candlePaint(paintMode, hueT))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 10. NUMBERS FOR THE PLATE AND THE DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
float  eChg     = energy - nz(energy[3], energy)
string eWord    = eChg > 2.0 ? "rising" : eChg < -2.0 ? "falling" : "steady"
string sideWord = score > 0.2 ? "buyers" : score < -0.2 ? "sellers" : "balanced"
float  spanChg  = spanATR - nz(spanATR[3], spanATR)
string wWord    = spanChg > 0.05 ? "widening" : spanChg < -0.05 ? "narrowing" : "steady"
 
// Hue shift: bars since the score last crossed zero (the aurora's colour crossed its neutral mid-hue).
var int  hueCrossBar = na
var bool hueSeen     = false
bool huePos = score > 0
if bar_index > 0 and huePos != huePos[1]
    hueCrossBar := bar_index
    hueSeen     := true
if na(hueCrossBar)
    hueCrossBar := bar_index
int    hueBars = bar_index - hueCrossBar
string hueTxt  = str.tostring(hueBars) + (hueSeen ? "" : "+") + " bars"
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 11. MAP — types and shared series
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Every map decision (box born / grown / frozen, zone born / tested / broken, peak moved / swept) is taken on a
// CONFIRMED bar only, so nothing repaints. The last-bar pass (section 14) only moves right edges, writes tag text
// and places the tags.
 
// Calm: one compression box. live = still growing (every close since it started stayed inside). x2 / t2 = the last
// bar that closed inside. After the freeze its rails start at x2; hSwept / lSwept = a wick traded through that edge.
type Calm
    int   x1
    int   t1
    int   x2
    int   t2
    float top
    float bot
    bool  live
    int   frozeBar
    bool  hSwept
    bool  lSwept
    array<box> slabs
    box   frame
    line  railH
    line  railL
    label tag
    label tagH
    label tagL
 
// Zone: one surge origin zone (the base the surge left from). state 0 fresh, 1 tested. born = the surge's first
// bar; tests and breaks are counted from the bar after it. dead = deleted (a running surge stops updating it).
type Zone
    bool  bull
    float top
    float bot
    int   x1
    int   bornT
    int   born
    float peakE
    float leg
    bool  running
    int   state
    int   tests
    bool  touching
    bool  dead
    array<box>  slabs
    array<line> edge
    line  far
    box   origin
    label tag
 
// Peak: the extreme one surge reached. running = its surge still runs (the rail follows it and cannot be swept).
type Peak
    bool  isHigh
    float price
    int   x
    int   startT
    bool  running
    bool  dead
    line  ln
    label tag
 
var array<Calm> calms     = array.new<Calm>()
var array<Zone> zBull     = array.new<Zone>()
var array<Zone> zBear     = array.new<Zone>()
var array<box>  brokeB    = array.new<box>()      // grey dotted outlines of broken surge zones (no text)
var array<Peak> peaks     = array.new<Peak>()     // untouched peak rails, the running one included
var array<line> peakStubs = array.new<line>()     // swept peak rails: dim stubs, no text
 
color cMid      = color.from_gradient(0.5, 0.0, 1.0, cBear, cBull)   // the aurora's mid-hue around balance
int   halfBarMs = timeframe.in_seconds() * 500                        // half a candle in ms: boxes cover whole candles
int   sEndLvl   = math.min(surgeEnd, surgeThr - 1)
float hi300     = ta.highest(high, 300)
float lo300     = ta.lowest(low, 300)
float calmHiN   = ta.highest(high, calmMin)
float calmLoN   = ta.lowest(low, calmMin)
float baseHiS   = ta.highest(high, baseN)[1]                          // the baseN bars before this one
float baseLoS   = ta.lowest(low, baseN)[1]
bool  eCrossUp  = ta.crossover(energy, surgeThr)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 12. MAP — helpers
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_layerT: the transparency each of n NESTED layers gets so the full stack reaches t0 (after Brightness / light
// chart / Paper & Ink) where all n overlap; where fewer overlap the fill is fainter, step by step, with no seams.
f_layerT(int t0, int n) =>
    int   tb = f_t(t0)
    float a  = 1.0 - math.pow(1.0 - (100 - tb) / 100.0, 1.0 / math.max(1, n))
    int(math.max(0, math.min(99, math.round(100 - 100 * a))))
 
// f_calmLayout: the slabs share the box's width and shrink toward its middle line, so the light is densest at the
// middle and fades out to the high and the low; the frame is the crisp outline. xloc.bar_time, whole candles.
f_calmLayout(Calm c) =>
    int   l    = c.t1 - halfBarMs
    int   r    = c.t2 + halfBarMs
    float mid  = (c.top + c.bot) / 2.0
    float half = (c.top - c.bot) / 2.0
    int   n    = array.size(c.slabs)
    if n > 0
        for k = 0 to n - 1
            float h = half * (n - k) / n
            box   b = array.get(c.slabs, k)
            box.set_lefttop(b, l, mid + h)
            box.set_rightbottom(b, r, mid - h)
    box.set_lefttop(c.frame, l, c.top)
    box.set_rightbottom(c.frame, r, c.bot)
 
// f_calmNew: a live calm box over bars x1 .. now (t1 = open time of bar x1).
f_calmNew(int x1, int t1, float top, float bot) =>
    int tl = f_layerT(math.min(95, zoneT + 6), slabsN)
    array<box> sl = array.new<box>()
    for k = 0 to slabsN - 1
        array.push(sl, box.new(t1, top, time, bot, xloc = xloc.bar_time, border_color = color.new(cMid, 100), border_width = 1,
             bgcolor = color.new(cMid, tl)))
    box fr = box.new(t1, top, time, bot, xloc = xloc.bar_time, border_color = color.new(cMid, f_t(10)), border_width = 1,
         bgcolor = color.new(cMid, 100))
    Calm c = Calm.new(x1 = x1, t1 = t1, x2 = bar_index, t2 = time, top = top, bot = bot, live = true, frozeBar = na,
         hSwept = false, lSwept = false, slabs = sl, frame = fr, railH = na, railL = na, tag = na, tagH = na, tagL = na)
    f_calmLayout(c)
    c
 
// f_calmKill: delete every drawing of a calm box.
f_calmKill(Calm c) =>
    for b in c.slabs
        box.delete(b)
    array.clear(c.slabs)
    box.delete(c.frame)
    line.delete(c.railH)
    line.delete(c.railL)
    label.delete(c.tag)
    label.delete(c.tagH)
    label.delete(c.tagL)
 
// f_calmFreeze: the first close outside (or the 500-bar guard). The box dims and loses its tag; every edge the
// freezing candle did NOT trade through continues as a dotted rail from the box's right edge (hitH / hitL = it did).
f_calmFreeze(Calm c, bool hitH, bool hitL) =>
    c.live     := false
    c.frozeBar := bar_index
    c.hSwept   := hitH
    c.lSwept   := hitL
    int tl = f_layerT(math.min(97, zoneT + 16), array.size(c.slabs))
    for b in c.slabs
        box.set_bgcolor(b, color.new(cMid, tl))
    box.set_border_color(c.frame, color.new(cMid, f_t(45)))
    label.delete(c.tag)
    c.tag := na
    if showCalmR
        if not hitH
            c.railH := line.new(f_xo(c.x2), c.top, f_xr(bar_index + 1), c.top, color = color.new(cBear, f_t(25)),
                 style = line.style_dotted, width = 1)
        if not hitL
            c.railL := line.new(f_xo(c.x2), c.bot, f_xr(bar_index + 1), c.bot, color = color.new(cBull, f_t(25)),
                 style = line.style_dotted, width = 1)
 
// f_calmSweep: after the freezing bar, the first wick through an edge stops that rail there as a dim stub, no text.
f_calmSweep(Calm c) =>
    if not c.live and bar_index > c.frozeBar
        if not c.hSwept and high > c.top
            c.hSwept := true
            if not na(c.railH)
                line.set_x1(c.railH, f_xo(c.x2))
                line.set_x2(c.railH, bar_index)
                line.set_color(c.railH, color.new(cBear, f_t(75)))
            label.delete(c.tagH)
            c.tagH := na
        if not c.lSwept and low < c.bot
            c.lSwept := true
            if not na(c.railL)
                line.set_x1(c.railL, f_xo(c.x2))
                line.set_x2(c.railL, bar_index)
                line.set_color(c.railL, color.new(cBull, f_t(75)))
            label.delete(c.tagL)
            c.tagL := na
 
// f_zStyle: near-edge style. Paper & Ink: bear role dashed, bull role solid (direction by style); every other theme:
// fresh solid, tested dashed (state by line).
f_zStyle(bool bull, int state) =>
    isMono ? (bull ? line.style_solid : line.style_dashed) : state == 0 ? line.style_solid : line.style_dashed
 
// f_zoneKill: delete every drawing of a surge zone and mark it dead.
f_zoneKill(Zone z) =>
    for b in z.slabs
        box.delete(b)
    array.clear(z.slabs)
    for l in z.edge
        line.delete(l)
    array.clear(z.edge)
    line.delete(z.far)
    box.delete(z.origin)
    label.delete(z.tag)
    z.tag  := na
    z.dead := true
 
// f_zoneLayout: NESTED slabs (all from the origin, each shorter) so the fill is strongest at the base and fades to
// the right edge xr; the edge lines reach xr. x1 is re-clamped every time: a long-lived zone ages past 4,990 bars.
f_zoneLayout(Zone z, int xr) =>
    int   x0   = f_xo(z.x1)
    int   n    = array.size(z.slabs)
    float span = math.max(1.0, float(xr - x0))
    if n > 0
        for k = 0 to n - 1
            box b = array.get(z.slabs, k)
            box.set_left(b, x0)
            box.set_right(b, x0 + int(math.round(span * (n - k) / n)))
    for l in z.edge
        line.set_x1(l, x0)
        line.set_x2(l, xr)
    if not na(z.far)
        line.set_x1(z.far, x0)
        line.set_x2(z.far, xr)
 
// f_zoneNew: the base of a new surge as a glowing zone: nested gradient, solid near edge with a soft glow under it,
// faint dotted far edge, the base candles outlined (origin block). An older zone of the same side that it overlaps
// leaves first; the oldest of the side leaves when the keep count is passed. tP = open time of the last base bar.
f_zoneNew(array<Zone> zs, bool bull, float top, float bot, int x1, int t1, int tP) =>
    int n = array.size(zs)
    if n > 0
        for i = n - 1 to 0
            Zone o = array.get(zs, i)
            if top >= o.bot and bot <= o.top
                f_zoneKill(o)
                array.remove(zs, i)
    color c     = bull ? cBull : cBear
    float nearP = bull ? top : bot
    float farP  = bull ? bot : top
    int   x2    = f_xr(bar_index + math.max(0, plateOff - 1))
    int   tl    = f_layerT(zoneT, slabsN)
    array<box> sl = array.new<box>()
    for k = 0 to slabsN - 1
        array.push(sl, box.new(f_xo(x1), top, f_xo(x1), bot, border_color = color.new(c, 100), border_width = 1,
             bgcolor = color.new(c, tl)))
    box ob = box.new(t1 - halfBarMs, top, tP + halfBarMs, bot, xloc = xloc.bar_time, border_color = color.new(c, f_t(0)),
         border_width = 1, bgcolor = color.new(c, f_t(math.max(40, zoneT - 20))))
    array<line> eg = f_glowLine(x1, nearP, x2, nearP, c, 3, 2)
    line.set_style(array.last(eg), f_zStyle(bull, 0))
    line fr = line.new(f_xo(x1), farP, x2, farP, color = color.new(c, f_t(60)), style = line.style_dotted, width = 1)
    Zone z = Zone.new(bull = bull, top = top, bot = bot, x1 = x1, bornT = time, born = bar_index, peakE = energy, leg = 0.0,
         running = true, state = 0, tests = 0, touching = false, dead = false, slabs = sl, edge = eg, far = fr, origin = ob, tag = na)
    f_zoneLayout(z, x2)
    array.push(zs, z)
    while array.size(zs) > keepSurge
        f_zoneKill(array.shift(zs))
    z
 
// f_zoneTested: fresh -> tested. Dimmer fill and origin block, the glow under the near edge goes, the edge turns
// dashed and thinner.
f_zoneTested(Zone z) =>
    color c = z.bull ? cBull : cBear
    z.state := 1
    int tl = f_layerT(math.min(95, zoneT + 12), array.size(z.slabs))
    for b in z.slabs
        box.set_bgcolor(b, color.new(c, tl))
    if array.size(z.edge) > 1
        line core0 = array.pop(z.edge)
        for l in z.edge
            line.delete(l)
        array.clear(z.edge)
        array.push(z.edge, core0)
    if array.size(z.edge) > 0
        line core = array.last(z.edge)
        line.set_style(core, f_zStyle(z.bull, 1))
        line.set_color(core, color.new(c, f_t(30)))
        line.set_width(core, 1)
    box.set_bgcolor(z.origin, color.new(c, f_t(math.min(95, zoneT - 5))))
    box.set_border_color(z.origin, color.new(c, f_t(40)))
    box.set_border_style(z.origin, line.style_dashed)
 
// f_zoneBreak: a close through the far side. Every live drawing goes; a grey dotted outline with no text stays from
// the base to the breaking candle (the newest keepBroke of them).
f_zoneBreak(Zone z) =>
    color cDead = isMono ? cBroken : cNeu
    f_zoneKill(z)
    if keepBroke > 0
        array.push(brokeB, box.new(f_xo(z.x1), z.top, f_xr(bar_index), z.bot, border_color = color.new(cDead, f_t(35)),
             border_width = 1, border_style = line.style_dotted, bgcolor = color.new(cDead, 100)))
    f_capBoxes(brokeB, keepBroke)
 
// f_zoneUpdate: one side, one confirmed bar, from the bar after each zone's birth: break (close through the far
// side), visit start (a wick back inside = tested), visit end.
f_zoneUpdate(array<Zone> zs) =>
    int n = array.size(zs)
    if n > 0
        for i = n - 1 to 0
            Zone z = array.get(zs, i)
            if bar_index > z.born
                bool inZ = high >= z.bot and low <= z.top
                bool brk = z.bull ? close < z.bot : close > z.top
                if brk
                    f_zoneBreak(z)
                    array.remove(zs, i)
                    z.touching := false
                else if inZ and not z.touching
                    z.tests += 1
                    if z.state == 0
                        f_zoneTested(z)
                    z.touching := true
                else if not inZ and z.touching
                    z.touching := false
 
// f_peakNew: a new surge's extreme as a rail (PEAK H bear role, PEAK L bull role; Paper & Ink: PEAK H dashed). The
// oldest untouched rail leaves when the keep count is passed.
f_peakNew(bool isHigh, float p, int x) =>
    color c  = isHigh ? cBear : cBull
    line  ln = line.new(f_xo(x), p, f_xr(bar_index + 1), p, color = color.new(c, f_t(20)),
         style = isHigh ? kBearStyle : line.style_solid, width = 1)
    Peak pk = Peak.new(isHigh = isHigh, price = p, x = x, startT = time, running = true, dead = false, ln = ln, tag = na)
    array.push(peaks, pk)
    while array.size(peaks) > keepPeaks
        Peak o = array.shift(peaks)
        line.delete(o.ln)
        label.delete(o.tag)
        o.dead := true
    pk
 
// f_peakSweep: once its surge has ended, the first wick through a peak stops the rail there as a dim stub, no text.
f_peakSweep() =>
    int n = array.size(peaks)
    if n > 0
        for i = n - 1 to 0
            Peak p = array.get(peaks, i)
            if not p.running and (p.isHigh ? high > p.price : low < p.price)
                line.set_x1(p.ln, f_xo(p.x))
                line.set_x2(p.ln, bar_index)
                line.set_color(p.ln, color.new(p.isHigh ? cBear : cBull, f_t(78)))
                label.delete(p.tag)
                p.tag  := na
                p.dead := true
                array.push(peakStubs, p.ln)
                array.remove(peaks, i)
    f_capLines(peakStubs, keepPeaks)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 13. MAP — per bar (confirmed bars only, so no box, zone or rail repaints)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Surge state: sOn = a surge is running; sBull = its side (the energy-direction score's sign on its first bar);
// sExt / sExtBar = its extreme so far; sPeakE = its peak energy; sLeg = base far side -> extreme, in the ATR of its
// first bar (sAtr). They keep the last surge's numbers after it ends (dashboard "Last surge").
var bool  sOn     = false
var bool  sSeen   = false
var bool  sBull   = true
var int   sStart  = na
var float sBaseHi = na
var float sBaseLo = na
var float sAtr    = na
var float sExt    = na
var int   sExtBar = na
var float sPeakE  = na
var float sLeg    = na
var Zone  sZone   = na
var Peak  sPeak   = na
var int   calmRun = 0                              // consecutive closed bars with energy below the calm level
 
if barstate.isconfirmed
    // 1. live surge zones: broken (close through the far side) / tested (a wick back inside)
    f_zoneUpdate(zBull)
    f_zoneUpdate(zBear)
 
    // 2. the running surge: follow its extreme, raise its peak energy, end it below the end level
    if sOn
        if sBull ? high > sExt : low < sExt
            sExt    := sBull ? high : low
            sExtBar := bar_index
        sPeakE := math.max(sPeakE, energy)
        sLeg   := (sBull ? sExt - sBaseLo : sBaseHi - sExt) / sAtr
        if energy < sEndLvl
            sOn := false
        if not na(sZone)
            if not sZone.dead
                sZone.peakE   := sPeakE
                sZone.leg     := sLeg
                sZone.running := sOn
        if not na(sPeak)
            if not sPeak.dead
                sPeak.price   := sExt
                sPeak.x       := sExtBar
                sPeak.running := sOn
                line.set_xy1(sPeak.ln, f_xo(sExtBar), sExt)
                line.set_y2(sPeak.ln, sExt)
    // 3. a new surge: energy crosses above the surge level while none is running
    else if eCrossUp and not na(baseHiS) and not na(baseLoS)
        sOn     := true
        sSeen   := true
        sBull   := score >= 0
        sStart  := bar_index
        sBaseHi := baseHiS
        sBaseLo := baseLoS
        sAtr    := atrS
        if sBaseHi - sBaseLo > maxBaseA * atrS        // trim a tall base (crash / spike candle) from its extreme
            if score >= 0
                sBaseHi := sBaseLo + maxBaseA * atrS
            else
                sBaseLo := sBaseHi - maxBaseA * atrS
        sExt    := sBull ? high : low
        sExtBar := bar_index
        sPeakE  := energy
        sLeg    := (sBull ? sExt - sBaseLo : sBaseHi - sExt) / sAtr
        sZone   := na
        sPeak   := na
        // no zone when the base is a single price or the surge's first bar already closed through its far side
        bool bornBroken = sBull ? close < sBaseLo : close > sBaseHi
        if showSurge and sBaseHi - sBaseLo >= syminfo.mintick and not bornBroken
            array<Zone> side = sBull ? zBull : zBear
            sZone     := f_zoneNew(side, sBull, sBaseHi, sBaseLo, bar_index - baseN, time[baseN], time[1])
            sZone.leg := sLeg
        if showPeaks
            sPeak := f_peakNew(sBull, sExt, sExtBar)
 
    // 4. peaks of ended surges: the first wick through one stops it
    f_peakSweep()
 
    // 4b. far retirement: finished zones and peaks far from the close leave (they squash the price scale)
    if farAtr > 0
        for sd = 0 to 1
            array<Zone> zs = sd == 0 ? zBull : zBear
            int nz0 = array.size(zs)
            if nz0 > 0
                for i = nz0 - 1 to 0
                    Zone zf = array.get(zs, i)
                    if not zf.running and math.min(math.abs(close - zf.top), math.abs(close - zf.bot)) > farAtr * atrS
                        f_zoneKill(zf)
                        array.remove(zs, i)
        int np0 = array.size(peaks)
        if np0 > 0
            for i = np0 - 1 to 0
                Peak pf = array.get(peaks, i)
                if not pf.running and math.abs(close - pf.price) > farAtr * atrS
                    line.delete(pf.ln)
                    label.delete(pf.tag)
                    array.remove(peaks, i)
        int nb0 = array.size(brokeB)
        if nb0 > 0
            for i = nb0 - 1 to 0
                box bf = array.get(brokeB, i)
                if math.min(math.abs(close - box.get_top(bf)), math.abs(close - box.get_bottom(bf))) > farAtr * atrS
                    box.delete(bf)
                    array.remove(brokeB, i)
        int ns0 = array.size(peakStubs)
        if ns0 > 0
            for i = ns0 - 1 to 0
                line lf = array.get(peakStubs, i)
                if math.abs(close - line.get_y1(lf)) > farAtr * atrS
                    line.delete(lf)
                    array.remove(peakStubs, i)
        int nc0 = array.size(calms)
        if nc0 > 0
            for i = nc0 - 1 to 0
                Calm cf = array.get(calms, i)
                if not cf.live and math.min(math.abs(close - cf.top), math.abs(close - cf.bot)) > farAtr * atrS
                    f_calmKill(cf)
                    array.remove(calms, i)
 
    // 5. calm boxes: born after calmMin calm bars, grown while closes stay inside, frozen by the first close outside
    calmRun := energy < calmThr ? calmRun + 1 : 0
    if showCalm
        bool hasLive = false
        if array.size(calms) > 0
            Calm lc0 = array.last(calms)
            hasLive := lc0.live
        if hasLive
            Calm lc = array.last(calms)
            if close > lc.top or close < lc.bot
                f_calmFreeze(lc, high > lc.top, low < lc.bot)
                calmRun := 0
            else
                lc.top := math.max(lc.top, high)
                lc.bot := math.min(lc.bot, low)
                lc.x2  := bar_index
                lc.t2  := time
                f_calmLayout(lc)
                if bar_index - lc.x1 >= 500           // guard: a box no close ever leaves stops growing after 500 bars
                    f_calmFreeze(lc, false, false)
                    calmRun := 0
        else if calmRun >= calmMin
            array.push(calms, f_calmNew(bar_index - calmMin + 1, time[calmMin - 1], calmHiN, calmLoN))
            while array.size(calms) > keepCalm
                f_calmKill(array.shift(calms))
        for c in calms
            f_calmSweep(c)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 14. RIGHT EDGE — live geometry, the plate and every map tag through ONE lane pass (last bar, every tick)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_tagSet: create a tag on its first last-bar pass, then only move / rewrite it.
f_tagSet(label lb, int x, float y, string txt, color c, string tip) =>
    label out = lb
    if na(out)
        out := f_tag(x, y, txt, c, label.style_label_left, f_size(tagSize))
    else
        label.set_xy(out, x, y)
        label.set_text(out, txt)
        label.set_textcolor(out, c)
    label.set_tooltip(out, tip)
    out
 
// f_push: one entry of the lane register (desired y, height in gaps, label, its text, never-skip flag).
f_push(array<float> ys, array<float> hs, array<label> ls, array<string> ts, array<bool> fx, float y, float h, label lb, string txt, bool fix) =>
    array.push(ys, y)
    array.push(hs, h)
    array.push(ls, lb)
    array.push(ts, txt)
    array.push(fx, fix)
 
// f_sgn: signed ATR distance "+1.4 ATR" / "-0.8 ATR"
f_sgn(float d) =>
    (d >= 0 ? "+" : "-") + str.tostring(math.abs(d), "0.0") + " ATR"
 
var label plateLbl   = na
string    hiddenTags = ""                          // tags the Top Right dashboard would cover (listed in its tooltips)
string    tFmt       = "yyyy-MM-dd HH:mm"
 
if barstate.islast
    int   xEnd = f_xr(bar_index + math.max(0, plateOff - 1))   // live rails and zones end here
    int   xTag = f_xr(bar_index + plateOff)                    // every right-edge tag sits in this column
    float eHi  = close
    float eLo  = close
    array<float>  tY   = array.new<float>()
    array<float>  tHt  = array.new<float>()
    array<label>  tL   = array.new<label>()
    array<string> tTx  = array.new<string>()
    array<bool>   tFix = array.new<bool>()
 
    // the AURORA plate on the centre line (never skipped)
    if showPlate and not na(centre)
        string ptxt = "AURORA · " + str.tostring(energy, "0") + " · " + eWord + " · " + str.tostring(spanATR, "0.0") + " ATR"
        if na(plateLbl)
            plateLbl := f_plate(xTag, centre, ptxt, cIn, label.style_label_left, size.small)
        else
            label.set_xy(plateLbl, xTag, centre)
            label.set_text(plateLbl, ptxt)
            label.set_color(plateLbl, cIn)
            label.set_textcolor(plateLbl, f_ink(cIn))
        label.set_tooltip(plateLbl, "Energy " + str.tostring(energy, "0") + " of 100 (percentile of the last " + str.tostring(eLen)
             + " bars) · side " + sideWord + " · glow " + str.tostring(upW / atrS, "0.0") + " ATR above, " + str.tostring(dnW / atrS, "0.0")
             + " ATR below the " + str.tostring(cLen) + " EMA at " + f_px(centre))
        f_push(tY, tHt, tL, tTx, tFix, centre, 1.3, plateLbl, ptxt, true)
    else if not na(plateLbl)
        label.delete(plateLbl)
        plateLbl := na
 
    // calm boxes: the live box's tag, then the CALM H / CALM L rails of frozen boxes that no wick has swept
    for c in calms
        if c.live
            int    nb  = c.x2 - c.x1 + 1
            float  hA  = (c.top - c.bot) / atrS
            string txt = "CALM · " + str.tostring(nb) + " bars · " + str.tostring(hA, "0.0") + " ATR"
            string tip = "Calm box (compression): energy stayed below " + str.tostring(calmThr) + " for " + str.tostring(calmMin)
                 + "+ closed bars from " + str.format_time(c.t1, tFmt, syminfo.timezone) + ". " + str.tostring(nb) + " bars so far, high "
                 + f_px(c.top) + ", low " + f_px(c.bot) + " (" + str.tostring(hA, "0.0") + " ATR tall). It grows while candles close inside it; the first close outside freezes it and leaves CALM H / CALM L rails."
            float  y   = (c.top + c.bot) / 2.0
            c.tag := f_tagSet(c.tag, xTag, y, txt, cMid, tip)
            f_push(tY, tHt, tL, tTx, tFix, y, 1.0, c.tag, txt, false)
        else
            if not na(c.railH) and not c.hSwept
                line.set_x1(c.railH, f_xo(c.x2))
                line.set_x2(c.railH, xEnd)
                string txH = "CALM H " + f_px(c.top)
                string tpH = "High of the calm box that froze " + str.tostring(bar_index - c.frozeBar) + " bars ago: " + f_px(c.top) + ", "
                     + f_sgn((c.top - close) / atrS) + " from the close. No wick has traded above it since; the first one ends the rail."
                c.tagH := f_tagSet(c.tagH, xTag, c.top, txH, cBear, tpH)
                f_push(tY, tHt, tL, tTx, tFix, c.top, 1.0, c.tagH, txH, false)
            if not na(c.railL) and not c.lSwept
                line.set_x1(c.railL, f_xo(c.x2))
                line.set_x2(c.railL, xEnd)
                string txL = "CALM L " + f_px(c.bot)
                string tpL = "Low of the calm box that froze " + str.tostring(bar_index - c.frozeBar) + " bars ago: " + f_px(c.bot) + ", "
                     + f_sgn((c.bot - close) / atrS) + " from the close. No wick has traded below it since; the first one ends the rail."
                c.tagL := f_tagSet(c.tagL, xTag, c.bot, txL, cBull, tpL)
                f_push(tY, tHt, tL, tTx, tFix, c.bot, 1.0, c.tagL, txL, false)
 
    // surge zones: right edges, then "SURGE · 92 · 2.1 ATR leg" at the zone's middle
    array<Zone> allZ = array.concat(array.copy(zBull), zBear)
    for z in allZ
        f_zoneLayout(z, xEnd)
        color  c   = z.bull ? cBull : cBear
        string txt = "SURGE · " + str.tostring(z.peakE, "0") + " · " + str.tostring(z.leg, "0.0") + " ATR leg"
        bool   ins = close <= z.top and close >= z.bot
        float  dz  = z.bull ? close - z.top : z.bot - close
        string tip = "Surge origin (" + (z.bull ? "buyers" : "sellers") + "): energy crossed " + str.tostring(surgeThr) + " at "
             + str.format_time(z.bornT, tFmt, syminfo.timezone) + "; the base is the " + str.tostring(baseN) + " bars before it, "
             + f_px(z.bot) + " - " + f_px(z.top) + ". Peak energy " + str.tostring(z.peakE, "0") + ", leg " + str.tostring(z.leg, "0.0")
             + " ATR from the base's " + (z.bull ? "low to the surge's high" : "high to the surge's low") + (z.running ? " (surge still running)." : " (surge ended).")
             + "\nState: " + (z.state == 0 ? "fresh, price has not come back inside" : "tested " + str.tostring(z.tests) + "x")
             + "\nClose: " + (ins ? "inside the zone" : str.tostring(dz / atrS, "0.0") + " ATR " + (z.bull ? "above" : "below") + " it")
        float  y   = (z.top + z.bot) / 2.0
        z.tag := f_tagSet(z.tag, xTag, y, txt, z.state == 0 ? c : color.new(c, 30), tip)
        f_push(tY, tHt, tL, tTx, tFix, y, 1.0, z.tag, txt, false)
        eHi := math.max(eHi, z.top)
        eLo := math.min(eLo, z.bot)
 
    // peak rails: "PEAK H 27,180.50 · +1.4 ATR" (signed distance from the close)
    for p in peaks
        line.set_x1(p.ln, f_xo(p.x))
        line.set_x2(p.ln, xEnd)
        float  d   = (p.price - close) / atrS
        string txt = (p.isHigh ? "PEAK H " : "PEAK L ") + f_px(p.price) + " · " + f_sgn(d)
        string tip = (p.isHigh ? "Highest high of the buyers' surge" : "Lowest low of the sellers' surge") + " that started "
             + str.format_time(p.startT, tFmt, syminfo.timezone) + ": " + f_px(p.price) + ", " + f_sgn(d) + " from the close. "
             + (p.running ? "The surge is still running, so the rail follows its extreme." : "No wick has traded through it since the surge ended; the first one ends the rail.")
        p.tag := f_tagSet(p.tag, xTag, p.price, txt, p.isHigh ? cBear : cBull, tip)
        f_push(tY, tHt, tL, tTx, tFix, p.price, 1.0, p.tag, txt, false)
 
    // ONE lane pass. gap = max(lane gap x ATR, span / 38); span = every tag, every live zone, the glow's outer edges
    // and the last 300 bars' high / low. 1) tags in the band a Top Right dashboard covers are skipped (text cleared,
    // listed in its tooltips; the plate never); 2) the rest, sorted top to bottom, are pushed apart symmetrically so
    // price order is kept, then a top-down pass guarantees the gap; 3) a tag pushed up into that band is cleared too.
    int m = array.size(tY)
    if m > 0
        float gU   = f_edge(glowN, 1)
        float gD   = f_edge(glowN, -1)
        float spHi = math.max(math.max(nz(hi300, high), math.max(eHi, nz(gU, close))), array.max(tY))
        float spLo = math.min(math.min(nz(lo300, low), math.min(eLo, nz(gD, close))), array.min(tY))
        float spn  = math.max(spHi - spLo, syminfo.mintick)
        float gap  = math.max(math.max(atrS * laneGap, spn / 38.0), syminfo.mintick * 2)
        bool  dTop = showDash and dashPos == "Top Right"
        float band = (dashCompact ? 0.07 : 0.20) * (dashSize == "Tiny" ? 0.8 : dashSize == "Normal" ? 1.25 : dashSize == "Large" ? 1.6 : 1.0) * spn
        array<int>   ord = array.sort_indices(tY, order.descending)
        array<float> ys  = array.new<float>()
        array<float> hs  = array.new<float>()
        array<int>   ks  = array.new<int>()
        for k in ord
            float y = array.get(tY, k)
            if dTop and not array.get(tFix, k) and y > spHi - band
                label lb = array.get(tL, k)
                label.set_xy(lb, xTag, y)
                label.set_text(lb, "")
                hiddenTags += (hiddenTags == "" ? "" : "\n") + array.get(tTx, k)
            else
                array.push(ys, y)
                array.push(hs, array.get(tHt, k))
                array.push(ks, k)
        int mm = array.size(ys)
        if mm > 1
            for it = 0 to 40
                bool moved = false
                for j = 1 to mm - 1
                    float need = gap * (array.get(hs, j - 1) + array.get(hs, j)) / 2.0
                    float dd   = array.get(ys, j - 1) - array.get(ys, j)
                    if dd < need * 0.999
                        float sh = (need - dd) / 2.0
                        array.set(ys, j - 1, array.get(ys, j - 1) + sh)
                        array.set(ys, j, array.get(ys, j) - sh)
                        moved := true
                if not moved
                    break
            for j = 1 to mm - 1
                float need = gap * (array.get(hs, j - 1) + array.get(hs, j)) / 2.0
                if array.get(ys, j - 1) - array.get(ys, j) < need
                    array.set(ys, j, array.get(ys, j - 1) - need)
        if mm > 0
            for j = 0 to mm - 1
                int   k  = array.get(ks, j)
                float y  = array.get(ys, j)
                label lb = array.get(tL, k)
                label.set_xy(lb, xTag, y)
                if dTop and not array.get(tFix, k) and y > spHi - band
                    label.set_text(lb, "")
                    hiddenTags += (hiddenTags == "" ? "" : "\n") + array.get(tTx, k)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 15. DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
if showDash and barstate.islast
    // map numbers (shared by the rows and the Read line)
    bool  calmLive = false
    int   calmN    = 0
    float calmH    = na
    if array.size(calms) > 0
        Calm cl = array.last(calms)
        if cl.live
            calmLive := true
            calmN    := cl.x2 - cl.x1 + 1
            calmH    := (cl.top - cl.bot) / atrS
    int    sAgo    = sSeen ? bar_index - sStart : 0
    string sSide   = sBull ? "buyers" : "sellers"
    string hidTip  = hiddenTags == "" ? "" : "\n\nTags not drawn because this dashboard covers their band (their rails and zones are still drawn):\n" + hiddenTags
 
    f_dBegin()
    f_dHead("AURORA GLOW", "Aurora Glow: momentum energy drawn as light, with calm boxes (compression), surge origin zones and peak levels mapped on top. Hover each row for what it measures." + hidTip)
 
    color eCol = color.from_gradient(e01, 0.0, 1.0, cNeu, cIn)
    f_dRow("Energy", str.tostring(energy, "0") + " · " + eWord, eCol,
         "Momentum energy 0-100: the percentile rank of speed (RSI slope) x participation (relative volume) x range expansion (fast ATR / slow ATR) against the last "
         + str.tostring(eLen) + " bars. 78 = stronger than 78 % of that window. Momentum traders read high and rising energy as a move with fuel behind it, and low or falling energy as a move running out of it. Rising / falling compares with 3 bars ago. On the chart: the brightness and width of the glow, and the plate.")
 
    if not dashCompact
        color sCol = sideWord == "balanced" ? cNeu : cIn
        f_dRow("Side", sideWord + " · " + str.tostring(math.abs(score) * 100.0, "0") + "%", sCol,
             "Which side the energy-direction score leans to and how strongly (0-100 % of its recent extreme). It mixes RSI slope, RSI level and the close's side of the centre line, weighted by energy. 'balanced' = within 20 % of neutral. Traders read a strong one-sided score as control by that side, and a score sliding toward balance as that control fading. On the chart: the hue of the aurora and the side that stretches further.")
 
        f_dRow("Width", str.tostring(spanATR, "0.0") + " ATR · " + wWord, cTxt,
             "Full height of the glow from its top edge to its bottom edge, in ATR(14): calm width + energy x extra width on each side, with the momentum side stretched. Widening = energy is building; narrowing = it is draining away. A very narrow aurora describes a quiet, compressed market. On the chart: the glow itself, its outline and the plate.")
 
        f_dRow("Hue shift", hueTxt, cTxt,
             "Bars since the aurora's colour last crossed its neutral mid-hue (the score changed sign). A recent shift means the momentum direction changed lately; because the close and RSI lead the average, the hue often shifts before the centre line turns. '+' = no crossing inside the loaded history. On the chart: where the colour of the glow changes over.")
 
        f_dRow("Volume", hasVol ? str.tostring(relVol, "0.0") + "x avg" : "no volume", hasVol ? (relVol >= 1.0 ? cIn : cNeu) : cNeu,
             "Current bar volume divided by its " + str.tostring(volLen) + "-bar average: the participation part of the energy. Above 1.0x = more traders involved than usual, which tends to make a move more meaningful; below = a thin move. Symbols without volume count as 1.0x. On the chart: part of the glow's width and brightness.")
 
        f_dRow("Calm", calmLive ? str.tostring(calmN) + " bars · " + str.tostring(calmH, "0.0") + " ATR" : (showCalm ? "none" : "off"), calmLive ? cMid : cNeu,
             "A live calm box: energy stayed below " + str.tostring(calmThr) + " for at least " + str.tostring(calmMin) + " closed bars and every close since has stayed inside the box. Value = bars in the box · its height in ATR. Many traders read a long, tight compression as a market storing energy, and watch its edges once price leaves it. 'none' = no live box. On the chart: the mid-hue box tagged 'CALM'; after a close outside freezes it, the CALM H / CALM L rails.")
 
        string surV = "none yet"
        if not showSurge and not showPeaks
            surV := "off"
        else if sSeen
            surV := sSide + " · " + str.tostring(sPeakE, "0") + " · " + str.tostring(sLeg, "0.0") + " ATR · " + str.tostring(sAgo) + " bars"
        f_dRow("Last surge", surV, sSeen ? (sBull ? cBull : cBear) : cNeu,
             "The most recent surge (energy crossed above " + str.tostring(surgeThr) + "): its side (the energy-direction score at its first bar), its peak energy, the leg from its base to its extreme in ATR, and the bars since it started. "
             + (sSeen ? (sOn ? "It is still running (energy has not closed below " + str.tostring(sEndLvl) + " yet), so the numbers can still grow." : "It has ended; the numbers are final.") : "")
             + " Momentum traders read the base of a strong surge as the area the move left from, and its extreme as the level the move reached. On the chart: the SURGE zone and its PEAK rail.")
 
        int    nP  = array.size(peaks)
        string pkV = showPeaks ? "none" : "off"
        color  pkC = cNeu
        if nP > 0
            Peak  best  = array.get(peaks, 0)
            float bestD = math.abs(best.price - close)
            for p in peaks
                if math.abs(p.price - close) < bestD
                    best  := p
                    bestD := math.abs(p.price - close)
            pkV := str.tostring(nP) + " · nearest " + (best.isHigh ? "H " : "L ") + f_sgn((best.price - close) / atrS)
            pkC := best.isHigh ? cBear : cBull
        f_dRow("Peaks untouched", pkV, pkC,
             "Peak rails (the extreme each surge reached) that no wick has traded through since their surge ended, and the signed distance from the close to the nearest one in ATR (+ above, - below). Untouched extremes are levels many traders watch for a revisit. On the chart: the PEAK H / PEAK L rails and their tags." + hidTip)
 
    // Read line: clauses joined with "; ", a new line whenever the current one would pass ~60 characters.
    string sideClause = sideWord == "balanced" ? "balanced, glow " + wWord : sideWord + " lead, glow " + wWord
    array<string> readParts = array.from("Energy " + str.tostring(energy, "0") + " and " + eWord,
         sideClause + " at " + str.tostring(spanATR, "0.0") + " ATR")
    if calmLive
        array.push(readParts, "calm box " + str.tostring(calmN) + " bars, " + str.tostring(calmH, "0.0") + " ATR tall")
    if sOn
        array.push(readParts, (sBull ? "buyers'" : "sellers'") + " surge running, peak " + str.tostring(sPeakE, "0") + ", leg " + str.tostring(sLeg, "0.0") + " ATR")
    else if sSeen and not calmLive
        array.push(readParts, "last surge " + sSide + " " + str.tostring(sAgo) + " bars ago")
    array.push(readParts, "hue crossed " + hueTxt + " ago")
    string readTxt = ""
    int    readLen = 0
    for p in readParts
        if readLen == 0
            readTxt += p
            readLen := str.length(p)
        else if readLen + 2 + str.length(p) > 60
            readTxt += ";\n " + p
            readLen := str.length(p)
        else
            readTxt += "; " + p
            readLen += 2 + str.length(p)
    f_dRead(readTxt)

← 返回列表