MACD Master [SimpleAlgo]

SimpleAlgoAI · study · 527 行 · 点赞 77 · TradingView 原页

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

Pine Script

//@version=6
// MACD Master
//
// The classic MACD as a toolkit: signals, the price of the next signal before it happens, divergences, a clock for the
// next cross, coloured candles and a panel.
//
// The pane is the MACD itself, calculated the standard way: an EMA of the close over the fast length minus one over the
// slow length, an EMA of that difference as the signal line, and the gap between the two as the histogram. The histogram
// has four states: up and building, up and fading, down and building, down and fading. The candles on the chart take the
// same four colours.
//
// Signals. Not every cross is a signal. A signal is a cross that turns the MACD back toward its zero line from outside
// the grey band: up through the signal line from below the band is marked Oversold, down through it from above the band
// is marked Overbought. The labels can say Buy and Sell instead, or be plain dots. When the same signal comes again before
// the opposite one, it is marked with a dot instead of repeating the word. Every other cross is drawn as a hollow ring in
// the pane. The panel counts, on this chart, how often each kind was undone by the opposite cross within five bars.
//
// The dashed line on the price chart is the close at which the MACD would meet its signal line. It is not an estimate.
// An EMA is a fixed blend of the newest close and its own last value, so the close that puts the histogram at exactly
// zero can be solved from the last candle's numbers. While a candle is forming, it is the close that decides that candle.
// Once the candle has closed, it is the close that decides the next one. It is named "Next signal" when the cross it
// stands for would be a signal.
//
// Divergences are measured wave to wave. Every stretch the MACD spends under its signal line has one lowest MACD value
// and one lowest low. When the stretch ends they are compared with the stretch before. The lines are drawn on the candle
// that ends the stretch and are never redrawn.
//
// The clock carries both lines forward as if every coming candle closed at the latest price, to the bar where they meet.
//
// A signal says that momentum has turned. It does not say where price goes next.
 
indicator("MACD Master [SimpleAlgo]", "MACD Master [SimpleAlgo]", overlay = false, explicit_plot_zorder = true, max_lines_count = 500, max_labels_count = 500)
 
// ───────────────────────── Settings ─────────────────────────
 
grpM = "MACD"
fastIn = input.int(12, "Fast length", minval = 2, maxval = 500, group = grpM)
slowIn = input.int(26, "Slow length", minval = 3, maxval = 1000, group = grpM)
sigIn  = input.int(9, "Signal length", minval = 2, maxval = 500, group = grpM, tooltip = "The standard MACD. The MACD line is an EMA of the close over the fast length minus an EMA of the close over the slow length. The signal line is an EMA of the MACD line. The histogram is the gap between the two. 12, 26 and 9 are the classic settings.")
 
grpS = "Signals"
sigOn    = input.bool(true, "Signals on the chart", group = grpS, inline = "s")
sigStyle = input.string("Overbought and Oversold", "", options = ["Overbought and Oversold", "Buy and Sell", "Dots"], group = grpS, inline = "s", display = display.none, tooltip = "A signal is a MACD cross that turns the MACD back toward its zero line from outside the grey band. Up signal: the MACD crosses up through its signal line while the signal line is below the band. Down signal: it crosses down while the signal line is above the band. A signal is marked once its candle has closed and is never moved or removed. The list picks what the labels say: Oversold and Overbought, Buy and Sell, or dots with no words. When the same signal comes again before the opposite one, it is marked with a dot instead of repeating the word.")
bandIn   = input.float(0.5, "Band width", minval = 0.0, maxval = 5.0, step = 0.1, group = grpS, display = display.none, tooltip = "The width of the grey band around the zero line, in ATRs on each side. A cross inside the band is not a signal. A wider band gives fewer signals, further from zero. 0 removes the band: every cross toward the zero line is then a signal.")
divIn    = input.bool(true, "Divergences", group = grpS, tooltip = "Measured wave to wave. Every stretch the MACD spends under its signal line has one lowest MACD value and one lowest low. When the stretch ends they are compared with the stretch before: a lower low in price with a higher low on the MACD is a bullish divergence. A higher high in price with a lower high on the MACD is a bearish one. The lines are drawn on the candle that ends the stretch, on the chart and in the pane, and are never redrawn.")
 
