Chart Pattern Blueprint [Quantum Algo]

Quantum-Algo · study · 375 行 · 点赞 790 · TradingView 原页

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

Pine Script

//@version=6
indicator("Chart Pattern Blueprint [Quantum Algo]", overlay = true, max_lines_count = 300, max_labels_count = 300, max_boxes_count = 60, max_polylines_count = 60)
 
// ════════════════════════════════════════════════════════════════
//  CHART PATTERN BLUEPRINT
//  Automatic detection of four classical reversal patterns — Head
//  and Shoulders, Inverse Head and Shoulders, Double Top and
//  Double Bottom — drawn the way an engineer would draw them: a
//  filled outline of the pattern, the neckline, a dimension line
//  measuring the pattern height, and the measured-move target
//  projected from the neckline break. Each pattern then moves
//  through a visible lifecycle (forming, confirmed, target
//  reached, failed, expired) and the title block keeps an honest
//  count of how often each pattern type has reached its target on
//  the chart you are looking at.
//
//  Concept credits: Head and Shoulders, Double Top and Double
//  Bottom patterns and the measured-move target from classical
//  technical analysis — Richard W. Schabacker (Technical Analysis
//  and Stock Market Profits, 1932) and Robert D. Edwards and John
//  Magee (Technical Analysis of Stock Trends, 1948) · the practice
//  of measuring pattern outcomes statistically follows Thomas N.
//  Bulkowski (Encyclopedia of Chart Patterns) · Average True Range
//  by J. Welles Wilder Jr. (1978) · swing pivots from standard
//  charting technique · additive (Laplace) smoothing from
//  classical statistics. The geometry rules, lifecycle engine,
//  blueprint rendering, outcome statistics and all code are
//  original work. No third-party or open-source script code was
//  reused.
// ════════════════════════════════════════════════════════════════
 
// ─── INPUTS ─────────────────────────────────────────────────────
grpP = "Patterns"
showHS  = input.bool(true, "Head and Shoulders / Inverse Head and Shoulders", group = grpP)
showDbl = input.bool(true, "Double Top / Double Bottom", group = grpP)
pivLen  = input.int(5, "Swing Length", minval = 2, maxval = 30, group = grpP, tooltip = "Bars on each side that define a swing point. A pattern is only evaluated after its last swing is confirmed, this many bars later. Larger values find larger patterns.")
minH    = input.float(2.0, "Minimum Pattern Height (Average True Range)", step = 0.25, minval = 0.5, group = grpP)
maxW    = input.int(150, "Maximum Pattern Width (Bars)", minval = 20, maxval = 500, group = grpP)
 
grpG = "Geometry Tolerances"
eqTol   = input.float(0.15, "Double Pattern: Peak Equality (Share Of Height)", step = 0.01, minval = 0.02, maxval = 0.5, group = grpG, tooltip = "How far apart the two tops (or bottoms) may be, as a share of the pattern height.")
shTol   = input.float(0.40, "Head and Shoulders: Shoulder Symmetry (Share Of Height)", step = 0.05, minval = 0.05, maxval = 1.0, group = grpG)
neckTol = input.float(0.40, "Head and Shoulders: Neckline Tilt (Share Of Height)", step = 0.05, minval = 0.05, maxval = 1.0, group = grpG)
 
grpC = "Confirmation And Target"
brkBuf     = input.float(0.1, "Neckline Break Buffer (Average True Range)", step = 0.05, minval = 0.0, group = grpC, tooltip = "A pattern is confirmed when a bar closes beyond the neckline by this distance.")
tgtMult    = input.float(1.0, "Target (Multiple Of Pattern Height)", step = 0.1, minval = 0.3, maxval = 3.0, group = grpC, tooltip = "The classical measured move projects one pattern height from the neckline.")
waitMult   = input.float(1.0, "Wait For Break (Multiple Of Pattern Width)", step = 0.25, minval = 0.25, group = grpC)
settleMult = input.float(2.0, "Time To Reach Target (Multiple Of Pattern Width)", step = 0.25, minval = 0.5, group = grpC)
keepN      = input.int(6, "Patterns To Keep On Chart", minval = 2, maxval = 15, group = grpC)
 
