PROTECTED SOURCE SCRIPT
Atualizado

OverBought & OverSold [SwissAlgo]

45
OverBought & OverSold [SwissAlgo]
Statistical analysis of momentum extremes

----------------------------------------------------------
Purpose
This indicator was built to answer three questions:
  1. Is the current price move statistically extreme? - By comparing current momentum to historical distribution
  2. What is the current market regime? - By combining trend position and momentum direction
  3. Is momentum accelerating or decelerating? - By analyzing weekly momentum shifts


----------------------------------------------------------
What You Can Do With This Indicator

Identify Statistical Extremes
  • See when price momentum seems to have reached levels that historically preceded reversals
  • Compare the current Rate of Change to its historical mean and standard deviation
  • Spot when readings exceed ±1σ, ±2σ, or higher thresholds

Monitor Market Regime/State
  • Track whether the market seems to be in BULL, WEAK BULL, BEAR, or WEAK BEAR state
  • Observe potential transitions between regimes as they occur
  • Understand the relationship between price position and momentum

Assess Momentum Quality
  • Distinguish between potentially accelerating momentum (lime/red bars) and decelerating momentum (green/maroon bars)
  • Watch for possible momentum deterioration within established trends
  • Track weekly momentum patterns that filter out daily noise

Measure Distance from Trend
  • Monitor how far the price is from its long-term moving average (EMA 350)
  • Identify when price approaches trend support/resistance
  • Contextualize current position relative to historical distance patterns


----------------------------------------------------------
Overview
This indicator calculates a volume-weighted Rate of Change (ROC) and displays it with statistical Z-Score bands. It combines ROC analysis with market regime detection using weekly MACD and EMA positioning.
Key Features
  • Volume-weighted ROC calculation with 5-bar smoothing
  • Dynamic Z-Score bands (±0.5σ to ±6σ)
  • Four-state market regime classification
  • Weekly Stochastic RSI-based histogram coloring
  • Visual markers for extreme readings
  • Information table with current statistics

Calculations
Volume-Weighted ROC
The indicator compares two 5-bar volume-weighted average prices separated by the ROC
Length period:
  • Recent VWAP = Σ(Price × Volume) / Σ(Volume) for last 5 bars
  • Past VWAP = Σ(Price × Volume) / Σ(Volume) for 5 bars at lookback
  • ROC = ((Recent VWAP - Past VWAP) / Past VWAP) × 100
  • Default ROC Length: 30 periods

Why volume-weighted:
  • Single price points can be affected by temporary spikes
  • Volume weighting emphasizes legitimate price moves
  • 5-bar averaging reduces single-bar noise

Z-Score Bands
The indicator maintains separate statistical distributions for positive and negative ROC values:
For positive ROC values:
  • Calculates mean and standard deviation of all positive ROC readings
  • Plots bands at +0.5σ, +1σ, +2σ, +3σ, +4σ, +5σ, +6σ above the mean

For negative ROC values:
  • Calculates mean and standard deviation of all negative ROC readings
  • Plots bands at -0.5σ, -1σ, -2σ, -3σ, -4σ, -5σ, -6σ below the mean

Z-Score formula:
  • If ROC > 0: Z = (ROC - Positive Mean) / Positive Std Dev
  • If ROC < 0: Z = (ROC - Negative Mean) / Negative Std Dev

Why separate distributions:
  • Upward and downward momentum often have different statistical properties
  • Separate analysis provides more accurate extreme identification
  • Each side maintains its own mean and volatility characteristics

The ±1σ bands use thicker lines (linewidth=2) as these levels are most frequently tested.
Market Regime States
Four states based on weekly MACD (10, 24, 8) and EMA 350:
BULL
  • Conditions: Price > EMA 350, Weekly MACD > 0, MACD > Signal, ROC histogram lime
  • Background: Lime (85% transparency)
  • Interpretation: Price above long-term trend with accelerating momentum

WEAK BULL
  • Conditions: Price > EMA 350 AND (MACD < Signal OR ROC histogram green)
  • Background: Green (95% transparency)
  • Interpretation: Price above trend, but momentum seems to be decelerating

BEAR
  • Conditions: Price < EMA 350, Weekly MACD < 0, MACD < Signal, ROC histogram red
  • Background: Red (85% transparency)
  • Interpretation: Price below long-term trend with accelerating downward momentum

WEAK BEAR
  • Conditions: Price < EMA 350 AND (MACD > Signal OR ROC histogram maroon)
  • Background: Maroon (95% transparency)
  • Interpretation: Price below trend, but downward momentum seems to be decelerating

NEUTRAL
  • Conditions: None of the above met
  • Background: Gray (95% transparency)
  • Interpretation: Transitional state between regimes

Why weekly MACD:
  • Filters daily volatility and noise
  • Provides more stable regime classification
  • Reduces false regime switches

Histogram Colors
Colors determined by Weekly Stochastic RSI (14, 14, 3, 3):
  • Lime: ROC > 0 and K > D (rising positive momentum)
  • Green: ROC > 0 and K < D (falling positive momentum)
  • Red: ROC < 0 and K < D (falling negative momentum)
  • Maroon: ROC < 0 and K > D (rising negative momentum)

Why weekly Stochastic RSI:
  • Shows momentum direction independent of absolute level
  • Weekly timeframe provides stable readings
  • K/D crossover indicates momentum shifts

