Pullback Ribbon [JOAT]

officialjackofalltrades · study · 837 行 · 点赞 69 · 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("Pullback Ribbon [JOAT]", "Pullback Ribbon", overlay = 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 glow depth, lane gaps, ribbon width, mark offsets and distances
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7. RIBBON INPUTS (declared first so they lead the Settings dialog; the kit blocks follow)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G0 = "Ribbon"
string ribStyle  = input.string("Clean", "Ribbon style", options = ["Clean", "Full ribbon"], group = G0,
     tooltip = "Clean = the two edges only: a crisp fast line, a slow line coloured by the trend, a gradient body between them and a soft glow on the far side of the slow line that fades away from price. Full ribbon = every average of the fan drawn, with filled bands between the two edges instead of the body.")
string maType    = input.string("EMA", "Average type", options = ["EMA", "SMA", "HMA", "WMA"], group = G0,
     tooltip = "The moving-average family used for every line. EMA hugs price, SMA is the smoothest, HMA turns fastest, WMA sits in between.")
float  src       = input.source(close, "Source", group = G0, tooltip = "The price each average is built from.")
int    fastLen   = input.int(20, "Fast / slow length", minval = 2, maxval = 500, group = G0, inline = "len")
int    slowLen   = input.int(50, "", minval = 3, maxval = 1000, group = G0, inline = "len",
     tooltip = "The two edges of the ribbon: fast length first, slow length second. If the two are swapped the shorter one is still treated as the fast edge.")
int    lineCount = input.int(7, "Lines in the full ribbon", minval = 3, maxval = 7, group = G0,
     tooltip = "How many averages are fanned between the fast and the slow length (evenly spaced lengths). They are drawn only in the Full ribbon style, but in both styles they measure the ribbon ORDER shown in the Trend row: fully ordered = every average stacked in sequence.")
string fastMode  = input.string("Accent", "Fast line colour / width", options = ["Accent", "Trend"], group = G0, inline = "fw")
int    fastW     = input.int(2, "", minval = 1, maxval = 4, group = G0, inline = "fw",
     tooltip = "Accent = the theme accent (white on a dark chart, ink on a white one), so the fast line stays crisp against the coloured slow line. Trend = the same trend colour as the slow line.")
int    slowW     = input.int(2, "Slow line width", minval = 1, maxval = 4, group = G0,
     tooltip = "The slow line carries the trend colour: bull role while the fast average sits above it, bear role while below, fading through neutral grey around a crossing.")
bool   showFill  = input.bool(true, "Fill the ribbon / full-ribbon transparency", group = G0, inline = "f1")
int    fillT     = input.int(84, "", minval = 40, maxval = 97, group = G0, inline = "f1",
     tooltip = "Clean: a gradient body between the two lines, faintest at the fast line and strongest at the slow line, where it meets the glow. Full ribbon: the transparency of the band next to the fast line when no pullback has held yet (bands fade outward from it and brighten as pullbacks hold). The Theme Brightness slider scales both.")
 
string G0g = "Glow"
bool   showGlow   = input.bool(true, "Glow on the far side of the slow line", group = G0g,
     tooltip = "Soft layered light beyond the slow line, on the side away from price: below it in an up ribbon, above it in a down ribbon. It strengthens as pullbacks hold and dims while the averages are out of order. Hidden on the bar where the two edges cross.")
int    glowLayers = input.int(4, "Glow layers / depth (ATR)", minval = 2, maxval = 4, group = G0g, inline = "gl")
float  glowDepth  = input.float(1.0, "", minval = 0.2, maxval = 3.0, step = 0.1, group = G0g, inline = "gl",
     tooltip = "How many fading layers (2-4) and how far the glow reaches beyond the slow line in ATR(14). Each layer is its own gradient and the fade follows a curve, so the light is densest at the line and thins out quickly.")
int    glowT      = input.int(58, "Glow strength", minval = 20, maxval = 90, group = G0g,
     tooltip = "Transparency of the glow right at the slow line before the held-pullback lift (lower = stronger, 0 = solid). The Theme Brightness slider scales it.")
 
string G0b = "Pullbacks"
int    heldFull  = input.int(5, "Held pullbacks for full brightness", minval = 1, maxval = 20, group = G0b,
     tooltip = "The glow is at its base strength with no held pullback in the current run and strongest once this many have held in a row. A break or a crossing of the edges resets the run.")
int    recLen    = input.int(10, "Record length (pullbacks)", minval = 1, maxval = 50, group = G0b,
     tooltip = "How many of the most recent pullbacks make the 'held N of M' record. Both held and broken pullbacks count, across breaks and direction changes.")
float  breakTol  = input.float(0.0, "Far-edge break tolerance (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = G0b,
     tooltip = "A close must be this many ATR beyond the far edge to count as a break. 0 = any close through the far edge.")
bool   showMarks = input.bool(true, "Mark held pullbacks / size", group = G0b, inline = "m1")
string markSize  = input.string("Small", "", options = ["Small", "Normal", "Large"], group = G0b, inline = "m1",
     tooltip = "A small dot at the deepest point of every pullback that held, with the run count and the depth from the fast line in ATR: '3 · 0.42 ATR'. A mark appears when its pullback resolves (a close back on the trend side) and sits on the bar of the deepest point. The size also applies to the break tags.")
bool   showBreak = input.bool(true, "Break tag when the far edge is closed through", group = G0b,
     tooltip = "A grey tag with the closing price on the bar that closes through the far edge of the ribbon and resets the held run.")
 
string G0p = "Plate"
bool   showPlate = input.bool(true, "Data plate at the right end / bars right", group = G0p, inline = "p1")
int    plateOff  = input.int(3, "", minval = 1, maxval = 50, group = G0p, inline = "p1",
     tooltip = "Line 1: ribbon state, width in ATR, held record. Line 2: widening or narrowing, ribbon age, close vs the fast line. The number is how many bars right of the last candle it sits, on the fast line.")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 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)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 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.
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 asks f_lane for a y. The register is cleared at the start of each
// last-bar redraw (f_laneReset) so the slots are recomputed from scratch every tick.
var array<float> laneReg = array.new<float>()
 
