Auto Trend Lines, Channels & Patterns [EDGE]

TonyANT · study · 461 行 · 点赞 727 · TradingView 原页

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

Pine Script

// =============================================================================
// AUTO TREND LINES, CHANNELS & PATTERNS [EDGE]
// Draws trend lines through accepted swings of the local structure, the channel
// or pattern the best lines form (channel, triangle, wedge, expanding) and the
// stop band beyond each line.
// Built for price-action and SMC traders who want a few validated lines instead
// of every possible connection between pivots.
// =============================================================================
//@version=6
indicator("Auto Trend Lines, Channels & Patterns [EDGE]", "TL [EDGE]", overlay = true, max_bars_back = 2000,
     max_lines_count = 200, max_labels_count = 60)
 
// =============================================================================
// RULES
// Swing: a pivot (n bars each side, n by timeframe) accepted only when the move
//        from the previous opposite swing is at least "Swing depth" ATR, so micro
//        pullbacks never anchor a line.
// Line:  through two swings of one side at least "Minimum span" apart (two
//        touches only: at least "Long span" apart). Valid while no body close
//        crosses it by more than "Break tolerance" and the price touched it no
//        longer ago than its own span. A touch is a wick within "Touch
//        tolerance"; consecutive touching bars count once. Lines with the most
//        touches win, at most "Lines per side". A side is recomputed only when a
//        new swing of that side appears or one of its lines breaks.
// Break: a body close beyond the line. The line is removed, or kept dashed and
//        stopped at the breaking bar for "Keep broken line" bars.
// Channel / pattern: the best resistance and support lines together. Similar
//        slopes: CHANNEL; converging: TRIANGLE (opposite slopes) or WEDGE (same
//        direction); diverging: EXPANDING. With one line only, a parallel through
//        the opposite extreme is drawn when the price respected it at least twice.
// Band:  the area beyond a line where stops rest, "Stop band width" ATR wide.
// =============================================================================
 
// =============================================================================
// GROUP 1 - SWINGS
// =============================================================================
G_SW = "Swings"
len_auto   = input.bool(true, "Auto swing length by timeframe", group = G_SW,
     tooltip = "On: bars on each side of a swing are picked by timeframe - 3 on 5M-15M, 4 on 30M, 5 from 1H.\nOff: the manual value below is used.")
len_manual = input.int(5, "Swing length (manual)", minval = 2, maxval = 20, group = G_SW,
     tooltip = "Used only when auto length is off. Bars on each side of a pivot.\nSmaller = more swings and more candidate lines; larger = fewer, more significant swings.\nTypical: 3-5 intraday, 5-8 swing trading.")
depth_mult = input.float(1.5, "Swing depth (ATR 200)", minval = 0.5, maxval = 5.0, step = 0.25, group = G_SW,
     tooltip = "A swing is accepted only when the move from the previous opposite swing is at least this many ATR(200). Keeps micro pullbacks out of the lines.\nLower = more swings and lines; higher = only major swings.\nTypical: 1.0-2.0.")
 
// =============================================================================
// GROUP 2 - LINES
// =============================================================================
G_LN = "Lines"
max_pts   = input.int(12, "Swings to scan per side", minval = 3, maxval = 20, group = G_LN,
     tooltip = "How many of the latest swing highs (lows) are paired when looking for a line.\nMore = older and longer lines can be found, at a higher calculation cost.")
min_touch = input.int(2, "Minimum touches", minval = 2, maxval = 5, group = G_LN,
     tooltip = "2: a line through two swings, accepted only when they are at least \"Long span\" apart.\n3: the price must have respected the line a third time - fewer, more reliable lines.")
per_side  = input.int(1, "Lines per side", minval = 1, maxval = 3, group = G_LN,
     tooltip = "How many lines are drawn on each side.\n1 keeps the chart clean; 2-3 also show nested structures at the cost of more overlap.")
min_span  = input.int(4, "Minimum span (swing lengths)", minval = 2, maxval = 12, group = G_LN,
     tooltip = "The two anchor swings must be at least this many swing lengths apart: no lines through two highs of one peak.\nLower = shorter local lines; higher = only lines of the larger structure.")
