MACD Pro [OrbitOne]

orbitonetv · study · 275 行 · 点赞 127 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © orbitonetv
//@version=6
indicator("MACD Pro [OrbitOne]", "MACD Pro [OrbitOne]", overlay = false, max_lines_count = 500, max_labels_count = 500)
 
// ════════ LANGUAGE ════════
lang = input.string("English", "Chart language", options = ["English", "Türkçe", "Español", "Português", "Deutsch", "Français", "Русский", "中文"], tooltip = "Language of the labels, dashboard and alert() messages on the chart.")
 
// ════════ MACD ════════
gM      = "MACD"
src     = input.source(close, "Source", group = gM)
fastLen = input.int(12, "Fast length", minval = 1, group = gM)
slowLen = input.int(26, "Slow length", minval = 1, group = gM)
sigLen  = input.int(9, "Signal length", minval = 1, group = gM)
oscType = input.string("EMA", "Oscillator MA type", options = ["EMA", "SMA", "WMA", "RMA"], group = gM)
sigType = input.string("EMA", "Signal MA type", options = ["EMA", "SMA", "WMA", "RMA"], group = gM)
tfIn    = input.timeframe("", "Timeframe", group = gM, tooltip = "Empty = chart timeframe. Choose a HIGHER timeframe to see its MACD on this chart. Higher-timeframe values use the last closed bar, so they do not repaint.")
confirm = input.bool(true, "Wait for bar close", group = gM, tooltip = "Cross and zero-line signals appear only on closed bars and never repaint.")
 
