Gatev Relative Value Arbiter [JOAT]Gatev Relative Value Arbiter
Introduction
Gatev Relative Value Arbiter studies relative value between the chart symbol and a selected peer using beta spread, z-score, stationarity, Kalman residuals, and OU speed.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Rolling Beta Spread
The chart log price is modeled against the peer log price with rolling beta and alpha.
2. Spread Z-Score
Residual spread is normalized to identify cheap and rich dislocations.
3. Kalman Residual
A recursive residual estimate adapts to changing pair behavior.
4. Stationarity and OU Speed
Correlation, beta drift, skew, kurtosis, and OU-style speed grade pair quality.
spread = logChart - (alpha + beta * logPeer)
Features
Peer relative-value model
Rolling beta and spread z-score
Kalman residual z-score
Stationarity and cointegration energy proxies
Cheap, rich, prime, broken, and fair-value states
Input Parameters
Peer symbol
Rolling beta and z-score lengths
Entry and exit z thresholds
Minimum correlation
Cooldown and display toggles
How to Use This Script
Choose a logically related peer. Cheap and rich states are most meaningful when pair validity and stationarity remain acceptable.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
GRA is original in combining rolling beta arbitrage logic, Kalman residuals, OU speed, and stationarity grading.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades
Indicator

Veyra Delta Lens [JOAT]Veyra Delta Lens
Introduction
Veyra Delta Lens estimates delta pressure from OHLCV data and converts it into auction pressure, CVD z-score, participation entropy, absorption, and pressure-shift events.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Signed Volume Pressure
Candle close location and body impact estimate directional volume pressure.
2. CVD Normalization
Cumulative pressure is normalized so current pressure can be compared with recent history.
3. Participation Entropy
Volume concentration and close location distinguish balanced absorption from directional release.
4. Pressure Envelope
An auction mean and delta rails display pressure on the price chart.
delta = signedVolume * 0.65 + impactVolume * 0.35
Features
Estimated signed volume pressure
CVD z-score and impulse scoring
Absorption and divergence context
Auction mean and pressure rails
Sparse VX+ and VX- labels
Input Parameters
Delta smoothing and impulse memory
CVD normalization window
Participation entropy window
Event score and cooldown
Rails, trace, and candle toggles
How to Use This Script
Use VX+ and VX- labels as confirmed pressure shifts. Gold circles show absorption or divergence conditions aligned with the current regime.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
Veyra is original in combining estimated delta, CVD normalization, entropy, auction rails, absorption, and divergence in one restrained overlay.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades
Indicator

Intermarket Flow OscillatorAdvanced Macro Regime Tracking & Apex Reversal Detection
What is the Intermarket Flow Oscillator (IFO)?
The Intermarket Flow Oscillator (IFO) is a quantitative momentum tool designed to track capital rotation between risk-on assets (growth, equities) and risk-off assets (defensives, bonds, safe havens). By utilizing advanced statistical normalization and John Ehlers' digital signal processing, the IFO visualizes structural market regimes and pinpoints high-probability exhaustion reversals.
Whether you are trading swing setups on the daily chart or monitoring intraday capital flows, the IFO acts as a macro compass to keep you on the right side of institutional money.
The Mathematical Engine
Traditional spread indicators suffer from noise and asymmetric scaling. The IFO solves this using a two-step quantitative process:
Z-Score Normalization: The script calculates the natural log ratio of a Risk Asset versus a Safe Haven asset, then applies a rolling Z-Score. This transforms the intermarket spread into a stationary stochastic process, making standard deviation thresholds mathematically reliable.
John Ehlers' 2-Pole SuperSmoother: To eliminate high-frequency market noise without introducing the severe phase lag typical of moving averages, the Z-Score is passed through an advanced DSP filter.
How to Read the Signals
Trend Shifts & Structural Regimes (The Zero-Line)
The smoothed oscillator crossing the zero equilibrium line indicates a macro shift in capital allocation.
Green Cloud (IFO > 0): Structural Risk-On Regime. Institutions are accumulating risk/growth. Traders should look for long momentum setups and favor high-beta assets.
Red Cloud (IFO < 0): Structural Risk-Off Regime. Capital is fleeing to safety. Traders should focus on cash preservation, defensive value, or short setups.
Apex Mean-Reversion Turns (▲ and ▼)
The script calculates the first derivative (Velocity) of the smoothed capital flow. When the oscillator reaches extreme statistical exhaustion thresholds (default ±1.5 standard deviations) and the velocity flips, the IFO prints a high-contrast triangle.
Bullish Apex (▲): Occurs deep in negative territory (panic/capitulation). Represents a mathematically optimal exhaustion point where selling pressure is dying. Excellent for buying the bottom in growth stocks.
Bearish Apex (▼): Occurs high in positive territory (euphoria). Represents exhaustion in risk-taking and serves as an early warning to take profits or look for short entries.
Practical Trading Application: Sector Rotation (XLK vs. XLP)
While the default script pairs S&P 500 Futures (ES) against 10-Year Treasuries (ZN), the true power of the IFO shines in sector rotation.
The Setup: Set the Risk Asset to XLK (Technology) and the Safe Haven to XLP (Consumer Staples).
The Logic: XLK represents high-beta, duration-sensitive growth (Apple, Microsoft, Nvidia). XLP represents inelastic consumer demand (Procter & Gamble, Walmart). This spread is the ultimate risk-on/risk-off gauge.
Key Features & Customization
Customizable Pairs: Fully adjustable inputs to test different macro pairs (e.g., BTC vs. Gold, BTCUSDT.P vs. USDT, Discretionary vs. Utilities, High Yield Bonds vs. Treasuries).
Dynamic Coloring: The oscillator line shifts between bright/faded colors based on momentum velocity, giving you a visual cue before a crossover even happens.
Indicator

Intermarket Confluence Engine | AnonycryptousIntermarket Confluence Engine (ICE) | Anonycryptous
Description & user manual
Why this indicator exists
Most indicators analyze one asset in isolation. They look at price, momentum, volume, or volatility — all on the same chart, all based on the same data feed. That is useful, but it leaves out the context that drives markets at a deeper level: the relationship between assets, the macro regime, the direction of capital flow across instruments.
ICE approaches the problem differently.
Instead of analyzing a single price series, it takes two assets and computes their ratio. That ratio becomes the subject of analysis — not the individual prices. The result is a view of relative strength, regime state, and intermarket context that no single-asset indicator can produce.
It runs eight independent analytical engines on that ratio. Each engine returns a directional score. Those scores are weighted based on the selected asset class and combined into a single confluence number from -10 to +10. The dashboard shows the engine breakdown, the macro state, and the current statistical position of the ratio in its historical distribution — all in one compact panel.
ICE is not a signal indicator. It does not tell you when to buy or sell. It tells you what the current relationship between two assets looks like across eight independent dimensions, and how much those dimensions agree with each other.
Important notice
ICE does not generate trading signals.
It does not tell you when to buy or sell.
It does not predict market direction.
It does not guarantee any outcome.
All trading decisions remain entirely with the user.
Always apply your own judgment and manage your own risk.
1. Overview
ICE is a ratio-based intermarket confluence scoring system. It takes two configurable assets, computes their price ratio (Asset A divided by Asset B), and runs that ratio through eight analytical engines simultaneously.
The nine engines are:
- Relative strength — how much Asset A is outperforming or underperforming Asset B on a rate-of-change basis
- Trend — EMA structure and slope direction of the ratio
- Momentum — volume-weighted RSI and MACD histogram alignment on the ratio
- Volatility — Bollinger Band width, ATR percentile, and squeeze state of the ratio
- Statistical extremes — Z-score and historical percentile position of the ratio
- Macro regime — direction of DXY, VIX, and 10-year Treasury yields
- Liquidity — yield curve proxy using 10-year yield rate of change
- Intermarket correlation — rolling correlation between the ratio and each macro feed
- Volume participation — OBV slope and relative volume confirmation on both assets
Each engine is weighted based on the selected asset class. A custom weighting mode is available for manual control. All weights are normalized so the final score always maps to the -10 to +10 range regardless of class selection.
The chart displays the ratio as a line with an EMA stack (21, 50, 200), Bollinger Bands, and statistical deviation bands based on Z-score distance from the historical mean. Signals fire when confluence crosses configurable thresholds. Divergence between the ratio and its volume-weighted RSI is detected mechanically and shown on the chart.
2. The ratio
2.1 What it represents
The ratio is simply the price of Asset A divided by the price of Asset B. If Asset A is gold (XAUUSD) and Asset B is silver (XAGUSD), the ratio is the gold/silver ratio — how many ounces of silver one ounce of gold can buy. If Asset A is NQ futures and Asset B is ES futures, the ratio represents the relative performance of tech versus the broad market.
The ratio rises when Asset A outperforms Asset B. It falls when Asset B outperforms Asset A. All eight engines work on this ratio, not on the underlying prices.
2.2 What is plotted
The ratio line is the primary visual element. It is colored gold when above its 50-period EMA and grey when below. The EMA stack (green for the 21, blue for the 50, white for the 200) shows the structural state of the ratio trend.
Two band systems are visible simultaneously:
Statistical deviation bands — based on Z-score. The upper band is the historical mean plus 2 standard deviations (configurable). The lower band is the mean minus 2 standard deviations. When the ratio is near or beyond these bands, the Statistical engine activates and the dashboard notes an extreme condition.
Bollinger Bands — a separate volatility-based band using a configurable period and multiplier. These bands are lighter and secondary to the statistical bands.
Squeeze markers appear as small squares along the statistical mean when the Bollinger Bands are contained inside the Keltner Channel — indicating compressed volatility and a potential breakout.
2.3 Signal markers
Signals are plotted directly on the ratio chart using triangles and circles. All markers use plotshape, not labels.
Large triangles up (green) — strong bull confluence (score above +6)
Large triangles down (red) — strong bear confluence (score below -6)
Small triangles up (faded green) — moderate bull confluence (score between +3.5 and +6)
Small triangles down (faded red) — moderate bear confluence (score between -3.5 and -6)
Cyan circles — bullish momentum divergence aligned with positive score
Orange circles — bearish momentum divergence aligned with negative score
Purple squares — active volatility squeeze
3. The eight engines
3.1 Relative strength engine
This engine measures how much Asset A is outperforming Asset B on a rate-of-change basis. It computes the ROC of each asset independently over a configurable period (default 14) and subtracts them to get a delta. That delta is then Z-score normalized over a longer lookback (default 50) to assess whether the current outperformance is historically significant.
The engine also tracks the velocity of the ratio itself — the first derivative of the ratio — and whether the ratio is above its own EMA.
Score: +1 when the RS Z-score is above 0.5 and the ratio is above its EMA. -1 when the RS Z-score is below -0.5 and the ratio is below its EMA. 0 otherwise.
The dashboard shows the raw RS Z-score in the state section so you can see how far from neutral the relative strength is reading.
3.2 Trend engine
The trend engine evaluates the EMA alignment of the ratio across three periods (21, 50, 200), the slope direction using linear regression, and optionally a higher timeframe EMA confirmation.
A full bull stack is when EMA 21 is above EMA 50 and EMA 50 is above EMA 200, combined with a positive slope. A full bear stack is the reverse. Transitional states occur when the stack is broken but slope still has a direction.
The HTF trend filter uses a configurable higher timeframe (default weekly) and checks whether the chosen asset is above its 50-period EMA on that timeframe. When enabled, the trend engine only scores positively if the HTF also confirms.
Score: +1 for confirmed bull trend. -1 for confirmed bear trend. 0 for compression or transition.
The trend state shown in the dashboard (Expansion, Contraction, Transitional, Compression) reflects the combination of stack state and slope direction.
3.3 Momentum engine
The momentum engine uses a volume-weighted RSI applied to the ratio. The weighting uses the combined average volume of both assets, normalized by its own moving average. This is the same architecture as VW RSI Pro — gains and losses are scaled by relative volume before the RSI calculation, so bars with above-average volume have more influence on the RSI than bars with below-average volume.
Alongside the VW RSI, the engine computes MACD histogram acceleration (the change in histogram value, not just its level). This distinguishes between momentum that is building and momentum that is present but decelerating.
Score: +1 when VW RSI is above 52 and MACD histogram is positive. -1 when VW RSI is below 48 and MACD histogram is negative. 0 otherwise.
The VW RSI value is shown in the state section of the dashboard. Values above 55 are colored green, below 45 red, between them grey.
3.4 Volatility engine
The volatility engine assesses whether the ratio is in a phase of compression or expansion, and which direction expansion is occurring.
It computes Bollinger Band width relative to its 100-bar average — widening bands indicate expansion, narrowing bands indicate compression. ATR percentile rank over a configurable lookback (default 100 bars) provides a second volatility measure. A squeeze is identified when the Bollinger Bands are fully contained within the Keltner Channel.
Score: +1 when volatility is expanding and the ratio is above the Bollinger midline, or when a squeeze releases upward. -1 for the same conditions in the downward direction. 0 during compression or neutral volatility states.
The vol state (Squeeze, Breakout, Expansion, Compression, Neutral) is shown in the dashboard state section. Squeeze appears in purple, breakout in gold, expansion in the configured bull color.
3.5 Statistical extremes engine
This engine measures where the current ratio stands within its own historical distribution. It computes a Z-score of the ratio over a configurable lookback (default 50) and a historical percentile rank over a longer window (default 252 bars, approximately one year of daily data).
When the ratio is more than 1.5 standard deviations above its mean and above the 80th percentile, it is classified as historically expensive — a potential mean reversion candidate to the downside. When it is more than 1.5 standard deviations below its mean and below the 20th percentile, it is historically cheap — a potential mean reversion candidate to the upside.
Score: +1 at extreme lows (below mean, below 20th percentile). -1 at extreme highs (above mean, above 80th percentile). 0 within normal range.
The Z-score and historical percentile are shown in the dashboard state section. A gold highlight on the Z-score indicates an active extreme condition.
The mean reversion probability displayed in the extended panel is a normalized version of the absolute Z-score distance — a rough proxy for how far the ratio has stretched from its historical center. It is not a probability in the statistical sense, but a relative measure of extension.
3.6 Macro regime engine
The macro regime engine uses three external data feeds — DXY (dollar index), VIX (volatility index), and TNX (10-year Treasury yield) — loaded via request.security(). It evaluates the trend direction of each feed relative to a smoothed EMA (configurable length, default 20) and classifies the current macro environment.
The global regime classification (Risk-On / Risk-Off / Mixed) appears in the dashboard header. It is always based on the same three-signal count regardless of asset class: VIX level, DXY trend, and yield direction.
The macro score, however, is class-aware. Each asset class has its own logic:
Gold / Silver — risk-off conditions (elevated VIX, falling yields, falling dollar) favor Asset A (gold). Risk-on conditions (low VIX, rising yields, rising dollar) favor Asset B (silver outperforms on industrial demand). Score is +1 for acute risk-off, -1 for sustained risk-on.
Crypto — DXY direction is the primary gatekeeper. Falling DXY and falling yields are bullish for crypto. Rising DXY and rising yields are bearish. VIX provides a third signal. Two of the three conditions must align for a score to fire.
Forex — trend-following regime logic. Risk-on environments favor the ratio direction, risk-off favors the reverse.
Indices — same structure as Forex. Risk-on = positive bias.
Commodities — DXY-led. Falling dollar supports commodity ratios.
Score: +1 for regime favorable to Asset A. -1 for regime favorable to Asset B. 0 for mixed.
3.7 Liquidity engine
The liquidity engine uses the 10-year Treasury yield (TNX) rate of change as a proxy for liquidity conditions. Falling long-term yields indicate looser financial conditions — lower cost of capital, more risk appetite. Rising yields indicate tightening.
The TNX rate of change is computed over 20 bars and smoothed with a 10-bar EMA. When the smoothed ROC is below -0.1, conditions are classified as expanding. Above +0.1, contracting.
Score logic is class-aware:
- Gold / Silver — expanding liquidity (falling yields) is positive for the ratio since gold benefits more from low rates. Contracting is negative.
- Crypto — same direction. Loose liquidity benefits risk assets.
- Forex — inverted. Rising yields support yield-differential-driven pairs.
- Other classes — expansion is positive.
Score: +1 for favorable liquidity, -1 for unfavorable, 0 for neutral.
3.8 Intermarket correlation engine
This engine computes the rolling Pearson correlation between the ratio and each macro feed (DXY, VIX, TNX) over a configurable window (default 30 bars). It then assesses whether the current correlations match the expected structural behavior for the selected asset class.
For the Gold/Silver ratio, for example, historically the ratio is positively correlated with VIX (risk-off pushes gold relative to silver) and negatively correlated with DXY (weaker dollar benefits silver less). When those correlations are in place and above a threshold (±0.15), the engine confirms the macro alignment.
A correlation shift is detected when the sign of a correlation flips compared to 10 bars ago — this is flagged in the dashboard as a regime change signal.
Score: +1 when correlations confirm expected behavior for Asset A outperformance. -1 when they confirm the reverse. 0 when correlations are below threshold or mixed.
3.9 Volume participation engine
This engine measures whether the volume behind the ratio's current move confirms its direction. It uses two inputs: the relative volume difference between Asset A and Asset B, and the slope of the on-balance volume (OBV) calculated on the ratio.
The relative volume comparison checks whether Asset A is attracting more volume than Asset B relative to their combined average. When Asset A draws disproportionately more volume, it indicates institutional interest in the primary asset. The OBV slope uses a 20-bar linear regression to determine whether cumulative directional volume is rising or falling.
A bullish confirmation requires the OBV slope to be positive, the ratio to be above its 21 EMA, and Asset A to have higher relative volume. A bearish confirmation requires the reverse. When volume diverges from price direction — OBV falling while price rises, or vice versa — this is flagged in the extended panel as a volume divergence warning.
Score: +1 when volume participation confirms the ratio move upward. -1 when it confirms downward. 0 when volume is inconclusive or mixed.
4. Adaptive weighting
Each engine returns -1, 0, or +1. Each score is multiplied by the engine's weight for the selected asset class. The sum of all nine weighted scores is normalized against the total possible weight to produce the final confluence score on a -10 to +10 scale.
Asset class presets:
Gold / Silver — statistical extremes and macro regime are weighted most heavily (14 each). This reflects the GSR's mean-reverting nature and strong sensitivity to macro conditions. Volume participation carries moderate weight — on the GSR, volume confirmation is useful but less decisive than macro state.
Crypto — liquidity and momentum are weighted most heavily (14 each). Volume participation also carries elevated weight, since capital rotation between an asset and stablecoins is directly visible in relative volume.
Forex — trend and correlation are weighted most heavily (14 each). Currency pairs respond to trend conditions and intermarket relationships more reliably than statistical extremes.
Indices — momentum and liquidity are weighted most heavily (14 each). Volume participation also carries elevated weight — index futures moves backed by strong volume are more reliable than low-volume drifts.
Commodities — relative strength and volatility are weighted most heavily (14 each). Volume participation carries moderate weight since commodity ratio moves are often driven by volume imbalances between the two assets.
Custom — all nine weights are individually configurable from 0 to 20.
The confidence percentage shown in the dashboard is the spread between the normalized bull and bear score components — a measure of how much the engines agree rather than merely how many fire.
5. Dashboard
The dashboard is a single compact panel with four columns and thirteen rows. It shows the complete scoring state, engine breakdown, and market context in one place.
Header row — indicator name, asset class, confluence label, and score out of 10. The header color reflects the net score direction.
Confidence and regime row — confidence percentage and the global macro regime (Risk-On / Risk-Off / Mixed).
Engine scores — eight engines displayed two per row across four columns. Each engine shows its label and its weighted score with direction indicator. A green upward triangle indicates a positive contribution. A red downward triangle indicates a negative contribution. A grey dot indicates a neutral score.
State section — trend state, volatility state, VW RSI value, and Z-score. The trend state label (Expansion, Contraction, Transitional, Compression) reflects the combination of EMA alignment and slope. The vol state (Squeeze, Breakout, Expansion, Compression, Neutral) reflects the Bollinger/Keltner relationship.
Macro feeds — DXY direction, VIX level, 10-year yield direction, and current divergence state.
Brand footer — version reference.
The extended macro panel (disabled by default) can be enabled in settings for a second panel showing full correlation values, ATR percentile, statistical state detail, OBV slope, volume participation score, volume divergence flag, and liquidity state.
6. Asset pair configuration
6.1 Gold/Silver ratio (GSR)
The gold/silver ratio is the primary design case for ICE. It measures how many ounces of silver are required to buy one ounce of gold. Historically the ratio has ranged between 15 and 120. It is mean-reverting over long cycles but can trend persistently for months or years.
Recommended setup:
- Asset A: OANDA:XAUUSD
- Asset B: OANDA:XAGUSD
- Asset class: Gold / Silver
The statistical extremes engine is particularly relevant here. When the ratio is near historical highs (above the 80th percentile, Z-score above 1.5), silver has historically outperformed gold significantly over the following months. When near historical lows, gold has tended to recover its premium.
The macro regime engine is also central. Acute risk-off events (2008, 2020) spike the GSR rapidly as gold outperforms. Sustained risk-on environments with rising yields and industrial demand tend to compress it.
6.2 Crypto setups
For crypto ratio analysis, stablecoin dominance (CRYPTOCAP:USDT.D) as Asset B provides a direct view of capital rotation between an asset and cash equivalents. When the ratio rises, the asset is gaining relative to stablecoins — capital is flowing in. When it falls, capital is rotating out.
Recommended setups:
- BINANCE:BTCUSDT / CRYPTOCAP:USDT.D — Bitcoin vs stablecoin dominance
- BINANCE:SOLUSDT / CRYPTOCAP:USDT.D — SOL vs stablecoin dominance
- BINANCE:ETHUSDT / CRYPTOCAP:USDT.D — ETH vs stablecoin dominance
- Asset class: Crypto for all of the above
BTC.D (Bitcoin dominance, CRYPTOCAP:BTC.D) as Asset B can be used to measure altcoin performance relative to Bitcoin specifically — useful for identifying altseason conditions.
6.3 NQ futures setups
For Nasdaq and MNQ trading, ratio analysis provides directional and regime context.
Recommended setups:
- CME_MINI:NQ1! / CME_MINI:ES1! — Nasdaq vs S&P 500. When this ratio rises, tech is outperforming the broad market. A falling ratio suggests defensive rotation or underperformance of growth. Asset class: Indices.
- CME_MINI:NQ1! / CME_MINI:RTY1! — Nasdaq vs Russell 2000. Large-cap growth vs small-cap. Risk appetite proxy. Asset class: Indices.
- CME_MINI:NQ1! / TVC:DXY — NQ relative to dollar strength. Strong inverse relationship historically. Asset class: Indices.
6.4 Precious metals and commodities
- OANDA:XAUUSD / TVC:DXY — gold relative to dollar. One of the cleanest inverse relationships in macro markets. Asset class: Commodities or Gold/Silver.
- OANDA:XAUUSD / CME_MINI:ES1! — gold vs equities. Risk-off proxy. When this ratio rises, gold is outperforming stocks. Asset class: Commodities.
- TVC:USOIL / TVC:NATGAS — oil vs natural gas relative value. Asset class: Commodities.
6.5 Forex setups
For currency pairs, use the pair itself as a ratio — Asset A as the base currency ETF or index, Asset B as the quote. Alternatively, use currency index feeds directly.
- FX:EURUSD as a direct entry (ratio of EUR to USD)
- TVC:DXY / FX:EURUSD — dollar index vs euro. Asset class: Forex.
7. Macro feeds
The three macro feeds are loaded via request.security() and must resolve on PulseWire.
Default symbols:
- DXY: TVC:DXY
- VIX: CBOE:VIX
- 10-year yield: TVC:TNX
These can be changed in the Macro Feeds settings group if alternative data sources are preferred. Each feed can be individually disabled — if all three are disabled, the macro regime, liquidity, and correlation engines return neutral (0) scores.
On lower timeframes (1m, 3m), macro feeds may have limited bar history, which can cause some engines to return neutral until sufficient data is loaded. From 15m and higher, all engines should be fully active. On very low timeframes, the statistical engines also require a minimum number of bars before the lookbacks are satisfied.
8. How to use
8.1 Reading the score
The confluence score on a -10 to +10 scale communicates direction and intensity simultaneously. It does not communicate timing.
A score of +7 with 70% confidence means six or seven engines are aligned in a bullish direction for Asset A relative to Asset B, with the weighted agreement being high. It does not mean a trade should be entered immediately — it means the current relative conditions strongly favor Asset A.
A score near 0 with low confidence means the engines are split. This is not a bearish signal — it is the absence of a clear signal. In practice, scores between -3 and +3 with confidence below 40% suggest the ratio is in a mixed or transitional regime.
8.2 Using the score with price action
ICE works on the ratio — not on the underlying price. To apply it to a trade on the underlying asset, you need to interpret the score in context.
On a BTC/USDT.D ratio chart with a score of -7, the ratio is falling — BTC is losing ground relative to stablecoin dominance. This is a macro tailwind for a bearish BTC view. It does not tell you where to enter or where to put your stop. It tells you the broader relative conditions are bearish.
Combine ICE with a price-action tool, a structure indicator, or an entry system applied to the actual trading instrument. ICE provides the regime and relative context. The entry decision remains with the user.
8.3 Divergence signals
When the ratio makes a lower low but the VW RSI makes a higher low, a bullish divergence is detected. When the ratio makes a higher high but the VW RSI makes a lower high, a bearish divergence is detected. These are mechanical detections using pivot analysis.
Divergence signals that align with the net confluence score carry more weight. A bullish divergence on a ratio that is already scoring positively on four or five engines is a stronger condition than a divergence in an otherwise neutral scoring environment. Cyan circles mark bull divergence, orange circles mark bear divergence.
8.4 Squeeze and volatility breakouts
When the volatility engine identifies a squeeze (Bollinger Bands inside the Keltner Channel), a purple square appears along the statistical mean line. This indicates compressed volatility and an elevated probability of a significant directional move.
When the squeeze releases, the volatility engine contributes its score in the direction of the breakout. Combined with trend and momentum alignment, a squeeze release can produce a rapid score shift. These moments are marked on the chart and flagged in the dashboard vol state row.
8.5 Statistical extremes
The statistical engine is most useful on the Gold/Silver ratio and other fundamentally mean-reverting pairs. When the Z-score exceeds 1.5 and the ratio is in the top 20% of its historical range, the statistical engine scores negatively — signaling that the ratio has historically tended to revert from this level.
This is not a timing signal. The ratio can remain at extremes for weeks or months. The statistical engine scores the degree of extension, not the moment of reversal. Use it alongside momentum and trend engines to assess whether the extreme is beginning to resolve.
9. Settings reference
Asset configuration
- Asset A — the primary asset. Default: XAUUSD.
- Asset B — the secondary asset. Default: XAGUSD. The ratio is Asset A divided by Asset B.
- Plot ratio line — toggles the main ratio line on the chart.
- Plot ratio EMAs — toggles the 21/50/200 EMA stack on the ratio.
- Plot std dev bands — toggles the statistical deviation bands and Bollinger Bands.
Asset class and weighting
- Asset class — selects the weighting preset. Options: Gold/Silver, Crypto, Forex, Indices, Commodities, Custom.
- Individual weight inputs — only active in Custom mode. Each engine can be weighted from 0 to 20.
Macro feeds
- Use DXY / VIX / TNX — individual toggles for each macro feed.
- DXY / VIX / TNX symbol — configurable symbols. Defaults: TVC:DXY, CBOE:VIX, TVC:TNX.
- Macro smoothing — EMA length for the macro feed trend detection. Default 20.
Relative strength engine
- ROC length — rate of change period for both assets. Default 14.
- RS EMA length — EMA applied to the ratio for trend confirmation. Default 21.
- RS Z-score lookback — lookback for normalization of the RS delta. Default 50.
Trend engine
- Fast / Slow / Macro EMA — the three EMA periods for the ratio. Defaults: 21, 50, 200.
- MTF trend filter — enables the higher timeframe confirmation gate.
- HTF timeframe — the timeframe used for the HTF EMA check. Default weekly.
Momentum engine
- RSI length — period for the VW RSI calculation. Default 14.
- Volume smoothing — SMA length for volume normalization. Default 14.
- Volume weighted RSI — enables volume weighting on the RSI. Default on.
- MACD fast / slow / signal — MACD parameters applied to the ratio. Defaults: 12, 26, 9.
Volatility engine
- BB length / BB multiplier — Bollinger Band parameters. Defaults: 20, 2.0.
- ATR length — period for ATR calculation. Default 14.
- ATR percentile lookback — historical window for ATR percentile ranking. Default 100.
- Squeeze KC length / multiplier — Keltner Channel parameters for squeeze detection. Defaults: 20, 1.5.
Statistical extremes engine
- Z-score lookback — window for Z-score calculation. Default 50.
- Percentile lookback — historical window for percentile ranking. Default 252 (approximately one year of daily data).
- Z-score extreme threshold — standard deviations from mean required to classify as extreme. Default 1.5.
Correlation engine
- Correlation window — rolling window for Pearson correlation. Default 30.
Visuals
- Bull / bear / neutral color — configurable colors for all directional elements.
- Ratio line color — color of the main ratio line.
- Show score background — colors the pane background faintly by net score direction.
- Background transparency — transparency level for the score background. Default 93.
Dashboard
- Show dashboard — master toggle. Default on.
- Position — Top Left, Top Right, Bottom Left, Bottom Right. Default Bottom Right.
- Size — Tiny, Small, Normal. Default Tiny.
- Show extended macro panel — enables a second panel with full correlation, volume, and statistical detail. Default off. Recommended for desktop only.
10. Notes
- ICE operates on a ratio of two assets. If either asset has no data on the current chart timeframe, the ratio will be unavailable and the engines will not fire. Ensure both symbols resolve correctly in PulseWire before interpreting the dashboard.
- The macro feeds (DXY, VIX, TNX) are loaded separately via request.security(). On lower timeframes, the feed data may require a few bars to warm up before producing stable readings. All engines should be fully active from the 15m timeframe and above.
- The volume used by the momentum engine is the combined average of both asset volumes. On ratio pairs where one or both assets have zero or unavailable volume (such as some index feeds), the volume-weighted RSI falls back to an unweighted RSI automatically.
- All statistical calculations (Z-score, percentile rank) require a minimum number of bars equal to the lookback period. On charts with limited history or very short timeframes, these engines may return neutral until sufficient bars are loaded.
- The correlation engine requires both assets to have non-constant price series over the correlation window. On very stable or pegged assets, correlation may be undefined and the engine returns neutral.
- ICE does not repaint. All scores and signals are based on confirmed bar data.
- The indicator is designed for ratio analysis. It can technically be used with a single asset by setting Asset B to a constant reference (such as a stablecoin or index), but it was built around the two-asset ratio concept and performs best in that context.
11. Disclaimer
This indicator is provided for educational and informational purposes only.
All outputs are based on historical price data and mathematical calculations.
Past behavior does not guarantee future results.
Trading involves substantial risk of loss.
Use at your own discretion.
Indicator

