Auto Triangles [ITA]

itamardrori_ · study · 440 行 · 点赞 55 · TradingView 原页

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

Pine Script

// © ITA Trading Tools - itamardrori_
//@version=6
// =============================================================================
// Auto Triangles [ITA]
//
// A triangle is two trendlines closing in on each other: the highs coming down,
// the lows coming up, or one of them flat. Traders draw them by hand, redraw
// them every few days, and then draw the measured-move target by hand too.
//
// This finds them from pivots, names the type, follows the active one bar by
// bar, marks the close that breaks it, and draws the classic target: the
// height of the triangle at its widest point, projected from the breakout.
// When price reaches the target, the target says so.
//
// Decisions worth stating:
//
//   no repaint    a pivot is only known some bars after it happens, so a
//                 triangle appears that many bars after its last pivot. Once
//                 drawn, it is not redrawn backwards in time.
//
//   containment   every close between the first pivot and today has to sit
//                 between the two lines. Wicks may poke through, closes may
//                 not, and a close outside is what a breakout is.
//
//   the type      is read from how far each line moves over the life of the
//                 pattern, against the pattern's own height. A line that
//                 moves less than 20% of the height is flat. Two lines moving
//                 the same way are a wedge, not a triangle, and are skipped.
// =============================================================================
 
// Drawn in front of the candles. Behind them, any label near price ends up
// under a candle that prints after it, and the next candles cannot be known
// when the label is placed.
indicator("Auto Triangles [ITA]", overlay = true, max_bars_back = 500, max_lines_count = 200, max_labels_count = 200, behind_chart = false)
 
// ─── INPUTS ──────────────────────────────────────────────────────────────────
grpCalc  = "Detection"
pivLen   = input.int(5, "Pivot Length", minval = 2, maxval = 30, group = grpCalc,
     tooltip = "Bars on each side of a swing high or low. Larger finds bigger, slower triangles.")
minSpan  = input.int(15, "Shortest Triangle In Bars", minval = 5, maxval = 200, group = grpCalc)
maxSpan  = input.int(150, "Longest Triangle In Bars", minval = 20, maxval = 400, group = grpCalc)
flatPct  = input.float(20, "Flat Line Tolerance, Percent Of Height", minval = 5, maxval = 40, step = 5, group = grpCalc,
     tooltip = "A line that moves less than this share of the triangle's height over its life counts as flat.")
minHgtAtr = input.float(1.5, "Smallest Height In ATRs", minval = 0.5, maxval = 10, step = 0.5, group = grpCalc,
     tooltip = "Skips triangles too small to matter on this chart.")
 
