Pattern Evidence Map: Chart Patterns vs Random Entries

thescalpeltrader · study · 997 行 · 点赞 320 · 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/
// © thescalpeltrader
 
//@version=6
indicator("Pattern Evidence Map: Chart Patterns vs Random Entries", "Pattern Evidence Map", overlay = true, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
// ─────────────────────────────────────────────────────────────────────────────
// What this script does
// 1. Finds chart patterns on closed bars with three detectors that run side by side:
//    - line patterns from zigzag pivots (triangles, wedges, channels, rectangles, broadening)
//    - reversal patterns from zigzag pivots (head and shoulders, double top, and their inverses)
//    - flags and pennants (a sharp pole followed by a short pause)
// 2. Follows each pattern until price closes outside it (up or down) or its window ends.
// 3. After a break it follows price until the stop is hit or the time limit ends, and
//    records the best move and the exit in R multiples (1 R = distance from the breakout
//    close to the first stop). Stop type and trailing are chosen in the settings.
// 4. Takes the same measurement for random entries on the same chart, in the same
//    direction, with a stop the same number of ATRs away, trailed the same way.
// Nothing here is a trade signal.
// ─────────────────────────────────────────────────────────────────────────────
 
// ── Inputs ───────────────────────────────────────────────────────────────────
G0 = "Patterns"
useLines = input.bool(true, "Triangles, wedges, channels, rectangles", group = G0)
useRev   = input.bool(false, "Head & shoulders, double tops and bottoms", group = G0)
useFlags = input.bool(false, "Flags and pennants", group = G0)
 
G1 = "Detection"
pivLen  = input.int(5, "Pivot length (bars each side)", minval = 3, maxval = 8, group = G1, display = display.none)
tolPct  = input.float(10.0, "Line patterns: touch tolerance (% of height)", minval = 2, maxval = 30, step = 1, group = G1, display = display.none)
minBars = input.int(15, "Line patterns: minimum width (bars)", minval = 10, maxval = 100, group = G1, display = display.none)
revTol  = input.float(20.0, "Double top/bottom: peak tolerance (% of height)", minval = 5, maxval = 50, step = 5, group = G1, display = display.none)
revMinH = input.float(1.5, "Reversal patterns: minimum height (× ATR)", minval = 0.5, maxval = 10, step = 0.5, group = G1, display = display.none)
flagK   = input.float(4.0, "Flags: minimum pole (× ATR, within 10 bars)", minval = 2, maxval = 15, step = 0.5, group = G1, display = display.none)
 
G2 = "Stop"
SL_ATR   = "ATR multiple"
SL_SWING = "Previous swing"
SL_FAR   = "Pattern far side"
SL_MID   = "Pattern middle"
slMode  = input.string(SL_ATR, "Stop type", options = [SL_ATR, SL_SWING, SL_FAR, SL_MID], tooltip = "Where the first stop sits, measured from the breakout close. 1 R is the distance to it.\n\nATR multiple: the multiple of ATR(14) set below.\nPrevious swing: the last confirmed swing low before an upward break, or swing high before a downward break.\nPattern far side: the pattern's opposite boundary at the breakout bar.\nPattern middle: halfway between the two boundaries at the breakout bar.\n\nThe stop is never closer than 0.25 ATR.", group = G2, display = display.none)
atrMult = input.float(1.0, "ATR multiple (for the ATR stop)", minval = 0.25, maxval = 5, step = 0.25, group = G2, display = display.none)
 
TR_NONE = "None"
TR_BE   = "Breakeven after trigger"
TR_STEP = "Step up every 1 R"
TR_ATR  = "ATR trail"
TR_BAR  = "N-bar low/high"
trMode    = input.string(TR_NONE, "Trailing", options = [TR_NONE, TR_BE, TR_STEP, TR_ATR, TR_BAR], tooltip = "How the stop moves after the break. It only ever moves in the break's favour.\n\nNone: the stop stays where it started.\nBreakeven after trigger: the stop moves to the breakout price once the move reaches the trigger below.\nStep up every 1 R: each full R gained moves the stop up by 1 R (at +2 R the stop is at +1 R).\nATR trail: the stop follows the best price since the break, the ATR multiple below behind it.\nN-bar low/high: the stop follows the lowest low of the last N bars (upward break) or the highest high (downward break).", group = G2, display = display.none)
beTrig    = input.float(1.0, "Breakeven trigger (R)", minval = 0.25, maxval = 5, step = 0.25, group = G2, display = display.none)
trailMult = input.float(2.0, "ATR trail multiple", minval = 0.5, maxval = 10, step = 0.25, group = G2, display = display.none)
trailN    = input.int(10, "N for the N-bar trail", minval = 2, maxval = 100, group = G2, display = display.none)
 
G4 = "Record"
RES_BEST = "Best move"
RES_EXIT = "Exit"
resMode = input.string(RES_EXIT, "Result shown", options = [RES_EXIT, RES_BEST], tooltip = "Exit: the R at the exit. That is the stop price when the stop was hit (a gap through the stop counts at the open), or the close when the time limit ended. A break stopped at its first stop counts as -1 R.\n\nBest move: the best R reached in the break direction before the stop was hit or the time limit ended. It can never be negative.", group = G4, display = display.none)
nRand   = input.int(5, "Random entries per breakout", minval = 1, maxval = 10, group = G4, display = display.none)
seed    = input.int(7, "Random seed", minval = 1, group = G4, display = display.none)
minN    = input.int(20, "Mark figures with fewer cases than (*)", minval = 5, group = G4, display = display.none)
 
G3 = "Display"
showDev    = input.bool(true, "Draw developing line patterns", group = G3)
showLevels = input.bool(true, "Draw the stop after a breakout", group = G3)
showRec    = input.bool(true, "Table: record by pattern", group = G3)
showLive   = input.bool(true, "Table: current patterns", group = G3)
showFoot   = input.bool(false, "Table: full notes", tooltip = "The same explanations appear when you hover over the table's column titles.", group = G3)
txtIn      = input.string("Small", "Table text size", options = ["Small", "Normal", "Large"], group = G3, display = display.none)
posIn      = input.string("Top right", "Table position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Bottom left"], group = G3, display = display.none)
 
ts   = txtIn == "Small" ? size.small : txtIn == "Large" ? size.large : size.normal
tpos = posIn == "Top right" ? position.top_right : posIn == "Middle right" ? position.middle_right : posIn == "Bottom right" ? position.bottom_right : posIn == "Top left" ? position.top_left : position.bottom_left
bool showExit = resMode == RES_EXIT
 
// ── Colours ──────────────────────────────────────────────────────────────────
C_BG  = #0E1117
C_HD  = #1C2A4D
C_LB  = #FFD54F
C_TX  = #FFFFFF
C_UP  = #40C4FF
C_LO  = #EA80FC
C_OK  = #00E676
C_AM  = #FFC400
C_BAD = #FF5252
 
