本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sunilp303
//@version=6
indicator("RSI Divergence Strength + ATR Extension", shorttitle = "RSI Div Strength + ATR X", overlay = false, format = format.price, precision = 2, max_bars_back = 1000, max_lines_count = 100, max_labels_count = 100)
// ─────────────────────────────────────────────────────────────────────────────
// A signal needs all of the following:
// 1. Regular divergence: price makes a new extreme and RSI does not confirm it
// 2. RSI was stretched at the pivots
// 3. Price confirms by closing through the trigger level within 10 bars
//
// Label: P = price % change between pivots | RSI = RSI % change between pivots
// ─────────────────────────────────────────────────────────────────────────────
// ───── Inputs ─────
int rsiLen = input.int(14, "RSI length", minval = 2)
string quality = input.string("Strict", "Signal quality", options = ["Strict", "Normal"], tooltip = "Strict: RSI beyond 35/65, at least 5 RSI points of divergence, 15 bars between same-side signals. Normal: RSI beyond 40/60, at least 3 RSI points, 10 bars between same-side signals.")
bool waitConfirm = input.bool(true, "Wait for price confirmation", tooltip = "Bullish: close above the high made since the pivot. Bearish: close below the low made since the pivot. The setup is cancelled if price closes beyond the second pivot or 10 bars pass.")
int lbL = input.int(5, "Pivot left bars", minval = 1, maxval = 50)
int lbR = input.int(3, "Pivot right bars", minval = 1, maxval = 50)
int maxDrawn = input.int(4, "Divergences to show", minval = 1, maxval = 20)
bool showPxLines = input.bool(true, "Draw lines on price chart")
color rsiCol = input.color(#7E57C2, "RSI")
const string G_SHADE = "Color by Gap %"
float weakGap = input.float(15.0, "Darkest at Gap %", minval = 0, step = 1, tooltip = "Gap % = |Price % - RSI %|. Signals at or below this value use the darkest color.", group = G_SHADE)
float strongGap = input.float(45.0, "Brightest at Gap %", minval = 1, step = 1, tooltip = "Signals at or above this value use the brightest color.", group = G_SHADE)
color bearCol = input.color(#FF1744, "Bearish: bright", inline = "bear", group = G_SHADE)
color bearWeak = input.color(#7F1D1D, "dark", inline = "bear", group = G_SHADE)
color bullCol = input.color(#00C853, "Bullish: bright", inline = "bull", group = G_SHADE)
color bullWeak = input.color(#0B4F45, "dark", inline = "bull", group = G_SHADE)
const string G_ALERT = "Alerts"
bool alertsOn = input.bool(true, "Enable alerts", tooltip = "After changing any alert setting, delete and recreate the TradingView alert. Alerts keep the settings they were created with.", group = G_ALERT)
bool alertBull = input.bool(true, "Bullish signals", group = G_ALERT)
bool alertBear = input.bool(true, "Bearish signals", group = G_ALERT)
bool alertEarly = input.bool(false, "Early alert when a setup forms", tooltip = "Alerts when the divergence appears, before price confirms it, and includes the trigger price. Requires Wait for price confirmation. Some setups will be cancelled without confirming.", group = G_ALERT)
string alertFormat = input.string("Text", "Message format", options = ["Text", "JSON"], tooltip = "Text is easy to read on phone, email or popup. JSON is for webhooks.", group = G_ALERT)
bool atrXAlert = input.bool(true, "Alert when ATR X from MA is reached", tooltip = "Fires on the bar close when price first moves beyond the level, above or below the MA.", group = G_ALERT)
float atrXLevel = input.float(4.0, "ATR X alert level", minval = 0.5, step = 0.5, group = G_ALERT)
const string G_ATRX = "ATR X from MA"
int maLen = input.int(50, "MA length", minval = 1, group = G_ATRX)
string maType = input.string("SMA", "MA type", options = ["SMA", "EMA"], group = G_ATRX)
bool showAtrX = input.bool(true, "Show ATR X in RSI pane", group = G_ATRX)
// ───── Fixed rules ─────
const int MIN_BARS = 5
const int MAX_BARS = 60
const int PIVOTS_KEPT = 5
const int PIVOT_TOL = 2
const int ARM_BARS = 10
bool isStrict = quality == "Strict"
float bullZone = isStrict ? 35.0 : 40.0
float bearZone = isStrict ? 65.0 : 60.0
float minPts = isStrict ? 5.0 : 3.0
float minAtr = isStrict ? 0.5 : 0.25
int coolDown = isStrict ? 15 : 10
// ───── Types ─────
type Pivot
int rsiBar
float rsiVal
int priceBar
float priceVal
float atrVal
type Setup
int dir
Pivot a
Pivot b
float pricePct
float rsiPct
float rsiPts
float gapPct
float level
int armedBar
type Drawing
line rsiLine
line priceLine
label rsiLabel
// ───── Series ─────
float rsiSeries = ta.rsi(close, rsiLen)
float atrSeries = ta.atr(14)
float rsiPL = ta.pivotlow(rsiSeries, lbL, lbR)
float rsiPH = ta.pivothigh(rsiSeries, lbL, lbR)
float highSince = ta.highest(high, lbR + 1)
float lowSince = ta.lowest(low, lbR + 1)
// ATR X = (Close - MA) / ATR(14). Positive is above the MA, negative is below it.
float smaSeries = ta.sma(close, maLen)
float emaSeries = ta.ema(close, maLen)
float maSeries = maType == "EMA" ? emaSeries : smaSeries
float atrX = atrSeries > 0 ? (close - maSeries) / atrSeries : na
string maName = str.tostring(maLen) + " " + maType
bool atrXUp = ta.crossover(atrX, atrXLevel)
bool atrXDown = ta.crossunder(atrX, -atrXLevel)
// ───── State ─────
var array<Pivot> lowPivots = array.new<Pivot>()
var array<Pivot> highPivots = array.new<Pivot>()
var array<Drawing> drawings = array.new<Drawing>()
var Setup armedBull = na
var Setup armedBear = na
var int lastBull = na
var int lastBear = na
// ───── Helpers ─────
fmtPct(float x) =>
(x >= 0 ? "+" : "") + str.tostring(x, "0.00") + "%"
fmtX(float x) =>
na(x) ? "n/a" : (x >= 0 ? "+" : "") + str.tostring(x, "0.00") + "x"
priceExtreme(bool isLow) =>
int t = math.min(PIVOT_TOL, lbR)
float best = isLow ? low[lbR] : high[lbR]
int bestOff = lbR
for off = lbR - t to lbR + t
float v = isLow ? low[off] : high[off]
if not na(v) and (isLow ? v < best : v > best)
best := v
bestOff := off
[best, bar_index - bestOff]
rsiLineClear(Pivot a, Pivot b, bool isLow) =>
bool ok = true
int span = b.rsiBar - a.rsiBar
if span > 1
float slope = (b.rsiVal - a.rsiVal) / span
for i = 1 to span - 1
float v = rsiSeries[bar_index - (a.rsiBar + i)]
float lineY = a.rsiVal + slope * i
if not na(v) and (isLow ? v < lineY : v > lineY)
ok := false
break
ok
evaluate(Pivot a, Pivot b, bool isLow) =>
Setup result = na
bool shapeOk = isLow ? b.priceVal < a.priceVal and b.rsiVal > a.rsiVal : b.priceVal > a.priceVal and b.rsiVal < a.rsiVal
bool zoneOk = isLow ? math.min(a.rsiVal, b.rsiVal) <= bullZone : math.max(a.rsiVal, b.rsiVal) >= bearZone
bool sizeOk = math.abs(b.rsiVal - a.rsiVal) >= minPts and math.abs(b.priceVal - a.priceVal) >= minAtr * nz(b.atrVal)
if shapeOk and zoneOk and sizeOk and a.priceVal != 0 and a.rsiVal != 0
if rsiLineClear(a, b, isLow)
float pricePct = (b.priceVal - a.priceVal) / a.priceVal * 100.0
float rsiPct = (b.rsiVal - a.rsiVal) / a.rsiVal * 100.0
float gapPct = math.abs(pricePct - rsiPct)
result := Setup.new(isLow ? 1 : -1, a, b, pricePct, rsiPct, b.rsiVal - a.rsiVal, gapPct, isLow ? highSince : lowSince, bar_index)
result
scan(array<Pivot> pivots, Pivot b, bool isLow) =>
Setup result = na
int n = pivots.size()
if n > 0
for i = n - 1 to 0
Pivot a = pivots.get(i)
int dist = b.rsiBar - a.rsiBar
if dist > MAX_BARS
break
if dist >= MIN_BARS
result := evaluate(a, b, isLow)
if not na(result)
break
result
// Weak divergences are dark and strong divergences are bright.
strengthColor(Setup s) =>
float top = math.max(strongGap, weakGap + 1.0)
s.dir == 1 ? color.from_gradient(s.gapPct, weakGap, top, bullWeak, bullCol) : color.from_gradient(s.gapPct, weakGap, top, bearWeak, bearCol)
// Bright green needs dark text to stay readable.
labelTextColor(Setup s) =>
float top = math.max(strongGap, weakGap + 1.0)
s.dir == 1 and s.gapPct >= (weakGap + top) / 2.0 ? color.black : color.white
sendAlert(Setup s, bool isEarly) =>
bool sideOn = s.dir == 1 ? alertBull : alertBear
if alertsOn and sideOn
string name = s.dir == 1 ? "Bullish" : "Bearish"
string stage = isEarly ? "setup" : "confirmed"
string trigger = str.tostring(s.level, format.mintick)
string detail = isEarly ? "setup forming, trigger: close " + (s.dir == 1 ? "above " : "below ") + trigger : "confirmed at " + str.tostring(close, format.mintick)
string textMsg = syminfo.ticker + " " + timeframe.period + ": " + name + " RSI divergence " + detail + " | P " + fmtPct(s.pricePct) + " | RSI " + fmtPct(s.rsiPct) + " | ATR X from " + maName + ": " + fmtX(atrX)
string jsonMsg = '{"ticker":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","type":"' + name + '","stage":"' + stage + '","close":' + str.tostring(close) + ',"trigger":' + str.tostring(s.level) + ',"price_pct":' + str.tostring(s.pricePct, "0.00") + ',"rsi_pct":' + str.tostring(s.rsiPct, "0.00") + ',"rsi_pts":' + str.tostring(s.rsiPts, "0.00") + ',"gap_pct":' + str.tostring(s.gapPct, "0.00") + ',"atr_x":' + str.tostring(nz(atrX), "0.00") + ',"ma":"' + maName + '"}'
alert(alertFormat == "JSON" ? jsonMsg : textMsg, alert.freq_once_per_bar_close)
emitSignal(Setup s) =>
color c = strengthColor(s)
string name = s.dir == 1 ? "Bullish" : "Bearish"
string txt = "P " + fmtPct(s.pricePct) + " | RSI " + fmtPct(s.rsiPct) + " | ATR " + fmtX(atrX)
string tip = name + " RSI divergence\nPrice: " + str.tostring(s.a.priceVal, format.mintick) + " → " + str.tostring(s.b.priceVal, format.mintick) + " (" + fmtPct(s.pricePct) + ")\nRSI: " + str.tostring(s.a.rsiVal, "0.00") + " → " + str.tostring(s.b.rsiVal, "0.00") + " (" + fmtPct(s.rsiPct) + ", " + str.tostring(s.rsiPts, "0.00") + " pts)\nGap: " + str.tostring(s.gapPct, "0.00") + "%\nATR X from " + maName + " at signal: " + fmtX(atrX)
line rl = line.new(s.a.rsiBar, s.a.rsiVal, s.b.rsiBar, s.b.rsiVal, color = c, width = 2)
line pl = showPxLines ? line.new(s.a.priceBar, s.a.priceVal, s.b.priceBar, s.b.priceVal, color = c, width = 2, force_overlay = true) : na
label lb = label.new(s.b.rsiBar, s.b.rsiVal, txt, color = c, textcolor = labelTextColor(s), style = s.dir == 1 ? label.style_label_up : label.style_label_down, size = size.small, tooltip = tip)
drawings.push(Drawing.new(rl, pl, lb))
while drawings.size() > maxDrawn
Drawing old = drawings.shift()
line.delete(old.rsiLine)
line.delete(old.priceLine)
label.delete(old.rsiLabel)
sendAlert(s, false)
// ───── Signal engine (bar close only) ─────
Setup firedBull = na
Setup firedBear = na
if barstate.isconfirmed
if not na(armedBull)
if close < armedBull.b.priceVal or bar_index - armedBull.armedBar > ARM_BARS
armedBull := na
else if close > armedBull.level
firedBull := armedBull
armedBull := na
if not na(armedBear)
if close > armedBear.b.priceVal or bar_index - armedBear.armedBar > ARM_BARS
armedBear := na
else if close < armedBear.level
firedBear := armedBear
armedBear := na
if barstate.isconfirmed and not na(rsiPL)
[px, pxBar] = priceExtreme(true)
Pivot p = Pivot.new(bar_index - lbR, rsiSeries[lbR], pxBar, px, atrSeries[bar_index - pxBar])
Setup found = scan(lowPivots, p, true)
if not na(found)
if waitConfirm
armedBull := found
if alertEarly and (na(lastBull) or bar_index - lastBull >= coolDown)
sendAlert(found, true)
else
firedBull := found
lowPivots.push(p)
if lowPivots.size() > PIVOTS_KEPT
lowPivots.shift()
if barstate.isconfirmed and not na(rsiPH)
[px, pxBar] = priceExtreme(false)
Pivot p = Pivot.new(bar_index - lbR, rsiSeries[lbR], pxBar, px, atrSeries[bar_index - pxBar])
Setup found = scan(highPivots, p, false)
if not na(found)
if waitConfirm
armedBear := found
if alertEarly and (na(lastBear) or bar_index - lastBear >= coolDown)
sendAlert(found, true)
else
firedBear := found
highPivots.push(p)
if highPivots.size() > PIVOTS_KEPT
highPivots.shift()
bool sigBull = not na(firedBull) and (na(lastBull) or bar_index - lastBull >= coolDown)
bool sigBear = not na(firedBear) and (na(lastBear) or bar_index - lastBear >= coolDown)
if sigBull
lastBull := bar_index
emitSignal(firedBull)
if sigBear
lastBear := bar_index
emitSignal(firedBear)
// ───── ATR X alert ─────
if barstate.isconfirmed and alertsOn and atrXAlert and (atrXUp or atrXDown)
string side = atrXUp ? "above" : "below"
string textMsg = syminfo.ticker + " " + timeframe.period + ": Price is " + fmtX(atrX) + " ATR from the " + maName + " (" + side + " the " + str.tostring(atrXLevel, "0.0") + "x level) at " + str.tostring(close, format.mintick)
string jsonMsg = '{"ticker":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","type":"ATR X","side":"' + side + '","close":' + str.tostring(close) + ',"atr_x":' + str.tostring(nz(atrX), "0.00") + ',"level":' + str.tostring(atrXLevel) + ',"ma":"' + maName + '"}'
alert(alertFormat == "JSON" ? jsonMsg : textMsg, alert.freq_once_per_bar_close)
// ───── ATR X badge in the RSI pane ─────
var table atrBadge = table.new(position.top_right, 1, 1, border_width = 0)
if showAtrX and barstate.islast
bool isExtended = not na(atrX) and math.abs(atrX) >= atrXLevel
color badgeBg = isExtended ? (atrX > 0 ? bearCol : bullCol) : color.new(color.gray, 25)
table.cell(atrBadge, 0, 0, "ATR X from " + maName + ": " + fmtX(atrX), text_color = color.white, text_size = size.small, bgcolor = badgeBg, tooltip = "(Close - " + maName + ") / ATR(14). The badge is colored at or beyond the " + str.tostring(atrXLevel, "0.0") + "x alert level.")
plot(atrX, "ATR X from MA", color = color.gray, display = display.status_line + display.data_window)
// ───── Plots ─────
hTop = hline(70, "Overbought", color = color.new(color.gray, 50), linestyle = hline.style_dashed)
hBot = hline(30, "Oversold", color = color.new(color.gray, 50), linestyle = hline.style_dashed)
hline(50, "Midline", color = color.new(color.gray, 75), linestyle = hline.style_dotted)
fill(hTop, hBot, color = color.new(rsiCol, 94), title = "RSI band")
plot(rsiSeries, "RSI", color = rsiCol, linewidth = 2)
color bullMarker = sigBull ? strengthColor(firedBull) : na
color bearMarker = sigBear ? strengthColor(firedBear) : na
plotshape(sigBull, "Bullish signal", shape.triangleup, location.belowbar, bullMarker, size = size.small, force_overlay = true)
plotshape(sigBear, "Bearish signal", shape.triangledown, location.abovebar, bearMarker, size = size.small, force_overlay = true)
// ───── Alert setup ─────
// Add Alert > Condition: RSI Div Strength + ATR X > Any alert() function call
// The Alerts section in the indicator settings controls what fires and the message format.