Trend Leg Maturity (ATR ZigZag)

a.b · study · 316 行 · 点赞 242 · TradingView 原页

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

Pine Script

//@version=6
// ─────────────────────────────────────────────────────────────────────────────
// Trend Leg Maturity
// Independently written. Uses only built-in Pine Script functions; no request.*() calls.
// Concepts acknowledged: ATR-based ZigZag (reversal-threshold) swing detection, percentile rank.
// All state is updated on confirmed bars only. Past legs never change once recorded.
// Descriptive context only: no prediction or advice.
// ─────────────────────────────────────────────────────────────────────────────
indicator("Trend Leg Maturity (ATR ZigZag)", shorttitle = "Trend Leg Maturity", overlay = true, max_lines_count = 100, max_boxes_count = 100, max_bars_back = 500)
 
// ═════════════════════════════ CONSTANTS ═════════════════════════════════════
const int   MAX_HIST_LINES = 6        // completed legs kept on the chart
const int   SCAN_LIMIT     = 400      // max bars scanned back when a new leg's extreme is located
const color PANEL_BG       = #151A24E6
const color PANEL_FRAME    = #FFFFFF40
const color TXT            = #E8ECF1
const color TXT_MUTED      = #9AA1AC
const color C_YOUNG        = #26A69A
const color C_MID          = #64B5F6
const color C_MATURE       = #FFA726
const color C_ALERT        = #EF5350
 
const string G_CORE = "Core Logic"
const string G_DISP = "Display"
 
// ═════════════════════════════ INPUTS ════════════════════════════════════════
revMult  = input.float(2.5, "Reversal threshold (× ATR)", minval = 1.0, maxval = 8.0, step = 0.1, group = G_CORE,
     tooltip = "A leg is confirmed over when a bar closes at least this many ATR back from the leg's peak. Lower = more, shorter legs. Higher = fewer, longer legs.")
atrLen   = input.int(14, "ATR length", minval = 1, maxval = 100, group = G_CORE)
histLegs = input.int(100, "Past legs kept per direction", minval = 20, maxval = 300, group = G_CORE,
     tooltip = "Most recent completed legs used for the percentile ranks.")
minLegs  = input.int(10, "Minimum past legs for percentiles", minval = 5, maxval = 100, group = G_CORE,
     tooltip = "Below this number of past legs in the current direction, only raw Age and Stretch are shown.")
 
showLegs  = input.bool(true, "Draw legs", group = G_DISP)
showEnd   = input.bool(true, "Draw \"leg ends\" zone", group = G_DISP,
     tooltip = "Translucent zone from the leg's peak to the close level that would confirm the leg over. It moves with each new peak and with ATR.")
showPanel = input.bool(true, "Show panel", group = G_DISP)
panelPos  = input.string("Top Right", "Panel position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right"], group = G_DISP)
panelSize = input.string("Small", "Panel text size", options = ["Tiny", "Small", "Normal"], group = G_DISP)
 
// ═════════════════════════════ STATE ═════════════════════════════════════════
float atrNow = ta.atr(atrLen)
 
// Current leg. legDir: 1 up, -1 down, 0 not started. legReady turns true after the first confirmed reversal;
// the first partial leg is never recorded or drawn.
var int   legDir   = 0
var float startP   = na
var int   startB   = na
var float extP     = na
var int   extB     = na
var bool  legReady = false
 
// Completed legs per direction: size in ATR (at confirmation) and lifetime in bars (pivot to confirmation bar).
var array<float> upExt = array.new<float>()
var array<float> upDur = array.new<float>()
var array<float> dnExt = array.new<float>()
var array<float> dnDur = array.new<float>()
 
var line curLine = na
var box  zone    = na
var array<line> histLines = array.new<line>()
var int lastCls = -1
 
// ═════════════════════════════ HELPERS ═══════════════════════════════════════
f_pos(string s) =>
    switch s
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        "Middle Right" => position.middle_right
        => position.top_right
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
var table tbl = showPanel ? table.new(f_pos(panelPos), 2, 4, bgcolor = PANEL_BG, frame_color = PANEL_FRAME, frame_width = 2, border_width = 0) : na
string txtSize = f_size(panelSize)
 