MAXW   = 300    // widest line pattern considered, in bars
MINR   = 0.25   // smallest stop distance, in ATR
F_P    = 10     // flags: longest pole, in bars
F_WMIN = 5      // flags: bars of pause before the flag is recognised
F_WMAX = 20     // flags: longest pause, in bars
F_RETR = 0.5    // flags: largest retracement of the pole
NF     = 14     // number of pattern families
 
// ── Names ────────────────────────────────────────────────────────────────────
var array<string> TYPES = array.from("Rectangle", "Ascending triangle", "Descending triangle", "Symmetrical triangle", "Rising wedge", "Falling wedge", "Rising channel", "Falling channel", "Broadening")
// families: 0 rising wedge/channel, 1 falling wedge/channel, 2 rectangle/symmetrical, 3 ascending triangle,
// 4 descending triangle, 5 broadening, 6 head & shoulders, 7 inverse head & shoulders, 8 double top,
// 9 double bottom, 10 bull flag, 11 bear flag, 12 bull pennant, 13 bear pennant
var array<string> FAMS   = array.from("Rising", "Falling", "Flat/Sym", "Asc tri", "Desc tri", "Broaden", "H&S", "Inv H&S", "Dbl top", "Dbl bottom", "Bull flag", "Bear flag", "Bull pennant", "Bear pennant")
var array<string> FAMTIP = array.from("Rising wedges and rising channels. Textbook: bearish.", "Falling wedges and falling channels. Textbook: bullish.", "Rectangles and symmetrical triangles. Textbook: either way.", "Ascending triangles. Textbook: bullish.", "Descending triangles. Textbook: bearish.", "Broadening shapes: the lines move apart. Textbook: either way.", "Head and shoulders: a higher middle peak between two lower ones. The row counts closes below the neckline. Textbook: bearish. Counted only when price is still inside the pattern at the bar it is recognised.", "Inverse head and shoulders. The row counts closes above the neckline. Textbook: bullish. Counted only when price is still inside the pattern at the bar it is recognised.", "Double top: two peaks at about the same level. The row counts closes below the low between them. Textbook: bearish. Counted only when price is still inside the pattern at the bar it is recognised.", "Double bottom: two lows at about the same level. The row counts closes above the high between them. Textbook: bullish. Counted only when price is still inside the pattern at the bar it is recognised.", "Bull flag: a sharp rise, then a short pause between roughly parallel lines. The row counts closes above the pause. Textbook: bullish.", "Bear flag: a sharp fall, then a short pause. The row counts closes below the pause. Textbook: bearish.", "Bull pennant: a sharp rise, then a short pause that narrows. Textbook: bullish.", "Bear pennant: a sharp fall, then a short pause that narrows. Textbook: bearish.")
var array<string> QTRS   = array.from("bottom quarter", "lower middle", "upper middle", "top quarter")
 
// table rows: family and direction (0 up, 1 down)
var array<int> ROWF = array.new_int()
var array<int> ROWD = array.new_int()
f_addRow(int f, int d) =>
    ROWF.push(f)
    ROWD.push(d)
if barstate.isfirst
    if useLines
        f_addRow(1, 0)
        f_addRow(1, 1)
        f_addRow(3, 0)
        f_addRow(3, 1)
        f_addRow(0, 0)
        f_addRow(0, 1)
        f_addRow(4, 0)
        f_addRow(4, 1)
        f_addRow(2, 0)
        f_addRow(2, 1)
        f_addRow(5, 0)
        f_addRow(5, 1)
    if useRev
        f_addRow(6, 1)
        f_addRow(8, 1)
        f_addRow(7, 0)
        f_addRow(9, 0)
    if useFlags
        f_addRow(10, 0)
        f_addRow(12, 0)
        f_addRow(11, 1)
        f_addRow(13, 1)
 
// ── Record (all on closed bars) ──────────────────────────────────────────────
var int nCand     = 0   // developing line patterns that have resolved
var int nCandConf = 0   // of those, confirmed by a fifth touch
var array<int>   nConf   = array.new_int(NF, 0)          // confirmed patterns resolved, by family
var array<int>   nBroke  = array.new_int(NF, 0)          // broke out (either way)
var array<int>   nUp     = array.new_int(NF, 0)          // broke out upward
// family × direction, index = family × 2 + (0 up, 1 down)
var array<int>   nRes    = array.new_int(NF * 2, 0)      // breaks with a finished measurement
var array<float> sReach  = array.new_float(NF * 2, 0)    // sum of best move, in R
var array<float> sExit   = array.new_float(NF * 2, 0)    // sum of exit, in R
var array<int>   rN      = array.new_int(NF * 2, 0)      // random entries
var array<float> rReach  = array.new_float(NF * 2, 0)
var array<float> rExit   = array.new_float(NF * 2, 0)
var array<int>   posN    = array.new_int(4, 0)           // line patterns: breakouts by price position before the break
var array<int>   posUp   = array.new_int(4, 0)
var array<int>   timeN   = array.new_int(4, 0)           // line patterns: alive in each quarter of the window
var array<int>   timeExp = array.new_int(4, 0)           // of those, expired with no breakout
 
// ── One tracked pattern ──────────────────────────────────────────────────────
type Pat
    int    st = 0        // 0 none, 1 developing (line patterns only), 2 confirmed, 3 broken out
    int    fam = 0
    string name = ""
    int    ux1 = 0       // upper boundary: a line through two points
    float  uy1 = 0.0
    int    ux2 = 1
    float  uy2 = 0.0
    int    lx1 = 0       // lower boundary
    float  ly1 = 0.0
    int    lx2 = 1
    float  ly2 = 0.0
    int    dxU = 0       // bar where each boundary starts on the chart
    int    dxL = 0
    int    x0 = 0        // first bar of the pattern
    int    xc = 0        // bar the breakout window is counted from
    int    width = 0
    int    dead = 0      // last bar of the breakout window
    int    dir = 0       // 1 broke up, -1 broke down
    float  eP = 0.0      // breakout close
    float  eR = 1.0      // first stop distance in price = 1 R
    float  eStop = 0.0   // current stop price
    float  eExt = 0.0    // best price since the break
    int    eBar = 0
    int    eHor = 0      // time limit in bars
    float  eMfe = 0.0    // best move so far, in R
    line   uLn
    line   lLn
    line   tLn
    label  lb
    array<bool> vPos
    array<bool> vTime
 
f_newPat() =>
    Pat p = Pat.new()
    p.vPos := array.new_bool(4, false)
    p.vTime := array.new_bool(4, false)
    p
 
var Pat A = f_newPat()   // line patterns
var Pat B = f_newPat()   // reversal patterns
var Pat C = f_newPat()   // flags and pennants
 
