Machine Learning Elliott Wave [FEELS]

FeelsStrategy · study · 735 行 · 点赞 382 · TradingView 原页

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

Pine Script

//@version=6
// Machine Learning Elliott Wave [FEELS]
// Version 1.0 — 2026-11-18
//
// Counts the Elliott wave in play and projects where the running wave usually stops on this chart.
//
// Swings come from seven zigzags at once (1.5 to 6 ATR by default). A swing ends when price moves
// against it by that many ATRs. On every zigzag the script looks at the last swing points for a count
// in play, checked against the wave rules:
//   0-1        a readable wave 1, price still beyond point 0                -> wave 2 running
//   0-1-2      wave 2 retraced 0.382-0.786 of wave 1, price still beyond point 0 -> wave 3 running
//   0-1-2-3    and wave 3 went past wave 1 and is at least as long             -> wave 4 running
//   0-1-2-3-4  and wave 4 retraced 0.236-0.618 of wave 3 and stayed beyond 2   -> wave 5 running
// Each wave must last a few bars, and the count must be wide enough to read. The biggest zigzag
// with a count in play wins; a bare 0-1 is used only when no zigzag has a count past wave 2.
//
// Every zigzag also remembers its own past swings in the same roles (skipping any with two swing points on one candle):
//   wave-3-like: a leg after a 0.382-0.786 pullback that went past the end of the leg before it.
//                Answer: how far it ran from the pullback, in units of the leg before (log scale).
//   wave-4-like: a pullback after a leg that made a new extreme. Answer: its depth as a share of that leg.
//   wave-2-like: any pullback (with or without a new extreme before it). Same answer.
// Waves 2 and 4 use the 9 most similar past pullbacks (leg size in ATR, leg length in bars, leg against the
// leg before). Wave 3 uses all past wave-3-like legs: similarity added nothing there in testing.
// Wave 5 has too few past examples, so it shows the book level (1.0 x wave 1 from point 4).
//
// The projection starts from where price is now. Levels the running wave already reached are ticked.
// For the levels ahead it counts only the similar swings that got at least as far as price has, and
// says how many of them went on to each level. The target is the level where most of them stopped.
// The band is where the middle half of them stopped.
// On the chart: the next stop and the other levels ahead with their share (rounded to 10%, ~ when fewer
// than 10 swings), and the book path to wave 5. The legend says why, in words.
// The similar past swings behind the share are drawn where they happened: scroll back to see them.
//
// Nothing here is a forecast. In testing, these swings behave the same on shuffled price data, so this
// is a map of how far similar swings went on this chart, not an edge. Swings are decided on closed bars.
 
indicator("Machine Learning Elliott Wave [FEELS]", "ML Elliott Wave [FEELS]", overlay = true,
     max_lines_count = 300, max_labels_count = 400, max_polylines_count = 10, max_boxes_count = 50, max_bars_back = 5000)
 
// ─────────────────────────────────────────────────────────────── inputs ────
grpS = "Swings"
sizeStr = input.string("1.5, 2, 2.5, 3, 4, 5, 6", "Zigzag sizes, × ATR", group = grpS,
     tooltip = "A swing ends after a move against it of this many ATRs. Every size is counted; the biggest one with a count in play is shown.")
atrLen  = input.int(14, "ATR length", minval = 1, maxval = 200, group = grpS,
     tooltip = "The ATR the zigzag sizes are measured in.")
minW    = input.int(4, "Shortest wave, bars", minval = 1, maxval = 50, group = grpS,
     tooltip = "Waves shorter than this are not counted, so the count stays readable.")
minSpan = input.int(40, "Shortest full count 0-5, bars", minval = 5, maxval = 500, group = grpS,
     tooltip = "A count must be at least this wide (scaled down for counts still at wave 3 or 4).")
 
grpM = "Model"
knn     = input.int(9, "Similar pullbacks it learns from (waves 2 and 4)", minval = 3, maxval = 30, group = grpM,
     tooltip = "How many past pullbacks closest to this one (size in ATR, length in bars, size against the leg before) the share is counted from. Wave 3 uses all past wave-3-like legs.")
minHist = input.int(5, "Past swings it needs before it projects", minval = 3, maxval = 100, group = grpM,
     tooltip = "With fewer past swings in this role, no next stop is drawn.")
maxHist = input.int(300, "Past swings it remembers, per zigzag and role", minval = 20, maxval = 1000, group = grpM,
     tooltip = "Older swings are forgotten past this number.")
 