ATR Exceedance Probability Model [LuxAlgo]The Volatility Exceedance Probability Model (VEPM) indicator is a comprehensive statistical tool designed to quantify the significance of volatility spikes, determine the likelihood of trend continuation, and categorize market environments into specific regimes.
🔶 USAGE
The indicator provides a multi-layered view of volatility, allowing traders to distinguish between standard market noise and statistically significant "exceedance" events.
🔹 Oscillator Interpretation
The main oscillator plots the current exceedance frequency (the rate at which price or range breaches ATR-based thresholds) against a long-term baseline.
Bullish/Significant Glow: When the Z-Score of the frequency exceeds the sensitivity threshold, the oscillator glows green, indicating a high-probability volatility expansion.
Bearish/Normal Glow: When the frequency falls below the baseline, the oscillator shifts toward red, signaling a contraction in volatility.
Frequency Delta: The area between the current frequency and baseline frequency is filled to highlight the momentum of volatility expansion or exhaustion.
🔹 Chart Visuals & Regimes
The script overlays information directly on the price action to provide context:
ATR Bands: Dynamic bands based on the Average True Range act as the "exceedance" barrier.
Regime Boxes: The indicator automatically identifies "Quiet," "Normal," and "High Vol" regimes. These are visualized as colored boxes (defaulting to High Vol) to show the duration and range of specific volatility climates.
Significance Dots: Circles appear at the top of the chart to mark bars that have breached the volatility threshold.
🔹 Dashboard Metrics
A real-time dashboard provides quantitative data:
Exceedance Freq: The percentage of bars in the short-term window that breached the ATR levels.
Serial Break Prob: The historical probability that a breach will be followed by another breach (continuation).
Clustering Edge: The statistical advantage of volatility clustering; a positive value suggests that volatility is currently feeding on itself.
🔶 DETAILS
The VEPM operates on the principle that volatility is not constant but "clusters" in time. It uses the following logic to derive its metrics:
Exceedance Detection: It calculates whether the current price range (True Range) or price levels (High/Low) exceed a user-defined ATR multiplier.
Statistical Z-Score: By comparing the current frequency of these breaches to a long-term baseline (200 bars by default), the model calculates a Z-Score to determine if the current activity is statistically "abnormal."
Continuation Probability: The model looks back at previous breaches and calculates how often they resulted in immediate follow-through, providing a "Serial Break" percentage.
🔶 SETTINGS
🔹 Core Settings
ATR Length: The lookback period used for the Average True Range calculation.
ATR Multiplier: The threshold used to define what constitutes a "breach" or exceedance.
Breach Detection Method: Choose between comparing the bar's total range to ATR or checking if price levels exceed the previous bar's bands.
🔹 Statistical Windows
Short-Term Window: The period used to calculate the current exceedance frequency.
Baseline Window: The long-term period used to establish the "normal" mean of volatility frequency.
Z-Score Sensitivity: Determines the threshold for identifying statistically significant volatility spikes.
🔹 Visuals
Show ATR Bands: Toggles the visibility of the ATR-based levels on the chart.
Bands Mode: Determines if bands are offset from a central basis (SMA/EMA) or from the bar's High/Low.
Regime Box Options: Toggles background boxes for Quiet, Normal, or High Volatility regimes.
🔹 Dashboard
Dashboard: Enables or disables the on-screen information table.
Position/Size: Controls the location and scale of the dashboard UI.
Indicator