// extra state for the line-pattern detector
var int   cD0  = 0       // first pivot side: 1 high, -1 low
var float cTol = na
// extra state for the flag detector
var int   fS0  = 0       // bar of the pole's end
var int   fSg  = 1       // 1 bull, -1 bear
 
// ── Series ───────────────────────────────────────────────────────────────────
var array<int>   zx = array.new_int()
var array<float> zy = array.new_float()
var array<int>   zd = array.new_int()
 
atr = ta.atr(14)
ph  = ta.pivothigh(high, pivLen, pivLen)
pl  = ta.pivotlow(low, pivLen, pivLen)
loN = ta.lowest(low, trailN)
hiN = ta.highest(high, trailN)
 
// ── Helpers ──────────────────────────────────────────────────────────────────
// 1 = new pivot added, 2 = last pivot replaced by a more extreme one, 0 = nothing
f_zz(int d, float p, int x) =>
    int r = 0
    int n = zx.size()
    if n == 0 or zd.last() != d
        zx.push(x)
        zy.push(p)
        zd.push(d)
        r := 1
    else if (d == 1 and p > zy.last()) or (d == -1 and p < zy.last())
        zx.set(n - 1, x)
        zy.set(n - 1, p)
        r := 2
    if zx.size() > 40
        zx.shift()
        zy.shift()
        zd.shift()
    r
 
// last confirmed swing on one side: side = 1 for a swing high, -1 for a swing low
f_lastSwing(int side) =>
    float v = na
    int n = zx.size()
    if n > 0
        for i = n - 1 to 0
            if zd.get(i) == side
                v := zy.get(i)
                break
    v
 
// new stop after a bar that did not hit the stop; it only moves in the break's favour
f_trail(int dir, float e, float r1, float cur, float mfeR, float ext, float a, float nb) =>
    float cand = cur
    if trMode == TR_BE
        if mfeR >= beTrig
            cand := e
    else if trMode == TR_STEP
        if mfeR >= 1
            cand := e + dir * (math.floor(mfeR) - 1) * r1
    else if trMode == TR_ATR
        cand := ext - dir * trailMult * a
    else if trMode == TR_BAR
        cand := nb
    if na(cand)
        cand := cur
    dir == 1 ? math.max(cur, cand) : math.min(cur, cand)
 
f_y(int x1, float y1, int x2, float y2, int x) =>
    y1 + (y2 - y1) * (x - x1) / (x2 - x1)
 
f_up(Pat p, int x) =>
    f_y(p.ux1, p.uy1, p.ux2, p.uy2, x)
 
f_lo(Pat p, int x) =>
    f_y(p.lx1, p.ly1, p.lx2, p.ly2, x)
 
f_inc(array<int> a, int i) =>
    a.set(i, a.get(i) + 1)
 
f_add(array<float> a, int i, float v) =>
    a.set(i, a.get(i) + v)
 
f_ix(int fam, int dir) =>
    fam * 2 + (dir == 1 ? 0 : 1)
 
f_clamp4(float v) =>
    math.max(0, math.min(3, int(math.floor(v))))
 
f_type(float uMove, float lMove, float hS, float hE) =>
    float flat = 0.25 * (hS + hE) / 2
    bool uF = math.abs(uMove) < flat
    bool lF = math.abs(lMove) < flat
    int t = 0
    if hE > 1.4 * hS
        t := 8
    else if hE < 0.7 * hS
        t := (uF and lF) ? 3 : (uF and lMove > 0) ? 1 : (lF and uMove < 0) ? 2 : (uMove > 0 and lMove > 0) ? 4 : (uMove < 0 and lMove < 0) ? 5 : 3
    else
        float m = (uMove + lMove) / 2
        t := (uF and lF) ? 0 : m > flat ? 6 : m < -flat ? 7 : 0
    t
 
f_fam(int t) =>
    (t == 4 or t == 6) ? 0 : (t == 5 or t == 7) ? 1 : (t == 0 or t == 3) ? 2 : t == 1 ? 3 : t == 2 ? 4 : 5
 
f_drop(Pat p) =>
    line.delete(p.uLn)
    line.delete(p.lLn)
    label.delete(p.lb)
 
// redraw both boundaries up to the current bar
f_draw(Pat p) =>
    line.set_xy1(p.uLn, p.dxU, f_up(p, p.dxU))
    line.set_xy2(p.uLn, bar_index, f_up(p, bar_index))
    line.set_xy1(p.lLn, p.dxL, f_lo(p, p.dxL))
    line.set_xy2(p.lLn, bar_index, f_lo(p, bar_index))
 
// Random entries: random earlier bars of this chart, same direction, a first stop
// the same number of ATRs away (stopAtr), the same trailing and the same time limit.
f_rand(int dir, int hor, int fam, float stopAtr) =>
    int maxK = math.min(bar_index, 4900)
    if maxK > hor + 50
        for s = 1 to nRand
            int k = int(math.random(hor + 1, maxK, seed))
            float r1 = atr[k] * stopAtr
            float e = close[k]
            if not na(r1) and r1 > 0
                float sp = e - dir * r1
                float mfe = 0.0
                float ext = e
                float ex = e
                for j = 1 to hor
                    int o = k - j
                    float h = high[o]
                    float l = low[o]
                    if (dir == 1 and l <= sp) or (dir == -1 and h >= sp)
                        ex := dir == 1 ? math.min(open[o], sp) : math.max(open[o], sp)
                        break
                    mfe := math.max(mfe, dir == 1 ? (h - e) / r1 : (e - l) / r1)
                    ext := dir == 1 ? math.max(ext, h) : math.min(ext, l)
                    if j == hor
                        ex := close[o]
                    else
                        sp := f_trail(dir, e, r1, sp, mfe, ext, atr[o], dir == 1 ? loN[o] : hiN[o])
                f_inc(rN, f_ix(fam, dir))
                f_add(rReach, f_ix(fam, dir), mfe)
                f_add(rExit, f_ix(fam, dir), dir * (ex - e) / r1)
 
