RSI Triangle Detector

HyperCruc · study · 212 行 · 点赞 19 · TradingView 原页

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

Pine Script

//@version=6
indicator("RSI Triangle Detector", shorttitle="RSI Triangle", overlay=false, max_lines_count=500, max_labels_count=500, max_bars_back=500)
 
// ───────── Inputs ─────────
grpR   = "RSI"
src    = input.source(close, "Source", group=grpR)
rsiLen = input.int(14, "RSI Length", minval=1, group=grpR)
maLen  = input.int(14, "MA Length", minval=1, group=grpR)
 
grpT     = "Triangle"
pivL     = input.int(3, "Pivot Left Bars", minval=1, group=grpT)
pivR     = input.int(3, "Pivot Right Bars", minval=1, group=grpT)
minWidth = input.int(8, "Min Triangle Width (bars)", minval=2, group=grpT)
maxWidth = input.int(100, "Max Triangle Width (bars)", minval=5, maxval=300, group=grpT)
flatTol  = input.float(0.10, "Flat Slope Tolerance (RSI/bar)", minval=0, step=0.01, group=grpT)
minConv  = input.float(0.10, "Min Convergence (RSI/bar)", minval=0.01, step=0.01, group=grpT, tooltip="How much the upper and lower lines approach each other per bar. Higher values pick up only clearly defined triangles.")
tol      = input.float(2.0, "Line Overshoot Tolerance (RSI)", minval=0, step=0.5, group=grpT)
breakBuf = input.float(0.0, "Breakout Buffer (RSI)", minval=0, step=0.5, group=grpT)
maxWait  = input.int(40, "Bars to Wait for Breakout After Formation", minval=1, group=grpT)
useMid   = input.bool(true, "Exclude Triangles Crossing the Midline", group=grpT, tooltip="Only triangles that sit entirely above or entirely below the midline are evaluated.")
midLv    = input.float(50.0, "Midline", minval=1, maxval=99, step=1, group=grpT)
useDir   = input.bool(true, "Filter by Line Direction", group=grpT, tooltip="Triangles above the midline: exclude those whose upper line slopes up (flat or falling only). Triangles below the midline: exclude those whose lower line slopes down (flat or rising only).")
 
grpV     = "Display"
showType = input.bool(true, "Show Triangle Type", group=grpV)
colTri   = input.color(color.white, "Triangle Lines", group=grpV)
colBull  = input.color(color.teal, "Breakout Up", group=grpV)
colBear  = input.color(color.red, "Breakout Down", group=grpV)
 
grpC       = "Chart Display"
showLv     = input.bool(true, "Show Horizontal Line and Trendline", group=grpC, tooltip="Triangles above the midline: a horizontal line at the period high, and a trendline connecting the lows on the lower side. Triangles below the midline: a horizontal line at the period low, and a trendline connecting the highs on the upper side.")
showChartL = input.bool(true, "Show Label on Breakout Bar", group=grpC)
maxSets    = input.int(50, "Line Sets to Keep", minval=1, maxval=100, group=grpC, tooltip="One set consists of two lines: a horizontal line and a trendline. Older lines beyond this number are deleted.")
extBars    = input.int(50, "Bars to Extend Lines After Breakout", minval=1, group=grpC)
colLv      = input.color(color.orange, "Line Color", group=grpC)
 
// ───────── RSI ─────────
rsi   = ta.rsi(src, rsiLen)
rsiMa = ta.sma(rsi, maLen)
 