Cloud Institutional Bands | Rainbow MatrixGENERAL OVERVIEW
The Cloud Institutional Bands is a statistical price-envelope indicator that maps institutional accumulation and exhaustion zones using deviation channels built on a Log-Normal regression anchored to a dynamic VWAP. Instead of treating the chart as a series of fixed support and resistance levels, the indicator continuously classifies the current price into one of four statistical regimes — and colors the chart accordingly.
The main goal of this indicator is to give traders a clean, automatic read on how stretched price is relative to its own statistical baseline — without having to manually identify trend strength, overextension, or exhaustion zones bar by bar. Every band you see on the chart represents a specific deviation from the volume-weighted regression base, and every color tells you which statistical zone is currently active.
It plots four pairs of deviation bands (eight bands in total: four above the regression base and four below), each calibrated to a Fibonacci-proportioned sigma multiplier. Combined with the dynamic VWAP and the Zone Info Panel, the indicator gives a complete read on directional bias, statistical position, and proximity to extreme zones — all from a single visual.
This indicator was developed for traders who already understand band-based indicators (Bollinger, Keltner, Donchian) and want a statistically corrected envelope that handles asymmetric price distributions properly, particularly during volatility expansion phases.
WHAT IS THE THEORY BEHIND THIS INDICATOR?
Most envelope indicators on PulseWire — Bollinger Bands, Keltner Channels, and their derivatives — share a common architectural choice: they apply standard deviation directly to the price series, using a Simple Moving Average (or similar linear estimator) as the central tendency. This treats price as a symmetric variable.
The problem: price is not symmetric. Price has a hard floor at zero and unbounded upside. Its returns follow a log-normal distribution, not a normal one. Applying linear statistics to asymmetric data introduces a systematic bias — bands that are too wide on one side and too narrow on the other, especially during volatility expansion. This bias becomes most visible at exactly the moments traders need accuracy most: trend climaxes, blow-off tops, capitulation lows.
This indicator addresses that bias by performing the regression in log space. The price series is first transformed via the natural logarithm, the linear regression is fitted on the log-prices, the standard deviation of the residuals is computed, and the resulting deviation bands are exponentiated back to price space. The math is standard — what makes it useful is applying it to a series that actually follows the underlying distribution it assumes.
Why traders use it: each band represents a probabilistic boundary. When price sits between the regression base and the first deviation band, it is statistically inside its normal operating range — equilibrium. When price crosses into the second band, the move has crossed into directional territory. The third band marks the threshold beyond which most of the impulse has already happened — exhaustion. The fourth band marks the tail of the distribution — a Black Swan event in Taleb's sense — where less than 1% of candles reach under normal conditions.
The dynamic VWAP overlay adds a second dimension: directional bias. While the regression bands tell you how stretched price is, the VWAP tells you whether the volume-weighted average favors buyers or sellers. Together they give a two-axis read on every bar: directional bias plus statistical zone.
CLOUD INSTITUTIONAL BANDS FEATURES
The indicator includes 6 main features:
Log-Normal Regression Engine
Fibonacci-Proportioned Deviation Bands
Dynamic VWAP with Glow
Rainbow Zone Fills
Zone Info Panel (HUD)
Black Swan Alerts
Multilingual interface and full customization across all visual layers.
LOG-NORMAL REGRESSION ENGINE
🔹 What It Does
The core of the indicator. Every bar, the engine performs four operations:
◇ Transforms the price series (hlc3) into log space via the natural logarithm.
◇ Fits a linear regression through the log-prices over the configured lookback window.
◇ Computes the standard deviation of the residuals — the gap between actual log-price and the regression line.
◇ Exponentiates the regression line and the deviation bands back to price space.
The result is a statistical baseline (the Base Line) and four pairs of deviation bands that respect the asymmetric nature of price distribution.
🔹 Method
The regression base is calculated using a standard linear regression on the log-price series. This is the classic least-squares fit — every bar in the lookback window contributes equally. The result is a baseline that represents where the market would be statistically if it were tracking its own trend perfectly.
🔹 Period
The Band Period input sets the rolling lookback window for both the regression and the standard deviation calculation. Larger values produce smoother, wider bands that respond slowly to new price action. Smaller values produce tighter, more reactive bands that follow recent volatility more closely. The default is 200 bars, calibrated for the 223-minute Bitcoin chart. For other instruments and timeframes, the period should be adjusted to match the natural cycle length of the asset.
FIBONACCI-PROPORTIONED DEVIATION BANDS
🔹 The Four Sigma Multipliers
Instead of plotting bands at integer multiples of the standard deviation (1σ, 2σ, 3σ), this indicator uses Fibonacci-inspired proportions:
◇ ±1.50σ — Breathing Zone (yellow above, green below)
◇ ±1.85σ — Alert Zone (orange above, teal below)
◇ ±2.75σ — Exhaustion Zone (red above, blue below)
◇ ±3.85σ — Black Swan Zone (purple above, aqua below)
Each multiplier corresponds to a different probabilistic regime:
◇ Breathing Zone: equilibrium. Most candles operate inside this range. Low conviction, no signal.
◇ Alert Zone: directional move in progress. Trend is asserting itself. Watch for follow-through.
◇ Exhaustion Zone: most of the impulse has already happened. Pullback probability rising. New entries in trend direction have unfavorable risk-reward.
◇ Black Swan Zone: statistical extreme. Less than 1% of candles reach this band under normal market conditions. Elevated probability of either mean reversion or volatility regime change.
snapshot
DYNAMIC VWAP WITH GLOW
🔹 What It Does
A Volume-Weighted Moving Average is plotted alongside the regression bands, using the same lookback window. The VWAP renders in teal when price trades above it (bullish bias) and in red when price trades below (bearish bias).
🔹 Glow Effect
The VWAP line carries a proximity-based glow: the closer price gets to the VWAP, the more intense the glow becomes. This visual cue prepares the eye for proximity to a high-liquidity zone, where reactions often occur.
🔹 Why It Matters
The regression bands tell you how stretched price is. The VWAP tells you what bias the volume-weighted average favors. Together they give a complete read on every bar:
◇ Price above VWAP and inside Breathing Zone: healthy uptrend.
◇ Price above VWAP and at +2.75σ: uptrend in exhaustion.
◇ Price below VWAP and at -3.85σ: capitulation or imminent reversal.
RAINBOW ZONE FILLS
🔹 What They Show
The space between adjacent deviation bands is filled with a semi-transparent color matching the zone palette. This makes the current zone immediately visible without having to read the Z-Score number — the chart background tells you the regime at a glance.
🔹 Toggleable
Fills can be turned off for traders who prefer to see only the band lines themselves. The lines alone (with the Base Line and VWAP) still provide all the information; the fills are a visual aid to make zone identification faster.
ZONE INFO PANEL (HUD)
🔹 What It Shows
A compact corner panel reports three live values:
◇ ZONE — the name of the currently active zone (e.g., "ALERT — HIGH RISK ZONE", "EQUILIBRIUM — BASE LINE")
◇ DEV. — the current Z-Score, expressed in standard deviations (e.g., "+2.44σ")
◇ VWAP — the current position relative to the dynamic VWAP ("VWAP: BUY ZONE" or "VWAP: SELL ZONE")
🔹 Why It Helps
The HUD removes the need to interpret colors and band positions visually. It tells you in plain language where price is, how stretched it is, and which direction the volume-weighted bias is leaning. Useful for live trading where decisions need to happen quickly.
🔹 Customization
The HUD can be positioned in any of the four chart corners and rendered in any of five font sizes. The display language is controlled by the System Language input.
snapshot
BLACK SWAN ALERTS
🔹 What Triggers
The indicator fires an alert when price touches the ±3.85σ band — the Black Swan zone. Two separate alerts are available: one for the upper extreme (potential capitulation top), one for the lower extreme (potential capitulation bottom).
🔹 How They Fire
Alerts are gated by barstate.isconfirmed, which means they only trigger on the close of the bar that touched the band — not intra-bar. This prevents false signals from wicks that get rejected before the bar closes.
🔹 Frequency
Each alert uses alert.freq_once_per_bar, ensuring no duplicate firings on the same candle.
MULTILINGUAL INTERFACE
The indicator supports five languages for the HUD display and alert messages: English (default), Português, Español, Русский, and 中文 (Chinese). Code, comments, and configuration tooltips remain in English regardless of the selected language.
For reference, the English text of all multilingual UI strings used in the HUD and alerts:
◇ BLACK SWAN — EXTREME HIGH / BLACK SWAN — EXTREME LOW
◇ BUYING EXHAUSTION / SELLING EXHAUSTION
◇ ALERT — HIGH RISK ZONE / ALERT — LOW RISK ZONE
◇ INSTITUTIONAL BREATHING ZONE
◇ EQUILIBRIUM — BASE LINE
◇ VWAP: BUY ZONE / VWAP: SELL ZONE
◇ ZONE: / DEV.: / VWAP:
◇ Black Swan Alert High: "Price at 4th standard deviation — EXTREME HIGH. High probability of severe reversal."
◇ Black Swan Alert Low: "Price at 4th standard deviation — EXTREME LOW. High probability of explosive reversal."
HOW TO USE
This indicator is not a signal generator. It is a state classifier: it tells you which statistical zone the current price is in, and how that zone relates to the volume-weighted bias.
🔹 Reading the Chart
◇ Identify the current Z-Score from the Zone Info Panel.
◇ Note the active zone color in the panel and on the chart fills.
◇ Combine with VWAP position for directional context.
🔹 Tactical Reading
◇ Z-Score between -1.50 and +1.50: market is in equilibrium. Mean-reversion strategies have higher edge than breakout strategies.
◇ Z-Score crossing ±1.85: breakout in progress. Trend-following entries have higher edge than fade entries.
◇ Z-Score at ±2.75: trend is mature. Trailing stops should be tightened. New entries in trend direction have unfavorable risk-reward.
◇ Z-Score touching ±3.85: Black Swan touch. Statistically the tail. Mean reversion has elevated probability — but Black Swans can also indicate regime change, where volatility expands and a new range opens. Use the Black Swan Alert to catch these events.
🔹 Multi-Timeframe Reading
◇ On lower timeframes (1m, 5m, 15m), the bands react to micro-trends and serve as dynamic support and resistance.
◇ On higher timeframes (1h, 4h, daily), the bands map macro regime — the outer bands at higher timeframes represent multi-day exhaustion zones.
INPUTS EXPLAINED
🔹 System Language
Display language for the HUD and alert messages. Options: English (default), Português, Español, Русский, 中文 (Chinese).
🔹 Band Period (bars)
Rolling lookback for the Log-Normal regression and the VWAP. Range 50–500, default 200. Higher values produce smoother, wider bands; lower values produce tighter, more reactive bands.
🔹 Show Thermal Zone Fills
Toggle for the semi-transparent rainbow fills between adjacent bands.
🔹 Show Black Swan Glow (4th Std Dev)
Toggle for the glow effect on the outermost ±3.85σ bands. The glow intensifies as price approaches the band.
🔹 Show Base Line (Gravitational Center)
Toggle for the regression central line — the statistical baseline around which the bands are computed.
🔹 Show Dynamic VWAP (Macro)
Toggle for the volume-weighted reference line with proximity glow.
🔹 Show Zone Info Panel
Toggle for the corner HUD reporting current zone, Z-Score, and VWAP position.
🔹 Panel Position
Position of the HUD on the chart. Four corners available: Top Right (default), Top Left, Bottom Right, Bottom Left.
🔹 Font Size
HUD font size. Options: Tiny (default), Small, Normal, Large, Huge.
🔹 Black Swan Alert (4th Std Dev touch)
Toggle for the alerts that fire when price touches the ±3.85σ band. Two alerts: one for the upper extreme, one for the lower extreme.
IMPORTANT NOTES
The Cloud Institutional Bands works on any timeframe. The Band Period default of 200 is calibrated for the 223-minute chart and may need adjustment for other timeframes — a good rule of thumb is to set the period to approximately one full daily cycle for the chart timeframe (e.g., 288 bars for 5-minute charts, 96 bars for 15-minute charts).
The indicator works best on instruments with reliable volume data: crypto perpetual contracts, large-cap equities, major forex pairs. On low-volume instruments, the dynamic VWAP component becomes less reliable, though the regression bands continue to function correctly.
Alerts fire once per confirmed bar. Historical bars never repaint after they close. The live bar updates intra-bar as expected for a real-time indicator.
The four sigma multipliers (1.50, 1.85, 2.75, 3.85) are intentionally non-standard. They are Fibonacci-inspired proportions, not arbitrary choices, and they map to four behavioral regimes derived from observation rather than to integer statistical thresholds.
Pine Script v6. Open-source under Mozilla Public License 2.0.
UNIQUENESS
The Cloud Institutional Bands is unique in three ways. First, it performs the regression in log space, addressing the asymmetric nature of price distribution that linear estimators (such as the Simple Moving Average used by Bollinger Bands) fail to account for. This produces bands that behave correctly during volatility expansion phases, where standard envelopes show systematic bias. Second, it uses Fibonacci-proportioned sigma multipliers (1.50, 1.85, 2.75, 3.85) instead of integer steps, mapping the bands to four behavioral regimes — breathing, alert, exhaustion, and Black Swan — that correspond to observable phases of institutional order flow rather than to arbitrary thresholds. Third, it integrates a dynamic VWAP overlay with proximity-based glow alongside the regression bands, giving traders a two-axis read on every bar: how stretched price is statistically, and which direction the volume-weighted bias favors. The combination of log-space regression, Fibonacci sigma calibration, and integrated VWAP context produces a statistical envelope that behaves differently from standard band-based indicators, particularly at trend climaxes and capitulation events where standard envelopes are least reliable. Indicator

Z-Score Probability Pro KAMA
Z-Score Probability Pro KAMA, v1.0 by Erika Barker
Hey guys, this is the successor to my original Z-Score Probability HMA Indicator, which you can still use if you prefer that one.
This is version 1.0 of the new rebuild, and it is a pretty big upgrade. The goal was to keep the statistical foundation that made the original useful, but make it more adaptive, cleaner, and better at understanding different market conditions.
What is new
1. Timeframe auto-adaptation
No more constantly re-tuning the indicator when you switch charts.
The lookback now automatically adjusts based on the chart timeframe, using a calendar-style window, defaulting to about 5 trading days. The dashboard also shows the effective lookback being used, so you always know what the script is calculating from.
It works from 1 minute charts all the way up to weekly charts.
2. Better smoothing logic
The original HMA was doing a lot of work at once. In this version, the baseline and the Z-score smoothing are separated so each one can do its own job better.
By default:
* Baseline: KAMA, great for adapting to noisy markets
* Z-score smoothing: ALMA, smoother and cleaner on the oscillator
HMA is still available if you prefer the original feel.
3. Modified Z-Score option
There is now an optional Modified Z-Score mode using MAD, median absolute deviation.
This is useful for markets with big outliers, fat tails, sudden spikes, crypto moves, small caps, and anything that tends to behave a little wild.
When this mode is turned on, the threshold bands automatically adjust.
4. Regime filter using Hurst logic (been needing out on this a lot lately on personal stuff)
This version attempts to classify the market as:
* Trending
* Mean-reverting
* Random
That matters because an extreme Z-score does not always mean the same thing.
In a mean-reverting market, an extreme Z-score can suggest exhaustion.
In a trending market, that same extreme can sometimes mean continuation or breakout strength.
This was one of the biggest things I wanted to improve from the original.
5. Divergence engine
The indicator now includes both regular and hidden divergence.
It can detect:
* Regular bullish divergence
* Regular bearish divergence
* Hidden bullish divergence
* Hidden bearish divergence
Divergences are confirmed using pivots, so they are non-repainting, but they will appear a few bars after the actual pivot. That is the tradeoff for confirmation.
6. Higher-timeframe confirmation
The script can pull Z-score confirmation from a higher timeframe.
You can use the automatic HTF mode or set it manually. HTF values only update after the higher-timeframe candle closes, so this is designed to avoid repainting.
7. Strong Buy and Strong Sell signals
Signals are based on a confluence score instead of just one condition.
The score looks at things like:
* Z-score reversal
* Divergence
* Baseline slope
* Market regime
* Higher-timeframe agreement
* Volume confirmation, when volume is available
You can choose the conviction level:
* Low
* Medium
* High
Medium is the default and should give fewer, cleaner signals.
8. Live dashboard
The dashboard shows:
* Detected timeframe
* Effective lookback
* Current Z-score
* Market regime
* Hurst value
* Higher-timeframe status
* Bull and bear scores
* Conviction threshold
* Last signal
You can move it to any corner of the chart.
9. More stable defaults
The defaults were chosen to be centered in stable performance zones, not over-optimized for one market.
Basically, I did not want this to be something that only looks good on one ticker, one timeframe, during one perfect backtest window.
10. Built in Pine v6
This version uses Pine v6 features, including dynamic higher-timeframe requests and confirmed-bar alert logic.
Repaint disclosure
This indicator is designed to avoid repainting, but there are a few things to know:
* Divergence and Strong Buy/Sell labels appear after pivot confirmation, default is 3 bars later
* Higher-timeframe confirmation only updates after the higher-timeframe candle closes
* Alerts fire on confirmed bars, not intrabar ticks
So, signals are delayed slightly by design, but that is what makes them confirmed.
How to use it
Beginner
Leave everything on default.
Watch the dashboard and look for:
* Strong Buy
* Strong Sell
Medium conviction is probably the best starting point.
Intermediate
Try the Modified Z-Score mode on crypto, small caps, or anything with sharp moves and big outliers.
Turn on Hidden Divergence if you like trading trend continuation setups.
Advanced
You can tune the component weights to match your own strategy.
The indicator is flexible, so you can make it more reversal-focused, more trend-following, or more confirmation-heavy depending on your trading style. Indicator

Sigma Structure [RWCS]What it is:
Sigma Structure is a confluence-based trading indicator that unifies three distinct analytical layers into a single, cohesive view: a Z-Score oscillator measuring price deviation from its 20 EMA, a normalized MACD histogram for momentum context, and an Order Block detection engine that identifies structural demand and supply zones directly on the price chart. The result is an indicator that tells you not just when price is statistically extended, but where that extension is occurring relative to meaningful price structure — giving every signal a location and every location a statistical weight.
How it works:
1. Z-Score layer: Price is measured as the number of standard deviations it sits above or below its 20-period EMA. This produces an oscillator that reads consistently across any asset or timeframe — a reading of +2 on Bitcoin means the same thing structurally as +2 on the S&P or EURUSD. The line color intensifies from faded to full aqua as it moves above zero, and faded to full fuchsia below, so the degree of extension is immediately legible at a glance. Fixed bands at ±1, ±2, and ±3 sigma define the statistical landscape.
2. MACD layer: A standard MACD histogram is computed normally, then linearly scaled so its rolling peak aligns with the ±3σ band. No calculation is modified — only the display axis is shared with the Z-Score. This means crossovers, divergences, and momentum shifts read identically to a standard MACD, but now live in the same visual space as the bands, letting you see momentum and mean-reversion context simultaneously.
3. Order Block layer: The indicator scans for order blocks using a sequential candle method — a bearish candle followed by a configurable number of consecutive bullish candles (demand), or a bullish candle followed by consecutive bearish candles (supply). Detected zones are drawn directly on the price chart as shaded regions with solid top boundaries and dashed bottom boundaries, color-coded aqua for demand and fuchsia for supply. Zones extend rightward bar by bar and self-invalidate the moment price closes through them, so what you see on the chart is always live and relevant.
4. Confluence signals: Two signal types fire when the Z-Score and Order Block layers align. An OB Reversal label appears when price is inside an Order Block while the Z-Score is at or beyond ±2σ — the statistical extension and the structural level are confirming each other as a fade opportunity. An OB Continuation label appears when price pulls back into an Order Block and the Z-Score reclaims zero — the trend is reasserting after a mean-reversion dip into demand or supply.
5. Volatility divergence: A background highlight layer compares price's rolling highs and lows against the rolling highs and lows of realized volatility (standard deviation of log returns). When price makes a new low without a corresponding expansion in realized volatility, a bullish divergence is flagged. The inverse flags bearish divergence. These are not entry signals on their own — they indicate moments where price action and volatility are telling different stories and warrant closer attention.
Possible ways to use it:
1. Reversal setups: When the Z-Score reaches ±2σ or beyond and price simultaneously tags an active Order Block zone, the statistical extension and structural level are aligned. The OB Reversal label marks these bars. Look for MACD histogram compression or a zero cross in the same window for additional confirmation before acting.
2. Trend continuation entries: In trending markets, price frequently pulls back into demand or supply zones and finds support exactly where it should. When the Z-Score crosses back through zero inside an active zone, the OB Continuation label fires — this is your structural retest with momentum confirmation.
3. Divergence as a filter: The volatility divergence highlights flag potential exhaustion in price moves that lack volatility confirmation. Use these as a reason to tighten risk or wait for the OB/Z-Score confluence before entering, rather than chasing the move.
4. EMA trend bias: The fast and slow EMA overlay on the price chart provides a quick structural read. Aligning your OB Reversal or Continuation signals in the direction of the EMA cross adds a higher-timeframe trend filter without requiring a second indicator.
5. Alert-driven scanning: Three configurable alerts cover the ±2σ Trade Zone cross, OB Reversal confluence, and OB Continuation setup. Set these across a watchlist to surface actionable conditions without manual chart monitoring.
Settings guide:
1. EMA / Std Dev Length: Both default to 20, matching a standard Bollinger Band configuration. Increase for smoother, slower signals on higher timeframes.
2. MACD Norm Lookback: Controls how far back the indicator looks to find the MACD histogram's peak for scaling. Higher values produce more stable scaling; lower values make the histogram more reactive to recent momentum.
3. Sequential Candles for OB: The number of consecutive candles required after the origin candle to confirm a block. Higher values produce fewer, higher-quality zones.
4. Max Active Zones: How many demand and supply zones can coexist on each side. Older zones are removed when the limit is reached.
5. Divergence Lookback: The rolling window for comparing price extremes against volatility extremes. Shorter values produce more frequent signals; longer values are more selective.
Disclaimer:
This indicator is published for educational and informational purposes only. Nothing presented here constitutes financial advice, a solicitation, or a recommendation to buy or sell any financial instrument. All trading involves risk, including the possible loss of principal. Past performance of any indicator or methodology is not indicative of future results. You are solely responsible for your own trading decisions. Always conduct your own research and consult a qualified financial professional before making any investment decisions. Indicator