grpT = "Tools"
lineIn   = input.bool(true, "Next cross price", group = grpT, tooltip = "The close at which the MACD would meet its signal line, drawn on the price chart. It is solved from the MACD's own formula, so it is exact. A close on one side of it leaves the MACD above its signal line, a close on the other side leaves it below. While a candle is forming it is the price for that candle. Once the candle has closed it is the price for the next one, so it moves every candle. It reads Next signal when that cross would be a signal.")
clockIn  = input.bool(true, "Cross clock", group = grpT, tooltip = "Both lines carried forward in the pane as if every coming candle closed at the latest price, to the bar where they would meet. It is worked out from the MACD's own formula, so it is exact for that case. It answers how long the cross takes if price goes nowhere.")
candleIn = input.bool(true, "Colour the candles", group = grpT, tooltip = "The candles take the four states of the histogram. Bright up colour: the MACD is above its signal line and the gap is growing. Dim up colour: above, and the gap is shrinking. Bright down colour: below its signal line and the gap is growing. Dim down colour: below, and the gap is shrinking.")
 
grpL = "Look"
glowIn    = input.bool(true, "Glow under the MACD line", group = grpL)
themeIn   = input.string("Mint and Pink", "Colours", options = ["Mint and Pink", "Ice", "Neon", "Custom"], group = grpL, display = display.none)
cUpIn     = input.color(#00FFA3, "", group = grpL, inline = "col")
cDnIn     = input.color(#FF3D71, "", group = grpL, inline = "col")
sizeIn    = input.string("Normal", "Text size", options = ["Small", "Normal", "Large"], group = grpL, display = display.none)
showPanel = input.bool(true, "Panel", group = grpL, inline = "p")
panelPos  = input.string("Auto", "", options = ["Auto", "Top left", "Top right", "Bottom left", "Bottom right"], group = grpL, inline = "p", display = display.none, tooltip = "Auto keeps the panel in the top right corner of the price chart and moves it to the bottom right corner while price is at the top of the screen.")
 
[colUp, colDn] = switch themeIn
    "Mint and Pink" => [#00FFA3, #FF3D71]
    "Ice"           => [#7DD3FC, #FFFFFF]
    "Neon"          => [#FFFFFF, #D946EF]
    => [cUpIn, cDnIn]
color colPanel = #262B38
color colGrey  = #8B90A0
// the two fading states are the same two colours, half way to the chart's background
color colUpDim = color.from_gradient(50, 0, 100, chart.bg_color, colUp)
color colDnDim = color.from_gradient(50, 0, 100, chart.bg_color, colDn)
 
// what the two signals are called, on the labels, in the panel and on the cross price
bool   lblOn  = sigStyle != "Dots"
string nameUp = sigStyle == "Buy and Sell" ? "Buy" : sigStyle == "Dots" ? "Up" : "Oversold"
string nameDn = sigStyle == "Buy and Sell" ? "Sell" : sigStyle == "Dots" ? "Down" : "Overbought"
 
// the words on a signal label: dark on a light colour, white on a dark one
inkOn(color c) =>
    (0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) > 150 ? #0F0B16 : #FFFFFF
 
// fixed rules
int flipBars = 5            // a cross was undone when the MACD crossed its signal line the other way within this many bars
int minCount = 20           // crosses of each kind the chart needs before its record is shown
int maxAhead = 20           // the clock looks this many bars ahead
 
// ───────────────────────── The MACD ─────────────────────────
 
// the fast length is the shorter of the two, whichever way round they are typed in
int fastLen = math.min(fastIn, slowIn)
int slowLen = fastIn == slowIn ? slowIn + 1 : math.max(fastIn, slowIn)
 
float fast = ta.ema(close, fastLen)
float slow = ta.ema(close, slowLen)
float macd = fast - slow
float sig  = ta.ema(macd, sigIn)
float hist = macd - sig
 
// the four states of the histogram. 0: up and building, 1: up and fading, 2: down and building, 3: down and fading
float histPrev = hist[1]
float histWas  = nz(histPrev, hist)
int   st       = hist > 0 ? (hist >= histWas ? 0 : 1) : (hist <= histWas ? 2 : 3)
var int stRun  = 0
stRun := st == st[1] ? stRun + 1 : 1
 
// which side of zero the MACD line is on, and for how long
bool above      = macd > 0
var int sideRun = 0
sideRun := above == above[1] ? sideRun + 1 : 1
 
// the band: this many ATRs on each side of the zero line
float atrNow   = ta.atr(slowLen)
float band     = bandIn * atrNow
float sigPrev  = sig[1]
float bandPrev = band[1]
 
// ───────────────────────── The cross price ─────────────────────────
 
// An EMA is a blend: new value = a x close + (1 - a) x old value, with a = 2 / (length + 1). So on the next candle
//   MACD   = (aF - aS) x close + (1 - aF) x fast - (1 - aS) x slow
//   signal = aG x MACD + (1 - aG) x signal now
// and the histogram, MACD minus signal, is zero exactly when the MACD equals the signal line as it stands now.
// Solving that for the close gives the price below. A close above it leaves the MACD above its signal line, a close below it leaves it below
float aF = 2.0 / (fastLen + 1)
float aS = 2.0 / (slowLen + 1)
float aG = 2.0 / (sigIn + 1)
float crossNext = (sig - (1 - aF) * fast + (1 - aS) * slow) / (aF - aS)
float crossPrev = crossNext[1]
 
// On a candle that is still forming, the price that decides it is the one solved from the last closed candle.
// Once a candle has closed, the price shown is the one that decides the next candle
bool  live    = not barstate.isconfirmed
float crossPx = live ? crossPrev : crossNext
float histRef = live ? histPrev : hist
bool  refUp   = histRef > 0
// a price that cannot go below zero cannot reach a cross price that is below zero
bool  crossOk = not na(crossPx) and (crossPx > 0 or close <= 0)
// price can already be on the far side of it: then the MACD crosses unless price closes back
bool  beyond  = crossOk and (refUp ? close < crossPx : close > crossPx)
// would that cross be a signal? The rule looks at where the signal line stood on the candle before the cross,
// so the answer is known before the candle closes
float sigRef  = live ? sigPrev : sig
float bandRef = live ? bandPrev : band
bool  nextSig = refUp ? sigRef > bandRef : sigRef < -bandRef
 
// ───────────────────────── Crosses, signals and their record ─────────────────────────
 
bool xUp  = hist > 0 and histPrev <= 0
bool xDn  = hist < 0 and histPrev >= 0
// a cross counts once its candle has closed
bool xNow = (xUp or xDn) and barstate.isconfirmed and not na(band)
 
// a signal is a cross that turns the MACD back toward zero from outside the band:
// up while the signal line was below the band on the candle before, down while it was above it
bool buyNow  = xNow and xUp and sigPrev < -bandPrev
bool sellNow = xNow and xDn and sigPrev > bandPrev
bool sigNow  = buyNow or sellNow
 
// a run: the same signal again with no opposite signal in between. On the chart only the first of a run is written out
var int runSide   = 0
bool    repeatNow = sigNow and runSide == (buyNow ? 1 : -1)
if sigNow
    runSide := buyNow ? 1 : -1
 
var int nSig     = 0        // signals that have had their five bars
var int fSig     = 0        // of those, the ones undone by the opposite cross
var int nOth     = 0        // every other cross that has had its five bars
var int fOth     = 0        // of those, the ones undone
var int pendKind = 0        // the last cross while it is still inside its five bars. 1: a signal, 2: another cross, 0: none
var int pendBar  = 0
 
if xNow
    // a new cross while the last one was still inside its five bars: the last one was undone
    if pendKind == 1
        nSig += 1
        fSig += 1
    else if pendKind == 2
        nOth += 1
        fOth += 1
    // the first candles are left out of the record, the averages are still settling there
    pendKind := bar_index >= slowLen * 4 ? (sigNow ? 1 : 2) : 0
    pendBar  := bar_index
// five bars on and still on the same side: the cross held
if not xNow and barstate.isconfirmed and pendKind != 0 and bar_index - pendBar >= flipBars
    if pendKind == 1
        nSig += 1
    else
        nOth += 1
    pendKind := 0
 
bool  recOk = nSig >= minCount and nOth >= minCount
float pSig  = nSig > 0 ? 100.0 * fSig / nSig : na
float pOth  = nOth > 0 ? 100.0 * fOth / nOth : na
 
// ───────────────────────── Divergences ─────────────────────────
 
// the wave under way below the signal line: its lowest MACD value and its lowest low, and the bar of each
var float dnMacd     = na
var int   dnMacdBar  = na
var float dnLow      = na
var int   dnLowBar   = na
// the same for the wave before it
var float pDnMacd    = na
var int   pDnMacdBar = na
var float pDnLow     = na
var int   pDnLowBar  = na
// the wave under way above the signal line: its highest MACD value and its highest high
var float upMacd     = na
var int   upMacdBar  = na
var float upHigh     = na
var int   upHighBar  = na
var float pUpMacd    = na
var int   pUpMacdBar = na
var float pUpHigh    = na
var int   pUpHighBar = na
 
bool bullDiv = false
bool bearDiv = false
 
// a cross up ends the wave below the signal line: price lower than the wave before it, the MACD higher
if xNow and xUp and not na(dnMacd)
    bullDiv := not na(pDnMacd) and dnLow < pDnLow and dnMacd > pDnMacd
    if bullDiv and divIn
        line.new(pDnMacdBar, pDnMacd, dnMacdBar, dnMacd, color = color.new(colUp, 82), width = 5)
        line.new(pDnMacdBar, pDnMacd, dnMacdBar, dnMacd, color = colUp, width = 2)
        line.new(pDnLowBar, pDnLow, dnLowBar, dnLow, color = color.new(colUp, 82), width = 5, force_overlay = true)
        line.new(pDnLowBar, pDnLow, dnLowBar, dnLow, color = colUp, width = 2, force_overlay = true)
    pDnMacd    := dnMacd
    pDnMacdBar := dnMacdBar
    pDnLow     := dnLow
    pDnLowBar  := dnLowBar
    dnMacd     := na
    dnMacdBar  := na
    dnLow      := na
    dnLowBar   := na
 
// a cross down ends the wave above the signal line: price higher than the wave before it, the MACD lower
if xNow and xDn and not na(upMacd)
    bearDiv := not na(pUpMacd) and upHigh > pUpHigh and upMacd < pUpMacd
    if bearDiv and divIn
        line.new(pUpMacdBar, pUpMacd, upMacdBar, upMacd, color = color.new(colDn, 82), width = 5)
        line.new(pUpMacdBar, pUpMacd, upMacdBar, upMacd, color = colDn, width = 2)
        line.new(pUpHighBar, pUpHigh, upHighBar, upHigh, color = color.new(colDn, 82), width = 5, force_overlay = true)
        line.new(pUpHighBar, pUpHigh, upHighBar, upHigh, color = colDn, width = 2, force_overlay = true)
    pUpMacd    := upMacd
    pUpMacdBar := upMacdBar
    pUpHigh    := upHigh
    pUpHighBar := upHighBar
    upMacd     := na
    upMacdBar  := na
    upHigh     := na
    upHighBar  := na
 
// the closed candle joins the wave it belongs to
if barstate.isconfirmed and not na(hist)
    if hist < 0
        if na(dnMacd) or macd < dnMacd
            dnMacd    := macd
            dnMacdBar := bar_index
        if na(dnLow) or low < dnLow
            dnLow    := low
            dnLowBar := bar_index
    if hist > 0
        if na(upMacd) or macd > upMacd
            upMacd    := macd
            upMacdBar := bar_index
        if na(upHigh) or high > upHigh
            upHigh    := high
            upHighBar := bar_index
 
// the last signal, for the panel
var int  lastSigBar = na
var bool lastSigUp  = false
var bool lastSigDiv = false
if sigNow
    lastSigBar := bar_index
    lastSigUp  := buyNow
    lastSigDiv := bullDiv or bearDiv
 
// ───────────────────────── The pane ─────────────────────────
// Drawn from the back to the front: the band, the zero line, the glow, the histogram, the two lines, the crosses
 
color stCol   = st == 0 ? colUp : st == 1 ? colUpDim : st == 2 ? colDn : colDnDim
color sideCol = hist > 0 ? colUp : colDn
 
float bandShow = bandIn > 0 ? band : na
bandTop = plot(bandShow, "Band, top", color = color.new(colGrey, 72), editable = false, display = display.pane)
bandBot = plot(-bandShow, "Band, bottom", color = color.new(colGrey, 72), editable = false, display = display.pane)
fill(bandTop, bandBot, color = color.new(colGrey, 91), title = "Band", editable = false)
hline(0, "Zero line", color = color.new(colGrey, 50), linestyle = hline.style_solid, editable = false)
 
// the glow: the space between the MACD line and the zero line, filled in the line's colour at the line and clear at zero
zeroPlot  = plot(0, "Zero, for the glow", color = na, editable = false, display = display.pane)
macdGhost = plot(macd, "MACD, for the glow", color = na, editable = false, display = display.pane)
color glowCol  = color.new(sideCol, glowIn ? 70 : 100)
color clearCol = color.new(sideCol, 100)
fill(macdGhost, zeroPlot, math.max(macd, 0), math.min(macd, 0), macd > 0 ? glowCol : clearCol, macd > 0 ? clearCol : glowCol, title = "Glow")
 
// the histogram is lit at its tip and fades towards the zero line: four columns for every bar, the shorter ones dimmer and drawn on top
plot(hist, "Histogram", color = color.from_gradient(78, 0, 100, chart.bg_color, stCol), style = plot.style_columns)
plot(hist * 0.75, "Histogram, three quarters", color = color.from_gradient(52, 0, 100, chart.bg_color, stCol), style = plot.style_columns, editable = false, display = display.pane)
plot(hist * 0.50, "Histogram, half", color = color.from_gradient(34, 0, 100, chart.bg_color, stCol), style = plot.style_columns, editable = false, display = display.pane)
plot(hist * 0.25, "Histogram, quarter", color = color.from_gradient(20, 0, 100, chart.bg_color, stCol), style = plot.style_columns, editable = false, display = display.pane)
 
// the signal line, then the MACD line in the colour of the side it is on, with the gap between them softly filled
sigPlot  = plot(sig, "Signal", color = color.new(chart.fg_color, 50), linewidth = 1)
plot(macd, "MACD, glow", color = color.new(sideCol, 85), linewidth = 6, editable = false, display = display.pane)
macdPlot = plot(macd, "MACD", color = sideCol, linewidth = 2)
fill(macdPlot, sigPlot, color = color.new(sideCol, 90), title = "MACD to signal", editable = false)
 
// crosses: a solid dot for a signal, a hollow ring for every other cross
bool  ringNow = xNow and not sigNow
color dotCol  = xUp ? colUp : colDn
plot(sigNow ? macd : na, "Signal cross, glow", color = color.new(dotCol, 80), style = plot.style_circles, linewidth = 6, editable = false, display = display.pane)
plot(sigNow ? macd : na, "Signal cross", color = dotCol, style = plot.style_circles, linewidth = 3, editable = false, display = display.pane)
plot(ringNow ? macd : na, "Other cross", color = color.new(chart.fg_color, 52), style = plot.style_circles, linewidth = 4, editable = false, display = display.pane)
plot(ringNow ? macd : na, "Other cross, centre", color = chart.bg_color, style = plot.style_circles, linewidth = 2, editable = false, display = display.pane)
 
// ───────────────────────── The price chart ─────────────────────────
 
// the candles in the four states of the histogram
barcolor(candleIn and not na(hist) ? stCol : na, title = "Candle colours", editable = false)
 
// the signals. Labels: the up signal under its candle, the down signal over it
sigSize = sizeIn == "Small" ? size.tiny : sizeIn == "Large" ? size.normal : size.small
if sigOn and lblOn and buyNow and not repeatNow
    label.new(bar_index, low, nameUp, yloc = yloc.belowbar, color = colUp, style = label.style_label_up, textcolor = inkOn(colUp), size = sigSize, tooltip = nameUp + " signal: the MACD crossed up through its signal line from below the band." + (bullDiv ? " With a bullish divergence." : ""), force_overlay = true)
if sigOn and lblOn and sellNow and not repeatNow
    label.new(bar_index, high, nameDn, yloc = yloc.abovebar, color = colDn, style = label.style_label_down, textcolor = inkOn(colDn), size = sigSize, tooltip = nameDn + " signal: the MACD crossed down through its signal line from above the band." + (bearDiv ? " With a bearish divergence." : ""), force_overlay = true)
// Dots: a wide faint one behind a small solid one. Every signal when the list is set to Dots, and otherwise every repeat
// of the same signal, so a run reads as one word followed by dots
bool  dotsOn = sigOn and (not lblOn or repeatNow)
float dotGap = 0.3 * atrNow
plotshape(dotsOn and buyNow ? low - dotGap : na, "Buy dot, glow", shape.circle, location.absolute, color.new(colUp, 82), size = size.small, editable = false, display = display.pane, force_overlay = true)
plotshape(dotsOn and buyNow ? low - dotGap : na, "Buy dot", shape.circle, location.absolute, colUp, size = size.tiny, editable = false, display = display.pane, force_overlay = true)
plotshape(dotsOn and sellNow ? high + dotGap : na, "Sell dot, glow", shape.circle, location.absolute, color.new(colDn, 82), size = size.small, editable = false, display = display.pane, force_overlay = true)
plotshape(dotsOn and sellNow ? high + dotGap : na, "Sell dot", shape.circle, location.absolute, colDn, size = size.tiny, editable = false, display = display.pane, force_overlay = true)
 
// prices are written the way the chart writes them: with the symbol's own number of decimals and with thousands separators
decimalsOf(float tick) =>
    int   d = 0
    float t = tick
    while d < 8 and math.abs(t - math.round(t)) > 0.000000001 * math.max(1.0, t)
        t *= 10
        d += 1
    d
 
var int    priceDec = decimalsOf(syminfo.mintick)
var string priceFmt = "#,##0"
if barstate.isfirst and priceDec > 0
    priceFmt := "#,##0."
    for i = 1 to priceDec
        priceFmt += "0"
 
fmtP(float x) =>
    str.tostring(x, priceFmt)
 
var line     xGlow  = na
var line     xLine  = na
var label    xLab   = na
var polyline ckMacd = na
var polyline ckSig  = na
var label    ckText = na
 
// the clock: bars until the MACD meets its signal line if every coming candle closes at the latest price.
// 0: this candle would do it if it closed here. na: not within the bars the clock looks ahead
int clockN = na
 
if barstate.islast
    line.delete(xGlow)
    line.delete(xLine)
    label.delete(xLab)
    polyline.delete(ckMacd)
    polyline.delete(ckSig)
    label.delete(ckText)
    lblSize  = sizeIn == "Small" ? size.small : sizeIn == "Large" ? size.large : size.normal
    hintSize = sizeIn == "Large" ? size.normal : size.small
    // the cross price: a dashed line from the last candle to the right, in the colour of the cross it would be
    if lineIn and crossOk
        color  cx  = refUp ? colDn : colUp
        string act = nextSig ? (refUp ? nameDn : nameUp) : (refUp ? "down" : "up")
        // four short lines, so the label fits in the room to the right of the last candle even on a zoomed out chart
        string tx  = (nextSig ? "Next signal:\n" : "Next cross:\n") + act + "\n" + (beyond ? (refUp ? "unless above\n" : "unless below\n") : (refUp ? "close below\n" : "close above\n")) + fmtP(crossPx)
        // the full sentence when the label is hovered
        string tipX = (refUp ? "The MACD crosses down through its signal line " : "The MACD crosses up through its signal line ") + (beyond ? "unless the candle closes " + (refUp ? "above " : "below ") : "if the candle closes " + (refUp ? "below " : "above ")) + fmtP(crossPx) + (nextSig ? ". That cross would be a signal." : ".")
        xGlow := line.new(bar_index, crossPx, bar_index + 3, crossPx, xloc = xloc.bar_index, extend = extend.right, color = color.new(cx, 86), width = 5, force_overlay = true)
        xLine := line.new(bar_index, crossPx, bar_index + 3, crossPx, xloc = xloc.bar_index, extend = extend.right, color = cx, style = line.style_dashed, width = 1, force_overlay = true)
        xLab  := label.new(bar_index + 3, crossPx, tx, xloc = xloc.bar_index, yloc = yloc.price, color = color.from_gradient(16, 0, 100, chart.bg_color, cx), style = label.style_label_left, textcolor = cx, size = lblSize, textalign = text.align_left, tooltip = tipX, force_overlay = true)
    // the clock. A forming candle that has already taken the histogram to the other side would cross if it closed here
    bool ready   = not na(hist) and not na(histRef)
    bool flipped = ready and (hist > 0) != refUp
    if flipped
        clockN := 0
    if ready and not flipped
        // both averages carried forward bar by bar with the latest price as every coming close
        array<chart.point> ptsM = array.new<chart.point>()
        array<chart.point> ptsS = array.new<chart.point>()
        ptsM.push(chart.point.from_index(bar_index, macd))
        ptsS.push(chart.point.from_index(bar_index, sig))
        float f    = fast
        float s    = slow
        float g    = sig
        float mEnd = macd
        for k = 1 to maxAhead
            f := aF * close + (1 - aF) * f
            s := aS * close + (1 - aS) * s
            float m = f - s
            g := aG * m + (1 - aG) * g
            ptsM.push(chart.point.from_index(bar_index + k, m))
            ptsS.push(chart.point.from_index(bar_index + k, g))
            mEnd := m
            if (m - g > 0) != refUp
                clockN := k
                break
        // drawn in the pane: the two lines dotted to where they meet, and the number of bars written there
        if clockIn and not na(clockN)
            color nx = refUp ? colDn : colUp
            ckSig  := polyline.new(ptsS, line_color = color.new(chart.fg_color, 55), line_style = line.style_dotted, line_width = 1)
            ckMacd := polyline.new(ptsM, line_color = color.new(sideCol, 20), line_style = line.style_dotted, line_width = 2)
            ckText := label.new(bar_index + clockN, mEnd, "○ in " + str.tostring(clockN) + (clockN == 1 ? " bar" : " bars"), xloc = xloc.bar_index, yloc = yloc.price, color = color.new(chart.bg_color, 100), style = label.style_label_left, textcolor = nx, size = hintSize, textalign = text.align_left)
 
// ───────────────────────── Words ─────────────────────────
 
// Where the panel goes on Auto: the top right corner of the price chart, and the bottom right corner while price is in the top part
// of the screen, so the panel never sits on the newest candles or on the cross price. For that the script keeps the highest high,
// the lowest low and the latest close of the candles on the screen
int tLeft  = chart.left_visible_bar_time
int tRight = chart.right_visible_bar_time
var float  visHi      = na
var float  visLo      = na
var float  visClose   = na
var string autoCorner = "Top right"
if time >= tLeft and time <= tRight
    visHi    := na(visHi) ? high : math.max(visHi, high)
    visLo    := na(visLo) ? low : math.min(visLo, low)
    visClose := close
 
var table panel = na
 
if barstate.islast and showPanel and not na(hist)
    color blank = color.new(#000000, 100)
    // how far the latest price on the screen is below the highest one, as a share of the screen's range. The panel moves down when
    // that is less than a quarter and back up when it is more than a third, so it does not flicker between the two corners
    float span    = nz(visHi - visLo)
    float topRoom = span > 0 and not na(visClose) ? (visHi - visClose) / span : 1.0
    if topRoom < 0.25
        autoCorner := "Bottom right"
    else if topRoom > 0.34
        autoCorner := "Top right"
    string corner = panelPos == "Auto" ? autoCorner : panelPos
    tablePos = switch corner
        "Top left"     => position.top_left
        "Top right"    => position.top_right
        "Bottom right" => position.bottom_right
        => position.bottom_left
    if na(panel)
        panel := table.new(tablePos, 2, 8, frame_width = 0, border_width = 0, force_overlay = true)
    table.set_position(panel, tablePos)
    txtSize = sizeIn == "Small" ? size.small : sizeIn == "Large" ? size.large : size.normal
    color txt = #D1D4DC
    color dim = color.new(#D1D4DC, 40)
    color bg  = color.new(colPanel, 15)
    // a little room in front of every value: the words change with every tick, and a value that grows by a character
    // before the table is measured again would otherwise lose its first letter
    string sp = "   "
    // momentum: the state of the histogram and how long it has lasted
    string r1 = (st <= 1 ? "Up, " : "Down, ") + (st == 0 or st == 2 ? "building for " : "fading for ") + str.tostring(stRun) + (stRun == 1 ? " bar" : " bars")
    // the next cross: which way it would be, at which close, and how far that is. The signal's own name when it would be one
    string wNext = nextSig ? (refUp ? nameDn : nameUp) : (refUp ? "Down" : "Up")
    string r2 = "Out of reach on this candle"
    if crossOk
        if beyond
            r2 := wNext + (refUp ? " unless price closes above " : " unless price closes below ") + fmtP(crossPx)
        else
            float awayPct = math.abs(close - crossPx) / math.abs(close) * 100
            r2 := wNext + (refUp ? " on a close below " : " on a close above ") + fmtP(crossPx) + ", " + str.tostring(awayPct, awayPct >= 0.1 ? "0.00" : "0.000") + "% away"
    string l2 = crossOk and nextSig ? "Next signal" : "Next cross"
    // the clock in words
    string wCross = refUp ? "Crosses down" : "Crosses up"
    string rc = na(clockN) ? "No cross within " + str.tostring(maxAhead) + " bars" : clockN == 0 ? wCross + " if this candle closes here" : wCross + " in " + str.tostring(clockN) + (clockN == 1 ? " bar" : " bars")
    string r3 = (above ? "Above for " : "Below for ") + str.tostring(sideRun) + (sideRun == 1 ? " bar" : " bars")
    string r4 = "None on this chart yet"
    if not na(lastSigBar)
        int ago = bar_index - lastSigBar
        r4 := (lastSigUp ? nameUp : nameDn) + ", " + (ago == 0 ? "on this bar" : str.tostring(ago) + (ago == 1 ? " bar ago" : " bars ago")) + (lastSigDiv ? ", with a divergence" : "")
    string r5 = recOk ? str.tostring(pSig, "0") + "% undone within " + str.tostring(flipBars) + " bars, other crosses " + str.tostring(pOth, "0") + "%" : "Not enough crosses on this chart yet"
    string tip2 = "The close at which the MACD meets its signal line, solved from the MACD's own formula. While a candle is forming it is the price for that candle. Once it has closed it is the price for the next one. It reads Next signal when that cross would be a signal."
    string tipC = "How long the cross takes if price goes nowhere: both lines carried forward as if every coming candle closed at the latest price."
    string tip5 = "Counted on this chart. Of the signals, the share that was undone by the opposite cross within " + str.tostring(flipBars) + " bars, against the same share for every other cross. " + str.tostring(nSig) + " signals and " + str.tostring(nOth) + " other crosses so far. It says how long a signal lasted, not whether price followed it."
    table.cell(panel, 0, 0, "MACD MASTER", text_color = txt, text_size = txtSize, text_halign = text.align_left, bgcolor = bg)
    table.cell(panel, 1, 0, str.tostring(fastLen) + " · " + str.tostring(slowLen) + " · " + str.tostring(sigIn), text_color = dim, text_size = txtSize, text_halign = text.align_right, bgcolor = bg)
    table.cell(panel, 0, 1, "Momentum", text_color = dim, text_size = txtSize, text_halign = text.align_left, bgcolor = bg)
    table.cell(panel, 1, 1, sp + r1, text_color = st <= 1 ? colUp : colDn, text_size = txtSize, text_halign = text.align_right, bgcolor = bg)
    table.cell(panel, 0, 2, l2, text_color = dim, text_size = txtSize, text_halign = text.align_left, bgcolor = bg)
    table.cell(panel, 1, 2, sp + r2, text_color = txt, text_size = txtSize, text_halign = text.align_right, bgcolor = bg, tooltip = tip2)
    int rw = 3
    if clockIn
        table.cell(panel, 0, rw, "If price stays here", text_color = dim, text_size = txtSize, text_halign = text.align_left, bgcolor = bg)
        table.cell(panel, 1, rw, sp + rc, text_color = txt, text_size = txtSize, text_halign = text.align_right, bgcolor = bg, tooltip = tipC)
        rw += 1
    table.cell(panel, 0, rw, "Zero line", text_color = dim, text_size = txtSize, text_halign = text.align_left, bgcolor = bg)
    table.cell(panel, 1, rw, sp + r3, text_color = txt, text_size = txtSize, text_halign = text.align_right, bgcolor = bg)
    table.cell(panel, 0, rw + 1, "Last signal", text_color = dim, text_size = txtSize, text_halign = text.align_left, bgcolor = bg)
    table.cell(panel, 1, rw + 1, sp + r4, text_color = txt, text_size = txtSize, text_halign = text.align_right, bgcolor = bg)
    table.cell(panel, 0, rw + 2, "Signals", text_color = dim, text_size = txtSize, text_halign = text.align_left, bgcolor = bg)
    table.cell(panel, 1, rw + 2, sp + r5, text_color = txt, text_size = txtSize, text_halign = text.align_right, bgcolor = bg, tooltip = tip5)
    // at the bottom of the chart, one clear row under the panel: TradingView draws its event icons along that edge
    if corner == "Bottom left" or corner == "Bottom right"
        table.cell(panel, 0, rw + 3, ".", text_color = blank, text_size = txtSize, bgcolor = blank)
 
// ───────────────────────── Alerts ─────────────────────────
 
bool zeroUp    = macd > 0 and macd[1] <= 0
bool zeroDn    = macd < 0 and macd[1] >= 0
bool fadeStart = (st == 1 and st[1] == 0) or (st == 3 and st[1] == 2)
// price has traded at the cross price during this candle: the MACD crosses if the candle closes beyond it
bool atCross   = not na(crossPrev) and (histPrev > 0 ? low <= crossPrev : high >= crossPrev)
 
alertcondition(buyNow, "Signal up (Oversold, Buy)", "MACD Master: signal up. The MACD crossed up through its signal line from below the band")
alertcondition(sellNow, "Signal down (Overbought, Sell)", "MACD Master: signal down. The MACD crossed down through its signal line from above the band")
alertcondition(xUp, "MACD crossed up (any cross)", "MACD Master: the MACD crossed above its signal line")
alertcondition(xDn, "MACD crossed down (any cross)", "MACD Master: the MACD crossed below its signal line")
alertcondition(bullDiv, "Bullish divergence", "MACD Master: bullish divergence. Price made a lower low, the MACD a higher one")
alertcondition(bearDiv, "Bearish divergence", "MACD Master: bearish divergence. Price made a higher high, the MACD a lower one")
alertcondition(atCross, "Price reached the next cross price", "MACD Master: price is at the level where the MACD crosses its signal line if the candle closes beyond it")
alertcondition(zeroUp, "MACD above zero", "MACD Master: the MACD line crossed above zero")
alertcondition(zeroDn, "MACD below zero", "MACD Master: the MACD line crossed below zero")
alertcondition(fadeStart, "Momentum started fading", "MACD Master: the histogram has started to shrink")

← 返回列表