f_laneReset() =>
    array.clear(laneReg)
 
// f_lane: returns the nearest free y to `y`, trying y, y - gap, y + gap, y - 2gap, y + 2gap ... (gap = ATR mult)
f_lane(float y, float gapAtrMult) =>
    float gap = math.max(nz(atrK) * gapAtrMult, syminfo.mintick * 2)
    float out = y
    for k = 0 to 24
        float off  = math.ceil(k / 2.0) * gap
        float cand = k % 2 == 0 ? y + off : y - off
        bool  free = true
        for r in laneReg
            if math.abs(r - cand) < gap * 0.999
                free := false
        if free
            out := cand
            break
    array.push(laneReg, out)
    out
 
// Retirement: push every new object into one array per kind, then cap it. Oldest leaves first (array.shift).
// This indicator draws no boxes or lines (the ribbon and its glow are plots + fills); only labels are capped.
string G3 = "Limits (free account)"
int maxLabels = input.int(120, "Max marks and tags kept", minval = 4, maxval = 500, group = G3,
     tooltip = "Oldest first. A held-pullback mark costs two labels (the dot and its tag), a break tag one.")
 
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 held-pullback 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 : 8                 // header + 6 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.
f_dHead(string title) =>
    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)
        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))
        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("Score", "Candle paint", options = ["Off", "Score", "Mono"], group = G4,
     tooltip = "Off = chart candles. Score = bear -> neutral -> bull gradient by where the close sits around the ribbon: neutral grey inside it, full colour about 0.75 ATR beyond an edge, so pullbacks into the ribbon go grey and stretched candles carry the trend colour. Mono = one colour so the ribbon carries all the colour. On by default because this is a ribbon tool.")
 
// 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. RIBBON — seven average slots fanned between the fast and the slow length (slots past "Lines" are hidden)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_ma: every family is computed on every bar (so the calls stay consistent) and the chosen one is returned.
f_ma(float s, simple int len, string typ) =>
    float e = ta.ema(s, len)
    float m = ta.sma(s, len)
    float h = ta.hma(s, len)
    float w = ta.wma(s, len)
    typ == "EMA" ? e : typ == "SMA" ? m : typ == "HMA" ? h : w
 
