OPEN-SOURCE SCRIPT
Ultimate MACD [captainua]

Ultimate MACD [captainua] - Comprehensive MACD Trading System
Overview
This indicator combines traditional MACD calculations with advanced features including divergence detection, volume analysis, histogram analysis tools, regression forecasting, strong top/bottom detection, and multi-timeframe confirmation to provide a comprehensive MACD-based trading system. The script calculates MACD using configurable moving average types (EMA, SMA, RMA, WMA) and applies various smoothing methods to reduce noise while maintaining responsiveness. The combination of these features creates a multi-layered confirmation system that reduces false signals by requiring alignment across multiple indicators and timeframes.
Core Calculations
MACD Calculation:
The script calculates MACD using the standard formula: MACD Line = Fast MA - Slow MA, Signal Line = Moving Average of MACD Line, Histogram = MACD Line - Signal Line. The default parameters are Fast=12, Slow=26, Signal=9, matching the traditional MACD settings. The script supports four moving average types:
- EMA (Exponential Moving Average): Standard and most responsive, default choice
- SMA (Simple Moving Average): Equal weight to all periods
- RMA (Wilder's Moving Average): Smoother, less responsive
- WMA (Weighted Moving Average): Recent prices weighted more heavily
The price source can be configured as Close (standard), Open, High, Low, HL2, HLC3, or OHLC4. Alternative sources provide different sensitivity characteristics for various trading strategies.
Configuration Presets:
The script includes trading style presets that automatically configure MACD parameters:
- Scalping: Fast/Responsive settings (8,18,6 with minimal smoothing)
- Day Trading: Balanced settings (10,22,7 with minimal smoothing)
- Swing Trading: Standard settings (12,26,9 with moderate smoothing)
- Position Trading: Smooth/Conservative settings (15,35,12 with higher smoothing)
- Custom: Full manual control over all parameters
Histogram Smoothing:
The histogram can be smoothed using EMA to reduce noise and filter minor fluctuations. Smoothing length of 1 = raw histogram (no smoothing), higher values (3-5) = smoother histogram. Increased smoothing reduces noise but may delay signals slightly.
Percentage Mode:
MACD values can be converted to percentage of price (MACD/Close*100) for cross-instrument comparison. This is useful when comparing MACD signals across instruments with different price levels (e.g., BTC vs ETH). The percentage mode normalizes MACD values, making them comparable regardless of instrument price.
MACD Scale Factor:
A scale factor multiplier (default 1.0) allows adjusting MACD display size for better visibility. Use 0.3-0.5 if MACD appears too compressed, or 2.0-3.0 if too small.
Dynamic Overbought/Oversold Levels:
Overbought and oversold levels are calculated dynamically based on MACD's mean and standard deviation over a lookback period. The formula: OB = MACD Mean + (StdDev × OB Multiplier), OS = MACD Mean - (StdDev × OS Multiplier). This adapts to current market conditions, widening in volatile markets and narrowing in calm markets. The lookback period (default 20) controls how quickly the levels adapt: longer periods (30-50) = more stable levels, shorter (10-15) = more responsive.
OB/OS Background Coloring:
Optional background coloring can highlight the entire panel when MACD enters overbought or oversold territory, providing prominent visual indication of extreme conditions. The background colors are drawn on top of the main background to ensure visibility.
Divergence Detection
Regular Divergence:
The script uses the MACD line (not histogram) for divergence detection, which provides more reliable signals. Bullish divergence: Price makes a lower low while MACD line makes a higher low. Bearish divergence: Price makes a higher high while MACD line makes a lower high. Divergences often precede reversals and are powerful reversal signals.
Pivot-Based Divergence:
The divergence detection uses actual pivot points (pivotlow/pivothigh) instead of simple lowest/highest comparisons. This provides more accurate divergence detection by identifying significant pivot lows/highs in both price and MACD line. The pivot-based method compares two recent pivot points: for bullish divergence, price makes a lower low while MACD makes a higher low at the pivot points. This method reduces false divergences by requiring actual pivot points rather than just any low/high within a period.
The pivot lookback parameters (left and right) control how many bars on each side of a pivot are required for confirmation. Higher values = more conservative pivot detection.
Hidden Divergence:
Continuation patterns that signal trend continuation rather than reversal. Bullish hidden divergence: Price makes a higher low but MACD makes a lower low. Bearish hidden divergence: Price makes a lower high but MACD makes a higher high. These patterns indicate the trend is likely to continue in the current direction.
Zero-Line Filter:
The "Don't Touch Zero Line" option ensures divergences occur in proper context: for bullish divergence, MACD must stay below zero; for bearish divergence, MACD must stay above zero. This filters out divergences that occur in neutral zones.
Range Filtering:
Minimum and maximum lookback ranges control the time window between pivots to consider for divergence. This helps filter out divergences that are too close together (noise) or too far apart (less relevant).
Volume Confirmation System
Volume threshold filtering requires current volume to exceed the volume SMA multiplied by the threshold factor. The formula: Volume Confirmed = Volume > (Volume SMA × Threshold). If the threshold is set to 1.0 or lower, volume confirmation is effectively disabled (always returns true). This allows you to use the indicator without volume filtering if desired. Volume confirmation significantly increases divergence and signal reliability.
Volume Climax and Dry-Up Detection:
The script can mark bars with extremely high volume (volume climax) or extremely low volume (volume dry-up). Volume climax indicates potential reversal points or strong momentum continuation. Volume dry-up indicates low participation and may produce unreliable signals. These markers use standard deviation multipliers to identify extreme volume conditions.
Zero-Line Cross Detection
MACD zero-line crosses indicate momentum shifts: above zero = bullish momentum, below zero = bearish momentum. The script includes alert conditions for zero-line crosses with cooldown protection to prevent alert spam. Zero-line crosses can provide early warning signals before MACD crosses the signal line.
Histogram Analysis Tools
Histogram Moving Average:
A moving average applied to the histogram itself helps identify histogram trend direction and acts as a signal line for histogram movements. Supports EMA, SMA, RMA, and WMA types. Useful for identifying when histogram momentum is strengthening or weakening.
Histogram Bollinger Bands:
Bollinger Bands are applied to the MACD histogram instead of price. The calculation: Basis = SMA(Histogram, Period), StdDev = stdev(Histogram, Period), Upper = Basis + (StdDev × Deviation Multiplier), Lower = Basis - (StdDev × Deviation Multiplier). This creates dynamic zones around the histogram that adapt to histogram volatility. When the histogram touches or exceeds the bands, it indicates extreme conditions relative to recent histogram behavior.
Stochastic MACD (StochMACD):
Stochastic MACD applies the Stochastic oscillator formula to the MACD histogram instead of price. This normalizes the histogram to a 0-100 scale, making it easier to identify overbought/oversold conditions on the histogram itself. The calculation: %K = ((Histogram - Lowest Histogram) / (Highest Histogram - Lowest Histogram)) × 100. %K is smoothed, and %D is calculated as the moving average of smoothed %K. Standard thresholds are 80 (overbought) and 20 (oversold).
Regression Forecasting
The script includes advanced regression forecasting that predicts future MACD values using mathematical models. This helps anticipate potential MACD movements and provides forward-looking context for trading decisions.
Regression Types:
- Linear: Simple trend line (y = mx + b) - fastest, works well for steady trends
- Polynomial: Quadratic curve (y = ax² + bx + c) - captures curvature in MACD movement
- Exponential Smoothing: Weighted average with more weight on recent values - responsive to recent changes
- Moving Average: Uses difference between short and long MA to estimate trend - stable and smooth
Forecast Horizon:
Number of bars to forecast ahead (default 5, max 50 for linear/MA, max 20 for polynomial due to performance). Longer horizons predict further ahead but may be less accurate.
Confidence Bands:
Optional upper/lower bands around forecast show prediction uncertainty based on forecast error (standard deviation of prediction vs actual). Wider bands = higher uncertainty. The confidence level multiplier (default 1.5) controls band width.
Forecast Display:
Forecast appears as dotted lines extending forward from current bar, with optional confidence bands. All forecast values respect percentage mode and scale factor settings.
Strong Top/Bottom Signals
The script detects strong recovery from extreme MACD levels, generating "sBottom" and "sTop" signals. These identify significant reversal potential when MACD recovers substantially from overbought/oversold extremes.
Strong Bottom (sBottom):
Triggered when:
1. MACD was at or near its lowest point in the bottom period (default 10 bars)
2. MACD was in or near the oversold zone
3. MACD has recovered by at least the threshold amount (default 0.5) from the lowest point
4. Recovery persists for confirmation bars (default 2 consecutive bars)
5. MACD has moved out of the oversold zone
6. Volume is above average
7. All enabled filters pass
8. Minimum bars have passed since last signal (reset period, default 5 bars)
Strong Top (sTop):
Triggered when:
1. MACD was at or near its highest point in the top period (default 7 bars)
2. MACD was in or near the overbought zone
3. MACD has declined by at least the threshold amount (default 0.5) from the highest point
4. Decline persists for confirmation bars (default 2 consecutive bars)
5. MACD has moved out of the overbought zone
6. Volume is above average
7. All enabled filters pass
8. Minimum bars have passed since last signal (reset period, default 5 bars)
Label Placement:
sTop/sBottom labels appear on the historical bar where the actual extreme occurred (not on current bar), showing the exact MACD value at that extreme. Labels respect the unified distance checking system to prevent overlaps with Buy/Sell Strength labels.
Signal Strength Calculation
The script calculates a composite signal strength score (0-100) based on multiple factors:
- MACD distance from signal line (0-50 points): Larger separation indicates stronger signal
- Volume confirmation (0-15 points): Volume above average adds points
- Secondary timeframe alignment (0-15 points): Higher timeframe agreement adds points
- Distance from zero line (0-20 points): Closer to zero can indicate stronger reversal potential
Higher scores (70+) indicate stronger, more reliable signals. The signal strength is displayed in the statistics table and can be used as a filter to only accept signals above a threshold.
Smart Label Placement System
The script includes an advanced label placement system that tracks MACD extremes and places Buy/Sell Strength labels at optimal locations:
Label Placement Algorithm:
- Labels appear on the current bar at confirmation (not on historical extreme bars), ensuring they're visible when the signal is confirmed
- The system tracks pending signals when MACD enters OB/OS zones or crosses the signal line
- During tracking, the system continuously searches for the true extreme (lowest MACD for buys, highest MACD for sells) within a configurable historical lookback period
- Labels are only finalized when: (1) MACD exits the OB/OS zone, (2) sufficient bars have passed (2x minimum distance), (3) MACD has recovered/declined by a configurable percentage from the extreme (default 15%), and (4) tracking has stopped (no better extreme found)
Label Spacing and Overlap Prevention:
- Minimum Bars Between Labels: Base distance requirement (default 5 bars)
- Label Spacing Multiplier: Scales the base distance (default 1.5x) for better distribution. Higher values = more spacing between labels
- Effective distance = Base Distance × Spacing Multiplier (e.g., 5 × 1.5 = 7.5 bars minimum)
- Unified distance checking prevents overlaps between all label types (Buy Strength, Sell Strength, sTop, sBottom)
Strength-Based Filtering:
- Label Strength Minimum (%): Only labels with strength at or above this threshold are displayed (default 75%)
- When multiple potential labels are close together, the system automatically compares strengths and keeps only the strongest one
- This ensures only the most significant signals are displayed, reducing chart clutter
Zero Line Polarity Enforcement:
- Enforce Zero Line Polarity (default enabled): Ensures labels follow traditional MACD interpretation
- Buy Strength labels only appear when the tracked extreme MACD value was below zero (negative territory)
- Sell Strength labels only appear when the tracked extreme MACD value was above zero (positive territory)
- This prevents counter-intuitive labels (e.g., Buy labels above zero line) and aligns with standard MACD trading principles
Recovery/Decline Confirmation:
- Recovery/Decline Confirm (%): Percent move away from the extreme required before finalizing (default 15%)
- For Buy labels: MACD must recover by at least this percentage from the tracked bottom
- For Sell labels: MACD must decline by at least this percentage from the tracked top
- Higher values = more confirmation required, fewer but more reliable labels
Historical Lookback:
- Historical Lookback for Label Placement: Number of bars to search for true extremes (default 20)
- The system searches within this period to find the actual lowest/highest MACD value
- Higher values analyze more history but may be slower; lower values are faster but may miss some extremes
Cross Quality Score
The script calculates a MACD cross quality score (0-100) that rates crossover quality based on:
- Cross angle (0-50 points): Steeper crosses = stronger signals
- Volume confirmation (0-25 points): Volume above average adds points
- Distance from zero line (0-25 points): Crosses near zero line are stronger
This score helps identify high-quality crossovers and can be used as a filter to only accept signals meeting minimum quality threshold.
Filtering System
Histogram Filter:
Requires histogram to be above zero for buy signals, below zero for sell signals. Ensures momentum alignment before generating signals.
Signal Strength Filter:
Requires minimum signal strength score for signals. Higher threshold = only strongest signals pass. This combines multiple confirmation factors into a single filter.
Cross Quality Filter:
Requires minimum cross quality score for signals. Rates crossover quality based on angle, volume, momentum, and distance from zero. Only signals meeting minimum quality threshold will be generated.
All filters use the pattern: filterResult = not filterEnabled OR conditionMet. This means if a filter is disabled, it always passes (returns true). Filters can be combined, and all must pass for a signal to fire.
Multi-Timeframe Analysis
The script can display MACD from a secondary (higher) timeframe and use it for confirmation. When secondary timeframe confirmation is enabled, signals require the higher timeframe MACD to align (bullish/bearish) with the signal direction. This ensures signals align with the larger trend context, reducing counter-trend trades.
Secondary Timeframe MACD:
The secondary timeframe MACD uses the same calculation parameters (fast, slow, signal, MA type) as the main MACD but from a higher timeframe. This provides context for the current timeframe's MACD position relative to the larger trend. The secondary MACD lines are displayed on the chart when enabled.
Noise Filtering
Noise filtering hides small histogram movements below a threshold. This helps focus on significant moves and reduces chart clutter. When enabled, only histogram movements above the threshold are displayed. Typical threshold values are 0.1-0.5 for most instruments, depending on the instrument's price range and volatility.
Signal Debounce
Signal debounce prevents duplicate MACD cross signals within a short time period. Useful when MACD crosses back and forth quickly, creating multiple signals. Debounce ensures only one signal per period, reducing signal spam during choppy markets. This is separate from alert cooldown, which applies to all alert types.
Background Color Modes
The script offers three background color modes:
- Dynamic: Full MACD heatmap based on OB/OS conditions, confidence, and momentum. Provides rich visual feedback.
- Monotone: Soft neutral background but still allows overlays (OB/OS zones). Keeps the chart clean without overpowering candles.
- Off: No MACD background (only overlays and plots). Maximum chart cleanliness.
When OB/OS background colors are enabled, they are drawn on top of the main background to ensure visibility.
Statistics Table
A real-time statistics table displays current MACD values, signal strength, distance from zero line, secondary timeframe alignment, volume confirmation status, and all active filter statuses. The table dynamically adjusts to show only enabled features, keeping it clean and relevant. The table position can be configured (Top Left, Top Right, Bottom Left, Bottom Right).
Performance Statistics Table
An optional performance statistics table shows comprehensive filter diagnostics:
- Total buy/sell signals (raw crossover count before filters)
- Filtered buy/sell signals (signals that passed all filters)
- Overall pass rates (percentage of signals that passed filters)
- Rejected signals count
- Filter-by-filter rejection diagnostics showing which filters rejected how many signals
This table helps optimize filter settings by showing which filters are most restrictive and how they impact signal frequency. The diagnostics format shows rejections as "X B / Y S" (X buy signals rejected, Y sell signals rejected) or "Disabled" if the filter is not active.
Alert System
The script includes separate alert conditions for each signal type:
- MACD Cross: MACD line crosses above/below Signal line (with or without secondary confirmation)
- Zero-Line Cross: MACD crosses above/below zero
- Divergence: Regular and hidden divergence detections
- Secondary Timeframe: Higher timeframe MACD crosses
- Histogram MA Cross: Histogram crosses above/below its moving average
- Histogram Zero Cross: Histogram crosses above/below zero
- StochMACD: StochMACD overbought/oversold entries and %K/%D crosses
- Histogram BB: Histogram touches/breaks Bollinger Bands
- Volume Events: Volume climax and dry-up detections
- OB/OS: MACD entry/exit from overbought/oversold zones
- Strong Top/Bottom: sTop and sBottom signal detections
Each alert type has its own cooldown system to prevent alert spam. The cooldown requires a minimum number of bars between alerts of the same type, reducing duplicate alerts during volatile periods. Alert types can be filtered to only evaluate specific alert types (All, MACD Cross, Zero Line, Divergence, Secondary Timeframe, Histogram MA, Histogram Zero, StochMACD, Histogram BB, Volume Events, OB/OS, Strong Top/Bottom).
How Components Work Together
MACD crossovers provide the primary signal when the MACD line crosses the Signal line. Zero-line crosses indicate momentum shifts and can provide early warning signals. Divergences identify potential reversals before they occur.
Volume confirmation ensures signals occur with sufficient market participation, filtering out low-volume false breakouts. Histogram analysis tools (MA, Bollinger Bands, StochMACD) provide additional context for signal reliability and identify significant histogram zones.
Signal strength combines multiple confirmation factors into a single score, making it easy to filter for only the strongest signals. Cross quality score rates crossover quality to identify high-quality setups. Multi-timeframe confirmation ensures signals align with higher timeframe trends, reducing counter-trend trades.
Usage Instructions
Getting Started:
The default configuration shows MACD(12,26,9) with standard EMA calculations. Start with default settings and observe behavior, then customize settings to match your trading style. You can use configuration presets for quick setup based on your trading style.
Customizing MACD Parameters:
Adjust Fast Length (default 12), Slow Length (default 26), and Signal Length (default 9) based on your trading timeframe. Shorter periods (8,17,7) for faster signals, longer (15,30,12) for smoother signals. You can change the moving average type: EMA for responsiveness, RMA for smoothness, WMA for recent price emphasis.
Price Source Selection:
Choose Close (standard), or alternative sources (HL2, HLC3, OHLC4) for different sensitivity. HL2 uses the midpoint of the high-low range, HLC3 and OHLC4 incorporate more price information.
Histogram Smoothing:
Set smoothing to 1 for raw histogram (no smoothing), or increase (3-5) for smoother histogram that reduces noise. Higher smoothing reduces false signals but may delay signals slightly.
Percentage Mode:
Enable percentage mode when comparing MACD across instruments with different price levels. This normalizes MACD values, making them directly comparable.
Dynamic OB/OS Levels:
The dynamic thresholds automatically adapt to volatility. Adjust the multipliers (default 1.5) to fine-tune sensitivity: higher values (2.0-3.0) = more extreme thresholds (fewer signals), lower (1.0-1.5) = more frequent signals. Adjust the lookback period to control how quickly levels adapt. Enable OB/OS background colors for visual indication of extreme conditions.
Volume Confirmation:
Set volume threshold to 1.0 (default, effectively disabled) or higher (1.2-1.5) for standard confirmation. Higher values require more volume for confirmation. Set to 0.1 to completely disable volume filtering.
Filters:
Enable filters gradually to find your preferred balance. Start with histogram filter for basic momentum alignment, then add signal strength filter (threshold 50+) for moderate signals, then cross quality filter (threshold 50+) for high-quality crossovers. Combine filters for highest-quality signals but expect fewer signals.
Divergence:
Enable divergence detection and adjust pivot lookback parameters. Pivot-based divergence provides more accurate detection using actual pivot points. Hidden divergence is useful for trend-following strategies. Adjust range parameters to filter divergences by time window.
Zero-Line Crosses:
Zero-line cross alerts are automatically available when alerts are enabled. These provide early warning signals for momentum shifts.
Histogram Analysis Tools:
Enable Histogram Moving Average to see histogram trend direction. Enable Histogram Bollinger Bands to identify extreme histogram zones. Enable Stochastic MACD to normalize histogram to 0-100 scale for overbought/oversold identification.
Multi-Timeframe:
Enable secondary timeframe MACD to see higher timeframe context. Enable secondary confirmation to require higher timeframe alignment for signals.
Signal Strength:
Signal strength is automatically calculated and displayed in the statistics table. Use signal strength filter to only accept signals above a threshold (e.g., 50 for moderate, 70+ for strong signals only).
Smart Label Placement:
Configure label placement settings to control label appearance and quality:
- Label Strength Minimum (%): Set threshold (default 75%) to show only strong signals. Higher = fewer, stronger labels
- Label Spacing Multiplier: Adjust spacing (default 1.5x) for better distribution. Higher = more spacing between labels
- Recovery/Decline Confirm (%): Set confirmation requirement (default 15%). Higher = more confirmation, fewer labels
- Enforce Zero Line Polarity: Enable (default) to ensure Buy labels only appear when tracked extreme was below zero, Sell labels only when above zero
- Historical Lookback: Adjust search period (default 20 bars) for finding true extremes. Higher = more history analyzed
Cross Quality:
Cross quality score is automatically calculated for crossovers. Use cross quality filter to only accept high-quality crossovers (threshold 50+ for moderate, 70+ for high quality).
Alerts:
Set up alerts for your preferred signal types. Enable alert cooldown (default enabled, 5 bars) to prevent alert spam. Use alert type filter to only evaluate specific alert types (All, MACD Cross, Zero Line, Divergence, Secondary Timeframe, Histogram MA, Histogram Zero, StochMACD, Histogram BB, Volume Events, OB/OS, Strong Top/Bottom). Each signal type has its own alert condition, so you can be selective about which signals trigger alerts.
Visual Elements and Signal Markers
The script uses various visual markers to indicate signals and conditions:
- MACD Line: Green when above signal (bullish), red when below (bearish) if dynamic colors enabled. Optional black outline for enhanced visibility
- Signal Line: Orange line with optional black outline for enhanced visibility
- Histogram: Color-coded based on direction and momentum (green for bullish rising, lime for bullish falling, red for bearish falling, orange for bearish rising)
- Zero Line: Horizontal reference line at MACD = 0
- Fill to Zero: Green/red semi-transparent fill between MACD line and zero line showing bullish/bearish territory
- Fill Between OB/OS: Blue semi-transparent fill between overbought/oversold thresholds highlighting neutral zone
- OB/OS Background Colors: Background coloring when MACD enters overbought/oversold zones
- Background Colors: Dynamic or monotone backgrounds indicating MACD state, or custom chart background
- Divergence Labels: "🐂" for bullish, "🐻" for bearish, "H Bull" for hidden bullish, "H Bear" for hidden bearish
- Divergence Lines: Colored lines connecting pivot points when divergences are detected
- Volume Climax Markers: ⚡ symbol for extremely high volume
- Volume Dry-Up Markers: 💧 symbol for extremely low volume
- Buy/Sell Strength Labels: Show signal strength percentage (e.g., "Buy Strength: 75%")
- Strong Top/Bottom Labels: "sTop" and "sBottom" for extreme level recoveries
- Secondary MACD Lines: Purple lines showing higher timeframe MACD
- Histogram MA: Orange line showing histogram moving average
- Histogram BB: Blue bands around histogram showing extreme zones
- StochMACD Lines: %K and %D lines with overbought/oversold thresholds
- Regression Forecast: Dotted blue lines extending forward with optional confidence bands
Signal Priority and Interpretation
Signals are generated independently and can occur simultaneously. Higher-priority signals generally indicate stronger setups:
1. MACD Cross with Multiple Filters - Highest priority: Requires MACD crossover plus all enabled filters (histogram, signal strength, cross quality) and secondary timeframe confirmation if enabled. These are the most reliable signals.
2. Zero-Line Cross - High priority: Indicates momentum shift. Can provide early warning signals before MACD crosses the signal line.
3. Divergence Signals - Medium-High priority: Pivot-based divergence is more reliable than simple divergence. Hidden divergence indicates continuation rather than reversal.
4. MACD Cross with Basic Filters - Medium priority: MACD crosses signal line with basic histogram filter. Less reliable alone but useful when combined with other confirmations.
Best practice: Wait for multiple confirmations. For example, a MACD crossover combined with divergence, volume confirmation, and secondary timeframe alignment provides the strongest setup.
Chart Requirements
For proper script functionality and compliance with TradingView requirements, ensure your chart displays:
- Symbol name: The trading pair or instrument name should be visible
- Timeframe: The chart timeframe should be clearly displayed
- Script name: "Ultimate MACD [captainua]" should be visible in the indicator title
These elements help traders understand what they're viewing and ensure proper script identification. The script automatically includes this information in the indicator title and chart labels.
Performance Considerations
The script is optimized for performance:
- Calculations use efficient Pine Script functions (ta.ema, ta.sma, etc.) which are optimized by TradingView
- Conditional execution: Features only calculate when enabled
- Label management: Old labels are automatically deleted to prevent accumulation
- Array management: Divergence label arrays are limited to prevent memory accumulation
The script should perform well on all timeframes. On very long historical data with many enabled features, performance may be slightly slower, but it remains usable.
Known Limitations and Considerations
- Dynamic OB/OS levels can vary significantly based on recent MACD volatility. In very volatile markets, levels may be wider; in calm markets, they may be narrower.
- Volume confirmation requires sufficient historical volume data. On new instruments or very short timeframes, volume calculations may be less reliable.
- Higher timeframe MACD uses request.security() which may have slight delays on some data feeds.
- Stochastic MACD requires the histogram to have sufficient history. Very short periods on new charts may produce less reliable StochMACD values initially.
- Divergence detection requires sufficient historical data to identify pivot points. Very short lookback periods may produce false positives.
Practical Use Cases
The indicator can be configured for different trading styles and timeframes:
Swing Trading:
Use MACD(12,26,9) with secondary timeframe confirmation. Enable divergence detection. Use signal strength filter (threshold 50+) and cross quality filter (threshold 50+) for higher-quality signals. Enable histogram analysis tools for additional context.
Day Trading:
Use MACD(8,17,7) or use "Day Trading" preset with minimal histogram smoothing for faster signals. Enable zero-line cross alerts for early signals. Use volume confirmation with threshold 1.2-1.5. Enable histogram MA for momentum tracking.
Trend Following:
Use MACD(12,26,9) or longer periods (15,30,12) for smoother signals. Enable secondary timeframe confirmation for trend alignment. Hidden divergence signals are useful for trend continuation entries. Use cross quality filter to identify high-quality crossovers.
Reversal Trading:
Focus on divergence detection (pivot-based for accuracy) combined with zero-line crosses. Enable volume confirmation. Use histogram Bollinger Bands to identify extreme histogram zones. Enable StochMACD for overbought/oversold identification.
Multi-Timeframe Analysis:
Enable secondary timeframe MACD to see context from larger timeframes. For example, use daily MACD on hourly charts to understand the larger trend context. Enable secondary confirmation to require higher timeframe alignment for signals.
Practical Tips and Best Practices
Getting Started:
Start with default settings and observe MACD behavior. The default configuration (MACD 12,26,9 with EMA) is balanced and works well across different markets. After observing behavior, customize settings to match your trading style. Consider using configuration presets for quick setup.
Reducing Repainting:
All signals are based on confirmed bars, minimizing repainting. The script uses confirmed bar data for all calculations to ensure backtesting accuracy.
Signal Quality:
MACD crosses with multiple filters provide the highest-quality signals because they require alignment across multiple indicators. These signals have lower frequency but higher reliability. Use signal strength scores to identify the strongest signals (70+). Use cross quality scores to identify high-quality crossovers (70+).
Filter Combinations:
Start with histogram filter for basic momentum alignment, then add signal strength filter for moderate signals, then cross quality filter for high-quality crossovers. Combining all filters significantly reduces false signals but also reduces signal frequency. Find your balance based on your risk tolerance.
Volume Filtering:
Set volume threshold to 1.0 (default, effectively disabled) or lower to effectively disable volume filtering if you trade instruments with unreliable volume data or want to test without volume confirmation. Standard confirmation uses 1.2-1.5 threshold.
MACD Period Selection:
Standard MACD(12,26,9) provides balanced signals suitable for most trading. Shorter periods (8,17,7) for faster signals, longer (15,30,12) for smoother signals. Adjust based on your timeframe and trading style. Consider using configuration presets for optimized settings.
Moving Average Type:
EMA provides balanced responsiveness with smoothness. RMA is smoother and less responsive. WMA gives more weight to recent prices. SMA gives equal weight to all periods. Choose based on your preference for responsiveness vs. smoothness.
Divergence:
Pivot-based divergence is more reliable than simple divergence because it uses actual pivot points. Hidden divergence indicates continuation rather than reversal, useful for trend-following strategies. Adjust pivot lookback parameters to control sensitivity.
Dynamic Thresholds:
Dynamic OB/OS thresholds automatically adapt to volatility. In volatile markets, thresholds widen; in calm markets, they narrow. Adjust the multipliers to fine-tune sensitivity. Enable OB/OS background colors for visual indication.
Zero-Line Crosses:
Zero-line crosses indicate momentum shifts and can provide early warning signals before MACD crosses the signal line. Enable alerts for zero-line crosses to catch these early signals.
Alert Management:
Enable alert cooldown (default enabled, 5 bars) to prevent alert spam. Use alert type filter to only evaluate specific alert types. Signal debounce (default enabled, 3 bars) prevents duplicate MACD cross signals during choppy markets.
Technical Specifications
- Pine Script Version: v6
- Indicator Type: Non-overlay (displays in separate panel below price chart)
- Repainting Behavior: Minimal - all signals are based on confirmed bars, ensuring accurate backtesting results
- Performance: Optimized with conditional execution. Features only calculate when enabled.
- Compatibility: Works on all timeframes (1 minute to 1 month) and all instruments (stocks, forex, crypto, futures, etc.)
- Edge Case Handling: All calculations include safety checks for division by zero, NA values, and boundary conditions. Alert cooldowns and signal debounce handle edge cases where conditions never occurred or values are NA.
Technical Notes
- All MACD values respect percentage mode conversion when enabled
- Volume confirmation uses cached volume SMA for performance
- Label arrays (divergence) are automatically limited to prevent memory accumulation
- Background coloring: OB/OS backgrounds are drawn on top of main background to ensure visibility
- All calculations are optimized with conditional execution - features only calculate when enabled (performance optimization)
- Signal strength calculation combines multiple factors into a single score for easy filtering
- Cross quality calculation rates crossover quality based on angle, volume, and distance from zero
- Secondary timeframe MACD uses request.security() for higher timeframe data access
- Histogram analysis features (Bollinger Bands, MA, StochMACD) provide additional context beyond basic MACD signals
- Statistics table dynamically adjusts to show only enabled features, keeping it clean and relevant
- Divergence detection uses MACD line (not histogram) for more reliable signals
- Configuration presets automatically optimize MACD parameters for different trading styles
- Smart label placement: Labels appear on current bar at confirmation, using strength from tracked extreme point
- Label spacing uses effective distance (base distance × spacing multiplier) for better distribution
- Zero line polarity enforcement ensures Buy labels only appear when tracked extreme MACD < 0, Sell labels only when tracked extreme MACD > 0
- Label finalization requires MACD exit from OB/OS zone, sufficient bars passed, and recovery/decline percentage confirmation
- Strength-based filtering automatically compares and keeps only the strongest label when multiple signals are close together
- Enhanced visualization: Line outlines drawn behind main lines for superior visibility (black default, configurable)
- Enhanced visualization: Fill between MACD and zero line provides instant visual feedback (green above, red below)
- Enhanced visualization: Fill between OB/OS thresholds highlights neutral zone when dynamic levels are active
- Custom chart background overrides background mode when enabled, allowing theme-consistent indicator panels
Overview
This indicator combines traditional MACD calculations with advanced features including divergence detection, volume analysis, histogram analysis tools, regression forecasting, strong top/bottom detection, and multi-timeframe confirmation to provide a comprehensive MACD-based trading system. The script calculates MACD using configurable moving average types (EMA, SMA, RMA, WMA) and applies various smoothing methods to reduce noise while maintaining responsiveness. The combination of these features creates a multi-layered confirmation system that reduces false signals by requiring alignment across multiple indicators and timeframes.
Core Calculations
MACD Calculation:
The script calculates MACD using the standard formula: MACD Line = Fast MA - Slow MA, Signal Line = Moving Average of MACD Line, Histogram = MACD Line - Signal Line. The default parameters are Fast=12, Slow=26, Signal=9, matching the traditional MACD settings. The script supports four moving average types:
- EMA (Exponential Moving Average): Standard and most responsive, default choice
- SMA (Simple Moving Average): Equal weight to all periods
- RMA (Wilder's Moving Average): Smoother, less responsive
- WMA (Weighted Moving Average): Recent prices weighted more heavily
The price source can be configured as Close (standard), Open, High, Low, HL2, HLC3, or OHLC4. Alternative sources provide different sensitivity characteristics for various trading strategies.
Configuration Presets:
The script includes trading style presets that automatically configure MACD parameters:
- Scalping: Fast/Responsive settings (8,18,6 with minimal smoothing)
- Day Trading: Balanced settings (10,22,7 with minimal smoothing)
- Swing Trading: Standard settings (12,26,9 with moderate smoothing)
- Position Trading: Smooth/Conservative settings (15,35,12 with higher smoothing)
- Custom: Full manual control over all parameters
Histogram Smoothing:
The histogram can be smoothed using EMA to reduce noise and filter minor fluctuations. Smoothing length of 1 = raw histogram (no smoothing), higher values (3-5) = smoother histogram. Increased smoothing reduces noise but may delay signals slightly.
Percentage Mode:
MACD values can be converted to percentage of price (MACD/Close*100) for cross-instrument comparison. This is useful when comparing MACD signals across instruments with different price levels (e.g., BTC vs ETH). The percentage mode normalizes MACD values, making them comparable regardless of instrument price.
MACD Scale Factor:
A scale factor multiplier (default 1.0) allows adjusting MACD display size for better visibility. Use 0.3-0.5 if MACD appears too compressed, or 2.0-3.0 if too small.
Dynamic Overbought/Oversold Levels:
Overbought and oversold levels are calculated dynamically based on MACD's mean and standard deviation over a lookback period. The formula: OB = MACD Mean + (StdDev × OB Multiplier), OS = MACD Mean - (StdDev × OS Multiplier). This adapts to current market conditions, widening in volatile markets and narrowing in calm markets. The lookback period (default 20) controls how quickly the levels adapt: longer periods (30-50) = more stable levels, shorter (10-15) = more responsive.
OB/OS Background Coloring:
Optional background coloring can highlight the entire panel when MACD enters overbought or oversold territory, providing prominent visual indication of extreme conditions. The background colors are drawn on top of the main background to ensure visibility.
Divergence Detection
Regular Divergence:
The script uses the MACD line (not histogram) for divergence detection, which provides more reliable signals. Bullish divergence: Price makes a lower low while MACD line makes a higher low. Bearish divergence: Price makes a higher high while MACD line makes a lower high. Divergences often precede reversals and are powerful reversal signals.
Pivot-Based Divergence:
The divergence detection uses actual pivot points (pivotlow/pivothigh) instead of simple lowest/highest comparisons. This provides more accurate divergence detection by identifying significant pivot lows/highs in both price and MACD line. The pivot-based method compares two recent pivot points: for bullish divergence, price makes a lower low while MACD makes a higher low at the pivot points. This method reduces false divergences by requiring actual pivot points rather than just any low/high within a period.
The pivot lookback parameters (left and right) control how many bars on each side of a pivot are required for confirmation. Higher values = more conservative pivot detection.
Hidden Divergence:
Continuation patterns that signal trend continuation rather than reversal. Bullish hidden divergence: Price makes a higher low but MACD makes a lower low. Bearish hidden divergence: Price makes a lower high but MACD makes a higher high. These patterns indicate the trend is likely to continue in the current direction.
Zero-Line Filter:
The "Don't Touch Zero Line" option ensures divergences occur in proper context: for bullish divergence, MACD must stay below zero; for bearish divergence, MACD must stay above zero. This filters out divergences that occur in neutral zones.
Range Filtering:
Minimum and maximum lookback ranges control the time window between pivots to consider for divergence. This helps filter out divergences that are too close together (noise) or too far apart (less relevant).
Volume Confirmation System
Volume threshold filtering requires current volume to exceed the volume SMA multiplied by the threshold factor. The formula: Volume Confirmed = Volume > (Volume SMA × Threshold). If the threshold is set to 1.0 or lower, volume confirmation is effectively disabled (always returns true). This allows you to use the indicator without volume filtering if desired. Volume confirmation significantly increases divergence and signal reliability.
Volume Climax and Dry-Up Detection:
The script can mark bars with extremely high volume (volume climax) or extremely low volume (volume dry-up). Volume climax indicates potential reversal points or strong momentum continuation. Volume dry-up indicates low participation and may produce unreliable signals. These markers use standard deviation multipliers to identify extreme volume conditions.
Zero-Line Cross Detection
MACD zero-line crosses indicate momentum shifts: above zero = bullish momentum, below zero = bearish momentum. The script includes alert conditions for zero-line crosses with cooldown protection to prevent alert spam. Zero-line crosses can provide early warning signals before MACD crosses the signal line.
Histogram Analysis Tools
Histogram Moving Average:
A moving average applied to the histogram itself helps identify histogram trend direction and acts as a signal line for histogram movements. Supports EMA, SMA, RMA, and WMA types. Useful for identifying when histogram momentum is strengthening or weakening.
Histogram Bollinger Bands:
Bollinger Bands are applied to the MACD histogram instead of price. The calculation: Basis = SMA(Histogram, Period), StdDev = stdev(Histogram, Period), Upper = Basis + (StdDev × Deviation Multiplier), Lower = Basis - (StdDev × Deviation Multiplier). This creates dynamic zones around the histogram that adapt to histogram volatility. When the histogram touches or exceeds the bands, it indicates extreme conditions relative to recent histogram behavior.
Stochastic MACD (StochMACD):
Stochastic MACD applies the Stochastic oscillator formula to the MACD histogram instead of price. This normalizes the histogram to a 0-100 scale, making it easier to identify overbought/oversold conditions on the histogram itself. The calculation: %K = ((Histogram - Lowest Histogram) / (Highest Histogram - Lowest Histogram)) × 100. %K is smoothed, and %D is calculated as the moving average of smoothed %K. Standard thresholds are 80 (overbought) and 20 (oversold).
Regression Forecasting
The script includes advanced regression forecasting that predicts future MACD values using mathematical models. This helps anticipate potential MACD movements and provides forward-looking context for trading decisions.
Regression Types:
- Linear: Simple trend line (y = mx + b) - fastest, works well for steady trends
- Polynomial: Quadratic curve (y = ax² + bx + c) - captures curvature in MACD movement
- Exponential Smoothing: Weighted average with more weight on recent values - responsive to recent changes
- Moving Average: Uses difference between short and long MA to estimate trend - stable and smooth
Forecast Horizon:
Number of bars to forecast ahead (default 5, max 50 for linear/MA, max 20 for polynomial due to performance). Longer horizons predict further ahead but may be less accurate.
Confidence Bands:
Optional upper/lower bands around forecast show prediction uncertainty based on forecast error (standard deviation of prediction vs actual). Wider bands = higher uncertainty. The confidence level multiplier (default 1.5) controls band width.
Forecast Display:
Forecast appears as dotted lines extending forward from current bar, with optional confidence bands. All forecast values respect percentage mode and scale factor settings.
Strong Top/Bottom Signals
The script detects strong recovery from extreme MACD levels, generating "sBottom" and "sTop" signals. These identify significant reversal potential when MACD recovers substantially from overbought/oversold extremes.
Strong Bottom (sBottom):
Triggered when:
1. MACD was at or near its lowest point in the bottom period (default 10 bars)
2. MACD was in or near the oversold zone
3. MACD has recovered by at least the threshold amount (default 0.5) from the lowest point
4. Recovery persists for confirmation bars (default 2 consecutive bars)
5. MACD has moved out of the oversold zone
6. Volume is above average
7. All enabled filters pass
8. Minimum bars have passed since last signal (reset period, default 5 bars)
Strong Top (sTop):
Triggered when:
1. MACD was at or near its highest point in the top period (default 7 bars)
2. MACD was in or near the overbought zone
3. MACD has declined by at least the threshold amount (default 0.5) from the highest point
4. Decline persists for confirmation bars (default 2 consecutive bars)
5. MACD has moved out of the overbought zone
6. Volume is above average
7. All enabled filters pass
8. Minimum bars have passed since last signal (reset period, default 5 bars)
Label Placement:
sTop/sBottom labels appear on the historical bar where the actual extreme occurred (not on current bar), showing the exact MACD value at that extreme. Labels respect the unified distance checking system to prevent overlaps with Buy/Sell Strength labels.
Signal Strength Calculation
The script calculates a composite signal strength score (0-100) based on multiple factors:
- MACD distance from signal line (0-50 points): Larger separation indicates stronger signal
- Volume confirmation (0-15 points): Volume above average adds points
- Secondary timeframe alignment (0-15 points): Higher timeframe agreement adds points
- Distance from zero line (0-20 points): Closer to zero can indicate stronger reversal potential
Higher scores (70+) indicate stronger, more reliable signals. The signal strength is displayed in the statistics table and can be used as a filter to only accept signals above a threshold.
Smart Label Placement System
The script includes an advanced label placement system that tracks MACD extremes and places Buy/Sell Strength labels at optimal locations:
Label Placement Algorithm:
- Labels appear on the current bar at confirmation (not on historical extreme bars), ensuring they're visible when the signal is confirmed
- The system tracks pending signals when MACD enters OB/OS zones or crosses the signal line
- During tracking, the system continuously searches for the true extreme (lowest MACD for buys, highest MACD for sells) within a configurable historical lookback period
- Labels are only finalized when: (1) MACD exits the OB/OS zone, (2) sufficient bars have passed (2x minimum distance), (3) MACD has recovered/declined by a configurable percentage from the extreme (default 15%), and (4) tracking has stopped (no better extreme found)
Label Spacing and Overlap Prevention:
- Minimum Bars Between Labels: Base distance requirement (default 5 bars)
- Label Spacing Multiplier: Scales the base distance (default 1.5x) for better distribution. Higher values = more spacing between labels
- Effective distance = Base Distance × Spacing Multiplier (e.g., 5 × 1.5 = 7.5 bars minimum)
- Unified distance checking prevents overlaps between all label types (Buy Strength, Sell Strength, sTop, sBottom)
Strength-Based Filtering:
- Label Strength Minimum (%): Only labels with strength at or above this threshold are displayed (default 75%)
- When multiple potential labels are close together, the system automatically compares strengths and keeps only the strongest one
- This ensures only the most significant signals are displayed, reducing chart clutter
Zero Line Polarity Enforcement:
- Enforce Zero Line Polarity (default enabled): Ensures labels follow traditional MACD interpretation
- Buy Strength labels only appear when the tracked extreme MACD value was below zero (negative territory)
- Sell Strength labels only appear when the tracked extreme MACD value was above zero (positive territory)
- This prevents counter-intuitive labels (e.g., Buy labels above zero line) and aligns with standard MACD trading principles
Recovery/Decline Confirmation:
- Recovery/Decline Confirm (%): Percent move away from the extreme required before finalizing (default 15%)
- For Buy labels: MACD must recover by at least this percentage from the tracked bottom
- For Sell labels: MACD must decline by at least this percentage from the tracked top
- Higher values = more confirmation required, fewer but more reliable labels
Historical Lookback:
- Historical Lookback for Label Placement: Number of bars to search for true extremes (default 20)
- The system searches within this period to find the actual lowest/highest MACD value
- Higher values analyze more history but may be slower; lower values are faster but may miss some extremes
Cross Quality Score
The script calculates a MACD cross quality score (0-100) that rates crossover quality based on:
- Cross angle (0-50 points): Steeper crosses = stronger signals
- Volume confirmation (0-25 points): Volume above average adds points
- Distance from zero line (0-25 points): Crosses near zero line are stronger
This score helps identify high-quality crossovers and can be used as a filter to only accept signals meeting minimum quality threshold.
Filtering System
Histogram Filter:
Requires histogram to be above zero for buy signals, below zero for sell signals. Ensures momentum alignment before generating signals.
Signal Strength Filter:
Requires minimum signal strength score for signals. Higher threshold = only strongest signals pass. This combines multiple confirmation factors into a single filter.
Cross Quality Filter:
Requires minimum cross quality score for signals. Rates crossover quality based on angle, volume, momentum, and distance from zero. Only signals meeting minimum quality threshold will be generated.
All filters use the pattern: filterResult = not filterEnabled OR conditionMet. This means if a filter is disabled, it always passes (returns true). Filters can be combined, and all must pass for a signal to fire.
Multi-Timeframe Analysis
The script can display MACD from a secondary (higher) timeframe and use it for confirmation. When secondary timeframe confirmation is enabled, signals require the higher timeframe MACD to align (bullish/bearish) with the signal direction. This ensures signals align with the larger trend context, reducing counter-trend trades.
Secondary Timeframe MACD:
The secondary timeframe MACD uses the same calculation parameters (fast, slow, signal, MA type) as the main MACD but from a higher timeframe. This provides context for the current timeframe's MACD position relative to the larger trend. The secondary MACD lines are displayed on the chart when enabled.
Noise Filtering
Noise filtering hides small histogram movements below a threshold. This helps focus on significant moves and reduces chart clutter. When enabled, only histogram movements above the threshold are displayed. Typical threshold values are 0.1-0.5 for most instruments, depending on the instrument's price range and volatility.
Signal Debounce
Signal debounce prevents duplicate MACD cross signals within a short time period. Useful when MACD crosses back and forth quickly, creating multiple signals. Debounce ensures only one signal per period, reducing signal spam during choppy markets. This is separate from alert cooldown, which applies to all alert types.
Background Color Modes
The script offers three background color modes:
- Dynamic: Full MACD heatmap based on OB/OS conditions, confidence, and momentum. Provides rich visual feedback.
- Monotone: Soft neutral background but still allows overlays (OB/OS zones). Keeps the chart clean without overpowering candles.
- Off: No MACD background (only overlays and plots). Maximum chart cleanliness.
When OB/OS background colors are enabled, they are drawn on top of the main background to ensure visibility.
Statistics Table
A real-time statistics table displays current MACD values, signal strength, distance from zero line, secondary timeframe alignment, volume confirmation status, and all active filter statuses. The table dynamically adjusts to show only enabled features, keeping it clean and relevant. The table position can be configured (Top Left, Top Right, Bottom Left, Bottom Right).
Performance Statistics Table
An optional performance statistics table shows comprehensive filter diagnostics:
- Total buy/sell signals (raw crossover count before filters)
- Filtered buy/sell signals (signals that passed all filters)
- Overall pass rates (percentage of signals that passed filters)
- Rejected signals count
- Filter-by-filter rejection diagnostics showing which filters rejected how many signals
This table helps optimize filter settings by showing which filters are most restrictive and how they impact signal frequency. The diagnostics format shows rejections as "X B / Y S" (X buy signals rejected, Y sell signals rejected) or "Disabled" if the filter is not active.
Alert System
The script includes separate alert conditions for each signal type:
- MACD Cross: MACD line crosses above/below Signal line (with or without secondary confirmation)
- Zero-Line Cross: MACD crosses above/below zero
- Divergence: Regular and hidden divergence detections
- Secondary Timeframe: Higher timeframe MACD crosses
- Histogram MA Cross: Histogram crosses above/below its moving average
- Histogram Zero Cross: Histogram crosses above/below zero
- StochMACD: StochMACD overbought/oversold entries and %K/%D crosses
- Histogram BB: Histogram touches/breaks Bollinger Bands
- Volume Events: Volume climax and dry-up detections
- OB/OS: MACD entry/exit from overbought/oversold zones
- Strong Top/Bottom: sTop and sBottom signal detections
Each alert type has its own cooldown system to prevent alert spam. The cooldown requires a minimum number of bars between alerts of the same type, reducing duplicate alerts during volatile periods. Alert types can be filtered to only evaluate specific alert types (All, MACD Cross, Zero Line, Divergence, Secondary Timeframe, Histogram MA, Histogram Zero, StochMACD, Histogram BB, Volume Events, OB/OS, Strong Top/Bottom).
How Components Work Together
MACD crossovers provide the primary signal when the MACD line crosses the Signal line. Zero-line crosses indicate momentum shifts and can provide early warning signals. Divergences identify potential reversals before they occur.
Volume confirmation ensures signals occur with sufficient market participation, filtering out low-volume false breakouts. Histogram analysis tools (MA, Bollinger Bands, StochMACD) provide additional context for signal reliability and identify significant histogram zones.
Signal strength combines multiple confirmation factors into a single score, making it easy to filter for only the strongest signals. Cross quality score rates crossover quality to identify high-quality setups. Multi-timeframe confirmation ensures signals align with higher timeframe trends, reducing counter-trend trades.
Usage Instructions
Getting Started:
The default configuration shows MACD(12,26,9) with standard EMA calculations. Start with default settings and observe behavior, then customize settings to match your trading style. You can use configuration presets for quick setup based on your trading style.
Customizing MACD Parameters:
Adjust Fast Length (default 12), Slow Length (default 26), and Signal Length (default 9) based on your trading timeframe. Shorter periods (8,17,7) for faster signals, longer (15,30,12) for smoother signals. You can change the moving average type: EMA for responsiveness, RMA for smoothness, WMA for recent price emphasis.
Price Source Selection:
Choose Close (standard), or alternative sources (HL2, HLC3, OHLC4) for different sensitivity. HL2 uses the midpoint of the high-low range, HLC3 and OHLC4 incorporate more price information.
Histogram Smoothing:
Set smoothing to 1 for raw histogram (no smoothing), or increase (3-5) for smoother histogram that reduces noise. Higher smoothing reduces false signals but may delay signals slightly.
Percentage Mode:
Enable percentage mode when comparing MACD across instruments with different price levels. This normalizes MACD values, making them directly comparable.
Dynamic OB/OS Levels:
The dynamic thresholds automatically adapt to volatility. Adjust the multipliers (default 1.5) to fine-tune sensitivity: higher values (2.0-3.0) = more extreme thresholds (fewer signals), lower (1.0-1.5) = more frequent signals. Adjust the lookback period to control how quickly levels adapt. Enable OB/OS background colors for visual indication of extreme conditions.
Volume Confirmation:
Set volume threshold to 1.0 (default, effectively disabled) or higher (1.2-1.5) for standard confirmation. Higher values require more volume for confirmation. Set to 0.1 to completely disable volume filtering.
Filters:
Enable filters gradually to find your preferred balance. Start with histogram filter for basic momentum alignment, then add signal strength filter (threshold 50+) for moderate signals, then cross quality filter (threshold 50+) for high-quality crossovers. Combine filters for highest-quality signals but expect fewer signals.
Divergence:
Enable divergence detection and adjust pivot lookback parameters. Pivot-based divergence provides more accurate detection using actual pivot points. Hidden divergence is useful for trend-following strategies. Adjust range parameters to filter divergences by time window.
Zero-Line Crosses:
Zero-line cross alerts are automatically available when alerts are enabled. These provide early warning signals for momentum shifts.
Histogram Analysis Tools:
Enable Histogram Moving Average to see histogram trend direction. Enable Histogram Bollinger Bands to identify extreme histogram zones. Enable Stochastic MACD to normalize histogram to 0-100 scale for overbought/oversold identification.
Multi-Timeframe:
Enable secondary timeframe MACD to see higher timeframe context. Enable secondary confirmation to require higher timeframe alignment for signals.
Signal Strength:
Signal strength is automatically calculated and displayed in the statistics table. Use signal strength filter to only accept signals above a threshold (e.g., 50 for moderate, 70+ for strong signals only).
Smart Label Placement:
Configure label placement settings to control label appearance and quality:
- Label Strength Minimum (%): Set threshold (default 75%) to show only strong signals. Higher = fewer, stronger labels
- Label Spacing Multiplier: Adjust spacing (default 1.5x) for better distribution. Higher = more spacing between labels
- Recovery/Decline Confirm (%): Set confirmation requirement (default 15%). Higher = more confirmation, fewer labels
- Enforce Zero Line Polarity: Enable (default) to ensure Buy labels only appear when tracked extreme was below zero, Sell labels only when above zero
- Historical Lookback: Adjust search period (default 20 bars) for finding true extremes. Higher = more history analyzed
Cross Quality:
Cross quality score is automatically calculated for crossovers. Use cross quality filter to only accept high-quality crossovers (threshold 50+ for moderate, 70+ for high quality).
Alerts:
Set up alerts for your preferred signal types. Enable alert cooldown (default enabled, 5 bars) to prevent alert spam. Use alert type filter to only evaluate specific alert types (All, MACD Cross, Zero Line, Divergence, Secondary Timeframe, Histogram MA, Histogram Zero, StochMACD, Histogram BB, Volume Events, OB/OS, Strong Top/Bottom). Each signal type has its own alert condition, so you can be selective about which signals trigger alerts.
Visual Elements and Signal Markers
The script uses various visual markers to indicate signals and conditions:
- MACD Line: Green when above signal (bullish), red when below (bearish) if dynamic colors enabled. Optional black outline for enhanced visibility
- Signal Line: Orange line with optional black outline for enhanced visibility
- Histogram: Color-coded based on direction and momentum (green for bullish rising, lime for bullish falling, red for bearish falling, orange for bearish rising)
- Zero Line: Horizontal reference line at MACD = 0
- Fill to Zero: Green/red semi-transparent fill between MACD line and zero line showing bullish/bearish territory
- Fill Between OB/OS: Blue semi-transparent fill between overbought/oversold thresholds highlighting neutral zone
- OB/OS Background Colors: Background coloring when MACD enters overbought/oversold zones
- Background Colors: Dynamic or monotone backgrounds indicating MACD state, or custom chart background
- Divergence Labels: "🐂" for bullish, "🐻" for bearish, "H Bull" for hidden bullish, "H Bear" for hidden bearish
- Divergence Lines: Colored lines connecting pivot points when divergences are detected
- Volume Climax Markers: ⚡ symbol for extremely high volume
- Volume Dry-Up Markers: 💧 symbol for extremely low volume
- Buy/Sell Strength Labels: Show signal strength percentage (e.g., "Buy Strength: 75%")
- Strong Top/Bottom Labels: "sTop" and "sBottom" for extreme level recoveries
- Secondary MACD Lines: Purple lines showing higher timeframe MACD
- Histogram MA: Orange line showing histogram moving average
- Histogram BB: Blue bands around histogram showing extreme zones
- StochMACD Lines: %K and %D lines with overbought/oversold thresholds
- Regression Forecast: Dotted blue lines extending forward with optional confidence bands
Signal Priority and Interpretation
Signals are generated independently and can occur simultaneously. Higher-priority signals generally indicate stronger setups:
1. MACD Cross with Multiple Filters - Highest priority: Requires MACD crossover plus all enabled filters (histogram, signal strength, cross quality) and secondary timeframe confirmation if enabled. These are the most reliable signals.
2. Zero-Line Cross - High priority: Indicates momentum shift. Can provide early warning signals before MACD crosses the signal line.
3. Divergence Signals - Medium-High priority: Pivot-based divergence is more reliable than simple divergence. Hidden divergence indicates continuation rather than reversal.
4. MACD Cross with Basic Filters - Medium priority: MACD crosses signal line with basic histogram filter. Less reliable alone but useful when combined with other confirmations.
Best practice: Wait for multiple confirmations. For example, a MACD crossover combined with divergence, volume confirmation, and secondary timeframe alignment provides the strongest setup.
Chart Requirements
For proper script functionality and compliance with TradingView requirements, ensure your chart displays:
- Symbol name: The trading pair or instrument name should be visible
- Timeframe: The chart timeframe should be clearly displayed
- Script name: "Ultimate MACD [captainua]" should be visible in the indicator title
These elements help traders understand what they're viewing and ensure proper script identification. The script automatically includes this information in the indicator title and chart labels.
Performance Considerations
The script is optimized for performance:
- Calculations use efficient Pine Script functions (ta.ema, ta.sma, etc.) which are optimized by TradingView
- Conditional execution: Features only calculate when enabled
- Label management: Old labels are automatically deleted to prevent accumulation
- Array management: Divergence label arrays are limited to prevent memory accumulation
The script should perform well on all timeframes. On very long historical data with many enabled features, performance may be slightly slower, but it remains usable.
Known Limitations and Considerations
- Dynamic OB/OS levels can vary significantly based on recent MACD volatility. In very volatile markets, levels may be wider; in calm markets, they may be narrower.
- Volume confirmation requires sufficient historical volume data. On new instruments or very short timeframes, volume calculations may be less reliable.
- Higher timeframe MACD uses request.security() which may have slight delays on some data feeds.
- Stochastic MACD requires the histogram to have sufficient history. Very short periods on new charts may produce less reliable StochMACD values initially.
- Divergence detection requires sufficient historical data to identify pivot points. Very short lookback periods may produce false positives.
Practical Use Cases
The indicator can be configured for different trading styles and timeframes:
Swing Trading:
Use MACD(12,26,9) with secondary timeframe confirmation. Enable divergence detection. Use signal strength filter (threshold 50+) and cross quality filter (threshold 50+) for higher-quality signals. Enable histogram analysis tools for additional context.
Day Trading:
Use MACD(8,17,7) or use "Day Trading" preset with minimal histogram smoothing for faster signals. Enable zero-line cross alerts for early signals. Use volume confirmation with threshold 1.2-1.5. Enable histogram MA for momentum tracking.
Trend Following:
Use MACD(12,26,9) or longer periods (15,30,12) for smoother signals. Enable secondary timeframe confirmation for trend alignment. Hidden divergence signals are useful for trend continuation entries. Use cross quality filter to identify high-quality crossovers.
Reversal Trading:
Focus on divergence detection (pivot-based for accuracy) combined with zero-line crosses. Enable volume confirmation. Use histogram Bollinger Bands to identify extreme histogram zones. Enable StochMACD for overbought/oversold identification.
Multi-Timeframe Analysis:
Enable secondary timeframe MACD to see context from larger timeframes. For example, use daily MACD on hourly charts to understand the larger trend context. Enable secondary confirmation to require higher timeframe alignment for signals.
Practical Tips and Best Practices
Getting Started:
Start with default settings and observe MACD behavior. The default configuration (MACD 12,26,9 with EMA) is balanced and works well across different markets. After observing behavior, customize settings to match your trading style. Consider using configuration presets for quick setup.
Reducing Repainting:
All signals are based on confirmed bars, minimizing repainting. The script uses confirmed bar data for all calculations to ensure backtesting accuracy.
Signal Quality:
MACD crosses with multiple filters provide the highest-quality signals because they require alignment across multiple indicators. These signals have lower frequency but higher reliability. Use signal strength scores to identify the strongest signals (70+). Use cross quality scores to identify high-quality crossovers (70+).
Filter Combinations:
Start with histogram filter for basic momentum alignment, then add signal strength filter for moderate signals, then cross quality filter for high-quality crossovers. Combining all filters significantly reduces false signals but also reduces signal frequency. Find your balance based on your risk tolerance.
Volume Filtering:
Set volume threshold to 1.0 (default, effectively disabled) or lower to effectively disable volume filtering if you trade instruments with unreliable volume data or want to test without volume confirmation. Standard confirmation uses 1.2-1.5 threshold.
MACD Period Selection:
Standard MACD(12,26,9) provides balanced signals suitable for most trading. Shorter periods (8,17,7) for faster signals, longer (15,30,12) for smoother signals. Adjust based on your timeframe and trading style. Consider using configuration presets for optimized settings.
Moving Average Type:
EMA provides balanced responsiveness with smoothness. RMA is smoother and less responsive. WMA gives more weight to recent prices. SMA gives equal weight to all periods. Choose based on your preference for responsiveness vs. smoothness.
Divergence:
Pivot-based divergence is more reliable than simple divergence because it uses actual pivot points. Hidden divergence indicates continuation rather than reversal, useful for trend-following strategies. Adjust pivot lookback parameters to control sensitivity.
Dynamic Thresholds:
Dynamic OB/OS thresholds automatically adapt to volatility. In volatile markets, thresholds widen; in calm markets, they narrow. Adjust the multipliers to fine-tune sensitivity. Enable OB/OS background colors for visual indication.
Zero-Line Crosses:
Zero-line crosses indicate momentum shifts and can provide early warning signals before MACD crosses the signal line. Enable alerts for zero-line crosses to catch these early signals.
Alert Management:
Enable alert cooldown (default enabled, 5 bars) to prevent alert spam. Use alert type filter to only evaluate specific alert types. Signal debounce (default enabled, 3 bars) prevents duplicate MACD cross signals during choppy markets.
Technical Specifications
- Pine Script Version: v6
- Indicator Type: Non-overlay (displays in separate panel below price chart)
- Repainting Behavior: Minimal - all signals are based on confirmed bars, ensuring accurate backtesting results
- Performance: Optimized with conditional execution. Features only calculate when enabled.
- Compatibility: Works on all timeframes (1 minute to 1 month) and all instruments (stocks, forex, crypto, futures, etc.)
- Edge Case Handling: All calculations include safety checks for division by zero, NA values, and boundary conditions. Alert cooldowns and signal debounce handle edge cases where conditions never occurred or values are NA.
Technical Notes
- All MACD values respect percentage mode conversion when enabled
- Volume confirmation uses cached volume SMA for performance
- Label arrays (divergence) are automatically limited to prevent memory accumulation
- Background coloring: OB/OS backgrounds are drawn on top of main background to ensure visibility
- All calculations are optimized with conditional execution - features only calculate when enabled (performance optimization)
- Signal strength calculation combines multiple factors into a single score for easy filtering
- Cross quality calculation rates crossover quality based on angle, volume, and distance from zero
- Secondary timeframe MACD uses request.security() for higher timeframe data access
- Histogram analysis features (Bollinger Bands, MA, StochMACD) provide additional context beyond basic MACD signals
- Statistics table dynamically adjusts to show only enabled features, keeping it clean and relevant
- Divergence detection uses MACD line (not histogram) for more reliable signals
- Configuration presets automatically optimize MACD parameters for different trading styles
- Smart label placement: Labels appear on current bar at confirmation, using strength from tracked extreme point
- Label spacing uses effective distance (base distance × spacing multiplier) for better distribution
- Zero line polarity enforcement ensures Buy labels only appear when tracked extreme MACD < 0, Sell labels only when tracked extreme MACD > 0
- Label finalization requires MACD exit from OB/OS zone, sufficient bars passed, and recovery/decline percentage confirmation
- Strength-based filtering automatically compares and keeps only the strongest label when multiple signals are close together
- Enhanced visualization: Line outlines drawn behind main lines for superior visibility (black default, configurable)
- Enhanced visualization: Fill between MACD and zero line provides instant visual feedback (green above, red below)
- Enhanced visualization: Fill between OB/OS thresholds highlights neutral zone when dynamic levels are active
- Custom chart background overrides background mode when enabled, allowing theme-consistent indicator panels
開源腳本
秉持TradingView一貫精神,這個腳本的創作者將其設為開源,以便交易者檢視並驗證其功能。向作者致敬!您可以免費使用此腳本,但請注意,重新發佈代碼需遵守我們的社群規範。
--Vitalii (captainua)
免責聲明
這些資訊和出版物並非旨在提供,也不構成TradingView提供或認可的任何形式的財務、投資、交易或其他類型的建議或推薦。請閱讀使用條款以了解更多資訊。
開源腳本
秉持TradingView一貫精神,這個腳本的創作者將其設為開源,以便交易者檢視並驗證其功能。向作者致敬!您可以免費使用此腳本,但請注意,重新發佈代碼需遵守我們的社群規範。
--Vitalii (captainua)
免責聲明
這些資訊和出版物並非旨在提供,也不構成TradingView提供或認可的任何形式的財務、投資、交易或其他類型的建議或推薦。請閱讀使用條款以了解更多資訊。