long_span = input.int(12, "Long span for 2 touches (swing lengths)", minval = 4, maxval = 40, group = G_LN,
     tooltip = "A line with only two touches is accepted when its anchors are at least this far apart; a short two-point line is not a trend line.\nLower = more two-touch lines; higher = two-touch lines only across long moves.")
stale_x   = input.float(1.0, "Stale after (spans)", minval = 0.5, maxval = 5.0, step = 0.5, group = G_LN,
     tooltip = "A line is dropped when the price has not touched it for longer than its own anchor span times this value.\nHigher = lines stay on the chart longer after the price left them.")
touch_tol = input.float(0.3, "Touch tolerance (ATR)", minval = 0.05, maxval = 1.0, step = 0.05, group = G_LN,
     tooltip = "A wick this close to the line counts as a touch.\nHigher = more touches counted, looser lines.\nTypical: 0.2-0.4.")
break_tol = input.float(0.1, "Break tolerance (ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = G_LN,
     tooltip = "A body close beyond the line by more than this breaks it.\n0 = any close beyond the line breaks it; higher = tolerates shallow closes through the line.")
keep_brk  = input.int(0, "Keep broken line (bars)", minval = 0, maxval = 300, group = G_LN,
     tooltip = "0: a broken line disappears at once.\nOtherwise it stays dashed, stopped at the breaking bar, for this many bars - useful to review retests of the broken line.")
 
// =============================================================================
// GROUP 3 - CHANNELS AND BANDS
// =============================================================================
G_CH = "Channels and bands"
show_ch   = input.bool(true, "Channels and patterns", group = G_CH,
     tooltip = "Fills the space between the best resistance and support lines and names the pattern: channel, triangle, wedge or expanding.\nWith one line only, tries a parallel through the opposite extreme.")
show_band = input.bool(true, "Stop band beyond lines", group = G_CH,
     tooltip = "Translucent band beyond each line where stops rest - a reference for stop placement and for where a break is likely to be tested.")
band_atr  = input.float(0.25, "Stop band width (ATR)", minval = 0.05, maxval = 1.0, step = 0.05, group = G_CH,
     tooltip = "Width of the stop band in ATR(200).\nWider = more conservative stop placement.\nTypical: 0.2-0.3.")
 
// =============================================================================
// GROUP 4 - STYLE
// =============================================================================
G_ST = "Style"
col_up     = input.color(#089981, "Support lines", group = G_ST,
     tooltip = "Color of support lines and their stop bands.")
col_dn     = input.color(#f23645, "Resistance lines", group = G_ST,
     tooltip = "Color of resistance lines and their stop bands.")
col_ch     = input.color(#787b86, "Channel fill", group = G_ST,
     tooltip = "Color of the channel or pattern fill and of its caption.")
label_size = input.string(size.small, "Label size", options = [size.tiny, size.small, size.normal], group = G_ST,
     tooltip = "Caption size for lines and patterns.")
label_dx   = input.int(10, "Label spacing (bars)", minval = 0, maxval = 50, group = G_ST,
     tooltip = "Horizontal distance between the line captions and the pattern caption, so the texts do not overlap where the lines converge.\n0 = all captions at the same distance from the last bar.")
 
// =============================================================================
// SWINGS
// Pivots are filtered by the depth of the move from the previous opposite swing,
// so a line can only be anchored on swings that mattered to the structure.
// ATR(200) is the unit; on young symbols it falls back to ATR(50) and ATR(14).
// =============================================================================
tf_m = timeframe.in_seconds() / 60
int n = len_auto ? (tf_m < 30 ? 3 : tf_m < 60 ? 4 : 5) : len_manual
 
a200 = ta.atr(200)
a50  = ta.atr(50)
a14  = ta.atr(14)
float atr = na(a200) ? (na(a50) ? a14 : a50) : a200
// captions sit right of the last bar; time-based x keeps them in the right-offset area
int bar_ms = timeframe.in_seconds() * 1000
 
var array<int>   sw_bar = array.new<int>()
var array<float> sw_px  = array.new<float>()
var array<int>   sw_typ = array.new<int>()
 