f_cell(int c, int r, string t, color tc, string tip) =>
    table.cell(tbl, c, r, t, text_color = tc, text_halign = text.align_left, text_size = txtSize, bgcolor = PANEL_BG, tooltip = tip)
    true
 
// Ten-circle meter, e.g. ●●●●●●○○○○ (value 0-100, rounded to the nearest tenth).
f_bar(float pct) =>
    int filled = math.round(math.max(0.0, math.min(100.0, pct)) / 10.0)
    string s = ""
    for i = 1 to 10
        s := s + (i <= filled ? "●" : "○")
    s
 
// Price distance in units a trader recognises: pips on forex, points (+ %) elsewhere.
f_dist(float d) =>
    float a = math.abs(d)
    string s = ""
    if syminfo.type == "forex"
        s := str.tostring(a / (syminfo.mintick * 10.0), "0.0") + " pips"
    else
        s := str.tostring(a, format.mintick)
        if close > 0
            s := s + " (" + str.tostring(a / close * 100.0, "0.00") + "%)"
    s
 
// Append a finished leg value, keeping the most recent histLegs.
f_push(array<float> a, float v) =>
    array.push(a, v)
    if array.size(a) > histLegs
        array.shift(a)
    true
 
// Percentile rank (0-100) of v among stored values: share smaller than v, ties count half.
f_pct(array<float> a, float v) =>
    int n = array.size(a)
    float res = na
    if n > 0
        float cnt = 0.0
        for i = 0 to n - 1
            float x = array.get(a, i)
            if x < v
                cnt += 1.0
            else if x == v
                cnt += 0.5
        res := cnt / n * 100.0
    res
 
f_class(float score) =>
    score < 33.3 ? 0 : (score > 66.7 ? 2 : 1)
 
f_cname(int c) =>
    c == 0 ? "YOUNG" : (c == 1 ? "MID-LIFE" : "MATURE")
 
f_clsCol(int c) =>
    c == 0 ? C_YOUNG : (c == 1 ? C_MID : (c == 2 ? C_MATURE : TXT_MUTED))
 
// Highest high (wantHigh) or lowest low since fromBar (inclusive), searching at most SCAN_LIMIT bars back.
f_scan(bool wantHigh, int fromBar) =>
    int n = math.min(bar_index - fromBar, SCAN_LIMIT)
    float v = wantHigh ? high : low
    int b = bar_index
    for k = 0 to n
        float x = wantHigh ? high[k] : low[k]
        if (wantHigh and x > v) or ((not wantHigh) and x < v)
            v := x
            b := bar_index - k
    [v, b]
 
// Metrics of the current leg: [age bars, stretch ATR, age pct, stretch pct, maturity score, class (-1 none), past legs].
f_metrics() =>
    int   A   = na
    float E   = na
    float ap  = na
    float ep  = na
    float sc  = na
    int   cls = -1
    int   nH  = 0
    if legDir != 0 and legReady and not na(atrNow) and atrNow > 0 and not na(startB)
        A := bar_index - startB
        E := math.abs(extP - startP) / atrNow
        array<float> dA = legDir == 1 ? upDur : dnDur
        array<float> eA = legDir == 1 ? upExt : dnExt
        nH := array.size(dA)
        if nH >= minLegs
            ap := f_pct(dA, A * 1.0)
            ep := f_pct(eA, E)
            sc := (ap + ep) / 2.0
            cls := f_class(sc)
    [A, E, ap, ep, sc, cls, nH]
 
// ═════════════════════════════ LEG ENGINE (confirmed bars only) ══════════════
bool legEndUp     = false     // an up leg was confirmed over on this bar
bool legEndDn     = false     // a down leg was confirmed over on this bar
bool becameMature = false     // the current leg's class changed to MATURE on this bar
 
