本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// MacD + Divergence
// MOM = MACD line (fast EMA - slow EMA), DAD = its signal line used as long-term momentum.
// Adds slope coloring, momentum wave counts (1-2-3-4-5) and MOM divergence.
indicator("MacD + Divergence", shorttitle = "MacD + Divergence", overlay = false, max_labels_count = 500, max_lines_count = 500)
// ═══ Settings ════════════════════════════════════════════════════════════════
presetIn = input.string("1:3", "Length preset", options = ["1:3", "1:5", "Custom"], group = "Settings", tooltip = "1:3 = 5/20/30 (default, for charts in a 1:3 ratio). 1:5 = 3/10/15. Custom uses the three lengths below.")
srcIn = input.source(close, "Source", group = "Settings")
fastIn = input.int(5, "Custom fast EMA", minval = 1, group = "Settings")
slowIn = input.int(20, "Custom slow EMA", minval = 1, group = "Settings")
dadIn = input.int(30, "Custom DAD EMA", minval = 1, group = "Settings")
colorMode = input.string("Live", "Color update mode", options = ["Live", "On bar close"], group = "Settings", tooltip = "Live: colors flip intrabar on the right edge. On bar close: the live bar keeps the last confirmed color.")
// ═══ Display ═════════════════════════════════════════════════════════════════
showMom = input.bool(true, "Show MOM line", group = "Display")
showHist = input.bool(false, "Show MOM histogram", group = "Display")
showDad = input.bool(true, "Show DAD line", group = "Display")
showZero = input.bool(true, "Show zero line", group = "Display")
momWidth = input.int(1, "MOM line width", minval = 1, maxval = 10, group = "Display")
dadWidth = input.int(3, "DAD line width", minval = 1, maxval = 10, group = "Display")
histTransp = input.int(40, "Histogram transparency", minval = 0, maxval = 100, group = "Display")
// ═══ Colors ══════════════════════════════════════════════════════════════════
slopeColor = input.bool(true, "Color lines by slope", group = "Colors", tooltip = "On: MOM, DAD and the histogram switch between their rising and falling colors bar by bar. Off: each one uses a single color — the left swatch of its row.")
momRiseCol = input.color(#22C55E, "MOM line", group = "Colors", inline = "mom")
momFallCol = input.color(#EF4444, "", group = "Colors", inline = "mom", tooltip = "Left swatch = rising, right swatch = falling.")
dadRiseCol = input.color(#22C55E, "DAD line", group = "Colors", inline = "dad")
dadFallCol = input.color(#EF4444, "", group = "Colors", inline = "dad", tooltip = "Left swatch = rising, right swatch = falling.")
histRiseCol = input.color(#22C55E, "Histogram", group = "Colors", inline = "hist")
histFallCol = input.color(#EF4444, "", group = "Colors", inline = "hist", tooltip = "Left swatch = rising, right swatch = falling.")
zeroCol = input.color(#FFFFFF, "Zero line", group = "Colors")
upWaveCol = input.color(#22C55E, "Wave counts", group = "Colors", inline = "wave")
dnWaveCol = input.color(#EF4444, "", group = "Colors", inline = "wave", tooltip = "Left swatch = up count, right swatch = down count.")
bullCol = input.color(#22C55E, "Regular divergence", group = "Colors", inline = "reg")
bearCol = input.color(#EF4444, "", group = "Colors", inline = "reg", tooltip = "Left swatch = bullish, right swatch = bearish.")
sBullCol = input.color(#15803D, "Strong divergence", group = "Colors", inline = "strong")
sBearCol = input.color(#B91C1C, "", group = "Colors", inline = "strong", tooltip = "Left swatch = bullish, right swatch = bearish.")
hBullCol = input.color(#3B82F6, "Hidden divergence", group = "Colors", inline = "hid")
hBearCol = input.color(#F97316, "", group = "Colors", inline = "hid", tooltip = "Left swatch = bullish, right swatch = bearish.")
// ═══ Wave counts ═════════════════════════════════════════════════════════════
showCounts = input.bool(true, "Show wave counts", group = "Wave counts")
confirmBars = input.int(1, "Bars to confirm a hook", minval = 1, maxval = 10, group = "Wave counts", tooltip = "How many bars MOM must move the other way before a peak/trough counts. Higher = fewer, cleaner counts.")
requireStoch = input.bool(false, "Require stochastic cycle", group = "Wave counts", tooltip = "Stricter rule: a MOM peak only counts if Stochastic %K (5,2,3) also made a cycle high within N bars; troughs need a cycle low.")
stochWin = input.int(2, "Stochastic window (bars)", minval = 0, maxval = 20, group = "Wave counts")
lblSizeIn = input.string("small", "Label size", options = ["tiny", "small", "normal", "large"], group = "Wave counts")
// ═══ Divergence ══════════════════════════════════════════════════════════════
showDiv = input.bool(true, "Show divergence", group = "Divergence")
showBear = input.bool(true, "Regular bearish", group = "Divergence", inline = "d1")
showBull = input.bool(true, "Regular bullish", group = "Divergence", inline = "d1")
showSBear = input.bool(true, "Strong bearish", group = "Divergence", inline = "d2")
showSBull = input.bool(true, "Strong bullish", group = "Divergence", inline = "d2")
showHBear = input.bool(false, "Hidden bearish", group = "Divergence", inline = "d3")
showHBull = input.bool(false, "Hidden bullish", group = "Divergence", inline = "d3")
showDivLbl = input.bool(true, "Show divergence labels", group = "Divergence")
divLookback = input.int(60, "Lookback bars", minval = 5, group = "Divergence")
divMinBars = input.int(5, "Minimum bars apart", minval = 1, group = "Divergence")
priceWin = input.int(3, "Price window (bars)", minval = 1, maxval = 11, group = "Divergence", tooltip = "Price at a MOM pivot = highest high / lowest low over this window centred on the pivot bar.")
reqBeyond0 = input.bool(false, "Require pivots beyond zero", group = "Divergence", tooltip = "Bearish needs both MOM peaks above zero, bullish needs both troughs below zero.")
// ═══ Status window ═══════════════════════════════════════════════════════════
showPanel = input.bool(false, "Show status window", group = "Status window", tooltip = "Green when MOM and DAD are both rising, red when both are falling, neutral when they disagree.")
panelPos = input.string("Top right", "Position", options = ["Top right", "Top left", "Bottom right", "Bottom left", "Middle right"], group = "Status window")
panelSize = input.string("normal", "Text size", options = ["tiny", "small", "normal", "large"], group = "Status window")
panelBuy = input.color(#22C55E, "Buy", group = "Status window", inline = "pcol")
panelSell = input.color(#EF4444, "Sell", group = "Status window", inline = "pcol")
panelWait = input.color(#6B7280, "Wait", group = "Status window", inline = "pcol")
// ═══ Core math ═══════════════════════════════════════════════════════════════
fastLen = presetIn == "1:3" ? 5 : presetIn == "1:5" ? 3 : fastIn
slowLen = presetIn == "1:3" ? 20 : presetIn == "1:5" ? 10 : slowIn
dadLen = presetIn == "1:3" ? 30 : presetIn == "1:5" ? 15 : dadIn
mom = ta.ema(srcIn, fastLen) - ta.ema(srcIn, slowLen)
dad = ta.ema(mom, dadLen)
// ═══ Slope coloring (hold the previous color when flat) ══════════════════════
var bool momUpState = true
var bool dadUpState = true
if mom > nz(mom[1], mom)
momUpState := true
else if mom < nz(mom[1], mom)
momUpState := false
if dad > nz(dad[1], dad)
dadUpState := true
else if dad < nz(dad[1], dad)
dadUpState := false
holdColor = colorMode == "On bar close" and not barstate.isconfirmed and bar_index > 0
momUpDisp = holdColor ? momUpState[1] : momUpState
dadUpDisp = holdColor ? dadUpState[1] : dadUpState
momCol = momUpDisp or not slopeColor ? momRiseCol : momFallCol
dadCol = dadUpDisp or not slopeColor ? dadRiseCol : dadFallCol
histCol = color.new(momUpDisp or not slopeColor ? histRiseCol : histFallCol, histTransp)
plot(showHist ? mom : na, "MOM histogram", color = histCol, style = plot.style_columns)
plot(showZero ? 0.0 : na, "Zero line", color = zeroCol, style = plot.style_line, linewidth = 1)
plot(showMom ? mom : na, "MOM", color = momCol, linewidth = momWidth)
plot(showDad ? dad : na, "DAD", color = dadCol, linewidth = dadWidth)
// ═══ Shared helpers ══════════════════════════════════════════════════════════
lblSize = lblSizeIn == "tiny" ? size.tiny : lblSizeIn == "small" ? size.small : lblSizeIn == "normal" ? size.normal : size.large
momRange = nz(ta.highest(mom, 100) - ta.lowest(mom, 100), 0)
off = (momRange > 0 ? momRange : math.max(math.abs(nz(mom)), 1.0)) * 0.06
drawText(bx, yv, txt, above, col) =>
label.new(bx, yv + (above ? off : -off), text = txt, xloc = xloc.bar_index, style = label.style_none, textcolor = col, size = lblSize)
// ═══ MOM peak / trough detection ═════════════════════════════════════════════
bool rawPeak = bar_index > confirmBars + 1
bool rawTrough = rawPeak
if rawPeak
float cand = mom[confirmBars]
if not (cand > mom[confirmBars + 1])
rawPeak := false
if not (cand < mom[confirmBars + 1])
rawTrough := false
for i = 0 to confirmBars - 1
if not (mom[i] < mom[i + 1])
rawPeak := false
if not (mom[i] > mom[i + 1])
rawTrough := false
// Stochastic %K (5, 2, 3) cycle filter
kFast = ta.sma(ta.stoch(close, high, low, 5), 2)
kCycleHi = kFast[1] > kFast[2] and kFast < kFast[1]
kCycleLo = kFast[1] < kFast[2] and kFast > kFast[1]
sinceKHi = ta.barssince(kCycleHi)
sinceKLo = ta.barssince(kCycleLo)
stochOkPk = not requireStoch or (not na(sinceKHi) and math.abs(sinceKHi + 1 - confirmBars) <= stochWin)
stochOkTr = not requireStoch or (not na(sinceKLo) and math.abs(sinceKLo + 1 - confirmBars) <= stochWin)
isPeak = rawPeak and stochOkPk
isTrough = rawTrough and stochOkTr
pivBar = bar_index - confirmBars
pivVal = mom[confirmBars]
// Price at the pivot bar, over a window centred on it
priceShift = int(math.max(confirmBars - (priceWin - 1) / 2, 0))
pivHigh = ta.highest(high, priceWin)[priceShift]
pivLow = ta.lowest(low, priceWin)[priceShift]
// ═══ Momentum wave counts ════════════════════════════════════════════════════
// Odd numbers are impulse waves, even numbers are retraces.
var int wDir = 0 // 1 = up count, -1 = down count, 0 = none yet
var int wNum = 0
var float lastOdd = na // value of the last odd-wave pivot
var label lastOddLbl = na
var float pendEven = na // the even-wave retrace still being tracked
var label pendEvenLbl = na
var float flipRef = na // break this level and the count flips direction
var float prevPeak = na
var float prevTrough = na
bool newWaveUp = false
bool newWaveDn = false
int printedNum = 0
if showCounts and isPeak
if wDir == 0
if not na(prevPeak) and pivVal > prevPeak
wDir := 1
wNum := 1
lastOdd := pivVal
flipRef := prevTrough
lastOddLbl := drawText(pivBar, pivVal, "1", true, upWaveCol)
newWaveUp := true
printedNum := 1
else if wDir == 1
// up count: peaks are the impulse waves
if pivVal > lastOdd
if na(pendEven)
// the same impulse ran higher — move the odd label to the new extreme
lastOdd := pivVal
label.delete(lastOddLbl)
lastOddLbl := drawText(pivBar, pivVal, str.tostring(wNum), true, upWaveCol)
else
wNum += 1
lastOdd := pivVal
flipRef := pendEven
pendEven := na
pendEvenLbl := na
lastOddLbl := drawText(pivBar, pivVal, str.tostring(wNum), true, upWaveCol)
newWaveUp := true
printedNum := wNum
else
// down count: peaks are the retraces; a peak above flipRef flips to up
if not na(flipRef) and pivVal > flipRef
wDir := 1
wNum := 1
lastOdd := pivVal
flipRef := prevTrough
pendEven := na
pendEvenLbl := na
lastOddLbl := drawText(pivBar, pivVal, "1", true, upWaveCol)
newWaveUp := true
printedNum := 1
else if wNum % 2 == 1
wNum += 1
pendEven := pivVal
pendEvenLbl := drawText(pivBar, pivVal, str.tostring(wNum), true, dnWaveCol)
newWaveDn := true
printedNum := wNum
else if not na(pendEven) and pivVal > pendEven
// highest peak between two counted odd waves — move the even label
pendEven := pivVal
label.delete(pendEvenLbl)
pendEvenLbl := drawText(pivBar, pivVal, str.tostring(wNum), true, dnWaveCol)
if showCounts and isTrough
if wDir == 0
if not na(prevTrough) and pivVal < prevTrough
wDir := -1
wNum := 1
lastOdd := pivVal
flipRef := prevPeak
lastOddLbl := drawText(pivBar, pivVal, "1", false, dnWaveCol)
newWaveDn := true
printedNum := 1
else if wDir == -1
// down count: troughs are the impulse waves
if pivVal < lastOdd
if na(pendEven)
lastOdd := pivVal
label.delete(lastOddLbl)
lastOddLbl := drawText(pivBar, pivVal, str.tostring(wNum), false, dnWaveCol)
else
wNum += 1
lastOdd := pivVal
flipRef := pendEven
pendEven := na
pendEvenLbl := na
lastOddLbl := drawText(pivBar, pivVal, str.tostring(wNum), false, dnWaveCol)
newWaveDn := true
printedNum := wNum
else
// up count: troughs are the retraces; a trough below flipRef flips to down
if not na(flipRef) and pivVal < flipRef
wDir := -1
wNum := 1
lastOdd := pivVal
flipRef := prevPeak
pendEven := na
pendEvenLbl := na
lastOddLbl := drawText(pivBar, pivVal, "1", false, dnWaveCol)
newWaveDn := true
printedNum := 1
else if wNum % 2 == 1
wNum += 1
pendEven := pivVal
pendEvenLbl := drawText(pivBar, pivVal, str.tostring(wNum), false, upWaveCol)
newWaveUp := true
printedNum := wNum
else if not na(pendEven) and pivVal < pendEven
// lowest trough between two counted odd waves — move the even label
pendEven := pivVal
label.delete(pendEvenLbl)
pendEvenLbl := drawText(pivBar, pivVal, str.tostring(wNum), false, upWaveCol)
// ═══ MOM divergence ══════════════════════════════════════════════════════════
var array<float> pkMom = array.new<float>()
var array<int> pkBar = array.new<int>()
var array<float> pkPrc = array.new<float>()
var array<float> trMom = array.new<float>()
var array<int> trBar = array.new<int>()
var array<float> trPrc = array.new<float>()
bool divBear = false
bool divBull = false
bool divSBear = false
bool divSBull = false
bool divHBear = false
bool divHBull = false
drawDiv(b1, v1, b2, v2, col, strong, txt, above) =>
line.new(b1, v1, b2, v2, xloc = xloc.bar_index, color = col, style = strong ? line.style_solid : line.style_dashed, width = strong ? 2 : 1)
if showDivLbl
drawText(b2, v2, txt, above, col)
if isPeak and array.size(pkMom) > 0
p1m = array.last(pkMom)
p1b = array.last(pkBar)
p1p = array.last(pkPrc)
gap = pivBar - p1b
if showDiv and gap >= divMinBars and gap <= divLookback
zeroOk = not reqBeyond0 or (pivVal > 0 and p1m > 0)
regular = pivHigh > p1p and pivVal < p1m // higher high in price, lower high in MOM
hidden = pivHigh < p1p and pivVal > p1m // lower high in price, higher high in MOM
bool strongOk = false
if array.size(trMom) >= 2
t2m = array.get(trMom, array.size(trMom) - 1)
t2b = array.get(trBar, array.size(trBar) - 1)
t2p = array.get(trPrc, array.size(trPrc) - 1)
t1m = array.get(trMom, array.size(trMom) - 2)
t1p = array.get(trPrc, array.size(trPrc) - 2)
if t2b > p1b and t2b < pivBar
strongOk := t2p > t1p and t2m < t1m // higher low in price, lower low in MOM
if zeroOk and regular and strongOk and showSBear
divSBear := true
drawDiv(p1b, p1m, pivBar, pivVal, sBearCol, true, "Strong Bear", true)
else if zeroOk and regular and showBear
divBear := true
drawDiv(p1b, p1m, pivBar, pivVal, bearCol, false, "Bear Div", true)
else if zeroOk and hidden and showHBear
divHBear := true
drawDiv(p1b, p1m, pivBar, pivVal, hBearCol, false, "H Bear", true)
if isTrough and array.size(trMom) > 0
q1m = array.last(trMom)
q1b = array.last(trBar)
q1p = array.last(trPrc)
gap = pivBar - q1b
if showDiv and gap >= divMinBars and gap <= divLookback
zeroOk = not reqBeyond0 or (pivVal < 0 and q1m < 0)
regular = pivLow < q1p and pivVal > q1m // lower low in price, higher low in MOM
hidden = pivLow > q1p and pivVal < q1m // higher low in price, lower low in MOM
bool strongOk = false
if array.size(pkMom) >= 2
s2m = array.get(pkMom, array.size(pkMom) - 1)
s2b = array.get(pkBar, array.size(pkBar) - 1)
s2p = array.get(pkPrc, array.size(pkPrc) - 1)
s1m = array.get(pkMom, array.size(pkMom) - 2)
s1p = array.get(pkPrc, array.size(pkPrc) - 2)
if s2b > q1b and s2b < pivBar
strongOk := s2p < s1p and s2m > s1m // lower high in price, higher high in MOM
if zeroOk and regular and strongOk and showSBull
divSBull := true
drawDiv(q1b, q1m, pivBar, pivVal, sBullCol, true, "Strong Bull", false)
else if zeroOk and regular and showBull
divBull := true
drawDiv(q1b, q1m, pivBar, pivVal, bullCol, false, "Bull Div", false)
else if zeroOk and hidden and showHBull
divHBull := true
drawDiv(q1b, q1m, pivBar, pivVal, hBullCol, false, "H Bull", false)
// Record the pivots (lists stay trimmed; drawings are capped by max_labels/lines_count)
if isPeak
array.push(pkMom, pivVal)
array.push(pkBar, pivBar)
array.push(pkPrc, pivHigh)
if array.size(pkMom) > 300
array.shift(pkMom)
array.shift(pkBar)
array.shift(pkPrc)
prevPeak := pivVal
if isTrough
array.push(trMom, pivVal)
array.push(trBar, pivBar)
array.push(trPrc, pivLow)
if array.size(trMom) > 300
array.shift(trMom)
array.shift(trBar)
array.shift(trPrc)
prevTrough := pivVal
// ═══ Status window — buy / sell state ═════════════════════════════════════════
// Both momenta up = buy state, both down = sell state, anything else = wait.
bothUp = momUpDisp and dadUpDisp
bothDown = not momUpDisp and not dadUpDisp
stateTxt = bothUp ? "BUY" : bothDown ? "SELL" : "WAIT"
stateCol = bothUp ? panelBuy : bothDown ? panelSell : panelWait
panelPosition = panelPos == "Top right" ? position.top_right : panelPos == "Top left" ? position.top_left : panelPos == "Bottom right" ? position.bottom_right : panelPos == "Bottom left" ? position.bottom_left : position.middle_right
panelTextSize = panelSize == "tiny" ? size.tiny : panelSize == "small" ? size.small : panelSize == "normal" ? size.normal : size.large
var table statusTbl = table.new(panelPosition, 1, 3, border_width = 1, border_color = color.new(color.gray, 60))
if showPanel and barstate.islast
table.cell(statusTbl, 0, 0, stateTxt, text_color = color.white, bgcolor = stateCol, text_size = panelTextSize)
table.cell(statusTbl, 0, 1, "MOM " + (momUpDisp ? "rising" : "falling"), text_color = momUpDisp ? panelBuy : panelSell, text_size = panelTextSize)
table.cell(statusTbl, 0, 2, "DAD " + (dadUpDisp ? "rising" : "falling"), text_color = dadUpDisp ? panelBuy : panelSell, text_size = panelTextSize)
// ═══ Alerts ══════════════════════════════════════════════════════════════════
dadTurnUp = dad > dad[1] and dad[1] <= dad[2]
dadTurnDn = dad < dad[1] and dad[1] >= dad[2]
alertcondition(dadTurnUp, "DAD turned up", "MacD + Divergence: DAD turned up")
alertcondition(dadTurnDn, "DAD turned down", "MacD + Divergence: DAD turned down")
alertcondition(isTrough, "MOM hooked up", "MacD + Divergence: MOM hooked up")
alertcondition(isPeak, "MOM hooked down", "MacD + Divergence: MOM hooked down")
alertcondition(newWaveUp, "New up-wave count", "MacD + Divergence: new up-wave count printed")
alertcondition(newWaveDn, "New down-wave count", "MacD + Divergence: new down-wave count printed")
alertcondition(divBear, "Regular bearish divergence", "MacD + Divergence: regular bearish divergence")
alertcondition(divBull, "Regular bullish divergence", "MacD + Divergence: regular bullish divergence")
alertcondition(divSBear, "Strong bearish divergence", "MacD + Divergence: strong bearish divergence")
alertcondition(divSBull, "Strong bullish divergence", "MacD + Divergence: strong bullish divergence")
alertcondition(divHBear, "Hidden bearish divergence", "MacD + Divergence: hidden bearish divergence")
alertcondition(divHBull, "Hidden bullish divergence", "MacD + Divergence: hidden bullish divergence")
// Dynamic message — fires only if you create an "alert() function calls" alert
if newWaveUp or newWaveDn
alert("MacD + Divergence: " + (newWaveUp ? "up" : "down") + " count, wave " + str.tostring(printedNum), alert.freq_once_per_bar)