Visual Markers
  • Red arrows (↓): Display when ROC ≥ +1σ (overbought zone)
  • Lime arrows (↑): Display when ROC ≤ -0.5σ (oversold zone)

These markers highlight when readings reach statistical extremes.
Information Table
Located at the top-right, displays four rows:
Row 1 - Market State
  • Shows current regime text (BULL/WEAK BULL/BEAR/WEAK BEAR/NEUTRAL)
  • Color matches regime state

Row 2 - Current Z-Score
  • Shows Z-Score value with 2 decimal places
  • Lime when Z ≤ -0.5 (statistically oversold)
  • Red when Z ≥ +1 (statistically overbought)
  • White for values between -0.5 and +1 (normal range)
  • Adds bullet (●) for extreme values

Row 3 - Price ROC %
  • Shows current ROC percentage
  • Lime when positive
  • Red when negative

Row 4 - Distance % EMA
  • Shows percentage distance from EMA 350
  • Calculates Z-score of distance
  • Red with ● when close to EMA in bull market (|Z| < 0.5)
  • Lime with ● when close to EMA in bear market (|Z| < 0.5)
  • Standard colors otherwise (lime when above EMA, red when below)

Why distance matters:
  • A price approaching EMA 350 in a bull market can signal a support test
  • Price near EMA 350 in a bear market can signal a resistance test
  • Z-score of distance shows if the current proximity is statistically unusual

----------------------------------------------------------
Settings
ROC Length (Integer, default: 30, minimum: 1)
  • Number of periods for ROC lookback
  • Higher values = slower response, smoother
  • Lower values = faster response, more sensitive

Source (Source, default: close)
  • Price data input for calculations
  • Can use close, open, high, low, hl2, hlc3, ohlc4

Show Info Table (Boolean, default: true)
Toggle table visibility

----------------------------------------------------------
Technical Details
  • Uses lookahead=barmerge.lookahead_off for all request.security() calls
  • Accumulates all historical ROC values in arrays for Z-Score calculation
  • Weekly timeframe data retrieved via request.security() on "1W" resolution
  • EMA length hardcoded to 350 periods
  • All plots use Pine Script v6 syntax

Data Requirements
  • Minimum bars required: ROC Length + 5 bars
  • Works on any timeframe
  • Applicable to any instrument with volume data
  • Historical data used: All available bars on the chart

Display Elements
Plots:
  • ROC histogram (plotcandle format)
  • Zero line (horizontal line)
  • 14 standard deviation lines (7 positive, 7 negative)
  • 13 filled regions between bands
  • 14 sigma labels (displayed on last bar only)
  • Extreme zone markers (arrows)

Color Scheme:
  • Positive bands: Lime with varying transparency
  • Negative bands: Red with varying transparency
  • Fills: Green (positive) and Red (negative) with high transparency
  • Bands beyond 3σ use increased transparency (85%, 90%, 93%)

Visual Hierarchy
  • ±1σ bands: Thicker lines (most important levels)
  • ±0.5σ to ±3σ: Standard visibility
  • ±4σ to ±6σ: Faded (visible only during extreme events)

Notes
  • This is an oscillator-type indicator (overlay=false)
  • Displays in a separate pane below the price chart
  • Does not generate automatic buy/sell signals
  • Does not include alert conditions
  • Does not repaint (all calculations use confirmed data)

Limitations
  • Requires sufficient historical data for meaningful statistics
  • Z-Score bands recalculate as new data accumulates
  • Market regime requires weekly MACD calculation (may show neutral on insufficient data)
  • Volume-weighting requires volume data availability
  • EMA 350 is fixed (not adjustable via inputs)
  • Statistical extremes do not guarantee reversals
  • Past distribution patterns do not predict future behavior


----------------------------------------------------------

Disclaimer

Educational Purpose Only
This indicator is provided for educational and informational purposes only. It is a technical analysis tool that displays statistical calculations and historical data patterns.
Not Financial Advice
This indicator does not provide financial, investment, trading, or any other type of professional advice. All content and calculations are for informational purposes only and should not be construed as a recommendation to buy, sell, or hold any security or financial instrument.
No Guarantee of Results
Past performance and historical statistical patterns do not guarantee future results. Markets are inherently unpredictable, and statistical analysis cannot predict future price movements with certainty. The appearance of statistical extremes does not ensure that reversals will occur.
User Responsibility
Users of this indicator are solely responsible for their own trading and investment decisions. You should conduct your own research and due diligence and consult with qualified financial professionals before making any investment decisions.
Risk Warning
Trading and investing in financial markets involves substantial risk of loss. You should only trade with capital you can afford to lose. The use of technical indicators does not eliminate market risk.
No Warranty
This indicator is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to warranties of accuracy, reliability, or fitness for a particular purpose. The author makes no guarantees regarding the accuracy of calculations or the absence of errors.
Limitation of Liability
The author and publisher of this indicator shall not be held liable for any losses, damages, or claims arising from the use or inability to use this indicator, including but not limited to trading losses, lost profits, or any other financial losses.
Data Accuracy
While efforts have been made to ensure calculation accuracy, users should independently verify all outputs. The indicator relies on data provided by TradingView, and the author is not responsible for data feed errors or interruptions.
User Agreement
By using this indicator, you acknowledge that you have read, understood, and agree to this disclaimer. If you do not agree with any part of this disclaimer, you should not use this indicator.
Notas de Lançamento
Color fixes
Notas de Lançamento
chart fix

Aviso legal

As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.