// A confirmed pattern on one closed bar: window ended, still inside, or broken.
// Returns 1 for a break up, -1 for a break down, 0 otherwise.
f_step(Pat p, bool trackPos) =>
    int ev = 0
    float upNow = f_up(p, bar_index)
    float loNow = f_lo(p, bar_index)
    if upNow <= loNow or bar_index > p.dead
        f_inc(nConf, p.fam)
        if trackPos
            for i = 0 to 3
                if p.vTime.get(i)
                    f_inc(timeN, i)
                    f_inc(timeExp, i)
        label.set_text(p.lb, p.name + " · no breakout")
        p.st := 0
    else
        if trackPos
            p.vTime.set(f_clamp4(4.0 * (bar_index - p.xc) / (p.dead - p.xc)), true)
        int dir = close > upNow ? 1 : close < loNow ? -1 : 0
        if dir == 0
            if trackPos
                p.vPos.set(f_clamp4(4.0 * (close - loNow) / (upNow - loNow)), true)
        else
            f_inc(nConf, p.fam)
            f_inc(nBroke, p.fam)
            if dir == 1
                f_inc(nUp, p.fam)
            if trackPos
                for i = 0 to 3
                    if p.vPos.get(i)
                        f_inc(posN, i)
                        if dir == 1
                            f_inc(posUp, i)
                    if p.vTime.get(i)
                        f_inc(timeN, i)
            // first stop for the chosen stop type
            float rawStop = close - dir * atr * atrMult
            if slMode == SL_SWING
                rawStop := f_lastSwing(-dir)
            else if slMode == SL_FAR
                rawStop := dir == 1 ? loNow : upNow
            else if slMode == SL_MID
                rawStop := (upNow + loNow) / 2
            float dist = dir * (close - rawStop)
            if na(dist)
                dist := atr * atrMult
            dist := math.max(dist, MINR * atr)
            p.dir   := dir
            p.eP    := close
            p.eR    := dist
            p.eStop := close - dir * dist
            p.eExt  := close
            p.eBar  := bar_index
            p.eHor  := math.max(20, math.min(120, 2 * p.width))
            p.eMfe  := 0.0
            f_rand(dir, p.eHor, p.fam, dist / atr)
            label.set_text(p.lb, p.name + (dir == 1 ? " · broke up" : " · broke down"))
            p.tLn := na
            if showLevels
                label.new(bar_index, close, "", style = label.style_circle, color = C_AM, size = size.tiny)
                int fx = f_ix(p.fam, dir)
                if not showExit and nRes.get(fx) > 0
                    float avgLvl = p.eP + dir * p.eR * sReach.get(fx) / nRes.get(fx)
                    p.tLn := line.new(bar_index, avgLvl, bar_index + 10, avgLvl, color = C_OK, width = 2, style = line.style_dotted)
            p.st := 3
            ev := dir
    ev
 
// After a break: follow price until the stop is hit or the time limit ends.
f_measure(Pat p) =>
    if bar_index > p.eBar
        bool hs = p.dir == 1 ? low <= p.eStop : high >= p.eStop
        float exitP = na
        if hs
            exitP := p.dir == 1 ? math.min(open, p.eStop) : math.max(open, p.eStop)
        else
            p.eMfe := math.max(p.eMfe, p.dir == 1 ? (high - p.eP) / p.eR : (p.eP - low) / p.eR)
            p.eExt := p.dir == 1 ? math.max(p.eExt, high) : math.min(p.eExt, low)
            if bar_index - p.eBar >= p.eHor
                exitP := close
            else
                p.eStop := f_trail(p.dir, p.eP, p.eR, p.eStop, p.eMfe, p.eExt, atr, p.dir == 1 ? loN : hiN)
        if not na(exitP)
            float exitR = p.dir * (exitP - p.eP) / p.eR
            f_inc(nRes, f_ix(p.fam, p.dir))
            f_add(sReach, f_ix(p.fam, p.dir), p.eMfe)
            f_add(sExit, f_ix(p.fam, p.dir), exitR)
            label.set_text(p.lb, p.name + (p.dir == 1 ? " · broke up" : " · broke down") + " · best " + str.tostring(p.eMfe, "#0.0") + " R · exit " + (exitR > 0 ? "+" : "") + str.tostring(exitR, "#0.0") + " R" + (hs ? "" : " (time limit)"))
            line.set_x2(p.tLn, bar_index)
            p.st := 0
 
// Reversal patterns from the latest pivots. s = 1 when the newest pivot is a high
// (head & shoulders, double top), -1 when it is a low (the inverse forms).
f_revDetect(Pat p) =>
    bool found = false
    int n = zx.size()
    if n >= 4 and not na(atr)
        int s = zd.get(n - 1)
        if n >= 6
            int xRS = zx.get(n - 1)
            int xN2 = zx.get(n - 2)
            int xHD = zx.get(n - 3)
            int xN1 = zx.get(n - 4)
            int xLS = zx.get(n - 5)
            float RS = s * zy.get(n - 1)
            float N2 = s * zy.get(n - 2)
            float HD = s * zy.get(n - 3)
            float N1 = s * zy.get(n - 4)
            float LS = s * zy.get(n - 5)
            float L0 = s * zy.get(n - 6)
            float hg = HD - f_y(xN1, N1, xN2, N2, xHD)
            float sL = LS - f_y(xN1, N1, xN2, N2, xLS)
            float sR = RS - f_y(xN1, N1, xN2, N2, xRS)
            int dl = xHD - xLS
            int dr = xRS - xHD
            if hg >= revMinH * atr and sL >= 0.3 * hg and sL <= 0.85 * hg and sR >= 0.3 * hg and sR <= 0.85 * hg and math.abs(N1 - N2) <= 0.35 * hg and dl <= 3 * dr and dr <= 3 * dl and xRS - xLS >= 15 and L0 < math.min(N1, N2) and s * close <= RS and s * close >= f_y(xN1, N1, xN2, N2, bar_index)
                found := true
                p.fam  := s == 1 ? 6 : 7
                p.name := s == 1 ? "Head & shoulders" : "Inverse head & shoulders"
                if s == 1
                    // upper boundary = right shoulder level, lower boundary = neckline
                    p.ux1 := xRS
                    p.uy1 := zy.get(n - 1)
                    p.ux2 := xRS + 1
                    p.uy2 := zy.get(n - 1)
                    p.lx1 := xN1
                    p.ly1 := zy.get(n - 4)
                    p.lx2 := xN2
                    p.ly2 := zy.get(n - 2)
                    p.dxU := xRS
                    p.dxL := xN1
                else
                    // upper boundary = neckline, lower boundary = right shoulder level
                    p.ux1 := xN1
                    p.uy1 := zy.get(n - 4)
                    p.ux2 := xN2
                    p.uy2 := zy.get(n - 2)
                    p.lx1 := xRS
                    p.ly1 := zy.get(n - 1)
                    p.lx2 := xRS + 1
                    p.ly2 := zy.get(n - 1)
                    p.dxU := xN1
                    p.dxL := xRS
                p.x0    := xLS
                p.xc    := xRS
                p.width := xRS - xLS
                p.dead  := xRS + p.width
                // outline of the shoulders and head
                line.new(xLS, zy.get(n - 5), xN1, zy.get(n - 4), color = C_AM)
                line.new(xN1, zy.get(n - 4), xHD, zy.get(n - 3), color = C_AM)
                line.new(xHD, zy.get(n - 3), xN2, zy.get(n - 2), color = C_AM)
                line.new(xN2, zy.get(n - 2), xRS, zy.get(n - 1), color = C_AM)
                p.lb := label.new(xHD, zy.get(n - 3), p.name, style = s == 1 ? label.style_label_down : label.style_label_up, color = C_HD, textcolor = C_TX, size = size.small)
        if not found
            int xH2 = zx.get(n - 1)
            int xLM = zx.get(n - 2)
            int xH1 = zx.get(n - 3)
            float H2 = s * zy.get(n - 1)
            float LM = s * zy.get(n - 2)
            float H1 = s * zy.get(n - 3)
            float L0 = s * zy.get(n - 4)
            float hg = (H1 + H2) / 2 - LM
            int w = xH2 - xH1
            if hg >= revMinH * atr and math.abs(H1 - H2) <= revTol / 100 * hg and w >= 10 and L0 <= LM - 0.5 * hg and s * close <= math.max(H1, H2) and s * close >= LM
                found := true
                p.fam  := s == 1 ? 8 : 9
                p.name := s == 1 ? "Double top" : "Double bottom"
                float failPx = s * math.max(H1, H2)
                float neckPx = zy.get(n - 2)
                p.ux1 := xH1
                p.uy1 := s == 1 ? failPx : neckPx
                p.ux2 := xH2
                p.uy2 := s == 1 ? failPx : neckPx
                p.lx1 := xH1
                p.ly1 := s == 1 ? neckPx : failPx
                p.lx2 := xH2
                p.ly2 := s == 1 ? neckPx : failPx
                p.dxU := xH1
                p.dxL := xH1
                p.x0    := xH1
                p.xc    := xH2
                p.width := w
                p.dead  := xH2 + w
                line.new(xH1, zy.get(n - 3), xLM, zy.get(n - 2), color = C_AM)
                line.new(xLM, zy.get(n - 2), xH2, zy.get(n - 1), color = C_AM)
                p.lb := label.new(xH2, zy.get(n - 1), p.name, style = s == 1 ? label.style_label_down : label.style_label_up, color = C_HD, textcolor = C_TX, size = size.small)
    if found
        p.uLn := line.new(p.dxU, f_up(p, p.dxU), bar_index, f_up(p, bar_index), color = C_UP, width = 2)
        p.lLn := line.new(p.dxL, f_lo(p, p.dxL), bar_index, f_lo(p, bar_index), color = C_LO, width = 2)
        p.st := 2
    found
 