Indicator

Z-Score Mean Reversion ProZ-Score Mean Reversion Pro is a Strategy designed to identify high-probability mean reversion setups by combining statistical Z-Score extremes with RSI momentum confirmation, Bollinger Band volatility filtering, and EMA trend alignment. It provides clean buy/sell signals, visual trade zones, dashboard data, and alert outputs to assist in short-term reversal trading, intraday setups, and swing mean reversion trades.
🔑 FEATURES
Z-Score Mean Reversion Engine: Detects statistically stretched price moves and highlights potential reversal zones when price deviates too far from its rolling mean.
Multi-Layer Signal Confirmation: Combines RSI exhaustion, Bollinger Band Width volatility checks, and EMA trend filtering to reduce false signals and improve trade quality.
Built-In Risk Management: Includes ATR-based stop loss and take profit logic, plus optional mean reversion exits when price returns toward equilibrium.
⚠️ NOTES & DISCLAIMERS
This script works best on 5m, 15m, 1H, and 4H charts across Forex, Crypto, Indices, and liquid Stocks.
Best suited for mean reversion traders looking to capture exhaustion moves and short-term reversals.
ATR exits are ideal for structured risk management, while Z-Score exits are better for pure statistical reversion setups.
Always use risk management (Stop Loss).
This script is for educational and research purposes only. Always forward test before using live capital.
Strategy

Impulse Structure Zones [JOAT]Impulse Structure Zones
Introduction
Impulse Structure Zones (ISZ) is an open-source, institutional-grade zone engine that detects statistically significant price impulses using a Z-Score methodology, identifies the origin candle of each impulse as an order block, and grades each zone using a multi-factor wick rejection scoring system. Bullish and bearish zones are tracked in parallel arrays with full lifecycle management — creation, extension, mitigation detection, and rejection confirmation — all rendered as clean, non-repainting boxes on the chart with a mid-line bisecting each zone.
The core problem ISZ solves is the manual process of locating high-probability order block zones on a chart. Institutional price delivery frequently originates from specific candles where large orders were placed — the last opposing candle before a strong directional move. ISZ automates the detection of those moves, marks the origin candles, and then monitors each zone to fire a graded rejection signal when price returns to test the level. Grades A, B, and C communicate signal quality based on wick dominance, proportional wick depth, volume confirmation, and candle size relative to ATR.
Core Concepts
1. Z-Score Impulse Detection
Price change is measured bar-by-bar as a percentage move and normalized into a Z-Score against a rolling mean and standard deviation window:
float pxChg = (close - close ) / close * 100.0
float zscore = (pxChg - avgChg) / math.max(stdChg, 0.0001)
A bar qualifies as an impulse when the absolute Z-Score exceeds the user-defined threshold (default: 1.5). This isolates moves that are statistically unusual relative to recent activity — the same principle used in quantitative strategies to filter meaningful displacement from noise. All signals are gated on barstate.isconfirmed to prevent repainting.
2. Order Block Identification
When a bullish impulse is confirmed, ISZ scans back through recent bars to locate the last bearish candle (close < open) before the move. That candle's high and low become the order block zone boundaries. For bearish impulses, the last bullish candle is used. This matches the ICT definition of an order block — the final imbalance candle before institutional displacement.
3. Zone Lifecycle Management
Each zone is stored as a user-defined type (UDT) containing the box object, mid-line, price boundaries, birth bar, direction, mitigation flag, and rejection flag. Zones extend rightward on each bar until price closes beyond the zone (mitigation), at which point the box is frozen and marked as mitigated. A maximum zone count is enforced and oldest zones are trimmed to maintain chart performance.
4. A/B/C Rejection Grading
When price returns to test a live zone and a rejection candle forms, ISZ grades the signal quality using four independent scoring factors:
Wick dominance ratio: The rejection wick length divided by candle body size
Proportional wick depth: The wick as a percentage of the total candle range
Volume confirmation: Current bar volume compared to the 20-bar average
Candle size vs ATR: Whether the rejection candle is of meaningful size relative to recent volatility
A total score of 6+ = Grade A, 4-5 = Grade B, below 4 = Grade C. Grade is displayed as a label on the rejection bar.
Features
Z-Score Impulse Engine: Statistically filters price moves against a rolling mean/standard deviation window — configurable length and threshold
Automatic Order Block Detection: Last opposing candle before each confirmed impulse identified and stored as a zone
Bidirectional Zone Tracking: Bullish (demand) and bearish (supply) zones managed in separate arrays with independent colors
A/B/C Rejection Grading: Four-factor scoring system labels each zone test with a quality grade
Zone Mitigation Detection: Zones that are fully closed through are frozen and visually distinguished from active zones
Mid-Line Reference: Each zone box includes a dashed mid-line at the 50% level — institutional equilibrium reference
ATR Proximity Filter: Rejection signals only fire when price is within a configurable ATR multiple of the zone
Volume Confirmation: Optional volume filter requires above-average volume at rejection for grading
Non-Repainting: All signals gated on barstate.isconfirmed — no look-ahead bias
Zone History Limit: Oldest zones automatically removed when the maximum count is reached to maintain performance
Dashboard (Top Right): Active bull/bear zone counts, last signal grade, last impulse Z-Score, and ATR — updated on each bar
Live Z-Score Candle Gradient Coloring: Impulse candles colored teal or rose based on Z-Score strength — immediately identifies statistically significant displacement bars on the chart
ATR Band Plots Around EMA 750: Visual upper and lower extremity zones drawn as ATR-based bands around the 750-period EMA — communicates when price is at macro stretch relative to the long-term anchor
RR Trade Boxes on Rejection Signals: Auto-generated SL/TP boxes on every rejection signal — 1.5× ATR stop loss with 3:1 reward-to-risk ratio, extending forward from the signal bar
Session Win Rate Tracking: Asia, London, and NY win rates tracked independently for rejection trades — outcome recorded against each signal's ATR-based TP/SL levels
Best Session Highlight: Dashboard automatically identifies and highlights the highest win-rate session across all three windows
Expanded Dashboard (9 Rows): Dashboard expanded to 9 rows — now includes live Z-Score reading, total impulse count, and full session win rate breakdown alongside existing zone and signal data
Input Parameters
Z-Score Settings:
Z-Score Length: Rolling window for mean and standard deviation calculation (default: 20)
Z-Score Threshold: Minimum absolute Z-Score required to qualify as an impulse (default: 1.5)
Zone Settings:
Max Active Zones: Maximum number of zones tracked simultaneously per direction (default: 8)
Bull Zone Color / Bear Zone Color: Independent colors per direction
Rejection Settings:
ATR Proximity (multiplier): How close price must be to a zone to trigger rejection check (default: 0.5)
ATR Length: Period for ATR calculation (default: 14)
Require Volume Confirmation: Toggle — above-average volume required for Grade A
How to Use This Indicator
Step 1: Identify Active Zones
Active bullish zones (demand) appear below price in teal. Active bearish zones (supply) appear above price in rose. Mitigated zones are visually dimmed. Focus on zones that have not yet been tested — these are the most relevant levels for future price interaction.
Step 2: Wait for Price to Return to the Zone
ISZ does not generate entry signals on impulse creation. It monitors active zones for return tests. When price pulls back into a zone, watch for the rejection grading label to appear.
Step 3: Grade the Signal
An A-grade rejection at a fresh, unmitigated zone is the highest-quality setup. B-grade is acceptable with additional confluence. C-grade rejections at already-tested zones carry the least weight. Use the grade in combination with your own bias and higher-timeframe analysis.
Step 4: Monitor the Dashboard
The dashboard shows active zone counts, last Z-Score, last grade, and ATR. A high Z-Score at impulse creation indicates an unusually strong move — those zones tend to attract more significant future tests.
Indicator Limitations
Z-Score impulse detection requires sufficient historical bars (at least 2× the Z-Score length) to produce accurate statistics — on very short chart histories the first few zones may form under unstable conditions
Order block detection scans back a fixed number of bars (configurable). In fast-moving markets where multiple candles are the same color, the scan may place the zone further back than an analyst would manually
Rejection grading uses volume data. On instruments with synthetic or unreliable volume (e.g., some CFDs, synthetic indices), the volume scoring component will not reflect true market activity
Zones do not account for gap fills, overnight moves, or after-hours sessions — a zone that appears unmitigated on the chart may have been effectively traded through outside of regular hours depending on the instrument
The A/B/C grading is a quantitative scoring system, not a certainty measure. Grade A signals do not guarantee price continuation in the expected direction
Originality Statement
ISZ combines Z-Score statistical impulse detection with origin-candle order block identification and a multi-factor rejection grading system in a single, self-contained indicator. This combination is original for the following reasons:
The use of a Z-Score normalized against a rolling mean and standard deviation — rather than a fixed pip or percentage threshold — makes impulse detection adaptive to current market volatility. The same threshold parameter behaves consistently across instruments and timeframes without requiring manual recalibration
The A/B/C grading system applies four independent quantitative factors (wick dominance, wick proportion, volume, candle size) simultaneously to classify signal quality at the point of zone interaction — rather than simply marking every return to a zone as equal
Zone lifecycle management (create → extend → mitigate → reject → trim) is handled automatically through UDT arrays with in-place field mutation, eliminating the need for manual zone maintenance or re-drawing
The combination of impulse detection, zone creation, and rejection grading in a single engine — with a unified dashboard — removes the need to layer multiple indicators to accomplish the same workflow
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Order block zones are historical reference levels and do not guarantee that price will react at those levels. A/B/C grades reflect quantitative scoring and do not predict future price movement. Always apply proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Deviation Lens [JOAT]Deviation Lens
Introduction
Deviation Lens is an open-source multi-dimensional statistical displacement tool that applies Z-Score analysis simultaneously to three market dimensions: price level, close-to-close price change, and volume. Rather than using arbitrary overbought/oversold thresholds derived from historical maxima and minima, Deviation Lens computes exactly how many standard deviations each dimension is from its recent rolling mean. This provides a precise, adaptive, distribution-aware measure of how statistically extreme current market conditions are.
The core insight is that markets are mean-reverting systems over short time horizons. Statistical extremes — conditions where price, momentum, or volume are far from their recent averages — represent transient states. The further from the mean, the greater the statistical probability that conditions will normalize. Deviation Lens quantifies this probability directly, from 0% (at the mean) to 99.7% (at three standard deviations), and displays it as a live reversal probability for every bar.
Core Concepts
1. Three-Dimensional Z-Score Calculation
Three independent Z-Scores are computed on every bar:
The Price Z-Score measures how far the current close is from the rolling mean close in standard deviation units. This captures whether the current price level is statistically cheap or expensive relative to recent history.
The Change Z-Score measures how far the current bar's close-to-close price change is from the rolling mean change — quantifying momentum extremity rather than price level extremity.
The Volume Z-Score measures how far the current volume is from the rolling mean volume. High-volume Z-Score values identify bars where unusual institutional participation is statistically evident:
priceZ = priceStd > 0 ? (close - priceMean) / priceStd : 0.0
changeZ = changeStd > 0 ? (chg - changeMean) / changeStd : 0.0
volumeZ = volStd > 0 ? (volume - volMean) / volStd : 0.0
2. Reversal Probability Mapping
The absolute Z-Score is mapped to a reversal probability percentage based on the properties of the normal distribution. A Z-Score of 1.0 corresponds to 68.3% of values lying within one standard deviation — meaning only 31.7% of readings exceed this level, implying a 68.3% probability of mean reversion. A Z-Score of 2.0 corresponds to 95.4%, and 3.0 to 99.7%:
calcRevProb(float z) =>
float absZ = math.abs(z)
absZ >= 3.0 ? 99.7 : absZ >= 2.5 ? 98.8 : absZ >= 2.0 ? 95.4 : absZ >= 1.5 ? 86.6 : absZ >= 1.0 ? 68.3 : absZ >= 0.5 ? 38.3 : 0.0
This probability is displayed in the dashboard alongside the live Z-Score value, giving the trader both the raw statistical reading and its corresponding reversal likelihood.
3. Composite Z-Score and Zone Classification
The three individual Z-Scores are combined into a composite score using configurable weights for each dimension. The composite is then classified into a zone: EXTREME (above the configurable extreme threshold), ELEVATED, NEUTRAL, or the opposing directional equivalents. Zone classification determines the dashboard color coding and alert triggers:
composite = (priceZ * wPrice + changeZ * wChange + volumeZ * wVolume) / totalWeight
4. Divergence and Hidden Divergence Detection
Deviation Lens monitors for two divergence conditions. Standard divergence occurs when the Z-Score direction disagrees with the price direction — price makes a higher high but the Z-Score makes a lower high (bearish divergence), or price makes a lower low but the Z-Score makes a higher low (bullish divergence). Hidden divergence occurs when the Z-Score makes an extreme move while price action is relatively contained — a potential continuation pattern. Divergence events are labeled directly on the chart with bold, clearly sized labels:
bullDiv = close > close and priceZ < priceZ // Price up, Z down = bull div
bearDiv = close < close and priceZ > priceZ // Price down, Z up = bear div
Labels: BULL DIV, BEAR DIV (size.small), H.BULL, H.BEAR (size.tiny for hidden divergence).
5. Multi-Dimensional Dashboard
The institutional dashboard presents all three Z-Scores, the composite Z-Score, current zone classification, reversal probability, and divergence status simultaneously. The layout is designed so the most actionable information — Zone and Rev. Probability — is displayed at the largest text size, with supporting metrics at smaller sizes.
Features
Three independent Z-Scores: Price level, price change (momentum), and volume — each computed on its own rolling mean and standard deviation
Configurable Z-Score weights: The composite score uses adjustable per-dimension weights allowing emphasis on price, momentum, or volume depending on trading context
Live reversal probability: Probability percentage mapped directly from the Z-Score using normal distribution properties (68.3% at 1σ through 99.7% at 3σ)
Zone classification: Composite Z-Score classified as Extreme, Elevated, or Neutral in both directions with color-coded dashboard display
Divergence labels (BULL DIV / BEAR DIV): Z-Score vs price direction disagreement labeled on-chart at size.small
Hidden divergence labels (H.BULL / H.BEAR): Z-Score extreme with contained price action labeled at size.tiny
Configurable extreme and elevated thresholds: Both Z-Score thresholds independently adjustable
Institutional dashboard (top right): 14-row table with Price Z, Change Z, Volume Z, Composite Z, Zone, Reversal Probability, and divergence status
Adaptive thresholds: All calculations normalize to the rolling lookback period, adapting to current instrument and timeframe volatility
Alerts: Separate alertconditions for extreme bull and extreme bear composite Z-Score readings
Input Parameters
Z-Score Settings:
Z-Score Length: Rolling window for all three Z-Score calculations (default: 20)
Extreme Threshold: Z-Score magnitude classified as Extreme zone (default: 2.0)
Elevated Threshold: Z-Score magnitude classified as Elevated zone (default: 1.0)
Dimension Weights:
Price Weight: Relative weight of the price Z-Score in composite (default: 1.0)
Change Weight: Relative weight of the momentum Z-Score in composite (default: 1.0)
Volume Weight: Relative weight of the volume Z-Score in composite (default: 0.5)
Divergence:
Divergence Lookback: Bars back for divergence comparison (default: 5)
Show Divergence Labels toggle
Display:
Show Dashboard toggle
Bull and Bear color inputs
How to Use This Indicator
Step 1: Read the Composite Zone
The Zone row in the dashboard shows the current composite Z-Score classification. EXTREME readings at the top of the scale indicate the highest statistical probability of mean reversion. NEUTRAL readings indicate current conditions are close to the mean and have low statistical directional edge from this tool alone.
Step 2: Check Reversal Probability
The Rev. Probability row translates the Z-Score magnitude directly into a percentage. A reading above 95% means the current composite Z-Score is in the outer 5% of its historical distribution — a statistical extreme that has preceded mean reversion 95% of the time in the measured period.
Step 3: Assess Each Dimension Independently
The three individual Z-Score rows reveal which dimension is driving the composite. A high composite driven entirely by volume Z-Score is a different setup than one driven by price Z-Score. Understanding which dimension is extreme helps filter entries: a price Z-Score extreme without supporting momentum or volume Z-Score extremes may be a lower-conviction reading.
Step 4: React to Divergence Labels
BULL DIV and BEAR DIV labels appear when Z-Score momentum diverges from price direction. These signal that the statistical driver of a move is weakening even as price continues. H.BULL and H.BEAR hidden divergence labels flag potential continuation setups where Z-Score is extreme but price is not.
Step 5: Combine with Structural Context
Deviation Lens produces the highest value when its extreme readings coincide with a structural confluence point — an order block, session low, or structure level. A 99.7% reversal probability at a tested support zone is a higher-conviction setup than the same reading in open air.
Indicator Limitations
All Z-Scores are computed relative to the rolling lookback window. The lookback defines what "normal" means. A very short lookback will produce extreme readings frequently; a very long lookback will rarely reach the extreme threshold. Calibration to the instrument and timeframe is required
The reversal probability percentages are derived from the normal distribution assumption. Price change and volume distributions are not perfectly normal — they exhibit fat tails and skew. The probabilities are approximations, not precise statistical guarantees
The composite Z-Score uses equal weights by default. Changing dimension weights significantly alters which market conditions produce extreme readings. Weight adjustments should be based on the specific instrument's characteristics
Divergence detection uses a simple lookback comparison, not a peak-detection algorithm. In choppy markets, divergence labels may appear frequently without providing actionable signals
Originality Statement
Deviation Lens is original in its simultaneous, weighted multi-dimensional Z-Score framework that maps composite statistical extremity directly to a reversal probability percentage. This indicator is published because:
Applying Z-Score analysis to three independent market dimensions simultaneously — price level, momentum (close-to-close change), and volume — rather than a single oscillator provides a richer statistical picture of current market extremity than any single-dimension Z-Score tool
The direct mapping of Z-Score magnitude to reversal probability percentages using normal distribution properties gives traders an immediately interpretable statistic rather than a raw number requiring subjective interpretation
The composite weighted Z-Score system, where each dimension's contribution to the overall reading is configurable, allows the indicator to be tuned toward price-mean-reversion strategies, momentum exhaustion strategies, or volume anomaly detection depending on the trader's methodology
The combined detection of standard divergence and hidden divergence between the Z-Score and price direction provides trend continuation and reversal signals from the same framework
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Z-Score readings and reversal probability percentages are statistical tools based on historical distributions and do not guarantee any future price behavior. The normal distribution assumption applied to price and volume data is an approximation. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Confluence Signal Engine [JOAT]Confluence Signal Engine
Introduction
Most traders encounter a common trap: stacking multiple indicators that all claim to measure something different, yet each one is ultimately derived from the same price data. The result is not confirmation — it is correlated noise presented as agreement. The Confluence Signal Engine was built to address this directly.
This indicator assigns a composite score to the current market condition by evaluating six deliberately chosen dimensions of market behavior. Each dimension is designed to measure a fundamentally different property of price action. When multiple dimensions agree, that agreement carries more weight than any single indicator firing alone. The result is a single, normalised score between -1 and +1, accompanied by a visual confidence meter and a score breakdown table so you can see exactly what is driving the signal.
This is an overlay indicator — it plots directly on the price chart.
---
Core Concepts
The Six Scoring Dimensions
Each dimension returns one of three values: +1 (bullish contribution), -1 (bearish contribution), or 0 (neutral / insufficient data). These are summed and divided by 6.0 to produce the composite score.
D1 — EMA Alignment (Trend Direction)
Compares a fast EMA to a slow EMA. If the fast EMA is above the slow EMA, the trend dimension scores +1. If below, it scores -1. This is the structural backbone — a baseline read on which side of the trend the price currently sits.
D2 — Price Z-Score (Statistical Deviation)
Calculates how many standard deviations the current close is from a baseline EMA. A Z-score below the negative threshold suggests the price has deviated far enough below the mean to be considered statistically stretched — a potential reversion candidate, scored +1. A Z-score above the positive threshold scores -1. This dimension does not measure trend; it measures relative price position against recent statistical norms.
D3 — Volume Pressure (Demand Validation)
Uses a Volume RSI (RSI applied to volume over 8 bars, divided by 50) as a proxy for whether volume activity is elevated. When volume pressure exceeds the threshold, the candle's direction (close vs. open) determines the score: a bullish candle in high-volume conditions scores +1; a bearish candle scores -1. When volume is not elevated, this dimension returns 0, contributing nothing. This prevents volume noise on low-activity bars from polluting the signal.
D4 — RSI Momentum (Momentum Quality)
Evaluates both the current RSI value and its slope. A rising RSI above 50 scores +1 — confirming that momentum is positive and strengthening. A falling RSI below 50 scores -1. This differs from a simple RSI threshold because the slope requirement means momentum must be actively moving in the scored direction, not merely sitting above or below a level.
D5 — Structural Position (Range Placement)
Compares the current close to the midpoint of the highest high and lowest low over a configurable lookback period. Closing above the midpoint scores +1; closing below scores -1. This is a simple but useful structural context: is price holding in the upper or lower half of its recent range?
D6 — Volatility Context (Environment Quality)
Divides a fast ATR by a slow ATR to produce a volatility ratio. A low ratio (calm, contracting volatility) scores +1 — historically a more favorable environment for trend continuation. A high ratio (expanding, elevated volatility) scores -1, flagging that the current environment may be erratic. A ratio between the two thresholds is neutral. This dimension does not predict price direction; it assesses whether current conditions are conducive to acting on the other signals.
---
Composite Score and Confidence
compositeScore = (D1 + D2 + D3 + D4 + D5 + D6) / 6.0
confidence = math.abs(compositeScore) * 100
The composite score ranges from -1.0 (all six dimensions bearish) to +1.0 (all six dimensions bullish). The confidence value is simply the absolute magnitude — a score of ±1.0 represents 100% agreement across all dimensions, while a score near 0 represents disagreement or neutrality.
Signal thresholds:
Score > buy threshold (default 0.3) → bullish signal
Score < sell threshold (default -0.3) → bearish signal
Score > high-confidence threshold (default ±0.6) → high-confidence signal
Signals are gated by barstate.isconfirmed — they only fire on fully closed bars, preventing intra-bar repainting. State tracking also prevents the same directional signal from repeating consecutively without a change in direction first.
---
Visual Components
24-Cell Gradient Confidence Meter
A horizontal bar of 24 cells is displayed at the bottom of the chart. The left side is the bearish extreme, the center is neutral, and the right side is the bullish extreme. The current composite score position is highlighted within the meter, giving a continuous visual read of where the market sits in the conviction range — not just whether a signal has fired, but how strongly.
Score Breakdown Table
A table showing three columns for each dimension: dimension name, dimension number, and its current score (+1, -1, or 0). This allows you to see exactly which dimensions are contributing to the composite and which are neutral or conflicting.
Gradient Bar Coloring
Price bars are colored using a gradient that interpolates from a neutral color toward the signal color, weighted by the absolute value of the composite score. A high-confidence bull signal produces a strong green bar; a low-confidence or mixed signal produces a muted or neutral color. This keeps bar coloring proportional to actual conviction rather than using a binary flip.
---
Features
Six-dimension composite scoring system covering trend, statistics, volume, momentum, structure, and volatility
Composite score normalised to with confidence percentage
Non-repainting: all signals confirmed on bar close via barstate.isconfirmed
State-tracked signals prevent repeated same-direction firing
24-cell gradient confidence meter with continuous position display
Score breakdown table showing each dimension's individual contribution
Gradient bar coloring proportional to conviction level
Configurable thresholds for all six dimensions and signal levels
---
Input Parameters
EMA Fast / Slow (default 21 / 55) — D1 trend alignment
Z-Score Baseline EMA (default 50) — the mean used for Z-score calculation
Z-Score Window (default 50) — standard deviation lookback
Z-Score Threshold (default 1.5) — how many standard deviations trigger the score
Volume RSI Length (default 8) — RSI period applied to volume
Volume Threshold (default 1.2) — Volume RSI / 50 must exceed this to activate D3
RSI Length (default 14) — standard RSI period for D4
Structure Lookback (default 20) — bars used to define the high/low range for D5
ATR Fast / Slow (default 14 / 50) — periods for the volatility ratio in D6
Volatility Thresholds (default 0.8 / 1.5) — low and high boundaries for the ATR ratio
Buy Threshold (default 0.3) — minimum composite score to generate a long signal
Sell Threshold (default -0.3) — maximum composite score to generate a short signal
High-Confidence Threshold (default ±0.6) — score level at which a signal is classified as high-confidence
---
How to Use
Apply to any chart. The overlay paints directly on price bars.
Watch the confidence meter for the current composite score position. A score pressed toward either extreme with multiple dimensions aligned is a higher-quality read than one sitting near center.
Use the score breakdown table to understand why the composite score is what it is. If only 2 of 6 dimensions are contributing, the signal is weaker regardless of whether it crossed the threshold.
High-confidence signals (score beyond ±0.6 by default) indicate that four or more of the six dimensions are in agreement. These can be treated as stronger setups than threshold-level signals.
Combine the composite score read with your own price action, support/resistance, or higher-timeframe context before entering a trade. This indicator is a confluence tool, not a standalone entry system.
If several dimensions are conflicting (score near 0), the market is not in a clear state — no action is the appropriate response.
---
Limitations
No indicator can predict future price. The composite score reflects current market conditions based on recent historical data — not what will happen next.
Z-score and structural position dimensions are mean-reverting in nature, while EMA alignment and RSI momentum are trend-following. In strongly trending markets, D2 and D5 may produce persistent bearish readings even during a healthy uptrend, suppressing the composite score. This is by design — the indicator is more suited to environments where confluence across all dimensions is achievable.
Volume RSI (D3) is only reliable on instruments and timeframes with consistent, meaningful volume data. On synthetic instruments, indices, or very low-timeframe charts, volume data may be unreliable and D3's contribution should be weighted accordingly.
The volatility context dimension (D6) measures the environment , not direction. A low-volatility score of +1 does not mean the market is about to move up — only that conditions are historically more favorable for clean signals.
Signal state tracking prevents consecutive same-direction signals, which reduces noise but also means the indicator will not re-fire during a prolonged trending move. This is a deliberate design choice but should be understood before use.
Default thresholds were chosen for general applicability. Different asset classes, timeframes, and volatility regimes may benefit from threshold adjustment.
Past signal quality on any given instrument does not guarantee future performance.
---
Originality Statement
The core innovation of this indicator is the deliberate selection of six dimensions that measure fundamentally different market properties rather than multiple views of the same property. Standard multi-indicator approaches tend to combine RSI, MACD, and Stochastic — all of which are momentum oscillators derived from price, generating correlated signals that appear independent but are not.
This indicator separates the problem into distinct domains: trend direction (EMA alignment), statistical deviation from the mean (Z-score), demand-side pressure (Volume RSI), momentum quality and direction (RSI slope + level), structural placement within recent range (midpoint comparison), and environmental favorability (ATR ratio). Because these dimensions are largely uncorrelated with each other, genuine multi-dimension agreement represents a qualitatively different kind of confluence than stacking three oscillators. The 24-cell gradient meter goes further — it provides a continuous conviction read rather than a binary signal, treating market condition as a spectrum.
---
Disclaimer
This indicator is provided for educational and informational purposes only. It does not constitute financial advice, investment advice, or a recommendation to buy or sell any security. All trading involves risk, including the possible loss of principal. Past indicator performance does not guarantee future results. Always conduct your own research and consult a qualified financial professional before making any trading decisions.
-Made with passion by officialjackofalltrades
Indicator