plot(rsi, "RSI", color=color.new(#7e57c2, 0))
plot(rsiMa, "RSI MA", color=color.yellow)
hU = hline(70, "Upper Band", color=color.gray, linestyle=hline.style_dashed)
hline(midLv, "Midline", color=color.new(color.gray, 50), linestyle=hline.style_dashed)
hD = hline(30, "Lower Band", color=color.gray, linestyle=hline.style_dashed)
fill(hU, hD, color=color.new(#7e57c2, 92))
 
// ───────── Pivot high / low tracking ─────────
ph = ta.pivothigh(rsi, pivL, pivR)
pl = ta.pivotlow(rsi, pivL, pivR)
 
var int   h1x = na
var float h1y = na
var int   h2x = na
var float h2y = na
var int   l1x = na
var float l1y = na
var int   l2x = na
var float l2y = na
 
bool newPivot = false
if barstate.isconfirmed
    if not na(ph)
        h1x := h2x
        h1y := h2y
        h2x := bar_index - pivR
        h2y := ph
        newPivot := true
    if not na(pl)
        l1x := l2x
        l1y := l2y
        l2x := bar_index - pivR
        l2y := pl
        newPivot := true
 
// ───────── Triangle being monitored ─────────
var bool  active    = false
var int   aHx       = na
var float aHy       = na
var float aSH       = na
var int   aLx       = na
var float aLy       = na
var float aSL       = na
var int   aHx2      = na
var float aHy2      = na
var int   aLx2      = na
var float aLy2      = na
var int   formedBar = na
var line  upLn      = na
var line  loLn      = na
 
bool formed    = false
bool bullBreak = false
bool bearBreak = false
 
// Check the formed triangle on every bar
if active and barstate.isconfirmed
    u = aHy + aSH * (bar_index - aHx)
    l = aLy + aSL * (bar_index - aLx)
    line.set_xy2(upLn, bar_index, u)
    line.set_xy2(loLn, bar_index, l)
    if u <= l
        active := false // Reached the apex (no breakout)
    else if rsi > u + breakBuf
        bullBreak := true
        active := false
    else if rsi < l - breakBuf
        bearBreak := true
        active := false
    else if bar_index - formedBar > maxWait
        active := false
 
// ───────── Chart display (horizontal line and trendline) ─────────
var line[]  lvLines = array.new<line>()
var int[]   lvBars  = array.new<int>()
var float[] lvSlope = array.new<float>()
 
if bullBreak or bearBreak
    startX = math.min(aHx, aLx)
    n = bar_index - startX
    // Find the high and low of the consolidation period only, excluding the breakout bar
    float hh = high[1]
    float ll = low[1]
    if n >= 1
        for i = 1 to n
            hh := math.max(hh, high[i])
            ll := math.min(ll, low[i])
    // Whether the triangle is above or below the midline
    upperSide = (aHy + aHy2 + aLy + aLy2) / 4 >= midLv
    if showLv
        if upperSide
            // Upper: horizontal line at the period high / Lower: trendline connecting the lows of the RSI pivot-low bars
            y1 = low[bar_index - aLx]
            y2 = low[bar_index - aLx2]
            sl = (y2 - y1) / (aLx2 - aLx)
            lvLines.push(line.new(startX, hh, bar_index, hh, color=colLv, style=line.style_dashed, width=1, force_overlay=true))
            lvSlope.push(0.0)
            lvLines.push(line.new(aLx, y1, bar_index, y1 + sl * (bar_index - aLx), color=colLv, style=line.style_solid, width=1, force_overlay=true))
            lvSlope.push(sl)
        else
            // Lower: horizontal line at the period low / Upper: trendline connecting the highs of the RSI pivot-high bars
            y1 = high[bar_index - aHx]
            y2 = high[bar_index - aHx2]
            sl = (y2 - y1) / (aHx2 - aHx)
            lvLines.push(line.new(startX, ll, bar_index, ll, color=colLv, style=line.style_dashed, width=1, force_overlay=true))
            lvSlope.push(0.0)
            lvLines.push(line.new(aHx, y1, bar_index, y1 + sl * (bar_index - aHx), color=colLv, style=line.style_solid, width=1, force_overlay=true))
            lvSlope.push(sl)
        lvBars.push(bar_index)
        lvBars.push(bar_index)
        while lvLines.size() > maxSets * 2
            line.delete(lvLines.shift())
            lvBars.shift()
            lvSlope.shift()
    if showChartL
        label.new(bar_index, na, bullBreak ? "Break Up" : "Break Down", yloc=bullBreak ? yloc.belowbar : yloc.abovebar, style=bullBreak ? label.style_label_up : label.style_label_down, color=bullBreak ? colBull : colBear, textcolor=color.white, size=size.small, force_overlay=true)
 
// Extend the remaining lines to the right (trendlines keep their slope)
if lvLines.size() > 0
    for i = 0 to lvLines.size() - 1
        if bar_index - lvBars.get(i) <= extBars
            ln = lvLines.get(i)
            line.set_xy2(ln, bar_index, line.get_y1(ln) + lvSlope.get(i) * (bar_index - line.get_x1(ln)))
 
// When a new pivot high or low is confirmed, check whether a triangle has formed
if barstate.isconfirmed and newPivot and not active and not na(h1x) and not na(l1x)
    sH    = (h2y - h1y) / (h2x - h1x)
    sL    = (l2y - l1y) / (l2x - l1x)
    width = math.max(h2x, l2x) - math.min(h1x, l1x)
    shapeOk   = sH <= flatTol and sL >= -flatTol and (sL - sH) >= minConv
    widthOk   = width >= minWidth and width <= maxWidth
    overlapOk = math.max(h1x, l1x) < math.min(h2x, l2x)
    // Whether all four pivot points are on the same side of the midline
    sideOk    = not useMid or math.min(l1y, l2y) >= midLv or math.max(h1y, h2y) <= midLv
    // Above the midline: upper line flat or falling only / Below the midline: lower line flat or rising only
    upperTri  = (h1y + h2y + l1y + l2y) / 4 >= midLv
    dirOk     = not useDir or (upperTri ? sH <= 0 : sL >= 0)
    if shapeOk and widthOk and overlapOk and sideOk and dirOk
        startX = math.max(h1x, l1x)
        ok = true
        for i = 0 to bar_index - startX
            x = bar_index - i
            u = h1y + sH * (x - h1x)
            l = l1y + sL * (x - l1x)
            if u <= l or rsi[i] > u + tol or rsi[i] < l - tol
                ok := false
                break
        if ok
            active    := true
            formed    := true
            formedBar := bar_index
            aHx := h1x
            aHy := h1y
            aSH := sH
            aLx := l1x
            aLy := l1y
            aSL := sL
            aHx2 := h2x
            aHy2 := h2y
            aLx2 := l2x
            aLy2 := l2y
            upLn := line.new(h1x, h1y, bar_index, h1y + sH * (bar_index - h1x), color=colTri, width=1)
            loLn := line.new(l1x, l1y, bar_index, l1y + sL * (bar_index - l1x), color=colTri, width=1)
            linefill.new(upLn, loLn, color.new(colTri, 90))
            if showType
                triType = math.abs(sH) <= flatTol ? "Ascending Triangle" : math.abs(sL) <= flatTol ? "Descending Triangle" : "Symmetrical Triangle"
                label.new(h1x, h1y, triType, style=label.style_none, textcolor=colTri, size=size.small, yloc=yloc.price)
 
// ───────── Alerts ─────────
alertcondition(formed, "Triangle Formed", "RSI has formed a triangle pattern")
alertcondition(bullBreak, "Triangle Breakout Up", "RSI broke out above the triangle")
alertcondition(bearBreak, "Triangle Breakout Down", "RSI broke out below the triangle")

← 返回列表