// Flag check on this bar: was the bar F_WMIN bars back the end of a pole?
// g = 1 looks for a bull flag, -1 for a bear flag. Returns the pole size (na if none)
// and how many bars back the pole started.
f_flagCheck(int g) =>
    float top = g == 1 ? high[F_WMIN] : -low[F_WMIN]
    bool ok = true
    float plo = na
    int ploOff = F_WMIN
    for off = F_WMIN + F_P to 0
        float qh = g == 1 ? high[off] : -low[off]
        float ql = g == 1 ? low[off] : -high[off]
        if off != F_WMIN and qh > top
            ok := false
            break
        if off >= F_WMIN and (na(plo) or ql < plo)
            plo := ql
            ploOff := off
    float pole = na
    if ok
        float a0 = atr[F_WMIN + F_P]
        float sz = top - plo
        if not na(a0) and sz >= flagK * a0
            bool deep = false
            for off = F_WMIN - 1 to 0
                float ql = g == 1 ? low[off] : -high[off]
                if ql < top - F_RETR * sz
                    deep := true
                    break
            if not deep
                pole := sz
    [pole, ploOff]
 
// Fit lines to the highs and lows of the pause (bars s0+1 .. previous bar) and
// store them as the pattern's boundaries. Sets flag or pennant from how much they narrow.
f_flagFit(Pat p, int s0, int g) =>
    int m = bar_index - 1 - s0
    float sx = 0.0
    float sxx = 0.0
    float syh = 0.0
    float sxyh = 0.0
    float syl = 0.0
    float sxyl = 0.0
    for i = s0 + 1 to bar_index - 1
        int off = bar_index - i
        float x = i - s0
        float qh = g == 1 ? high[off] : -low[off]
        float ql = g == 1 ? low[off] : -high[off]
        sx += x
        sxx += x * x
        syh += qh
        sxyh += x * qh
        syl += ql
        sxyl += x * ql
    float den = m * sxx - sx * sx
    float mU = (m * sxyh - sx * syh) / den
    float mL = (m * sxyl - sx * syl) / den
    float aU = na
    float aL = na
    for i = s0 + 1 to bar_index - 1
        int off = bar_index - i
        float x = i - s0
        float qh = g == 1 ? high[off] : -low[off]
        float ql = g == 1 ? low[off] : -high[off]
        aU := na(aU) ? qh - mU * x : math.max(aU, qh - mU * x)
        aL := na(aL) ? ql - mL * x : math.min(aL, ql - mL * x)
    float x2 = bar_index - s0
    float u1 = aU + mU
    float u2 = aU + mU * x2
    float l1 = aL + mL
    float l2 = aL + mL * x2
    p.ux1 := s0 + 1
    p.ux2 := bar_index
    p.lx1 := s0 + 1
    p.lx2 := bar_index
    p.uy1 := g == 1 ? u1 : -l1
    p.uy2 := g == 1 ? u2 : -l2
    p.ly1 := g == 1 ? l1 : -u1
    p.ly2 := g == 1 ? l2 : -u2
    float hS = u1 - l1
    float hE = (aU + mU * (x2 - 1)) - (aL + mL * (x2 - 1))
    bool pen = hE < 0.7 * hS
    p.fam  := (pen ? 12 : 10) + (g == 1 ? 0 : 1)
    p.name := (g == 1 ? "Bull " : "Bear ") + (pen ? "pennant" : "flag")
 
// ── Pivot events ─────────────────────────────────────────────────────────────
int evH = 0
int evL = 0
if barstate.isconfirmed
    int px = bar_index - pivLen
    if zd.size() > 0 and zd.last() == 1
        if not na(pl)
            evL := f_zz(-1, pl, px)
        if not na(ph)
            evH := f_zz(1, ph, px)
    else
        if not na(ph)
            evH := f_zz(1, ph, px)
        if not na(pl)
            evL := f_zz(-1, pl, px)
 
bool added    = evH == 1 or evL == 1
bool replaced = not added and (evH == 2 or evL == 2)
bool evConf   = false
bool evUp     = false
bool evDown   = false
bool reform   = false
 