Swing-Level Z-Score Oscillator▶️Overview
The Swing-Level Z-Score Oscillator is an innovative indicator that bridges the gap between classic market structure and statistical probability. Instead of relying on traditional moving averages as a baseline, this oscillator evaluates price extremes relative to recent structural pivot levels (Swing Highs and Swing Lows).
By transforming these structural deviations into a standardized Z-Score, it provides a highly intuitive, context-aware perspective on Overbought (OB) and Oversold (OS) conditions.
▶️How It Works (The Logic)
Traditional oscillators often lag or provide false signals during strong trends. This script tackles that issue through a unique three-step process:
Dynamic Baseline : The algorithm constantly scans for recent Pivot Highs and Pivot Lows. It takes the average of the last N pivots to establish a dynamic "horizontal zone" of recent historical interest. This acts as our expected mean.
Error & Volatility: It measures the distance (error) between the current Close price and this expected mean. To understand the significance of this distance, it calculates the rolling standard deviation of these errors.
Z-Score Normalization: Finally, it divides the current error by the standard deviation. The result is a clean Z-Score that tells you exactly how many standard deviations the current price has stretched away from recent structural levels.
▶️Key Features
Actionable Market Context: Because the baseline is built on actual price pivots rather than arbitrary averages, the oscillator respects current market structure (support/resistance).
Intelligent Gradient UI: The indicator features a dynamic color-coding system.
The histogram and signal line smoothly fade based on the intensity of the momentum.
Vivid Extreme Alerts: When the Z-Score stretches beyond the critical ±2.0 Sigma threshold, the histogram flashes vivid Cyan (Overbought) or Neon Pink (Oversold), immediately catching your attention.
Plug-and-Play Presets: Don't want to mess with settings? Use the "Operating Mode" dropdown to quickly switch between Short-term, Standard, and Long-term presets tailored to different trading styles. Fully customizable options are also available.
▶️How to Trade with It
Mean Reversion (Fade the Extremes): When the histogram hits the vivid ±2.0 zones, the price is statistically overextended relative to recent swing levels. Look for exhaustion price action (like pin bars) combined with a hook back toward the center line to trade reversions.
Pullbacks in a Trend: During a clear trend, look for the oscillator to reset back to the Center Line (0) or the ±1 Sigma lines. These often represent optimal, low-risk entry points (buy the dip/sell the rally) before the trend resumes.
Momentum Breakouts: A sudden, aggressive spike that blasts through the ±2 Sigma line can indicate a genuine structural breakout with heavy momentum, rather than a mere overextension.
▶️Settings & Customization
If you select "Custom" in the Operating Mode, you can fine-tune:
Left/Right Bars: Adjusts the sensitivity of the pivot detection. Lower numbers catch micro-swings, while higher numbers catch major structural points.
StdDev Length: The lookback period for calculating the variance of the errors.
Past Pivots Count (N): Determines how many historical pivots are used to calculate the "Expected Value" baseline.
Disclaimer: This script is for educational and analytical purposes only. Always combine oscillator readings with broader price action analysis and proper risk management. Indicator

Smoothed ZLEMA Z-scoreThis indicator computes a Z-score of price using a Zero Lag EMA (ZLEMA) instead of a standard moving average, then applies a second ZLEMA pass to smooth the result. The output oscillates around zero — crossings of the zero line generate buy/sell signals with a configurable cooldown filter. Primary utility is as a mean-reversion and momentum-shift detector rather than a trend-following tool. Its edge comes from answering one specific question: has price moved so far from its dynamic equilibrium that a reversal is statistically due?
Because the mean is a ZLEMA (Zero Lag EMA) rather than a simple or standard EMA, it tracks price closely without the usual lag tax. This makes the Z-score more reactive — it rises and falls faster than a Bollinger-based oscillator, meaning it spends less time stuck at extremes after the actual turning point has already passed.
The smoothing pass on top then removes the noise that would otherwise cause whipsaws on that fast signal. So you get the best of both worlds: fast mean-tracking, clean signal output.
Practical applications:
Entries on mean-reversion setups — when the Z-score crosses back to zero from a stretched extreme (±1.5 to ±2.5 zone), it signals that price has returned to statistical normalcy, which is often the safest entry point.
Momentum confirmation — on a breakout, a zero-cross in the direction of the break confirms that price is not just stretching — it's shifting its mean relationship entirely.
Divergence reads — if price makes a new high but the Z-score makes a lower high, the move is losing statistical intensity even if it hasn't reversed yet.
The indicator is genuinely timeframe-agnostic but behaves differently at each scale: The key insight on timeframes: the Z-score's absolute value at any point is what matters more than the signal itself. On lower timeframes, ±1.5 is already extreme. On daily charts, the oscillator needs to push beyond ±2 before a zero-cross signal carries real weight.
The Mathematics —
What It's Actually Measuring:
The Z-score tells you how unusual the current price is relative to its recent self, expressed in standard deviation units. This is a statistical normalization — it strips away the actual price level and volatility of the asset, leaving only the relative displacement.
The ZLEMA twist modifies both the mean and the variance calculation. In a standard Bollinger-based Z-score, a simple moving average is the center. Here, the center is a zero-lag EMA — which means:
The mean itself moves toward current price faster
Variance is computed against that faster mean, so it captures dispersion around a more current reference point
The result is a Z-score that doesn't have the "stale mean" problem that plagues traditional oscillators in trending conditions
Visually, think of it this way: a standard deviation band around a slow SMA creates a wide tunnel that price has to escape to trigger a reading. A ZLEMA-based deviation band is a narrower, faster-moving tunnel that hugs price more tightly, so genuine outlier moves register more immediately.
The final smoothing pass converts the noisy raw Z-score (which can spike and collapse within a few bars) into a cleaner wave that crosses zero in a more deliberate, readable way. The quality of a zero-cross signal is directly proportional to how deep the Z-score was before crossing. A cross from −2.2 back above zero is a high-conviction mean-reversion. A cross from −0.4 is statistical noise dressed as a signal — the cooldown filter is your defense against those.
The fill coloring reinforces this: orange above zero, blue below. When the fill is deep and the cross happens, the visual contrast of the color flipping is itself a useful alert.
This indicator does not predict direction in a vacuum. A Z-score of +2.5 does not guarantee a decline — in a strong trending market, price can "ride the band" with the Z-score hovering at elevated levels for extended periods. The zero-cross signal is most reliable in mean-reverting market regimes (range-bound conditions, consolidation phases, overnight sessions in futures). In strong trends, signals against the trend direction should be filtered by a higher-timeframe trend indicator before acting on them.
How to Use It:
The indicator is best read as a mean-reversion oscillator with momentum context:
Z-score rising through zero from below = price reclaiming its ZLEMA mean, potential momentum shift upward
Z-score falling through zero from above = price breaking down through its mean
Extreme values (±2 or beyond) suggest price is statistically stretched and likely to revert
The cooldown parameter is important to tune — on trending instruments, increase it to avoid whipsaws; on ranging instruments, reducing it captures more turns
The ZLEMA backbone makes this more responsive than a traditional Bollinger-based Z-score, which can lag by several bars in fast-moving markets.
Disclaimer:
This indicator and any signals it generates are provided strictly for educational and informational purposes. Nothing presented here constitutes financial advice, investment advice, or a recommendation to buy or sell any financial instrument. Good Luck !! Indicator

VWAP Z-Score & Exhaustion Matrix [AlgoPoint]AlgoPoint VWAP Z-Score & Order Flow Matrix
Overview
The AlgoPoint VWAP Z-Score Matrix is a quantitative oscillator designed to identify statistical extremes in price action relative to a dynamic volume-weighted baseline. By combining a Rolling VWAP, Volume-Weighted Standard Deviation, Volume Exhaustion, and an Intrabar Order Flow Delta proxy, this indicator provides a comprehensive framework for modeling mean-reversion (fade) setups.
Mathematical Core & Components
This indicator relies on three primary quantitative mechanics:Rolling VWAP & Z-Score: Unlike a traditional anchored VWAP that resets daily, this script calculates a Rolling VWAP over a user-defined lookback window. The standard deviation is volume-weighted, ensuring that high-volume nodes have a proportional impact on the variance. The Z-Score normalizes the price deviation from the VWAP, creating a 0-centered oscillator.
- Volume Exhaustion: The script compares the current bar's volume against a Simple Moving Average (SMA) of volume. If the current volume is lower than the average, it flags a state of "exhaustion," indicating a potential deceleration in the current price push.
- Order Flow Delta Proxy: To evaluate microstructure without requiring lower timeframe data, the indicator estimates intrabar buying and selling pressure. It apportions the total bar volume into "Up Volume" and "Down Volume" based on where the close occurs relative to the high-low range. The net difference establishes the Volume Delta.
Visual Elements & Interpretation
Dual-Gradient Bar Coloring: The main chart candles and the oscillator line are dynamically colored using a dual-gradient system. The color smoothly transitions from a neutral gray at the mean (0) to green at negative extremes and red at positive extremes.
Reference Thresholds: Default extreme limits are set at +2.5 and -2.5 Z-Scores.Exhaustion Nodes: Circular nodes appear on the oscillator line when the price reaches an extreme Z-Score simultaneously with volume exhaustion.
Quant Dashboard: A real-time table displaying the current Z-Score, Volume Status (Active/Exhausted), Order Flow Delta (Net Buyers/Sellers), and the absolute Rolling VWAP price.
Signal Generation
"Fade Long" and "Fade Short" labels are generated only when all structural conditions are met and the bar is confirmed (barstate.isconfirmed)
Fade Short: Z-Score > Upper Threshold AND Volume is Exhausted AND Delta is Negative (Sellers taking control).
Fade Long: Z-Score < Lower Threshold AND Volume is Exhausted AND Delta is Positive (Buyers taking control).
Alerts
The indicator includes standard alert conditions and dynamic JSON webhook strings for automated trading systems, providing real-time data on the asset, price, Z-Score, and Delta values upon signal generation. Indicator