grpShow   = "Display"
showTypes = input.string("All", "Types", options = ["All", "Ascending", "Descending", "Symmetrical"], group = grpShow)
keepPast  = input.int(6, "Finished Triangles To Keep", minval = 0, maxval = 40, group = grpShow)
showFill  = input.bool(true, "Shade The Triangle", group = grpShow)
showTgt   = input.bool(true, "Draw The Target", group = grpShow)
showPanel = input.bool(true, "Show The Panel", group = grpShow)
lineW     = input.int(2, "Line Thickness", minval = 1, maxval = 4, group = grpShow)
labelSizeStr = input.string("Normal", "Label Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
statPos   = input.string("Top Right", "Panel Position",
     options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpShow)
statSizeStr = input.string("Normal", "Panel Text Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
 
grpCol   = "Colors"
liveCol  = input.color(#e5c56b, "Triangle Still Forming", group = grpCol)
upCol    = input.color(#089981, "Broke Up", group = grpCol)
dnCol    = input.color(#f23645, "Broke Down", group = grpCol)
deadCol  = input.color(#787b86, "Ran Out Without A Break", group = grpCol)
failCol  = input.color(#ff9800, "Failed Break", group = grpCol)
labelBg  = input.color(color.new(#1e222d, 0), "Label Background", group = grpCol)
 
sizeOf(string s) =>
    r = size.normal
    if s == "Tiny"
        r := size.tiny
    else if s == "Small"
        r := size.small
    else if s == "Large"
        r := size.large
    else if s == "Huge"
        r := size.huge
    r
 
posOf(string s) =>
    r = position.top_right
    if s == "Top Left"
        r := position.top_left
    else if s == "Bottom Right"
        r := position.bottom_right
    else if s == "Bottom Left"
        r := position.bottom_left
    r
 
statSize  = sizeOf(statSizeStr)
labelSize = sizeOf(labelSizeStr)
 
lineAt(int x1, float y1, int x2, float y2, int x) =>
    y1 + (y2 - y1) * (x - x1) / (x2 - x1)
 
// ─── PIVOTS ──────────────────────────────────────────────────────────────────
atr = ta.atr(14)
ph  = ta.pivothigh(high, pivLen, pivLen)
pl  = ta.pivotlow(low, pivLen, pivLen)
 
var array<int>   hX = array.new<int>()
var array<float> hY = array.new<float>()
var array<int>   lX = array.new<int>()
var array<float> lY = array.new<float>()
 
newPivot = false
if barstate.isconfirmed
    if not na(ph)
        array.push(hX, bar_index - pivLen)
        array.push(hY, ph)
        newPivot := true
        if array.size(hX) > 6
            array.shift(hX)
            array.shift(hY)
    if not na(pl)
        array.push(lX, bar_index - pivLen)
        array.push(lY, pl)
        newPivot := true
        if array.size(lX) > 6
            array.shift(lX)
            array.shift(lY)
 
// ─── THE ACTIVE TRIANGLE ─────────────────────────────────────────────────────
var bool   act   = false
var int    ux1   = 0
var float  uy1   = na
var int    ux2   = 0
var float  uy2   = na
var int    lx1   = 0
var float  ly1   = na
var int    lx2   = 0
var float  ly2   = na
var int    x0    = 0
var int    apex  = 0
var float  h0    = na
var string kind  = ""
 
var line     aU   = na
var line     aL   = na
var line     aUp  = na
var line     aLp  = na
var linefill aF   = na
var label    aLab = na
 
var int lastEnd = -1
 
// Finished triangles, kept in groups so the oldest can be removed whole.
var array<line>     pastLines  = array.new<line>()
var array<linefill> pastFills  = array.new<linefill>()
var array<label>    pastLabels = array.new<label>()
 
// The most recent breakout and its target.
var float  tgt      = na
var int    tgtDir   = 0
var bool   tgtHit   = false
var bool   tgtFail  = false
var float  failLvl  = na
var line   tgtLine  = na
var label  tgtLab   = na
var string lastKind = ""
var int    lastBar  = na
 
dropActive() =>
    line.delete(aU)
    line.delete(aL)
    line.delete(aUp)
    line.delete(aLp)
    linefill.delete(aF)
    label.delete(aLab)
 
typeWanted(string k) =>
    showTypes == "All" or showTypes == k
 
// ─── DETECTION ───────────────────────────────────────────────────────────────
// Tried on every new pivot, on every pairing of the last four swing highs with
// the last four swing lows. Only the latest two of each would miss most
// triangles: one stray swing in the middle and the pair no longer fits. When
// several pairings pass, the longest one wins.
if barstate.isconfirmed and newPivot and array.size(hX) >= 2 and array.size(lX) >= 2
    nh = array.size(hX)
    nl = array.size(lX)
    hFrom = math.max(0, nh - 4)
    lFrom = math.max(0, nl - 4)
 
    found = false
    bux1 = 0
    buy1 = 0.0
    bux2 = 0
    buy2 = 0.0
    blx1 = 0
    bly1 = 0.0
    blx2 = 0
    bly2 = 0.0
    bx0  = 0
    bApex = 0
    bH0  = 0.0
    bKind = ""
 
    for a = hFrom to nh - 2
        for b = a + 1 to nh - 1
            for c = lFrom to nl - 2
                for d = c + 1 to nl - 1
                    cux1 = array.get(hX, a)
                    cuy1 = array.get(hY, a)
                    cux2 = array.get(hX, b)
                    cuy2 = array.get(hY, b)
                    clx1 = array.get(lX, c)
                    cly1 = array.get(lY, c)
                    clx2 = array.get(lX, d)
                    cly2 = array.get(lY, d)
                    cx0  = math.min(cux1, clx1)
 
                    // The highs and the lows have to take turns, so each
                    // line's first touch comes before the other's last touch.
                    ok = cux1 < clx2 and clx1 < cux2 and cx0 > lastEnd
                    ok := ok and bar_index - cx0 >= minSpan and bar_index - cx0 <= maxSpan
                    // A longer pairing already found makes this one moot.
                    ok := ok and (not found or cx0 < bx0)
                    // Both lines have to start at about the same time. A line
                    // whose first touch comes much later would be stretched
                    // back over bars that never came near it.
                    ok := ok and math.abs(cux1 - clx1) <= 0.3 * (bar_index - cx0)
                    xs = math.max(cux1, clx1)
 
                    cH0 = 0.0
                    cApex = 0
                    cKind = ""
                    su = 0.0
                    sl = 0.0
                    if ok
                        cH0 := lineAt(cux1, cuy1, cux2, cuy2, xs) - lineAt(clx1, cly1, clx2, cly2, xs)
                        su := (cuy2 - cuy1) / (cux2 - cux1)
                        sl := (cly2 - cly1) / (clx2 - clx1)
                        dw = su - sl
                        ok := cH0 >= minHgtAtr * atr and dw < 0
                        if ok
                            cApex := xs + int(math.floor(cH0 / -dw))
                            // The apex must still be ahead, and not so far
                            // ahead that the lines are nearly parallel. 450
                            // keeps it inside how far ahead a line may go.
                            ok := cApex > bar_index + 1 and cApex - bar_index <= (bar_index - cx0) * 1.5 and cApex - bar_index <= 450
                            wNow = lineAt(cux1, cuy1, cux2, cuy2, bar_index) - lineAt(clx1, cly1, clx2, cly2, bar_index)
                            ok := ok and wNow <= cH0 * 0.85
                    if ok
                        life = cApex - xs
                        dU = su * life
                        dL = sl * life
                        tol = cH0 * flatPct / 100.0
                        if math.abs(dU) <= tol and dL > tol
                            cKind := "Ascending"
                        else if math.abs(dL) <= tol and dU < -tol
                            cKind := "Descending"
                        else if dU < -tol and dL > tol
                            cKind := "Symmetrical"
                        ok := cKind != "" and typeWanted(cKind)
                    if ok
                        for k = 0 to bar_index - cx0
                            xb = bar_index - k
                            if close[k] > lineAt(cux1, cuy1, cux2, cuy2, xb) or close[k] < lineAt(clx1, cly1, clx2, cly2, xb)
                                ok := false
                                break
                    if ok
                        found := true
                        bux1  := cux1
                        buy1  := cuy1
                        bux2  := cux2
                        buy2  := cuy2
                        blx1  := clx1
                        bly1  := cly1
                        blx2  := clx2
                        bly2  := cly2
                        bx0   := cx0
                        bApex := cApex
                        bH0   := cH0
                        bKind := cKind
 
    // A refinement of the active triangle replaces it. A shorter one inside
    // it does not.
    if found and (not act or bx0 >= x0)
        if act
            dropActive()
        act  := true
        ux1  := bux1
        uy1  := buy1
        ux2  := bux2
        uy2  := buy2
        lx1  := blx1
        ly1  := bly1
        lx2  := blx2
        ly2  := bly2
        x0   := bx0
        apex := bApex
        h0   := bH0
        kind := bKind
        aU   := line.new(x0, lineAt(ux1, uy1, ux2, uy2, x0), bar_index, lineAt(ux1, uy1, ux2, uy2, bar_index), color = liveCol, width = lineW)
        aL   := line.new(x0, lineAt(lx1, ly1, lx2, ly2, x0), bar_index, lineAt(lx1, ly1, lx2, ly2, bar_index), color = liveCol, width = lineW)
        aUp  := line.new(bar_index, lineAt(ux1, uy1, ux2, uy2, bar_index), apex, lineAt(ux1, uy1, ux2, uy2, apex), color = color.new(liveCol, 40), width = 1, style = line.style_dotted)
        aLp  := line.new(bar_index, lineAt(lx1, ly1, lx2, ly2, bar_index), apex, lineAt(lx1, ly1, lx2, ly2, apex), color = color.new(liveCol, 40), width = 1, style = line.style_dotted)
        aF   := showFill ? linefill.new(aU, aL, color.new(liveCol, 90)) : na
        // Above the first upper point, which is a swing high, so no candle sits there.
        aLab := label.new(x0, lineAt(ux1, uy1, ux2, uy2, x0) + atr * 0.6, kind + " triangle", style = label.style_label_down, color = labelBg, textcolor = liveCol, size = labelSize)
 
// ─── FOLLOWING IT ────────────────────────────────────────────────────────────
brokeUp = false
brokeDn = false
 
finish(color c) =>
    line.set_color(aU, c)
    line.set_color(aL, c)
    line.delete(aUp)
    line.delete(aLp)
    if not na(aF)
        linefill.set_color(aF, color.new(c, 90))
    label.set_textcolor(aLab, c)
 
if barstate.isconfirmed and act
    uNow = lineAt(ux1, uy1, ux2, uy2, bar_index)
    lNow = lineAt(lx1, ly1, lx2, ly2, bar_index)
    line.set_xy2(aU, bar_index, uNow)
    line.set_xy2(aL, bar_index, lNow)
    line.set_xy1(aUp, bar_index, uNow)
    line.set_xy1(aLp, bar_index, lNow)
 
    ended = false
    if close > uNow or close < lNow
        brokeUp := close > uNow
        brokeDn := not brokeUp
        c = brokeUp ? upCol : dnCol
        finish(c)
        mark = brokeUp ? "▲ Break up" : "▼ Break down"
        yMark = brokeUp ? high + atr * 0.6 : low - atr * 0.6
        array.push(pastLabels, label.new(bar_index, yMark, mark, style = brokeUp ? label.style_label_down : label.style_label_up, color = labelBg, textcolor = c, size = labelSize))
 
        // The measured move: the height at the widest point, from the line
        // that was broken.
        label.delete(tgtLab)
        tgt      := brokeUp ? uNow + h0 : lNow - h0
        tgtDir   := brokeUp ? 1 : -1
        tgtHit   := false
        tgtFail  := false
        // A break has failed once price closes beyond the far side of the
        // triangle, the level where a stop would usually sit.
        failLvl  := brokeUp ? lNow : uNow
        lastKind := kind
        lastBar  := bar_index
        if showTgt
            tgtLine := line.new(bar_index, tgt, bar_index + 20, tgt, color = color.new(c, 20), width = 1, style = line.style_dashed)
            tgtLab  := label.new(bar_index + 20, tgt, "Target " + str.tostring(tgt, format.mintick), style = label.style_label_left, color = labelBg, textcolor = c, size = labelSize)
            array.push(pastLines, tgtLine)
        ended := true
    else if bar_index >= apex - 1
        // It ran into its own apex without a close outside. It stays on the
        // chart, greyed, because hiding the ones that went nowhere would
        // leave only the ones that worked.
        finish(deadCol)
        lastKind := kind
        lastBar  := bar_index
        ended := true
 
    if ended
        array.push(pastLines, aU)
        array.push(pastLines, aL)
        if not na(aF)
            array.push(pastFills, aF)
        array.push(pastLabels, aLab)
        act := false
        lastEnd := bar_index
        aU   := na
        aL   := na
        aUp  := na
        aLp  := na
        aF   := na
        aLab := na
 
// Old triangles are removed oldest first once there are more than asked for.
// A triangle owns about three lines, one fill and three labels.
while array.size(pastLines) > keepPast * 3 + 3
    line.delete(array.shift(pastLines))
while array.size(pastFills) > keepPast + 1
    linefill.delete(array.shift(pastFills))
while array.size(pastLabels) > keepPast * 3 + 3
    label.delete(array.shift(pastLabels))
 
// ─── THE TARGET ──────────────────────────────────────────────────────────────
if barstate.isconfirmed and not na(tgt) and not tgtHit and not tgtFail
    if (tgtDir == 1 and close < failLvl) or (tgtDir == -1 and close > failLvl)
        tgtFail := true
        failMark = tgtDir == 1 ? low - atr * 1.2 : high + atr * 1.2
        array.push(pastLabels, label.new(bar_index, failMark, "✗ Break failed", style = tgtDir == 1 ? label.style_label_up : label.style_label_down, color = labelBg, textcolor = failCol, size = labelSize))
        if not na(tgtLab)
            label.set_text(tgtLab, "Target " + str.tostring(tgt, format.mintick) + " cancelled")
            label.set_textcolor(tgtLab, failCol)
        if not na(tgtLine)
            line.set_color(tgtLine, color.new(failCol, 40))
    else if (tgtDir == 1 and high >= tgt) or (tgtDir == -1 and low <= tgt)
        tgtHit := true
        if not na(tgtLab)
            label.set_text(tgtLab, "✓ Target " + str.tostring(tgt, format.mintick) + " reached")
        if not na(tgtLine)
            line.set_x2(tgtLine, bar_index)
            line.set_style(tgtLine, line.style_solid)
            label.set_x(tgtLab, bar_index)
 
// ─── THE PANEL ───────────────────────────────────────────────────────────────
distText(float lvl) =>
    str.tostring((lvl - close) / close * 100.0, "+#.#;-#.#") + "%"
 
var table panel = na
if showPanel and barstate.islast
    if na(panel)
        panel := table.new(posOf(statPos), 3, 4, border_width = 1)
    txtCol = color.new(color.white, 25)
    table.clear(panel, 0, 0, 2, 3)
    table.cell(panel, 0, 0, "AUTO TRIANGLES", text_color = liveCol, text_size = statSize, text_halign = text.align_left)
    if act
        uNow = lineAt(ux1, uy1, ux2, uy2, bar_index)
        lNow = lineAt(lx1, ly1, lx2, ly2, bar_index)
        table.cell(panel, 1, 0, kind + ", forming", text_color = liveCol, text_size = statSize)
        table.cell(panel, 0, 1, "Upper line", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
        table.cell(panel, 1, 1, str.tostring(uNow, format.mintick), text_color = upCol, text_size = statSize)
        table.cell(panel, 2, 1, distText(uNow), text_color = upCol, text_size = statSize)
        table.cell(panel, 0, 2, "Lower line", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
        table.cell(panel, 1, 2, str.tostring(lNow, format.mintick), text_color = dnCol, text_size = statSize)
        table.cell(panel, 2, 2, distText(lNow), text_color = dnCol, text_size = statSize)
        table.cell(panel, 0, 3, "Apex in", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
        table.cell(panel, 1, 3, str.tostring(apex - bar_index) + " bars", text_color = txtCol, text_size = statSize)
    else
        table.cell(panel, 1, 0, "None forming", text_color = txtCol, text_size = statSize)
        if lastKind != ""
            table.cell(panel, 0, 1, "Last triangle", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
            table.cell(panel, 1, 1, lastKind + ", " + str.tostring(bar_index - lastBar) + " bars ago", text_color = txtCol, text_size = statSize)
        if not na(tgt)
            table.cell(panel, 0, 2, "Last target", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
            table.cell(panel, 1, 2, str.tostring(tgt, format.mintick), text_color = tgtDir == 1 ? upCol : dnCol, text_size = statSize)
            table.cell(panel, 2, 2, tgtHit ? "reached" : tgtFail ? "break failed" : distText(tgt), text_color = tgtFail ? failCol : tgtDir == 1 ? upCol : dnCol, text_size = statSize)
 
// ─── ALERTS ──────────────────────────────────────────────────────────────────
alertcondition(brokeUp, "Triangle broke up", "Close above a triangle's upper line.")
alertcondition(brokeDn, "Triangle broke down", "Close below a triangle's lower line.")

← 返回列表