Chart Patterns: Triangles and Wedges [Saikix]

Saikix · study · 884 行 · 点赞 568 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Chart Patterns: Triangles and Wedges [Saikix]
// © Saikix
 
//@version=6
indicator("Chart Patterns: Triangles and Wedges [Saikix]", shorttitle="Saikix-Triangle", overlay=true, max_lines_count=500, max_labels_count=500, max_bars_back=1000, behind_chart=false)
 
G_DET = "Detection"
tfIn    = input.timeframe("", "Timeframe", group=G_DET, display=display.none,
     tooltip="The timeframe the patterns are found on. Empty = chart timeframe. A timeframe lower than the chart's uses the chart's. Swings, breaks, retests, targets and alerts are checked when a bar of this timeframe closes, and the lines are drawn through the chart bars where those highs and lows were made. Bars, as in Minimum bars, count bars of this timeframe. Patterns need enough history of this timeframe: on a much lower chart timeframe, scroll the chart back to load more bars.")
onS     = input.bool(true, "Small swings", inline="s", group=G_DET, display=display.none)
lenS    = input.int(6, "", minval=2, maxval=60, inline="s", group=G_DET, display=display.none)
onM     = input.bool(true, "Medium swings", inline="m", group=G_DET, display=display.none)
lenM    = input.int(12, "", minval=2, maxval=60, inline="m", group=G_DET, display=display.none)
onL     = input.bool(true, "Large swings", inline="l", group=G_DET, display=display.none)
lenL    = input.int(24, "", minval=2, maxval=60, inline="l", group=G_DET, display=display.none,
     tooltip="Each size finds its own patterns, so small patterns can sit inside big ones. A swing high is higher than this many bars before it and not lower than a third as many bars after it (at least 2), and highs and lows always alternate. A swing is confirmed that many bars later, so a pattern appears a few bars after its last touch.")
avoidOv = input.bool(true, "Avoid overlap", group=G_DET, display=display.none,
     tooltip="Patterns of a similar size never overlap. A pattern at least twice as long (first touch to last touch) can still enclose smaller patterns, one level deep, so a big triangle shows with the small ones inside it. Turn this off to let patterns of every size overlap.")
minH    = input.float(3.0, "Minimum height (× ATR)", minval=0.0, maxval=20.0, step=0.5, group=G_DET, display=display.none,
     tooltip="Hide patterns lower than this many ATR (14). The height is measured between the two lines where both have started. 0 = any height.")
minBars = input.int(10, "Minimum bars", minval=4, maxval=200, group=G_DET, display=display.none,
     tooltip="From the first touch to the last touch.")
maxBars = input.int(200, "Maximum bars", minval=20, maxval=400, group=G_DET, display=display.none,
     tooltip="From the first touch to the apex, where the two lines meet.")
flatPct = input.int(20, "Flat line (%)", minval=0, maxval=45, group=G_DET, display=display.none,
     tooltip="A line counts as flat when its slope is at most this share of the two slopes added together. Ascending: flat upper line, rising lower line. Descending: falling upper line, flat lower line. Symmetrical: falling upper line, rising lower line. Rising wedge: both lines rising, neither flat. Falling wedge: both lines falling, neither flat.")
poleMul = input.float(2.0, "Pennant pole (× height)", minval=1.0, maxval=10.0, step=0.5, group=G_DET, display=display.none,
     tooltip="A pennant is a triangle right after a sharp move (the pole). The pole must be at least this many times the triangle's height, within as many bars before the triangle as the triangle is long, and the triangle must not retrace more than half of it.")
 
G_TYPE = "Patterns to show"
shSym = input.bool(true, "Symmetrical", group=G_TYPE, display=display.none)
shAsc = input.bool(true, "Ascending", group=G_TYPE, display=display.none)
shDsc = input.bool(true, "Descending", group=G_TYPE, display=display.none)
shPen = input.bool(true, "Pennant", group=G_TYPE, display=display.none,
     tooltip="With Pennant off, a pennant is shown as the triangle it is shaped like.")
shRW  = input.bool(true, "Rising wedge", group=G_TYPE, display=display.none)
shFW  = input.bool(true, "Falling wedge", group=G_TYPE, display=display.none)
shForm = input.bool(true, "Show forming pattern", group=G_TYPE, display=display.none,
     tooltip="A pattern whose 4th touch is not confirmed yet, drawn with dashed lines and \"(forming)\" after its name. It uses the lowest low (highest high) since the last confirmed touch, checked at bar close. It becomes a normal pattern when the touch is confirmed, or disappears if price breaks the shape first. Alerts are sent only for confirmed patterns.")
 
G_SIG = "Break, retest and target"
showBrk = input.bool(true, "Show breaks", group=G_SIG, display=display.none,
     tooltip="The first close outside the pattern before the apex. Checked at bar close.")
showRt  = input.bool(true, "Show retests", group=G_SIG, display=display.none,
     tooltip="After a break, price moves away from the break level (the broken line's price at the break), comes back to it and closes on the broken side, within 20 bars of the break. A close back beyond the break level cancels it.")
showTgt = input.bool(true, "Show targets", group=G_SIG, display=display.none,
     tooltip="The pattern's height measured from the broken line at the break. For a pennant broken in the direction of its pole, the pole's length. Drawn for as many bars as the pattern is long, and stopped at a failed break.")
 
G_PAST = "Past patterns"
pastN = input.int(20, "Past patterns to show", minval=0, maxval=50, group=G_PAST, display=display.none,
     tooltip="Older patterns, with their breaks, retests and targets, in lighter colors.")
 