bool isFull = ribStyle == "Full ribbon"
int lenA = math.min(fastLen, slowLen)              // fast edge (the shorter length)
int lenB = math.max(fastLen, slowLen)              // slow edge
int lDen = math.max(1, lineCount - 1)
// Linear spacing: slot i sits at lenA + (lenB - lenA) * i / (lines - 1). Slots at or past the line count take the
// slow length so slot (lines - 1) is always the slow edge and every hidden slot is a harmless duplicate of it.
int len0 = lenA
int len1 = 1 >= lineCount ? lenB : math.round(lenA + (lenB - lenA) * 1.0 / lDen)
int len2 = 2 >= lineCount ? lenB : math.round(lenA + (lenB - lenA) * 2.0 / lDen)
int len3 = 3 >= lineCount ? lenB : math.round(lenA + (lenB - lenA) * 3.0 / lDen)
int len4 = 4 >= lineCount ? lenB : math.round(lenA + (lenB - lenA) * 4.0 / lDen)
int len5 = 5 >= lineCount ? lenB : math.round(lenA + (lenB - lenA) * 5.0 / lDen)
int len6 = lenB
 
float ma0 = f_ma(src, len0, maType)
float ma1 = f_ma(src, len1, maType)
float ma2 = f_ma(src, len2, maType)
float ma3 = f_ma(src, len3, maType)
float ma4 = f_ma(src, len4, maType)
float ma5 = f_ma(src, len5, maType)
float ma6 = f_ma(src, len6, maType)
 
float maF = ma0                                    // fast edge
float maS = ma6                                    // slow edge (every slot >= lines - 1 equals it)
float rTop = math.max(maF, maS)
float rBot = math.min(maF, maS)
float atrS = na(atrK) or atrK <= 0 ? math.max(rTop - rBot, syminfo.mintick * 10) : atrK
 
// Ribbon order: count adjacent pairs stacked upward / downward across the slots (measured in both styles).
array<float> maArr = array.from(ma0, ma1, ma2, ma3, ma4, ma5, ma6)
int upPairs = 0
int dnPairs = 0
for i = 0 to lineCount - 2
    float a = array.get(maArr, i)
    float b = array.get(maArr, i + 1)
    if a > b
        upPairs += 1
    else if a < b
        dnPairs += 1
bool alignedUp = upPairs == lineCount - 1
bool alignedDn = dnPairs == lineCount - 1
bool aligned   = alignedUp or alignedDn
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 9. PULLBACK ENGINE (confirmed bars only, so history and the live bar agree)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// A pullback starts when the close enters the ribbon (between the edges). It HOLDS when a later close sits back on
// the trend side of the fast line without any close through the far edge in between; it BREAKS on a close through
// the far edge (beyond the tolerance). Held pullbacks in a row drive the glow strength; a break or a direction
// change resets that run. The record keeps the last N outcomes regardless of resets ("held 4 of 5").
var int   dirPrev     = 0          // ribbon direction on the previous confirmed bar (1 fast above slow, -1 below)
var int   flipBar     = na         // confirmed bar the current direction began on (ribbon age)
var bool  flipSeen    = false      // a real crossing happened inside the loaded history (else the age is a floor)
var bool  inPull      = false      // a pullback is open (close went inside, no verdict yet)
var bool  wasThrough  = false      // the previous confirmed close was already through the far edge
var float pullExt     = na         // the pullback's extreme (low in an up ribbon, high in a down ribbon)
var int   pullExtBar  = na         // bar of that extreme
var float pullDepth   = na         // extreme's distance from the fast line in ATR at the time it printed
var int   pullStart   = na         // first bar inside
var int   heldRun     = 0          // held pullbacks in a row since the last break / direction change
var array<int> record = array.new<int>()   // last N outcomes, 1 = held, 0 = broke, newest last
var int   lastOutcome = 0          // 1 held, -1 broke, 0 none yet
var float lastDepth   = na         // depth of the last resolved pullback (ATR)
var int   lastBar     = na         // bar the last pullback resolved on
var int   lastLen     = na         // bars the last pullback spent inside the ribbon
var array<label> tagLabels = array.new<label>()
 