// accept a pivot: same side — only a more extreme one replaces the last swing;
// opposite side — only with a move of at least thr from the last swing
f_accept(int b, float px, int typ, float thr) =>
    bool ok = false
    int m = sw_bar.size()
    if m == 0
        sw_bar.push(b)
        sw_px.push(px)
        sw_typ.push(typ)
        ok := true
    else if sw_typ.last() == typ
        if typ == 1 ? px > sw_px.last() : px < sw_px.last()
            sw_bar.set(m - 1, b)
            sw_px.set(m - 1, px)
            ok := true
    else if math.abs(px - sw_px.last()) >= thr
        sw_bar.push(b)
        sw_px.push(px)
        sw_typ.push(typ)
        ok := true
    if sw_bar.size() > 60
        sw_bar.shift()
        sw_px.shift()
        sw_typ.shift()
    ok
 
float ph = ta.pivothigh(n, n)
float pl = ta.pivotlow(n, n)
bool new_hi = not na(ph) and not na(atr) ? f_accept(bar_index - n, ph, 1, depth_mult * atr) : false
bool new_lo = not na(pl) and not na(atr) ? f_accept(bar_index - n, pl, -1, depth_mult * atr) : false
 
// =============================================================================
// LINE EVALUATION
// A candidate line is tested bar by bar from its first anchor: any body close
// beyond it rejects the line, wicks near it count as touches. The most touched
// lines win; a line running within half an ATR of a picked one is a duplicate.
// =============================================================================
// a line through (b1, p1) and (b2, p2) on side sd (1 highs, -1 lows): valid while
// no body close crosses it; touches = wicks within tol_t, consecutive bars once
f_eval(int b1, float p1, int b2, float p2, int sd, float tol_t, float tol_b) =>
    float s = (p2 - p1) / (b2 - b1)
    bool valid = true
    int touches = 0
    int last_touch = -100000
    int lim = math.min(bar_index - b1, 1990)
    if lim >= 0
        for off = lim to 0
            int k = bar_index - off
            float lv = p1 + s * (k - b1)
            if sd == 1
                if close[off] > lv + tol_b
                    valid := false
                    break
                if high[off] >= lv - tol_t and k - last_touch > n
                    touches += 1
                    last_touch := k
            else
                if close[off] < lv - tol_b
                    valid := false
                    break
                if low[off] <= lv + tol_t and k - last_touch > n
                    touches += 1
                    last_touch := k
    [valid, touches, s, last_touch]
 
// the best lines of one side among pairs of the latest swings
f_select(int sd, float tol_t, float tol_b) =>
    array<int>   cb = array.new<int>()
    array<float> cp = array.new<float>()
    if sw_bar.size() > 0
        for i = sw_bar.size() - 1 to 0
            if sw_typ.get(i) == sd and cb.size() < max_pts
                cb.push(sw_bar.get(i))
                cp.push(sw_px.get(i))
    array<int>   c_b1 = array.new<int>()
    array<float> c_p1 = array.new<float>()
    array<int>   c_b2 = array.new<int>()
    array<float> c_p2 = array.new<float>()
    array<int>   c_t  = array.new<int>()
    if cb.size() >= 2
        for i = 0 to cb.size() - 2            // i newer, j older
            for j = i + 1 to cb.size() - 1
                int b1 = cb.get(j)
                int b2 = cb.get(i)
                if b2 - b1 >= min_span * n
                    [valid, t, s, lt] = f_eval(b1, cp.get(j), b2, cp.get(i), sd, tol_t, tol_b)
                    // stale: no touch for longer than the anchor span
                    if valid and t >= min_touch and (t >= 3 or b2 - b1 >= long_span * n) and bar_index - lt <= stale_x * (b2 - b1)
                        c_b1.push(b1)
                        c_p1.push(cp.get(j))
                        c_b2.push(b2)
                        c_p2.push(cp.get(i))
                        c_t.push(t)
    // pick by touches, then by span; skip a line running within half an ATR of a picked one
    array<int>   o_b1 = array.new<int>()
    array<float> o_p1 = array.new<float>()
    array<int>   o_b2 = array.new<int>()
    array<float> o_p2 = array.new<float>()
    array<int>   o_t  = array.new<int>()
    array<bool>  used = array.new<bool>(c_b1.size(), false)
    if c_b1.size() > 0
        for tries = 1 to c_b1.size()
            if o_b1.size() >= per_side
                break
            int best = -1
            for i = 0 to c_b1.size() - 1
                if used.get(i)
                    continue
                if best == -1 or c_t.get(i) > c_t.get(best) or (c_t.get(i) == c_t.get(best) and c_b2.get(i) - c_b1.get(i) > c_b2.get(best) - c_b1.get(best))
                    best := i
            if best == -1
                break
            used.set(best, true)
            float sb = (c_p2.get(best) - c_p1.get(best)) / (c_b2.get(best) - c_b1.get(best))
            float vb = c_p1.get(best) + sb * (bar_index - c_b1.get(best))
            bool dup = false
            if o_b1.size() > 0
                for q = 0 to o_b1.size() - 1
                    float sq = (o_p2.get(q) - o_p1.get(q)) / (o_b2.get(q) - o_b1.get(q))
                    float vq = o_p1.get(q) + sq * (bar_index - o_b1.get(q))
                    if math.abs(vb - vq) < 0.5 * atr
                        dup := true
            if dup
                continue
            o_b1.push(c_b1.get(best))
            o_p1.push(c_p1.get(best))
            o_b2.push(c_b2.get(best))
            o_p2.push(c_p2.get(best))
            o_t.push(c_t.get(best))
    [o_b1, o_p1, o_b2, o_p2, o_t]
 