// ═════════════ Detector 1: line patterns ═════════════
// stage 1: developing
if barstate.isconfirmed and A.st == 1
    float upNow = f_up(A, bar_index)
    float loNow = f_lo(A, bar_index)
    if close > upNow + cTol or close < loNow - cTol or upNow <= loNow or bar_index - A.x0 > MAXW
        nCand += 1
        f_drop(A)
        A.st := 0
    else if added
        int n  = zx.size()
        int ix = (evH == 1 and evL == 1) ? n - 2 : n - 1
        int x4 = zx.get(ix)
        float y4 = zy.get(ix)
        float lv = cD0 == 1 ? f_up(A, x4) : f_lo(A, x4)
        float hS = f_up(A, A.x0) - f_lo(A, A.x0)
        float hE = f_up(A, x4) - f_lo(A, x4)
        nCand += 1
        if math.abs(y4 - lv) <= cTol and x4 - A.x0 >= minBars and hE > 0
            float uMove = f_up(A, x4) - f_up(A, A.x0)
            float lMove = f_lo(A, x4) - f_lo(A, A.x0)
            int t = f_type(uMove, lMove, hS, hE)
            A.name  := TYPES.get(t)
            A.fam   := f_fam(t)
            A.xc    := x4
            A.width := x4 - A.x0
            A.dead  := x4 + A.width
            nCandConf += 1
            A.vPos.fill(false)
            A.vTime.fill(false)
            line.set_style(A.uLn, line.style_solid)
            line.set_style(A.lLn, line.style_solid)
            line.set_color(A.uLn, C_UP)
            line.set_color(A.lLn, C_LO)
            f_draw(A)
            linefill.new(A.uLn, A.lLn, color.new(C_UP, 90))
            label.set_text(A.lb, A.name)
            label.set_textcolor(A.lb, C_TX)
            label.set_color(A.lb, C_HD)
            A.st := 2
            evConf := true
        else
            f_drop(A)
            A.st := 0
    else if replaced
        reform := true
        f_drop(A)
        A.st := 0
    else
        f_draw(A)
 
// stage 2: confirmed
if barstate.isconfirmed and A.st == 2
    f_draw(A)
    int e = f_step(A, true)
    if e == 1
        evUp := true
    if e == -1
        evDown := true
 
// stage 3: after the break
if barstate.isconfirmed and A.st == 3
    f_measure(A)
 
// new developing pattern from the last four pivots
bool formed = false
if barstate.isconfirmed and useLines and A.st == 0 and (added or replaced or reform) and zx.size() >= 4
    int n  = zx.size()
    int x0 = zx.get(n - 4)
    int x1 = zx.get(n - 3)
    int x2 = zx.get(n - 2)
    int x3 = zx.get(n - 1)
    float y0 = zy.get(n - 4)
    float y1 = zy.get(n - 3)
    float y2 = zy.get(n - 2)
    float y3 = zy.get(n - 1)
    int d0 = zd.get(n - 4)
    int hxa = d0 == 1 ? x0 : x1
    int hxb = d0 == 1 ? x2 : x3
    int lxa = d0 == 1 ? x1 : x0
    int lxb = d0 == 1 ? x3 : x2
    float hya = d0 == 1 ? y0 : y1
    float hyb = d0 == 1 ? y2 : y3
    float lya = d0 == 1 ? y1 : y0
    float lyb = d0 == 1 ? y3 : y2
    int w = x3 - x0
    if w >= 10 and w <= MAXW
        float hS = f_y(hxa, hya, hxb, hyb, x0) - f_y(lxa, lya, lxb, lyb, x0)
        float hE = f_y(hxa, hya, hxb, hyb, x3) - f_y(lxa, lya, lxb, lyb, x3)
        float hN = f_y(hxa, hya, hxb, hyb, bar_index) - f_y(lxa, lya, lxb, lyb, bar_index)
        float avgH = (hS + hE) / 2
        if hS > 0 and hE > 0 and hN > 0 and avgH >= atr
            float tol = tolPct / 100 * avgH
            bool good = true
            for i = 0 to bar_index - x0
                int xb = bar_index - i
                float c = close[i]
                if c > f_y(hxa, hya, hxb, hyb, xb) + tol or c < f_y(lxa, lya, lxb, lyb, xb) - tol
                    good := false
                    break
            if good
                A.x0  := x0
                A.dxU := x0
                A.dxL := x0
                A.ux1 := hxa
                A.uy1 := hya
                A.ux2 := hxb
                A.uy2 := hyb
                A.lx1 := lxa
                A.ly1 := lya
                A.lx2 := lxb
                A.ly2 := lyb
                cD0  := d0
                cTol := tol
                A.uLn := line.new(x0, f_up(A, x0), bar_index, f_up(A, bar_index), color = color.new(C_UP, showDev ? 20 : 100), style = line.style_dashed, width = 2)
                A.lLn := line.new(x0, f_lo(A, x0), bar_index, f_lo(A, bar_index), color = color.new(C_LO, showDev ? 20 : 100), style = line.style_dashed, width = 2)
                A.lb  := label.new(x0, f_up(A, x0), showDev ? "Developing" : "", style = label.style_label_down, color = color.new(C_HD, showDev ? 0 : 100), textcolor = C_LB, size = size.small)
                A.st := 1
                formed := true
if reform and not formed
    nCand += 1
 
// ═════════════ Detector 2: head & shoulders, double tops and bottoms ═════════════
if barstate.isconfirmed and B.st == 3
    f_measure(B)
if barstate.isconfirmed and useRev and B.st == 0 and (added or replaced)
    if f_revDetect(B)
        evConf := true
if barstate.isconfirmed and B.st == 2
    f_draw(B)
    int e = f_step(B, false)
    if e == 1
        evUp := true
    if e == -1
        evDown := true
 
// ═════════════ Detector 3: flags and pennants ═════════════
if barstate.isconfirmed and C.st == 3
    f_measure(C)
if barstate.isconfirmed and C.st == 2
    f_flagFit(C, fS0, fSg)
    C.width := bar_index - fS0 + F_P
    f_draw(C)
    label.set_text(C.lb, C.name)
    int e = f_step(C, false)
    if e == 1
        evUp := true
    if e == -1
        evDown := true
if barstate.isconfirmed and useFlags and C.st == 0 and bar_index > F_WMIN + F_P + 20
    for k = 0 to 1
        int g = k == 0 ? 1 : -1
        [pole, ploOff] = f_flagCheck(g)
        if not na(pole)
            fS0 := bar_index - F_WMIN
            fSg := g
            f_flagFit(C, fS0, g)
            C.dxU   := fS0 + 1
            C.dxL   := fS0 + 1
            C.x0    := bar_index - ploOff
            C.xc    := fS0
            C.width := F_WMIN + F_P
            C.dead  := fS0 + F_WMAX
            float topPx = g == 1 ? high[F_WMIN] : low[F_WMIN]
            line.new(bar_index - ploOff, g == 1 ? low[ploOff] : high[ploOff], fS0, topPx, color = C_AM, width = 2)
            C.uLn := line.new(C.dxU, f_up(C, C.dxU), bar_index, f_up(C, bar_index), color = C_UP, width = 2)
            C.lLn := line.new(C.dxL, f_lo(C, C.dxL), bar_index, f_lo(C, bar_index), color = C_LO, width = 2)
            C.lb  := label.new(fS0, topPx, C.name, style = g == 1 ? label.style_label_down : label.style_label_up, color = C_HD, textcolor = C_TX, size = size.small)
            C.st := 2
            evConf := true
            break
 