// Mark lane: historical marks sit at different bars, so the right-edge register does not see them. This short
// memory (last 16 tags) pushes a new tag AWAY from price while an earlier tag within 12 bars sits in its slot.
var array<int>   mkX = array.new<int>()
var array<float> mkY = array.new<float>()
f_mkLane(int x, float y, float gap, int away) =>
    float out = y
    for k = 0 to 8
        float cand = y + away * k * gap
        bool  free = true
        int   n    = array.size(mkX)
        if n > 0
            for j = 0 to n - 1
                if math.abs(array.get(mkX, j) - x) < 12 and math.abs(array.get(mkY, j) - cand) < gap * 0.999
                    free := false
        if free
            out := cand
            break
    array.push(mkX, x)
    array.push(mkY, out)
    if array.size(mkX) > 16
        array.shift(mkX)
        array.shift(mkY)
    out
 
f_laneReset()                      // one right-edge lane register per bar: the plate is the only right-edge label
 
int dir = maF > maS ? 1 : maF < maS ? -1 : 0
bool heldNow  = false
bool brokeNow = false
bool flipNow  = false
 
if barstate.isconfirmed and dir != 0
    if dir != dirPrev
        if dirPrev != 0
            flipNow  := true
            flipSeen := true
        dirPrev    := dir
        flipBar    := bar_index
        heldRun    := 0
        inPull     := false
        wasThrough := false
    float farEdge   = dir == 1 ? rBot : rTop
    bool  throughFar = dir == 1 ? close < farEdge - breakTol * atrS : close > farEdge + breakTol * atrS
    bool  trendSide  = dir == 1 ? close > maF : close < maF
    bool  inside     = not throughFar and not trendSide
    if throughFar
        if inPull
            array.push(record, 0)
            lastOutcome := -1
            lastDepth   := pullDepth
            lastBar     := bar_index
            lastLen     := bar_index - pullStart
        // a break only means something when there was a run or an open pullback to break
        brokeNow   := not wasThrough and (heldRun > 0 or inPull)
        heldRun    := 0
        inPull     := false
    else if inPull
        if dir == 1 and low < pullExt
            pullExt    := low
            pullExtBar := bar_index
            pullDepth  := (maF - low) / atrS
        if dir == -1 and high > pullExt
            pullExt    := high
            pullExtBar := bar_index
            pullDepth  := (high - maF) / atrS
        if trendSide
            heldRun += 1
            array.push(record, 1)
            lastOutcome := 1
            lastDepth   := pullDepth
            lastBar     := bar_index
            lastLen     := bar_index - pullStart
            inPull      := false
            heldNow     := true
    else if inside
        inPull     := true
        pullExt    := dir == 1 ? low : high
        pullExtBar := bar_index
        pullDepth  := (dir == 1 ? maF - low : high - maF) / atrS
        pullStart  := bar_index
    wasThrough := throughFar
    while array.size(record) > recLen
        array.shift(record)
 
    // Held mark: a plateless tag (no dot: a dot at a swing extreme reads as a signal) "run · depth ATR", pushed away from price
    if heldNow and showMarks
        color mc   = dir == 1 ? cBull : cBear
        int   mx   = f_xo(pullExtBar)
        string tip = "Pullback held · " + str.tostring(heldRun) + " in a row · " + (dir == 1 ? "low " : "high ") + f_px(pullExt)
             + " · " + str.tostring(pullDepth, "0.00") + " ATR " + (dir == 1 ? "below" : "above") + " the fast line · "
             + str.tostring(lastLen) + " bars inside the ribbon"
        float ty = f_mkLane(mx, dir == 1 ? pullExt - 0.28 * atrS : pullExt + 0.28 * atrS, 0.7 * atrS, dir == 1 ? -1 : 1)
        label tg = f_tag(mx, ty, str.tostring(heldRun) + " · " + str.tostring(pullDepth, "0.00") + " ATR", mc,
             dir == 1 ? label.style_label_up : label.style_label_down, f_size(markSize))
        label.set_tooltip(tg, tip)
        array.push(tagLabels, tg)
 
    // Break tag: grey, price on it, on the bar that closed through the far edge
    if brokeNow and showBreak
        float bky = f_mkLane(bar_index, dir == 1 ? low - 0.25 * atrS : high + 0.25 * atrS, 0.7 * atrS, dir == 1 ? -1 : 1)
        label bg  = f_tag(bar_index, bky, "break · " + f_px(close), cNeu, dir == 1 ? label.style_label_up : label.style_label_down, f_size(markSize))
        label.set_tooltip(bg, "Close through the " + (dir == 1 ? "slow edge below" : "slow edge above") + " · held run reset")
        array.push(tagLabels, bg)
 
    f_capLabels(tagLabels, maxLabels)
 
