TradingView MACD: settings and signal rules
Add MACD from Indicators, then read three separate values: the fast-minus-slow average, its signal average, and the gap between them.
Start with Close and 12/26/9 on the chart timeframe. A MACD/Signal cross is a histogram zero cross; it is different from the MACD line crossing zero. This tutorial includes a copyable Pine v6 indicator with confirmed alerts. It does not contain a backtest or establish profitable settings.
Add MACD to a TradingView chart
- Open Indicators on your chart and search for MACD or Moving Average Convergence Divergence.
- Select TradingView's built-in indicator. It appears in its own pane.
- Open Settings and check Source, Fast length, Slow length, Signal length, and the two MA types. Keep the calculation timeframe equal to the chart while learning the signals.
The built-in indicator is a useful reference when comparing a community script: match every input, then inspect the three values on the same closed bar. A script with extra colors or a buy/sell label is not evidence of better trading performance.
Browse related studies in the TradingView indicators directory. This tutorial and its code can be read and copied without buying Pineify; Pineify product access and TradingView alert limits are separate.
Why Traders Use This Indicator
- Compare the relative position of two moving averages in one pane.
- Define repeatable crossover events for chart inspection and alerts.
- See whether the gap between MACD and its signal average is widening or narrowing.
| Parameter | Default | Description |
|---|---|---|
| Fast / slow length | 12 / 26 | This example uses 12 and 26 chart bars. Keep fast below slow. Equal lengths make MACD zero; reversing them changes its sign. |
| Signal length | 9 | Length of the average applied to MACD. Changing it alters Signal and Histogram, but leaves the MACD line unchanged. |
| Source | Close | Input to the fast and slow averages. A different source changes all three output series. |
| Oscillator MA type | EMA | Applies to both fast and slow averages. Selecting SMA changes the MACD calculation and downstream values. |
| Signal MA type | EMA | Applies only to the average of MACD. This example also supports SMA for comparison. |
| Calculation timeframe | Chart in this example | The built-in MACD can use another timeframe. Its Wait for timeframe closes setting affects when those values become available; this script uses only chart bars. |
MACD mathematics and settings differences
With EMA selected for both MA types, MACD = EMA(source, fast) - EMA(source, slow), Signal = EMA(MACD, signalLength), and Histogram = MACD - Signal. Selecting SMA replaces the relevant average, not the subtraction. See TradingView's MACD calculation and input reference.
For EMA length n, the recursion after initialization is EMA(t) = alpha × source(t) + (1 - alpha) × EMA(t-1), where alpha = 2 / (n + 1). Old observations retain declining weight. An SMA instead gives equal weight to the latest n observations.
Arithmetic example, not market data: if Fast MA = 105, Slow MA = 102 and Signal = 2, MACD = 3 and Histogram = 1. If MACD is -3 and Signal is -4, Histogram is also +1. A positive histogram therefore does not imply a positive MACD line.
Compare settings without assuming a winner
- 12/26/9: the baseline used in this example.
- 8/21/5: a shorter comparison set, with more weight on recent observations and less smoothing.
- 24/52/18: a longer comparison set, with more smoothing and a slower response to many price changes.
These are illustrative alternatives, not tested recommendations for particular markets or timeframes. Keep symbol, session, timeframe, source and MA types fixed, then change one length at a time. Count crossover events and inspect their timing. To compare trading results, define entries, exits, fees and slippage in a separate strategy and reserve data outside the tuning sample. No such test is reported here.
Signal Interpretation
Three readings with different meanings
- MACD crosses Signal: MACD moves from at or below Signal to above it (or the reverse). This is the same mathematical event as Histogram crossing zero; it is not an independent confirmation.
- MACD crosses zero: the fast average crosses the slow average. It says nothing by itself about how long price will continue in that direction.
- Histogram contracts: its absolute distance from zero shrinks. The MACD/Signal gap is closing. It may expand again without crossing zero, so there is no fixed lead time to a crossover.
The four histogram colors in the example encode sign and change: positive/rising, positive/falling, negative/falling, and negative/rising. Read the values as well as the colors; styles can be customized.
Confirm the bar used by the rule
On an open chart bar, the values can change and a crossover can disappear. The example gates all four named alert conditions with barstate.isconfirmed. Choose the named event and Once Per Bar Close in TradingView's alert dialog. Alternatively, choose Any alert() function call for the two signal-line crossover messages. Do not create both unless duplicate notifications are intended.
Pine code exposes alert events; you must still create the running alert in TradingView. Recreate it after changing the script, inputs or chart context because an existing alert uses its saved configuration. See TradingView's alert documentation and our crossover alerts guide.
These checks confirm the chart bar, not a higher-timeframe series added later. TradingView's bar-state documentation defines this boundary. Close confirmation delays an event until the bar closes; it does not remove losing signals.
Combining with Other Indicators
An EMA filter can restrict upward crossover events to bars where Close is above a chosen price EMA. RSI can add a separate momentum condition. Both change the event set and can also remove useful signals; their value requires a defined test.
Volume or VWAP adds different context, but neither identifies institutional participation from a MACD crossover. Repeated crossings in a narrow range remain a limitation even when several indicators agree.
Writing Pine Script Manually
Challenges of Manual Coding
Compute crossover functions on every bar, then apply the confirmation gate to their results.
Keep MACD zero crosses separate from Histogram zero crosses in alert names.
Match source, timeframe and both MA types before comparing against another MACD script.
//@version=6
indicator(title="MACD: Confirmed Crosses [Pineify]", shorttitle="MACD Crosses", overlay=false)
// ==========================================
// User Inputs
// ==========================================
fastLength = input.int(12, title="Fast Length", minval=1, group="MACD Parameters")
slowLength = input.int(26, title="Slow Length", minval=1, group="MACD Parameters")
signalLength = input.int(9, title="Signal Smoothing", minval=1, group="MACD Parameters")
src = input.source(close, title="Source", group="MACD Parameters")
oscMaType = input.string("EMA", title="Oscillator MA Type", options=["EMA", "SMA"], group="MACD Parameters")
signalMaType = input.string("EMA", title="Signal Line MA Type", options=["EMA", "SMA"], group="MACD Parameters")
// Visual Styling
colMacd = input.color(#2962FF, title="MACD Line", group="Visual Styling")
colSignal = input.color(#FF6D00, title="Signal Line", group="Visual Styling")
colGrowAbove = input.color(#26A69A, title="Histogram Growing Above Zero", group="Visual Styling")
colFallAbove = input.color(#80CBC4, title="Histogram Fading Above Zero", group="Visual Styling")
colGrowBelow = input.color(#EF5350, title="Histogram Growing Below Zero", group="Visual Styling")
colFallBelow = input.color(#FFCDD2, title="Histogram Fading Below Zero", group="Visual Styling")
showBgAlert = input.bool(true, title="Highlight Confirmed Crosses in Pane", group="Visual Styling")
// ==========================================
// Calculations
// ==========================================
fastMA = oscMaType == "SMA" ? ta.sma(src, fastLength) : ta.ema(src, fastLength)
slowMA = oscMaType == "SMA" ? ta.sma(src, slowLength) : ta.ema(src, slowLength)
macdLine = fastMA - slowMA
signalLine = signalMaType == "SMA" ? ta.sma(macdLine, signalLength) : ta.ema(macdLine, signalLength)
hist = macdLine - signalLine
// Color represents the histogram sign and change from its prior value
histColor = hist >= 0 ? (hist >= hist[1] ? colGrowAbove : colFallAbove) : (hist <= hist[1] ? colGrowBelow : colFallBelow)
// ==========================================
// Plotting
// ==========================================
plot(hist, title="Histogram", style=plot.style_columns, color=histColor)
plot(macdLine, title="MACD Line", color=colMacd, linewidth=2)
plot(signalLine, title="Signal Line", color=colSignal, linewidth=2)
hline(0, title="Zero Centerline", color=color.new(color.gray, 60), linestyle=hline.style_dotted)
// ==========================================
// Chart-timeframe signal conditions
// ==========================================
bullishCross = ta.crossover(macdLine, signalLine)
bearishCross = ta.crossunder(macdLine, signalLine)
zeroCrossBull = ta.crossover(macdLine, 0)
zeroCrossBear = ta.crossunder(macdLine, 0)
// Optional visual highlight for confirmed crossover bars
bgcolor(showBgAlert and bullishCross and barstate.isconfirmed ? color.new(color.green, 90) : showBgAlert and bearishCross and barstate.isconfirmed ? color.new(color.red, 90) : na)
// These alert() calls execute only at chart-bar close
if bullishCross and barstate.isconfirmed
alert("MACD Bullish Crossover confirmed on " + syminfo.ticker + " (" + timeframe.period + ")", alert.freq_once_per_bar_close)
if bearishCross and barstate.isconfirmed
alert("MACD Bearish Crossover confirmed on " + syminfo.ticker + " (" + timeframe.period + ")", alert.freq_once_per_bar_close)
// TradingView UI Alert Dialog Support
alertcondition(bullishCross and barstate.isconfirmed, title="MACD Bullish Cross", message="MACD Line crossed above Signal Line on {{ticker}}")
alertcondition(bearishCross and barstate.isconfirmed, title="MACD Bearish Cross", message="MACD Line crossed below Signal Line on {{ticker}}")
alertcondition(zeroCrossBull and barstate.isconfirmed, title="MACD Zero Line Bullish Cross", message="MACD Line crossed above Zero Line on {{ticker}}")
alertcondition(zeroCrossBear and barstate.isconfirmed, title="MACD Zero Line Bearish Cross", message="MACD Line crossed below Zero Line on {{ticker}}")Maintenance Note: This chart-timeframe indicator plots values and exposes alerts; it places no orders and produces no Strategy Tester results. Plots still update on the open bar. Recheck signal behavior if you add external sources, other timeframes or strategy orders.
Build with Pineify Visual Editor
Pineify lets you configure supported indicators and export Pine Script. Available settings and plan requirements vary by indicator. Compare the generated rules with the example before using its signals.
| Feature | Manual Pine Script | Pineify Visual Editor |
|---|---|---|
| MACD inputs | The example exposes lengths, source and EMA/SMA choices. | The MACD module exposes source and fast, slow and signal lengths using ta.macd. |
| Custom behavior | Edit the calculations and event conditions directly. | Configure supported conditions visually; use the AI Coding Agent for a custom code request and review its output. |
| Verification | Compare closed-bar values and test alerts in TradingView. | Apply the same checks to generated code; generation does not establish trading performance. |
Configure the MACD module with source and length inputs.
Use its MACD, Signal and Histogram outputs when defining conditions.
Review exported Pine Script alongside the rules you intended.
Step-by-Step Tutorial
Choose a Pineify workflow
Open the Visual Pine Script Editor for supported modules or the AI Coding Agent for a custom script request. Check the applicable plan before using paid features.
Set the MACD inputs
Choose source and fast, slow and signal lengths. The visual MACD module uses ta.macd; the EMA/SMA selector in this page's custom example is a separate capability.
Define the event
Specify a MACD/Signal crossover or a MACD zero cross, and explicitly require chart-bar close confirmation when that is your intended rule.
Inspect and validate the output
Read the generated conditions, add the script to TradingView and compare its closed-bar values. Create the alert in TradingView after verifying the selected event.
Trading Strategies & Pro Tips
Signal-line crossing rule
An upward event requires previous MACD <= previous Signal and current MACD > current Signal at bar close. A state such as MACD > Signal remains true across multiple bars; it is not the crossing event.
Pro Tip: This event is equivalent to Histogram crossing above zero. Counting both as confirmation counts the same evidence twice.
Centerline crossing rule
An upward MACD zero cross means the fast average has moved above the slow average. Check its chart-bar timing separately from the signal-line crossing.
Pro Tip: Do not assume a fixed ordering or delay between signal-line and centerline events.
Divergence as an observation
Price making a lower low while MACD makes a higher low is a regular bullish divergence observation. A higher price high with a lower MACD high is the bearish counterpart.
Pro Tip: Choose a consistent swing definition. Pivot-based detection needs later bars to confirm a pivot; divergence does not guarantee reversal and is not implemented in this example.
Common Mistakes to Avoid
- Treating a positive histogram as proof that MACD is above zero.
- Calling a below-zero MACD reading oversold: MACD is unbounded and its raw values depend on price scale.
- Interpreting every crossing in a sideways range as a trade entry.
- Assuming a closed-bar alert guarantees a fill, profit, or a higher-timeframe confirmation.
- Choosing a parameter set from its best historical result without accounting for costs and an independent test period.
Frequently Asked Questions
Define your custom MACD rule in Pineify
- Use the visual MACD module for source and length settings.
- Describe custom MA choices or alerts to the AI Coding Agent.
- Review generated code and check current product plan requirements.
Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.
Related Indicator Tutorials
MACD-V Indicator
Calculate volatility-normalized MACD, review its range model, and build inspectable Pine Script.
MACD Volume Indicator
Separate volume-weighted MACD from standard MACD with a volume confirmation rule.
MACD and Alligator Strategy
Define an Alligator trend filter, MACD timing rule, exits, and controlled Pine Script tests.
MACD Calculator
Compute Moving Average Convergence Divergence values to identify trend direction and momentum.
MACD Crossover Strategy Tutorial
Learn how to build, backtest, and optimize a MACD crossover strategy on TradingView using Pine Script v5 and Pineify Deep Report.