Harmonic Patterns - First PRZ Touch

ingtian · study · 799 行 · 点赞 225 · TradingView 原页

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

Pine Script

// This Pine Script(TM) source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ingtian
// Harmonic patterns with Carney's published ratios, signalled on the first closed bar that reaches the PRZ.
//@version=6
indicator("Harmonic Patterns - First PRZ Touch", "HP First Touch", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_polylines_count = 100)
 
// ============================================================================ inputs
const string G_SW = "Swings"
const string G_RU = "Pattern rules"
const string G_PA = "Patterns"
const string G_LV = "Stop and targets"
const string G_DR = "Drawing"
 
const string SW_NONE = "None"
const string SW_PCT  = "Percent of price"
const string SW_ATR  = "ATR(14) multiple"
const string PO_BOTH = "Both"
const string PO_BULL = "Bull"
const string PO_BEAR = "Bear"
const string PO_OFF  = "Off"
const string LEG_AD  = "AD leg"
const string LEG_CD  = "CD leg"
const string SL_DEF  = "Pattern default"
const string SL_XA   = "XA level"
const string SL_ATR  = "PRZ edge + ATR"
const string SL_CD   = "CD multiple"
const string OV_ZONE = "One per zone"
const string OV_ALL  = "Show all"
const string FIN_COL = "Collapse into label"
const string FIN_KEEP = "Keep lines"
const string RAT_NEW = "Newest pattern"
const string RAT_ALL = "All"
const string RAT_OFF = "Off"
const int    ARM_CAP = 3000
 
const string T_PIV   = "A swing high (low) is a bar strictly above (below) the `left` bars before it and at least as high (low) as the `right` bars after it, so it is known only `right` bars after it prints. X, A, B and C are drawn on their own bars once confirmed. A point may pair with any earlier opposite swing if the leg is clean: the end point is beyond every bar of the leg, and no bar of the leg breaks its start."
const string T_SW    = "Ignore a new opposite swing unless it is at least this far from the previous one: a percent of price, or a multiple of ATR(14). None keeps every swing."
const string T_TOL   = "Tolerance for Carney's single ratio values, in ratio units: a value f is accepted within f +/- tol for f <= 1 and f x (1 +/- tol) for f > 1, i.e. +/- tol x max(1, f). Published ranges such as BC 1.618-2.618 or the Gartley's AB=CD 1.0-1.27 are used exactly. The defining D level (XD, or CD/AB for AB=CD) is one-sided, from the level itself to tol x max(1, level) beyond it, so D fires at the level and not before it. Carney gives +/-3% for the Gartley B: read as 3 points of XA that is tol 0.03 (the default 0.02 is stricter); read as 3% of 0.618 it is about 0.02. Pattern names stay unique up to 0.1."
const string T_SPAN  = "Minimum: Carney's minimum pattern size, 30 bars on any timeframe, counted from X to D (A to D for AB=CD). A setup whose PRZ is reached before that is too small and is dropped. Maximum: a search horizon, not a pattern rule. Older swings are not searched and older setups are dropped; larger values find larger patterns at more computation."
const string T_TPLEG = "Targets are retracements of the AD leg or of the CD leg, measured from D back toward A (or C)."
const string T_TP    = "Each enabled target is this ratio of the chosen leg from D. Its label shows the price and the reward-to-risk (R) against the stop."
const string T_SL    = "Pattern default: Gartley at X (Carney: 'Stop Loss >1.0', i.e. beyond X), Bat at 1.13 XA (Carney's 'make-or-break' level), and 1 x ATR(14) beyond the PRZ far edge for Alt Bat, Butterfly, Crab, Deep Crab and AB=CD (Carney asks for a very small stop on the Crab and Deep Crab but gives no number; none is given for the others). XA level: the value is an XA ratio from A (1.0 = X). PRZ edge + ATR: the value is an ATR(14) multiple beyond the PRZ far edge. CD multiple: the value times CD beyond D. ATR(14) is taken at the bar before D, so the D bar's own range does not widen its stop. If a stop would not lie beyond D, or XA level is used on AB=CD, the PRZ edge + 1 ATR stop is used and the tooltip says so."
const string T_LVL   = "Lines run from D for at most this many bars and end on the bar their level trades, marked 'hit'. The stop also ends all open targets, marked 'void'; when every target is hit, the stop line ends. Targets count from the bar after D. The stop also counts on the D bar, where it can only have traded after the entry. If the stop and a target trade on the same bar, the stop counts. When several patterns complete on the same bar, only the first one gets lines; the others' levels are in the tooltip."
const string T_FIN   = "Collapse into label: on the bar a pattern's stop trades, its last target trades or its lines reach their maximum length, its stop and target lines, their labels and its PRZ box are removed, and the outcome is added to its name label in the order the levels traded: 'TP1 > SL' (TP1, then the stop), 'TP1 > TP2', 'SL', or 'expired' when the lines ended first ('TP1 > expired' after a target). The outcome is that of the first pattern of the label, the one the lines belong to. The tooltip lists each level with its price and the bar it traded on. Lines of patterns still running stay. Keep lines: finished lines stay on the chart, marked 'hit' or 'void'."
const string T_RAT   = "The ratio of each leg to the one before it (XB, AC, BD) and XD, drawn on the legs they measure. Newest pattern: only the most recently drawn pattern shows them; an older pattern's ratio labels are removed when a newer pattern is drawn. Every pattern's ratios are also in its name label's tooltip."
const string T_OV    = "Show all (default): every pattern is drawn, with its own stop, targets and alert. One per zone: a pattern whose D lies inside the PRZ of the first pattern of an earlier name label of the same direction, widened by this many ATR(14) on each side (the ATR of the bar before D), while that pattern's lines still run (its stop and its last target have not traded and the lines have not reached their maximum length), is not drawn and gets no stop, targets or alert. Its name is added to that label with the bars since that label's signal, e.g. '+ Bat (+35 bars)', and its points and ratios to the label's tooltip. This setting never moves or removes a drawn pattern, and only kept patterns can take others in. Drawn patterns completing on the same bar share one label; each pattern is checked on its own, so one of them can join an earlier label while the others are drawn."
const string T_KEEP  = "The oldest pattern's drawings are deleted first, together with the other patterns that share its name label. Each pattern uses up to 3 polylines and TradingView allows 100."
const string T_PRZ   = "The PRZ of a completed pattern: its defining D level up to the tolerance beyond it, where that lies inside the BC projection range and the AB=CD limits. Drawn over the bars in which D could fire."
const string T_FORM  = "For the newest forming X-A-B-C of each pattern and direction: the part of its PRZ a new C-to-D extreme can still reach. Provisional: redrawn every bar and removed when the setup fails. Not signals."
 