// the stop as it stands on each bar after a breakout (steps when trailing is on)
plot(showLevels and A.st == 3 ? A.eStop : na, "Stop · line pattern", color = C_BAD, linewidth = 2, style = plot.style_linebr, display = display.pane)
plot(showLevels and B.st == 3 ? B.eStop : na, "Stop · reversal pattern", color = C_BAD, linewidth = 2, style = plot.style_linebr, display = display.pane)
plot(showLevels and C.st == 3 ? C.eStop : na, "Stop · flag or pennant", color = C_BAD, linewidth = 2, style = plot.style_linebr, display = display.pane)
 
// ── Table ────────────────────────────────────────────────────────────────────
f_p(int num, int den) =>
    den <= 0 ? "–" : str.tostring(math.round(100.0 * num / den)) + "%" + (den < minN ? "*" : "")
 
f_pn(int num, int den) =>
    den <= 0 ? "– (0)" : f_p(num, den) + " (" + str.tostring(den) + ")"
 
// average in R
f_a(float sum, int den) =>
    den <= 0 ? "–" : str.tostring(sum / den, "#0.00") + (den < minN ? "*" : "")
 
f_an(float sum, int den) =>
    den <= 0 ? "– (0)" : f_a(sum, den) + " (" + str.tostring(den) + ")"
 
f_gap(float s1, int n1, float s2, int n2) =>
    string s = "–"
    if n1 > 0 and n2 > 0
        float g = s1 / n1 - s2 / n2
        s := (g > 0 ? "+" : "") + str.tostring(g, "#0.00")
    s
 
// totals over all families for one direction (off = 0 up, 1 down)
f_sumI(array<int> a, int off) =>
    int s = 0
    for i = 0 to NF - 1
        s += a.get(i * 2 + off)
    s
 
f_sumF(array<float> a, int off) =>
    float s = 0.0
    for i = 0 to NF - 1
        s += a.get(i * 2 + off)
    s
 
f_cell(table t, int c, int r, string s, color tc, color bg) =>
    table.cell(t, c, r, s, text_color = tc, bgcolor = bg, text_size = ts, text_halign = c == 0 ? text.align_left : text.align_right)
 
// cell with a hover explanation
f_tip(table t, int c, int r, string s, color tc, color bg, string tip) =>
    table.cell(t, c, r, s, text_color = tc, bgcolor = bg, text_size = ts, text_halign = c == 0 ? text.align_left : text.align_right, tooltip = tip)
 
f_row(table t, int r, string s, color tc, color bg) =>
    table.cell(t, 0, r, s, text_color = tc, bgcolor = bg, text_size = ts, text_halign = text.align_left)
    table.merge_cells(t, 0, r, 6, r)
 
// one record row: pattern, break direction, confirmed count, share that broke this way, result, random, gap
f_rec(table t, int r, string name, string tip, int di, int nC, int nB, float sR, int nR, float sRr, int nRr, color bg) =>
    f_tip(t, 0, r, name, C_LB, bg, tip)
    f_cell(t, 1, r, di == 0 ? "Up" : "Down", di == 0 ? C_UP : C_LO, bg)
    f_cell(t, 2, r, str.tostring(nC), C_TX, bg)
    f_cell(t, 3, r, f_p(nB, nC), C_TX, bg)
    f_cell(t, 4, r, f_a(sR, nR), C_TX, bg)
    f_cell(t, 5, r, f_a(sRr, nRr), C_TX, bg)
    f_cell(t, 6, r, f_gap(sR, nR, sRr, nRr), C_TX, bg)
 
// live rows for a pattern that has broken out; returns the next free row
f_liveBroken(table t, int r0, Pat p) =>
    int r = r0
    int fx = f_ix(p.fam, p.dir)
    float stopR = p.dir * (p.eStop - p.eP) / p.eR
    array<float> sS = showExit ? sExit : sReach
    array<float> rS = showExit ? rExit : rReach
    f_row(t, r, "Now: " + p.name + (p.dir == 1 ? " · broke up" : " · broke down"), C_LB, C_BG)
    r += 1
    f_row(t, r, "Stop " + str.tostring(p.eStop, format.mintick) + " (" + (stopR > 0 ? "+" : "") + str.tostring(stopR, "#0.0") + " R) · bar " + str.tostring(bar_index - p.eBar) + " of " + str.tostring(p.eHor) + " · best " + str.tostring(p.eMfe, "#0.0") + " R", C_TX, C_BG)
    r += 1
    f_row(t, r, FAMS.get(p.fam) + (p.dir == 1 ? " up" : " down") + (showExit ? " avg exit: " : " avg reach: ") + f_an(sS.get(fx), nRes.get(fx)) + " · random " + f_a(rS.get(fx), rN.get(fx)), C_TX, C_BG)
    r += 1
    r
 
// live rows for a confirmed pattern that has not broken yet; returns the next free row
f_liveWaiting(table t, int r0, Pat p) =>
    int r = r0
    int nC = nConf.get(p.fam)
    int nU = nUp.get(p.fam)
    int nD = nBroke.get(p.fam) - nU
    f_row(t, r, "Now: " + p.name + " · confirmed", C_LB, C_BG)
    r += 1
    f_row(t, r, FAMS.get(p.fam) + " broke up " + f_p(nU, nC) + " · down " + f_p(nD, nC) + " (" + str.tostring(nC) + ")", C_TX, C_BG)
    r += 1
    r
 