if barstate.isconfirmed and not na(atrNow) and atrNow > 0
    float pvP      = na
    int   pvB      = na
    bool  reversed = false
 
    if legDir == 0
        legDir := 1
        startP := low
        startB := bar_index
        extP   := high
        extB   := bar_index
    else if legDir == 1
        if high > extP
            extP := high
            extB := bar_index
        if close <= extP - revMult * atrNow
            if legReady
                f_push(upExt, (extP - startP) / atrNow)
                f_push(upDur, bar_index - startB)
            pvP := extP
            pvB := extB
            startP := extP
            startB := extB
            [vL, bL] = f_scan(false, pvB)
            legDir := -1
            extP := vL
            extB := bL
            legReady := true
            reversed := true
            legEndUp := true
    else
        if low < extP
            extP := low
            extB := bar_index
        if close >= extP + revMult * atrNow
            if legReady
                f_push(dnExt, (startP - extP) / atrNow)
                f_push(dnDur, bar_index - startB)
            pvP := extP
            pvB := extB
            startP := extP
            startB := extB
            [vH, bH] = f_scan(true, pvB)
            legDir := 1
            extP := vH
            extB := bH
            legReady := true
            reversed := true
            legEndDn := true
 
    if reversed
        lastCls := -1
 
    [A0, E0, ap0, ep0, sc0, cls0, nH0] = f_metrics()
    becameMature := cls0 == 2 and lastCls != 2
    lastCls := cls0
 
    // ── Drawing ──
    if showLegs and legReady
        color lc = f_clsCol(cls0)
        float lvl0 = legDir == 1 ? extP - revMult * atrNow : extP + revMult * atrNow
        if reversed
            if not na(curLine)
                line.set_xy2(curLine, pvB, pvP)
                line.set_color(curLine, color.new(TXT_MUTED, 55))
                line.set_width(curLine, 1)
                array.push(histLines, curLine)
                if array.size(histLines) > MAX_HIST_LINES
                    line.delete(array.shift(histLines))
            if not na(zone)
                box.delete(zone)
            curLine := line.new(startB, startP, extB, extP, color = lc, width = 2)
            zone := showEnd ? box.new(extB, math.max(extP, lvl0), bar_index, math.min(extP, lvl0), border_color = color.new(lc, 35), border_style = line.style_dashed, border_width = 1, bgcolor = color.new(lc, 90)) : na
        else if not na(curLine)
            line.set_xy1(curLine, startB, startP)
            line.set_xy2(curLine, extB, extP)
            line.set_color(curLine, lc)
            if showEnd and not na(zone)
                box.set_lefttop(zone, extB, math.max(extP, lvl0))
                box.set_rightbottom(zone, bar_index, math.min(extP, lvl0))
                box.set_border_color(zone, color.new(lc, 35))
                box.set_bgcolor(zone, color.new(lc, 90))
 