// Record totals
int recTot  = array.size(record)
int recHeld = 0
if recTot > 0
    for v in record
        recHeld += v
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 10. COLOUR + 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 in every style. Rules: plot() 1 with a const colour, 2 with a series
// colour; fill() 1 with a series colour; a gradient fill (series top/bottom values + series top/bottom colours) 4,
// the only rule that reproduces the 69 TradingView reported for v1.1; barcolor() 1; alertcondition() 1.
//   scale anchor plot(close), const colour (section 0) ............ 1 x 1 =  1
//   fill anchors aF, aS, const colour ............................. 2 x 1 =  2
//   glow edges gp1-gp4, const colour .............................. 4 x 1 =  4
//   glow layers 1-4, gradient fill ................................ 4 x 4 = 16
//   Clean body, gradient fill ..................................... 1 x 4 =  4
//   full-ribbon slots pf1-pf5, series colour ...................... 5 x 2 = 10
//   full-ribbon bands 1-6, series colour .......................... 6 x 1 =  6
//   slow line + fast line, series colour .......................... 2 x 2 =  4
//   barcolor (candle paint) ....................................... 1 x 1 =  1
//   alertcondition x 3 (section 14) ............................... 3 x 1 =  3
//   TOTAL ......................................................... 51 of 64 (v1.1 was 69: 6 glow layers = 30,
//   9 fan slots = 16 + 8 bands = 24). Keep it at 56 or fewer.
// Trend colour (slow line, body, glow, plate): bull role / bear role by the side of the fast line, fading through
// neutral while the edges are within 0.25 ATR of each other (around a crossing).
float sepN  = (maF - maS) / atrS
color tc    = f_grad(cBear, cNeu, cBull, 0.5 + 0.5 * math.max(-1.0, math.min(1.0, sepN / 0.25)))
 
// Full-ribbon colour: the separation sets the hue; a close on the wrong side of the fast line pulls it to neutral.
float dN    = math.max(-1.0, math.min(1.0, sepN / 0.5))
float posN  = (close - maF) / atrS
float pN    = math.max(-1.0, math.min(1.0, posN / 0.5))
bool  agree = dN * pN > 0
float tCol  = 0.5 + (agree ? 0.5 : 0.3) * dN
color ribCol = f_grad(cBear, cNeu, cBull, tCol)
 
// Strength from the held run (0 = base, heldFull = strongest).
float lum = math.min(1.0, heldRun / float(heldFull))
 
// f_bandT / f_lineT: Full-ribbon transparency ladders by slot fraction (0 fast edge, 1 slow edge), lifted by lum.
f_bandT(int i) =>
    float frac = math.min(1.0, i / float(lDen))
    int   t    = math.round(fillT + (96 - fillT) * frac * 0.9 - 26.0 * lum)
    f_t(math.min(99, math.max(0, t)))
f_lineT(int i) =>
    float frac = math.min(1.0, i / float(lDen))
    int   t    = math.round(8 + 62.0 * frac - 8.0 * lum)
    f_t(math.min(99, math.max(0, t)))
 
// Far-side glow. Edge transparency tEdge (at the slow line) is lifted by the held run and dimmed while the averages
// are out of order; layer boundary k of N sits k/N of the depth beyond the slow line, AWAY from price, and its
// opacity falls off as (1 - k/N)^1.7, so the light is densest at the line. Each layer is a gradient fill between
// two boundaries; the glow is na on the bar the edges cross so the fills never smear across the ribbon.
bool  glowOn = showGlow and dir != 0 and dir == nz(dir[1])
float gD     = glowDepth * atrS
int   tEdge  = math.max(15, math.min(95, math.round(glowT - 18.0 * lum + (aligned ? 0.0 : 10.0))))
 
f_glowT(int k) =>
    float f = math.min(1.0, k / float(glowLayers))
    int   t = math.round(100.0 - (100.0 - tEdge) * math.pow(1.0 - f, 1.7))
    f_t(math.min(100, math.max(0, t)))