string STOP_TXT  = slMode == SL_ATR ? str.tostring(atrMult) + " ATR" : slMode == SL_SWING ? "previous swing" : slMode == SL_FAR ? "pattern far side" : "pattern middle"
string TRAIL_TXT = trMode == TR_NONE ? "no trailing" : trMode == TR_BE ? "breakeven after " + str.tostring(beTrig) + " R" : trMode == TR_STEP ? "step up every 1 R" : trMode == TR_ATR ? str.tostring(trailMult) + " ATR trail" : str.tostring(trailN) + "-bar trail"
string RULES_TXT = "1 R is the distance from the breakout close to the first stop (stop type: " + STOP_TXT + "; trailing: " + TRAIL_TXT + "). Price is followed until the stop is hit or the time limit ends (twice the pattern's width, 20 to 120 bars). Each of the three detectors follows one pattern at a time. "
string TIP_STAR  = "A star (*) marks a figure based on fewer than " + str.tostring(minN) + " cases."
string TIP_TITLE = "This chart's own record of chart patterns, counted on closed bars. Past behaviour; not a recommendation. Hover over a column title or a pattern name for its meaning. " + TIP_STAR
string TIP_PAT   = "Pattern. Hover over a name to see what it is and its textbook direction."
string TIP_BREAK = "Direction of the break: a close above the pattern (Up) or below it (Down). Triangles, wedges, channels and rectangles have a row for each direction. Head and shoulders, double tops and bottoms, flags and pennants show their textbook direction only; their breaks the other way are still counted in the All rows."
string TIP_N     = "Confirmed patterns of this kind on this chart."
string TIP_BROKE = "Share of these confirmed patterns that broke in this row's direction. The rest broke the other way or ended without a break. " + TIP_STAR
string TIP_RES   = showExit ? "Average R at the exit: the stop price when the stop was hit (a gap through the stop counts at the open), or the close when the time limit ended. " + RULES_TXT + TIP_STAR : "Average best move in the break direction, in R, before the stop was hit or the time limit ended. It can never be negative, and a few large moves can lift an average. " + RULES_TXT + TIP_STAR
string TIP_RAND  = "The same measurement for random entries: random earlier bars of this chart, same direction, a first stop the same number of ATRs away, the same trailing and time limit. " + TIP_STAR
string TIP_GAP   = "Pattern figure minus random figure, in R. Near zero means breaks from this pattern did about the same as random entries."
 
var table tb = na
if barstate.islast
    if not na(tb)
        table.delete(tb)
    tb := table.new(tpos, 7, 60, bgcolor = C_BG, frame_color = C_HD, frame_width = 1, border_color = color.new(C_TX, 85), border_width = 1)
    int r = 0
    int tConf = nConf.sum()
    array<float> sShow = showExit ? sExit : sReach
    array<float> rShow = showExit ? rExit : rReach
    table.cell(tb, 0, r, "Pattern Evidence Map · " + timeframe.period + " · " + str.tostring(tConf) + " patterns", text_color = C_TX, bgcolor = C_HD, text_size = ts, text_halign = text.align_left, tooltip = TIP_TITLE)
    table.merge_cells(tb, 0, r, 6, r)
    r += 1
 
    if showRec
        f_tip(tb, 0, r, "Pattern", C_LB, C_HD, TIP_PAT)
        f_tip(tb, 1, r, "Break", C_LB, C_HD, TIP_BREAK)
        f_tip(tb, 2, r, "n", C_LB, C_HD, TIP_N)
        f_tip(tb, 3, r, "Broke", C_LB, C_HD, TIP_BROKE)
        f_tip(tb, 4, r, showExit ? "Exit R" : "Reach R", C_LB, C_HD, TIP_RES)
        f_tip(tb, 5, r, "Rand R", C_LB, C_HD, TIP_RAND)
        f_tip(tb, 6, r, "Gap", C_LB, C_HD, TIP_GAP)
        r += 1
        if ROWF.size() > 0
            for k = 0 to ROWF.size() - 1
                int f  = ROWF.get(k)
                int di = ROWD.get(k)
                int fx = f * 2 + di
                int nB = di == 0 ? nUp.get(f) : nBroke.get(f) - nUp.get(f)
                f_rec(tb, r, FAMS.get(f), FAMTIP.get(f), di, nConf.get(f), nB, sShow.get(fx), nRes.get(fx), rShow.get(fx), rN.get(fx), C_BG)
                r += 1
        int tUp = nUp.sum()
        f_rec(tb, r, "All", "Every pattern together, including breaks against the textbook direction that have no row of their own.", 0, tConf, tUp, f_sumF(sShow, 0), f_sumI(nRes, 0), f_sumF(rShow, 0), f_sumI(rN, 0), C_HD)
        r += 1
        f_rec(tb, r, "All", "Every pattern together, including breaks against the textbook direction that have no row of their own.", 1, tConf, nBroke.sum() - tUp, f_sumF(sShow, 1), f_sumI(nRes, 1), f_sumF(rShow, 1), f_sumI(rN, 1), C_HD)
        r += 1
 
    if showLive
        if A.st == 0 and B.st == 0 and C.st == 0
            f_row(tb, r, "Now: no pattern", C_LB, C_BG)
            r += 1
        if A.st == 1
            f_row(tb, r, "Now: developing (2 highs, 2 lows)", C_LB, C_BG)
            r += 1
            f_row(tb, r, "Past ones confirmed: " + f_pn(nCandConf, nCand), C_TX, C_BG)
            r += 1
        else if A.st == 2
            float upL = f_up(A, bar_index)
            float loL = f_lo(A, bar_index)
            int q  = f_clamp4(4.0 * (close - loL) / (upL - loL))
            int tq = f_clamp4(4.0 * (bar_index - A.xc) / (A.dead - A.xc))
            int used = int(math.round(100.0 * (bar_index - A.xc) / (A.dead - A.xc)))
            r := f_liveWaiting(tb, r, A)
            f_row(tb, r, "Price in " + QTRS.get(q) + ": broke up " + f_pn(posUp.get(q), posN.get(q)), C_TX, C_BG)
            r += 1
            f_row(tb, r, "Window " + str.tostring(used) + "% used: no breakout " + f_pn(timeExp.get(tq), timeN.get(tq)), C_TX, C_BG)
            r += 1
        else if A.st == 3
            r := f_liveBroken(tb, r, A)
        if B.st == 2
            r := f_liveWaiting(tb, r, B)
        else if B.st == 3
            r := f_liveBroken(tb, r, B)
        if C.st == 2
            r := f_liveWaiting(tb, r, C)
        else if C.st == 3
            r := f_liveBroken(tb, r, C)
 
    if showFoot
        f_row(tb, r, "Broke: share of confirmed patterns", C_LB, C_BG)
        r += 1
        f_row(tb, r, showExit ? "Exit R: avg R at the stop or time limit" : "Reach R: avg best move before the stop", C_LB, C_BG)
        r += 1
        f_row(tb, r, "Stop: " + STOP_TXT + " · " + TRAIL_TXT, C_LB, C_BG)
        r += 1
        f_row(tb, r, "Rand R: random entries, same rules", C_LB, C_BG)
        r += 1
        f_row(tb, r, "* under " + str.tostring(minN) + " cases", C_LB, C_BG)
        r += 1
    table.cell(tb, 0, r, "Past behaviour, not advice · hover titles", text_color = C_LB, bgcolor = C_BG, text_size = ts, text_halign = text.align_left, tooltip = TIP_TITLE)
    table.merge_cells(tb, 0, r, 6, r)
 
// ── Alerts (events only) ─────────────────────────────────────────────────────
alertcondition(evConf, "Pattern confirmed", "Pattern Evidence Map: a pattern was confirmed.")
alertcondition(evUp, "Closed above pattern", "Pattern Evidence Map: price closed above a confirmed pattern.")
alertcondition(evDown, "Closed below pattern", "Pattern Evidence Map: price closed below a confirmed pattern.")

← 返回列表