Trend Gauge [BullByte]Trend Gauge
Summary
A multi-factor trend detection indicator that aggregates EMA alignment, VWMA momentum scaling, volume spikes, ATR breakout strength, higher-timeframe confirmation, ADX-based regime filtering, and RSI pivot-divergence penalty into one normalized trend score. It also provides a confidence meter, a Δ Score momentum histogram, divergence highlights, and a compact, scalable dashboard for at-a-glance status.
________________________________________
## 1. Purpose of the Indicator
Why this was built
Traders often monitor several indicators in parallel - EMAs, volume signals, volatility breakouts, higher-timeframe trends, ADX readings, divergence alerts, etc., which can be cumbersome and sometimes contradictory. The “Trend Gauge” indicator was created to consolidate these complementary checks into a single, normalized score that reflects the prevailing market bias (bullish, bearish, or neutral) and its strength. By combining multiple inputs with an adaptive regime filter, scaling contributions by magnitude, and penalizing weakening signals (divergence), this tool aims to reduce noise, highlight genuine trend opportunities, and warn when momentum fades.
Key Design Goals
Signal Aggregation
Merged trend-following signals (EMA crossover, ATR breakout, higher-timeframe confirmation) and momentum signals (VWMA thrust, volume spikes) into a unified score that reflects directional bias more holistically.
Market Regime Awareness
Implemented an ADX-style filter to distinguish between trending and ranging markets, reducing the influence of trend signals during sideways phases to avoid false breakouts.
Magnitude-Based Scaling
Replaced binary contributions with scaled inputs: VWMA thrust and ATR breakout are weighted relative to recent averages, allowing for more nuanced score adjustments based on signal strength.
Momentum Divergence Penalty
Integrated pivot-based RSI divergence detection to slightly reduce the overall score when early signs of momentum weakening are detected, improving risk-awareness in entries.
Confidence Transparency
Added a live confidence metric that shows what percentage of enabled sub-indicators currently agree with the overall bias, making the scoring system more interpretable.
Momentum Acceleration Visualization
Plotted the change in score (Δ Score) as a histogram bar-to-bar, highlighting whether momentum is increasing, flattening, or reversing, aiding in more timely decision-making.
Compact Informational Dashboard
Presented a clean, scalable dashboard that displays each component’s status, the final score, confidence %, detected regime (Trending/Ranging), and a labeled strength gauge for quick visual assessment.
________________________________________
## 2. Why a Trader Should Use It
Main benefits and use cases
1. Unified View: Rather than juggling multiple windows or panels, this indicator delivers a single score synthesizing diverse signals.
2. Regime Filtering: In ranging markets, trend signals often generate false entries. The ADX-based regime filter automatically down-weights trend-following components, helping you avoid chasing false breakouts.
3. Nuanced Momentum & Volatility: VWMA and ATR breakout contributions are normalized by recent averages, so strong moves register strongly while smaller fluctuations are de-emphasized.
4. Early Warning of Weakening: Pivot-based RSI divergence is detected and used to slightly reduce the score when price/momentum diverges, giving a cautionary signal before a full reversal.
5. Confidence Meter: See at a glance how many sub-indicators align with the aggregated bias (e.g., “80% confidence” means 4 out of 5 components agree ). This transparency avoids black-box decisions.
6. Trend Acceleration/Deceleration View: The Δ Score histogram visualizes whether the aggregated score is rising (accelerating trend) or falling (momentum fading), supplementing the main oscillator.
7. Compact Dashboard: A corner table lists each check’s status (“Bull”, “Bear”, “Flat” or “Disabled”), plus overall Score, Confidence %, Regime, Trend Strength label, and a gauge bar. Users can scale text size (Normal, Small, Tiny) without removing elements, so the full picture remains visible even in compact layouts.
8. Customizable & Transparent: All components can be enabled/disabled and parameterized (lengths, thresholds, weights). The full Pine code is open and well-commented, letting users inspect or adapt the logic.
9. Alert-ready: Built-in alert conditions fire when the score crosses weak thresholds to bullish/bearish or returns to neutral, enabling timely notifications.
________________________________________
## 3. Component Rationale (“Why These Specific Indicators?”)
Each sub-component was chosen because it adds complementary information about trend or momentum:
1. EMA Cross
o Basic trend measure: compares a faster EMA vs. a slower EMA. Quickly reflects trend shifts but by itself can whipsaw in sideways markets.
2. VWMA Momentum
o Volume-weighted moving average change indicates momentum with volume context. By normalizing (dividing by a recent average absolute change), we capture the strength of momentum relative to recent history. This scaling prevents tiny moves from dominating and highlights genuinely strong momentum.
3. Volume Spikes
o Sudden jumps in volume combined with price movement often accompany stronger moves or reversals. A binary detection (+1 for bullish spike, -1 for bearish spike) flags high-conviction bars.
4. ATR Breakout
o Detects price breaking beyond recent highs/lows by a multiple of ATR. Measures breakout strength by how far beyond the threshold price moves relative to ATR, capped to avoid extreme outliers. This gives a volatility-contextual trend signal.
5. Higher-Timeframe EMA Alignment
o Confirms whether the shorter-term trend aligns with a higher timeframe trend. Uses request.security with lookahead_off to avoid future data. When multiple timeframes agree, confidence in direction increases.
6. ADX Regime Filter (Manual Calculation)
o Computes directional movement (+DM/–DM), smoothes via RMA, computes DI+ and DI–, then a DX and ADX-like value. If ADX ≥ threshold, market is “Trending” and trend components carry full weight; if ADX < threshold, “Ranging” mode applies a configurable weight multiplier (e.g., 0.5) to trend-based contributions, reducing false signals in sideways conditions. Volume spikes remain binary (optional behavior; can be adjusted if desired).
7. RSI Pivot-Divergence Penalty
o Uses ta.pivothigh / ta.pivotlow with a lookback to detect pivot highs/lows on price and corresponding RSI values. When price makes a higher high but RSI makes a lower high (bearish divergence), or price makes a lower low but RSI makes a higher low (bullish divergence), a divergence signal is set. Rather than flipping the trend outright, the indicator subtracts (or adds) a small penalty (configurable) from the aggregated score if it would weaken the current bias. This subtle adjustment warns of weakening momentum without overreacting to noise.
8. Confidence Meter
o Counts how many enabled components currently agree in direction with the aggregated score (i.e., component sign × score sign > 0). Displays this as a percentage. A high percentage indicates strong corroboration; a low percentage warns of mixed signals.
9. Δ Score Momentum View
o Plots the bar-to-bar change in the aggregated score (delta_score = score - score ) as a histogram. When positive, bars are drawn in green above zero; when negative, bars are drawn in red below zero. This reveals acceleration (rising Δ) or deceleration (falling Δ), supplementing the main oscillator.
10. Dashboard
• A table in the indicator pane’s top-right with 11 rows:
1. EMA Cross status
2. VWMA Momentum status
3. Volume Spike status
4. ATR Breakout status
5. Higher-Timeframe Trend status
6. Score (numeric)
7. Confidence %
8. Regime (“Trending” or “Ranging”)
9. Trend Strength label (e.g., “Weak Bullish Trend”, “Strong Bearish Trend”)
10. Gauge bar visually representing score magnitude
• All rows always present; size_opt (Normal, Small, Tiny) only changes text size via text_size, not which elements appear. This ensures full transparency.
________________________________________
## 4. What Makes This Indicator Stand Out
• Regime-Weighted Multi-Factor Score: Trend and momentum signals are adaptively weighted by market regime (trending vs. ranging) , reducing false signals.
• Magnitude Scaling: VWMA and ATR breakout contributions are normalized by recent average momentum or ATR, giving finer gradation compared to simple ±1.
• Integrated Divergence Penalty: Divergence directly adjusts the aggregated score rather than appearing as a separate subplot; this influences alerts and trend labeling in real time.
• Confidence Meter: Shows the percentage of sub-signals in agreement, providing transparency and preventing blind trust in a single metric.
• Δ Score Histogram Momentum View: A histogram highlights acceleration or deceleration of the aggregated trend score, helping detect shifts early.
• Flexible Dashboard: Always-visible component statuses and summary metrics in one place; text size scaling keeps the full picture available in cramped layouts.
• Lookahead-Safe HTF Confirmation: Uses lookahead_off so no future data is accessed from higher timeframes, avoiding repaint bias.
• Repaint Transparency: Divergence detection uses pivot functions that inherently confirm only after lookback bars; description documents this lag so users understand how and when divergence labels appear.
• Open-Source & Educational: Full, well-commented Pine v6 code is provided; users can learn from its structure: manual ADX computation, conditional plotting with series = show ? value : na, efficient use of table.new in barstate.islast, and grouped inputs with tooltips.
• Compliance-Conscious: All plots have descriptive titles; inputs use clear names; no unnamed generic “Plot” entries; manual ADX uses RMA; all request.security calls use lookahead_off. Code comments mention repaint behavior and limitations.
________________________________________
## 5. Recommended Timeframes & Tuning
• Any Timeframe: The indicator works on small (e.g., 1m) to large (daily, weekly) timeframes. However:
o On very low timeframes (<1m or tick charts), noise may produce frequent whipsaws. Consider increasing smoothing lengths, disabling certain components (e.g., volume spike if volume data noisy), or using a larger pivot lookback for divergence.
o On higher timeframes (daily, weekly), consider longer lookbacks for ATR breakout or divergence, and set Higher-Timeframe trend appropriately (e.g., 4H HTF when on 5 Min chart).
• Defaults & Experimentation: Default input values are chosen to be balanced for many liquid markets. Users should test with replay or historical analysis on their symbol/timeframe and adjust:
o ADX threshold (e.g., 20–30) based on instrument volatility.
o VWMA and ATR scaling lengths to match average volatility cycles.
o Pivot lookback for divergence: shorter for faster markets, longer for slower ones.
• Combining with Other Analysis: Use in conjunction with price action, support/resistance, candlestick patterns, order flow, or other tools as desired. The aggregated score and alerts can guide attention but should not be the sole decision-factor.
________________________________________
## 6. How Scoring and Logic Works (Step-by-Step)
1. Compute Sub-Scores
o EMA Cross: Evaluate fast EMA > slow EMA ? +1 : fast EMA < slow EMA ? -1 : 0.
o VWMA Momentum: Calculate vwma = ta.vwma(close, length), then vwma_mom = vwma - vwma . Normalize: divide by recent average absolute momentum (e.g., ta.sma(abs(vwma_mom), lookback)), clip to .
o Volume Spike: Compute vol_SMA = ta.sma(volume, len). If volume > vol_SMA * multiplier AND price moved up ≥ threshold%, assign +1; if moved down ≥ threshold%, assign -1; else 0.
o ATR Breakout: Determine recent high/low over lookback. If close > high + ATR*mult, compute distance = close - (high + ATR*mult), normalize by ATR, cap at a configured maximum. Assign positive contribution. Similarly for bearish breakout below low.
o Higher-Timeframe Trend: Use request.security(..., lookahead=barmerge.lookahead_off) to fetch HTF EMAs; assign +1 or -1 based on alignment.
2. ADX Regime Weighting
o Compute manual ADX: directional movements (+DM, –DM), smoothed via RMA, DI+ and DI–, then DX and ADX via RMA. If ADX ≥ threshold, market is considered “Trending”; otherwise “Ranging.”
o If trending, trend-based contributions (EMA, VWMA, ATR, HTF) use full weight = 1.0. If ranging, use weight = ranging_weight (e.g., 0.5) to down-weight them. Volume spike stays binary ±1 (optional to change if desired).
3. Aggregate Raw Score
o Sum weighted contributions of all enabled components. Count the number of enabled components; if zero, default count = 1 to avoid division by zero.
4. Divergence Penalty
o Detect pivot highs/lows on price and corresponding RSI values, using a lookback. When price and RSI diverge (bearish or bullish divergence), check if current raw score is in the opposing direction:
If bearish divergence (price higher high, RSI lower high) and raw score currently positive, subtract a penalty (e.g., 0.5).
If bullish divergence (price lower low, RSI higher low) and raw score currently negative, add a penalty.
o This reduces score magnitude to reflect weakening momentum, without flipping the trend outright.
5. Normalize and Smooth
o Normalized score = (raw_score / number_of_enabled_components) * 100. This yields a roughly range.
o Optional EMA smoothing of this normalized score to reduce noise.
6. Interpretation
o Sign: >0 = net bullish bias; <0 = net bearish bias; near zero = neutral.
o Magnitude Zones: Compare |score| to thresholds (Weak, Medium, Strong) to label trend strength (e.g., “Weak Bullish Trend”, “Medium Bearish Trend”, “Strong Bullish Trend”).
o Δ Score Histogram: The histogram bars from zero show change from previous bar’s score; positive bars indicate acceleration, negative bars indicate deceleration.
o Confidence: Percentage of sub-indicators aligned with the score’s sign.
o Regime: Indicates whether trend-based signals are fully weighted or down-weighted.
________________________________________
## 7. Oscillator Plot & Visualization: How to Read It
Main Score Line & Area
The oscillator plots the aggregated score as a line, with colored fill: green above zero for bullish area, red below zero for bearish area. Horizontal reference lines at ±Weak, ±Medium, and ±Strong thresholds mark zones: crossing above +Weak suggests beginning of bullish bias, above +Medium for moderate strength, above +Strong for strong trend; similarly for bearish below negative thresholds.
Δ Score Histogram
If enabled, a histogram shows score - score . When positive, bars appear in green above zero, indicating accelerating bullish momentum; when negative, bars appear in red below zero, indicating decelerating or reversing momentum. The height of each bar reflects the magnitude of change in the aggregated score from the prior bar.
Divergence Highlight Fill
If enabled, when a pivot-based divergence is confirmed:
• Bullish Divergence : fill the area below zero down to –Weak threshold in green, signaling potential reversal from bearish to bullish.
• Bearish Divergence : fill the area above zero up to +Weak threshold in red, signaling potential reversal from bullish to bearish.
These fills appear with a lag equal to pivot lookback (the number of bars needed to confirm the pivot). They do not repaint after confirmation, but users must understand this lag.
Trend Direction Label
When score crosses above or below the Weak threshold, a small label appears near the score line reading “Bullish” or “Bearish.” If the score returns within ±Weak, the label “Neutral” appears. This helps quickly identify shifts at the moment they occur.
Dashboard Panel
In the indicator pane’s top-right, a table shows:
1. EMA Cross status: “Bull”, “Bear”, “Flat”, or “Disabled”
2. VWMA Momentum status: similarly
3. Volume Spike status: “Bull”, “Bear”, “No”, or “Disabled”
4. ATR Breakout status: “Bull”, “Bear”, “No”, or “Disabled”
5. Higher-Timeframe Trend status: “Bull”, “Bear”, “Flat”, or “Disabled”
6. Score: numeric value (rounded)
7. Confidence: e.g., “80%” (colored: green for high, amber for medium, red for low)
8. Regime: “Trending” or “Ranging” (colored accordingly)
9. Trend Strength: textual label based on magnitude (e.g., “Medium Bullish Trend”)
10. Gauge: a bar of blocks representing |score|/100
All rows remain visible at all times; changing Dashboard Size only scales text size (Normal, Small, Tiny).
________________________________________
## 8. Example Usage (Illustrative Scenario)
Example: BTCUSD 5 Min
1. Setup: Add “Trend Gauge ” to your BTCUSD 5 Min chart. Defaults: EMAs (8/21), VWMA 14 with lookback 3, volume spike settings, ATR breakout 14/5, HTF = 5m (or adjust to 4H if preferred), ADX threshold 25, ranging weight 0.5, divergence RSI length 14 pivot lookback 5, penalty 0.5, smoothing length 3, thresholds Weak=20, Medium=50, Strong=80. Dashboard Size = Small.
2. Trend Onset: At some point, price breaks above recent high by ATR multiple, volume spikes upward, faster EMA crosses above slower EMA, HTF EMA also bullish, and ADX (manual) ≥ threshold → aggregated score rises above +20 (Weak threshold) into +Medium zone. Dashboard shows “Bull” for EMA, VWMA, Vol Spike, ATR, HTF; Score ~+60–+70; Confidence ~100%; Regime “Trending”; Trend Strength “Medium Bullish Trend”; Gauge ~6–7 blocks. Δ Score histogram bars are green and rising, indicating accelerating bullish momentum. Trader notes the alignment.
3. Divergence Warning: Later, price makes a slightly higher high but RSI fails to confirm (lower RSI high). Pivot lookback completes; the indicator highlights a bearish divergence fill above zero and subtracts a small penalty from the score, causing score to stall or retrace slightly. Dashboard still bullish but score dips toward +Weak. This warns the trader to tighten stops or take partial profits.
4. Trend Weakens: Score eventually crosses below +Weak back into neutral; a “Neutral” label appears, and a “Neutral Trend” alert fires if enabled. Trader exits or avoids new long entries. If score subsequently crosses below –Weak, a “Bearish” label and alert occur.
5. Customization: If the trader finds VWMA noise too frequent on this instrument, they may disable VWMA or increase lookback. If ATR breakouts are too rare, adjust ATR length or multiplier. If ADX threshold seems off, tune threshold. All these adjustments are explained in Inputs section.
6. Visualization: The screenshot shows the main score oscillator with colored areas, reference lines at ±20/50/80, Δ Score histogram bars below/above zero, divergence fill highlighting potential reversal, and the dashboard table in the top-right.
________________________________________
## 9. Inputs Explanation
A concise yet clear summary of inputs helps users understand and adjust:
1. General Settings
• Theme (Dark/Light): Choose background-appropriate colors for the indicator pane.
• Dashboard Size (Normal/Small/Tiny): Scales text size only; all dashboard elements remain visible.
2. Indicator Settings
• Enable EMA Cross: Toggle on/off basic EMA alignment check.
o Fast EMA Length and Slow EMA Length: Periods for EMAs.
• Enable VWMA Momentum: Toggle VWMA momentum check.
o VWMA Length: Period for VWMA.
o VWMA Momentum Lookback: Bars to compare VWMA to measure momentum.
• Enable Volume Spike: Toggle volume spike detection.
o Volume SMA Length: Period to compute average volume.
o Volume Spike Multiplier: How many times above average volume qualifies as spike.
o Min Price Move (%): Minimum percent change in price during spike to qualify as bullish or bearish.
• Enable ATR Breakout: Toggle ATR breakout detection.
o ATR Length: Period for ATR.
o Breakout Lookback: Bars to look back for recent highs/lows.
o ATR Multiplier: Multiplier for breakout threshold.
• Enable Higher Timeframe Trend: Toggle HTF EMA alignment.
o Higher Timeframe: E.g., “5” for 5-minute when on 1-minute chart, or “60” for 5 Min when on 15m, etc. Uses lookahead_off.
• Enable ADX Regime Filter: Toggles regime-based weighting.
o ADX Length: Period for manual ADX calculation.
o ADX Threshold: Value above which market considered trending.
o Ranging Weight Multiplier: Weight applied to trend components when ADX < threshold (e.g., 0.5).
• Scale VWMA Momentum: Toggle normalization of VWMA momentum magnitude.
o VWMA Mom Scale Lookback: Period for average absolute VWMA momentum.
• Scale ATR Breakout Strength: Toggle normalization of breakout distance by ATR.
o ATR Scale Cap: Maximum multiple of ATR used for breakout strength.
• Enable Price-RSI Divergence: Toggle divergence detection.
o RSI Length for Divergence: Period for RSI.
o Pivot Lookback for Divergence: Bars on each side to identify pivot high/low.
o Divergence Penalty: Amount to subtract/add to score when divergence detected (e.g., 0.5).
3. Score Settings
• Smooth Score: Toggle EMA smoothing of normalized score.
• Score Smoothing Length: Period for smoothing EMA.
• Weak Threshold: Absolute score value under which trend is considered weak or neutral.
• Medium Threshold: Score above Weak but below Medium is moderate.
• Strong Threshold: Score above this indicates strong trend.
4. Visualization Settings
• Show Δ Score Histogram: Toggle display of the bar-to-bar change in score as a histogram. Default true.
• Show Divergence Fill: Toggle background fill highlighting confirmed divergences. Default true.
Each input has a tooltip in the code.
________________________________________
## 10. Limitations, Repaint Notes, and Disclaimers
10.1. Repaint & Lag Considerations
• Pivot-Based Divergence Lag: The divergence detection uses ta.pivothigh / ta.pivotlow with a specified lookback. By design, a pivot is only confirmed after the lookback number of bars. As a result:
o Divergence labels or fills appear with a delay equal to the pivot lookback.
o Once the pivot is confirmed and the divergence is detected, the fill/label does not repaint thereafter, but you must understand and accept this lag.
o Users should not treat divergence highlights as predictive signals without additional confirmation, because they appear after the pivot has fully formed.
• Higher-Timeframe EMA Alignment: Uses request.security(..., lookahead=barmerge.lookahead_off), so no future data from the higher timeframe is used. This avoids lookahead bias and ensures signals are based only on completed higher-timeframe bars.
• No Future Data: All calculations are designed to avoid using future information. For example, manual ADX uses RMA on past data; security calls use lookahead_off.
10.2. Market & Noise Considerations
• In very choppy or low-liquidity markets, some components (e.g., volume spikes or VWMA momentum) may be noisy. Users can disable or adjust those components’ parameters.
• On extremely low timeframes, noise may dominate; consider smoothing lengths or disabling certain features.
• On very high timeframes, pivots and breakouts occur less frequently; adjust lookbacks accordingly to avoid sparse signals.
10.3. Not a Standalone Trading System
• This is an indicator, not a complete trading strategy. It provides signals and context but does not manage entries, exits, position sizing, or risk management.
• Users must combine it with their own analysis, money management, and confirmations (e.g., price patterns, support/resistance, fundamental context).
• No guarantees: past behavior does not guarantee future performance.
10.4. Disclaimers
• Educational Purposes Only: The script is provided as-is for educational and informational purposes. It does not constitute financial, investment, or trading advice.
• Use at Your Own Risk: Trading involves risk of loss. Users should thoroughly test and use proper risk management.
• No Guarantees: The author is not responsible for trading outcomes based on this indicator.
• License: Published under Mozilla Public License 2.0; code is open for viewing and modification under MPL terms.
________________________________________
## 11. Alerts
• The indicator defines three alert conditions:
1. Bullish Trend: when the aggregated score crosses above the Weak threshold.
2. Bearish Trend: when the score crosses below the negative Weak threshold.
3. Neutral Trend: when the score returns within ±Weak after being outside.
Good luck
– BullByte