// ═════════════════════════════ PANEL ═════════════════════════════════════════
if showPanel and barstate.islast
    [A, E, ap, ep, sc, cls, nH] = f_metrics()
    color cc = f_clsCol(cls)
 
    // ── Row 0: title + maturity ──
    string head = "Finding first leg…"
    if legDir != 0 and legReady
        head := (legDir == 1 ? "▲ Up leg" : "▼ Down leg") + (cls >= 0 ? " · " + f_cname(cls) : " · building history (" + str.tostring(nH) + "/" + str.tostring(minLegs) + " legs)")
    table.set_frame_color(tbl, cls >= 0 ? cc : PANEL_FRAME)
 
    string typTxt = "n/a"
    if legDir != 0 and legReady and nH > 0
        array<float> dM = legDir == 1 ? upDur : dnDur
        array<float> eM = legDir == 1 ? upExt : dnExt
        typTxt := str.tostring(array.median(eM), "0.0") + " ATR over " + str.tostring(array.median(dM), "0") + " bars"
 
    f_cell(0, 0, "TREND LEG MATURITY", TXT, "Ranks the current price leg against completed legs on this chart, by age and by size in ATR. Descriptive context only, not advice or a forecast.")
    f_cell(1, 0, head, cc, "Maturity = average of the age and stretch percentiles: below 33 YOUNG, above 67 MATURE, otherwise MID-LIFE. A description of where this leg ranks among past legs, not a probability or a signal. Typical past leg in this direction (median): " + typTxt + ".")
 
    // ── Row 1: age ──
    string ageTxt = "—"
    if not na(A)
        ageTxt := str.tostring(A) + " bars"
        if not na(ap)
            ageTxt := f_bar(ap) + "  " + str.tostring(A) + " bars · older than " + str.tostring(math.min(99.0, math.round(ap))) + "% of past legs"
    f_cell(0, 1, "Age", TXT_MUTED, "Bars from the leg's start pivot to the current bar. Past legs are measured from their pivot to the bar that confirmed them over.")
    f_cell(1, 1, ageTxt, TXT, "Percentile among up to " + str.tostring(histLegs) + " past legs in the same direction (ties count half). The meter shows it rounded to the nearest tenth (each filled circle is about 10%). Needs at least " + str.tostring(minLegs) + " past legs.")
 
    // ── Row 2: stretch ──
    string strTxt = "—"
    if not na(E)
        strTxt := str.tostring(E, "0.0") + " ATR"
        if not na(ep)
            strTxt := f_bar(ep) + "  " + str.tostring(E, "0.0") + " ATR · bigger than " + str.tostring(math.min(99.0, math.round(ep))) + "% of past legs"
    f_cell(0, 2, "Stretch", TXT_MUTED, "Distance from the leg's start pivot to its current peak, in current ATR.")
    f_cell(1, 2, strTxt, TXT, "Percentile among up to " + str.tostring(histLegs) + " past legs in the same direction (ties count half). Past legs use their size in ATR at confirmation.")
 
    // ── Row 3: leg ends (visual pullback meter + level) ──
    string endTxt = "—"
    string endTip = "Legs are confirmed on bar close only."
    color  endCol = TXT
    if legDir != 0 and legReady and not na(atrNow) and atrNow > 0
        float lvl  = legDir == 1 ? extP - revMult * atrNow : extP + revMult * atrNow
        float away = legDir == 1 ? close - lvl : lvl - close
        float pull = math.max(0.0, legDir == 1 ? (extP - close) / atrNow : (close - extP) / atrNow)
        float frac = math.min(1.0, pull / revMult)
        endTxt := f_bar(frac * 100.0) + "  " + (legDir == 1 ? "↓ " : "↑ ") + str.tostring(lvl, format.mintick)
        endCol := frac >= 0.8 ? C_ALERT : (frac >= 0.5 ? C_MATURE : TXT)
        endTip := "Meter = how much of the reversal threshold price has pulled back from the peak (" + str.tostring(pull, "0.0") + " of " + str.tostring(revMult, "0.0") + " ATR). The leg is confirmed over on a close " + (legDir == 1 ? "below " : "above ") + str.tostring(lvl, format.mintick) + (away > 0 ? " (" + f_dist(away) + " away)" : " (level reached; confirms if the bar closes there)") + ". Amber from 50%, red from 80%. A reference level, not a recommendation. Uses the live close until the bar closes."
    f_cell(0, 3, "Leg ends", TXT_MUTED, "How close price is to the close level that would confirm this leg over: peak ∓ threshold × current ATR. It moves with each new peak and with ATR.")
    f_cell(1, 3, endTxt, endCol, endTip)
 
// ═════════════════════════════ ALERTS (bar close) ════════════════════════════
alertcondition(legEndUp, "Up leg confirmed over", "Trend Leg Maturity: the up leg on {{ticker}} ({{interval}}) was confirmed over; a down leg starts.")
alertcondition(legEndDn, "Down leg confirmed over", "Trend Leg Maturity: the down leg on {{ticker}} ({{interval}}) was confirmed over; an up leg starts.")
alertcondition(becameMature, "Leg became MATURE", "Trend Leg Maturity: the current leg on {{ticker}} ({{interval}}) is now MATURE versus past legs on this chart.")

← 返回列表