f_gv(int k) =>
    glowOn and k <= glowLayers ? maS - dir * gD * k / glowLayers : na
// f_layer: [top value, bottom value, top colour, bottom colour] for glow layer k (inner boundary k-1, outer k).
f_layer(int k) =>
    float vIn  = f_gv(k - 1)
    float vOut = f_gv(k)
    color cIn  = color.new(tc, f_glowT(k - 1))
    color cOut = color.new(tc, f_glowT(k))
    float tv   = dir == 1 ? vIn : vOut
    float bv   = dir == 1 ? vOut : vIn
    color tcl  = dir == 1 ? cIn : cOut
    color bcl  = dir == 1 ? cOut : cIn
    [tv, bv, tcl, bcl]
 
color cHide = color.new(#000000, 100)
// Invisible fill anchors first (so every fill sits UNDER the visible lines declared last).
aF  = plot(maF, "Fast anchor", cHide, display = display.pane, editable = false)
aS  = plot(maS, "Slow anchor", cHide, display = display.pane, editable = false)
gp1 = plot(f_gv(1), "Glow edge 1", cHide, display = display.pane, editable = false)
gp2 = plot(f_gv(2), "Glow edge 2", cHide, display = display.pane, editable = false)
gp3 = plot(f_gv(3), "Glow edge 3", cHide, display = display.pane, editable = false)
gp4 = plot(f_gv(4), "Glow edge 4", cHide, display = display.pane, editable = false)
 
[g1t, g1b, g1tc, g1bc] = f_layer(1)
[g2t, g2b, g2tc, g2bc] = f_layer(2)
[g3t, g3b, g3tc, g3bc] = f_layer(3)
[g4t, g4b, g4tc, g4bc] = f_layer(4)
fill(aS,  gp1, g1t, g1b, g1tc, g1bc, title = "Glow layer 1")
fill(gp1, gp2, g2t, g2b, g2tc, g2bc, title = "Glow layer 2")
fill(gp2, gp3, g3t, g3b, g3tc, g3bc, title = "Glow layer 3")
fill(gp3, gp4, g4t, g4b, g4tc, g4bc, title = "Glow layer 4")
 
// Clean body: gradient between the edges, faint at the fast line, at the glow's edge strength at the slow line.
bool  bodyOn  = showFill and not isFull and dir != 0
color cBodyF  = color.new(tc, f_t(93))
color cBodyS  = color.new(tc, f_t(math.max(tEdge, 40)))
fill(aF, aS, bodyOn ? rTop : na, bodyOn ? rBot : na, dir == 1 ? cBodyF : cBodyS, dir == 1 ? cBodyS : cBodyF, title = "Ribbon body")
 
// Full ribbon: the fan. Slot 0 is the fast edge (anchor aF) and slot 6 is always the slow edge (anchor aS), so
// only the inner slots 1-5 need their own plots. When fewer lines are chosen, slot (lines - 1) equals the slow edge
// and stays invisible (the slow line draws it); slots past it are na, so their bands draw nothing.
f_fanV(int i, float v) =>
    isFull and i < lineCount ? v : na
f_fanC(int i) =>
    i >= lineCount - 1 ? cHide : color.new(ribCol, f_lineT(i))
pf1 = plot(f_fanV(1, ma1), "Ribbon 2", f_fanC(1), 1)
pf2 = plot(f_fanV(2, ma2), "Ribbon 3", f_fanC(2), 1)
pf3 = plot(f_fanV(3, ma3), "Ribbon 4", f_fanC(3), 1)
pf4 = plot(f_fanV(4, ma4), "Ribbon 5", f_fanC(4), 1)
pf5 = plot(f_fanV(5, ma5), "Ribbon 6", f_fanC(5), 1)
bool bandsOn = showFill and isFull
fill(aF,  pf1, color = bandsOn ? color.new(ribCol, f_bandT(0)) : na, title = "Band 1")
fill(pf1, pf2, color = bandsOn ? color.new(ribCol, f_bandT(1)) : na, title = "Band 2")
fill(pf2, pf3, color = bandsOn ? color.new(ribCol, f_bandT(2)) : na, title = "Band 3")
fill(pf3, pf4, color = bandsOn ? color.new(ribCol, f_bandT(3)) : na, title = "Band 4")
fill(pf4, pf5, color = bandsOn ? color.new(ribCol, f_bandT(4)) : na, title = "Band 5")
fill(pf5, aS,  color = bandsOn and lineCount == 7 ? color.new(ribCol, f_bandT(5)) : na, title = "Band 6")
 
// The two edges, last so they draw on top: slow line in the trend colour, fast line crisp.
color fastCol = fastMode == "Accent" ? cAcc : tc
plot(maS, "Slow line", color.new(tc, f_t(0)), slowW)
plot(maF, "Fast line", color.new(fastCol, f_t(0)), fastW)
 
// Candle paint: neutral inside the ribbon, full colour ~0.75 ATR beyond an edge (half-width floored at 0.25 ATR).
float ribMid     = (rTop + rBot) / 2.0
float ribHalf    = math.max((rTop - rBot) / 2.0, 0.25 * atrS)
float paintScore = 0.5 + 0.5 * math.max(-1.0, math.min(1.0, (close - ribMid) / (ribHalf + 0.75 * atrS)))
barcolor(f_candlePaint(paintMode, paintScore))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 11. NUMBERS FOR THE PLATE AND THE DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
float widthATR = (rTop - rBot) / atrS
float widthChg = widthATR - nz(widthATR[5], widthATR)
string widWord = math.abs(widthChg) < 0.03 ? "steady" : widthChg > 0 ? "widening" : "narrowing"
float distF    = (close - maF) / atrS                               // + above the fast line, - below
 
// Ribbon state words (direction of the edges + where the close sits), no direction call
string stateWord = dir == 0 ? "flat" :
     dir == 1  ? (close > maF ? "up" : close >= rBot ? "up · pullback" : "up · broken") :
                 (close < maF ? "down" : close <= rTop ? "down · pullback" : "down · broken")
string trendWord = dir == 1 ? "up" : dir == -1 ? "down" : "flat"
int    orderN    = dir == 1 ? upPairs : dir == -1 ? dnPairs : 0
 
string recTxt  = recTot > 0 ? str.tostring(recHeld) + " of " + str.tostring(recTot) : "0 of 0"
int    ageBars = na(flipBar) ? na : bar_index - flipBar
string ageTxt  = na(ageBars) ? "—" : str.tostring(ageBars) + (flipSeen ? "" : "+") + " bars"
string distTxt = math.abs(distF) < 0.05 ? "on the fast line" :
     str.tostring(math.abs(distF), "0.00") + " ATR " + (distF > 0 ? "above" : "below") + " fast"
bool   insideNow = dir != 0 and close <= rTop and close >= rBot
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 12. RIGHT-END PLATE (one label, moved every tick)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
var label plateLbl = na
if barstate.islast
    if showPlate
        string ptxt = "RIBBON · " + stateWord + " · width " + str.tostring(widthATR, "0.0") + " ATR · held " + recTxt
             + "\n" + widWord + " · age " + ageTxt + " · close " + distTxt
        float  py   = f_lane(maF, 0.8)
        int    px   = f_xr(f_xo(bar_index + plateOff))
        if na(plateLbl)
            plateLbl := f_plate(bar_index + plateOff, py, ptxt, tc, label.style_label_left, size.small)
        else
            label.set_xy(plateLbl, px, py)
            label.set_text(plateLbl, ptxt)
            label.set_color(plateLbl, tc)
            label.set_textcolor(plateLbl, f_ink(tc))
        label.set_tooltip(plateLbl, "Fast " + str.tostring(lenA) + " " + maType + " at " + f_px(maF) + " · slow " + str.tostring(lenB) + " " + maType
             + " at " + f_px(maS) + " · held run " + str.tostring(heldRun) + " · " + str.tostring(orderN) + " of " + str.tostring(lineCount - 1) + " pairs in order")
    else if not na(plateLbl)
        label.delete(plateLbl)
        plateLbl := na
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 13. DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
if showDash and barstate.islast
    f_dBegin()
    f_dHead("PULLBACK RIBBON")
 
    if not dashCompact
        string trendTxt = trendWord + " · " + (aligned ? "fully ordered" : str.tostring(orderN) + " of " + str.tostring(lineCount - 1) + " in order")
        f_dRow("Trend", trendTxt, dir == 0 ? cNeu : tc,
             "Direction of the ribbon: up while the fast average sits above the slow one, down while below. 'Fully ordered' means all "
             + str.tostring(lineCount) + " averages of the ribbon are stacked in sequence (fastest on the outside). Trend traders read a fully ordered ribbon as a clean, persistent trend, and a mixed order as a trend that is young, tangled or turning. Counted on every average even in the Clean style. On the chart: the slow line colour and the plate.")
 
        f_dRow("Ribbon width", str.tostring(widthATR, "0.00") + " ATR · " + widWord, cTxt,
             "Distance between the fast and the slow edge in ATR(14), and whether it is wider or narrower than 5 bars ago. A widening ribbon describes a trend that is gaining speed; a narrowing one describes the averages converging, which often comes before a pause or a crossing. Very wide = a stretched move, very narrow = a range. On the chart: the plate.")
 
    string heldTxt = recTot > 0 ? recTxt + " · " + str.tostring(100.0 * recHeld / recTot, "0") + "% · run " + str.tostring(heldRun) : "none yet"
    f_dRow("Held pullbacks", heldTxt, recTot > 0 ? tc : cNeu,
         "Of the last " + str.tostring(recLen) + " pullbacks into the ribbon, how many closed back on the trend side of the fast line without a close through the far edge, as a count and a share, plus the current run held in a row (it sets the glow strength). A high share describes a trend whose dips keep being absorbed; a falling share describes pullbacks that are starting to get through. A record of what happened, not a forecast. On the chart: the numbered dots and the plate.")
 
    if not dashCompact
        string lastTxt = inPull ? "open · " + str.tostring(pullDepth, "0.00") + " ATR · " + str.tostring(bar_index - pullStart) + " bars inside" :
             lastOutcome == 1  ? "held · " + str.tostring(lastDepth, "0.00") + " ATR · " + str.tostring(bar_index - lastBar) + " bars ago" :
             lastOutcome == -1 ? "broke · " + str.tostring(lastDepth, "0.00") + " ATR · " + str.tostring(bar_index - lastBar) + " bars ago" :
             "none yet"
        f_dRow("Last pullback", lastTxt, inPull ? cTxt : lastOutcome == 1 ? tc : cNeu,
             "The most recent pullback: how deep it reached below (above) the fast line in ATR at its deepest point, whether it held or broke, and how many bars ago it resolved. 'open' = one is in progress now. Shallow pullbacks (well under 1 ATR) are typical of strong trends; pullbacks that reach the slow edge show the trend being tested. On the chart: the depth tag under the last dot, or the break tag.")
 
        f_dRow("Close vs fast line", math.abs(distF) < 0.05 ? "on the line" : str.tostring(math.abs(distF), "0.00") + " ATR " + (distF > 0 ? "above" : "below"), cTxt,
             "How far the close sits from the fast average, in ATR(14). Far beyond it on the trend side = price is extended from its mean; near zero or on the other side = price is back at the ribbon, a pullback in progress. On the chart: plate line 2.")
 
        f_dRow("Ribbon age", ageTxt, cTxt,
             "Confirmed bars since the fast and slow averages last crossed. A young ribbon has little record behind it yet; an old one has a longer history of held or broken pullbacks. '+' means no crossing inside the loaded history, so the true age is longer. On the chart: plate line 2.")
 
    // Read line: clauses joined with "; ", a new line started whenever the current one would pass ~60 characters,
    // so the merged cell never widens the table (a single clause longer than that still keeps its own line).
    array<string> readParts = array.from(trendWord + " ribbon, " + ageTxt + " old, " + widWord,
         "close " + distTxt + (insideNow ? ", inside" : ""), recTot > 0 ? recTxt + " held" : "no pullbacks yet")
    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)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 14. ALERTS (events, not signals)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
alertcondition(heldNow,  "Pullback held",            "Pullback Ribbon: a pullback closed back on the trend side of the fast line")
alertcondition(brokeNow, "Far edge broken",          "Pullback Ribbon: the close went through the far edge, held run reset")
alertcondition(flipNow,  "Ribbon direction changed", "Pullback Ribbon: the fast and slow edges crossed")

← 返回列表