grpL = "Look"
colCnt  = input.color(#139C8A, "Count", inline = "c", group = grpL)
colMod  = input.color(#7B5CD6, "Projection", inline = "c", group = grpL)
colInv  = input.color(#D2557A, "Invalid", inline = "c", group = grpL,
     tooltip = "Count: the waves and their numbers. Projection: the next stop, the levels ahead and the path to wave 5. Invalid: the line that kills the count and the ✕.")
showNx  = input.bool(true, "Show the path to wave 5", group = grpL,
     tooltip = "Book proportions after the projected stop: wave 3 = 1.618 x wave 1, wave 4 = 0.382 of wave 3, wave 5 = 1.0 x wave 1.")
showLg  = input.bool(true, "Show the legend", group = grpL,
     tooltip = "Which wave, the next stop, why, and where the count is wrong, in words.")
lgPos   = input.string("Top right", "Legend position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = grpL,
     tooltip = "Where on the chart the legend sits.")
showTk  = input.bool(true, "Tick the levels already reached", group = grpL,
     tooltip = "Levels the running wave already passed get a ✓ with their price instead of a share.")
showHs  = input.bool(true, "Draw the similar past swings", group = grpL,
     tooltip = "The past swings the share is counted from, drawn where they happened, each with how far it went. Scroll back to see them.")
full5   = input.bool(false, "Past swings: wave 5 only past wave 3", group = grpL,
     tooltip = "On: a past swing's wave 5 is drawn only when it went past the end of its wave 3. Off: the swing after a valid wave 4 is drawn as 5 either way.")
txtSize = input.string("Normal", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = grpL,
     tooltip = "Size of the numbers, levels and legend.")
 
// ─────────────────────────────────────────────────────────────── helpers ───
txtSz(s) =>
    s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : s == "Large" ? size.large : size.small
// the past swings stay a step smaller than the count in play
txtSzH(s) =>
    s == "Large" ? size.normal : s == "Normal" ? size.small : size.tiny
fmtP(p) =>
    str.tostring(p, format.mintick)
fmtR(r) =>
    str.tostring(r)
// a share rounded to 10%, with ~ when it rests on fewer than 10 swings
pctS(int a, int b) =>
    (b < 10 ? "~" : "") + str.tostring(math.round(10.0 * a / b) * 10) + "%"
pctV(int a, int b) =>
    math.round(10.0 * a / b) * 10
lvP(float base, float sg, float unit, float r) =>
    math.exp(math.log(base) + sg * r * unit)
 
type ZZ
    float k
    int   dir  = 0
    float ext  = na
    int   extB = na
    float extA = na
    array<int>   pb
    array<float> pp
    array<float> pa
    array<float> s3a
    array<float> s3b
    array<float> s3c
    array<float> s3e
    array<float> s4a
    array<float> s4b
    array<float> s4c
    array<float> s4e
    array<float> s2a
    array<float> s2b
    array<float> s2c
    array<float> s2e
    array<int>   hB
    array<float> hP
    int          hN = 0
    array<int>   gi3
    array<int>   gi2
    array<int>   gi4
 
newZZ(float k) =>
    ZZ.new(k = k, pb = array.new<int>(), pp = array.new<float>(), pa = array.new<float>(),
         s3a = array.new<float>(), s3b = array.new<float>(), s3c = array.new<float>(), s3e = array.new<float>(),
         s4a = array.new<float>(), s4b = array.new<float>(), s4c = array.new<float>(), s4e = array.new<float>(),
         s2a = array.new<float>(), s2b = array.new<float>(), s2c = array.new<float>(), s2e = array.new<float>(),
         hB = array.new<int>(), hP = array.new<float>(), gi3 = array.new<int>(), gi2 = array.new<int>(), gi4 = array.new<int>())
 
// every swing point the zigzag ever confirmed (the last 3000), so a remembered swing can be drawn with what came after it
method hist(ZZ z, int x, float y) =>
    z.hB.push(x)
    z.hP.push(y)
    z.hN := z.hN + 1
    if z.hB.size() > 3000
        z.hB.shift()
        z.hP.shift()
 
// one closed bar of the zigzag; true when a new swing point was confirmed
method step(ZZ z, float a) =>
    bool np = false
    if z.dir == 0
        z.dir  := 1
        z.ext  := high
        z.extB := bar_index
        z.extA := a
        z.pb.push(bar_index)
        z.pp.push(low)
        z.hist(bar_index, low)
        z.pa.push(a)
    else if z.dir == 1
        if high > z.ext
            z.ext  := high
            z.extB := bar_index
            z.extA := a
        if z.ext - low >= z.k * a
            z.pb.push(z.extB)
            z.pp.push(z.ext)
            z.hist(z.extB, z.ext)
            z.pa.push(z.extA)
            z.dir  := -1
            z.ext  := low
            z.extB := bar_index
            z.extA := a
            np := true
    else
        if low < z.ext
            z.ext  := low
            z.extB := bar_index
            z.extA := a
        if high - z.ext >= z.k * a
            z.pb.push(z.extB)
            z.pp.push(z.ext)
            z.hist(z.extB, z.ext)
            z.pa.push(z.extA)
            z.dir  := 1
            z.ext  := high
            z.extB := bar_index
            z.extA := a
            np := true
    np
 
pushCap(array<float> arr, float v, int cap) =>
    arr.push(v)
    if arr.size() > cap
        arr.shift()
 
// where each remembered swing happened: the place of its first point in the zigzag's history, kept in step with the answers
pushCapI(array<int> arr, int v, int cap) =>
    arr.push(v)
    if arr.size() > cap
        arr.shift()
 
// a newly confirmed point D settles the swings before it: remember wave-3-like and wave-4-like answers
method learn(ZZ z) =>
    n = z.pp.size()
    if n >= 4
        a  = z.pp.get(n - 4)
        b  = z.pp.get(n - 3)
        c  = z.pp.get(n - 2)
        d  = z.pp.get(n - 1)
        ba = z.pb.get(n - 4)
        bb = z.pb.get(n - 3)
        bc = z.pb.get(n - 2)
        if a > 0 and b > 0 and c > 0 and d > 0
            L1 = math.abs(math.log(b) - math.log(a))
            L2 = math.abs(math.log(c) - math.log(b))
            if L1 > 0
                pb = L2 / L1
                up = b > a
                passed = up ? d > b : d < b
                // two swing points on one candle can't be read (which came first?), so such swings are skipped
                if pb >= 0.382 and pb <= 0.786 and passed and bb > ba and bc > bb
                    pushCap(z.s3a, math.abs(b - a) / z.pa.get(n - 3), maxHist)
                    pushCap(z.s3b, float(bb - ba), maxHist)
                    pushCap(z.s3c, pb, maxHist)
                    pushCap(z.s3e, math.abs(math.log(d) - math.log(c)) / L1, maxHist)
                    pushCapI(z.gi3, z.hN - 4, maxHist)
                newX = c > b ? c > math.max(a, b) : c < math.min(a, b)
                if L2 > 0 and not newX and bc > bb
                    pushCap(z.s2a, math.abs(c - b) / z.pa.get(n - 2), maxHist)
                    pushCap(z.s2b, float(bc - bb), maxHist)
                    pushCap(z.s2c, L2 / L1, maxHist)
                    pushCap(z.s2e, math.abs(math.log(c) - math.log(d)) / L2, maxHist)
                    pushCapI(z.gi2, z.hN - 3, maxHist)
                if L2 > 0 and newX and bc > bb
                    pushCap(z.s4a, math.abs(c - b) / z.pa.get(n - 2), maxHist)
                    pushCap(z.s4b, float(bc - bb), maxHist)
                    pushCap(z.s4c, L2 / L1, maxHist)
                    pushCap(z.s4e, math.abs(math.log(c) - math.log(d)) / L2, maxHist)
                    pushCapI(z.gi4, z.hN - 3, maxHist)
    if n > 10
        z.pb.shift()
        z.pp.shift()
        z.pa.shift()
 
// is the last n swing points (n = 3, 4, 5) a valid, readable count still in play at price px?
method inPlay(ZZ z, int n, float px) =>
    m = z.pp.size() - n
    bool ok = m >= (n == 2 ? 1 : 0)
    if ok and n == 2
        p0 = z.pp.get(m)
        p1 = z.pp.get(m + 1)
        s  = p1 > p0 ? 1.0 : -1.0
        ok := p0 > 0 and p1 > 0 and z.pp.get(m - 1) > 0 and p1 != p0
        ok := ok and z.pb.get(m + 1) - z.pb.get(m) >= math.max(minW, int(minSpan / 5))
        ok := ok and s * (px - p0) > 0
    else if ok
        p0 = z.pp.get(m)
        p1 = z.pp.get(m + 1)
        s  = p1 > p0 ? 1.0 : -1.0
        q0 = s * p0
        q1 = s * p1
        q2 = s * z.pp.get(m + 2)
        L1 = q1 - q0
        ok := L1 > 0
        if ok
            r2 = (q1 - q2) / L1
            ok := r2 >= 0.382 and r2 <= 0.786
        if ok and n >= 4
            q3 = s * z.pp.get(m + 3)
            ok := q3 - q2 >= L1
            if ok and n >= 5
                q4 = s * z.pp.get(m + 4)
                L3 = q3 - q2
                r4 = (q3 - q4) / L3
                ok := r4 >= 0.236 and r4 <= 0.618 and q4 > q2
        // readable: every wave lasts minW bars, the count is wide enough
        if ok
            for j = m to m + n - 2
                if z.pb.get(j + 1) - z.pb.get(j) < minW
                    ok := false
            if z.pb.get(m + n - 1) - z.pb.get(m) < int(minSpan * (n - 1) / 5)
                ok := false
        // still in play: price has not crossed the level that breaks the count
        if ok
            lim = n == 3 ? z.pp.get(m) : n == 4 ? z.pp.get(m + 2) : z.pp.get(m + 4)
            ok := s * (px - lim) > 0
    ok
 
// ─────────────────────────────────────────────────────────────── engine ────
var array<ZZ> zs = array.new<ZZ>()
if barstate.isfirst
    for part in str.split(sizeStr, ",")
        v = str.tonumber(str.trim(part))
        if not na(v) and v > 0
            zs.push(newZZ(v))
 
atrV = ta.atr(atrLen)
if barstate.isconfirmed and not na(atrV)
    for z in zs
        if z.step(atrV)
            z.learn()
 
// ─────────────────────────────────────────────────────────────── drawing ───
var array<line>     dL = array.new<line>()
var array<label>    dB = array.new<label>()
var array<polyline> dP = array.new<polyline>()
var array<box>      dX = array.new<box>()
 
clearAll() =>
    for x in dL
        x.delete()
    for x in dB
        x.delete()
    for x in dP
        x.delete()
    for x in dX
        x.delete()
    dL.clear()
    dB.clear()
    dP.clear()
    dX.clear()
 
addL(int x1, float y1, int x2, float y2, color c, int w, string st) =>
    dL.push(line.new(x1, y1, x2, y2, color = c, width = w, style = st))
 
addT(int x, float y, string t, color c, string st, string tip = "") =>
    dB.push(label.new(x, y, t, color = color.new(c, 100), textcolor = c, style = st, size = txtSz(txtSize), tooltip = tip, textalign = text.align_left))
 
var table lg = table.new(lgPos == "Top right" ? position.top_right : lgPos == "Bottom right" ? position.bottom_right : lgPos == "Top left" ? position.top_left : position.bottom_left, 1, 6)
lgRow(int r, string t, color c, bool big) =>
    if showLg and t != ""
        lg.cell(0, r, t, text_color = c, text_size = big ? txtSz(txtSize) : txtSize == "Large" ? size.normal : size.small, text_halign = text.align_right)
lgSet(string a, color ca, string b, color cb, string c1, string c2, string d, color cd, string e) =>
    lg.clear(0, 0, 0, 5)
    lgRow(0, a, ca, true)
    lgRow(1, b, cb, true)
    lgRow(2, c1, color.new(#6B7480, 0), false)
    lgRow(3, c2, color.new(#6B7480, 0), false)
    lgRow(4, d, cd, false)
    lgRow(5, e, color.new(#9AA3AE, 0), false)
 
if barstate.islast
    clearAll()
    // biggest zigzag with a count in play
    int sel = -1
    int nSel = 0
    nz = zs.size()
    if nz > 0
        ordK = array.new<float>()
        for z in zs
            ordK.push(z.k)
        idxK = ordK.sort_indices(order.descending)
        for pass = 0 to 1
            for ii = 0 to nz - 1
                zi = idxK.get(ii)
                z = zs.get(zi)
                for n in (pass == 0 ? array.from(5, 4, 3) : array.from(2))
                    if sel < 0 and z.inPlay(n, close)
                        sel  := zi
                        nSel := n
    if sel < 0
        lgSet("No Elliott count in play", color.gray, "Waiting for a clean 0-1-2", color.gray, "", "", "", color.gray, "")
    else
        z = zs.get(sel)
        n = nSel
        m = z.pp.size() - n
        p0 = z.pp.get(m)
        p1 = z.pp.get(m + 1)
        b0 = z.pb.get(m)
        b1 = z.pb.get(m + 1)
        up = p1 > p0
        s  = up ? 1.0 : -1.0
        wave = n
        // the count so far
        for j = 0 to n - 1
            bj = z.pb.get(m + j)
            pj = z.pp.get(m + j)
            if j < n - 1
                addL(bj, pj, z.pb.get(m + j + 1), z.pp.get(m + j + 1), colCnt, 3, line.style_solid)
            top = (j % 2 == 1) == up
            dB.push(label.new(bj, pj, str.tostring(j), color = colCnt, textcolor = color.white, style = top ? label.style_label_down : label.style_label_up, size = txtSz(txtSize)))
        lastB = z.pb.get(m + n - 1)
        lastP = z.pp.get(m + n - 1)
        addL(lastB, lastP, bar_index, close, colCnt, 3, line.style_solid)
        // invalid level
        inv = n <= 3 ? p0 : n == 4 ? z.pp.get(m + 2) : z.pp.get(m + 4)
        dur = math.min(math.max(8, b1 - b0), 150)   // labels can't sit more than 500 bars ahead
        x1  = bar_index + int(dur / 2) + 4
        xT  = x1 + 3
        xE  = xT + dur + 20
        addL(b0, inv, xE, inv, colInv, 1, line.style_dotted)
        invLn = dL.last()
        bool invTxt = true
        wDir = wave % 2 == 1 ? s : -s
        hdr = "Wave " + str.tostring(wave) + (wDir > 0 ? " up" : " down")
        wrong = "Wrong if " + (up ? "below " : "above ") + fmtP(inv)
        L1 = math.abs(math.log(p1) - math.log(p0))
        float base = na
        float unit = na
        float sg = na
        array<float> lv = array.new<float>()
        array<float> pool = array.new<float>()
        array<int>   poolR = array.new<int>()   // which role each swing in the pool came from
        array<int>   poolI = array.new<int>()   // and its place in that role's memory
        bool book = false
        if wave == 2
            pP = z.pp.get(m - 1)
            base := p1
            unit := L1
            sg   := -s
            lv   := array.from(0.236, 0.382, 0.5, 0.618, 0.786, 0.886)
            cnt2 = z.s2e.size()
            cnt4 = z.s4e.size()
            cnt  = cnt2 + cnt4
            if cnt >= minHist
                f1 = math.abs(p1 - p0) / z.pa.get(m + 1)
                f2 = float(b1 - b0)
                f3 = L1 / math.abs(math.log(p0) - math.log(pP))
                fa = array.new<float>()
                fb = array.new<float>()
                fc = array.new<float>()
                fe = array.new<float>()
                fa.concat(z.s2a)
                fa.concat(z.s4a)
                fb.concat(z.s2b)
                fb.concat(z.s4b)
                fc.concat(z.s2c)
                fc.concat(z.s4c)
                fe.concat(z.s2e)
                fe.concat(z.s4e)
                sd1 = fa.stdev()
                sd2 = fb.stdev()
                sd3 = fc.stdev()
                sd1 := sd1 > 0 ? sd1 : 1.0
                sd2 := sd2 > 0 ? sd2 : 1.0
                sd3 := sd3 > 0 ? sd3 : 1.0
                dist = array.new<float>()
                for i = 0 to cnt - 1
                    a1 = (fa.get(i) - f1) / sd1
                    a2 = (fb.get(i) - f2) / sd2
                    a3 = (fc.get(i) - f3) / sd3
                    dist.push(a1 * a1 + a2 * a2 + a3 * a3)
                ord = dist.sort_indices(order.ascending)
                for j = 0 to math.min(knn, cnt) - 1
                    oj = ord.get(j)
                    pool.push(fe.get(oj))
                    poolR.push(oj < cnt2 ? 2 : 4)
                    poolI.push(oj < cnt2 ? oj : oj - cnt2)
        else if wave == 3
            base := z.pp.get(m + 2)
            unit := L1
            sg   := s
            lv   := array.from(1.0, 1.272, 1.618, 2.0, 2.618)
            if z.s3e.size() >= minHist
                pool := z.s3e.copy()
                for j = 0 to pool.size() - 1
                    poolR.push(3)
                    poolI.push(j)
        else if wave == 4
            p2 = z.pp.get(m + 2)
            p3 = z.pp.get(m + 3)
            L3 = math.abs(math.log(p3) - math.log(p2))
            base := p3
            unit := L3
            sg   := -s
            lv   := array.from(0.236, 0.382, 0.5, 0.618, 0.786, 0.886)
            cnt  = z.s4e.size()
            if cnt >= minHist
                f1 = math.abs(p3 - p2) / z.pa.get(m + 3)
                f2 = float(z.pb.get(m + 3) - z.pb.get(m + 2))
                f3 = L3 / math.abs(math.log(p2) - math.log(p1))
                sd1 = z.s4a.stdev()
                sd2 = z.s4b.stdev()
                sd3 = z.s4c.stdev()
                sd1 := sd1 > 0 ? sd1 : 1.0
                sd2 := sd2 > 0 ? sd2 : 1.0
                sd3 := sd3 > 0 ? sd3 : 1.0
                dist = array.new<float>()
                for i = 0 to cnt - 1
                    a1 = (z.s4a.get(i) - f1) / sd1
                    a2 = (z.s4b.get(i) - f2) / sd2
                    a3 = (z.s4c.get(i) - f3) / sd3
                    dist.push(a1 * a1 + a2 * a2 + a3 * a3)
                ord = dist.sort_indices(order.ascending)
                for j = 0 to math.min(knn, cnt) - 1
                    pool.push(z.s4e.get(ord.get(j)))
                    poolR.push(4)
                    poolI.push(ord.get(j))
        else
            base := z.pp.get(m + 4)
            unit := L1
            sg   := s
            lv   := array.from(0.618, 1.0, 1.618)
            book := true
        now = z.ext > 0 ? math.abs(math.log(z.ext) - math.log(base)) / unit : 0.0
        tip = "zigzag " + str.tostring(z.k) + " ATR · learned from " + str.tostring(pool.size()) + " past swings" + (showHs ? " · the ones that got this far are drawn where they happened, scroll back" : "")
        // levels already reached
        if showTk
            for r in lv
                if r <= now
                    y = lvP(base, sg, unit, r)
                    addL(x1 + 6, y, x1 + 8, y, color.new(colCnt, 50), 2, line.style_solid)
                    addT(x1 + 6, y, fmtP(y) + " ✓", color.new(colCnt, 45), label.style_label_right)
        float yt = na
        if book
            yt := lvP(base, sg, unit, 1.0)
            addL(bar_index, close, xT, yt, colMod, 2, line.style_dashed)
            dB.push(label.new(xT, yt, "5", color = colMod, textcolor = color.white, style = label.style_label_center, size = txtSz(txtSize)))
            addT(xT + 6, yt, fmtP(yt) + " · book", colMod, label.style_label_left)
            lgSet(hdr + " · in progress", color.new(#2F3640, 0), "Book target " + fmtP(yt), colMod, "1.0 x wave 1 from point 4", "too few past wave 5s here to count", wrong, colInv, "")
        else
            alive = array.new<float>()
            for e in pool
                if e >= now
                    alive.push(e)
            nAl = alive.size()
            // the similar past swings that got this far, drawn where they happened like the count: newest first,
            // skipping any that overlap one already drawn or the count in play (they still count in the share).
            // When the waves after one went on by the rules, they are drawn too, up to wave 5.
            if showHs and nAl > 0
                hOff = z.hN - z.hB.size()
                f0 = wave == 4 ? 2 : 0
                hI = array.new<int>()
                hG = array.new<int>()
                hS = array.new<int>()
                for i = 0 to pool.size() - 1
                    if pool.get(i) >= now
                        rl = poolR.get(i)
                        np = rl == 3 ? 4 : 3
                        g0 = (rl == 3 ? z.gi3 : rl == 2 ? z.gi2 : z.gi4).get(poolI.get(i)) - hOff
                        if g0 >= 0 and g0 + np <= z.hB.size()
                            hI.push(i)
                            hG.push(g0)
                            hS.push(z.hB.get(g0))
                ovA = array.new<int>()
                ovB = array.new<int>()
                int drawn = 0
                if hI.size() > 0
                    for jj in hS.sort_indices(order.descending)
                        i  = hI.get(jj)
                        g0 = hG.get(jj)
                        e  = pool.get(i)
                        np = poolR.get(i) == 3 ? 4 : 3
                        sK = z.hP.get(g0 + 1) > z.hP.get(g0) ? 1.0 : -1.0
                        // the waves after it, while they keep to the rules (the count's own, on prices)
                        int nP = np
                        bool go = true
                        while go and f0 + nP <= 5 and g0 + nP < z.hB.size()
                            if z.hB.get(g0 + nP) > b0 or z.hB.get(g0 + nP) == z.hB.get(g0 + nP - 1)
                                break
                            nx = f0 + nP
                            q  = sK * z.hP.get(g0 + nP)
                            bool ok = false
                            if nx == 3
                                q0 = sK * z.hP.get(g0)
                                q1 = sK * z.hP.get(g0 + 1)
                                q2 = sK * z.hP.get(g0 + 2)
                                r2 = (q1 - q2) / (q1 - q0)
                                ok := r2 >= 0.382 and r2 <= 0.786 and q - q2 >= q1 - q0
                            else if nx == 4
                                q0 = sK * z.hP.get(g0)
                                q1 = sK * z.hP.get(g0 + 1)
                                q2 = sK * z.hP.get(g0 + 2)
                                q3 = sK * z.hP.get(g0 + 3)
                                r4 = (q3 - q) / (q3 - q2)
                                ok := q3 - q2 >= q1 - q0 and r4 >= 0.236 and r4 <= 0.618 and q > q2
                            else
                                p2 = sK * z.hP.get(g0 + 2 - f0)
                                p3 = sK * z.hP.get(g0 + 3 - f0)
                                p4 = sK * z.hP.get(g0 + 4 - f0)
                                r4 = (p3 - p4) / (p3 - p2)
                                // the swing after a valid 4 is drawn as 5; with the setting on, only when it goes past the end of wave 3
                                ok := r4 >= 0.236 and r4 <= 0.618 and p4 > p2 and (not full5 or q > p3)
                            if ok
                                nP += 1
                            else
                                go := false
                        // a wave-4-like pullback: draw the 0-1 before it too, when that start kept to the rules
                        int bk = 0
                        if f0 == 2 and g0 >= 2
                            q0 = sK * z.hP.get(g0 - 2)
                            q1 = sK * z.hP.get(g0 - 1)
                            q2 = sK * z.hP.get(g0)
                            q3 = sK * z.hP.get(g0 + 1)
                            r2 = (q1 - q2) / (q1 - q0)
                            rdbl = z.hB.get(g0 - 1) > z.hB.get(g0 - 2) and z.hB.get(g0) > z.hB.get(g0 - 1)
                            if rdbl and q1 > q0 and r2 >= 0.382 and r2 <= 0.786 and q3 - q2 >= q1 - q0
                                bk := 2
                        gS = g0 - bk
                        nA = nP + bk
                        xs = z.hB.get(gS)
                        xe = z.hB.get(g0 + nP - 1)
                        // it must end before the count in play starts, or their points pile up
                        bool free = drawn < 30 and z.hB.get(g0 + np - 1) < b0 and xs > bar_index - 4900   // drawing on a past bar reads its time, and series keep 5000 bars
                        if ovA.size() > 0
                            for qq = 0 to ovA.size() - 1
                                if xs < ovB.get(qq) and xe + (xe - xs) > ovA.get(qq)
                                    free := false
                        if free
                            ovA.push(xs)
                            ovB.push(xe + (xe - xs))   // the caption is often wider than a short box
                            float hi = z.hP.get(gS)
                            float lo = z.hP.get(gS)
                            for j = 1 to nA - 1
                                hi := math.max(hi, z.hP.get(gS + j))
                                lo := math.min(lo, z.hP.get(gS + j))
                            upK = sK > 0
                            dX.push(box.new(xs, hi, xe, lo, border_color = color.new(colMod, 55), bgcolor = color.new(colMod, 92)))
                            for j = 0 to nA - 2
                                ans = j == np - 2 + bk
                                addL(z.hB.get(gS + j), z.hP.get(gS + j), z.hB.get(gS + j + 1), z.hP.get(gS + j + 1), color.new(ans ? colMod : colCnt, ans ? 15 : 35), ans ? 2 : 1, line.style_solid)
                            // the points, as the same badges as the count in play, only fainter
                            for j = 0 to nA - 1
                                topP = ((j + f0 - bk) % 2 == 1) == upK
                                dB.push(label.new(z.hB.get(gS + j), z.hP.get(gS + j), str.tostring(j + f0 - bk), color = color.new(colCnt, 45), textcolor = color.white, style = j == 0 ? label.style_label_right : topP ? label.style_label_down : label.style_label_up, size = txtSzH(txtSize)))
                            // how far its wave really went, in plain words
                            wN = "wave " + str.tostring(wave)
                            rt = (wave == 2 or wave == 4) and e > 1.0 ? wN + " broke the count" : wave == 3 ? wN + " ran " + str.tostring(e, "0.00") + " × wave 1" : wN + " pulled back " + str.tostring(math.round(100 * e)) + "%"
                            // the caption is a header on the box edge at point 0 (above a fall, below a rise); point 0 moves left of that corner
                            dB.push(label.new(xs, upK ? lo : hi, "SIMILAR PATTERN" + (sK != s ? " (mirrored)" : "") + " · " + rt, color = color.new(colMod, 15), textcolor = color.white,
                                 style = upK ? label.style_label_upper_left : label.style_label_lower_left, size = txtSzH(txtSize),
                                 tooltip = "One of the " + str.tostring(nAl) + " similar swings on this chart that got as far as price has now." + (sK != s ? " It ran the other way: up and down are learned together, measured as a share of the leg before." : "") + " Its wave " + str.tostring(wave) + " ran " + str.tostring(e, "0.00") + (wave == 3 ? " × wave 1." : " of the leg before.") + (nP > np ? " The waves after it kept to the rules up to wave " + str.tostring(f0 + nP - 1) + "." : "") + (bk > 0 ? " Its 0-1-2 before kept to the rules too." : "")))
                            drawn += 1
            if pool.size() == 0
                lgSet(hdr + " · in progress", color.new(#2F3640, 0), "Not enough past swings yet", colMod, "", "", wrong, colInv, "")
            else if nAl == 0
                lgSet(hdr + " · in progress", color.new(#2F3640, 0), "Already further than every similar swing", colMod, "", "", wrong, colInv, "")
            else
                hint = nAl <= 4 ? "Few swings to learn from, treat as a hint" : ""   // the ~ already marks fewer than 10
                // target: the level ahead where most of the swings that got this far stopped
                int bestI = -1
                int bestC = -1
                for i = 0 to lv.size() - 1
                    r = lv.get(i)
                    if r > now
                        c = 0
                        for e in alive
                            if (wave == 2 or wave == 4) and e > 1.0
                                continue
                            hiI = -1
                            for jj = 0 to lv.size() - 1
                                if lv.get(jj) <= e and lv.get(jj) > now
                                    hiI := jj
                            if hiI == i
                                c += 1
                        if c > bestC
                            bestC := c
                            bestI := i
                // waves 2 and 4: swings that went past the start of the wave before broke the count
                int brk = 0
                if wave == 2 or wave == 4
                    for e in alive
                        if e > 1.0
                            brk += 1
                ptN = str.tostring(wave == 2 ? 0 : 2)
                if (wave == 2 or wave == 4) and 2 * brk > nAl
                    invTxt := false
                    invLn.set_x2(xT)
                    addT(xT - 2, inv, "invalid", color.new(colInv, 15), up ? label.style_label_lower_right : label.style_label_upper_right)
                    addL(bar_index, close, xT, inv, colInv, 2, line.style_dashed)
                    dB.push(label.new(xT, inv, "✕", color = colInv, textcolor = color.white, style = label.style_label_center, size = txtSz(txtSize), tooltip = tip))
                    addT(xT + 6, inv, fmtP(inv) + " · " + pctS(brk, nAl), colInv, label.style_label_left, tip)
                    lgSet(hdr + " · count at risk", color.new(#2F3640, 0), "Likely breaks " + (up ? "below " : "above ") + fmtP(inv) + " · " + pctS(brk, nAl), colInv,
                         "Why: " + str.tostring(brk) + " of " + str.tostring(nAl) + " similar swings on this chart", "that got this far went on past point " + ptN, "Then the count starts over", color.new(#9AA3AE, 0), hint)
                else if bestI >= 0 and bestC > 0
                    rT = lv.get(bestI)
                    yt := lvP(base, sg, unit, rT)
                    k = 0
                    for e in alive
                        if e >= rT
                            k += 1
                    alive.sort(order.ascending)
                    qLo = alive.get(int(0.25 * (nAl - 1) + 0.5))
                    qHi = alive.get(int(0.75 * (nAl - 1) + 0.5))
                    // a wave 2 or 4 deeper than the whole wave before it would break the count: the band stops at the invalid line
                    if wave == 2 or wave == 4
                        qLo := math.min(qLo, rT)
                        qHi := math.min(qHi, 1.0)
                    yLo = lvP(base, sg, unit, qLo)
                    yHi = lvP(base, sg, unit, qHi)
                    pts = array.new<chart.point>()
                    pts.push(chart.point.from_index(bar_index, close))
                    pts.push(chart.point.from_index(x1, yLo))
                    pts.push(chart.point.from_index(x1 + 6, yLo))
                    pts.push(chart.point.from_index(x1 + 6, yHi))
                    pts.push(chart.point.from_index(x1, yHi))
                    dP.push(polyline.new(pts, closed = true, line_color = color.new(colMod, 100), fill_color = color.new(colMod, 78)))
                    addL(bar_index, close, xT, yt, colMod, 2, line.style_dashed)
                    dB.push(label.new(xT, yt, str.tostring(wave), color = colMod, textcolor = color.white, style = label.style_label_center, size = txtSz(txtSize), tooltip = tip))
                    addT(xT + 6, yt, fmtP(yt) + " · " + pctS(k, nAl), colMod, label.style_label_left, tip)
                    // the other levels ahead, fainter the less likely
                    for r in lv
                        if r > now and r != rT and not ((wave == 2 or wave == 4) and r > 1.0)
                            kr = 0
                            for e in alive
                                if e >= r
                                    kr += 1
                            if kr > 0
                                y = lvP(base, sg, unit, r)
                                tr = int(math.max(25, 70 - 0.5 * pctV(kr, nAl)))
                                addL(x1 + 8, y, x1 + 10, y, color.new(colMod, tr), 2, line.style_solid)
                                addT(x1 + 10, y, fmtP(y) + " · " + pctS(kr, nAl), color.new(colMod, tr), label.style_label_left)
                    lgSet(hdr + " · in progress", color.new(#2F3640, 0), "Next stop " + fmtP(yt) + " · " + pctS(k, nAl), colMod,
                         "Why: " + str.tostring(k) + " of " + str.tostring(nAl) + " similar swings on this chart", "that got this far went on to reach it", wrong, colInv, hint)
                else if bestI >= 0
                    lgSet(hdr + " · at the edge", color.new(#2F3640, 0), "Similar swings stopped around here", colMod, "Why: none of " + str.tostring(nAl) + " that got this far", "reached the next level", wrong, colInv, hint)
                else if wave == 3
                    lgSet(hdr + " · in progress", color.new(#2F3640, 0), "Already past every level", colMod, str.tostring(nAl) + " of " + str.tostring(pool.size()) + " similar swings", "on this chart got this far", wrong, colInv, hint)
                else
                    lgSet(hdr + " · in progress", color.new(#2F3640, 0), "Already past every level", colMod, "", "", wrong, colInv, hint)
        if invTxt
            addT(xE, inv, "invalid", color.new(colInv, 15), label.style_label_left)
        // the path to wave 5, from the book: wave 3 = 1.618 x wave 1, wave 4 = 0.382 of wave 3, wave 5 = 1.0 x wave 1
        if showNx and not na(yt) and wave < 5
            float px = yt
            int   bx = xT
            float w3s = na
            for w = wave + 1 to 5
                float yN = na
                if w == 3
                    w3s := px
                    yN  := math.exp(math.log(px) + s * 1.618 * L1)
                else if w == 4
                    st3 = wave == 3 ? base : w3s
                    yN  := math.exp(math.log(px) - s * 0.382 * math.abs(math.log(px) - math.log(st3)))
                else
                    yN := math.exp(math.log(px) + s * L1)
                nx = bx + (w % 2 == 1 ? dur : int(dur * 0.6))
                tr = 25 + 15 * (w - wave - 1)
                addL(bx, px, nx, yN, color.new(colMod, tr), 2, line.style_dashed)
                top = (w % 2 == 1) == up
                dB.push(label.new(nx, yN, str.tostring(w) + "?", color = color.new(colMod, tr + 10), textcolor = color.white, style = top ? label.style_label_down : label.style_label_up, size = txtSz(txtSize)))
                // its price, unless a level ahead already shows the same price (wave 5 often lands on one)
                bool dup = false
                for r in lv
                    if r > now and math.abs(math.log(lvP(base, sg, unit, r)) - math.log(yN)) < 0.003
                        dup := true
                if not dup
                    addT(nx + 3, yN, fmtP(yN), color.new(colMod, tr + 10), label.style_label_left)
                px := yN
                bx := nx

← 返回列表