// ════════ DISPLAY ════════
gV       = "Display"
showLine = input.bool(true, "Show MACD and signal lines", group = gV)
lineCol  = input.bool(true, "Color MACD line by signal cross", group = gV, tooltip = "Green while MACD is above the signal line, red while below.")
showHist = input.bool(true, "Show histogram", group = gV)
hist4    = input.bool(true, "Histogram 4 colors", group = gV, tooltip = "Bright = momentum growing, light = momentum fading.")
showDots = input.bool(true, "Dots on signal crosses", group = gV)
bullCol  = input.color(#089981, "Bullish", inline = "c", group = gV)
bearCol  = input.color(#F23645, "Bearish", inline = "c", group = gV)
sigCol   = input.color(#FF9800, "Signal line", inline = "c", group = gV)
showBg   = input.bool(false, "Trend background", group = gV, tooltip = "Green background: MACD above zero and above signal. Red background: MACD below zero and below signal.")
colBars  = input.bool(false, "Color price bars by trend", group = gV)
 
// ════════ SIGNALS ════════
gS       = "Signals on price chart"
onPrice  = input.bool(true, "Show cross signals on price chart", group = gS)
xFilter  = input.string("Bullish below zero / bearish above zero", "Cross filter", options = ["All crosses", "Bullish below zero / bearish above zero"], group = gS, tooltip = "The second option keeps only crosses that start a new swing: bullish crosses while MACD is below zero and bearish crosses while it is above zero. Fewer, stronger signals.")
showZero = input.bool(false, "Show zero-line crosses", group = gS)
 
// ════════ DIVERGENCES ════════
gD      = "Divergences"
showDiv = input.bool(true, "Show divergences", group = gD)
divSrc  = input.string("Histogram", "Divergence source", options = ["Histogram", "MACD line"], group = gD)
lbL     = input.int(5, "Pivot lookback left", minval = 1, maxval = 50, group = gD)
lbR     = input.int(5, "Pivot lookback right", minval = 1, maxval = 50, group = gD, tooltip = "A pivot is confirmed after this many bars, so divergences appear with this delay and never repaint.")
minR    = input.int(5, "Min bars between pivots", minval = 1, group = gD)
maxR    = input.int(60, "Max bars between pivots", minval = 5, group = gD)
divOnPx = input.bool(true, "Draw divergence lines on price chart", group = gD)
 
// ════════ DASHBOARD ════════
gT     = "Dashboard"
showDb = input.bool(true, "Show dashboard", group = gT)
tf1    = input.timeframe("60", "Timeframe 1", group = gT)
tf2    = input.timeframe("240", "Timeframe 2", group = gT)
tf3    = input.timeframe("D", "Timeframe 3", group = gT)
dbPos  = input.string("Top right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gT)
dbSize = input.string("Tiny", "Size", options = ["Tiny", "Small", "Normal"], group = gT)
 
// ════════ TRANSLATIONS ════════
t(string en, string tr, string es, string pt, string de, string fr, string ru, string zh) =>
    switch lang
        "Türkçe"    => tr
        "Español"   => es
        "Português" => pt
        "Deutsch"   => de
        "Français"  => fr
        "Русский"   => ru
        "中文"       => zh
        => en
 
txtXUp     = "MACD ▲"
txtXDn     = "MACD ▼"
txtZUp     = t("ZERO ▲", "SIFIR ▲", "CERO ▲", "ZERO ▲", "NULL ▲", "ZÉRO ▲", "НОЛЬ ▲", "零轴 ▲")
txtZDn     = t("ZERO ▼", "SIFIR ▼", "CERO ▼", "ZERO ▼", "NULL ▼", "ZÉRO ▼", "НОЛЬ ▼", "零轴 ▼")
txtDivUp   = t("DIV ▲", "UYUMSUZ ▲", "DIV ▲", "DIV ▲", "DIV ▲", "DIV ▲", "ДИВ ▲", "背离 ▲")
txtDivDn   = t("DIV ▼", "UYUMSUZ ▼", "DIV ▼", "DIV ▼", "DIV ▼", "DIV ▼", "ДИВ ▼", "背离 ▼")
txtTrend   = t("Trend", "Trend", "Tendencia", "Tendência", "Trend", "Tendance", "Тренд", "趋势")
txtSBull   = t("▲▲ Strong bullish", "▲▲ Güçlü yükseliş", "▲▲ Alcista fuerte", "▲▲ Alta forte", "▲▲ Stark bullisch", "▲▲ Haussier fort", "▲▲ Сильный рост", "▲▲ 强势看涨")
txtBull    = t("▲ Bullish", "▲ Yükseliş", "▲ Alcista", "▲ Alta", "▲ Bullisch", "▲ Haussier", "▲ Рост", "▲ 看涨")
txtSBear   = t("▼▼ Strong bearish", "▼▼ Güçlü düşüş", "▼▼ Bajista fuerte", "▼▼ Baixa forte", "▼▼ Stark bärisch", "▼▼ Baissier fort", "▼▼ Сильное падение", "▼▼ 强势看跌")
txtBear    = t("▼ Bearish", "▼ Düşüş", "▼ Bajista", "▼ Baixa", "▼ Bärisch", "▼ Baissier", "▼ Падение", "▼ 看跌")
txtZero    = t("MACD vs zero", "MACD / sıfır", "MACD vs cero", "MACD vs zero", "MACD vs Null", "MACD vs zéro", "MACD и ноль", "MACD 与零轴")
txtAbove   = t("Above zero", "Sıfırın üstünde", "Sobre cero", "Acima de zero", "Über Null", "Au-dessus de zéro", "Выше нуля", "零轴上方")
txtBelow   = t("Below zero", "Sıfırın altında", "Bajo cero", "Abaixo de zero", "Unter Null", "Sous zéro", "Ниже нуля", "零轴下方")
txtHist    = t("Histogram", "Histogram", "Histograma", "Histograma", "Histogramm", "Histogramme", "Гистограмма", "柱状图")
txtGrow    = t("Momentum growing", "Momentum artıyor", "Impulso creciente", "Momento crescente", "Momentum steigt", "Momentum en hausse", "Импульс растёт", "动能增强")
txtFade    = t("Momentum fading", "Momentum azalıyor", "Impulso débil", "Momento enfraquecendo", "Momentum lässt nach", "Momentum en baisse", "Импульс слабеет", "动能减弱")
txtLastX   = t("Last cross", "Son kesişim", "Último cruce", "Último cruzamento", "Letzter Kreuzung", "Dernier croisement", "Последнее пересечение", "最近交叉")
txtLastD   = t("Last divergence", "Son uyumsuzluk", "Última divergencia", "Última divergência", "Letzte Divergenz", "Dernière divergence", "Последняя дивергенция", "最近背离")
txtAgo     = t("bars ago", "mum önce", "velas atrás", "velas atrás", "Kerzen her", "bougies", "свечей назад", "K线前")
txtBullDiv = t("Bullish divergence", "Pozitif uyumsuzluk", "Divergencia alcista", "Divergência de alta", "Bullische Divergenz", "Divergence haussière", "Бычья дивергенция", "看涨背离")
txtBearDiv = t("Bearish divergence", "Negatif uyumsuzluk", "Divergencia bajista", "Divergência de baixa", "Bärische Divergenz", "Divergence baissière", "Медвежья дивергенция", "看跌背离")
txtXBull   = t("Bullish cross", "Yukarı kesişim", "Cruce alcista", "Cruzamento de alta", "Bullische Kreuzung", "Croisement haussier", "Бычье пересечение", "金叉")
txtXBear   = t("Bearish cross", "Aşağı kesişim", "Cruce bajista", "Cruzamento de baixa", "Bärische Kreuzung", "Croisement baissier", "Медвежье пересечение", "死叉")
 
// ════════ CALCULATION ════════
ma(float s, int l, string typ) =>
    switch typ
        "SMA" => ta.sma(s, l)
        "WMA" => ta.wma(s, l)
        "RMA" => ta.rma(s, l)
        => ta.ema(s, l)
 
f_now() =>
    float m = ma(src, fastLen, oscType) - ma(src, slowLen, oscType)
    float s = ma(m, sigLen, sigType)
    [m, s, m - s]
 
// last closed bar of another timeframe (no repainting)
f_conf() =>
    [m, s, h] = f_now()
    [m[1], s[1], h[1], h[2]]
 
[m0, s0, h0] = f_now()
useTf = tfIn != "" and timeframe.in_seconds(tfIn) > timeframe.in_seconds()
[mT, sT, hT, hTp] = request.security(syminfo.tickerid, useTf ? tfIn : timeframe.period, f_conf(), lookahead = barmerge.lookahead_on)
 
macdV = useTf ? mT : m0
sigV  = useTf ? sT : s0
histV = useTf ? hT : h0
 
okBar   = not confirm or barstate.isconfirmed
xUpRaw  = ta.crossover(macdV, sigV)
xDnRaw  = ta.crossunder(macdV, sigV)
xUp     = xUpRaw and okBar
xDn     = xDnRaw and okBar
strongF = xFilter != "All crosses"
sigUp   = xUp and (not strongF or macdV < 0)
sigDn   = xDn and (not strongF or macdV > 0)
zUp     = ta.crossover(macdV, 0) and okBar
zDn     = ta.crossunder(macdV, 0) and okBar
 
growing = math.abs(histV) >= math.abs(nz(histV[1]))
 
// trend state: 2 strong bull, 1 bull, -1 bear, -2 strong bear
f_state(float m, float s) =>
    m >= s ? (m > 0 ? 2 : 1) : (m < 0 ? -2 : -1)
state = f_state(macdV, sigV)
 
var int lastX  = 0
var int lastXb = na
if xUp or xDn
    lastX  := xUp ? 1 : -1
    lastXb := bar_index
 
// ════════ PLOTS ════════
histCol = histV >= 0 ? (not hist4 or histV >= nz(histV[1]) ? bullCol : color.new(bullCol, 60)) : (not hist4 or histV <= nz(histV[1]) ? bearCol : color.new(bearCol, 60))
plot(showHist ? histV : na, "Histogram", color = histCol, style = plot.style_columns)
hline(0, "Zero line", color = color.new(color.gray, 50), linestyle = hline.style_dotted)
plot(showLine ? macdV : na, "MACD", color = lineCol ? (macdV >= sigV ? bullCol : bearCol) : #2962FF, linewidth = 2)
plot(showLine ? sigV : na, "Signal", color = sigCol, linewidth = 1)
plot(showDots and showLine and (xUp or xDn) ? sigV : na, "Cross dots", color = xUp ? bullCol : bearCol, style = plot.style_circles, linewidth = 4, display = display.all - display.status_line)
 
bgcolor(showBg and state == 2 ? color.new(bullCol, 90) : showBg and state == -2 ? color.new(bearCol, 90) : na, title = "Trend background")
barcolor(colBars ? (state == 2 ? bullCol : state == 1 ? color.new(bullCol, 50) : state == -2 ? bearCol : color.new(bearCol, 50)) : na, title = "Bar color")
 
if onPrice and sigUp
    label.new(bar_index, low, txtXUp, yloc = yloc.belowbar, style = label.style_label_up, color = bullCol, textcolor = color.white, size = size.small, force_overlay = true)
if onPrice and sigDn
    label.new(bar_index, high, txtXDn, yloc = yloc.abovebar, style = label.style_label_down, color = bearCol, textcolor = color.white, size = size.small, force_overlay = true)
if showZero and zUp
    label.new(bar_index, low, txtZUp, yloc = yloc.belowbar, style = label.style_label_up, color = color.new(bullCol, 40), textcolor = color.white, size = size.tiny, force_overlay = true)
if showZero and zDn
    label.new(bar_index, high, txtZDn, yloc = yloc.abovebar, style = label.style_label_down, color = color.new(bearCol, 40), textcolor = color.white, size = size.tiny, force_overlay = true)
 
// ════════ DIVERGENCES ════════
osc = divSrc == "Histogram" ? histV : macdV
pl  = ta.pivotlow(osc, lbL, lbR)
ph  = ta.pivothigh(osc, lbL, lbR)
 
var float plOsc = na
var float plPx  = na
var int   plBar = na
var float phOsc = na
var float phPx  = na
var int   phBar = na
var int   lastD  = 0
var int   lastDb = na
bullDiv = false
bearDiv = false
 
if not na(pl)
    int   b  = bar_index - lbR
    float px = low[lbR]
    if not na(plBar) and b - plBar >= minR and b - plBar <= maxR and pl > plOsc and px < plPx and pl < 0
        bullDiv := true
        if showDiv
            line.new(plBar, plOsc, b, pl, color = bullCol, width = 2)
            label.new(b, pl, txtDivUp, style = label.style_label_up, color = color.new(bullCol, 20), textcolor = color.white, size = size.tiny)
            if divOnPx
                line.new(plBar, plPx, b, px, color = bullCol, width = 2, style = line.style_dashed, force_overlay = true)
    plOsc := pl
    plPx  := px
    plBar := b
 
if not na(ph)
    int   b  = bar_index - lbR
    float px = high[lbR]
    if not na(phBar) and b - phBar >= minR and b - phBar <= maxR and ph < phOsc and px > phPx and ph > 0
        bearDiv := true
        if showDiv
            line.new(phBar, phOsc, b, ph, color = bearCol, width = 2)
            label.new(b, ph, txtDivDn, style = label.style_label_down, color = color.new(bearCol, 20), textcolor = color.white, size = size.tiny)
            if divOnPx
                line.new(phBar, phPx, b, px, color = bearCol, width = 2, style = line.style_dashed, force_overlay = true)
    phOsc := ph
    phPx  := px
    phBar := b
 
if bullDiv or bearDiv
    lastD  := bullDiv ? 1 : -1
    lastDb := bar_index - lbR
 
// ════════ MULTI-TIMEFRAME ════════
[a1, b1, c1, d1] = request.security(syminfo.tickerid, tf1, f_conf(), lookahead = barmerge.lookahead_on)
[a2, b2, c2, d2] = request.security(syminfo.tickerid, tf2, f_conf(), lookahead = barmerge.lookahead_on)
[a3, b3, c3, d3] = request.security(syminfo.tickerid, tf3, f_conf(), lookahead = barmerge.lookahead_on)
 
// ════════ DASHBOARD ════════
var table db = table.new(dbPos == "Top right" ? position.top_right : dbPos == "Bottom right" ? position.bottom_right : dbPos == "Top left" ? position.top_left : position.bottom_left, 2, 9, border_width = 1, force_overlay = true)
tSize = dbSize == "Tiny" ? size.tiny : dbSize == "Normal" ? size.normal : size.small
 
f_tf(string tf) =>
    tf == "D" or tf == "1D" ? "1D" : tf == "W" or tf == "1W" ? "1W" : tf == "M" or tf == "1M" ? "1M" : str.endswith(tf, "S") ? tf : timeframe.in_seconds(tf) >= 3600 ? str.tostring(timeframe.in_seconds(tf) / 3600) + "H" : tf + "m"
 
stTxt(int s) =>
    s == 2 ? txtSBull : s == 1 ? txtBull : s == -2 ? txtSBear : txtBear
stCol(int s) =>
    s == 2 ? color.new(bullCol, 10) : s == 1 ? color.new(bullCol, 50) : s == -2 ? color.new(bearCol, 10) : color.new(bearCol, 50)
 
f_row(int r, string k, string v, color c) =>
    table.cell(db, 0, r, k, bgcolor = color.new(color.gray, 35), text_color = color.white, text_size = tSize)
    table.cell(db, 1, r, v, bgcolor = c, text_color = color.white, text_size = tSize)
 
f_mtf(int r, string tf, float m, float s, float h, float hp) =>
    if na(m) or na(s)
        f_row(r, f_tf(tf), "—", color.new(color.gray, 20))
    else
        int st = f_state(m, s)
        string arrow = math.abs(h) >= math.abs(nz(hp)) ? " ↑" : " ↓"
        f_row(r, f_tf(tf), stTxt(st) + arrow, stCol(st))
 
if showDb and barstate.isfirst
    table.merge_cells(db, 0, 0, 1, 0)
 
if showDb and barstate.islast
    color nc = color.new(color.gray, 20)
    table.cell(db, 0, 0, "MACD Pro · " + str.tostring(fastLen) + "/" + str.tostring(slowLen) + "/" + str.tostring(sigLen) + " · OrbitOne", bgcolor = color.new(color.black, 30), text_color = color.white, text_size = tSize)
    f_row(1, txtTrend, stTxt(state), stCol(state))
    f_row(2, txtZero, macdV >= 0 ? txtAbove : txtBelow, macdV >= 0 ? color.new(bullCol, 30) : color.new(bearCol, 30))
    f_row(3, txtHist, growing ? txtGrow : txtFade, histV >= 0 ? color.new(bullCol, growing ? 20 : 60) : color.new(bearCol, growing ? 20 : 60))
    f_row(4, txtLastX, lastX == 0 ? "—" : (lastX == 1 ? txtXBull : txtXBear) + " · " + str.tostring(bar_index - lastXb) + " " + txtAgo, lastX == 1 ? bullCol : lastX == -1 ? bearCol : nc)
    f_row(5, txtLastD, lastD == 0 ? "—" : (lastD == 1 ? txtBullDiv : txtBearDiv) + " · " + str.tostring(bar_index - lastDb) + " " + txtAgo, lastD == 1 ? bullCol : lastD == -1 ? bearCol : nc)
    f_mtf(6, tf1, a1, b1, c1, d1)
    f_mtf(7, tf2, a2, b2, c2, d2)
    f_mtf(8, tf3, a3, b3, c3, d3)
 
// ════════ ALERTS ════════
alertcondition(sigUp, "Bullish cross", "MACD bullish cross | {{ticker}} | {{interval}} | {{close}}")
alertcondition(sigDn, "Bearish cross", "MACD bearish cross | {{ticker}} | {{interval}} | {{close}}")
alertcondition(zUp, "Zero line cross up", "MACD crossed above zero | {{ticker}} | {{interval}} | {{close}}")
alertcondition(zDn, "Zero line cross down", "MACD crossed below zero | {{ticker}} | {{interval}} | {{close}}")
alertcondition(bullDiv, "Bullish divergence", "MACD bullish divergence | {{ticker}} | {{interval}} | {{close}}")
alertcondition(bearDiv, "Bearish divergence", "MACD bearish divergence | {{ticker}} | {{interval}} | {{close}}")
alertcondition(sigUp or sigDn or bullDiv or bearDiv, "Any signal", "MACD Pro signal | {{ticker}} | {{interval}} | {{close}}")
 
// alert() messages follow the chart language. Create the alert with "Any alert() function call".
freq = confirm ? alert.freq_once_per_bar_close : alert.freq_once_per_bar
if sigUp
    alert("MACD Pro " + txtXBull + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)
if sigDn
    alert("MACD Pro " + txtXBear + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)
if bullDiv
    alert("MACD Pro " + txtBullDiv + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if bearDiv
    alert("MACD Pro " + txtBearDiv + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)

← 返回列表