// =============================================================================
// LINE STATE
// Drawn lines with their anchors, touch count and break bar. A side is rebuilt
// only when a new swing of that side appears or one of its lines breaks, so
// lines do not flicker between bars.
// =============================================================================
var array<line>     ln_main   = array.new<line>()
var array<int>      tl_side   = array.new<int>()
var array<int>      tl_b1   = array.new<int>()
var array<float>    tl_p1   = array.new<float>()
var array<int>      tl_b2   = array.new<int>()
var array<float>    tl_p2   = array.new<float>()
var array<int>      tl_touch    = array.new<int>()
var array<int>      tl_brk  = array.new<int>()       // bar of the break, -1 while active
var array<label>    lb_cap   = array.new<label>()
var array<line>     ln_band   = array.new<line>()      // stop band edge
var array<linefill> lf_band   = array.new<linefill>()
 
f_lval(int i, int k) =>
    float s = (tl_p2.get(i) - tl_p1.get(i)) / (tl_b2.get(i) - tl_b1.get(i))
    tl_p1.get(i) + s * (k - tl_b1.get(i))
 
f_remove(int i) =>
    line.delete(ln_main.get(i))
    label.delete(lb_cap.get(i))
    line.delete(ln_band.get(i))
    linefill.delete(lf_band.get(i))
    ln_main.remove(i)
    tl_side.remove(i)
    tl_b1.remove(i)
    tl_p1.remove(i)
    tl_b2.remove(i)
    tl_p2.remove(i)
    tl_touch.remove(i)
    tl_brk.remove(i)
    lb_cap.remove(i)
    ln_band.remove(i)
    lf_band.remove(i)
 
f_caption(int sd, int t, bool broken) =>
    (sd == 1 ? "RESISTANCE LINE" : "SUPPORT LINE") + " · " + str.tostring(t) + (t == 1 ? " touch" : " touches") + (broken ? " · broken" : "")
 
f_create(int sd, int b1, float p1, int b2, float p2, int t) =>
    color c = sd == 1 ? col_dn : col_up
    line ln = line.new(b1, p1, b2, p2, xloc = xloc.bar_index, extend = extend.right, color = c, width = 2)
    float s = (p2 - p1) / (b2 - b1)
    float off = sd * band_atr * atr
    line bd = line.new(b1, p1 + off, b2, p2 + off, xloc = xloc.bar_index, extend = extend.right, color = color.new(c, 100), width = 1)
    linefill bf = linefill.new(ln, bd, show_band ? color.new(c, 85) : color.new(c, 100))
    float lv = p1 + s * (bar_index - b1)
    label lb = label.new(time + 3 * bar_ms, lv, f_caption(sd, t, false), xloc = xloc.bar_time,
         style = label.style_label_left, color = color(na), textcolor = color.new(c, 10), size = label_size)
    ln_main.push(ln)
    tl_side.push(sd)
    tl_b1.push(b1)
    tl_p1.push(p1)
    tl_b2.push(b2)
    tl_p2.push(p2)
    tl_touch.push(t)
    tl_brk.push(-1)
    lb_cap.push(lb)
    ln_band.push(bd)
    lf_band.push(bf)
 
