OPEN-SOURCE SCRIPT
MB-MACD

## Description
**MB-MACD** is a custom Pine Script indicator designed to enhance momentum analysis by combining a volume-based "Main Buy Ratio" (MB) calculation with a traditional MACD oscillator. The MB Ratio estimates institutional buying pressure by apportioning volume based on the candle's range and close position, providing a unique proxy for "smart money" flow. This smoothed MB value is then used as the source for MACD computation, allowing for divergence detection between price action, the MB line, and the MACD Histogram.
Key features include:
- **MB Line**: A histogram-style plot showing smoothed buy/sell ratio, colored bullishly (teal) or bearishly (pink) based on direction.
- **MACD Histogram**: Standard MACD applied to the MB source, with optional smoothing.
- **Divergence Detection**: Identifies bullish and bearish divergences on both the MB line and MACD Histogram, with configurable filters for momentum decay and zero-line alignment.
- **Visualization Options**: Display divergence lines and labels in the indicator pane or synced as an overlay on the main chart for better context.
- **Alerts**: Triggers for bullish or bearish divergences to notify users of potential reversal setups.
This indicator is particularly useful for swing traders and momentum followers looking to spot hidden divergences that may signal trend reversals or continuations. It emphasizes risk management by highlighting where price and momentum decouple, but remember: divergences are probabilistic signals and should be confirmed with other tools.
As this is a community-shared script, I encourage users to test it thoroughly and provide feedback. If you spot any bugs, calculation errors, or improvements (e.g., edge cases with low-volume symbols or performance issues on certain timeframes), please comment below or reach out—your input helps refine it for everyone!
## User Manual
### Introduction
The **MB-MACD** indicator integrates volume analysis with MACD to detect divergences in price and momentum. The core innovation is the "Main Buy Ratio" (MB), which approximates buying vs. selling volume within each bar based on its range and close position. This MB value is smoothed and fed into a MACD calculation, enabling divergence scans on both the MB line and the resulting MACD Histogram.
Divergences occur when price makes higher highs/lower lows, but the oscillator (MB or Histogram) fails to confirm—often signaling potential reversals. The script offers flexible display options, filters to reduce false positives, and alerts for real-time notifications.
**Important Notes:**
- This is not financial advice; use it for educational purposes and backtest on your symbols/timeframes.
- Works best on liquid stocks or indices with reliable volume data (e.g., daily or higher timeframes).
- Performance may vary on low-volume assets or during after-hours trading.
- If you encounter issues (e.g., no divergences detected or rendering errors), check your chart settings and report them in the comments for community debugging.
### Inputs Explanation
The inputs are grouped for ease of configuration. Adjust them via the indicator's settings panel in TradingView.
#### Core Parameters
- **Show MB Line** (Default: True): Enables/disables the MB Ratio histogram plot.
- **Show MACD Histogram** (Default: True): Enables/disables the MACD line and histogram plots.
- **MB Smoothing (SMA)** (Default: 10, Min: 1): Length for smoothing the raw MB Ratio using a Simple Moving Average (SMA). Higher values reduce noise but may lag.
- **Pivot Lookback Length** (Default: 5, Min: 2): Bars to look back/forward for detecting price pivots (highs/lows) used in divergence logic.
- **Max Lines Kept** (Default: 100, Min: 10): Limits the number of divergence lines/labels to prevent chart clutter.
#### Display Settings
- **Show Lines (Indicator Pane)** (Default: True): Draws divergence lines on the MB line in the indicator pane.
- **Show Labels (Indicator Pane)** (Default: True): Adds labels (e.g., "L" for line divergence) at divergence points in the pane.
- **Show Hist Divergence Lines** (Default: True): Draws dashed lines for MACD Histogram divergences in the pane.
- **Show Hist Divergence Labels** (Default: True): Adds labels (e.g., "H" for histogram divergence) in the pane.
- **Sync Lines to Main Chart (Overlay)** (Default: True): Mirrors divergence lines and labels onto the main price chart for context (slightly offset for visibility).
#### Filters & Tolerance
- **Peak Alignment Tolerance (Bars)** (Default: 5, Min: 0): Allows flexibility in matching oscillator peaks/valleys to price pivots (e.g., within ±5 bars).
- **Max Divergence Distance (Bars)** (Default: 20, Min: 5): Maximum bars between two pivots for a valid divergence; prevents detecting overly distant signals.
- **Enable Momentum Decay Filter** (Default: True): For Histogram divergences, requires the current peak/valley to have a smaller absolute value than the previous (indicating convergence/decay).
- **Enable Zero-Side Filter** (Default: False): Ensures both peaks/valleys in a divergence are on the same side of the zero line (e.g., both positive or both negative).
#### MACD Settings
- **MACD Fast Length** (Default: 12): Fast EMA length for MACD.
- **MACD Slow Length** (Default: 26): Slow EMA length for MACD.
- **MACD Signal Length** (Default: 9): Smoothing length for the MACD signal line.
- **MACD Source Smoothing** (Default: 3, Min: 1): Additional SMA smoothing applied to the MB Ratio before MACD calculation.
### How It Works
1. **MB Ratio Calculation**: For each bar, the script computes the position of the close within the high-low range (0-1). This scales the volume into "buy" and "sell" portions, then derives a net ratio (-100% to +100%). It's smoothed via SMA for the final MB line.
2. **MACD Application**: The (optionally smoothed) raw MB is used as the MACD source, producing a MACD line, signal line, and histogram.
3. **Pivot Detection**: Uses Pine's `ta.pivothigh`/`ta.pivotlow` to find price highs/lows over the lookback period.
4. **Divergence Scanning**:
- **Bearish (on Highs)**: Price makes a higher high, but MB/Hist makes a lower high.
- **Bullish (on Lows)**: Price makes a lower low, but MB/Hist makes a higher low (closer to zero).
- Scans nearby bars for oscillator matches and applies filters.
5. **Rendering**: Lines/labels are drawn in the indicator pane or overlaid on the chart. Colors: Teal for bullish, Pink/Maroon for bearish.
6. **Cleanup**: Automatically removes old lines/labels to stay under the max limit.
### Interpreting the Outputs
- **MB Line (Columns)**: Positive (teal) indicates net buying pressure; negative (pink) shows selling. Watch for crossovers above/below zero as momentum shifts.
- **MACD Histogram (Area)**: Green/teal for positive momentum; red/maroon for negative. Widening bars suggest strengthening trends; narrowing indicates weakening.
- **Divergence Lines/Labels**:
- Solid lines: MB line divergences (thicker, labeled "L").
- Dashed lines: Histogram divergences (thinner, labeled "H").
- Bullish: Teal lines sloping up (potential bottom reversal).
- Bearish: Pink lines sloping down (potential top reversal).
- **Overlay on Chart**: Lines connect price pivots (or offset slightly for Histogram). Use this to visualize how divergences align with candlesticks.
- **Zero Line**: Gray horizontal line; divergences filtered by side if enabled.
**Example Usage**:
- On a daily stock chart, enable overlays and watch for a bullish "L" or "H" label near a price low—could signal a buy if confirmed by volume breakout.
- In a downtrend, bearish divergences on highs might warn of further downside.
### Alerts
- **Bullish Divergence (L or H)**: Triggers on any detected bullish divergence (MB or Histogram).
- **Bearish Divergence (L or H)**: Triggers on bearish divergences.
- Set up via TradingView's alert menu: Select the indicator, choose the condition, and customize the message (e.g., includes ticker).
### Troubleshooting / Known Issues
- **No Divergences Shown**: Increase "Peak Alignment Tolerance" or reduce filters. Ensure pivot length suits your timeframe (shorter for intraday).
- **Too Many Lines/Labels**: Lower "Max Lines Kept" or increase "Max Divergence Distance" to filter distant signals.
- **Performance on Low-Volume Symbols**: MB Ratio may be unreliable; test on high-volume assets first.
- **Rendering Errors**: If lines don't appear, check chart zoom or ensure "force_overlay=true" isn't conflicting with other indicators.
- **NaN/Undefined Values**: Rare on live data but possible in historical backtests; report with symbol/timeframe for fixes.
### Feedback and Contributions
This script is open for community improvement! If you find bugs (e.g., false positives in divergences, calculation edge cases, or UI glitches), or have suggestions (like additional filters or visualizations), please share in the comments. Your feedback helps make it better—let's debug and enhance it together!
**MB-MACD** is a custom Pine Script indicator designed to enhance momentum analysis by combining a volume-based "Main Buy Ratio" (MB) calculation with a traditional MACD oscillator. The MB Ratio estimates institutional buying pressure by apportioning volume based on the candle's range and close position, providing a unique proxy for "smart money" flow. This smoothed MB value is then used as the source for MACD computation, allowing for divergence detection between price action, the MB line, and the MACD Histogram.
Key features include:
- **MB Line**: A histogram-style plot showing smoothed buy/sell ratio, colored bullishly (teal) or bearishly (pink) based on direction.
- **MACD Histogram**: Standard MACD applied to the MB source, with optional smoothing.
- **Divergence Detection**: Identifies bullish and bearish divergences on both the MB line and MACD Histogram, with configurable filters for momentum decay and zero-line alignment.
- **Visualization Options**: Display divergence lines and labels in the indicator pane or synced as an overlay on the main chart for better context.
- **Alerts**: Triggers for bullish or bearish divergences to notify users of potential reversal setups.
This indicator is particularly useful for swing traders and momentum followers looking to spot hidden divergences that may signal trend reversals or continuations. It emphasizes risk management by highlighting where price and momentum decouple, but remember: divergences are probabilistic signals and should be confirmed with other tools.
As this is a community-shared script, I encourage users to test it thoroughly and provide feedback. If you spot any bugs, calculation errors, or improvements (e.g., edge cases with low-volume symbols or performance issues on certain timeframes), please comment below or reach out—your input helps refine it for everyone!
## User Manual
### Introduction
The **MB-MACD** indicator integrates volume analysis with MACD to detect divergences in price and momentum. The core innovation is the "Main Buy Ratio" (MB), which approximates buying vs. selling volume within each bar based on its range and close position. This MB value is smoothed and fed into a MACD calculation, enabling divergence scans on both the MB line and the resulting MACD Histogram.
Divergences occur when price makes higher highs/lower lows, but the oscillator (MB or Histogram) fails to confirm—often signaling potential reversals. The script offers flexible display options, filters to reduce false positives, and alerts for real-time notifications.
**Important Notes:**
- This is not financial advice; use it for educational purposes and backtest on your symbols/timeframes.
- Works best on liquid stocks or indices with reliable volume data (e.g., daily or higher timeframes).
- Performance may vary on low-volume assets or during after-hours trading.
- If you encounter issues (e.g., no divergences detected or rendering errors), check your chart settings and report them in the comments for community debugging.
### Inputs Explanation
The inputs are grouped for ease of configuration. Adjust them via the indicator's settings panel in TradingView.
#### Core Parameters
- **Show MB Line** (Default: True): Enables/disables the MB Ratio histogram plot.
- **Show MACD Histogram** (Default: True): Enables/disables the MACD line and histogram plots.
- **MB Smoothing (SMA)** (Default: 10, Min: 1): Length for smoothing the raw MB Ratio using a Simple Moving Average (SMA). Higher values reduce noise but may lag.
- **Pivot Lookback Length** (Default: 5, Min: 2): Bars to look back/forward for detecting price pivots (highs/lows) used in divergence logic.
- **Max Lines Kept** (Default: 100, Min: 10): Limits the number of divergence lines/labels to prevent chart clutter.
#### Display Settings
- **Show Lines (Indicator Pane)** (Default: True): Draws divergence lines on the MB line in the indicator pane.
- **Show Labels (Indicator Pane)** (Default: True): Adds labels (e.g., "L" for line divergence) at divergence points in the pane.
- **Show Hist Divergence Lines** (Default: True): Draws dashed lines for MACD Histogram divergences in the pane.
- **Show Hist Divergence Labels** (Default: True): Adds labels (e.g., "H" for histogram divergence) in the pane.
- **Sync Lines to Main Chart (Overlay)** (Default: True): Mirrors divergence lines and labels onto the main price chart for context (slightly offset for visibility).
#### Filters & Tolerance
- **Peak Alignment Tolerance (Bars)** (Default: 5, Min: 0): Allows flexibility in matching oscillator peaks/valleys to price pivots (e.g., within ±5 bars).
- **Max Divergence Distance (Bars)** (Default: 20, Min: 5): Maximum bars between two pivots for a valid divergence; prevents detecting overly distant signals.
- **Enable Momentum Decay Filter** (Default: True): For Histogram divergences, requires the current peak/valley to have a smaller absolute value than the previous (indicating convergence/decay).
- **Enable Zero-Side Filter** (Default: False): Ensures both peaks/valleys in a divergence are on the same side of the zero line (e.g., both positive or both negative).
#### MACD Settings
- **MACD Fast Length** (Default: 12): Fast EMA length for MACD.
- **MACD Slow Length** (Default: 26): Slow EMA length for MACD.
- **MACD Signal Length** (Default: 9): Smoothing length for the MACD signal line.
- **MACD Source Smoothing** (Default: 3, Min: 1): Additional SMA smoothing applied to the MB Ratio before MACD calculation.
### How It Works
1. **MB Ratio Calculation**: For each bar, the script computes the position of the close within the high-low range (0-1). This scales the volume into "buy" and "sell" portions, then derives a net ratio (-100% to +100%). It's smoothed via SMA for the final MB line.
2. **MACD Application**: The (optionally smoothed) raw MB is used as the MACD source, producing a MACD line, signal line, and histogram.
3. **Pivot Detection**: Uses Pine's `ta.pivothigh`/`ta.pivotlow` to find price highs/lows over the lookback period.
4. **Divergence Scanning**:
- **Bearish (on Highs)**: Price makes a higher high, but MB/Hist makes a lower high.
- **Bullish (on Lows)**: Price makes a lower low, but MB/Hist makes a higher low (closer to zero).
- Scans nearby bars for oscillator matches and applies filters.
5. **Rendering**: Lines/labels are drawn in the indicator pane or overlaid on the chart. Colors: Teal for bullish, Pink/Maroon for bearish.
6. **Cleanup**: Automatically removes old lines/labels to stay under the max limit.
### Interpreting the Outputs
- **MB Line (Columns)**: Positive (teal) indicates net buying pressure; negative (pink) shows selling. Watch for crossovers above/below zero as momentum shifts.
- **MACD Histogram (Area)**: Green/teal for positive momentum; red/maroon for negative. Widening bars suggest strengthening trends; narrowing indicates weakening.
- **Divergence Lines/Labels**:
- Solid lines: MB line divergences (thicker, labeled "L").
- Dashed lines: Histogram divergences (thinner, labeled "H").
- Bullish: Teal lines sloping up (potential bottom reversal).
- Bearish: Pink lines sloping down (potential top reversal).
- **Overlay on Chart**: Lines connect price pivots (or offset slightly for Histogram). Use this to visualize how divergences align with candlesticks.
- **Zero Line**: Gray horizontal line; divergences filtered by side if enabled.
**Example Usage**:
- On a daily stock chart, enable overlays and watch for a bullish "L" or "H" label near a price low—could signal a buy if confirmed by volume breakout.
- In a downtrend, bearish divergences on highs might warn of further downside.
### Alerts
- **Bullish Divergence (L or H)**: Triggers on any detected bullish divergence (MB or Histogram).
- **Bearish Divergence (L or H)**: Triggers on bearish divergences.
- Set up via TradingView's alert menu: Select the indicator, choose the condition, and customize the message (e.g., includes ticker).
### Troubleshooting / Known Issues
- **No Divergences Shown**: Increase "Peak Alignment Tolerance" or reduce filters. Ensure pivot length suits your timeframe (shorter for intraday).
- **Too Many Lines/Labels**: Lower "Max Lines Kept" or increase "Max Divergence Distance" to filter distant signals.
- **Performance on Low-Volume Symbols**: MB Ratio may be unreliable; test on high-volume assets first.
- **Rendering Errors**: If lines don't appear, check chart zoom or ensure "force_overlay=true" isn't conflicting with other indicators.
- **NaN/Undefined Values**: Rare on live data but possible in historical backtests; report with symbol/timeframe for fixes.
### Feedback and Contributions
This script is open for community improvement! If you find bugs (e.g., false positives in divergences, calculation edge cases, or UI glitches), or have suggestions (like additional filters or visualizations), please share in the comments. Your feedback helps make it better—let's debug and enhance it together!
סקריפט קוד פתוח
ברוח האמיתית של TradingView, יוצר הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יוכלו לעיין בו ולאמת את פעולתו. כל הכבוד למחבר! אמנם ניתן להשתמש בו בחינם, אך זכור כי פרסום חוזר של הקוד כפוף ל־כללי הבית שלנו.
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.
סקריפט קוד פתוח
ברוח האמיתית של TradingView, יוצר הסקריפט הזה הפך אותו לקוד פתוח, כך שסוחרים יוכלו לעיין בו ולאמת את פעולתו. כל הכבוד למחבר! אמנם ניתן להשתמש בו בחינם, אך זכור כי פרסום חוזר של הקוד כפוף ל־כללי הבית שלנו.
כתב ויתור
המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.