G_STYLE = "Colors and text"
cSym    = input.color(#3F51B5, "Triangle colors", inline="ct", group=G_STYLE, display=display.none)
cAsc    = input.color(#00897B, "", inline="ct", group=G_STYLE, display=display.none)
cDsc    = input.color(#F57C00, "", inline="ct", group=G_STYLE, display=display.none,
     tooltip="Symmetrical, ascending, descending.")
cRW     = input.color(#D81B60, "Wedge and pennant colors", inline="cw", group=G_STYLE, display=display.none)
cFW     = input.color(#039BE5, "", inline="cw", group=G_STYLE, display=display.none)
cPen    = input.color(#8E24AA, "", inline="cw", group=G_STYLE, display=display.none,
     tooltip="Rising wedge, falling wedge, pennant.")
colUp   = input.color(#089981, "Break colors", inline="cb", group=G_STYLE, display=display.none)
colDn   = input.color(#F23645, "", inline="cb", group=G_STYLE, display=display.none,
     tooltip="Up and down: the Break and Retest labels and the target line.")
lineW   = input.int(2, "Line width", minval=1, maxval=5, group=G_STYLE, display=display.none)
fillT   = input.int(88, "Fill transparency", minval=0, maxval=100, group=G_STYLE, display=display.none)
showNum = input.bool(true, "Show touch numbers", group=G_STYLE, display=display.none,
     tooltip="1 to 4 on the two highs and two lows the lines are drawn through.")
txtSize = input.int(13, "Text size", minval=8, maxval=30, group=G_STYLE, display=display.none)
 
G_ALERT = "Alerts"
alWhich = input.string("All", "Patterns to alert", options=["All", "Triangles (symmetrical, ascending, descending)", "Wedges (rising, falling)", "Pennants (bullish, bearish)", "Only symmetrical triangle", "Only ascending triangle", "Only descending triangle", "Only rising wedge", "Only falling wedge", "Only bullish pennant", "Only bearish pennant"], group=G_ALERT, display=display.none,
     tooltip="One alert for everything checked below: create the alert with \"Any alert() function call\". Sent when a bar closes, never on past bars. Independent of what is shown on the chart, but a pattern turned off in Patterns to show is not found, so it is not alerted either.\nFor a separate alert (or webhook) per event, pick the event in the alert's Condition list instead, e.g. \"Break up\".")
alDir   = input.string("Up and down", "Directions to alert", options=["Up and down", "Up only", "Down only"], group=G_ALERT, display=display.none,
     tooltip="For Testing a line (up = the upper line), Break, Retest, Target reached and Failed break.")
alForm  = input.bool(true, "Pattern formed", group=G_ALERT, display=display.none,
     tooltip="A new pattern appeared on the chart. The message has its upper and lower line prices and the bars left to the apex.")
alTest  = input.bool(false, "Testing a line", group=G_ALERT, display=display.none,
     tooltip="A closed bar of a pattern still forming reached the upper or lower line (within 0.25 ATR) and closed inside. It comes before a break, so you can watch the next bars. Once per visit to the line.")
alBrk   = input.bool(true, "Break", group=G_ALERT, display=display.none)
alRt    = input.bool(true, "Retest", group=G_ALERT, display=display.none)
alTgt   = input.bool(true, "Target reached", group=G_ALERT, display=display.none)
alFail  = input.bool(true, "Failed break", group=G_ALERT, display=display.none,
     tooltip="Within 20 bars of a break, a close back beyond the break level (by 0.25 ATR), before the target is reached. After a failed break, the target is no longer watched.")
alNoBrk = input.bool(true, "No break", group=G_ALERT, display=display.none,
     tooltip="The pattern reached its apex without a break.")
alFmt   = input.string("Text", "Message format", options=["Text", "JSON"], group=G_ALERT, display=display.none,
     tooltip="JSON is for webhooks: indicator, ticker, chart_tf, pattern_tf, price and a list of events (type, pattern, direction or line, and the prices of that event).")
 
TOL    = 0.25
SEP    = 0.50
RR_WIN = 20
MIN_W  = 0.25
RETR   = 0.5
DUP    = 2
PAST_T = 40
NEST   = 2.0
 
bool   useHtf = tfIn != "" and timeframe.in_seconds(tfIn) > timeframe.in_seconds(timeframe.period)
string tfEff  = useHtf ? tfIn : timeframe.period
var array<float> uH  = array.new<float>()
var array<float> uL  = array.new<float>()
var array<float> uC  = array.new<float>()
var array<float> uA  = array.new<float>()
var array<int>   uHB = array.new<int>()
var array<int>   uLB = array.new<int>()
var array<int>   uBI = array.new<int>()
var array<int>   uEB = array.new<int>()
var int   ui     = 0
var int   openU  = 0
var float bpu    = 1.0
var float trSum  = 0.0
var int   lastProc = -1
 
rightOf(int L) => int(math.max(2, math.round(L / 3.0)))
R_S = rightOf(lenS)
R_M = rightOf(lenM)
R_L = rightOf(lenL)
 
tfLabel(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec < 3600 ? str.tostring(math.round(sec / 60.0), "#") + "m" : sec < 86400 ? str.tostring(math.round(sec / 3600.0), "#") + "h" : sec < 604800 ? "D" : sec < 2419200 ? "W" : "M"
 
fmtP(float p) => str.tostring(p, format.mintick)
 
type Tri
    string   kind
    int      pdir
    int      xu
    float    yu
    float    su
    int      xl
    float    yl
    float    sl
    int      sx
    int      lastX
    float    apex
    float    h0
    float    pole
    int      poleX
    float    poleY
    int      xu2
    float    yu2
    int      xl2
    float    yl2
    int      state = 0
    int      endX
    float    brkLvl
    float    tgt
    int      tgtEnd
    int      hitX
    int      rrPhase = 0
    int      rtX
    bool     rtDone = false
    bool     past = false
    bool     hidden = false
    bool     nmBelow = false
    line     lu
    line     ll
    line     eu
    line     el
    linefill lf
    line     lp
    label    nm
    array<label> nums
    label    lbB
    label    lbR
    line     lt
    label    lbT
    int      lastTU
    int      lastTL
    bool     failDone = false
    bool     failed = false
    bool     outer = false
    bool     inner = false
    bool     forming = false
    int      cxu
    int      cxu2
    int      cxl
    int      cxl2
    int      cpoleX
    float    csu
    float    csl
    float    capex
 
type Lvl
    bool        on
    int         L
    int         R
    array<int>   zx
    array<float> zy
    array<int>   zk
    Tri         cur
    int         lastEnd = 0
 
uAt(Tri t, int x) => t.yu + t.su * (x - t.xu)
lAt(Tri t, int x) => t.yl + t.sl * (x - t.xl)
 
kindName(Tri t) =>
    t.kind == "Pennant" ? (t.pdir == 1 ? "Bullish pennant" : "Bearish pennant") : str.contains(t.kind, "wedge") ? t.kind : t.kind + " triangle"
 
method kindCol(Tri t) =>
    t.kind == "Symmetrical" ? cSym : t.kind == "Ascending" ? cAsc : t.kind == "Descending" ? cDsc : t.kind == "Rising wedge" ? cRW : t.kind == "Falling wedge" ? cFW : cPen
 
method dirCol(Tri t) =>
    t.state == 1 ? colUp : colDn
 
method barsToApex(Tri t) =>
    int(math.max(1, math.ceil(t.apex - openU)))
 
method nameText(Tri t) =>
    int left = t.barsToApex()
 
    string pre = useHtf ? tfLabel(tfEff) + " " : ""
    t.forming ? pre + kindName(t) + " (forming)" : pre + kindName(t) + (t.state == 0 ? " · " + str.tostring(left) + (left == 1 ? " bar" : " bars") + " to apex" : t.state == 2 ? " · No break" : "")
 
newLvl(bool on, int L, int R) => Lvl.new(on, L, R, array.new<int>(), array.new<float>(), array.new<int>(), na, 0)
 
var Lvl lvS = newLvl(onS, lenS, R_S)
var Lvl lvM = newLvl(onM, lenM, R_M)
var Lvl lvL = newLvl(onL, lenL, R_L)
 
method zzAdd(Lvl lv, int x, float y, int k) =>
    bool changed = false
    int n = lv.zk.size()
    if n > 0 and lv.zk.get(n - 1) == k
        if (k == 1 and y > lv.zy.get(n - 1)) or (k == -1 and y < lv.zy.get(n - 1))
            lv.zx.set(n - 1, x)
            lv.zy.set(n - 1, y)
            changed := true
    else
        lv.zx.push(x)
        lv.zy.push(y)
        lv.zk.push(k)
        if lv.zk.size() > 6
            lv.zx.shift()
            lv.zy.shift()
            lv.zk.shift()
        changed := true
    changed
 
method pivots(Lvl lv) =>
    bool changed = false
    if lv.on and ui >= lv.L + lv.R
        int   p   = ui - lv.R
        float hp  = uH.get(p)
        float lp  = uL.get(p)
        float hiL = uH.get(p - 1)
        float loL = uL.get(p - 1)
        for x = p - lv.L to p - 1
            hiL := math.max(hiL, uH.get(x))
            loL := math.min(loL, uL.get(x))
        float hiR = uH.get(p + 1)
        float loR = uL.get(p + 1)
        for x = p + 1 to ui
            hiR := math.max(hiR, uH.get(x))
            loR := math.min(loR, uL.get(x))
        if hp > hiL and hp >= hiR
            changed := lv.zzAdd(p, hp, 1) or changed
        if lp < loL and lp <= loR
            changed := lv.zzAdd(p, lp, -1) or changed
    changed
 
shapeOf(array<int> px, array<float> py, array<int> pk, int lastEnd) =>
    Tri res = na
    float aNow = uA.get(ui)
    if not na(aNow)
        int   xu1 = na
        float yu1 = na
        int   xu2 = na
        float yu2 = na
        int   xl1 = na
        float yl1 = na
        int   xl2 = na
        float yl2 = na
        for i = 0 to 3
            if pk.get(i) == 1
                if na(xu1)
                    xu1 := px.get(i)
                    yu1 := py.get(i)
                else
                    xu2 := px.get(i)
                    yu2 := py.get(i)
            else
                if na(xl1)
                    xl1 := px.get(i)
                    yl1 := py.get(i)
                else
                    xl2 := px.get(i)
                    yl2 := py.get(i)
        float su = (yu2 - yu1) / (xu2 - xu1)
        float sl = (yl2 - yl1) / (xl2 - xl1)
        int sx    = int(math.min(xu1, xl1))
        int bx    = int(math.max(xu1, xl1))
        int lastX = int(math.max(xu2, xl2))
        float h0  = (yu1 + su * (bx - xu1)) - (yl1 + sl * (bx - xl1))
        float atrBx = uA.get(bx)
        if su < sl and h0 > 0 and sx >= lastEnd and (na(atrBx) or h0 >= minH * atrBx)
            float apex = (yl1 - sl * xl1 - yu1 + su * xu1) / (su - sl)
            float shU  = math.abs(su) / (math.abs(su) + math.abs(sl))
            float flat = flatPct / 100.0
            string kind = shU <= flat and sl > 0 ? "Ascending" : 1 - shU <= flat and su < 0 ? "Descending" : su < 0 and sl > 0 ? "Symmetrical" : su > 0 and sl > 0 ? "Rising wedge" : su < 0 and sl < 0 ? "Falling wedge" : ""
            float wNow = (yu1 + su * (ui - xu1)) - (yl1 + sl * (ui - xl1))
            if kind != "" and lastX - sx >= minBars and apex > ui and apex - sx <= maxBars and wNow >= MIN_W * h0
                float tol = TOL * aNow
                bool ok = true
                for x = xu1 to ui
                    if uH.get(x) > yu1 + su * (x - xu1) + tol
                        ok := false
                        break
                if ok
                    for x = xl1 to ui
                        if uL.get(x) < yl1 + sl * (x - xl1) - tol
                            ok := false
                            break
                if ok
                    for x = bx to ui
                        float c = uC.get(x)
                        if c > yu1 + su * (x - xu1) or c < yl1 + sl * (x - xl1)
                            ok := false
                            break
                if ok
 
                    int   k0   = int(math.max(0, sx - (lastX - sx)))
                    int   pdir = xu1 < xl1 ? 1 : -1
                    int   poleX = sx
                    float poleY = pdir == 1 ? uL.get(sx) : uH.get(sx)
                    for x = k0 to sx
                        float v = pdir == 1 ? uL.get(x) : uH.get(x)
                        if (pdir == 1 and v < poleY) or (pdir == -1 and v > poleY)
                            poleY := v
                            poleX := x
                    float pole = pdir == 1 ? yu1 - poleY : poleY - yl1
                    float ext  = pdir == 1 ? uL.get(sx) : uH.get(sx)
                    for x = sx to ui
                        float v = pdir == 1 ? uL.get(x) : uH.get(x)
                        ext := pdir == 1 ? math.min(ext, v) : math.max(ext, v)
                    float retr = pole > 0 ? (pdir == 1 ? yu1 - ext : ext - yl1) / pole : 9.0
                    bool triShape = kind == "Symmetrical" or kind == "Ascending" or kind == "Descending"
                    bool isPen = shPen and triShape and pole >= poleMul * h0 and retr <= RETR
                    bool want = isPen or (kind == "Symmetrical" ? shSym : kind == "Ascending" ? shAsc : kind == "Descending" ? shDsc : kind == "Rising wedge" ? shRW : shFW)
                    if want
                        res := Tri.new(isPen ? "Pennant" : kind, isPen ? pdir : 0, xu1, yu1, su, xl1, yl1, sl, sx, lastX, apex, h0, isPen ? pole : 0.0, isPen ? poleX : na, isPen ? poleY : na, xu2, yu2, xl2, yl2)
    res
 
method detect(Lvl lv) =>
    Tri res = na
    int n = lv.zk.size()
    if n >= 4
        res := shapeOf(lv.zx.slice(n - 4, n), lv.zy.slice(n - 4, n), lv.zk.slice(n - 4, n), lv.lastEnd)
    res
 
method tentative(Lvl lv) =>
    Tri res = na
    int n = lv.zk.size()
    if lv.on and na(lv.cur) and n >= 3
        int xk = lv.zx.get(n - 1)
        int k  = lv.zk.get(n - 1)
        if xk < ui
            int   j = xk + 1
            float v = k == 1 ? uL.get(j) : uH.get(j)
            for x = xk + 1 to ui
                float w = k == 1 ? uL.get(x) : uH.get(x)
                if (k == 1 and w < v) or (k == -1 and w > v)
                    v := w
                    j := x
            bool leftOk = j >= lv.L
            if leftOk
                for x = j - lv.L to j - 1
                    float w = k == 1 ? uL.get(x) : uH.get(x)
                    if (k == 1 and w <= v) or (k == -1 and w >= v)
                        leftOk := false
                        break
            if leftOk
                array<int>   px = array.copy(lv.zx.slice(n - 3, n))
                array<float> py = array.copy(lv.zy.slice(n - 3, n))
                array<int>   pk = array.copy(lv.zk.slice(n - 3, n))
                px.push(j)
                py.push(v)
                pk.push(-k)
                res := shapeOf(px, py, pk, lv.lastEnd)
    res
 
method toChart(Tri t) =>
    t.cxu  := uHB.get(t.xu)
    t.cxu2 := uHB.get(t.xu2)
    t.cxl  := uLB.get(t.xl)
    t.cxl2 := uLB.get(t.xl2)
    t.csu  := (t.yu2 - t.yu) / math.max(1, t.cxu2 - t.cxu)
    t.csl  := (t.yl2 - t.yl) / math.max(1, t.cxl2 - t.cxl)
 
    t.capex := t.csu < t.csl ? (t.yl - t.csl * t.cxl - t.yu + t.csu * t.cxu) / (t.csu - t.csl) : uEB.get(ui) + (t.apex - ui) * bpu
    if t.kind == "Pennant"
        t.cpoleX := t.pdir == 1 ? uLB.get(t.poleX) : uHB.get(t.poleX)
    t.cxu
 
futX(int x) => int(math.min(x, bar_index + 490))
 
ucAt(Tri t, int x) => t.yu + t.csu * (x - t.cxu)
lcAt(Tri t, int x) => t.yl + t.csl * (x - t.cxl)
 
method drawNew(Tri t) =>
    t.toChart()
    int x  = bar_index
    int ax = futX(int(math.floor(t.capex)))
    color c = t.kindCol()
    string st = t.forming ? line.style_dashed : line.style_solid
    t.lu := line.new(t.cxu, t.yu, x, ucAt(t, x), xloc=xloc.bar_index, color=c, width=lineW, style=st)
    t.ll := line.new(t.cxl, t.yl, x, lcAt(t, x), xloc=xloc.bar_index, color=c, width=lineW, style=st)
    t.lf := linefill.new(t.lu, t.ll, color.new(c, t.forming ? math.min(100, fillT + 6) : fillT))
    t.eu := line.new(x, ucAt(t, x), ax, ucAt(t, ax), xloc=xloc.bar_index, color=c, width=1, style=line.style_dotted)
    t.el := line.new(x, lcAt(t, x), ax, lcAt(t, ax), xloc=xloc.bar_index, color=c, width=1, style=line.style_dotted)
    if t.kind == "Pennant"
        t.lp := line.new(t.cpoleX, t.poleY, t.pdir == 1 ? t.cxu : t.cxl, t.pdir == 1 ? t.yu : t.yl, xloc=xloc.bar_index, color=c, width=1)
 
    bool below = t.nmBelow
    t.nm := label.new(below ? t.cxl : t.cxu, below ? t.yl : t.yu, t.nameText(), xloc=xloc.bar_index,
         style=below ? label.style_label_up : label.style_label_down, color=t.forming ? color.new(c, 30) : c, textcolor=color.white, size=txtSize,
         tooltip=t.forming ? "Forming: the 4th touch is not confirmed yet. It becomes a pattern when the touch is confirmed, or disappears if price breaks the shape first." : "")
 
    t.nums := array.new<label>()
    if showNum
        array<int>   xs = array.from(t.cxu, t.cxu2, t.cxl, t.cxl2)
        array<float> ys = array.from(t.yu, t.yu2, t.yl, t.yl2)
        array<bool>  hs = array.from(true, true, false, false)
        array<int>   ix = array.from(0, 1, 2, 3)
        for a = 0 to 2
            for b = 0 to 2 - a
                if xs.get(ix.get(b)) > xs.get(ix.get(b + 1))
                    int tmp = ix.get(b)
                    ix.set(b, ix.get(b + 1))
                    ix.set(b + 1, tmp)
        for i = 0 to 3
            int  j = ix.get(i)
            bool h = hs.get(j)
            bool atName = below ? (not h and xs.get(j) == t.cxl) : (h and xs.get(j) == t.cxu)
            if not atName and not (t.forming and i == 3)
                t.nums.push(label.new(xs.get(j), ys.get(j), str.tostring(i + 1), xloc=xloc.bar_index,
                     style=h ? label.style_label_down : label.style_label_up, color=color.new(c, 100), textcolor=c, size=math.max(8, txtSize - 2)))
 
method extendNow(Tri t) =>
    int x  = bar_index
    int ax = futX(int(math.floor(t.capex)))
    int xe = int(math.max(x, ax))
    t.lu.set_xy2(x, ucAt(t, x))
    t.ll.set_xy2(x, lcAt(t, x))
    t.eu.set_xy1(x, ucAt(t, x))
    t.el.set_xy1(x, lcAt(t, x))
    t.eu.set_xy2(xe, ucAt(t, xe))
    t.el.set_xy2(xe, lcAt(t, xe))
    t.nm.set_text(t.nameText())
 
method restyle(Tri t) =>
    color base = t.kindCol()
    color c    = t.past ? color.new(base, PAST_T) : base
    int   w    = t.past ? 1 : lineW
    t.lu.set_color(c)
    t.ll.set_color(c)
    t.lu.set_width(w)
    t.ll.set_width(w)
    if t.state == 2
        t.lu.set_style(line.style_dashed)
        t.ll.set_style(line.style_dashed)
    t.lf.set_color(color.new(base, t.past ? math.min(100, fillT + 6) : fillT))
    if not na(t.lp)
        t.lp.set_color(c)
    t.nm.set_color(c)
    t.nm.set_text(t.nameText())
    for lb in t.nums
        lb.set_textcolor(c)
    if t.state == 1 or t.state == -1
        color d = t.past ? color.new(t.dirCol(), PAST_T) : t.dirCol()
        if not na(t.lbB)
            t.lbB.set_color(d)
 
        if t.past
            label.delete(t.lbR)
            line.delete(t.lt)
            label.delete(t.lbT)
            t.lbR := na
            t.lt  := na
            t.lbT := na
        else
            if not na(t.lbR)
                t.lbR.set_color(d)
            if not na(t.lt)
                t.lt.set_color(d)
            if not na(t.lbT)
                t.lbT.set_textcolor(d)
    t.past
 
method finish(Tri t) =>
 
    int x = t.state == 2 ? int(math.min(bar_index, math.floor(t.capex))) : uEB.get(t.endX)
    t.lu.set_xy2(x, ucAt(t, x))
    t.ll.set_xy2(x, lcAt(t, x))
    line.delete(t.eu)
    line.delete(t.el)
    t.eu := na
    t.el := na
    bool up = t.state == 1
    if t.state == 1 or t.state == -1
        color d = t.dirCol()
        if showBrk
            t.lbB := label.new(x, up ? low[bar_index - x] : high[bar_index - x], "Break", xloc=xloc.bar_index, yloc=up ? yloc.belowbar : yloc.abovebar,
                 style=up ? label.style_label_up : label.style_label_down, color=d, textcolor=color.white, size=txtSize)
        if showTgt
            int xt = futX(x + int(math.round((t.tgtEnd - t.endX) * bpu)))
            t.lt  := line.new(x, t.tgt, xt, t.tgt, xloc=xloc.bar_index, color=d, width=1, style=line.style_dashed)
 
            t.lbT := label.new(x, t.tgt, "Target " + fmtP(t.tgt), xloc=xloc.bar_index,
                 style=up ? label.style_label_lower_left : label.style_label_upper_left, color=color.new(d, 100), textcolor=d, size=txtSize)
    t.restyle()
 
method dropDrawings(Tri t) =>
    line.delete(t.lu)
    line.delete(t.ll)
    line.delete(t.eu)
    line.delete(t.el)
    linefill.delete(t.lf)
    line.delete(t.lp)
    label.delete(t.nm)
    for lb in t.nums
        label.delete(lb)
    label.delete(t.lbB)
    label.delete(t.lbR)
    line.delete(t.lt)
    label.delete(t.lbT)
    t.hidden := true
 
var array<Tri> tris = array.new<Tri>()
 
array<Tri> evF  = array.new<Tri>()
array<Tri> evTU = array.new<Tri>()
array<Tri> evTL = array.new<Tri>()
array<Tri> evB  = array.new<Tri>()
array<Tri> evR  = array.new<Tri>()
array<Tri> evT  = array.new<Tri>()
array<Tri> evX  = array.new<Tri>()
array<Tri> evN  = array.new<Tri>()
 
method checkBreak(Lvl lv, array<Tri> evOut, array<Tri> evNone) =>
    Tri cur = lv.cur
    if not na(cur) and cur.state == 0
        int x = ui
        float u  = uAt(cur, x)
        float d  = lAt(cur, x)
        float cl = uC.get(x)
        if x < cur.apex and (cl > u or cl < d)
            cur.state  := cl > u ? 1 : -1
            cur.endX   := x
            float lvl   = cl > u ? u : d
            cur.brkLvl := lvl
            float hgt   = cur.kind == "Pennant" and cur.pdir == cur.state ? cur.pole : cur.h0
            cur.tgt    := lvl + cur.state * hgt
            cur.tgtEnd := x + int(math.max(1, math.round(cur.apex - cur.sx)))
            lv.lastEnd := x
            evOut.push(cur)
            cur.finish()
            lv.cur := na
        else if x >= cur.apex
            cur.state := 2
            cur.endX  := int(math.floor(cur.apex))
            lv.lastEnd := x
            evNone.push(cur)
            cur.finish()
            lv.cur := na
 
method checkTest(Lvl lv, array<Tri> evU, array<Tri> evL) =>
    Tri cur = lv.cur
    if not na(cur) and cur.state == 0
        int x = ui
        float tol = TOL * uA.get(ui)
        if uH.get(ui) >= uAt(cur, x) - tol
            if na(cur.lastTU) or cur.lastTU < x - 1
                evU.push(cur)
            cur.lastTU := x
        if uL.get(ui) <= lAt(cur, x) + tol
            if na(cur.lastTL) or cur.lastTL < x - 1
                evL.push(cur)
            cur.lastTL := x
 
encOf(Tri t, array<Tri> all) =>
    array<Tri> enc = array.new<Tri>()
    bool ok = true
    if avoidOv
        int tLen = t.lastX - t.sx
        for p in all
            int pEnd = p.state == 0 ? ui : p.endX
            if t.sx < pEnd
                if p.outer or tLen < NEST * (p.lastX - p.sx)
                    ok := false
                    break
                enc.push(p)
    [ok, enc]
 
isDup(Tri t, array<Tri> all) =>
    bool dup = false
    int n = all.size()
    if n > 0
        for i = n - 1 to int(math.max(0, n - 40))
            Tri p = all.get(i)
            if math.abs(p.xu - t.xu) <= DUP and math.abs(p.xl - t.xl) <= DUP
                dup := true
                break
    dup
 
placeBelow(Tri t, array<Tri> all) =>
    bool below = t.kind == "Pennant" and t.pdir == -1
    int n = all.size()
    if n > 0
        for i = n - 1 to int(math.max(0, n - 40))
            Tri p = all.get(i)
            if not p.hidden and p.nmBelow == below
                int   qx = below ? p.xl : p.xu
                float qy = below ? p.yl : p.yu
                int   tx = below ? t.xl : t.xu
                float ty = below ? t.yl : t.yu
                if math.abs(qx - tx) <= 10 and math.abs(qy - ty) <= uA.get(ui)
                    below := not below
                    break
    below
 
method tryNew(Lvl lv, bool changed, array<Tri> all, array<Tri> evOut) =>
    if lv.on and changed and na(lv.cur)
        Tri t = lv.detect()
        if not na(t)
            [ok, enc] = encOf(t, all)
            if ok and not isDup(t, all)
                for p in enc
                    p.inner := true
                t.outer := enc.size() > 0
                t.nmBelow := placeBelow(t, all)
                t.drawNew()
                all.push(t)
                lv.cur := t
                evOut.push(t)
 
formingOf(Lvl lv, array<Tri> all) =>
    Tri t = lv.tentative()
    if not na(t)
        [ok, enc] = encOf(t, all)
        if not ok or isDup(t, all)
            t := na
    t
 
bool tfChg   = timeframe.change(tfEff)
bool closesU = useHtf ? time_close == time_close(tfEff) : true
openU := (uH.size() == 0 or tfChg) ? uH.size() : uH.size() - 1
 
if barstate.isconfirmed
    bool startNew = uH.size() == 0 or tfChg
 
    int pend1 = startNew and uH.size() - 1 > lastProc ? uH.size() - 1 : -1
 
    if startNew
        uH.push(high)
        uL.push(low)
        uC.push(close)
        uHB.push(bar_index)
        uLB.push(bar_index)
        uBI.push(bar_index)
        uEB.push(bar_index)
    else
        int n = uH.size() - 1
        if high > uH.get(n)
            uH.set(n, high)
            uHB.set(n, bar_index)
        if low < uL.get(n)
            uL.set(n, low)
            uLB.set(n, bar_index)
        uC.set(n, close)
        uEB.set(n, bar_index)
    int pend2 = closesU ? uH.size() - 1 : -1
    for pass = 0 to 1
        int k = pass == 0 ? pend1 : pend2
        if k >= 0 and k > lastProc
            lastProc := k
            ui := k
 
            float tr = k == 0 ? uH.get(k) - uL.get(k) : math.max(uH.get(k) - uL.get(k), math.abs(uH.get(k) - uC.get(k - 1)), math.abs(uL.get(k) - uC.get(k - 1)))
            if k < 14
                trSum += tr
                uA.push(k == 13 ? trSum / 14 : na)
            else
                uA.push((uA.get(k - 1) * 13 + tr) / 14)
            int k0 = math.max(0, k - 20)
            bpu := (uEB.get(k) - uBI.get(k0) + 1) / (k - k0 + 1.0)
            bool chS = lvS.pivots()
            bool chM = lvM.pivots()
            bool chL = lvL.pivots()
 
            lvS.checkBreak(evB, evN)
            lvM.checkBreak(evB, evN)
            lvL.checkBreak(evB, evN)
            lvS.checkTest(evTU, evTL)
            lvM.checkTest(evTU, evTL)
            lvL.checkTest(evTU, evTL)
 
            if tris.size() > 0
                for i = tris.size() - 1 to 0
                    Tri t = tris.get(i)
                    if (t.state == 1 or t.state == -1) and ui > t.endX and ui <= t.endX + math.max(RR_WIN, t.tgtEnd - t.endX)
                        int s = t.state
                        if na(t.hitX) and not t.failed and ui <= t.tgtEnd
                            if (s == 1 and uH.get(ui) >= t.tgt) or (s == -1 and uL.get(ui) <= t.tgt)
                                t.hitX := ui
                                evT.push(t)
                                if not t.hidden and not na(t.lt)
                                    t.lt.set_x2(uEB.get(ui))
                                    t.lbT.set_text("Target reached " + fmtP(t.tgt))
 
                        if not t.failDone and ui <= t.endX + RR_WIN
                            if not na(t.hitX)
                                t.failDone := true
                            else if (uC.get(ui) - t.brkLvl) * s < -TOL * uA.get(ui)
                                t.failDone := true
                                t.failed   := true
                                evX.push(t)
 
                                if not t.hidden and not na(t.lt)
                                    t.lt.set_x2(uEB.get(ui))
                        if not t.rtDone and ui <= t.endX + RR_WIN
                            float lv  = t.brkLvl
                            float tol = TOL * uA.get(ui)
                            float sep = SEP * uA.get(ui)
                            float c   = (uC.get(ui) - lv) * s
                            float ee  = ((s == 1 ? uL.get(ui) : uH.get(ui)) - lv) * s
                            if c < -tol
                                t.rtDone := true
                            else if t.rrPhase == 0
                                if ee >= tol + sep
                                    t.rrPhase := 1
                            else
                                if t.rrPhase == 1 and ee <= tol
                                    t.rrPhase := 2
                                if t.rrPhase == 2 and c > 0
                                    t.rtX    := ui
                                    t.rtDone := true
                                    evR.push(t)
                                    if showRt and not t.hidden and not t.past
                                        bool up = s == 1
                                        color d = t.past ? color.new(t.dirCol(), PAST_T) : t.dirCol()
                                        t.lbR := label.new(uEB.get(ui), up ? uL.get(ui) : uH.get(ui), "Retest", xloc=xloc.bar_index, yloc=up ? yloc.belowbar : yloc.abovebar,
                                             style=up ? label.style_label_up : label.style_label_down, color=d, textcolor=color.white, size=txtSize)
 
            int before = tris.size()
            lvL.tryNew(chL, tris, evF)
            lvM.tryNew(chM, tris, evF)
            lvS.tryNew(chS, tris, evF)
 
            for p in tris
                if not p.past and (p.state == 2 or ((p.state == 1 or p.state == -1) and ui > p.tgtEnd))
                    p.past := true
                    if not p.hidden
                        p.restyle()
            if tris.size() > before
 
                int shown = 0
                for i = tris.size() - 1 to 0
                    Tri p = tris.get(i)
                    if not p.hidden and p.state != 0
                        shown += 1
                        if shown > pastN
                            p.dropDrawings()
                while tris.size() > 0
                    Tri p = tris.first()
                    bool waiting = p.state == 0 or ((p.state == 1 or p.state == -1) and ui <= p.endX + math.max(RR_WIN, p.tgtEnd - p.endX))
                    if p.hidden and not waiting
                        tris.shift()
                    else
                        break
 
var Tri fm = na
if barstate.isconfirmed and (barstate.islastconfirmedhistory or barstate.isrealtime) and lastProc >= 0
    if not na(fm)
        fm.dropDrawings()
        fm := na
    if shForm
        Tri best = na
        for c in array.from(formingOf(lvL, tris), formingOf(lvM, tris), formingOf(lvS, tris))
            if not na(c)
                if na(best) or c.apex - c.sx > best.apex - best.sx
                    best := c
        if not na(best)
            best.forming := true
            best.nmBelow := placeBelow(best, tris)
            best.drawNew()
            fm := best
 
if not na(lvS.cur)
    lvS.cur.extendNow()
if not na(lvM.cur)
    lvM.cur.extendNow()
if not na(lvL.cur)
    lvL.cur.extendNow()
 
alertPat(Tri t) =>
    switch alWhich
        "All"                                            => true
        "Triangles (symmetrical, ascending, descending)" => t.kind == "Symmetrical" or t.kind == "Ascending" or t.kind == "Descending"
        "Wedges (rising, falling)"                       => str.contains(t.kind, "wedge")
        "Pennants (bullish, bearish)"                    => t.kind == "Pennant"
        => alWhich == "Only " + str.lower(kindName(t))
alertDir(int s) => alDir == "Up and down" or (alDir == "Up only" and s == 1) or (alDir == "Down only" and s == -1)
dirName(int s) => s == 1 ? "up" : "down"
barsWord(int n) => str.tostring(n) + (n == 1 ? " bar" : " bars")
 
jsStr(string v) => "\"" + v + "\""
jsNum(float v) => na(v) ? "null" : str.tostring(v)
addTxt(string acc, string v) => acc == "" ? v : acc + " · " + v
addJs(string acc, string v) => acc == "" ? v : acc + "," + v
tfPre = useHtf ? tfLabel(tfEff) + " " : ""
jsHead(string typ, Tri t) => "{\"type\":" + jsStr(typ) + ",\"pattern\":" + jsStr(kindName(t))
string aTxt = ""
string aJs  = ""
if alForm
    for t in evF
        if alertPat(t)
            aTxt := addTxt(aTxt, "Pattern formed: " + tfPre + kindName(t) + ", upper " + fmtP(uAt(t, bar_index)) + ", lower " + fmtP(lAt(t, bar_index)) + ", " + barsWord(t.barsToApex()) + " to apex")
            aJs  := addJs(aJs, jsHead("formed", t) + ",\"upper\":" + jsNum(uAt(t, bar_index)) + ",\"lower\":" + jsNum(lAt(t, bar_index)) + ",\"bars_to_apex\":" + str.tostring(t.barsToApex()) + "}")
if alTest
    for t in evTU
        if alertPat(t) and alertDir(1)
            aTxt := addTxt(aTxt, "Testing the upper line: " + tfPre + kindName(t) + " at " + fmtP(uAt(t, bar_index)) + ", " + barsWord(t.barsToApex()) + " to apex")
            aJs  := addJs(aJs, jsHead("testing", t) + ",\"line\":\"upper\",\"level\":" + jsNum(uAt(t, bar_index)) + ",\"bars_to_apex\":" + str.tostring(t.barsToApex()) + "}")
    for t in evTL
        if alertPat(t) and alertDir(-1)
            aTxt := addTxt(aTxt, "Testing the lower line: " + tfPre + kindName(t) + " at " + fmtP(lAt(t, bar_index)) + ", " + barsWord(t.barsToApex()) + " to apex")
            aJs  := addJs(aJs, jsHead("testing", t) + ",\"line\":\"lower\",\"level\":" + jsNum(lAt(t, bar_index)) + ",\"bars_to_apex\":" + str.tostring(t.barsToApex()) + "}")
if alBrk
    for t in evB
        if alertPat(t) and alertDir(t.state)
            aTxt := addTxt(aTxt, "Break " + dirName(t.state) + ": " + tfPre + kindName(t) + ", break level " + fmtP(t.brkLvl) + ", target " + fmtP(t.tgt))
            aJs  := addJs(aJs, jsHead("break", t) + ",\"direction\":" + jsStr(dirName(t.state)) + ",\"break_level\":" + jsNum(t.brkLvl) + ",\"target\":" + jsNum(t.tgt) + "}")
if alRt
    for t in evR
        if alertPat(t) and alertDir(t.state)
            aTxt := addTxt(aTxt, "Retest after a break " + dirName(t.state) + ": " + tfPre + kindName(t) + ", back to the break level " + fmtP(t.brkLvl))
            aJs  := addJs(aJs, jsHead("retest", t) + ",\"direction\":" + jsStr(dirName(t.state)) + ",\"break_level\":" + jsNum(t.brkLvl) + ",\"target\":" + jsNum(t.tgt) + "}")
if alTgt
    for t in evT
        if alertPat(t) and alertDir(t.state)
            aTxt := addTxt(aTxt, "Target reached after a break " + dirName(t.state) + ": " + tfPre + kindName(t) + ", " + fmtP(t.tgt))
            aJs  := addJs(aJs, jsHead("target_reached", t) + ",\"direction\":" + jsStr(dirName(t.state)) + ",\"target\":" + jsNum(t.tgt) + "}")
if alFail
    for t in evX
        if alertPat(t) and alertDir(t.state)
            aTxt := addTxt(aTxt, "Failed break " + dirName(t.state) + ": " + tfPre + kindName(t) + ", closed back " + (t.state == 1 ? "below" : "above") + " the break level " + fmtP(t.brkLvl))
            aJs  := addJs(aJs, jsHead("failed_break", t) + ",\"direction\":" + jsStr(dirName(t.state)) + ",\"break_level\":" + jsNum(t.brkLvl) + "}")
if alNoBrk
    for t in evN
        if alertPat(t)
            aTxt := addTxt(aTxt, "No break: " + tfPre + kindName(t) + " reached its apex")
            aJs  := addJs(aJs, jsHead("no_break", t) + "}")
 
if barstate.isconfirmed and aTxt != ""
    string aMsg = alFmt == "JSON" ?
         "{\"indicator\":\"Saikix-Triangle\",\"ticker\":" + jsStr(syminfo.ticker) + ",\"chart_tf\":" + jsStr(timeframe.period) + ",\"pattern_tf\":" + jsStr(tfEff) + ",\"price\":" + jsNum(close) + ",\"events\":[" + aJs + "]}" :
         "[Saikix-Triangle] " + syminfo.ticker + " " + tfLabel(timeframe.period) + " " + aTxt + ". Price " + fmtP(close)
    alert(aMsg, alert.freq_once_per_bar_close)
 
anyDir(array<Tri> a, int s) =>
    bool f = false
    for t in a
        if t.state == s
            f := true
    f
bool cBrkUp  = anyDir(evB, 1)
bool cBrkDn  = anyDir(evB, -1)
alertcondition(evF.size() > 0, "Pattern formed", "[Saikix-Triangle] {{ticker}} {{interval}} A triangle, wedge or pennant formed. Price {{close}}")
alertcondition(evTU.size() > 0, "Testing the upper line", "[Saikix-Triangle] {{ticker}} {{interval}} Testing the upper line of a forming pattern. Price {{close}}")
alertcondition(evTL.size() > 0, "Testing the lower line", "[Saikix-Triangle] {{ticker}} {{interval}} Testing the lower line of a forming pattern. Price {{close}}")
alertcondition(cBrkUp, "Break up", "[Saikix-Triangle] {{ticker}} {{interval}} Break up: closed above a pattern. Price {{close}}")
alertcondition(cBrkDn, "Break down", "[Saikix-Triangle] {{ticker}} {{interval}} Break down: closed below a pattern. Price {{close}}")
alertcondition(cBrkUp or cBrkDn, "Any break", "[Saikix-Triangle] {{ticker}} {{interval}} A pattern broke. Price {{close}}")
alertcondition(anyDir(evR, 1), "Retest after a break up", "[Saikix-Triangle] {{ticker}} {{interval}} Retest after a break up: back to the break level. Price {{close}}")
alertcondition(anyDir(evR, -1), "Retest after a break down", "[Saikix-Triangle] {{ticker}} {{interval}} Retest after a break down: back to the break level. Price {{close}}")
alertcondition(anyDir(evT, 1), "Target reached after a break up", "[Saikix-Triangle] {{ticker}} {{interval}} Target reached after a break up. Price {{close}}")
alertcondition(anyDir(evT, -1), "Target reached after a break down", "[Saikix-Triangle] {{ticker}} {{interval}} Target reached after a break down. Price {{close}}")
alertcondition(anyDir(evX, 1), "Failed break up", "[Saikix-Triangle] {{ticker}} {{interval}} Failed break up: closed back below the break level. Price {{close}}")
alertcondition(anyDir(evX, -1), "Failed break down", "[Saikix-Triangle] {{ticker}} {{interval}} Failed break down: closed back above the break level. Price {{close}}")
alertcondition(evN.size() > 0, "No break", "[Saikix-Triangle] {{ticker}} {{interval}} A pattern reached its apex without a break. Price {{close}}")

← 返回列表