Statistical Reversion Engine [JOAT]Statistical Reversion Engine
Introduction
The Statistical Reversion Engine (SRE) is an advanced open-source mean reversion indicator that combines statistical deviation bands, premium/discount zone analysis, DCA level calculation, Z-score measurement, and enhanced reversion probability scoring to identify high-probability mean reversion opportunities. This indicator quantifies price deviation from statistical mean using multiple calculation methods (SMA, EMA, VWAP, HMA) and provides probabilistic assessment of reversion likelihood through multi-factor analysis including deviation magnitude, volatility regime, and historical reversion patterns.
Unlike basic Bollinger Band indicators that simply plot standard deviation bands, SRE employs a sophisticated statistical framework that calculates Z-scores, premium/discount percentages, enhanced reversion probability (incorporating volatility and premium factors), and tracks historical reversion speed to provide traders with quantitative mean reversion intelligence. The indicator also generates DCA (Dollar Cost Averaging) levels with volatility-adjusted spacing for systematic position building.
Why This Indicator Exists
This indicator addresses the challenge of identifying when price has deviated sufficiently from mean to warrant mean reversion trades. Traditional mean reversion indicators lack probabilistic quantification and don't account for volatility regime or historical reversion patterns. SRE systematically reveals:
Multiple Mean Calculations: SMA, EMA, VWAP (session/continuous), HMA for flexible mean definition
Statistical Deviation Bands: 1σ, 2σ, 3σ bands with customizable multipliers
Z-Score Calculation: Quantifies deviation in standard deviation units
Premium/Discount Analysis: Percentage deviation from mean with zone classification
Enhanced Reversion Probability: Multi-factor scoring (Z-score + premium + volatility)
DCA Level Generation: Volatility-adjusted levels for systematic position building
Historical Reversion Tracking: Measures average bars to return to mean after extreme deviation
Each component provides unique intelligence. Mean calculation defines center, deviation bands show extremes, Z-score quantifies magnitude, premium/discount shows percentage, probability scores likelihood, DCA levels provide entry framework, and historical tracking provides context.
Core Components Explained
1. Flexible Mean Calculation System
SRE supports four mean calculation methods:
f_calculate_mean(string type, int length) =>
float result = close
if type == "SMA"
result := ta.sma(close, length)
else if type == "EMA"
result := ta.ema(close, length)
else if type == "VWAP"
result := session_reset ? ta.vwap(hlc3) : ta.vwma(hlc3, length)
else if type == "HMA"
result := ta.hma(close, length)
result
Mean selection impacts reversion behavior:
- SMA: Simple average, slower to respond
- EMA: Exponential weighting, faster response
- VWAP: Volume-weighted, institutional reference
- HMA: Hull Moving Average, smoothest with minimal lag
2. Statistical Deviation Band System
Three deviation bands calculated using standard deviation:
float mean_line = f_calculate_mean(mean_type, mean_length)
float stdev = f_calculate_stdev(close, deviation_period)
float upper_band_1 = mean_line + (stdev * band_multiplier_1) // 1σ
float lower_band_1 = mean_line - (stdev * band_multiplier_1)
float upper_band_2 = mean_line + (stdev * band_multiplier_2) // 2σ
float lower_band_2 = mean_line - (stdev * band_multiplier_2)
float upper_band_3 = mean_line + (stdev * band_multiplier_3) // 3σ
float lower_band_3 = mean_line - (stdev * band_multiplier_3)
Default multipliers: 1.0, 2.0, 3.0 (customizable)
- 1σ: 68% of price action (normal range)
- 2σ: 95% of price action (extended range)
- 3σ: 99.7% of price action (extreme range)
3. Z-Score Calculation & Classification
Z-score quantifies deviation in standard deviation units:
f_calculate_zscore(float price, float mean, float stdev) =>
float zscore = stdev > 0 ? (price - mean) / stdev : 0.0
zscore
float zscore = f_calculate_zscore(close, mean_line, stdev)
Z-score interpretation:
- |Z| < 1.0: Normal deviation (40% reversion probability)
- |Z| 1.0-1.5: Moderate deviation (60% reversion probability)
- |Z| 1.5-2.0: Extended deviation (75% reversion probability)
- |Z| 2.0-2.5: Extreme deviation (85% reversion probability)
- |Z| > 3.0: 3-sigma event (95% reversion probability)
4. Premium/Discount Zone Analysis
Percentage deviation from mean with zone classification:
f_calculate_premium_discount(float price, float mean) =>
float pct = mean > 0 ? ((price - mean) / mean) * 100 : 0.0
pct
float premium_discount_pct = f_calculate_premium_discount(close, mean_line)
string current_zone =
premium_discount_pct >= premium_threshold * 2 ? "Extreme Premium" :
premium_discount_pct >= premium_threshold ? "Premium" :
premium_discount_pct <= discount_threshold * 2 ? "Extreme Discount" :
premium_discount_pct <= discount_threshold ? "Discount" :
"Fair Value"
Zone classification (default thresholds):
- Extreme Premium: >3.0% above mean (strong sell zone)
- Premium: 1.5-3.0% above mean (sell zone)
- Fair Value: -1.5% to +1.5% (neutral zone)
- Discount: -3.0% to -1.5% below mean (buy zone)
- Extreme Discount: <-3.0% below mean (strong buy zone)
5. Enhanced Reversion Probability Scoring
Multi-factor probability calculation:
f_enhanced_reversion_prob(float z, float premium_pct, float vol_rank) =>
float base_prob = f_reversion_probability(z)
// Adjust for premium/discount magnitude
float premium_factor = math.abs(premium_pct) > 3 ? 1.2 :
math.abs(premium_pct) > 2 ? 1.1 :
math.abs(premium_pct) > 1 ? 1.0 : 0.9
// Adjust for volatility (lower vol = higher reversion probability)
float vol_factor = vol_rank < 30 ? 1.2 :
vol_rank < 50 ? 1.1 :
vol_rank < 70 ? 1.0 : 0.85
math.min(base_prob * premium_factor * vol_factor, 99)
Enhanced probability accounts for:
- Base Z-score probability
- Premium/discount magnitude (larger deviation = higher probability)
- Volatility regime (lower volatility = more predictable reversion)
6. Volatility-Adjusted DCA Level Generation
DCA levels automatically adjust spacing based on volatility:
float current_atr = ta.atr(14)
float atr_pct = close > 0 ? (current_atr / close) * 100 : 0
float vol_multiplier = atr_pct > 3 ? 1.5 : atr_pct > 2 ? 1.2 : atr_pct > 1 ? 1.0 : 0.8
for i = 1 to dca_levels
float adjusted_spacing = (dca_spacing * vol_multiplier) / 100
float buy_level = mean_line * (1 - adjusted_spacing * i)
float sell_level = mean_line * (1 + adjusted_spacing * i)
array.push(dca_buy_levels, buy_level)
array.push(dca_sell_levels, sell_level)
Volatility adjustment:
- High vol (ATR% >3): 1.5x spacing (wider levels)
- Elevated vol (ATR% 2-3): 1.2x spacing
- Normal vol (ATR% 1-2): 1.0x spacing (default)
- Low vol (ATR% <1): 0.8x spacing (tighter levels)
7. Historical Reversion Speed Tracking
Measures average bars to return to mean after extreme deviation:
var array reversion_times = array.new_int(0)
var bool tracking_reversion = false
var int reversion_start_bar = 0
if math.abs(zscore) >= 2.5 and not tracking_reversion
tracking_reversion := true
reversion_start_bar := bar_index
if tracking_reversion and math.abs(zscore) < 0.5
int reversion_time = bar_index - reversion_start_bar
array.push(reversion_times, reversion_time)
tracking_reversion := false
float avg_reversion_time = array.size(reversion_times) > 0 ?
array.avg(reversion_times) : na
Average reversion time provides context for expected holding period.
Visual Elements
Mean Line: Electric lime line showing statistical mean
Deviation Bands: 1σ (lime), 2σ (violet), 3σ (deep violet) with gradient fills
Premium/Discount Zones: Background coloring (violet for premium, lime for discount)
DCA Levels: Dotted lines with "B1, B2, B3..." (buy) and "S1, S2, S3..." (sell) labels
Z-Score Label: Current Z-score displayed on price
Gradient Zone Fills: Progressive transparency between bands
Mean Reversion Signals: Triangle markers for strong buy/sell setups
Reversion Probability Heatmap: Background intensity based on enhanced probability
Dashboard: Real-time metrics including zone, P/D%, Z-score, reversion probability, mean value, distance, enhanced probability, deviation percentile, mean trend, nearest DCA, average reversion time, bars since extreme
Input Parameters
Mean Calculation:
Mean Type: SMA, EMA, VWAP, HMA (default: VWAP)
Mean Length: Period for mean calculation (default: 20)
Session Reset (VWAP): Toggle session anchoring (default: true)
Deviation Bands:
Band 1 Multiplier: 1σ multiplier (default: 1.0)
Band 2 Multiplier: 2σ multiplier (default: 2.0)
Band 3 Multiplier: 3σ multiplier (default: 3.0)
Deviation Period: Standard deviation calculation period (default: 20)
Premium/Discount:
Premium Threshold (%): Threshold for premium zone (default: 1.5%)
Discount Threshold (%): Threshold for discount zone (default: -1.5%)
DCA Levels:
Enable DCA Levels: Toggle DCA display (default: true)
Number of DCA Levels: Levels to generate (default: 5)
DCA Spacing (%): Base spacing between levels (default: 1.5%)
Visualization:
Show Deviation Bands: Toggle band display (default: true)
Show Band Fills: Toggle gradient fills (default: true)
Show Premium/Discount Zones: Toggle background coloring (default: true)
Show Z-Score Label: Toggle Z-score display (default: true)
How to Use This Indicator
Step 1: Identify Current Zone
Check dashboard "Zone" row. Extreme Discount = strong buy zone, Extreme Premium = strong sell zone.
Step 2: Assess Z-Score Magnitude
|Z| >2.0 indicates extended deviation. |Z| >3.0 is 3-sigma event (rare, high reversion probability).
Step 3: Check Enhanced Reversion Probability
Dashboard shows enhanced probability accounting for volatility and premium factors. >80% is high probability.
Step 4: Monitor Mean Trend
"Rising" mean suggests uptrend, "Falling" suggests downtrend. Trade with mean trend for higher probability.
Step 5: Use DCA Levels for Entry
Enter positions at DCA levels (B1, B2, B3 for longs; S1, S2, S3 for shorts) to average into position.
Step 6: Wait for Strong Signals
Triangle markers appear when:
- Extreme zone + enhanced probability >80% + band crossover
- These are highest conviction mean reversion setups
Best Practices
Mean reversion works best in ranging markets - avoid strong trends
3-sigma events (|Z| >3.0) have highest reversion probability but occur rarely
Use DCA levels to build positions systematically rather than all-in entries
Enhanced probability >80% indicates high-quality setup
Mean trend provides context - reversion against trend is lower probability
Volatility-adjusted DCA spacing prevents over-concentration in high vol
Average reversion time helps set realistic profit target timeframes
Combine with higher timeframe trend - mean reversion with trend is safer
Deviation percentile >90% indicates extreme deviation
Bars since extreme >50 suggests extended deviation may persist
Indicator Limitations
Mean reversion fails during strong trending markets
3-sigma events can persist longer than expected during major news
DCA levels don't account for fundamental catalysts
Enhanced probability is statistical, not deterministic
Historical reversion time doesn't guarantee future reversion speed
VWAP mean resets daily - may not be appropriate for all timeframes
Standard deviation assumes normal distribution - markets have fat tails
Premium/discount thresholds may need adjustment for different instruments
Technical Implementation
Built with Pine Script v6 using:
Four mean calculation methods (SMA, EMA, VWAP, HMA)
Three-tier deviation band system with customizable multipliers
Z-score calculation with standard deviation
Premium/discount percentage with zone classification
Enhanced reversion probability (Z-score + premium + volatility)
Volatility-adjusted DCA level generation
Historical reversion speed tracking with arrays
Deviation percentile ranking
Mean trend detection (fast vs slow mean)
Gradient zone fills with progressive transparency
Reversion probability heatmap background
Comprehensive dashboard with 12 metrics
The code is fully open-source and can be modified to suit individual trading styles.
Originality Statement
This indicator is original in its comprehensive statistical mean reversion approach. While Bollinger Bands and mean reversion are established concepts, this indicator is justified because:
It combines four mean calculation methods with three-tier deviation bands
Enhanced reversion probability incorporates Z-score, premium magnitude, and volatility regime
Volatility-adjusted DCA level generation adapts to market conditions
Historical reversion speed tracking provides empirical context
Premium/discount zone classification adds percentage-based perspective
Mean trend detection (fast vs slow) provides directional context
Deviation percentile ranking shows historical extremity
Integration of statistical measures (Z-score, stdev, percentile) with practical tools (DCA levels, signals)
Each component contributes unique information: mean defines center, deviation bands show extremes, Z-score quantifies magnitude, premium/discount shows percentage, enhanced probability scores likelihood, DCA levels provide framework, historical tracking provides context, and mean trend shows direction. The indicator's value lies in presenting these complementary perspectives simultaneously with unified statistical framework.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Mean reversion probabilities do not guarantee outcomes. Trading involves substantial risk of loss. Past performance does not guarantee future results. Always use proper risk management and never risk more than you can afford to lose.
-Made with passion by officialjackofalltrades Indicator