// rebuild one side: keep lines that are selected again, drop the rest, add new ones
f_rebuild(int sd) =>
    [o_b1, o_p1, o_b2, o_p2, o_t] = f_select(sd, touch_tol * atr, break_tol * atr)
    if ln_main.size() > 0
        for i = ln_main.size() - 1 to 0
            if tl_side.get(i) != sd or tl_brk.get(i) != -1
                continue
            bool keep = false
            if o_b1.size() > 0
                for q = 0 to o_b1.size() - 1
                    if o_b1.get(q) == tl_b1.get(i) and o_b2.get(q) == tl_b2.get(i)
                        keep := true
                        tl_touch.set(i, o_t.get(q))
            if not keep
                f_remove(i)
    if o_b1.size() > 0
        for q = 0 to o_b1.size() - 1
            bool exists = false
            if ln_main.size() > 0
                for i = 0 to ln_main.size() - 1
                    if tl_side.get(i) == sd and tl_brk.get(i) == -1 and tl_b1.get(i) == o_b1.get(q) and tl_b2.get(i) == o_b2.get(q)
                        exists := true
            if not exists
                f_create(sd, o_b1.get(q), o_p1.get(q), o_b2.get(q), o_p2.get(q), o_t.get(q))
 
// =============================================================================
// PER-BAR UPDATE
// On every confirmed bar each active line is checked for a break and for
// staleness; captions follow the last bar.
// =============================================================================
bool brk_hi = false
bool brk_lo = false
if barstate.isconfirmed and ln_main.size() > 0
    for i = ln_main.size() - 1 to 0
        if tl_brk.get(i) != -1
            if bar_index - tl_brk.get(i) >= keep_brk
                f_remove(i)
            continue
        float lv = f_lval(i, bar_index)
        int sd = tl_side.get(i)
        [v_, t_, s_, lt_] = f_eval(tl_b1.get(i), tl_p1.get(i), tl_b2.get(i), tl_p2.get(i), sd, touch_tol * atr, break_tol * atr)
        if bar_index - lt_ > stale_x * (tl_b2.get(i) - tl_b1.get(i))
            f_remove(i)
            continue
        bool broken = sd == 1 ? close > lv + break_tol * atr : close < lv - break_tol * atr
        if broken and keep_brk == 0
            f_remove(i)
            if sd == 1
                brk_hi := true
            else
                brk_lo := true
            continue
        if broken
            tl_brk.set(i, bar_index)
            line ln = ln_main.get(i)
            ln.set_extend(extend.none)
            ln.set_x2(bar_index)
            ln.set_y2(lv)
            ln.set_style(line.style_dashed)
            ln.set_width(1)
            linefill.delete(lf_band.get(i))
            line.delete(ln_band.get(i))
            lf_band.set(i, na)
            ln_band.set(i, na)
            label lb = lb_cap.get(i)
            lb.set_text(f_caption(sd, tl_touch.get(i), true))
            lb.set_xy(time, lv)
            lb.set_style(sd == 1 ? label.style_label_down : label.style_label_up)
            if sd == 1
                brk_hi := true
            else
                brk_lo := true
 
if not na(atr)
    if new_hi or brk_hi
        f_rebuild(1)
    if new_lo or brk_lo
        f_rebuild(-1)
 
// captions follow the last bar
if ln_main.size() > 0
    for i = 0 to ln_main.size() - 1
        if tl_brk.get(i) == -1
            lb_cap.get(i).set_xy(time + 3 * bar_ms, f_lval(i, bar_index))
 