const string S_GART = "Gartley: B 0.618 XA, C 0.382-0.886 AB, BC 1.13-1.618, AB=CD 1.0-1.27, D 0.786 XA. Default stop at X."
const string S_BAT  = "Bat: B 0.382-0.50 XA, C 0.382-0.886 AB, BC 1.618-2.618, CD at least AB, D 0.886 XA. Default stop 1.13 XA."
const string S_ALT  = "Alternate Bat: B 0.382 XA or less, C 0.382-0.886 AB, BC 2.0-3.618, CD at least AB, D 1.13 XA."
const string S_BUT  = "Butterfly: B 0.786 XA, C 0.382-0.886 AB, BC 1.618-2.24, CD at least AB, D 1.27 XA."
const string S_CRAB = "Crab: B 0.382-0.618 XA, C 0.382-0.886 AB, BC 2.618-3.618, CD at least AB, D 1.618 XA."
const string S_DEEP = "Deep Crab: B 0.886 XA (may go deeper, never past X), C 0.382-0.886 AB, BC 2.0-3.618, CD at least AB, D 1.618 XA."
const string S_ABCD = "AB=CD: C 0.382-0.886 AB, BC 1.13-2.618, CD = AB. The 1.27 / 1.618 alternates are not signalled because CD always reaches 1.0 x AB first. Off by default. Switched on with the other settings at default, it makes up about two thirds of all signals."
 
int    pivL    = input.int(2, "Pivot left / right", minval = 1, maxval = 50, inline = "piv", group = G_SW, display = display.none)
int    pivR    = input.int(2, "", minval = 1, maxval = 50, inline = "piv", group = G_SW, tooltip = T_PIV, display = display.none)
string swMode  = input.string(SW_NONE, "Min swing", options = [SW_NONE, SW_PCT, SW_ATR], inline = "sw", group = G_SW, display = display.none)
float  swVal   = input.float(1.0, "", minval = 0, step = 0.1, inline = "sw", group = G_SW, tooltip = T_SW, display = display.none, active = swMode != SW_NONE)
bool   zzShow  = input.bool(false, "Show zigzag", group = G_SW, tooltip = "Swings still usable for a pattern (within the X to D maximum).")
 
float  tol     = input.float(0.02, "Tolerance", minval = 0, maxval = 0.1, step = 0.005, group = G_RU, tooltip = T_TOL, display = display.none)
int    spanMin = input.int(30, "Bars X to D: min / max", minval = 5, maxval = 2000, inline = "span", group = G_RU, display = display.none)
int    spanMax = input.int(300, "", minval = 5, maxval = 2000, inline = "span", group = G_RU, tooltip = T_SPAN, display = display.none)
 
string gartOn  = input.string(PO_BOTH, "Gartley", options = [PO_BOTH, PO_BULL, PO_BEAR, PO_OFF], group = G_PA, tooltip = S_GART, display = display.none)
string batOn   = input.string(PO_BOTH, "Bat", options = [PO_BOTH, PO_BULL, PO_BEAR, PO_OFF], group = G_PA, tooltip = S_BAT, display = display.none)
string altOn   = input.string(PO_BOTH, "Alt Bat", options = [PO_BOTH, PO_BULL, PO_BEAR, PO_OFF], group = G_PA, tooltip = S_ALT, display = display.none)
string butOn   = input.string(PO_BOTH, "Butterfly", options = [PO_BOTH, PO_BULL, PO_BEAR, PO_OFF], group = G_PA, tooltip = S_BUT, display = display.none)
string crabOn  = input.string(PO_BOTH, "Crab", options = [PO_BOTH, PO_BULL, PO_BEAR, PO_OFF], group = G_PA, tooltip = S_CRAB, display = display.none)
string deepOn  = input.string(PO_BOTH, "Deep Crab", options = [PO_BOTH, PO_BULL, PO_BEAR, PO_OFF], group = G_PA, tooltip = S_DEEP, display = display.none)
string abcdOn  = input.string(PO_OFF, "AB=CD", options = [PO_BOTH, PO_BULL, PO_BEAR, PO_OFF], group = G_PA, tooltip = S_ABCD, display = display.none)
 