Liquidity Structure & Order Flow [UAlgo]Liquidity Structure & Order Flow is a range based market participation tool that combines a custom volume profile, value area analysis, liquidity void detection, and unusual volume tagging into a single chart overlay. Its goal is to show not only where volume has concentrated across price, but also how that activity was distributed between estimated buying pressure and selling pressure inside the recent market structure.
The script begins by scanning a rolling lookback range, then divides that vertical price space into a configurable number of bins. Each bin becomes a price segment that stores estimated buy volume, sell volume, and total volume. From there, the script builds a profile that highlights the Point of Control, the value area, and the internal order flow balance across the studied range.
What makes this indicator especially useful is that it does more than draw a standard profile. It also identifies areas where participation is abnormally thin relative to both the Point of Control and local neighboring bins. These low participation areas are marked as liquidity voids, helping the user see where the market moved through price with relatively little acceptance.
In addition, the script monitors the current bar for unusually large activity using a volume z score and a directional delta ratio filter. When a bar shows both exceptional size and meaningful directional imbalance, the script prints a bubble style marker above or below price. This gives the user a way to spot unusual participation events as they happen.
The result is a tool that can be used for profile analysis, liquidity mapping, imbalance recognition, and structural context. It helps answer several practical questions at once: where the market accepted price, where it rejected or skipped through price, where the strongest concentration of activity formed, and whether recent candles are showing exceptional directional participation.
🔹 Features
🔸 Custom Range Based Volume Profile
The script constructs a manual volume profile over the selected lookback period. Instead of relying on a built in profile engine, it divides the recent range into user defined price bins and allocates each bar’s volume into those bins. This gives full control over how the profile is built and how the final distribution is interpreted.
🔸 Buy Volume and Sell Volume Estimation
Every candle contributes both buy side and sell side estimates. The script uses the candle’s open, high, low, and close to derive a buy volume ratio, then splits total volume into buy volume and sell volume accordingly. This creates a practical order flow style approximation that is more informative than total volume alone.
🔸 Proportional Price Overlap Allocation
When a candle spans multiple bins, the script distributes its buy volume, sell volume, and total volume proportionally according to how much of the candle overlaps each bin. This produces a more realistic internal structure than simply dropping the full bar volume into one price row.
🔸 Point of Control Detection
The indicator finds the bin with the highest total volume and marks it as the Point of Control. This gives the user an immediate view of the strongest participation price inside the studied range.
🔸 Value Area Calculation
After the Point of Control is found, the script expands upward and downward through neighboring bins until the selected percentage of total profile volume is captured. This defines Value Area High and Value Area Low, allowing the user to distinguish the central acceptance region from the rest of the range.
🔸 Profile Coloring by Participation Side
The profile is drawn as stacked horizontal boxes showing estimated buy side participation and sell side participation inside each row. Bins inside the value area use stronger coloring, while bins outside the value area use softer coloring. This makes the internal structure easy to read visually.
🔸 Liquidity Void Detection
The script scans for bins with unusually weak participation outside the value area. A bin qualifies as a liquidity void candidate only if it is both small relative to the Point of Control and also weaker than its nearby neighbors. Consecutive weak bins are grouped into a larger void zone and labeled directly on the chart.
🔸 Unusual Volume Bubble Markers
Current bar activity is evaluated using a long period volume average and standard deviation. If the bar’s volume is statistically unusual and its estimated delta ratio is large enough, the script prints a directional bubble marker. Positive directional activity is shown below price, and negative directional activity is shown above price.
🔸 Optional Profile and Void Display
The user can independently control whether the volume profile, liquidity voids, and unusual volume markers are shown. This makes the script flexible enough for both full structure analysis and lighter chart layouts.
🔸 Extendable Structural Levels
The Point of Control, Value Area High, and Value Area Low can be drawn as either compact structure references or extended lines, depending on the chosen setting. This allows the user to decide whether the levels should function as local annotations or ongoing chart references.
🔸 Useful for Acceptance and Imbalance Analysis
The combination of profile structure, value area, void zones, and unusual activity markers gives the indicator a broader purpose than a standard profile. It can help identify accepted price, skipped price, directional participation, and possible future reaction areas.
🔹 Calculations
1) Building the Volume Profile Container
type PriceBin
float price
float buyVol = 0.0
float sellVol = 0.0
float totalVol = 0.0
type VolumeProfile
float highPrice = na
float lowPrice = na
float binSize = na
array bins
float pocPrice = na
float pocVol = 0.0
float vah = na
float val = na
float totalVol = 0.0
This is the foundation of the whole script.
Each PriceBin stores one price level area inside the profile. It contains:
the row midpoint price,
estimated buy volume,
estimated sell volume,
and total volume.
The VolumeProfile structure stores the full profile state:
the highest price of the lookback range,
the lowest price of the lookback range,
the bin size,
the array of bins,
and the final analytical values such as Point of Control, Value Area High, Value Area Low, and total profile volume.
So before any analysis happens, the script defines a complete custom data model for price distribution and order flow style estimation.
2) Initializing the Bins Across the Lookback Range
method initBins(VolumeProfile this, float h, float l, int numBins) =>
this.highPrice := h
this.lowPrice := l
this.binSize := (h - l) / numBins
this.pocPrice := na
this.pocVol := 0.0
this.totalVol := 0.0
this.vah := na
this.val := na
this.bins := array.new()
for i = 0 to numBins - 1
this.bins.push(PriceBin.new(price = l + i * this.binSize + (this.binSize / 2)))
This method creates the working profile rows.
First, it stores the high and low of the selected lookback period. Then it calculates binSize , which is the vertical price height of each row. That is simply the full range height divided by the number of bins.
After resetting all major profile outputs, the script creates a fresh bin array. Each new bin is assigned a midpoint price:
l + i * this.binSize + (this.binSize / 2)
That midpoint becomes the visual and analytical center of the row.
In practical terms, this is where the script transforms the raw market range into a structured ladder of price rows that can later receive allocated volume.
3) Locating the Correct Bin for a Price
method getBinIndex(VolumeProfile this, float p) =>
if na(this.lowPrice) or na(this.binSize) or this.binSize == 0
0
else
int idx = math.floor((p - this.lowPrice) / this.binSize)
math.max(0, math.min(idx, this.bins.size() - 1))
This helper method maps any price to its correct row index inside the profile.
It works by measuring how far the price sits above the profile low, then dividing that distance by the bin size. The result is the raw row index. After that, the value is clamped so it always stays inside the valid bin range.
This is important because the script repeatedly needs to know which rows are touched by each candle’s low and high. Without this mapping step, the profile could not distribute volume across price space correctly.
4) Estimating Buy Volume and Sell Volume From Candle Structure
float hlR = high - low
float bVR = hlR == 0 ? 0.5 : (close - low + high - open) / (2 * hlR)
float currentBuyVol = volume * bVR
float currentSellVol = volume * (1 - bVR)
float delta = currentBuyVol - currentSellVol
This snippet explains how the script approximates order flow direction on the current bar.
First, it measures the candle range from high to low. Then it computes a buy volume ratio using the relative location of the open and close inside that range:
(close - low + high - open) / (2 * hlR)
This ratio becomes a practical estimate of how much of the bar’s total volume behaved like buying pressure versus selling pressure. If the candle closes stronger and opens higher inside its range, the ratio leans more bullish. If the candle structure is weaker, the ratio leans more bearish.
That ratio is then used to split total volume into:
currentBuyVol
and
currentSellVol
Finally, the script calculates delta as the difference between estimated buy volume and estimated sell volume.
This is not true transaction tagged exchange delta, but it is a useful chart based directional participation model.
5) Distributing Candle Volume Across Touched Price Rows
method addBarVolume(VolumeProfile this, float h, float l, float c, float o, float v) =>
float hlRange = h - l
float buyVolRatio = hlRange == 0 ? 0.5 : (c - l + h - o) / (2 * hlRange)
float buyV = v * buyVolRatio
float sellV = v * (1 - buyVolRatio)
int startIdx = this.getBinIndex(l)
int endIdx = this.getBinIndex(h)
for i = startIdx to endIdx
if i >= 0 and i < this.bins.size()
PriceBin b = this.bins.get(i)
float binTop = b.price + (this.binSize / 2)
float binBot = b.price - (this.binSize / 2)
float overlapTop = math.min(h, binTop)
float overlapBot = math.max(l, binBot)
float overlap = math.max(0.0, overlapTop - overlapBot)
float weight = hlRange > 0 ? overlap / hlRange : (1.0 / (endIdx - startIdx + 1))
b.buyVol += buyV * weight
b.sellVol += sellV * weight
b.totalVol += v * weight
this.bins.set(i, b)
this.totalVol += v * weight
This is one of the most important calculations in the entire script.
For each candle inside the lookback period, the script first computes estimated buy volume and sell volume. Then it finds which profile rows are touched by the candle’s low and high.
For every touched row, it measures how much of the candle overlaps that specific row. That overlap becomes a weighting factor:
weight = overlap / hlRange
If a candle overlaps a row heavily, that row receives a larger share of the bar’s volume. If the overlap is small, the row receives only a small share.
The script then adds weighted buy volume, weighted sell volume, and weighted total volume into that bin.
This is much more realistic than assigning all volume to a single row because it respects the actual price space the candle traveled through.
6) Determining the Point of Control
method calcValueArea(VolumeProfile this, float pct) =>
float midPrice = (this.highPrice + this.lowPrice) / 2
float maxVol = -1.0
float bestPrice = na
int pocIdx = -1
for i = 0 to this.bins.size() - 1
PriceBin b = this.bins.get(i)
if b.totalVol > maxVol
maxVol := b.totalVol
bestPrice := b.price
pocIdx := i
else if b.totalVol == maxVol and maxVol > 0
if math.abs(b.price - midPrice) < math.abs(bestPrice - midPrice)
bestPrice := b.price
pocIdx := i
this.pocVol := maxVol
this.pocPrice := bestPrice
This is the first phase of the value area calculation.
The script scans all bins and finds the row with the greatest total volume. That row becomes the Point of Control. If two rows have the same maximum volume, the script breaks the tie by choosing the one closer to the middle of the full lookback range.
That tie handling matters because it avoids unstable selection when multiple bins have identical strength.
After the winning row is found, the script stores:
the Point of Control volume in pocVol
and the Point of Control price in pocPrice
So the Point of Control is not simply a visual midpoint. It is the actual strongest participation row in the profile.
7) Expanding Upward and Downward to Build the Value Area
float targetVol = this.totalVol * pct / 100.0
float currentVol = 0.0
if pocIdx >= 0 and pocIdx < this.bins.size()
currentVol := this.bins.get(pocIdx).totalVol
int upIdx = pocIdx + 1
int dnIdx = pocIdx - 1
while currentVol < targetVol and (upIdx < this.bins.size() or dnIdx >= 0)
float upVol = upIdx < this.bins.size() ? this.bins.get(upIdx).totalVol : -1.0
float dnVol = dnIdx >= 0 ? this.bins.get(dnIdx).totalVol : -1.0
After finding the Point of Control, the script calculates the target volume required for the value area. For example, if the input is 70 percent, the target becomes 70 percent of total profile volume.
The expansion begins from the Point of Control row itself. currentVol starts with the Point of Control row’s own total volume. Then the script looks one row up and one row down, repeatedly expanding until the accumulated volume reaches the target.
This is the standard logic of building a value area around the strongest participation center.
8) Deciding Whether to Expand Up or Down
if upVol > dnVol and upVol != -1.0
currentVol += upVol
upIdx += 1
else if dnVol > upVol and dnVol != -1.0
currentVol += dnVol
dnIdx -= 1
else if upVol == dnVol and upVol != -1.0
if currentVol + upVol > targetVol
if math.abs(this.bins.get(upIdx).price - midPrice) < math.abs(this.bins.get(dnIdx).price - midPrice)
currentVol += upVol
upIdx += 1
else
currentVol += dnVol
dnIdx -= 1
else
currentVol += upVol + dnVol
upIdx += 1
dnIdx -= 1
This block decides which side to include next in the value area.
If the row above has more volume than the row below, the script expands upward. If the row below has more volume, it expands downward. If both sides are equal, it uses distance to the overall midpoint as a tie breaker when necessary.
This is important because value area growth should follow participation strength, not arbitrary direction. The final result is a value area that naturally wraps around the highest volume concentration.
9) Final VAH and VAL Assignment
int finalUpIdx = math.max(pocIdx, upIdx - 1)
int finalDnIdx = math.min(pocIdx, dnIdx + 1)
this.vah := finalUpIdx < this.bins.size() ? this.bins.get(finalUpIdx).price : this.highPrice
this.val := finalDnIdx >= 0 ? this.bins.get(finalDnIdx).price : this.lowPrice
Once expansion is complete, the script converts the final included rows into value area boundaries.
The highest included row becomes Value Area High.
The lowest included row becomes Value Area Low.
These values define the central price zone where the chosen percentage of the profile’s total volume was traded.
So VAH and VAL are directly derived from the row by row structure of the profile, not from any fixed percentage of price range.
10) Detecting Unusual Volume Activity
float volSma = ta.sma(volume, 200)
float volStdev = ta.stdev(volume, 200)
float zScore = volStdev == 0 ? 0 : (volume - volSma) / volStdev
float deltaRatio = volume > 0 ? math.abs(delta) / volume : 0
bool isUnusual = zScore > zScoreThreshold and deltaRatio >= deltaRatioThreshold
This block evaluates whether the current bar is unusually active.
First, the script computes a 200 period average volume and standard deviation. Then it transforms the current bar’s volume into a z score, which shows how many standard deviations the bar stands above normal background activity.
Next, it calculates deltaRatio , which measures how large the directional imbalance is relative to total volume.
A bar is marked unusual only if both conditions are true:
the volume is statistically large enough,
and the directional imbalance is meaningful enough.
This double filter helps reduce false signals from large but directionless bars.
11) Printing Unusual Volume Bubbles
if showUnusual and isUnusual
string lblText = (delta > 0 ? "🟢 " : "🔴 ") + str.tostring(math.round(volume))
color lblColor = delta > 0 ? color.new(color.green, 0) : color.new(color.red, 0)
label uLbl = label.new(bar_index, delta > 0 ? low : high, text=lblText, style=label.style_none, textcolor=lblColor, yloc=delta > 0 ? yloc.belowbar : yloc.abovebar, size=size.small)
When an unusual bar is detected, the script prints a directional marker.
If estimated delta is positive, the bubble is shown below price in green.
If estimated delta is negative, the bubble is shown above price in red.
The displayed text also includes the rounded volume value. This allows the user to quickly see both direction and size of the unusual participation event.
So these markers are not random momentum tags. They specifically highlight bars where both participation size and directional imbalance stand out.
12) Rebuilding the Profile on the Last Bar
float highestPrice = ta.highest(high, lookback)
float lowestPrice = ta.lowest(low, lookback)
if barstate.islast and bar_index >= lookback - 1
profile.initBins(highestPrice, lowestPrice, rows)
for i = 0 to lookback - 1
profile.addBarVolume(high , low , close , open , volume )
profile.calcValueArea(vaPct)
This is the main execution block for the profile.
First, the script finds the highest high and lowest low across the chosen lookback window. That defines the total vertical space of the analysis.
Then, on the last visible bar, it:
initializes the bins,
loops through every candle inside the lookback,
adds each candle’s weighted volume into the profile,
and finally calculates the value area.
Running this only on the last bar is efficient because the full profile is a visual structure based on the current lookback window. It does not need to be redrawn historically on every past bar.
13) Scaling and Drawing the Profile Histogram
float maxVol = profile.pocVol
float allVols = array.new_float()
for i = 0 to profile.bins.size() - 1
allVols.push(profile.bins.get(i).totalVol)
float avgVol = allVols.avg()
float stdVol = allVols.stdev()
float clampedMaxVol = math.max(math.min(maxVol, avgVol + (stdVol * 2)), 0.000001)
Before drawing the profile, the script prepares a safer scaling reference.
Instead of using raw Point of Control volume alone without adjustment, it clamps the maximum drawable scale using the average row volume plus two standard deviations. This helps prevent a single extreme row from making the rest of the profile look too compressed.
In practical terms, this means the visual histogram remains readable even when one row is exceptionally dominant.
14) Drawing Buy Side and Sell Side Inside Each Row
int buyLen = math.round((b.buyVol / b.totalVol) * (drawVol / clampedMaxVol) * profileWidth)
int sellLen = math.round((b.sellVol / b.totalVol) * (drawVol / clampedMaxVol) * profileWidth)
bool inVA = b.price <= profile.vah and b.price >= profile.val
bool isPocRow = math.abs(b.price - profile.pocPrice) <= profile.binSize * 0.5
int x1 = profileRight
int x2 = x1 - buyLen
if buyLen > 0
box bB = box.new(x1, topP, x2, botP, border_color=c_border, bgcolor=c_buy)
int x3 = x2
int x4 = x3 - sellLen
if sellLen > 0
box bS = box.new(x3, topP, x4, botP, border_color=c_border, bgcolor=c_sell)
This is the actual profile drawing logic.
For each row, the script determines how much of the row’s total activity came from estimated buy volume and how much came from estimated sell volume. It then converts those fractions into horizontal lengths.
The buy portion is drawn first, then the sell portion continues from the end of the buy section. This creates a stacked horizontal bar that reveals both total participation and internal directional composition.
The row also receives context coloring:
rows inside the value area use stronger color treatment,
and the Point of Control row can receive a distinct border.
So the histogram communicates three layers at once:
how much volume was traded there,
whether that row sits inside the value area,
and how that row’s activity was split between estimated buying and selling pressure.
15) Drawing POC, VAH, and VAL Lines
line pocL = line.new(lineStartX, profile.pocPrice, lineEndX, profile.pocPrice, color=col_poc, width=2, style=line.style_solid)
profileLines.push(pocL)
line vahL = line.new(lineStartX, profile.vah, lineEndX, profile.vah, color=col_vah, width=1, style=line.style_dashed)
profileLines.push(vahL)
line valL = line.new(lineStartX, profile.val, lineEndX, profile.val, color=col_val, width=1, style=line.style_dashed)
profileLines.push(valL)
Once the profile is built, the script draws the three most important structural references:
Point of Control,
Value Area High,
and Value Area Low.
These lines can behave as compact annotations near the profile or as broader structure references if extension is enabled.
This gives the user a quick way to read acceptance and central balance without needing to inspect every row manually.
16) Detecting Liquidity Voids
float voidLimit = profile.pocVol * (voidThreshold / 100.0)
bool inVoid = false
float voidStartPrice = na
for i = 0 to profile.bins.size() - 1
PriceBin b = profile.bins.get(i)
bool isOutsideVA = b.price > profile.vah or b.price < profile.val
This is the beginning of the liquidity void logic.
A row is never treated as a void candidate solely because its volume is small. The script first requires that the row be outside the value area. This matters because low volume inside the main acceptance zone does not carry the same meaning as low volume outside it.
The script also calculates voidLimit as a percentage of Point of Control volume. That creates a relative participation threshold tied to the strongest row in the profile.
17) Comparing Each Row to Its Neighbors
float sumNeighbors = 0.0
int nC = 0
for j = math.max(0, i - 2) to math.min(profile.bins.size() - 1, i + 2)
if j != i
sumNeighbors += profile.bins.get(j).totalVol
nC += 1
float localAvg = nC > 0 ? sumNeighbors / nC : 0.0
bool isGap = b.totalVol < (localAvg * 0.5)
bool isLowVol = b.totalVol < voidLimit
bool isVoid = isLowVol and isGap and isOutsideVA
This is the real filter that defines a liquidity void.
The script looks at nearby bins around the current row and calculates a local neighbor average. Then it applies two separate tests:
the row must be low relative to the Point of Control threshold,
and it must also be weak relative to its nearby neighbors.
Only if both are true, and the row is outside the value area, does the script classify it as a void.
This is important because it prevents the indicator from marking every low volume row as a void. A valid void must look weak both globally and locally.
18) Grouping Consecutive Void Rows Into Zones
if isVoid
if not inVoid
inVoid := true
voidStartPrice := b.price - (profile.binSize / 2)
else
if inVoid
inVoid := false
float voidEndPrice = b.price - (profile.binSize / 2)
float topCoord = math.max(voidStartPrice, voidEndPrice)
float botCoord = math.min(voidStartPrice, voidEndPrice)
box vBox = box.new(bar_index - lookback, topCoord, bar_index, botCoord, border_color=na, bgcolor=col_void)
Once a void row is detected, the script begins tracking a continuous void run. If the next row is also a void, the zone continues. When the run ends, the script closes the zone and draws a box covering the full void area.
This means the indicator does not plot isolated tiny marks for each row. Instead, it groups neighboring weak rows into a cleaner structure that better represents a meaningful liquidity gap.
That box is then labeled as a liquidity void, making the zone easy to identify visually. Indicator

Adaptive Momentum RibbonWhat It Does
Adaptive Momentum Ribbon (AMR) is a directional momentum tool that identifies shifts in price equilibrium and marks them directly on the price chart with entry labels and dynamic invalidation levels. It pairs a robust statistical oscillator with a Keltner Channel envelope to give traders both timing signals and volatility context in a single overlay.
How It Works
The indicator is built on three independent components working together:
1. Median Absolute Deviation (MAD) Z-Score
Instead of using a standard deviation z-score (which is heavily influenced by outlier candles and spike wicks), AMR calculates a rolling median of price, then measures how far price has deviated from that median, normalized by the Median Absolute Deviation. MAD is a statistical measure of dispersion that is approximately 50% more resistant to outliers than standard deviation. The raw MAD value is scaled by 1.4826 to make it directly comparable to standard deviation under normal distribution assumptions. The result is a z-score that reflects genuine shifts in price positioning rather than reacting disproportionately to single volatile bars.
2. Butterworth Low-Pass Filter
The raw z-score is then passed through a second-order Butterworth low-pass filter. Unlike cascaded EMAs (which introduce cumulative lag at each stage), the Butterworth filter is designed to have a maximally flat frequency response in the passband. This means it preserves the shape of genuine momentum moves while attenuating high-frequency noise. The filter's two-pole design provides a steeper roll-off than any single-pole smoothing method, delivering cleaner zero-line crossovers with less delay.
3. Keltner Channel Envelope
A standard Keltner Channel (moving average +/- ATR multiple) provides volatility context. Unlike Bollinger Bands, which use standard deviation and tend to expand/contract sharply on individual outlier bars, Keltner Channels use Average True Range, producing smoother, more stable bands that account for gap behavior and true intrabar range.
Signal Logic
A bullish signal (upward label) fires when the filtered z-score crosses above zero, indicating that price has shifted above its rolling median by a statistically meaningful amount after smoothing.
A bearish signal (downward label) fires when the filtered z-score crosses below zero.
Each signal generates an invalidation level (dashed line), placed at the low (for bullish) or high (for bearish) of the signal bar, offset by a long-term volatility measure (100-period EMA of True Range). If price breaches this level, an X marker appears, indicating the signal's premise has been violated.
The invalidation level extends forward in real time until it is either breached or replaced by a new signal in the opposite direction.
How to Use It
Trend Confirmation: Use the signal labels alongside the Keltner Channel. Bullish signals firing near the lower KC band suggest mean-reversion opportunities. Bullish signals near or above the midline suggest trend continuation.
Invalidation as Risk Management: The dashed invalidation line can serve as a reference for stop-loss placement. When the X appears, the statistical basis for the entry no longer holds.
Parameter Guidance:
Momentum Period (default 20): Controls the lookback for the median and MAD calculation. Shorter periods react faster but produce more signals. Longer periods are smoother but slower.
Butterworth Smoothing (default 3): Controls noise filtering. A value of 1 passes the raw z-score through with minimal filtering. Values of 3-5 work well for most timeframes.
KC settings: Standard Keltner Channel parameters. The defaults (20 EMA, 14 ATR, 2x multiplier) are widely used and work across most instruments and timeframes.
Limitations and Honest Caveats
This indicator does not predict future price. It identifies statistical shifts in recent price positioning relative to a rolling median. These shifts may or may not lead to sustained moves.
Like all zero-crossing oscillators, it will generate false signals during choppy, range-bound markets. The Keltner Channel can help filter these visually (signals near the midline in a flat channel are lower conviction).
The invalidation levels are references, not guaranteed stop levels. Slippage and gaps can cause exits beyond these prices.
The MAD z-score assumes sufficient data variation. In extremely low-volatility environments where price barely moves, the MAD can approach zero. A fallback to standard deviation is built in for this edge case, but signals during such periods should be treated with extra caution.
No repainting. All signals fire on the confirmed close of the signal bar and reference the prior bar's high/low for level placement. No future data is accessed.
Summary
AMR combines outlier-robust statistics (MAD z-score), signal-processing-grade smoothing (Butterworth filter), and volatility-adaptive context (Keltner Channel) into a single chart overlay. It is designed for traders who want clean directional signals with built-in invalidation logic, without relying on indicators that overreact to spike wicks or require a separate oscillator pane. Indicator