// =============================================================================
// CHANNEL AND PATTERN
// The best line of each side defines the pattern by the difference of slopes.
// Redrawn on the last bar only: the pattern describes the current state.
// =============================================================================
var line     ch_ln = na
var linefill ch_lf = na
var label    ch_lb = na
 
f_best(int sd) =>
    int best = -1
    if ln_main.size() > 0
        for i = 0 to ln_main.size() - 1
            if tl_side.get(i) == sd and tl_brk.get(i) == -1
                if best == -1 or tl_touch.get(i) > tl_touch.get(best) or (tl_touch.get(i) == tl_touch.get(best) and tl_b1.get(i) > tl_b1.get(best))
                    best := i
    best
 
if show_ch and barstate.islast
    line.delete(ch_ln)
    linefill.delete(ch_lf)
    label.delete(ch_lb)
    int u = f_best(1)
    int d = f_best(-1)
    if u != -1 and d != -1
        float su = (tl_p2.get(u) - tl_p1.get(u)) / (tl_b2.get(u) - tl_b1.get(u))
        float sl = (tl_p2.get(d) - tl_p1.get(d)) / (tl_b2.get(d) - tl_b1.get(d))
        float scale = math.max(math.abs(su), math.abs(sl), 0.02 * atr)
        float diff = su - sl
        string kind = math.abs(diff) <= 0.25 * scale ? "CHANNEL" : diff < 0 ? (su < 0 and sl > 0 ? "CONTRACTING · triangle" : "CONTRACTING · wedge") : "EXPANDING"
        ch_lf := linefill.new(ln_main.get(u), ln_main.get(d), color.new(col_ch, 90))
        float mid = (f_lval(u, bar_index) + f_lval(d, bar_index)) / 2
        ch_lb := label.new(time + (3 + label_dx) * bar_ms, mid, kind, xloc = xloc.bar_time, style = label.style_label_left,
             color = color(na), textcolor = color.new(col_ch, 0), size = label_size)
    else if u != -1 or d != -1
        // one line: a parallel through the opposite extreme of its span
        int i = u != -1 ? u : d
        int sd = tl_side.get(i)
        float s = (tl_p2.get(i) - tl_p1.get(i)) / (tl_b2.get(i) - tl_b1.get(i))
        int lim = math.min(bar_index - tl_b1.get(i), 1990)
        float ext = na
        int extb = na
        for off = lim to 0
            float v = sd == 1 ? low[off] - s * (bar_index - off) : high[off] - s * (bar_index - off)
            if na(ext) or (sd == 1 ? v < ext : v > ext)
                ext := v
                extb := bar_index - off
        if not na(ext)
            float p0 = ext + s * extb
            [valid, t, s2, lt2] = f_eval(extb, p0, extb + 100, p0 + s * 100, -sd, touch_tol * atr, break_tol * atr)
            if valid and t >= 2
                color c = sd == 1 ? col_up : col_dn
                ch_ln := line.new(tl_b1.get(i), p0 + s * (tl_b1.get(i) - extb), bar_index, p0 + s * (bar_index - extb),
                     xloc = xloc.bar_index, extend = extend.right, color = color.new(c, 30), width = 1, style = line.style_dashed)
                ch_lf := linefill.new(ln_main.get(i), ch_ln, color.new(col_ch, 92))
                float mid = (f_lval(i, bar_index) + p0 + s * (bar_index - extb)) / 2
                ch_lb := label.new(time + (3 + label_dx) * bar_ms, mid, "CHANNEL · parallel", xloc = xloc.bar_time, style = label.style_label_left,
                     color = color(na), textcolor = color.new(col_ch, 0), size = label_size)
 
// =============================================================================
// ALERTS
// One alert per break, fired on the close of the breaking bar.
// =============================================================================
alertcondition(brk_hi, "Resistance line broken", "{{ticker}} {{interval}}: price closed above a resistance trend line")
alertcondition(brk_lo, "Support line broken", "{{ticker}} {{interval}}: price closed below a support trend line")
 
// Hidden price plot: binds the indicator to the symbol scale.
plot(close, "Scale anchor", color = color(na), display = display.none, editable = false)

← 返回列表