bool   showLvl = input.bool(true, "Show stop and targets", group = G_LV)
string tpLeg   = input.string(LEG_AD, "Targets measured on", options = [LEG_AD, LEG_CD], group = G_LV, tooltip = T_TPLEG, display = display.none)
bool   tp1On   = input.bool(true, "TP1", inline = "tp1", group = G_LV)
float  tp1     = input.float(0.382, "", minval = 0.01, maxval = 5, step = 0.001, inline = "tp1", group = G_LV, display = display.none, active = tp1On)
bool   tp2On   = input.bool(true, "TP2", inline = "tp2", group = G_LV)
float  tp2     = input.float(0.618, "", minval = 0.01, maxval = 5, step = 0.001, inline = "tp2", group = G_LV, display = display.none, active = tp2On)
bool   tp3On   = input.bool(false, "TP3", inline = "tp3", group = G_LV)
float  tp3     = input.float(1.0, "", minval = 0.01, maxval = 5, step = 0.001, inline = "tp3", group = G_LV, tooltip = T_TP, display = display.none, active = tp3On)
string slMode  = input.string(SL_DEF, "Stop", options = [SL_DEF, SL_XA, SL_ATR, SL_CD], inline = "sl", group = G_LV, display = display.none)
float  slVal   = input.float(1.0, "", minval = 0, step = 0.01, inline = "sl", group = G_LV, tooltip = T_SL, display = display.none, active = slMode != SL_DEF)
int    lvlBars = input.int(50, "Level lines: max bars", minval = 1, maxval = 500, group = G_LV, tooltip = T_LVL, display = display.none)
string finMode = input.string(FIN_COL, "Finished levels", options = [FIN_COL, FIN_KEEP], group = G_LV, tooltip = T_FIN, display = display.none, active = showLvl)
bool   foldOn  = showLvl and finMode == FIN_COL
color  slCol   = input.color(#E040FB, "Stop / target colours", inline = "lvc", group = G_LV)
color  tpCol   = input.color(#2962FF, "", inline = "lvc", group = G_LV)
 
int    keepN    = input.int(5, "Patterns kept", minval = 1, maxval = 30, group = G_DR, tooltip = T_KEEP, display = display.none)
string ovMode   = input.string(OV_ALL, "Overlapping patterns", options = [OV_ZONE, OV_ALL], inline = "ov", group = G_DR, display = display.none)
float  zoneK    = input.float(1.0, "", minval = 0, step = 0.1, inline = "ov", group = G_DR, tooltip = T_OV, display = display.none, active = ovMode == OV_ZONE)
bool   oneZone  = ovMode == OV_ZONE
bool   showFill = input.bool(true, "Fill triangles", group = G_DR)
string ratMode  = input.string(RAT_NEW, "Ratio labels", options = [RAT_NEW, RAT_ALL, RAT_OFF], group = G_DR, tooltip = T_RAT, display = display.none)
bool   showRat  = ratMode != RAT_OFF
bool   showPrz  = input.bool(true, "PRZ box", group = G_DR, tooltip = T_PRZ)
bool   showForm = input.bool(true, "Possible D zones (not signals)", group = G_DR, tooltip = T_FORM)
color  bullCol  = input.color(#00BCD4, "Bullish / bearish", inline = "col", group = G_DR)
color  bearCol  = input.color(#FF9800, "", inline = "col", group = G_DR)
 
if not chart.is_standard
    runtime.error("Use a standard chart (candles, bars, line). Heikin Ashi, Renko and similar charts use synthetic prices.")
if spanMin > spanMax
    runtime.error("Bars X to D: the minimum must not exceed the maximum.")
 
// Variable-depth history reads (segment extremes, late-touch replay) can reach pivR + spanMax + 1 <= 2051 bars, also
// on realtime bars where buffers are not auto-resized; drawings that far back need the time buffer too.
max_bars_back(open, 2100)
max_bars_back(high, 2100)
max_bars_back(low, 2100)
max_bars_back(time, 2100)
 
// ============================================================================ types
type Pivot
    int   idx
    int   t
    float price
    bool  isHigh
    float opp        // the same bar's other wick
    float segHi      // highest high / lowest low of the bars from the previous zigzag vertex (included) up to
    float segLo      // this one (excluded); na when there are none
 
type Pat
    string name
    int    waves        // 4 = XABCD, 3 = AB=CD
    float  xbLo
    float  xbHi
    float  acLo
    float  acHi
    float  bdLo
    float  bdHi
    float  lvLo         // defining D level L
    float  lvHi         // L + tol x max(1, L)
    float  abLo         // Carney's AB=CD inside an XABCD pattern: CD/AB from abLo to abHi (na = no bound)
    float  abHi
    float  stopXA       // pattern-default stop as an XA level; na = PRZ far edge + 1 ATR(14)
    string spec
    bool   bullOn
    bool   bearOn
 
// An X-A-B-C (or A-B-C) waiting for D.
type Setup
    int          pi
    array<Pivot> pts
    bool         bull
    float        zLo
    float        zHi
    float        run        // running extreme of the C->D leg, starting at C's own bar
    array<Pivot> hitPts
    float        hitLo
    float        hitHi
 
// A stop or target level of a detection.
type Lvl
    string tag
    float  price
    string txt
    string tip
    line   ln
    label  lb
    bool   live
    int    hitIdx
 
type Drawn
    array<line>     lines
    array<label>    labels
    array<polyline> polys
    array<box>      boxes
    array<Lvl>      lvls       // stop first
    bool            bull
    int             endIdx
    int             seen
    int             sig        // signal bar; patterns with the same sig and bull share one name label
    float           zLo        // PRZ
    float           zHi
    label           nameLb     // the name label, on the pattern that owns it
    string          tip        // that label's tooltip
    array<line>     rLn        // the ratio lines and labels (also in lines / labels)
    array<label>    rLb
    string          out = ""   // levels in the order they traded, e.g. "TP1 > SL"
    bool            folded = false
 
// ============================================================================ pattern table
bu(string m) => m == PO_BOTH or m == PO_BULL
be(string m) => m == PO_BOTH or m == PO_BEAR
pLo(float f) => f - tol * math.max(1.0, f)
pHi(float f) => f + tol * math.max(1.0, f)
 
// Carney's ratios: single values get +/- tol x max(1, f), ranges are used as published, the defining level is one-sided.
// AB=CD inside the XABCD patterns: 1.0-1.27 for the Gartley, at least 1.0 (CD >= AB) for the others.
var array<Pat> pats = array.from(
     Pat.new("Gartley",   4, pLo(0.618), pHi(0.618), 0.382, 0.886, 1.13,  1.618, 0.786, pHi(0.786), 1.0, 1.27, 1.0,  S_GART, bu(gartOn), be(gartOn)),
     Pat.new("Bat",       4, 0.382,      0.50,       0.382, 0.886, 1.618, 2.618, 0.886, pHi(0.886), 1.0, na,   1.13, S_BAT,  bu(batOn),  be(batOn)),
     Pat.new("Alt Bat",   4, 0.0,        0.382,      0.382, 0.886, 2.0,   3.618, 1.13,  pHi(1.13),  1.0, na,   na,   S_ALT,  bu(altOn),  be(altOn)),
     Pat.new("Butterfly", 4, pLo(0.786), pHi(0.786), 0.382, 0.886, 1.618, 2.24,  1.27,  pHi(1.27),  1.0, na,   na,   S_BUT,  bu(butOn),  be(butOn)),
     Pat.new("Crab",      4, 0.382,      0.618,      0.382, 0.886, 2.618, 3.618, 1.618, pHi(1.618), 1.0, na,   na,   S_CRAB, bu(crabOn), be(crabOn)),
     Pat.new("Deep Crab", 4, pLo(0.886), 1.0,        0.382, 0.886, 2.0,   3.618, 1.618, pHi(1.618), 1.0, na,   na,   S_DEEP, bu(deepOn), be(deepOn)),
     Pat.new("AB=CD",     3, na,         na,         0.382, 0.886, 1.13,  2.618, 1.0,   pHi(1.0),   na,  na,   na,   S_ABCD, bu(abcdOn), be(abcdOn)))
 
// ============================================================================ series (every bar, global scope)
float hiR   = ta.highest(high, pivR)    // bars after the pivot candidate
float loR   = ta.lowest(low, pivR)
float hiL   = ta.highest(high, pivL)
float loL   = ta.lowest(low, pivL)
float atrV  = ta.atr(14)
max_bars_back(atrV, 64)                 // stops read the ATR of the bar before D, up to pivR bars back
float candH = high[pivR]
float candL = low[pivR]
int   candT = time[pivR]
bool  full  = bar_index >= pivL + pivR
bool  isPH  = full and candH > hiL[pivR + 1] and candH >= hiR
bool  isPL  = full and candL < loL[pivR + 1] and candL <= loR
array<bool>  tpOn = array.from(tp1On, tp2On, tp3On)
array<float> tpK  = array.from(tp1, tp2, tp3)
 
// ============================================================================ geometry (all tests in price space)
maxNa(float a, float b) => na(a) ? b : na(b) ? a : math.max(a, b)
minNa(float a, float b) => na(a) ? b : na(b) ? a : math.min(a, b)
 
// Price interval of a point retracing the leg s -> e by lo..hi (ratio measured from e).
band(float s, float e, float lo, float hi) =>
    float r  = math.abs(s - e)
    float bl = s > e ? e + r * lo : e - r * hi
    float bh = s > e ? e + r * hi : e - r * lo
    [bl, bh]
 
inBand(float s, float e, float p, float lo, float hi) =>
    [bl, bh] = band(s, e, lo, hi)
    p >= bl and p <= bh
 
// PRZ for [X,] A, B, C: the BC projection range intersected with the defining level band and, for XABCD patterns,
// the AB=CD band; [na, na] if empty. AB leg from C: (C + B - A, C), so that CD/AB = k is band(ab, C, k, k).
// Level leg: XABCD -> (X, A); AB=CD -> the AB leg. An na AB=CD bound gives an na edge, which maxNa / minNa skip.
zoneOf(Pat pt, Pivot x, Pivot a, Pivot b, Pivot c) =>
    float ab = c.price + b.price - a.price
    [dLo, dHi] = band(b.price, c.price, pt.bdLo, pt.bdHi)
    [lLo, lHi] = band(pt.waves == 4 ? x.price : ab, pt.waves == 4 ? a.price : c.price, pt.lvLo, pt.lvHi)
    [aLo, aHi] = band(ab, c.price, pt.abLo, pt.abHi)
    float zLo = maxNa(math.max(dLo, lLo), aLo)
    float zHi = minNa(math.min(dHi, lHi), aHi)
    bool  ok  = zLo <= zHi
    [ok ? zLo : na, ok ? zHi : na]
 
legsOk(Pat pt, Pivot x, Pivot a, Pivot b, Pivot c) =>
    (pt.waves == 3 or inBand(x.price, a.price, b.price, pt.xbLo, pt.xbHi)) and inBand(a.price, b.price, c.price, pt.acLo, pt.acHi)
 
// Indices of vertices u that can start the leg ending at pz[iv], nearest first: v is strictly beyond every bar in
// [u, v), u's own bar included, and no bar in (u, v], v's own bar included, breaks u.
backCands(array<Pivot> pz, int iv, int stopIdx) =>
    array<int> out = array.new<int>()
    if iv >= 1
        Pivot v  = pz.get(iv)
        float hi = na
        float lo = na
        for j = iv - 1 to 0
            Pivot u = pz.get(j)
            if u.idx < stopIdx
                break
            Pivot k = pz.get(j + 1)
            hi := maxNa(hi, k.segHi)
            lo := minNa(lo, k.segLo)
            if u.isHigh != v.isHigh and u.idx < v.idx
                if v.isHigh ? v.price <= hi : v.price >= lo
                    break
                if u.isHigh ? math.max(hi, v.opp) <= u.price : math.min(lo, v.opp) >= u.price
                    out.push(j)
    out
 
// P = [X,] A, B, C, D. Returns [ok, zLo, zHi].
matchPat(Pat pt, array<Pivot> P) =>
    int   n   = P.size()
    Pivot d   = P.get(n - 1)
    Pivot c   = P.get(n - 2)
    Pivot b   = P.get(n - 3)
    Pivot a   = P.get(n - 4)
    Pivot p0  = P.get(0)
    int  span = d.idx - p0.idx
    bool ok   = false
    float zLo = na
    float zHi = na
    if span >= spanMin and span <= spanMax and legsOk(pt, p0, a, b, c)
        [lo, hi] = zoneOf(pt, p0, a, b, c)
        zLo := lo
        zHi := hi
        ok  := not na(lo) and d.price >= lo and d.price <= hi
    [ok, zLo, zHi]
 
// A setup for P = [X,] A, B, C if its legs pass and its PRZ is non-empty, else na.
newSetup(int pi, Pat pt, array<Pivot> P) =>
    int   n = P.size()
    Pivot c = P.get(n - 1)
    Setup s = na
    if legsOk(pt, P.first(), P.get(n - 3), P.get(n - 2), c)
        [zLo, zHi] = zoneOf(pt, P.first(), P.get(n - 3), P.get(n - 2), c)
        if not na(zLo)
            s := Setup.new(pi, P, c.isHigh, zLo, zHi, c.opp)
    s
 
// One closed bar for a setup: fire on the first new C->D extreme that reaches the PRZ, at the PRZ near edge, the
// previous extreme or the open, whichever comes first (a bar opening inside the PRZ fills at its open; a bar opening
// beyond the whole PRZ never traded it and fails the match). A bar breaking C, the X->D maximum, a bar past the PRZ
// far edge, or a PRZ reached before the X->D minimum (a pattern too small to count) kills the setup. On a hit,
// hitPts/hitLo/hitHi are set. Returns true while the setup stays armed.
stepSetup(Setup s, Pat pt, float op, float lo, float hi, int barIdx, int barTime) =>
    s.hitPts := na
    Pivot c    = s.pts.last()
    int   span = barIdx - s.pts.first().idx
    bool  dead = (s.bull ? hi > c.price : lo < c.price) or span > spanMax
    if not dead and (s.bull ? lo < s.run : hi > s.run)
        if s.bull ? (s.zHi >= lo and s.zLo <= s.run) : (s.zLo <= hi and s.zHi >= s.run)
            dead := span < spanMin
            if not dead
                float e = s.bull ? math.min(s.zHi, s.run, op) : math.max(s.zLo, s.run, op)
                array<Pivot> P = s.pts.copy()
                P.push(Pivot.new(barIdx, barTime, e, not s.bull))
                [ok, zLo, zHi] = matchPat(pt, P)
                if ok
                    s.hitPts := P
                    s.hitLo  := zLo
                    s.hitHi  := zHi
        s.run := s.bull ? lo : hi
    bool beyond = s.bull ? lo < s.zLo : hi > s.zHi
    not dead and na(s.hitPts) and not beyond
 
// Alternating zigzag of confirmed pivots; a same-side pivot replaces the tail only if more extreme. Each vertex keeps
// the bar extremes since the previous vertex. Pivots older than the longest allowed X->D span are dropped. Returns
// true when the tail changed.
addPivot(array<Pivot> pz, Pivot p, float atrNow) =>
    bool changed = false
    if pz.size() == 0
        pz.push(p)
        changed := true
    else
        Pivot tail = pz.last()
        // bars [tail, p), capped at the depth any pattern can reach (older segments are never read)
        float sh = na
        float sl = na
        int   o1 = bar_index - p.idx + 1
        int   o2 = math.min(bar_index - tail.idx, pivR + spanMax + 1)
        if o1 <= o2
            for o = o1 to o2
                sh := maxNa(sh, high[o])
                sl := minNa(sl, low[o])
        if tail.isHigh == p.isHigh
            if p.isHigh ? p.price > tail.price : p.price < tail.price
                p.segHi := maxNa(tail.segHi, sh)
                p.segLo := minNa(tail.segLo, sl)
                pz.set(pz.size() - 1, p)
                changed := true
        else
            float thr = swMode == SW_PCT ? tail.price * swVal / 100 : swMode == SW_ATR ? swVal * atrNow : na
            if na(thr) or math.abs(p.price - tail.price) >= thr
                p.segHi := sh
                p.segLo := sl
                pz.push(p)
                changed := true
    while pz.size() > 1 and pz.first().idx < bar_index - pivR - spanMax
        pz.shift()
    changed
 
// ============================================================================ stop and targets
fmtT(int t) => str.format_time(t, "yyyy-MM-dd HH:mm", "UTC")
fmtP(float p) => str.tostring(p, format.mintick)
fmtR(float r) => str.tostring(r, "#.###")
fmtRR(float r) => str.tostring(r, "#.#")
ratioOf(Pivot u, Pivot v, Pivot w) => math.abs(w.price - v.price) / math.abs(v.price - u.price)
keyOf(int pi, Pivot c) => str.tostring(pi) + "|" + str.tostring(c.idx) + (c.isHigh ? "H" : "L")
join(string a, string b) => a == "" ? b : b == "" ? a : a + " | " + b
seq(string a, string b) => a == "" ? b : a + " > " + b
tfStr() => timeframe.isminutes ? (timeframe.multiplier % 60 == 0 ? str.tostring(timeframe.multiplier / 60) + "h" : str.tostring(timeframe.multiplier) + "m") : timeframe.period
 
// [stop, description] for P = [X,] A, B, C, D and its PRZ.
stopOf(Pat pt, array<Pivot> P, float zLo, float zHi, float atrNow) =>
    int    n     = P.size()
    Pivot  d     = P.get(n - 1)
    Pivot  c     = P.get(n - 2)
    Pivot  a     = P.get(n - 4)
    Pivot  x     = P.get(0)
    bool   bull  = not d.isHigh
    float  sg    = bull ? 1.0 : -1.0
    float  entry = d.price
    float  zFar  = bull ? zLo : zHi
    float  stop  = na
    string desc  = ""
    if slMode == SL_DEF
        if na(pt.stopXA)
            stop := zFar - sg * atrNow
            desc := "pattern default: PRZ edge + 1 ATR"
        else
            stop := a.price + (x.price - a.price) * pt.stopXA
            desc := pt.stopXA == 1.0 ? "pattern default: X" : "pattern default: " + fmtR(pt.stopXA) + " XA"
    else if slMode == SL_XA
        stop := a.price + (x.price - a.price) * slVal
        desc := fmtR(slVal) + " XA"
    else if slMode == SL_ATR
        stop := zFar - sg * slVal * atrNow
        desc := "PRZ edge + " + fmtR(slVal) + " ATR"
    else
        stop := entry - sg * slVal * math.abs(c.price - d.price)
        desc := fmtR(slVal) + " CD"
    if sg * (entry - stop) <= 0 or (slMode == SL_XA and pt.waves == 3)
        stop := zFar - sg * atrNow
        desc := "fallback: PRZ edge + 1 ATR"
    [stop, desc]
 
// Ends a level's line and label on bar idx; the label gets the status ("hit", or "void" for a target the stop ended).
endLvl(Lvl v, int idx, string status) =>
    v.live := false
    if not na(v.ln)
        v.ln.set_x2(idx)
    if not na(v.lb)
        v.lb.set_x(idx)
        if status != ""
            v.lb.set_text(v.txt + "  " + status)
        if status == "void"
            v.lb.set_textcolor(color.gray)
    v.live
 
// One bar for a detection's levels. The stop counts first (on the D bar too, where it can only have traded after the
// entry) and ends every open line; targets count from the bar after D; when every target is hit the stop line ends.
track(Drawn dr, float hi, float lo, int idx, bool isD) =>
    Lvl sl = dr.lvls.first()
    if idx <= dr.endIdx and sl.live
        if dr.bull ? lo <= sl.price : hi >= sl.price
            sl.hitIdx := idx
            dr.out    := seq(dr.out, "SL")
            for [i, v] in dr.lvls
                if v.live
                    endLvl(v, idx, i == 0 ? "hit" : "void")
        else if not isD
            int nLive = 0
            for [i, v] in dr.lvls
                if i > 0
                    if v.live and (dr.bull ? hi >= v.price : lo <= v.price)
                        v.hitIdx := idx
                        dr.out   := seq(dr.out, v.tag)
                        endLvl(v, idx, "hit")
                    nLive += v.live ? 1 : 0
            if dr.lvls.size() > 1 and nLive == 0
                endLvl(sl, idx, "")
    sl.live
 
// ============================================================================ drawing
tipOf(Pat pt, array<Pivot> P, float zLo, float zHi, Drawn dr, string desc, string tps, int lag) =>
    int    n   = P.size()
    Pivot  d   = P.get(n - 1)
    Pivot  c   = P.get(n - 2)
    Pivot  b   = P.get(n - 3)
    Pivot  a   = P.get(n - 4)
    string ltr = n == 5 ? "XABCD" : "ABCD"
    string s   = (d.isHigh ? "Bearish " : "Bullish ") + pt.name
    for [j, v] in P
        s += "\n" + str.substring(ltr, j, j + 1) + "  " + fmtT(v.t) + " UTC  " + fmtP(v.price)
    string cdab = "CD/AB " + fmtR(math.abs(c.price - d.price) / math.abs(a.price - b.price))
    if n == 5
        Pivot x = P.get(0)
        s += "\nXB " + fmtR(ratioOf(x, a, b)) + "  AC " + fmtR(ratioOf(a, b, c)) + "  BD " + fmtR(ratioOf(b, c, d)) + "  XD " + fmtR(math.abs(a.price - d.price) / math.abs(x.price - a.price)) + "  " + cdab
    else
        s += "\nAC " + fmtR(ratioOf(a, b, c)) + "  BD " + fmtR(ratioOf(b, c, d)) + "  " + cdab
    s += "\nRatios: " + pt.spec
    s += "\nPRZ " + fmtP(zLo) + " - " + fmtP(zHi)
    string fl = ""   // level flags, after the signal line
    if na(dr)
        s += "\nEntry (D) " + fmtP(d.price) + ", in the zone of the first pattern of this label: no stop, targets or alert of its own"
    else
        Lvl sl = dr.lvls.first()
        s += "\nEntry (D) " + fmtP(d.price) + "   stop " + fmtP(sl.price) + " (" + desc + ")"
        if tps != ""
            s += "\n" + tps
        if not na(sl.hitIdx) and sl.hitIdx == d.idx
            fl += "\nStop traded on the D bar"
        if not na(sl.hitIdx) and sl.hitIdx > d.idx
            fl += "\nStop already traded before this signal"
        for [i, v] in dr.lvls
            if i > 0 and not na(v.hitIdx)
                fl += "\n" + v.tag + " already traded before this signal"
    s += "\nSignal at the close of the bar opening " + fmtT(time) + " UTC, close " + fmtP(close)
    if lag > 0
        s += "\nLate: the PRZ was reached " + str.tostring(lag) + " bar(s) before this signal, before C was confirmed"
    s + fl
 
// Legs, fills, letters, ratio lines and the PRZ box. lead = this pattern owns the bar's name label; the other patterns
// of that bar and direction get only a thin outline (their points, ratios and levels are in the shared tooltip).
drawPat(array<Pivot> P, float zLo, float zHi, color col, bool lead) =>
    int   n    = P.size()
    Pivot d    = P.get(n - 1)
    Drawn dr   = Drawn.new(array.new<line>(), array.new<label>(), array.new<polyline>(), array.new<box>(), array.new<Lvl>(), not d.isHigh, d.idx + lvlBars, bar_index, bar_index, zLo, zHi, na, na, array.new<line>(), array.new<label>())
    string ltr = n == 5 ? "XABCD" : "ABCD"
    array<chart.point> pts = array.new<chart.point>()
    for [j, v] in P
        pts.push(chart.point.from_index(v.idx, v.price))
        if lead and j < n - 1
            dr.labels.push(label.new(v.idx, v.price, str.substring(ltr, j, j + 1), yloc = v.isHigh ? yloc.abovebar : yloc.belowbar, color = color.new(col, 100), textcolor = col, style = v.isHigh ? label.style_label_down : label.style_label_up, size = size.normal))
    if showFill and lead
        color fc = color.new(col, 88)
        color nc = color.new(col, 100)
        dr.polys.push(polyline.new(array.from(pts.get(0), pts.get(1), pts.get(2)), closed = true, line_color = nc, fill_color = fc))
        dr.polys.push(polyline.new(array.from(pts.get(n - 3), pts.get(n - 2), pts.get(n - 1)), closed = true, line_color = nc, fill_color = fc))
    dr.polys.push(polyline.new(pts, line_color = col, line_width = lead ? 2 : 1))
    if showRat and lead
        color rb = color.new(chart.bg_color, 20)
        for j = 0 to n - 3
            Pivot u = P.get(j)
            Pivot w = P.get(j + 2)
            dr.rLn.push(line.new(u.idx, u.price, w.idx, w.price, color = color.new(col, 40), style = line.style_dashed))
            dr.rLb.push(label.new(math.round((u.idx + w.idx) / 2), (u.price + w.price) / 2, fmtR(ratioOf(u, P.get(j + 1), w)), color = rb, style = label.style_label_center, textcolor = col, size = size.small))
        if n == 5
            Pivot x = P.get(0)
            Pivot a = P.get(1)
            dr.rLn.push(line.new(x.idx, x.price, d.idx, d.price, color = color.new(col, 40), style = line.style_dotted))
            dr.rLb.push(label.new(math.round((x.idx + d.idx) / 2), (x.price + d.price) / 2, fmtR(math.abs(a.price - d.price) / math.abs(x.price - a.price)), color = rb, style = label.style_label_center, textcolor = col, size = size.small))
        dr.lines.concat(dr.rLn)
        dr.labels.concat(dr.rLb)
    if showPrz and lead and not na(zLo)
        dr.boxes.push(box.new(math.max(P.get(n - 2).idx + 1, P.first().idx + spanMin), zHi, bar_index, zLo, border_color = color.new(col, 50), bgcolor = color.new(col, 85)))
    dr
 
// Ratio labels "Newest pattern": an older pattern's ratio lines and labels go when a newer pattern draws its own.
method dropRat(Drawn dr) =>
    for x in dr.rLn
        x.delete()
    for x in dr.rLb
        x.delete()
    dr.rLn.clear()
    dr.rLb.clear()
 
// Collapse into label: removes a finished pattern's stop and target lines, their labels and its PRZ box, and adds the
// outcome to its name label and each level's price and bar to its tooltip, under the pattern's name (the tooltip's
// first line, e.g. "Bearish Bat"), since partners and merged patterns may follow it in the label.
method fold(Drawn dr) =>
    dr.folded := true
    Lvl    sl   = dr.lvls.first()
    string o    = sl.live ? seq(dr.out, "expired") : dr.out    // a live stop here means the lines reached their end
    string tEnd = fmtT(time[math.max(0, bar_index - dr.endIdx)])
    string tip  = "\n\nOutcome of the first pattern's stop and target lines (" + array.get(str.split(dr.tip, "\n"), 0) + "): " + o
    for [i, v] in dr.lvls
        v.ln.delete()
        v.lb.delete()
        string st = "void, the stop traded first"
        if not na(v.hitIdx)
            st := "traded on the bar opening " + fmtT(time[bar_index - v.hitIdx]) + " UTC"
        else if sl.live
            st := "not traded by the end of the lines, the bar opening " + tEnd + " UTC"
        else if i == 0
            st := "not traded, every target traded first"
        tip += "\n" + v.tag + " " + fmtP(v.price) + ": " + st
    for b in dr.boxes
        b.delete()
    dr.nameLb.set_text(dr.nameLb.get_text() + ": " + o)
    dr.tip := dr.tip + tip
    dr.nameLb.set_tooltip(dr.tip)
 
method wipe(Drawn dr) =>
    for x in dr.lines
        x.delete()
    for x in dr.labels
        x.delete()
    for x in dr.polys
        x.delete()
    for x in dr.boxes
        x.delete()
 
// Adds a pattern to a name label: txt to the label text, its tooltip block to the label's tooltip.
addTo(Drawn h, string txt, string tip) =>
    h.nameLb.set_text(h.nameLb.get_text() + txt)
    h.tip := h.tip + "\n\n" + tip
    h.nameLb.set_tooltip(h.tip)
 
// Draws and returns the alert snippet for a detection, once per (pattern, direction, bar) and per (pattern, C).
// A second pattern on the same bar and direction joins the first one's name label and tooltip. With One per zone,
// a pattern whose D lies in the widened PRZ of an earlier, still-live name label joins that label instead.
emit(Pat pt, int pi, array<Pivot> P, float zLo, float zHi, array<int> done, array<string> fired, array<Drawn> drawn, array<Drawn> heads) =>
    int    n    = P.size()
    Pivot  d    = P.get(n - 1)
    Pivot  c    = P.get(n - 2)
    Pivot  a    = P.get(n - 4)
    bool   bull = not d.isHigh
    string key  = keyOf(pi, c)
    int    code = pi * 2 + (bull ? 1 : 0)
    string msg  = ""
    if not done.includes(code) and not fired.includes(key)
        done.push(code)
        fired.push(key)
        if fired.size() > 500
            fired.shift()
        int    lag   = bar_index - d.idx      // a late touch put D up to pivR - 1 bars back
        string late  = lag > 0 ? " (late)" : ""
        float  atrD  = atrV[lag + 1]          // ATR known before D
        // the newest earlier name label of this direction whose lines still run and whose PRZ +/- zoneK ATR holds D
        Drawn  host  = na
        if oneZone and drawn.size() > 0
            for j = drawn.size() - 1 to 0
                Drawn h = drawn.get(j)
                if not na(h.nameLb) and h.bull == bull and h.sig < bar_index and h.lvls.first().live and bar_index <= h.endIdx and d.price >= h.zLo - zoneK * atrD and d.price <= h.zHi + zoneK * atrD
                    host := h
                    break
        Drawn  dr    = na
        if not na(host)
            int nb = bar_index - host.sig       // marks a later pattern apart from the label's same-bar partners
            addTo(host, " + " + pt.name + " (" + (lag > 0 ? "late, " : "") + "+" + str.tostring(nb) + (nb == 1 ? " bar)" : " bars)"), tipOf(pt, P, zLo, zHi, dr, "", "", lag))
        else
            int    slot  = bull ? 1 : 0
            Drawn  head  = heads.get(slot)
            bool   lead  = na(head)
            color  col   = bull ? bullCol : bearCol
            float  sg    = bull ? 1.0 : -1.0
            float  entry = d.price
            if lead and ratMode == RAT_NEW
                for h in drawn
                    h.dropRat()
            dr := drawPat(P, zLo, zHi, col, lead)
            [stop, desc] = stopOf(pt, P, zLo, zHi, atrD)
            string legN  = tpLeg == LEG_AD ? "AD" : "CD"
            float  leg   = tpLeg == LEG_AD ? math.abs(a.price - entry) : math.abs(c.price - entry)
            dr.lvls.push(Lvl.new("SL", stop, "SL " + fmtP(stop), "Stop: " + desc, na, na, true, na))
            string tpTip = ""
            string tpMsg = ""
            for i = 0 to 2
                if tpOn.get(i)
                    float  p  = entry + sg * tpK.get(i) * leg
                    string tg = "TP" + str.tostring(i + 1)
                    string rr = fmtRR(math.abs(p - entry) / math.abs(entry - stop)) + "R"
                    dr.lvls.push(Lvl.new(tg, p, tg + " " + fmtP(p) + " " + rr, tg + ": " + fmtR(tpK.get(i)) + " " + legN + " from D, " + rr + " against the stop", na, na, true, na))
                    tpTip += (tpTip == "" ? "" : "   ") + tg + " " + fmtP(p) + " (" + fmtR(tpK.get(i)) + " " + legN + ", " + rr + ")"
                    tpMsg += ", " + tg + " " + fmtP(p) + " (" + rr + ")"
            if lead and showLvl
                for v in dr.lvls
                    color lc = v.tag == "SL" ? slCol : tpCol
                    v.ln := line.new(d.idx, v.price, dr.endIdx, v.price, color = lc, style = v.tag == "SL" ? line.style_dashed : line.style_solid, width = 2)
                    v.lb := label.new(dr.endIdx, v.price, v.txt, color = color.new(lc, 100), textcolor = lc, style = label.style_label_left, size = size.small, tooltip = v.tip)
                    dr.lines.push(v.ln)
                    dr.labels.push(v.lb)
            // bars D..now
            for o = lag to 0
                track(dr, high[o], low[o], bar_index - o, o == lag)
            dr.seen := bar_index
            Lvl    sl   = dr.lvls.first()
            string flg  = ""
            for [i, v] in dr.lvls
                if i > 0 and not na(v.hitIdx)
                    flg += ", " + v.tag + " already traded"
            string slf  = na(sl.hitIdx) ? "" : sl.hitIdx == d.idx ? ", stop traded on the D bar" : ", stop already traded"
            string tip  = tipOf(pt, P, zLo, zHi, dr, desc, tpTip, lag)
            if lead
                label nl = label.new(d.idx, d.price, (bull ? "Bull " : "Bear ") + pt.name + late, yloc = bull ? yloc.belowbar : yloc.abovebar, style = bull ? label.style_label_up : label.style_label_down, color = col, textcolor = color.black, size = size.small, tooltip = tip)
                dr.labels.push(nl)
                dr.nameLb := nl
                dr.tip    := tip
                heads.set(slot, dr)
            else
                // a partner has no lines of its own, so its stop outcome so far goes into the shared label
                addTo(head, " + " + pt.name + late + (na(sl.hitIdx) ? "" : sl.hitIdx == d.idx ? " (stop on D bar)" : " (stop traded)"), tip)
            drawn.push(dr)
            // keep keepN patterns: the oldest goes together with the partners that share its name label
            while drawn.size() > keepN and drawn.first().sig < bar_index
                Drawn old = drawn.shift()
                old.wipe()
                for i = drawn.size() - 1 to 0
                    Drawn q = drawn.get(i)
                    if q.sig == old.sig and q.bull == old.bull
                        drawn.remove(i).wipe()
            string lv  = n == 5 ? "XD " + str.tostring(math.abs(a.price - entry) / math.abs(P.get(0).price - a.price), "0.000") : "CD/AB " + str.tostring(math.abs(c.price - entry) / math.abs(a.price - P.get(n - 3).price), "0.000")
            msg := (bull ? "Bull " : "Bear ") + pt.name + late + ": D " + fmtP(entry) + " (" + lv + "), PRZ " + fmtP(zLo) + "-" + fmtP(zHi) + ", close " + fmtP(close) + ", stop " + fmtP(stop) + tpMsg + slf + flg
    msg
 
// ============================================================================ state and main loop
var array<Pivot>  zz     = array.new<Pivot>()
var array<Setup>  armed  = array.new<Setup>()
var array<string> fired  = array.new<string>()
var array<Drawn>  drawn  = array.new<Drawn>()
var Drawn         proj   = na
var polyline      zzLine = na
string alertMsg = ""
 
// Everything runs on closed bars only, so history and realtime see the same thing.
if barstate.isconfirmed
    // 0) stop and target lines of earlier signals see this bar
    for dr in drawn
        if dr.seen < bar_index
            track(dr, high, low, bar_index, false)
            dr.seen := bar_index
    array<int>    done  = array.new<int>()
    array<Drawn>  heads = array.new<Drawn>(2)     // the pattern owning this bar's name label per direction [bear, bull]
    // 1) armed setups see this bar
    if armed.size() > 0
        array<Setup> alive = array.new<Setup>()
        for s in armed
            if not fired.includes(keyOf(s.pi, s.pts.last()))
                Pat  pt = pats.get(s.pi)
                bool ok = stepSetup(s, pt, open, low, high, bar_index, time)
                if not na(s.hitPts)
                    alertMsg := join(alertMsg, emit(pt, s.pi, s.hitPts, s.hitLo, s.hitHi, done, fired, drawn, heads))
                if ok
                    alive.push(s)
        armed := alive
    // 2) newly confirmed pivots (outside bar: the side matching the zigzag tail goes first)
    bool highFirst = not (isPH and isPL and zz.size() > 0 and not zz.last().isHigh)
    for k = 0 to 1
        bool doHigh = (k == 0) == highFirst
        if doHigh ? isPH : isPL
            Pivot p = Pivot.new(bar_index - pivR, candT, doHigh ? candH : candL, doHigh, doHigh ? candL : candH)
            if addPivot(zz, p, atrV)
                // 3) arm setups with C = the tail; bars C+1..now already happened, so replay them one by one
                int   m     = zz.size() - 1
                Pivot tail  = zz.get(m)
                int   stopC = bar_index - spanMax
                array<Setup> fresh = array.new<Setup>()
                array<int> bs = backCands(zz, m, stopC)
                for ib in bs
                    array<int> aCands = backCands(zz, ib, stopC)
                    for ia in aCands
                        array<int> xs = backCands(zz, ia, stopC)
                        for [i, pt] in pats
                            if tail.isHigh ? pt.bullOn : pt.bearOn
                                if pt.waves == 3
                                    Setup s = newSetup(i, pt, array.from(zz.get(ia), zz.get(ib), tail))
                                    if not na(s)
                                        fresh.push(s)
                                else
                                    for ix in xs
                                        Setup s = newSetup(i, pt, array.from(zz.get(ix), zz.get(ia), zz.get(ib), tail))
                                        if not na(s)
                                            fresh.push(s)
                for s in fresh
                    Pat  pt = pats.get(s.pi)
                    bool ok = true
                    for j = pivR - 1 to 0
                        ok := stepSetup(s, pt, open[j], low[j], high[j], bar_index - j, time[j])
                        if not ok
                            break
                    if not na(s.hitPts)
                        alertMsg := join(alertMsg, emit(pt, s.pi, s.hitPts, s.hitLo, s.hitHi, done, fired, drawn, heads))
                    else if ok
                        armed.push(s)
                while armed.size() > ARM_CAP
                    armed.shift()
    // 4) Collapse into label: name labels whose levels finished on this bar (after any pattern joined them on it)
    if foldOn
        for dr in drawn
            if not dr.folded and not na(dr.nameLb) and (not dr.lvls.first().live or bar_index >= dr.endIdx)
                dr.fold()
 
// ============================================================================ provisional visuals (last bar only)
bool redraw = barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed)
if zzShow and redraw and zz.size() > 1
    if not na(zzLine)
        zzLine.delete()
    array<chart.point> zp = array.new<chart.point>()
    for v in zz
        zp.push(chart.point.from_index(v.idx, v.price))
    zzLine := polyline.new(zp, line_color = color.new(color.gray, 30), line_style = line.style_dotted)
 
if showForm and redraw
    if not na(proj)
        proj.wipe()
    proj := Drawn.new(array.new<line>(), array.new<label>(), array.new<polyline>(), array.new<box>())
    if armed.size() > 0
        array<int>    seen = array.new<int>()
        array<string> nms  = array.new<string>(2, "")   // per direction [bear, bull]
        array<int>    lxs  = array.new<int>(2)
        array<float>  lys  = array.new<float>(2)
        for j = armed.size() - 1 to 0
            Setup s     = armed.get(j)
            int   code  = s.pi * 2 + (s.bull ? 1 : 0)
            Pivot c     = s.pts.last()
            int   left  = math.max(c.idx + 1, s.pts.first().idx + spanMin)
            int   right = math.min(s.pts.first().idx + spanMax, bar_index + 500)
            if not seen.includes(code) and not fired.includes(keyOf(s.pi, c)) and left <= right
                // only the part a new C->D extreme can still reach
                float lo = s.bull ? s.zLo : math.max(s.zLo, s.run)
                float hi = s.bull ? math.min(s.zHi, s.run) : s.zHi
                if lo <= hi
                    seen.push(code)
                    color col  = s.bull ? bullCol : bearCol
                    int   slot = s.bull ? 1 : 0
                    proj.boxes.push(box.new(left, hi, right, lo, border_color = color.new(col, 40), border_style = line.style_dashed, bgcolor = color.new(col, 85)))
                    for i = 0 to s.pts.size() - 2
                        Pivot u = s.pts.get(i)
                        Pivot w = s.pts.get(i + 1)
                        proj.lines.push(line.new(u.idx, u.price, w.idx, w.price, color = color.new(col, 40), style = line.style_dashed))
                    if nms.get(slot) == ""
                        lxs.set(slot, math.max(left, math.min(right, bar_index + 5)))   // near the last bar, not 300 bars out
                        lys.set(slot, (lo + hi) / 2)
                        nms.set(slot, pats.get(s.pi).name)
                    else
                        nms.set(slot, nms.get(slot) + ", " + pats.get(s.pi).name)
        for slot = 0 to 1
            if nms.get(slot) != ""
                color col = slot == 1 ? bullCol : bearCol
                proj.labels.push(label.new(lxs.get(slot), lys.get(slot), "possible " + (slot == 1 ? "bull" : "bear") + " D: " + nms.get(slot), color = color.new(col, 100), textcolor = col, style = label.style_label_left, size = size.tiny))
 
// ============================================================================ alerts
// One aggregated alert per closed bar (create it with "Any alert() function call"; alerts are realtime-only).
if alertMsg != ""
    alert(syminfo.prefix + ":" + syminfo.ticker + " " + tfStr() + ": " + alertMsg, alert.freq_once_per_bar_close)

← 返回列表