Ornstein-Uhlenbeck Mean Reversion Probability Bands [UAlgo]Ornstein-Uhlenbeck Mean Reversion Probability Bands is a statistical mean reversion indicator that models price as a mean reverting process and projects dynamic probability style zones around an estimated equilibrium mean. The script uses a rolling lookback of closing prices, fits an Ornstein-Uhlenbeck inspired parameter set from recent behavior, and then converts that estimate into inner and outer deviation bands around the current mean.
The indicator runs directly on price ( overlay=true ) and is built to help traders identify when price is stretched away from its estimated equilibrium. Instead of using a fixed moving average and static standard deviation, the script attempts to infer a mean reverting structure from the data itself. It estimates the long term mean, the speed of reversion, and an equilibrium style dispersion measure, then plots two upside and two downside mean reversion zones.
When price pushes into the upper or lower band regions, the script calculates a standardized distance from the estimated mean and displays a probability style label with both the percentage score and the current z score. This gives the user a quick visual read of how statistically extended price is relative to the model.
A key strength of this script is that it combines:
A rolling Ornstein-Uhlenbeck style parameter estimation
Adaptive mean reversion zones
Probability style stretch labels at band events
A clean overlay presentation with visible upper and lower probability regions
Important note: The percentage label in this script is a normal distribution coverage style score derived from the current z score. It is best understood as a probabilistic stretch measure, not a literal exact OU first passage probability.
🔹 Features
🔸 1) Ornstein-Uhlenbeck Inspired Mean Reversion Model
The script estimates a mean reverting process from recent closing prices instead of relying only on a moving average. It uses a rolling regression style approach on consecutive price observations, then converts those estimates into Ornstein-Uhlenbeck style parameters.
This makes the indicator more model driven than a standard band tool.
🔸 2) Rolling Adaptive Mean Line
The central mean line is not a fixed average only. It is the estimated equilibrium level ( mu ) of the fitted process. As the rolling price sample changes, the model updates and the mean shifts with changing market structure.
The mean line also changes color depending on whether current price is above or below that estimated equilibrium.
🔸 3) Dual Mean Reversion Zones (Inner and Outer)
The script builds two sets of reversion bands around the mean:
Inner bands using the inner multiplier
Outer bands using the outer multiplier
This creates a layered framework where the inner zone marks an early stretch area and the outer zone marks a more extreme statistical extension.
🔸 4) Probability Style Stretch Labels
When price crosses into the upper or lower band regions, the script calculates a z score based on current distance from the estimated mean and converts it into a percentage style probability score.
The label shows:
A directional marker
The probability style percentage
The current z score
This gives the user both a visual event trigger and a numeric measure of extension.
🔸 5) Visual Zone Based Design
The indicator uses filled upper and lower zones rather than emphasizing the band lines themselves. This creates a cleaner chart display where the mean line stays visible and the stretch regions are highlighted as colored areas above and below it.
This makes the indicator easy to read during fast chart scanning.
🔸 6) Configurable Lookback, Time Step, and Band Width
Users can customize:
The rolling lookback period used for model estimation
The time step parameter ( dt ) used in OU conversion
The inner band multiplier
The outer band multiplier
This makes the script adaptable to different timeframes, instruments, and preferred sensitivity levels.
🔸 7) Built In Estimation Safeguards
The parameter estimation logic includes fallback protections. If the inferred model parameters are unstable or unrealistic, the script falls back to simpler sample statistics. This helps prevent unusable outputs during difficult market regimes or low quality fits.
🔸 8) Directional Touch Event Logic
The script tracks both upper side and lower side band interaction:
Upper side events can signal statistically stretched bullish price movement
Lower side events can signal statistically stretched bearish price movement
Labels are only created on crossing events, which helps reduce repeated prints while price remains outside the band.
🔹 Calculations
1) Rolling Price Queue Management
The script stores recent closing prices in an array with a fixed maximum length:
price_array.update_queue(close, length_input)
The queue update method behaves differently depending on bar state:
On a new bar, it pushes the latest value
On an updating live bar, it overwrites the last stored value
This keeps the rolling sample aligned with the current chart state without duplicating the active bar.
2) Fallback Mean and Dispersion Estimates
Before attempting the OU style fit, the script calculates simple fallback values:
float fallback_mu = src_array.avg()
float fallback_sigma = src_array.stdev()
These act as safety defaults if the regression based OU estimate is not reliable.
Important note:
In this script, fallback_sigma is a simple sample standard deviation of price levels, not return volatility.
3) AR(1) Style Regression on Consecutive Prices
The model estimation is built from consecutive price pairs:
x = price
y = price
The script computes:
Mean of x
Mean of y
Covariance between x and y
Variance of x
Then it estimates:
float b = sum_cov / sum_var_x
This creates an AR(1) style coefficient that is later translated into OU style parameters.
4) Conversion from AR(1) Form to OU Style Parameters
If the estimated b is within a valid range:
if b > 0.05 and b < 0.95
the script computes:
float a = mean_y - b * mean_x
float mu_exact = a / (1.0 - b)
float theta_exact = -math.log(b) / dt
Interpretation:
mu_exact is the estimated long run mean.
theta_exact is the implied mean reversion speed.
The conversion assumes the AR(1) relation is a discrete time representation of a mean reverting process.
5) Residual Variance and Equilibrium Dispersion
The script next measures residual error from the AR(1) fit:
float err = y_i - (a + b * x_i)
float var_err = sum_err_sq / (n - 1)
Then it converts that residual variance into an equilibrium variance estimate:
float var_eq = var_err / (1.0 - b * b)
Finally:
float calc_sigma = math.sqrt(var_eq)
Important implementation note:
The variable named sigma in this script is used as an equilibrium style standard deviation around the mean, not as the continuous time OU diffusion coefficient from the SDE form.
6) Stability Filter for the Estimated Sigma
Even if the AR(1) fit is mathematically valid, the script only accepts the calculated sigma when it is reasonably close to the fallback sample standard deviation:
if calc_sigma < fallback_sigma * 1.5 and calc_sigma > fallback_sigma * 0.5
If this test fails, the script keeps the fallback values instead.
This helps avoid unstable band widths caused by bad short term fits.
7) Final Parameter Output
The estimation method returns:
OU_Params.new(theta, mu, sigma_eq)
Where:
theta is the estimated reversion speed
mu is the estimated equilibrium mean
sigma_eq is the accepted equilibrium dispersion measure
These parameters are then used to build the bands.
8) Band Construction
The script computes four band levels around the estimated mean:
float up_out = mean_val + (dev_val * mult_outer)
float up_in = mean_val + (dev_val * mult_inner)
float dn_in = mean_val - (dev_val * mult_inner)
float dn_out = mean_val - (dev_val * mult_outer)
Interpretation:
Inner bands represent a milder deviation from the mean.
Outer bands represent a more extreme deviation from the mean.
9) Mean and Zone Visualization
The mean line is explicitly plotted:
p_mean = plot(ou_bands.mean, color=color_mean, linewidth=2, title="Mean")
The inner and outer band plots are also created, but their colors are fully transparent:
color color_inner_up = color.new(#ffb74d, 100)
color color_outer_up = color.new(#ef5350, 100)
...
This means the visible structure mainly comes from the zone fills:
fill(p_ui, p_uo, ...)
fill(p_li, p_lo, ...)
So the user sees clean upper and lower probability zones rather than several bright boundary lines.
10) Touch and Crossing Logic
The script first checks whether price is currently inside a stretch area:
bool touch_upper = close >= ou_bands.upper_inner
bool touch_lower = close <= ou_bands.lower_inner
Then it checks for fresh crossings:
bool cross_up_in = ta.crossover(close, ou_bands.upper_inner)
bool cross_up_out = ta.crossover(close, ou_bands.upper_outer)
bool cross_dn_in = ta.crossunder(close, ou_bands.lower_inner)
bool cross_dn_out = ta.crossunder(close, ou_bands.lower_outer)
Labels are only created when price is touching the region and a fresh crossing occurs. This avoids creating labels on every bar that remains outside the band.
11) Z Score Calculation
When an event occurs, the script calculates the standardized distance from the mean:
float current_z_score = dev_val != 0 ? math.abs(close - mean_val) / dev_val : 0.0
Interpretation:
A z score of 1 means price is one equilibrium standard deviation away from the estimated mean.
Higher values indicate a more statistically stretched condition.
12) Probability Style Score Calculation
The script converts the z score into a percentage style score using an approximation of the error function:
float x = math.abs(z_score) / math.sqrt(2.0)
...
float prob = erf_approx * 100.0
Because erf(|z| / sqrt(2)) corresponds to the probability mass within plus or minus that z distance under a normal distribution, the output behaves like a confidence or coverage score.
Important note:
This is not a direct OU mean reversion probability in the strict stochastic process sense. It is a normal distribution style stretch score based on the current z distance.
13) Upper Event Label Logic
When price crosses into the upper band region:
if (touch_upper and cross_up_in) or (touch_upper and cross_up_out)
the script prints a bearish styled label above the bar:
"▼ %" + str.tostring(probability, "#.##") + " (Z:" + str.tostring(current_z_score, "#.##") + ")"
This reflects the idea that price is statistically extended above the mean and may be vulnerable to reversion.
14) Lower Event Label Logic
When price crosses into the lower band region:
if (touch_lower and cross_dn_in) or (touch_lower and cross_dn_out)
the script prints a bullish styled label below the bar:
"▲ %" + str.tostring(probability, "#.##") + " (Z:" + str.tostring(current_z_score, "#.##") + ")"
This reflects the idea that price is statistically extended below the mean and may be vulnerable to reversion.
15) Role of the Time Step Input
The dt_input parameter affects the conversion from the AR(1) coefficient into the OU reversion speed:
float theta_exact = -math.log(b) / dt
A larger dt lowers the inferred theta for the same b .
A smaller dt raises the inferred theta for the same b . Indicator

Hawkes Vol-Expansion Detector [UFVG]Financial markets exhibit "volatility clustering" large moves tend to be followed by large moves, and quiet periods by quiet periods. The Hawkes Vol-Expansion Detector is built on the premise that market volume and volatility are self-exciting. When a significant market shock occurs, it temporarily increases the probability of further shocks before eventually decaying back to a baseline level.
By tracking volume anomalies and ATR expansions through a mathematical framework known as a Hawkes Process, this indicator visualizes the buildup and decay of market intensity, giving traders a heads-up before prolonged volatility expansions.
The Mathematics: How It Works
At the core of this indicator is a discretized version of the Hawkes Process. It calculates the current market intensity (λ) at time t based on a constant baseline, the decayed intensity from previous periods, and new market shocks.
The exact formula calculated under the hood is:
λ_t = μ + (λ_{t-1} - μ) * e^(-β) + α * X_t
Here is what these variables represent in the indicator:
λ_t (Current Intensity): The total plotted excitation level of the market.
μ (Baseline Intensity, mu_eff): The constant, underlying rate of market activity when no shocks are occurring.
α (Excitation Jump, alpha_eff): The exact amount the intensity spikes when a new volume shock is detected.
β (Decay Rate, beta_eff): The speed at which the excess market excitement fades back to the baseline.
X_t (Shock Event): A boolean value (1 or 0) indicating if a volume/price shock occurred on the current candle.
Additionally, the indicator utilizes the Branching Ratio (n), defined mathematically as:
n = α / β
In quantitative modeling, if n < 1, the process is stable (shocks eventually die out). If n >= 1, the process becomes unstable and explodes. The auto-tuned parameters in this script are specifically designed to keep the branching ratio stable while remaining highly responsive to expansions.
Volume Shock Detection (X_t)
The indicator does not just fire the excitation parameter (α) on every candle. A "Shock Event" (X_t = 1) strictly occurs only when both of the following conditions are met:
Volume Z-Score: The current volume must exceed its rolling moving average by a specific standard deviation threshold.
Z = (V_t - μ_V) / σ_V
ATR Displacement: High volume without price movement is often absorption. To confirm a valid shock, the candle's high-to-low range must exceed a multiplier of the Average True Range (ATR).
Dynamic Timeframe Auto-Tuning
Different timeframes have different noise profiles. A 5-minute chart has erratic, frequent spikes, while a Daily chart's volume is more sustained. If the "Auto-adjust by Timeframe" setting is active, the script dynamically adjusts μ, α, β, and the Z-score threshold to fit the timeframe:
Low Timeframes (<= 5m): Uses a higher Z-score requirement (Z=2.0) to filter out intraday noise, with a faster decay rate.
Mid Timeframes (15m - 1H): Uses balanced parameters (Z=1.8).
High Timeframes (Daily+): Lowers the Z-score threshold (Z=1.5) but uses a higher baseline and slower decay, reflecting the longer-lasting impact of macro-level daily shocks.
How to Read the Chart
The indicator plots the λ_t line against a flat baseline (μ).
Yellow Diamonds: Mark the exact candles where a volume/ATR shock (X_t = 1) occurred.
Teal/Green Zones (Calm): The intensity is near baseline. The market is consolidating or ranging.
Orange Zones (Elevated): Multiple shocks are stacking up. The decay rate (β) cannot keep up with the new excitations (α). This is your warning that a trend or volatility expansion is initiating.
Red Zones (Expansion): The market is in a full volatility expansion. Excess intensity has crossed the critical threshold. Look for momentum continuation or impending climax depending on price action. Indicator

Indicator

Crypto PCA [LuxAlgo]The Crypto PCA indicator provides a sophisticated, multi-asset sentiment gauge by applying Principal Component Analysis (PCA) to a basket of the top 20 cryptocurrencies.
By extracting the primary driver of variance across these assets, the tool offers a "market-wide" oscillator that filters out individual coin noise to highlight the dominant trend and sentiment shifts in the crypto space.
In modern quantitative finance, PCA is used to reduce dimensionality and identify the underlying factors that move a group of assets. This indicator brings that institutional-grade approach to the retail trader, condensing the price action of Bitcoin, Ethereum, Solana, and 17 other majors into a single, actionable signal.
🔶 USAGE
The script serves as a macro-sentiment oscillator, allowing traders to see the "hidden" force driving the crypto market. It is designed to identify when the market is moving in unison and when that collective movement has reached an extreme.
🔹 Identifying Market Regimes
The primary use of the PCA line (PC1) is to determine the current market regime. When the oscillator is above the zero line and colored green, it indicates that the majority of the top 20 assets are experiencing positive variance, signaling a broad bullish regime. Conversely, when the line is below zero and colored red, the market is in a collective bearish state. Traders can use this to align their individual trades with the direction of the total market energy.
🔹 Using Snapshot Mode for Situational Analysis
While the continuous mode is ideal for long-term trend following, the Snapshot Mode provides a focused view of market dynamics over the most recent lookback window. This mode isolates the current sentiment cycle, allowing traders to see the specific trajectory and "shape" of the latest move without the influence of older historical data.
By enabling Snapshot Mode, you can analyze the immediate internal structure of the market. It is particularly useful for identifying whether a recent pump or dump is a coordinated market-wide event or a more fragmented move. This helps in distinguishing between a broad structural shift and a temporary volatility spike.
🔹 Spotting Overextended Sentiment
The indicator includes dashed horizontal lines at +2 and -2, representing standard deviation thresholds. Because the assets are standardized before calculation, these levels mark statistical extremes.
Overbought Extremes: When the PCA line exceeds +2, the broad market is significantly overextended to the upside. This often precedes a cooling-off period or a mean-reversion event across the entire sector.
Oversold Extremes: When the PCA line drops below -2, it suggests a "panic" or exhausted selling state across the basket. This can signal potential bottoming interest or a relief rally.
🔹 Gauging Relative Strength
The faint "ghost" lines in the background represent the individual standardized price paths of the 20 included assets. By comparing these to the main PCA line, traders can identify leaders and laggards. An asset line that stays consistently above the PCA line during a rally is exhibiting relative strength, while an asset trailing below the PCA line is underperforming the market average.
🔶 DETAILS
The indicator follows a rigorous mathematical pipeline to ensure the data is statistically significant and comparable across assets with different price scales.
🔹 Standardization (Z-Scores)
Before performing PCA, every asset must be on the same scale. The script converts the price of all 20 assets into Z-scores based on the user-defined Lookback Period. A Z-score tells us how many standard deviations a price is from its mean. This allows the movement of a high-priced asset like BTC to be mathematically compared to a lower-priced asset like PEPE.
🔹 The Basket & PCA Approximation
The indicator includes the following assets: BTC, ETH, BNB, XRP, SOL, TRX, DOGE, ADA, BCH, WBTC, XLM, LTC, HBAR, LINK, AVAX, PEPE, DOT, UNI, NEAR, and ICP.
The script uses a correlation-based approximation to find the First Principal Component. It calculates the correlation of each asset to the equally weighted basket and uses these correlations as "loadings" to compute the PC1. This ensures that assets moving in sync with the general market trend are given higher priority in the final oscillator value.
🔹 Why PCA?
Most "Crypto Indices" are simply weighted averages. PCA is superior because it identifies the commonality between assets. If 18 coins are moving up and 2 are moving down, PCA gives more weight to the 18 moving together, as they represent the "Principal Component" of the market's current energy.
🔶 SETTINGS
🔹 Main Settings
Lookback Period (N): Determines the window used for Z-score standardization and PCA calculation. A shorter period makes the indicator more reactive, while a longer period identifies macro-cycle shifts.
Z-Score Smoothing: Applies a Simple Moving Average (SMA) to the standardized asset values before the PCA calculation. This effectively filters out high-frequency noise and produces a smoother principal component line, which is useful for reducing false regime shifts in volatile markets.
Enable Snapshot Mode: Switches the visual output from a continuous rolling line to a static view of the PCA over the most recent lookback window.
🔹 Visual Settings
Standardized Assets Color: Controls the color and transparency of the 20 individual asset lines.
Bull/Bear Colors: Defines the colors used for positive and negative market sentiment.
Disclaimer: This indicator is a statistical tool for sentiment analysis and does not constitute financial advice. The PCA approach measures variance and correlation, not guaranteed future direction. Indicator