grpV = "Visuals"
inkCol  = input.color(#0d47a1, "Blueprint Ink", group = grpV)
dimCol  = input.color(#6a1b9a, "Dimension Lines", group = grpV)
tgtCol  = input.color(#c77800, "Target", group = grpV)
bullCol = input.color(#00897b, "Target Reached", group = grpV)
bearCol = input.color(#e4002b, "Failed", group = grpV)
silvCol = input.color(#546e7a, "Expired / Not Confirmed", group = grpV)
 
grpT = "Title Block"
showTb = input.bool(true, "Show Title Block", group = grpT)
tbPosS = input.string("Bottom Right", "Position", options = ["Bottom Right", "Bottom Left", "Top Right", "Top Left"], group = grpT)
tbSzS  = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal"], group = grpT)
 
// ─── TYPES ──────────────────────────────────────────────────────
type Pat
    int   kind      // 1 Double Top · 2 Double Bottom · 3 Head and Shoulders · 4 Inverse
    int   dir       // expected direction after the break: -1 down, 1 up
    int   keyBar
    int   dimBar
    float extreme
    float stopPx
    float height
    int   n1Bar
    float n1Px
    float slope
    int   startBar
    int   endBar
    int   detBar
    int   waitB
    int   settleB
    int   state     // 0 forming · 1 confirmed · 2 target reached · 3 failed · 4 expired
    int   confBar
    float target
    array<chart.point> pts
    polyline shape
    line  neck
    line  dim
    label dimLb
    label tag
    line  proj
    box   tgtBox
 
// ─── SHARED ─────────────────────────────────────────────────────
atrV = ta.atr(14)
f_kindName(int k) => k == 1 ? "Double Top" : k == 2 ? "Double Bottom" : k == 3 ? "Head and Shoulders" : "Inverse Head and Shoulders"
f_neck(Pat p, int b) => p.n1Px + p.slope * (b - p.n1Bar)
 
// ─── SWING ZIGZAG · alternating confirmed pivots ───────────────
var array<float> zPx  = array.new<float>()
var array<int>   zBar = array.new<int>()
var array<int>   zDir = array.new<int>()
f_addPivot(float px, int br, int d) =>
    bool changed = false
    n = zPx.size()
    if n > 0 and zDir.get(n - 1) == d
        if (d == 1 and px > zPx.get(n - 1)) or (d == -1 and px < zPx.get(n - 1))
            zPx.set(n - 1, px)
            zBar.set(n - 1, br)
            changed := true
    else
        zPx.push(px)
        zBar.push(br)
        zDir.push(d)
        if zPx.size() > 14
            zPx.shift()
            zBar.shift()
            zDir.shift()
        changed := true
    changed
f_zp(int k) => zPx.get(zPx.size() - 1 - k)
f_zb(int k) => zBar.get(zBar.size() - 1 - k)
f_zd(int k) => zDir.get(zDir.size() - 1 - k)
 
ph = ta.pivothigh(high, pivLen, pivLen)
pl = ta.pivotlow(low, pivLen, pivLen)
bool zNew = false
if barstate.isconfirmed and not na(ph)
    chH = f_addPivot(ph, bar_index - pivLen, 1)
    zNew := zNew or chH
if barstate.isconfirmed and not na(pl)
    chL = f_addPivot(pl, bar_index - pivLen, -1)
    zNew := zNew or chL
 
// ─── PATTERN STORE + STATISTICS ────────────────────────────────
var array<Pat> pats = array.new<Pat>()
var array<int> resN = array.new<int>(5, 0)   // confirmed patterns that have resolved, per kind
var array<int> hitN = array.new<int>(5, 0)   // of those, how many reached the target
f_rate(int k) =>
    n = resN.get(k)
    n > 0 ? (hitN.get(k) + 2.0) / (n + 4.0) : na
 
f_delete(Pat p) =>
    polyline.delete(p.shape)
    line.delete(p.neck)
    line.delete(p.dim)
    label.delete(p.dimLb)
    label.delete(p.tag)
    line.delete(p.proj)
    box.delete(p.tgtBox)
    true
 
f_status(Pat p, string txt, color col) =>
    polyline.delete(p.shape)
    p.shape := polyline.new(p.pts, closed = true, line_color = color.new(col, 0), fill_color = color.new(col, 82), line_width = 2)
    label.set_text(p.tag, f_kindName(p.kind) + " · " + txt)
    label.set_color(p.tag, color.new(col, 0))
    line.set_color(p.neck, color.new(col, 0))
    true
 
f_build(int kind, int dir, array<chart.point> pts, int keyBar, int dimBar, float extreme, float stopPx, float height, int n1Bar, float n1Px, float slope, int startBar, int endBar) =>
    p = Pat.new()
    p.kind := kind
    p.dir := dir
    p.keyBar := keyBar
    p.dimBar := dimBar
    p.extreme := extreme
    p.stopPx := stopPx
    p.height := height
    p.n1Bar := n1Bar
    p.n1Px := n1Px
    p.slope := slope
    p.startBar := startBar
    p.endBar := endBar
    p.detBar := bar_index
    w = math.max(endBar - startBar, 10)
    p.waitB := math.max(int(w * waitMult), 10)
    p.settleB := math.max(int(w * settleMult), 20)
    p.state := 0
    p.pts := pts
    p.shape := polyline.new(pts, closed = true, line_color = color.new(inkCol, 0), fill_color = color.new(inkCol, 84), line_width = 2)
    nkEnd = bar_index + 3
    p.neck := line.new(startBar, n1Px + slope * (startBar - n1Bar), nkEnd, n1Px + slope * (nkEnd - n1Bar), color = color.new(inkCol, 0), style = line.style_dashed, width = 2)
    nkDim = n1Px + slope * (dimBar - n1Bar)
    p.dim := line.new(dimBar, extreme, dimBar, nkDim, color = color.new(dimCol, 0), style = line.style_arrow_both, width = 1)
    p.dimLb := label.new(dimBar, (extreme + nkDim) / 2, "H " + str.tostring(height / atrV, "#.#") + " ATR", style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(dimCol, 0), size = size.small, tooltip = "Pattern height, measured from the pattern extreme to the neckline. The measured-move target projects this height from the neckline break.")
    p.tag := label.new(keyBar, extreme, f_kindName(kind) + " · forming", style = dir == -1 ? label.style_label_down : label.style_label_up, color = color.new(inkCol, 0), textcolor = color.white, size = size.small, tooltip = f_kindName(kind) + "\nForming: the shape is complete but price has not closed beyond the dashed neckline yet.\nIt is confirmed only by a close beyond the neckline, and discarded if price closes beyond the pattern extreme first.")
    p
 
f_register(Pat p) =>
    bool add = true
    n = pats.size()
    if n > 0
        q = pats.get(n - 1)
        if q.kind == p.kind and q.keyBar == p.keyBar
            if q.state == 0
                f_delete(q)
                pats.pop()
                add := true
            else
                add := false
    if add
        pats.push(p)
    if not add
        f_delete(p)
    while pats.size() > keepN
        f_delete(pats.shift())
    add
 
// ─── DETECTION · runs only when a new swing is confirmed ───────
bool evDetect = false
if zNew and zPx.size() >= 4
    s = f_zd(0)
    bool made = false
    // Head and Shoulders family: five swings plus the lead-in swing
    if showHS and zPx.size() >= 6
        rs = f_zp(0)
        n2 = f_zp(1)
        hd = f_zp(2)
        n1 = f_zp(3)
        ls = f_zp(4)
        pre = f_zp(5)
        rsB = f_zb(0)
        n2B = f_zb(1)
        hdB = f_zb(2)
        n1B = f_zb(3)
        lsB = f_zb(4)
        preB = f_zb(5)
        slope = n2B != n1B ? (n2 - n1) / (n2B - n1B) : 0.0
        nkHd = n1 + slope * (hdB - n1B)
        nkLs = n1 + slope * (lsB - n1B)
        nkRs = n1 + slope * (rsB - n1B)
        hH = s * (hd - nkHd)
        okShape = s * (hd - ls) > 0 and s * (hd - rs) > 0 and hH >= atrV * minH
        okSh = s * (ls - nkLs) >= hH * 0.25 and s * (rs - nkRs) >= hH * 0.25 and math.abs(ls - rs) <= hH * shTol
        okNeck = math.abs(n1 - n2) <= hH * neckTol
        okLead = s * (nkLs - pre) >= hH * 0.25
        okW = rsB - lsB <= maxW
        if okShape and okSh and okNeck and okLead and okW
            den = s * (ls - pre)
            frac = den > 0 ? math.min(math.max(s * (ls - nkLs) / den, 0.0), 1.0) : 1.0
            leftB = lsB - int((lsB - preB) * frac)
            rightB = rsB + math.max(rsB - n2B, 1)
            pts = array.new<chart.point>()
            pts.push(chart.point.from_index(leftB, n1 + slope * (leftB - n1B)))
            pts.push(chart.point.from_index(lsB, ls))
            pts.push(chart.point.from_index(n1B, n1))
            pts.push(chart.point.from_index(hdB, hd))
            pts.push(chart.point.from_index(n2B, n2))
            pts.push(chart.point.from_index(rsB, rs))
            pts.push(chart.point.from_index(rightB, n1 + slope * (rightB - n1B)))
            pNew = f_build(s == 1 ? 3 : 4, -s, pts, hdB, hdB, hd, rs, hH, n1B, n1, slope, leftB, rightB)
            added = f_register(pNew)
            made := true
            evDetect := evDetect or added
    // Double Top / Double Bottom: three swings plus the lead-in swing
    if showDbl and not made
        t2 = f_zp(0)
        md = f_zp(1)
        t1 = f_zp(2)
        pr = f_zp(3)
        t2B = f_zb(0)
        mdB = f_zb(1)
        t1B = f_zb(2)
        prB = f_zb(3)
        ext = s == 1 ? math.max(t1, t2) : math.min(t1, t2)
        hD = s * (ext - md)
        okD = hD >= atrV * minH and math.abs(t1 - t2) <= hD * eqTol and s * (md - pr) >= hD * 0.3 and t2B - t1B <= maxW and t2B - t1B >= pivLen * 2
        if okD
            denD = s * (t1 - pr)
            fracD = denD > 0 ? math.min(math.max(s * (t1 - md) / denD, 0.0), 1.0) : 1.0
            leftD = t1B - int((t1B - prB) * fracD)
            rightD = t2B + math.max(t2B - mdB, 1)
            ptsD = array.new<chart.point>()
            ptsD.push(chart.point.from_index(leftD, md))
            ptsD.push(chart.point.from_index(t1B, t1))
            ptsD.push(chart.point.from_index(mdB, md))
            ptsD.push(chart.point.from_index(t2B, t2))
            ptsD.push(chart.point.from_index(rightD, md))
            pD = f_build(s == 1 ? 1 : 2, -s, ptsD, t1B, t2B, ext, ext, hD, mdB, md, 0.0, leftD, rightD)
            addedD = f_register(pD)
            evDetect := evDetect or addedD
 
// ─── LIFECYCLE · forming → confirmed → target / failed / expired ─
bool evConfBull = false
bool evConfBear = false
bool evTarget = false
bool evFailed = false
if barstate.isconfirmed and pats.size() > 0
    for i = 0 to pats.size() - 1
        p = pats.get(i)
        if p.state == 0
            nk = f_neck(p, bar_index)
            line.set_xy2(p.neck, bar_index + 3, f_neck(p, bar_index + 3))
            if p.dir * (close - nk) > atrV * brkBuf
                p.state := 1
                p.confBar := bar_index
                p.target := nk + p.dir * p.height * tgtMult
                line.set_xy2(p.neck, bar_index, nk)
                line.set_style(p.neck, line.style_solid)
                label.set_text(p.tag, f_kindName(p.kind) + " · confirmed")
                label.set_tooltip(p.tag, f_kindName(p.kind) + "\nConfirmed: a bar closed beyond the neckline.\nMeasured-move target " + str.tostring(p.target, format.mintick) + " = neckline " + (p.dir == 1 ? "plus " : "minus ") + str.tostring(tgtMult, "#.##") + " x pattern height.\nThe pattern fails if price closes back beyond " + str.tostring(p.stopPx, format.mintick) + ", and expires after " + str.tostring(p.settleB) + " bars.")
                p.proj := line.new(bar_index, nk, bar_index + math.max(int(p.settleB / 4), 3), p.target, color = color.new(tgtCol, 0), style = line.style_arrow_right, width = 2)
                p.tgtBox := box.new(bar_index, p.target + atrV * 0.2, bar_index + p.settleB, p.target - atrV * 0.2, border_color = color.new(tgtCol, 0), border_style = line.style_dotted, bgcolor = color.new(tgtCol, 80), text = "Target " + str.tostring(p.target, format.mintick), text_color = color.new(tgtCol, 0), text_size = size.small, text_halign = text.align_right)
                if p.dir == 1
                    evConfBull := true
                else
                    evConfBear := true
            else if p.dir * (close - p.extreme) < 0
                p.state := 3
                f_status(p, "not confirmed", silvCol)
            else if bar_index - p.detBar > p.waitB
                p.state := 4
                f_status(p, "not confirmed", silvCol)
        else if p.state == 1 and bar_index > p.confBar
            reached = p.dir == 1 ? high >= p.target : low <= p.target
            if reached
                p.state := 2
                resN.set(p.kind, resN.get(p.kind) + 1)
                hitN.set(p.kind, hitN.get(p.kind) + 1)
                f_status(p, "target reached", bullCol)
                box.set_right(p.tgtBox, bar_index)
                box.set_bgcolor(p.tgtBox, color.new(bullCol, 70))
                evTarget := true
            else if p.dir * (close - p.stopPx) < 0
                p.state := 3
                resN.set(p.kind, resN.get(p.kind) + 1)
                f_status(p, "failed", bearCol)
                box.set_right(p.tgtBox, bar_index)
                box.set_bgcolor(p.tgtBox, color.new(silvCol, 88))
                evFailed := true
            else if bar_index - p.confBar > p.settleB
                p.state := 4
                resN.set(p.kind, resN.get(p.kind) + 1)
                box.set_bgcolor(p.tgtBox, color.new(silvCol, 88))
                f_status(p, "expired", silvCol)
 
// ─── TITLE BLOCK · the drawing's legend and outcome record ─────
tbPos = tbPosS == "Bottom Left" ? position.bottom_left : tbPosS == "Top Right" ? position.top_right : tbPosS == "Top Left" ? position.top_left : position.bottom_right
tbSz = tbSzS == "Tiny" ? size.tiny : tbSzS == "Normal" ? size.normal : size.small
var table tb = table.new(tbPos, 3, 8, bgcolor = color.new(#0b2545, 0), frame_color = color.new(#90caf9, 0), frame_width = 2, border_color = color.new(#90caf9, 70), border_width = 1)
f_row(int r, int k) =>
    rt = f_rate(k)
    n = resN.get(k)
    table.cell(tb, 0, r, f_kindName(k), text_color = color.new(#e3f2fd, 0), text_size = tbSz, text_halign = text.align_left)
    table.cell(tb, 1, r, str.tostring(n), text_color = color.new(#e3f2fd, 0), text_size = tbSz)
    table.cell(tb, 2, r, n > 0 ? str.tostring(hitN.get(k)) + " of " + str.tostring(n) + " · " + str.tostring(rt * 100, "#") + "%" : "—", text_color = n >= 5 and rt >= 0.6 ? color.new(#ffd54f, 0) : color.new(#e3f2fd, 0), text_size = tbSz)
    true
if showTb and barstate.islast
    table.cell(tb, 0, 0, "PATTERN BLUEPRINT · " + syminfo.ticker + " · " + timeframe.period, bgcolor = color.new(#90caf9, 0), text_color = #0b2545, text_size = tbSz, text_halign = text.align_left)
    table.cell(tb, 1, 0, "", bgcolor = color.new(#90caf9, 0))
    table.cell(tb, 2, 0, "", bgcolor = color.new(#90caf9, 0))
    table.merge_cells(tb, 0, 0, 2, 0)
    table.cell(tb, 0, 1, "Pattern", text_color = color.new(#90caf9, 0), text_size = tbSz, text_halign = text.align_left)
    table.cell(tb, 1, 1, "Resolved", text_color = color.new(#90caf9, 0), text_size = tbSz)
    table.cell(tb, 2, 1, "Target reached", text_color = color.new(#90caf9, 0), text_size = tbSz)
    f_row(2, 3)
    f_row(3, 4)
    f_row(4, 1)
    f_row(5, 2)
    string act = "No pattern on the board"
    if pats.size() > 0
        q = pats.get(pats.size() - 1)
        act := f_kindName(q.kind) + " · " + (q.state == 0 ? "forming" : q.state == 1 ? "confirmed, target " + str.tostring(q.target, format.mintick) : q.state == 2 ? "target reached" : q.state == 3 ? "closed without reaching target" : "expired")
    table.cell(tb, 0, 6, "Latest: " + act, text_color = color.new(#ffd54f, 0), text_size = tbSz, text_halign = text.align_left)
    table.merge_cells(tb, 0, 6, 2, 6)
    table.cell(tb, 0, 7, "Counts confirmed patterns only · smoothed rate · this chart's history, not a forecast", text_color = color.new(#90caf9, 20), text_size = size.tiny, text_halign = text.align_left)
    table.merge_cells(tb, 0, 7, 2, 7)
 
// ─── ALERTS ────────────────────────────────────────────────────
alertcondition(evDetect, "Pattern Forming", "A reversal pattern shape completed and is waiting for a neckline break.")
alertcondition(evConfBull, "Bullish Pattern Confirmed", "A bullish reversal pattern was confirmed by a close above its neckline.")
alertcondition(evConfBear, "Bearish Pattern Confirmed", "A bearish reversal pattern was confirmed by a close below its neckline.")
alertcondition(evTarget, "Pattern Target Reached", "A confirmed pattern reached its measured-move target.")
alertcondition(evFailed, "Pattern Failed", "A confirmed pattern closed back beyond its failure level.")

← 返回列表