Keltner Position Divergence with Reliability ScoringOverview
Keltner-Position Divergence with Reliability Scoring turns where price sits inside its Keltner channel into a bounded oscillator, reads it for divergence against price, and then scores — in real time — whether those divergences have actually been worth acting on for the symbol on your chart, and which direction is carrying the edge. It is a context / research read, not a standalone buy or sell signal.
The idea
A Keltner channel frames price with an ATR envelope around a moving average. Where price sits inside that envelope — pinned to the upper band, mid, or pinned to the lower band — is a bounded read of stretch. When price makes a new high but its Keltner position does not confirm (a lower band-position high), that non-confirmation can precede a turn. This script measures the divergence between price and its Keltner position, then keeps a self-updating track record of whether such divergences pay.
Why these parts are combined (mashup rationale)
Three components form one pipeline, not three separate signals:
A Keltner-position oscillator — price's location within the ATR envelope (0 centre, +1 upper band, −1 lower band), z-scored so the bands and zones mean the same on every asset.
Confirmed-pivot divergence — regular and hidden, between that position line and price, with an optional triple-pivot mode for rarer, stronger disagreements.
A reliability harness — a binomial-proportion confidence test that asks whether each class of divergence has preceded a favourable move (a k×ATR travel over a fixed horizon) more often than a same-zone baseline, reported per direction with a Wilson confidence bound.
Part 1 builds the bounded stretch read, part 2 fires only where price and position disagree, part 3 decides whether that disagreement has actually paid on this instrument. Remove any one and the tool can no longer answer "is this Keltner divergence worth trading here?"
How to use it
Read the verdict panel first. GREEN = these divergences have beaten a same-spot baseline here; RED = they've lost to it (skip, or change the band width / timeframe); AMBER = not statistically established yet; GREY = still gathering data. "Best signal" names the direction with the strongest measured edge; "Reward : risk" is the average best-vs-worst move after a signal, in ATR. A divergence is price making a higher high / lower low while the Keltner-position line does the opposite — marked in the pane and, optionally, on the price chart. It is context, never a standalone trigger.
Settings worth knowing
The regime filter ("Only count signals in regime") restricts the track record to signals that fired in a chosen regime — reverting markets suit divergence, strong trends punish it — so you can measure the edge where it's supposed to work. Costs subtracted (×ATR) raises the bar a signal must clear so the score is net of costs. Band width, MA length and the z-score window adapt the read to any instrument.
Universality & non-repainting
It reads only the chart's own price (configurable source), so it runs on any symbol, any timeframe, with no external data. Pivots confirm a fixed number of bars after the fact, and the track-record harness logs, updates and resolves only on confirmed (closed) bars, so its statistics never inflate or shift intrabar. The live oscillator updates each bar like any oscillator. All figures are in-sample and past-only.
Outputs for other scripts
Generic EXP_* plots — oscillator, signal, probability, edge, edge lower-bound, sample count, regime, band position — are published to the Data Window for use from other scripts via input.source().
Originality
Standard Keltner tools just plot the channel. This one turns band-position into a divergence oscillator and keeps a self-updating, confidence-scored, per-class track record against a same-zone baseline — so you see not just that a divergence printed, but whether and how it has paid on the current market. Clean-room implementation; no third-party Pine code reused.
Concept credits
Keltner channel — Chester Keltner; ATR-band refinement — Linda Raschke
Average True Range — J. Welles Wilder
Binomial score confidence interval — Edwin B. Wilson
Trend-efficiency regime measure — Perry Kaufman
Disclaimer
For research and education only. Not financial advice, not a recommendation, and not a guarantee of future results. All figures are in-sample and past-only. Markets carry risk; do your own research and manage your own risk. Indicator

DJT Strategy - The Art of the DipWHAT THIS IS
A satirical — but mechanically honest — volatility-event mean-reversion strategy for index charts (ES, SPX, SPY, NQ...). It trades one hypothesis, known to Wall Street as the TACO trade ("Trump Always Chickens Out"): when a policy Announcement detonates the VIX, the sell-off is usually walked back within days — a "90-day pause," a "very productive call," a clarification that the tariffs apply primarily to penguins. The dip, having been artisanally manufactured, is bought.
The jokes are in the labels. The engine underneath is a real VIX-spike fade with staged exits, and every decision is lookahead-clean.
HOW IT WORKS — ENTRY (Chaos Detection)
• Covfefe Threshold — VIX trades ≥ 12% (default) above YESTERDAY'S CONFIRMED daily close. Not today's repainting value — yesterday's close is final data the moment today begins.
• Flash Tantrum — fast intraday VIX rate-of-change (default 8% over 6 bars) to catch the 2:37 PM post that ends four decades of trade policy in under 280 characters.
• Minimum VIX floor (default 18) — below this the market is not scared, it is merely golfing.
• Vol-curve confirmation (default ON) — requires VIX9D > VIX. Genuine event panic inverts the front of the volatility curve: 9-day vol pricing above 30-day is the fingerprint of a real scare. If the curve isn't inverted, even the market doesn't believe the post, and the signal is skipped. This is the filter that separates an actual tantrum from a slow-drift vol day.
When everything aligns, the strategy goes long the chart symbol at the next bar open.
HOW IT WORKS — EXITS (the TACO Protocol, staged like the walk-back itself)
• GREAT CALL — the first reassuring headline: VIX Δ falls back under 8% (default) → take half the position off.
• CONCEPTS OF A PLAN — VIX reverts to within 4% of yesterday's close: a Framework of a Concept of a Deal has been reached → close the rest.
• YOU'RE FIRED — fixed stop loss (default 1.5%). Sometimes he does not, in fact, chicken out. This is the apology budget.
• DECLARE VICTORY — fixed profit target (default 2.5%). Exit into strength and take credit for the bounce you predicted after it happened.
• NEWS CYCLE EXPIRY — time stop (default 78 bars ≈ one full RTH session on 5m). After one news cycle, a newer, more beautiful crisis replaces this one and the edge is gone.
EXTRAS
• Escalation sizing — at FULL COVFEFE (2× the spike threshold) the position gets the BIGLY multiplier. Peak fear is peak walk-back probability. This is either alpha or a margin call; many people are saying both.
• Post-trade cooldown so a single escalating tweetstorm can't chain entries.
• RTH-only entries (default ON), plus an optional "Prime Posting Hours" filter (cable-news breakfast block + post-lunch Executive Time).
• "Believe Me" mode (default OFF) — experimental fade of VIX-crush euphoria, for days when everyone believes The Deal is real this time.
• ♟️ 4D CHESS MODE — reverses every signal, for users who believe there is, in fact, a plan. Exits are direction-aware, so the joke is mechanically sound. If this mode outperforms, please tell no one.
• CHAOS-O-METER™ dashboard — live chaos grade from 🏌️ GOLFING to 🚨 FULL COVFEFE, vol-curve status, a factory-floor "DAYS SINCE LAST TANTRUM" safety sign (resets constantly, as is tradition), deal accounting (Deals made / Fake news / Deals honored: TBD), net P&L denominated in $TRUMP at a peg of your choosing, and a Sharpe ratio readout that is simply THE BEST RATIO.
• 🗽 Liberation Day (April 2) is marked annually — heightened tantrum risk, observed like a holiday, because it is one now.
NO REPAINTING / NO LOOKAHEAD
The reference VIX level is yesterday's confirmed daily close, pulled with the standard non-repainting pattern (close of the daily feed with lookahead on — final the moment today starts). Signals are evaluated on confirmed chart-timeframe bars and orders fill at the next bar open. Everything the strategy decides is knowable at decision time — which is more than can be said for the policy it trades.
HOW TO USE
• Chart: an index or index future (ES1!, SPX, SPY, NQ1!...). Intraday timeframes; defaults tuned around 5m.
• Both vol symbols are inputs — swap in VXN for NQ, or your regional vol index pair for non-US indexes.
• Strategy properties: $1,000,000 initial capital (sized for index futures notional), 2 contracts per trade by default (so the half-off scale-out has a half; at the default 1.5% stop on ES this risks roughly 1% of equity per trade), $4.50/contract commission, 1 tick slippage. margin_long/margin_short are explicitly 0 — Pine v6's default of 100 silently rejects futures entries whose notional exceeds capital; if you fork this for leveraged instruments, keep that line.
DISCLAIMER
This is satire with a working strategy attached, published for education and entertainment. The VIX spikes are, regrettably, real; the edge may not be. Backtest results on manufactured dips do not guarantee future walk-backs. Not financial advice — frankly, it barely qualifies as advice.
Strategy

Auction Regime Router Entropy Gate & Hurst MemoryAuction Regime Router — Entropy Gate & Hurst Memory
What it is
Every structure playbook fails in the wrong regime. Fading the value-area edge works when price is anti-persistent (stretches snap back); riding a breakout works when price is persistent (moves feed on themselves); and nothing structural works when the tape is noise. This tool measures two things — how much structure exists, and what kind it is — and routes to a plain-language answer: FADES VIABLE / BREAKOUTS VIABLE / STAND ASIDE. It decides which of your tools to trust, never buy or sell.
The two measurements (and how they work together)
Permutation entropy (Bandt–Pompe 2002) — the gate. It measures how disordered the recent price sequence is from the frequencies of ordinal patterns (which of the 6 orderings each price triplet takes). High entropy = all patterns equally likely = noise = no structural edge. The gate is self-calibrated: entropy is ranked against its own recent history, so "noisy" means noisy for this symbol and timeframe.
Hurst exponent (Hurst 1951; Mandelbrot) — the router. Memory via diffusion scaling: how the dispersion of K-bar returns grows with K. H > 0.5 = persistent → continuation regime; H < 0.5 = anti-persistent → reversion regime. Research supports the routing: mean reversion is empirically more probable and faster during anti-persistent periods.
The mashup logic is a hierarchy, not a mixture: the entropy gate overrides the Hurst read. If the tape is noise, the router says STAND ASIDE regardless of what H says — because a memory estimate on noise is meaningless.
The honesty steps
A dead zone around H = 0.5 (default 0.45–0.55): near a random walk the memory read is unreliable, so the router says MIXED rather than pretending. Practitioners commonly require a margin before activating a playbook; both thresholds are inputs.
A minimum-dwell filter (the standard anti-chattering design from switched-systems control): a new regime is announced only after it survives a set number of confirmed bars, so the read doesn't flip-flop bar to bar. The cost is that many bars of lag — stated, and adjustable.
Estimates are proxies from bar data with overlapping windows — descriptive of the recent past, not a prediction. The dashboard shows the state, how long it has persisted (regime age), how dominant it has been recently (stability %), and any pending regime with a countdown — nothing more.
How to use it
Add to any liquid symbol/timeframe; defaults suit intraday index futures. The script requests no external data of any kind, so it runs on every plan and every symbol.
Glance at the regime lane — the thin colored strip at the bottom of the pane: blue = continuation, violet = reversion, amber = noise, gray = mixed. The palette is deliberately direction-neutral — no green or red anywhere in regime coding, so nothing can be misread as a buy or sell.
The HTF STACK row shows the raw regime on three higher timeframes derived as multiples of the chart (defaults 3×, 5×, 15× — so a 5m chart reads 15m/25m/75m automatically, adapting to any chart). A ✓ in green = every timeframe agrees on the same actionable regime (strongest context). A ⚠ in amber = a higher timeframe reads NOISE or the opposite regime while the chart claims a playbook (weakest — reduce or wait).
Read the dashboard for detail: REVERSION → your value-area fade / band-reversion tools are in their element; CONTINUATION → your breakout / drive tools are; NOISE → the gate is closed, stand aside; MIXED → no clear routing, reduce. STABILITY shows how settled the read is; PENDING shows a forming regime with a countdown.
Regime-change tags print only on announced (dwell-confirmed) changes; alerts fire on entering each state.
Best used as the selector above your structure toolkit rather than as a standalone display.
What makes it original
Hurst and entropy oscillators exist. What this adds: (1) the hierarchy — a self-calibrated entropy gate that can veto the memory read, instead of two numbers side by side; (2) routing to auction playbooks in plain language (fade vs breakout viability), not a raw statistic; (3) honest dead zones, a minimum-dwell announcement filter, and stability/pending context instead of a binary flip at H = 0.500. It is a decision-hygiene tool for structure traders.
Concept credits
Ordinal-pattern (permutation) entropy — C. Bandt & B. Pompe (2002). Long-memory / rescaled-range analysis — H. E. Hurst (1951); fractal market framing — B. Mandelbrot. Regime-gated strategy selection — standard quantitative practice. Implementation and charting design are the author's own.
Important disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. Regime labels are descriptive statistics of recent bars; regimes change without warning and estimates are proxies. Validate independently and manage your own risk. Indicator

Composite Reversion OscillatorComposite Reversion Oscillator
A short-term mean-reversion oscillator that blends three different "how stretched is this?" reads into one 0–100 line: how overbought/oversold momentum is, how long the current up/down streak has run, and where the latest return ranks against its own recent history. Each measures a different face of over-extension; together they flag exhaustion more reliably than any one alone.
Why these parts are combined (not a mashup for show). A short momentum oscillator flags overbought/oversold but ignores persistence. A streak read (an oscillator of the consecutive up/down-close count) captures persistence it misses — three green closes isn't one. A return-rank read captures the size of the latest move relative to its own norm, which neither of the others sees. Averaging the three yields a composite that only reaches an extreme when momentum, streak and move-size all agree — far fewer false "oversold" prints.
What's different here. Rather than presenting the composite as a fixed rule, it forward-calibrates whether those agreed extremes actually revert on this symbol, with an out-of-sample split and a multiple-testing check — because mean-reversion edges are regime-dependent and decay, which is exactly where symbol-specific honesty matters most. Signals fire once per excursion (no zone-edge whipsaw).
How it works. Component 1: a short-period momentum oscillator of price. Component 2: the same oscillator applied to the signed consecutive-close streak. Component 3: the percentile rank of the latest return within a recent window. The composite is their average, mapped to a ±100 pane. A long fires on the cross up out of oversold (and locks out until the line recovers to mid); a short mirrors it. Each is labelled by a triple barrier — a profit target and equal stop in ATR units plus a time limit — split into in-sample and recent out-of-sample.
How to use. Read the Verdict (Long/Short/Watch/Wait) and the Conviction, which reads "High" only when that turn type shows a positive edge that survives the test here — otherwise it openly says so. Best used with your own trend and risk plan, not alone. Non-repainting.
Disclaimer: for research and education only. Not financial advice. Trading carries risk of loss; manage your own positions. Indicator

Dominant Cycle OscillatorDominant Cycle Oscillator
A cycle tool that measures the market's current dominant cycle length directly from the data — rather than assuming a fixed period — then reads where price sits inside that cycle (its phase) and how strong the cycle is (its power). It answers three things a fixed-length oscillator can't: how long the cycle is right now, where we are within it, and whether a tradable cycle even exists.
Why these parts are combined (not a mashup for show). Each is required by the previous one. A band-pass filter isolates the tradable cycle band from slow trend and fast noise — you can't measure a cycle cleanly without first removing what isn't cyclical. An autocorrelation periodogram turns that cleaned series into a power spectrum and reports the dominant period as the spectrum's centre of gravity. A cycle-strength read — how far the dominant peak stands above the spectral noise floor — says whether that period is real or noise, so signals are suppressed when no cycle exists. Forward calibration then measures whether the cycle turns actually pay on this symbol.
How it works. Band-pass (high-pass + low-lag smoother) → autocorrelation across lags → discrete Fourier transform → power spectrum → dominant period via its centre of gravity. The cleaned cycle is normalized into a ±100 phase wave. A long fires when the phase turns up from a trough with a real cycle present, a short when it turns down from a peak; each side fires at most once per swing. Every signal is labelled by a triple barrier — a profit target and equal stop in ATR units plus a time limit — split into in-sample and recent out-of-sample, with a confidence interval and a multiple-testing check.
How to use. Read the Verdict (Long/Short, Weak cycle, or Wait) and the Conviction, which reads "High" only when that turn type shows a positive edge that survives the test on this symbol — otherwise it openly says "context only" or "no proven edge here." The dashboard shows the measured cycle length and its strength. Best used with your own trend and risk plan, not alone.
Honesty & limitations. The dominant-cycle estimate is approximate and lags at regime shifts. Edge figures are computed on this chart's own history with overlapping windows and no costs — context, not a guaranteed backtest; past behaviour doesn't predict the future. Non-repainting. The periodogram is computationally heavy on deep history / very low timeframes.
Disclaimer: for research and education only. Not financial advice. Trading carries risk of loss; manage your own positions. Indicator

Sharp Reversal OscillatorSharp Reversal Oscillator
A reversal-timing oscillator that re-shapes price into a near-Gaussian form so turning points snap into sharp, clear extremes instead of rounded, ambiguous ones — then scores its own turns forward on your chart, in plain language, so you can see at a glance whether to act or wait.
Why these parts are combined (not a mashup for show). Three steps are stacked, each fixing the previous one's flaw. Raw price excursions are fat-tailed, so it's unclear where an extreme really is; a distribution-normalizing transform stretches values near the edges, turning a compressed extreme into a clear spike. But that transform is easily biased by trend — in a strong move it pins to one side — so the input is first band-pass cleaned (slow trend and fastest noise removed), leaving the tradable swing it should sharpen. The normalization window is then set from the market's measured dominant cycle rather than a fixed guess, so it stays tuned as cycles stretch and compress. The three only work as one tool.
How it works. Band-pass clean → locate price within its recent range, scaled to (−1, 1) → distribution-normalizing transform, smoothed → signal when the line crosses its one-bar trigger from an extreme. The window optionally follows a dominant cycle measured by autocorrelation of the band-passed price. Each signal is then labelled by a triple barrier — a profit target and an equal stop in ATR units, plus a time limit — so a "win" means the target was hit before the stop. Results split into in-sample and recent out-of-sample, with a confidence interval and a multiple-testing check.
How to use. Read the Verdict row (Long/Short signal, Watch, or Wait). Check Conviction — it reads "High" only when that signal type shows a positive edge that survives the statistical test on this symbol; otherwise treat it as context. Green wave above zero is up-pressure, red below is down; shaded bands are extremes; the faint line is the trigger. Best used with your own trend and risk plan, not alone.
What's original. The band-pass-cleaned input, the self-tuning window, the forward triple-barrier calibration with an out-of-sample split, and a conviction read that openly admits when there's no proven edge — instead of presenting every signal as equally reliable.
Inputs. Price source (change it for any market), reading mode (Simple/Pro), engine and self-tuning controls, extreme level, full calibration settings, and an auto-adapting dashboard legible on dark or light charts. Defaults are tuned for NSE:NIFTY1! intraday.
Honesty & limitations. Edge figures are computed on this chart's own history with overlapping windows and no costs — context, not a guaranteed backtest; past behaviour doesn't predict the future, and the cycle estimate lags at regime shifts.
Disclaimer: for research and education only. Not financial advice. Trading carries risk of loss; manage your own positions. Indicator

Adaptive Trend Cycle OscillatorAdaptive Trend Cycle Oscillator
A bounded cycle-timing oscillator that does two things most cycle tools don't: it tunes its own period to the market's measured rhythm, and it scores its own signals forward on your chart in plain language — so you can see at a glance whether to act or wait.
What it is. A 0-100-style cycle line (shown −100…+100) that highlights up-phases and down-phases and marks turns out of oversold/overbought. A dashboard translates the current state into a one-word verdict and an honest conviction read.
Why these parts are combined (not a mashup for show). Three classical ideas are fused because each fixes the previous one's flaw. A trend-difference line (fast average minus slow average) captures direction but is unbounded and late at turns. Running it through a double stochastic normalization bounds it and sharpens the cyclical phase, so reversals show sooner with less whipsaw. The remaining weakness is the fixed normalization length — real cycles stretch and compress — so the length is set from a measured dominant cycle (autocorrelation of a band-passed price), making the oscillator self-tuning. The three only work as one tool; separately each is incomplete.
How it works. (1) Dominant cycle: band-pass filter → autocorrelation across lags → Fourier transform → power spectrum → dominant period via its centre of gravity. (2) Oscillator: trend-difference → stochastic over the measured period → smooth → stochastic → smooth. (3) Calibration: each signal is labelled by a triple barrier — a profit target and an equal stop in ATR units, plus a time limit — so a "win" means the target was reached before the stop. Results split into in-sample and recent out-of-sample, with a confidence interval and a multiple-testing check.
How to use. Read the Verdict row first (Long/Short signal, Watch, or Wait). Check Conviction — it only reads "High" when that signal type shows a positive edge that survives the statistical test on this symbol; otherwise treat the signal as context. Green wave above the mid line is an up-phase, red below is a down-phase; shaded bands are extremes. Best used alongside your own trend and risk plan, not alone.
What's original. The self-tuning period, the forward triple-barrier calibration with an out-of-sample split, and a conviction read that openly admits when there's no proven edge — rather than presenting every signal as equally reliable.
Inputs. Price source (change it to use any market), reading mode (Simple/Pro), cycle and self-tuning controls, signal zones, full calibration settings, and an auto-adapting dashboard that stays legible on dark or light charts. Defaults are tuned for NSE:NIFTY1! intraday.
Honesty & limitations. Edge figures are computed on this chart's own history with overlapping windows and no costs — context, not a guaranteed backtest; past behaviour doesn't predict the future, and the cycle estimate lags at regime shifts.
Disclaimer: for research and education only. Not financial advice. Trading carries risk of loss; manage your own positions. Indicator

VWAP Deviation Divergence OscillatorVWAP Deviation Divergence Oscillator
## Overview
The VWAP Deviation Divergence Oscillator turns the **deviation of price from its session-anchored Volume-Weighted Average Price (VWAP)** into a standardized, bounded oscillator, and then looks for **divergence between price and that deviation**. The idea it tests: when price makes a new extreme but sits less far from VWAP than before, the volume-weighted average is no longer confirming the move.
It is a single-pane oscillator. It requires real traded volume (use a futures contract; cash indices report none, in which case the dashboard shows "no volume"). Every data input is user-configurable, so it runs on any symbol that reports volume, in any market and on any timeframe. Defaults target NSE NIFTY index futures on intraday charts.
## What it plots
- A z-scored **VWAP deviation oscillator** (stretched above VWAP = up, stretched below = down), with a glow line and sigma-based overbought/oversold levels.
- **Extreme-zone bands** (default +/-3 sigma) with a gradient fill that deepens toward the edge.
- **Divergence lines and labels** on the oscillator - regular (reversal) and hidden (continuation), in two colors.
- **In-band reversal dots** where the oscillator turns inside an extreme zone.
- Optional **price-pane marks** at the confirmation bar (all generated by this one indicator).
- A **background-adaptive status dashboard** (oscillator value in sigma, zone, last divergence, last reversal, live distance to VWAP).
## Why these components are combined (mashup rationale)
This script combines a **derived measure**, a **normalization stage**, a **divergence engine** and a **reversal read**, because each answers a question the others cannot and none is useful here alone:
1. **VWAP deviation (price + volume).** VWAP is the volume-weighted "fair value" the session has actually transacted at - it blends price and traded volume, which a price-only oscillator does not. How far price sits from VWAP, in standardized terms, is a mean-reversion read: the deviation = price - session VWAP.
2. **Standardization (rolling z-score).** VWAP deviation differs in scale across instruments. The z-score expresses it in standard-deviation units, so "overbought/oversold" and the extreme bands mean the same thing on NIFTY, on a commodity future, or on a crypto instrument. Without this step the divergence thresholds would not transfer between symbols.
3. **Divergence engine.** The original payload is reading **price-versus-VWAP deviation disagreement at confirmed pivots**. The engine pairs each new price pivot with the oscillator value, then requires: a genuine new price extreme; the measure failing to confirm it; a minimum oscillator gap scaled to the oscillator own stdev; the two pivots within a maximum bar distance; and optionally an overbought/oversold reading at the pivot. These gates make the combination produce signal rather than noise.
4. **Reversal read.** Independently, the engine flags oscillator turns that occur inside the extreme bands - a complementary exhaustion cue.
Together the components form one pipeline: **build the signal -> make it comparable (z-score) -> surface where price and that signal disagree (divergence) and where it exhausts (reversal).** Each is incomplete alone.
## How it works (method)
deviation = price - session-anchored VWAP (which resets each session and requires real volume); this is standardized with a rolling z-score to the oscillator.
Regular and hidden divergence are detected from confirmed pivothigh/pivotlow pivots and filtered by the gates above; reversals are oscillator pivots that print inside the extreme bands. Pivots confirm a few bars after they occur, so a printed signal does not repaint. The confirmation lag equals the pivot length.
## How to use it
1. Add the indicator on a volume-bearing instrument (a futures contract); on a cash index it will read "no volume".
2. Read divergence as **context, not a trigger**: a bearish divergence (price higher high, deviation lower high) says price is less extended above VWAP than at the prior high; a bullish divergence says the opposite at lows. Confirm with your own structure, levels and risk process.
3. Tune the **pivot length**, **max gap** and **min oscillator gap** to your timeframe; raise them for fewer, cleaner signals.
## Originality
This is an original implementation - not a VWAP deviation line and not a generic divergence script, but the specific combination of VWAP deviation, sigma-standardization that makes the read portable across markets, a multi-gate divergence engine (magnitude + distance + extreme-zone), hidden-divergence and in-band reversal detection, and a background-adaptive dashboard. The code is written from scratch; helper functions use only their arguments and built-ins.
## Credits
The **Volume-Weighted Average Price (VWAP)** and **price/oscillator divergence** are standard, publicly documented techniques. This script is not affiliated with, nor endorsed by, any third party.
## Notes / limitations
- VWAP deviation needs real volume and is session-relative; it resets each session and is undefined without a volume feed.
- Divergence is descriptive context, never a guarantee of reversal.
- Confirmation lags each pivot by the pivot length.
## Disclaimer
Research and educational tool only. NOT financial advice and no guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script.
Indicator

Anchored VWAP Reversion ChannelAnchored VWAP Reversion Channel — Regime-Gated Fade Framework
## What this script does
This is an **analytical study** that frames mean-reversion ("fade") setups around an **anchored, volume-weighted regression channel**, then **gates** those setups by a statistical market-state test and **scores** them against their own forward outcomes. It does not place orders and it is not a signal service — its purpose is to let you see, on your own instrument and timeframe, whether fading a stretched move actually has an edge, instead of assuming it does.
It plots one channel (a centre line plus inner/outer residual-σ bands), marks fade setups at the outer band, draws supporting context (volume-profile POC / value area, untested prior-session POCs, momentum divergences, liquidity sweeps, and multi-timeframe trend lines), and reports a compact validation panel.
## Why these components are combined (mashup rationale)
Fading an extreme is really three separate questions, and no single classic indicator answers all three. Stacking look-alike indicators just echoes one input, so this tool deliberately combines **three non-redundant lenses and makes them check each other**:
1. **WHERE is price stretched?** — A **volume-weighted polynomial regression** anchored at the most recent swing pivot, with **residual-σ bands**. Because the curve tilts with the active leg, an outer-band tag stays meaningful even inside a trend, where a flat cumulative VWAP would not. A **volume profile** anchored to the *same* window supplies POC and value area, and prior-session POCs that have never since been traded through become **reversion targets**.
2. **Is a reversion actually firing here?** — Three orthogonal **tells** evaluated only at the band: a **close-back rejection**, a **band-confluent momentum divergence**, and an **equal-high/low liquidity sweep** (stop-run). Crucially, all three are derived from the same stretch, so their agreement is shrunk by a **design-effect correction** (effective-sample-size): three correlated echoes are not allowed to masquerade as three independent confirmations.
3. **Is the market in a reverting state at all?** — A **regime gate** combining a **variance-ratio test** and a **reversion-trust correlation** only lets a fade through when recent increments are offsetting (mean-reverting) rather than compounding (trending).
The pieces are not bolted together side by side: they share **one geometry** (the anchored channel) and **one volatility unit** (residual σ / ATR), and each can veto the others. A band tag with no tell does nothing; a tell with no reverting regime does nothing. The design goal is to **suppress** low-quality fades — into a trend, mid-range, or backed by a single echoed tell — more than to generate them.
## The honesty layer (what makes this more than a drawing)
Every fade that fires is logged and, a fixed horizon later, **resolved**: its forward return is measured in ATR units and tabulated **with the regime gate ON versus OFF**, reporting follow-through %, whipsaw %, a Wilson 95% confidence interval, and the **mean return per fade**. A per-fade series also exports to the Data Window so you can study the full return distribution offline. The gate has to **beat its own ungated baseline** to justify itself — the framework is built to be tested, not trusted blindly.
## How to use it
1. Set the **Price source** (group 01). It works on any symbol and any market; volume-based parts need a real volume feed.
2. A fade **arms** when price tags the outer band **and** at least one tell prints, then **passes** only if the regime gate reports a reverting state. Solid triangles are gated fades; the target is the centre line or the nearest untested POC.
3. Read the panel top-down: does **Gate ON** beat **Gate OFF** on both follow-through and mean R, with non-overlapping intervals and a reasonable sample size? If not, the edge is not present on this symbol/timeframe — change them rather than forcing the trade.
4. The signal lives on **higher intraday timeframes**; one-minute data is mostly noise.
## Defaults
Shipped tuned for **NSE:NIFTY** index futures on intraday timeframes (sources, pivot lengths, value-area %, and the Tuesday-style weekly session context reflect that instrument). Every value is exposed as an input — change the **Price source** and the relevant lengths to run the framework on any other instrument or market.
## What is original
The original work is the **coordination**, not any single formula: an anchored polynomial-regression channel used as a reversion frame, three decorrelated band tells fused by a design-effect shrink, a statistical regime gate, and a built-in A/B + forward-return validation harness — combined so each lens can veto the others and the whole thing reports its own hit rate. It is not a re-skin of one indicator.
## Concept credits (techniques are standard; this implementation is original)
Anchored VWAP (standard); volume-weighted least-squares / polynomial regression (standard); residual-σ channel (standard); Volume Profile, Value Area and POC — Market Profile, Steidlmayer / CBOT; Variance-Ratio test — Lo & MacKinlay (1988); design effect / effective sample size — Kish (1965); proportion confidence interval — Wilson (1927); ATR trailing stop / Supertrend (classic, used for the multi-timeframe context lines); RSI — Wilder; Stochastic — Lane.
## Disclaimer
For research and education only. This is an analytical study, **not** financial advice, **not** a recommendation, and **not** a guarantee of future results. All statistics shown are **in-sample** on loaded history, close-to-close, without costs or slippage — a study aid, not a backtest. Mean reversion fails in trends and through regime breaks. Do your own research and manage your own risk.
Indicator

Elaris Mean Reversion ProElaris Mean Reversion Pro
Elaris Mean Reversion Pro is a multi-factor mean reversion indicator designed to help traders identify situations where price has moved significantly away from its statistical mean and may be entering a potential reversion phase.
The indicator combines adaptive deviation bands, volatility measurements, momentum filters, market regime analysis, and optional higher-timeframe confirmation to provide a structured framework for analyzing stretched market conditions.
Unlike simple overbought and oversold tools, Elaris Mean Reversion Pro allows users to customize how extremes are measured through Z-Score, ATR-based, or hybrid deviation models while incorporating optional confirmation layers such as RSI, MFI, volume, ADX, and higher-timeframe trend filters.
Key Features
• Multiple mean calculation methods including EMA, SMA, RMA, WMA, VWMA, and HMA.
• Three deviation models:
* Z-Score Bands
* ATR Bands
* Hybrid Bands
• Mean reversion signal engine with multiple confirmation styles:
* Extreme Touch
* Mean Reclaim
* Candle Rejection
• Optional RSI and MFI extreme-condition filters.
• ADX-based market regime filter to help identify environments where mean reversion conditions may be more relevant.
• Optional volume and volatility filters.
• Higher-timeframe confirmation framework.
• Signal quality scoring system.
• Dynamic mean, deviation bands, and reversion zones.
• Built-in dashboard displaying:
* Market state
* Z-Score
* Distance from mean
* Momentum readings
* Regime status
* Higher-timeframe bias
• Alert conditions for:
* Long mean reversion signals
* Short mean reversion signals
* Upper extreme zones
* Lower extreme zones
How It Works
The indicator calculates a central mean and measures how far price has deviated from that mean using statistical or volatility-based methods.
When price reaches an extreme deviation zone, the indicator evaluates additional confirmation factors such as candle behavior, momentum conditions, volatility, volume, and trend regime before generating a signal.
Signals are intended to highlight potential mean reversion conditions and should be evaluated alongside the trader's own market analysis and risk management process.
Non-Repainting
This indicator uses confirmed bar logic and higher-timeframe requests with lookahead disabled. Signals are generated using closed-bar information and do not intentionally repaint historical signals.
Notes
Mean reversion techniques may behave differently across various market conditions. Strong directional trends, high-impact news events, and volatility expansions can influence market behavior and should always be considered when interpreting indicator outputs.
This tool is designed for market analysis and educational purposes only and does not constitute financial advice.
Indicator

XRS Pro Anchored VWAP + Dev Bands + EMA/SMA - MTF FixedXRS Pro Anchored VWAP + Dev Bands + EMA/SMA is a multi-session VWAP and moving-average tool designed for intraday futures and auction-market analysis.
This indicator plots multiple anchored VWAPs with optional standard deviation bands, giving traders a clean way to track session value, mean reversion zones, and higher-timeframe VWAP structure.
Included VWAP anchors:
• 9:30 AM New York session VWAP
• 6:00 PM Globex session VWAP
• Weekly VWAP
• Monthly VWAP
The VWAP engine uses a selectable lower-timeframe calculation source, defaulted to 1 minute, to help keep VWAP behavior consistent across chart timeframes.
Key features include:
• Auto session VWAP switching
• 9:30 anchored VWAP with ±1 and ±2 standard deviation bands
• 6:00 PM Globex anchored VWAP with ±1 and ±2 standard deviation bands
• Weekly and monthly VWAP options
• Optional EMA/SMA overlays, including EMA 9, EMA 21, EMA 30, EMA 50, EMA 200, SMA 50, and SMA 200
• Custom VWAP colors, band colors, widths, and fills
• Optional right-side extension for active VWAP and bands
• Price-scale labels hidden by default for a cleaner chart
• Alerts for VWAP touches and outer 2σ band touches
This tool is useful for traders who use VWAP, deviation bands, auction-market theory, session value, mean reversion, and trend context. It can help identify areas where price may be extended, balanced, reverting to value, or reacting around important anchored VWAP levels.
This indicator does not provide automatic buy or sell signals. It is intended as a discretionary analysis tool for market context, trade filtering, and confluence.
Disclaimer: This script is for educational and informational purposes only and does not constitute financial advice. Trading involves risk. Use at your own discretion.
Indicator

Machine Learning: Volume-Weighted Mean Reversion [Dots3Red]█ MACHINE LEARNING: VOLUME-WEIGHTED MEARN REVERSION KERNEL REGRESSION
Nadaraya-Watson kernel regression is a non-parametric machine learning method. Unlike moving averages which apply fixed, predefined weights to historical bars, kernel regression derives each bar's weight from a mathematical function — the kernel — that measures how relevant that bar is to the current estimate. No hardcoded coefficients. No assumed shape. The model adapts purely from the data.
This script introduces a fundamental extension to the standard method: volume as a second weighting dimension . The result is a regression curve that gravitates toward price levels where real market participation occurred — not toward price levels where a clock happened to tick.
█ WHY KERNEL REGRESSION IS MACHINE LEARNING
The term machine learning describes algorithms that derive structure from data rather than from manually specified rules. Kernel regression satisfies this definition formally. The estimator computes:
ŷ = Σ [ w(i) × close ] / Σ
where each weight w(i) is determined by a kernel function — not by the programmer. The model decides, from the data, how much each historical bar should influence the current estimate. This is the same mathematical family as K-Nearest Neighbors, which weights neighbors by proximity. It is cited as a foundational non-parametric ML method in Bishop (2006) and Hastie et al. (2009), and is described as an attention mechanism in deep learning literature — the same concept behind transformer models. The claim is accurate, not cosmetic.
█ THE CORE INNOVATION — VOLUME WEIGHTING
Every existing Nadaraya-Watson implementation on TradingView uses a pure time kernel:
• Standard NW: w(i) = K(i/h)
This means a bar with 10,000 shares traded and a bar with 10,000,000 shares traded receive identical weight if they are the same number of bars away. A thin overnight drift and a high-volume institutional session influence the regression equally. That is statistically incorrect — volume is a direct measure of how much informational content a price bar carries.
This script uses a volume-weighted kernel:
• This script: w(i) = vol_norm(i) × K(i/h)
where vol_norm(i) is the bar's volume normalized against the peak volume in the lookback window, raised to a configurable power exponent. The regression estimate is therefore:
ŷ = Σ [ vol_norm(i) × K(i/h) × close ] / Σ
High-volume bars anchor the curve. Low-volume bars — thin sessions, overnight drift, holiday trading — contribute minimally. The regression finds where the market actually agreed on price, not just where the clock recorded a tick.
█ THREE KERNEL FUNCTIONS
All three apply the same volume weighting. The choice controls how rapidly influence decays with time distance:
• Rational Quadratic (default) — heavier tail than Gaussian. Bars from 40–60 periods ago still contribute meaningfully if they had high volume. Best for daily and weekly charts where old high-volume levels remain structurally relevant.
• Gaussian — standard bell curve decay. Weight drops sharply with distance. Best for intraday charts where recency matters more than historical anchors.
• Epanechnikov — hard cutoff at the bandwidth boundary. Anything beyond h periods receives zero weight. Produces the most locally sensitive regression. Best for fast charts requiring tight responsiveness.
█ SIGNAL LOGIC
The envelope bands are placed at a configurable multiple of ATR, standard deviation, or a fixed percentage above and below the regression line. Three band width methods are available to match different volatility contexts.
Two signal modes are available:
• Reversion mode (default) — a signal fires when price crosses back through the band after an extension. The ▲ label appears on the bar where price returns inside the lower band. The ▼ label appears on the bar where price returns inside the upper band. This confirms reversion has begun rather than anticipating it.
• Extension mode — enable Signal on extension close to fire a signal the moment price closes outside a band. This is an early warning — useful for alerts before the reversion bar arrives.
Additional signal filters: minimum bars between signals to prevent repeat firing, optional slope direction gate so signals only fire when the regression slope agrees with the signal direction.
█ WHAT YOU SEE ON THE CHART
Regression line
The volume-weighted fair value curve. Cyan when slope is rising, magenta when falling. This is where the model estimates price should be given the recent history of high-participation price levels.
Envelope bands
Upper and lower boundaries built from ATR, standard deviation, or a fixed percentage. The upper band is tinted red — resistance zone. The lower band is tinted green — support zone.
Bar coloring — 4 states
• Bright red — price closed above the upper band. Extended, statistically stretched above fair value.
• Bright green — price closed below the lower band. Extended, statistically stretched below fair value.
• Dim silver — price inside bands, regression rising or falling, i.e normal bullish or bearish context.
The contrast between fully saturated outside-band bars and dimmed inside-band bars makes overextension immediately visible without reading the scale.
Signal labels
▲ REVERT or ▼ REVERT with VW=XX% showing the volume weight of the signal bar. A signal at VW=85% fired on a high-participation bar. A signal at VW=9% fired on a thin bar — lower confidence.
Signal bar highlighting
Two additional layers available: a background flash on the signal bar and a thick vertical line through the bar's full range. Both are independently toggleable. The vertical line uses width=4 — the maximum Pine Script allows — making the signal bar visually distinct even when zoomed out.
Dashboard
Displays: current regression value, slope direction, band width, Bar Vol Weight meter (▰▰▰▱▱▱) showing how much influence the current bar has on the regression, active kernel type, volume weighting status, percentage distance from the regression midline, and non-repainting mode status.
█ NON-REPAINTING
When Non-Repainting Mode is enabled (default), all calculations use a bar offset. The current bar's close does not enter its own regression estimate. Historical signals visible on closed bars will not change as new bars form. Disable this to see a predictive (repainting) version where the current bar participates in its own estimate — useful for visual exploration but not recommended for backtesting or alerts.
█ HOW TO USE
Core use case — mean reversion
This is a mean reversion tool. It works best when price is oscillating rather than trending directionally. The recommended workflow:
1 — Confirm a ranging regime with a separate regime classifier before acting on signals.
2 — Wait for price to reach or pierce the upper or lower band (bars turn bright red or green).
3 — Check the VW% in the signal label. Higher volume weight on the signal bar = higher confidence.
4 — Enter on the reversion signal (▲ or ▼ label). Stop beyond the wick of the signal bar.
5 — Target the regression midline as the primary exit. The % from mid dashboard row tracks progress in real time.
Timeframe guidance
The volume-weighting advantage increases with timeframe because higher timeframes produce more meaningful volume data per bar. H4 and Daily are the strongest timeframes for this tool. For intraday use, reduce the Volume Weight Power to 0.3–0.5 to soften the impact of individual volume spikes.
Quick-start settings by asset class
• Stocks daily: Window=100, Bandwidth=8, Vol Power=1.0, ATR×2.0
• Crypto daily: Window=80, Bandwidth=6, Vol Power=0.7, ATR×1.8
• Forex H4: Window=100, Bandwidth=10, Vol Power=1.0, ATR×1.5
• Indices H1: Window=120, Bandwidth=12, Vol Power=0.8, Stdev×2.0
█ SETTINGS REFERENCE
Kernel Settings
• Lookback Window — number of historical bars in the regression. Larger = smoother, more lag.
• Bandwidth (h) — controls how fast kernel weight decays with time. Higher = older bars still contribute.
• Kernel Type — Gaussian / Rational Quadratic / Epanechnikov. See kernel section above.
• RQ Alpha (α) — Rational Quadratic only. Lower = smoother mixture of length scales.
• Non-Repainting Mode — uses offset. Recommended ON for backtesting.
Volume Weighting
• Enable Volume Weighting — toggle the core innovation on or off. OFF = standard NW.
• Volume Normalization Window — peak volume reference window. Match or exceed the lookback window.
• Volume Weight Power — exponent on the volume weight. 1.0 = linear. 2.0 = quadratic. 0.5 = softer.
• Volume Weight Floor — minimum weight for any bar. Prevents zero-volume bars from being ignored entirely.
Envelope Bands
• Band Width Method — ATR (volatility-adaptive), Stdev (statistical), or Percent (fixed).
• ATR Length — period for ATR calculation.
• ATR / Stdev Mult — multiplier applied to ATR or standard deviation.
• Percent Offset % — used when Percent method is selected.
Signals
• Signal on band crossover — enable signals on band cross events.
• Signal on extension close — fire signal when price closes outside a band (early warning mode).
• Require slope change — only signal when regression slope direction agrees.
• Min bars between signals — gap guard to prevent repeat signals.
Visuals
• Dashboard — regression stats and live metrics table.
• Signal labels — ▲/▼ REVERT labels with volume weight percentage.
• Band fill — fill between upper and lower bands.
• Background flash — bright background color on signal bars.
• Vertical line on signal bar — thick line through full bar height at signal.
• Large dot marker — additional plotchar layer on signal bars.
• Dashboard position — Top Right / Top Left / Bottom Right / Bottom Left.
█ ALERTS
Seven alert conditions are available:
• Long signal — reversion through lower band
• Short signal — reversion through upper band
• Any signal — either direction
• Extended below lower band — early warning before reversion fires
• Extended above upper band — early warning before reversion fires
• Regression slope turned bullish
• Regression slope turned bearish
█ DISCLAIMER
This indicator is a decision-support tool. It does not constitute financial advice and does not guarantee future results. Past statistical patterns do not predict future price behavior. Always use proper risk management.
Method: Nadaraya-Watson Kernel Regression (Non-Parametric ML)
Innovation: Volume × Time Kernel Weighting
Kernels: Gaussian · Rational Quadratic · Epanechnikov
Signals: Mean Reversion (band crossover or extension)
Repainting: Configurable — non-repainting mode available Indicator

Anchored VWAP ChannelAnchored VWAP Channel — Regime, Confluence & Reversals
What it is
This is a single overlay that builds a complete read of price around one Anchored VWAP. Instead of just drawing a VWAP line, it wraps the VWAP in a volatility channel and then layers the context a discretionary trader normally checks by eye — where price sits versus fair value, whether the move is trending or stretched, where high-volume and Fibonacci levels line up, and where the edges are getting rejected. Everything is derived from the same anchor and measured in the same volatility unit (one standard deviation, σ), so the pieces describe one structure rather than competing with each other.
It runs on any asset class and any timeframe. On instruments that carry real volume (stocks, futures, crypto, etc.) the VWAP, the channel, and the volume profile are fully volume-weighted; on feeds without real volume it falls back gracefully and flags the change in the table (see "Notes and limitations").
Why these components are combined (and how they work together)
This is intentionally a mashup, and the parts are chosen because they answer different questions about the same reference point:
• The Anchored VWAP is the fair-value anchor — the volume-weighted average price since a chosen pivot.
• The channel turns dispersion around that anchor into a measurable unit: the bands are the AVWAP ± k·σ, where σ is the volume-weighted standard deviation of price about the VWAP. This converts "how far is price from fair value" into a number (σ-distance) every other module can reuse.
• The regime read uses that σ-distance together with the VWAP slope and the band behaviour to label continuation vs reversal — so the same channel that draws the bands also tells you whether to trust a band tag or fade it.
• The volume profile (Point of Control + Value Area) is computed over the same anchored window, so the high-volume price and the value range are measured on exactly the data the VWAP is built from — not an arbitrary separate lookback.
• The Fibonacci grid is drawn on the active swing leg and is only emphasised where a level coincides with the VWAP, a band, or the POC. The channel and profile are what make a fib level meaningful here; on their own the fib levels would be just lines.
• The reversal signals fire on outer-band rejections, and the optional confluence filter suppresses them while the regime is strongly trending (when band tags tend to continue) — i.e. one module gates another.
In short: the channel produces a σ-distance, and the regime, profile, fib confluence, reversal logic, divergence and squeeze modules all consume that single shared measurement. That shared plumbing is the reason these are bundled into one script instead of run as six separate indicators.
What it plots
• Anchored VWAP centerline with a glow halo, colored by slope direction.
• Channel bands at ±1σ and ±2σ. The fill can be a "reversion heat" gradient (denser toward the outer band, red above the VWAP, green below) or a neutral glow, or off.
• Volume profile drawn as a translucent Value Area box (VAL→VAH) with a distinct POC line — kept visually and positionally separate from the fib lines so the two are never confused.
• Fibonacci grid (active-leg retracement, plus optional swing-to-swing), with confluence levels marked by a star and a brighter tone.
• Signals: trend-shift triangles on VWAP reclaim/loss; solid reversal labels on band rejections; diamonds and connecting lines for σ-distance divergence; a marker on volatility-squeeze release.
• Status table (single panel): regime, bias, σ-distance, AVWAP, POC, Value Area, squeeze state, divergence, a reversion stop/target/RR template, a data-health row, multi-timeframe regime agreement, and a built-in legend.
• Optional forward projection cone and an optional self-calibration panel that scores how past signals resolved.
Anchor modes
Rolling (fixed bar window), Swing Low, Swing High, or Dual (auto — anchors to the more recent significant pivot). Pivot detection uses bar-count lookbacks (8/13/21/34/55/89), so the entire tool self-scales to any timeframe.
How to use it
1. Read the table first: regime + σ-distance tell you whether price is trending or stretched, and how far from fair value it is.
2. Use the bands as context — near the centerline is fair value; the ±2σ edge is where reversion risk is highest (and the heat fill shades it).
3. Treat reversal labels as fade-the-stretch signals, strongest when the regime is not trending and when a divergence diamond agrees.
4. Use trend-shift triangles (VWAP reclaim/loss) for continuation context.
5. Use fib-confluence stars and the Value Area box / POC as the levels most likely to react.
6. Check multi-timeframe agreement in the table before acting.
7. Optionally turn on the calibration panel to see, on your own symbol and timeframe, how often each signal type has historically followed through.
What makes it original
• A single shared σ framework: bands, regime, divergence, reversals and risk template all read from one volume-weighted standard-deviation measurement around one anchor, rather than bolting unrelated indicators together.
• Reversion-heat channel fill that encodes reversion risk as color density.
• Confluence-filtered reversals — band rejections gated by regime/divergence.
• Volume profile rendered as a separated zone so it never blends into the fib levels.
• A transparent self-calibration panel that scores the script's own signals against a follow-through threshold (descriptive, not a backtest).
Key settings
• Calculation Source — works on any asset/market; default hlc3, switchable to close, hl2, ohlc4, etc.
• Anchor mode and pivot/rolling length.
• Inner/outer band multipliers and fill style.
• Signal sensitivity, session-open filter, reversal-confirmation strictness.
• Table position / text size / legend, and toggles for every module.
Notes and limitations
• Signals are evaluated on closed bars; the σ-distance divergence confirms a few bars after a pivot by design, so it prints late (this is normal for pivot-based divergence and is not repainting of confirmed history).
• Last-bar drawings (profile, fib, projection cone) are redrawn on each new bar and will shift forward — that is expected.
• Asset classes / volume: runs on any market and any timeframe. On instruments that carry real volume (stocks, futures, crypto, etc.) the Anchored VWAP, the volume-weighted σ channel, and the Volume Profile (POC / Value Area) are all fully volume-weighted as intended. On feeds with no real volume (e.g. spot forex, some indices / CFDs) the script still works but degrades gracefully: the VWAP becomes a simple anchored mean, the channel uses an unweighted standard deviation, and the profile becomes a time-at-price distribution. The Data row in the table flags this state as "no-vol / DEGRADED" so you always know which mode you are in.
• The multi-timeframe dashboard uses higher-timeframe requests; you can turn it off to reduce load.
• This is an analysis/visualization tool, not a strategy — it does not place orders and is not optimized or backtested for entries/exits.
Disclaimer
This script is provided for educational and informational purposes only and is not financial, investment, or trading advice. It does not predict future prices. Markets carry risk and you can lose money. Past behaviour of any signal (including the calibration panel) does not guarantee future results. Always do your own research and consider consulting a licensed financial professional before trading. You are solely responsible for your decisions and their outcomes.
Indicator

Celestial Mean Reversion Envelopes [Pineify]Celestial Mean Reversion Envelopes
This indicator identifies mean reversion opportunities by wrapping an adaptive moving average in standard deviation envelopes and signaling when price snaps back inside after piercing a band. Rather than using a fixed-period moving average as the baseline, the central line adapts its speed based on how frequently price is setting new highest highs or lowest lows — it tracks price quickly in trending conditions and almost freezes in ranges, so the bands shift organically with market character.
Key Features
Adaptive mean that responds to trend intensity rather than time alone — sluggish during consolidation, responsive during strong moves
Standard deviation envelopes calibrated to actual recent volatility, not fixed ATR multiples
Buy and sell signals generated on band crossunders/crossovers, confirming the reversal rather than anticipating it
Translucent overbought/oversold shading between the mean and each band for quick visual context
Built-in alerts for both reversion directions
How It Works
The calculation runs in two stages: first building the adaptive mean, then constructing the envelopes around it.
Extreme tracking — On each bar, the indicator checks whether a new highest high or lowest low has formed over the lookback window. Bars where a fresh extreme appears are marked with a value of 1; all other bars get 0. The SMA of these binary values over the same window gives the fraction of recent bars that produced a new extreme.
Squaring the fraction — Raising that fraction to the power of 2 produces a nonlinear smoothing coefficient. When trends are strong and new extremes appear on most bars, the coefficient approaches 1 and the adaptive mean tracks price closely. In a choppy range where few new extremes form, the coefficient collapses near zero and the mean barely moves. This technique is inspired by TRAMA (Trend Regularity Adaptive Moving Average) by e2e4mfck.
Adaptive mean update — Each bar the mean nudges toward the source price by the amount determined by the coefficient. The result is an average that effectively switches between "responsive" and "parked" behavior depending on what the market is doing.
Standard deviation envelopes — The upper and lower bands are placed at ±(StdDev × multiplier) from the adaptive mean, where StdDev is computed over the same lookback period. This makes the band width proportional to recent volatility: wider when price has been swinging, tighter during quiet periods.
Signal generation — A buy signal fires when source crossesunder the lower band (price dipped below, then closed back above it). A sell signal fires on a crossover of the upper band. The crossunder/crossover logic requires price to actually breach and then retrace — a bar that merely touches the band without closing through it does not trigger.
How the Components Work Together
The adaptive mean solves a problem that conventional envelope indicators ignore: when a market trends hard, a static EMA or SMA falls behind, making the upper band a poor reference for "too far, too fast." Because the adaptive mean accelerates during trends, the envelopes stay anchored to current price levels rather than lagging. This means the bands are more likely to represent genuine statistical extremes rather than just momentum riding.
The standard deviation layer adds a second dimension. Instead of a fixed pip or percentage offset, the band width expands when the market is volatile and contracts when it is calm — naturally suppressing signals during low-volatility compression and allowing wider moves during active sessions before flagging exhaustion.
Together these two layers create a filter that roughly says: "price reached a statistically unusual distance from where the trend currently sits, then pulled back." That combination reduces fakeout signals compared to using static bands on a lagging baseline.
Trading Ideas and Insights
On higher timeframes (daily, 4H), buy signals at the lower band that coincide with a key support level or volume spike may offer higher-confidence entries. Look for the adaptive mean to be flattening — it suggests the trend is pausing rather than reversing.
In intraday trading, signals that appear after a sharp impulsive leg tend to perform better than signals generated inside a choppy range. The adaptive mean will often be steeply sloped after an impulse, indicating the signal is against the micro-trend — exercise more caution and use tighter risk.
When price oscillates between the bands repeatedly without triggering signals, the market is likely in a low-volatility squeeze. A breakout attempt that immediately pulls back (triggering a sell or buy signal) at the edge of that range can mark the failed breakout early.
The gradient fill zones serve as a running reference for where price stands relative to the mean. Price persistently in the upper (red) fill with a rising adaptive mean suggests a strong trend; consider fading only when price crosses back into the neutral zone.
Past performance of any signal pattern does not guarantee future results. Always combine signals with broader context — structure, volume, and higher-timeframe bias. These signals indicate potential exhaustion; they do not predict reversal magnitude.
Unique Aspects
The squaring of the trend-regularity fraction is the core differentiator. Most adaptive averages use linear coefficients; squaring creates a much sharper distinction between trending and ranging states, so the mean spends more time "frozen" during ranges and snaps to price quickly when momentum genuinely kicks in.
Signals require price to close back inside the band, not just touch it — this one-bar confirmation step reduces noise from wicks that briefly pierce a band and immediately reverse without a real close-to-close move.
Band width is purely standard-deviation based rather than ATR-derived, which means the scaling responds to the actual statistical dispersion of the source series rather than the high-low range. On instruments with many gaps this can produce meaningfully different widths than ATR bands.
How to Use
Add the indicator to any chart. It overlays directly on the price pane.
The blue line is the adaptive mean. When it is rising steeply the market is in an upward trending mode; when flat or slightly sloped, it is ranging.
The red-shaded zone above the mean is the overbought area; the green-shaded zone below is the oversold area. Price spending extended time in one zone suggests momentum, not necessarily exhaustion.
A green BUY label below a bar means price closed back above the lower band after briefly breaking it — potential reversion entry. A red SELL label above a bar means the opposite.
To set alerts, use the "Buy Alert" or "Sell Alert" conditions from the indicator's alert panel (Once Per Bar Close recommended to avoid premature triggers on intrabar wicks).
Customization
Adaptive Mean Length (default: 99) — Controls both the highest/lowest lookback and the SMA averaging window for the smoothing coefficient. Higher values slow the mean considerably and widen bands; lower values increase reactivity but also produce more frequent and less reliable signals.
Envelope Multiplier (default: 2.5) — Scales the standard deviation distance. 2.0 suits instruments with tighter typical ranges; raise to 3.0+ on highly volatile assets to avoid constant band touches that don't represent genuine extremes.
Source (default: close) — Change to hl2 or hlc3 to incorporate high and low into the baseline; close is typically sufficient for most reversion setups.
Color inputs — Adjust bullish/bearish/mean colors and toggle the gradient fill on or off depending on visual preference.
Conclusion
Celestial Mean Reversion Envelopes pairs an adaptive mean that adjusts its responsiveness to trend regularity with volatility-scaled deviation bands, targeting the specific moment when a stretched move closes back inside its statistical boundary. The approach is best suited to traders who wait for confirmation — the crossunder/crossover trigger ensures you're acting on a completed reversal bar, not an open wick. As with any mean-reversion tool, it works best when context confirms the extension is exhaustion rather than breakout continuation.
Indicator

Hurst Exponent Strategy [Fast + Weekly]## Overview
The **Hurst Exponent Strategy ** is an advanced quantitative tool that calculates the Hurst Exponent ($H$) using the Rescaled Range ($R/S$) analysis. Instead of tracking directional momentum or price overlays, this indicator measures the **statistical memory** and fractal dimension of financial time series to detect market regimes.
It helps traders identify whether an asset is trending, mean-reverting, or trapped in a state of pure noise (chaos).
---
## The Mathematics of Market Regimes
The indicator evaluates the price action and plots values between 0 and 1, anchored to a theoretical center line of **0.5 (Random Walk)**:
- **$H > 0.60$ (Trend / Persistent):** The market possesses long-term memory. Price movements tend to be followed by movements in the same direction. Ideal for trend-following strategies.
- **$H < 0.45$ (Elastic / Anti-Persistent):** The market behaves like a rubber band (Mean Reversion). Price movements are consistently followed by reversals. Ideal for grid, mean-reversion, or range-bound strategies.
- **$0.45 \le H \le 0.60$ (Chaos / Random Walk):** The price action mimics a Brownian motion. Movements are random, noise is high, and directional edge is minimal.
---
## Dual Timeframe Framework
To avoid fighting macro market structures, this script calculates two separate Hurst metrics simultaneously:
1. **Fast Hurst (Cyan Line):** Calculated on the current chart timeframe. It responds quickly to micro-regime shifts, pinpointing when a consolidation is breaking into a trend or expanding into chaos.
2. **Macro Hurst (Orange Line):** Multi-timeframe execution locked exclusively to the **Weekly ("W") chart**. It acts as a structural filter, keeping you aligned with the true macro nature of the asset.
Both exponents feature an optional built-in **Smoothing filter (SMA)** to remove high-frequency mathematical noise without heavily lagging the structural reading.
---
## Real-Time Informative Legend
The top-right dashboard monitors the live mathematical output of both exponents:
- Displays exact numerical values down to 4 decimal places.
- Dynamically classifies the market state into **TREND** (Green), **ELASTICO** (Red), or **CAOS** (Gray) for instant visual confirmation.
---
Disclaimer: This tool calculates mathematical probabilities based on historical fractal dimensions. It does not provide entry/exit arrows or guarantee profits. Use it as a regime filter alongside your preferred execution strategy. Indicator

Mean Reversion Pro 📊 Mean Reversion Pro — Data-Driven Edge on Any Market, Any Timeframe
Most mean reversion indicators tell you the price is "too far" from the moving average. This one tells you exactly how far is statistically worth trading — using your own chart's historical data as proof.
Works on all instruments and timeframes: futures (NQ, ES, CL, GC…), crypto (BTC, ETH, SOL…), forex (EUR/USD, GBP/USD…), indices (SPX, DAX, NASDAQ…), stocks, commodities — anything with a price and volume.
─────────────────────────────────────────
🔍 WHAT THIS INDICATOR DOES
─────────────────────────────────────────
Mean Reversion Pro silently analyses every historical instance where price deviated from a moving average by a given distance. For each of 15 tested threshold levels it computes:
• Win rate — % of times price returned to the MA within the timeout
• Expectancy — (win-rate × avg MFE) − (loss-rate × avg MAE)
• Profit Factor — gross gain / gross loss ratio
• Avg MAE — average adverse excursion (how far against you before reverting)
• Avg MFE — average favourable excursion (how far in your favour)
• Avg return time — average bars needed to reach the MA
It then automatically selects the threshold with the highest expectancy that also satisfies your minimum win-rate and minimum occurrences filters — and only then shows a signal. No manual optimisation. No curve-fitting.
─────────────────────────────────────────
⚙️ KEY FEATURES
─────────────────────────────────────────
✅ Universal — works on futures, crypto, forex, indices, stocks, commodities
✅ 3 threshold modes: fixed Points, ATR multiples, Z-Score (adapts to any volatility regime)
✅ 5 MA types: EMA, SMA, WMA, VWMA, Hull MA
✅ Auto-optimised threshold — the indicator finds the best level by itself
✅ Real-time dashboard: win-rate, expectancy, profit factor, MAE, MFE, return time (Long & Short)
✅ Dynamic bands: 1× and 1.5× optimal threshold zones drawn on the chart
✅ Non-repainting signals — only fires on confirmed, closed bars
✅ Optional filters: trend (EMA 50), volume, US session, minimum ATR
✅ Minimum history guard — signals are held until enough bars have been analysed
✅ All parameters fully exposed and documented with tooltips
─────────────────────────────────────────
📈 WHO IS THIS FOR
─────────────────────────────────────────
• Futures traders — NQ, MNQ, ES, MES, CL, GC, SI, ZB…
• Crypto traders — BTC, ETH, SOL and all altcoins on any exchange
• Forex traders — all major, minor and exotic pairs
• Index traders — SPX, NDX, DAX, FTSE, CAC, Nikkei…
• Stock traders and swing traders looking for mean reversion pullbacks
• Prop firm traders who need a systematic, rules-based edge
• Any trader tired of arbitrary support/resistance levels with no statistical backing
─────────────────────────────────────────
🧠 HOW TO USE IT
─────────────────────────────────────────
1. Apply to any chart on any timeframe
2. Let at least 500 bars load (recommended: 1000–2000 for robust statistics)
3. Choose Threshold Mode:
— Points → best for futures and indices (fixed price distances)
— ATR → best for crypto and forex (volatility-adjusted)
— Z-Score → best for statistical/quant approaches
4. Set your minimum Win Rate (default 65%) and minimum Occurrences (default 15)
5. A signal appears only when all statistical conditions are met AND your filters pass
6. Read the dashboard to assess setup quality before entering a trade
─────────────────────────────────────────
💡 WHY EXPECTANCY MATTERS MORE THAN WIN RATE
─────────────────────────────────────────
A strategy with 80% win rate can still lose money if the average loss is 5× the average win. Mean Reversion Pro uses expectancy — the only metric that combines win rate, average gain and average loss into a single number — as its selection criterion. A signal only appears when the math is in your favour.
─────────────────────────────────────────
⚠️ DISCLAIMER
─────────────────────────────────────────
This indicator is a decision-support tool only. It does not provide financial advice and does not guarantee future results. Past statistical performance is not indicative of future performance. Always use proper risk management. Indicator

Statistical Mean-Reversion Engine [SMRE]## Statistical Mean-Reversion Engine (SMRE)
SMRE is an open-source mean-reversion indicator that combines a rigorous statistical core with up to eight optional confirmation layers, designed primarily for index-futures trading on intraday timeframes (1-minute through 1-hour).
### What it does
For every bar, SMRE fits an Ornstein-Uhlenbeck (OU) process to the recent price series via linear regression on lag-1 prices, yielding four outputs:
- **μ (the mean)** — the equilibrium price the series is reverting to
- **θ (mean-reversion speed)** — how strongly the series pulls back to μ
- **HL (half-life)** — how many bars it takes to revert halfway
- **σ_eq (stationary residual variance)** — used to z-score the current price
The current price's z-score against μ (the "OU Z") is the primary signal. When |OU Z| exceeds a configurable threshold, a mean-reversion entry is considered — but only after the script also confirms that the recent price series is genuinely stationary using three orthogonal statistical tests:
- **Hurst exponent** must be below 0.55 (i.e., the series is not persistently trending)
- **Augmented Dickey-Fuller** t-statistic must be below -2.86 (rejects unit root)
- **Variance Ratio** test at q=4 must be below 1.0 (variance grows sub-linearly with horizon)
If all four conditions pass, the L1 (statistical core) signal fires.
### Why the multi-layer structure (mashup justification)
A single OU-based mean-reversion signal works well in stationary regimes but degrades in trending or volatile conditions. SMRE addresses this by validating each potential entry through up to eight orthogonal confirmation channels, each measuring something the others do not:
- **L2 — Volatility Regime (6-state):** Classifies market state via VIX, ADX, and realized volatility. Suppresses signals during high-trend conditions (regime 6, "Spike") where mean-reversion historically fails.
- **L3 — Spot-Futures Basis (Kalman filter):** Tracks the deviation between actual and theoretical futures pricing. Statistically significant basis dislocations often resolve via mean-reversion.
- **L4 — Options Surface:** Computes ATM implied volatility from straddle pricing and a skew z-score from OTM put/call ratio. Optional; requires user to provide option symbols.
- **L5 — Microstructure:** Blends rolling VWAP and session-anchored VWAP z-scores with VPIN (a volume-clock toxicity proxy) and order-flow imbalance. Captures flow-based exhaustion.
- **L6 — Gamma Walls (GEX) OR Put-Call Ratio:** Two mutually exclusive options. GEX requires OI symbols at five strikes; PCR requires a single broker-published PCR feed. Both detect option-driven price magnets.
- **L7 — Dispersion:** Rolling correlation of index returns with its top 5 constituent stocks' returns. High dispersion (low correlation) penalizes signals; high cohesion boosts them.
- **L7b — Residual Dispersion:** Idiosyncratic residual z-scores (β-adjusted) per constituent. If 3 of 5 stocks show same-sign extreme residuals, the index is detached from constituents — strong mean-reversion candidate.
- **L9 — Cross-Asset Stress:** Sigma-normalized stress across USD/INR, DXY, and crude oil. Penalizes signals during cross-asset hedging cascades.
Each layer outputs a {direction, strength} pair. The Layer 8 fusion engine combines these via a weighted composite score (default weights: L1=0.28, L5=0.22, L3=0.18, L4=0.12, L6/L7b=0.10), then applies a regime multiplier (L2 × L7 × VRP × cross-asset × expiry), clamped to to prevent extreme compounding.
If the absolute composite score crosses one of three thresholds (0.25 / 0.40 / 0.45 by default), a signal is fired at Scalp / Swing / Session horizon respectively. A TCA cost filter then validates that the expected move (distance to μ) exceeds estimated round-trip transaction cost; otherwise the signal is suppressed.
### Originality
The author is not aware of any other public Pine script that implements the full OU-fit chain (mean, mean-reversion speed, half-life, stationary variance) together with all three stationarity tests (Hurst, ADF, Variance Ratio) directly in Pine v6 — every step is computed natively, no external library calls. Additionally, the session-anchored VWAP with running volume-weighted sigma bands, the rolling-beta residual dispersion across multiple constituents, and the Kalman-filtered futures-basis residual are original Pine implementations. The signal telemetry module (a 200-signal FIFO ring buffer with horizon × composite-magnitude bucket attribution) is also an original diagnostic tool.
### How to use
1. **Apply to an index futures chart.** Defaults are pre-configured for NSE NIFTY1! futures, but inputs allow any index — change the VIX symbol, spot/futures symbols, constituent symbols, and currency pairs.
2. **Read the compact dashboard.** It's a single 9-row table (default position: middle-right) showing only what you need to evaluate a setup:
| Row | What it shows | What it means |
|---|---|---|
| Title | Profile + OU window in use | Confirms which calibration is active |
| OU Z-Score | Z-score with half-life (HL) | How extended price is + how long mean-reversion typically takes |
| Stat Validity | H / ADF / VR pass-fail | Whether the recent series is actually stationary (all 3 must pass) |
| Regime | Volatility state + VIX value | Whether market conditions favor mean-reversion |
| Composite | Fused score × regime multiplier | The unified signal strength |
| Confluence | Layers agreeing (out of 6) | How many orthogonal signals support the direction |
| TCA Edge | Expected move in bps + PASS/FAIL | Whether the trade clears transaction costs |
| E / SL / TP | Entry, Stop, Target + Risk:Reward | The trade levels if a signal fires |
| **DECISION** | Direction · Horizon · Side | The actionable output (green=long, red=short, gray=neutral) |
3. **Trade levels and markers.** When a signal fires, entry/stop/target lines auto-plot on the chart. Stop is ATR-based (default 1.2× ATR); target is min(OU mean μ, entry + 2× ATR). Triangle markers plot below (long) or above (short) the bar — small for Scalp, medium for Swing, large for Session.
4. **Optional diagnostic.** A separate Signal Telemetry table (disabled by default; enable via the "Show Telemetry Dashboard" input) tracks the last 200 signals' outcomes (win = price touched μ, loss = stop hit, expired = timeout) and reports hit rate by horizon × composite-magnitude bucket. This is a backward-looking diagnostic, not a backtest.
### Recommended chart and timeframe
This indicator was developed and parameter-tested primarily on NIFTY1! futures. The OU window auto-mapping (1m→32, 2m→20, 5m→12, 15m→32, 30m→20, 1h→24) was selected empirically through parameter sweeps. Users on other instruments should expect to tune the OU window manually or accept the auto-mapped default as a starting point.
The indicator works on any timeframe between 1 minute and daily, though intraday timeframes (1m through 1h) are where the multi-layer confluence adds the most value.
### Important notes
- This is an **indicator**, not a strategy — no backtest equity curve is produced. The telemetry table is a descriptive measure of recent signal outcomes only.
- Many layers are **optional**. If you don't have symbols for options OI, just leave those inputs blank; the script will redistribute composite weight naturally across the active layers.
- Signals can fluctuate intra-bar before bar close, especially in real-time mode. For consistent behavior, evaluate signals on closed bars only.
- The default constituents (top-5 NIFTY weights) need to be changed in the L7 inputs to use this on a different index.
### Disclaimer
This indicator is published for educational and research purposes only. It is not financial advice, not an investment recommendation, and not a solicitation to trade. Past behavior of signals does not guarantee future results. Trading futures, options, and equities carries substantial risk of loss. You are solely responsible for your trading decisions. The author makes no representations about the accuracy, completeness, or suitability of this indicator for any particular purpose. Use at your own risk, and always consult a qualified financial professional before trading.
Indicator

VWAP Control Shift Map [AGPro Series]VWAP Control Shift Map
🧠 Core Idea
Has VWAP control shifted from mean reversion to directional acceptance?
📌 Overview / What it does
VWAP Control Shift Map is a VWAP control and acceptance visualization tool built to identify when price is balanced around value, accepted above control, accepted below control, or rejected back into the VWAP band.
The script builds a rolling volume-weighted control line, maps a VWAP control band, labels acceptance and rejection events, and summarizes the current VWAP state in a compact AG Pro panel.
This script does not predict future price direction, automate trades, or provide guaranteed buy/sell signals. It is a structured decision-support map for VWAP control, acceptance quality, mean-reversion risk, and shift context.
🎯 Purpose & Design Philosophy
VWAP is one of the most watched value references across intraday and swing trading contexts.
The problem is that price can cross VWAP many times without meaningful control transfer. This script was built to separate casual VWAP interaction from stronger acceptance, rejection, and reversion behavior.
The design philosophy is to make VWAP context visually readable: where control sits, which side is accepted, whether reversion risk is rising, and whether the shift has quality.
⚡ Why This Script Is Different
Most VWAP tools plot a line, add bands, and leave interpretation entirely to the user.
This script does NOT simply mark every VWAP touch as important and does NOT treat every cross as a trend signal.
Instead, it frames VWAP as a control zone: acceptance above, acceptance below, rejection back into value, and mean-reversion risk are all organized into one visual map.
⚙️ Methodology
1. VWAP Control Detection
The script calculates a rolling volume-weighted control line using price and volume over the selected control window.
2. Control Band Mapping
It builds a volatility-adjusted band around VWAP to represent the current value-control area.
3. Acceptance Evaluation
Consecutive closes outside the band are used to identify directional acceptance.
4. Rejection Evaluation
If price returns into the band after a shift, the script marks VWAP rejection behavior.
5. Visual Output
The chart displays the VWAP control line, bordered control zone, centered band label, event labels, right-side state tags, and AG Pro panel.
🗺️ How to Read the Chart
The VWAP control line represents the rolling volume-weighted value reference.
The control band represents the active VWAP acceptance area.
Labels mark acceptance, rejection, and mean-reversion events.
Right-side tags show the current control state and shift quality.
The panel summarizes VWAP control, acceptance state, control side, reversion risk, shift quality, control band, and next context.
🚦 Signals & States
• VWAP BALANCE → price has not established a clear accepted side
• ACCEPT ABOVE → price has accepted above the VWAP control band
• ACCEPT BELOW → price has accepted below the VWAP control band
• VWAP REJECTION → a control shift returned back into the band
• REVERSION RISK → price is back inside the band after a directional control state
🔔 Alerts Logic
VWAP Control Shift Up alert triggers when price accepts above the VWAP control band.
VWAP Control Shift Down alert triggers when price accepts below the VWAP control band.
VWAP Rejection alert triggers when price returns back into the band after a control shift.
Alerts are attention markers. They are not trade instructions.
🧩 Confluence Logic
The context becomes stronger when acceptance direction, VWAP slope, distance from VWAP, and candle body pressure align.
The context becomes weaker when price quickly returns into the control band after an attempted shift.
📊 When to Use
• VWAP-based intraday analysis
• Swing charts where volume-weighted value remains relevant
• Mean-reversion versus directional acceptance decisions
• Markets with liquid volume and clean price structure
• Trend continuation or failed acceptance review
⚠️ When NOT to Use
• Very illiquid symbols
• Markets with unreliable volume
• Extremely noisy low-timeframe charts
• News shock environments where VWAP control changes abruptly
• Any context where a single indicator is being used without broader structure
🎛️ Key Inputs
• VWAP Control Length → controls the rolling volume-weighted control window
• Band Volatility Length → controls how the band width is calculated
• Control Band Multiplier → adjusts VWAP control band width
• Acceptance Bars → defines how many closes are needed for acceptance
• Rejection Window → controls failed-shift timing
• Visual settings → control the panel, zone, labels, font sizes, and projection
🖥️ Interface & Visual Design
The interface is designed for clean, premium chart reading.
The VWAP band uses visible four-edge zone boundaries so the control area remains clear in both editor and published TradingView views.
The panel uses the AG Pro merged blue header standard and keeps the current context readable without covering the main chart.
🧪 Practical Usage Workflow
1. Read the panel state.
2. Check whether price is inside, above, or below the VWAP control band.
3. Review acceptance or rejection labels.
4. Compare shift quality with reversion risk.
5. Use broader market structure before making any decision.
🔍 Interpretation Guidelines
VWAP control is not a prediction.
Acceptance shows where price has spent enough time outside the control band to suggest directional control.
Rejection shows that the attempted control shift returned back toward value.
Mean-reversion risk increases when price moves back into the VWAP control area after directional acceptance.
🚫 What This Script Is NOT
This script is not a prediction engine.
It is not financial advice.
It is not an auto-trading system.
It does not guarantee profitable trades.
It does not replace risk management or independent analysis.
⚠️ Limitations & Transparency
VWAP behavior can vary by timeframe, market session, liquidity, and volume quality.
Rolling VWAP control may differ from exchange-session VWAP or anchored VWAP tools.
Extreme volatility can temporarily reduce the usefulness of control-band interpretation.
Outputs should always be interpreted within broader market context.
🧠 Market Context Notes
VWAP often works as a value reference, but value can shift when acceptance becomes persistent.
A clean control shift is stronger when price accepts outside the band while VWAP slope supports the move.
A weak shift often returns back into the band and becomes a rejection or mean-reversion context.
🧾 Use Case Examples
When price accepts above the VWAP control band with strong shift quality, the chart may be showing directional control above value.
When price accepts below the band and VWAP turns down, the control context may favor downside acceptance.
When price quickly returns into the band after acceptance, VWAP rejection risk becomes more important.
🧱 System Philosophy
AGPro Series tools are built to convert complex market behavior into visual decision maps.
The goal is not certainty. The goal is structured context, cleaner interpretation, and better chart discipline.
🔐 Non-Promise Statement
No script can know the future.
No signal is certain.
No visual state should be treated as a guaranteed outcome.
📉 Risk Disclosure
Trading involves risk.
Markets can move unexpectedly.
Users are responsible for their own decisions, risk management, and trade execution.
This script does not provide financial advice.
📚 Educational Note
This tool is intended for educational and analytical use. It can help traders study VWAP control, acceptance shifts, rejection behavior, and mean-reversion risk.
Indicator

ATR Volatility Regime [NovaLens]Volatility regime tool built to separate two things ATR alone cannot tell you apart: where volatility currently sits in its own rolling history, and which direction the regime is rotating. Adds a velocity-gated release event on top, so the indicator flags fast coiled-spring releases on the confirmed bar - and refuses to fire on the slow leaks that only look like one.
Most volatility tools collapse one axis. A raw ATR plot tells you the bar range and nothing about whether that range is rare. A percentile-rank histogram tells you the rank but not whether vol is loading or unloading. ATR Volatility Regime separates the two by design:
Tier tracks where volatility sits in its own rolling history (Compression / Quiet / Normal / Elevated).
Phase tracks where volatility is rotating (Rising / Topping / Falling / Bottoming).
A Compression reading is not a breakout signal. It is the market saying "vol is loaded." Whether it actually releases depends on the next move. When a sustained compression actually breaks above mid-rank within a 5-bar velocity window, the indicator prints a Release diamond and pulses the pane background. Slow leaks that drift through Quiet for more than 5 bars are canceled, not reported. That single gate is what separates a real coiled-spring release from a sideways drift.
════════════════════════════════════════════
◉ HOW IT WORKS
The vol input. Wilder ATR over the chosen length, expressed as a percentage of close so the read is comparable across price levels and instruments. Mathematically guarded to stay clean across historical data gaps and unusual price series.
The percentile rank. The current ATR% is ranked against its own rolling lookback window (100 / 200 / 300 bars by Horizon). This is an asset-calibrated percentile - "P75 on BTC" means "vol higher than 75% of the last 200 BTC readings," not a market-wide cutoff. The same indicator works across SPY, BTC, EURUSD, and XAU without retuning. The raw rank drives the state engine; an EMA-smoothed copy drives the visual line so the plot reads calm without numbing event detection. Warm-up is honest: until the lookback fills, the panel shows "Warming up" and refuses to assign a tier. NA never collapses to a fake Normal.
The tier model. Four tiers cut on rawRank (P25, P50, P75) with asymmetric hysteresis: 1 confirmed bar to step up (so a vol breakout is not missed), 3 confirmed bars to step down (so a tier change only confirms when vol has actually died). The ribbon fill and oscillator line both color by tier. Extreme is a signal class, not a tier; it would flicker on and off at the P90 boundary if we colored the ribbon by it.
The phase model. Four phases (Rising / Topping / Falling / Bottoming) read off the rawRank slope. Slow rotations need 2 bars of confirmation to flip; violent moves with |delta rank| > 15 bypass the confirm and flip immediately. Peak and trough detection is plateau-aware: a strict ( greater-than on both sides) check missed the patterns where ATR percentile pins at 100 for multiple bars, so the algorithm uses greater-or-equal on the left side and greater-than on the right.
The events. Three signature events, each with its own gating:
Compression Release : velocity-gated. The Compression tier must run at least 10 bars to load the spring; on exit, rawRank must reach the mid (>= 50) within a 5-bar window. Slow leaks that drift through Quiet for more than 5 bars are canceled. Re-entering Compression also cancels the pending episode.
Extreme Touch : rawRank peaks at >= 90. Re-arm runs through a three-valve cascade (rank drop to <= 75, a higher pivot with a +2 rank headroom so a 98 peak after a 97 cannot re-fire, or 2x lookback time decay) so the same Extreme arc cannot duplicate-fire, but a genuinely higher pivot in the same arc still counts.
Cooling : armed when an Extreme fires; fires on the first confirmed bar after where rawRank falls below 75 within a 10-bar window. Disarms on fire or when the window expires. The armed-latch architecture means fast drops out of an Extreme are tracked after the Extreme event arms Cooling, instead of relying on a single fragile cross check that would miss the drop if the threshold was already crossed on the Extreme bar itself.
The Playbook Lens. Pure interpretation layer. Engine, percentile, tier, phase, and objective events are identical across lenses. The Lens recolors three visual surfaces only: the panel Playbook row text and tone, the Playbook Heatmap Strip at y = -5, and an optional Tint Price Candles by Playbook Fit overlay. Switching the Lens dropdown answers a different question against the same volatility truth: "does this regime align with the workflow I am running?" - context, never a directive.
════════════════════════════════════════════
◈ HOW TO READ IT
The pane shows the smoothed percentile rank line wrapped in a tier-colored ribbon with a Volatility Glow halo that breathes wider in the loaded zones (Compression and Extreme) and tightens in Normal. Threshold lines mark P25, P50, P75, and P90.
Deep blue (Compression): rawRank in [0, 25). Loaded spring.
Light blue (Quiet): rawRank in [25, 50). Below median, not stretched.
Gray (Normal): rawRank in [50, 75). Typical bar ranges.
Orange (Elevated): rawRank in . High vol relative to recent history.
Red (Extreme): event color, not a tier. Drives Extreme Touch markers.
Teal (Release): event color, not a tier. Drives Compression Release markers.
Markers, in order of conviction:
Compression Release (diamond on the line, Release color, with a matching pane background pulse): a >= 10 bar compression run resolved into Normal+ within 5 bars. Non-directional by design - a volatility state change, not a price direction call.
Extreme Touch (small circle anchored to the actual peak bar, Extreme color): rawRank just peaked at or above the 90th percentile of its rolling history. Reads as topping pressure of vol, not a directional reversal call.
Cooling (panel-only event, no chart marker): the first confirmed bar after an Extreme where rawRank fell back below 75 within a 10-bar window. Surfaces in the Last Event row and the Cooling alert.
The info panel synthesizes six rows: Volatility (tier + P-Score), Flow (phase), Age (bars in tier + the per-tier duration percentile so a 200-bar Quiet stretch is compared against historical Quiet stretches, not Elevated), Last Event / Context (state-based decay, no fixed timer), ATR Range (current bar range as % of price, with absolute price-unit ATR in the row tooltip), and Playbook (the Lens context read).
The Last Event row uses state-based decay , not an arbitrary 10-bar timer. A Compression Release stays visible while phase is Rising or tier is Normal+. An Extreme Touch stays visible while tier is Elevated. A Cooling read stays visible while tier is Normal or Elevated. When the event's regime context expires, the row returns to Context and summarizes the current regime instead of resizing or disappearing.
════════════════════════════════════════════
✦ HOW WE USE IT: THE COILED-SPRING ARC
This is the arc the indicator is built to catch - not the only path. Many compressions resolve sideways without a confirmed release, and the velocity gate is what filters those out.
A common pattern on a liquid index or crypto chart, Swing profile (default), Neutral lens: the line drops into Compression and parks there for 15-30 bars. The ribbon turns deep blue, the Glow widens, and the panel Age row may read something like "Mature · 22 bars" or "Extended · 22 bars" - meaning the current run has already lasted longer than most recent Compression stretches on this market. The spring is loaded.
The full arc reads in four panel updates:
Release. rawRank reaches 50+ within the 5-bar velocity window after exiting Compression. A Release diamond prints on the line, the pane background pulses teal for one bar, and the Last Event row reads "Compression Release".
Run. Within a few bars the tier transitions through Normal into Elevated, the phase row flips Rising, and the smoothed line climbs toward the upper distribution.
Touch. If the move keeps loading, rawRank peaks at 92-98 and an Extreme Touch circle prints on the peak bar - the smoothed line is now in the upper edge of its own rolling distribution. The Last Event row updates to "Extreme Touch".
Unwind. Within 10 bars rawRank falls below 75. Cooling fires and the Last Event row updates again.
The Playbook Lens reframes the same arc without changing a number. Flip to Breakout: the Heatmap Strip lights teal during the release window (favorable) and dims toward red as the move stretches into Extreme (less favorable). Flip to Mean Reversion: the strip stays red through the release (vol is the wrong direction for fading) and only lights teal when Cooling confirms and tier drifts back through Normal toward Quiet. Flip to Risk Control: Compression marks calmer bar-range context, Elevated and Extreme mark the wider-bar context. Same volatility truth, different playbook fit. The engine is identical across lenses; only the interpretation layer changes.
════════════════════════════════════════════
✦ OTHER APPLICATIONS
Breakout context : Compression Release diamonds after a loaded quiet regime, optionally combined with the Heatmap Strip reading favorable under the Breakout lens
Trend context : Rising Elevated or Rising Normal volatility as movement context for an external trend plan
Mean-reversion context : quieter or cooling regimes that may be more suitable for contained-range workflows
Volatility risk overlay : Elevated and Extreme states as wider-bar context when reviewing size, stops, or trade frequency
Vol regime classifier : use the Volatility row + Flow row in the panel as a top-down filter for any external trade plan, independent of the Lens
Alert-driven workflow : subscribe to Compression Release + Extreme Touch + Cooling and check the chart only when the volatility regime actually changes, not every bar
════════════════════════════════════════════
⚙ GETTING STARTED
ATR Volatility Regime ships with three pre-tuned Horizon profiles plus a Custom override. Pick a horizon and start reading the regime:
Intraday : ATR 14, lookback 100, smoothing 3. Faster events, lighter hysteresis (1 up / 2 down). Use on 1m through 1H charts.
Swing (default) : ATR 14, lookback 200, smoothing 5. Balanced. Start here on 1H through 1D charts.
Long-Term Hold : ATR 20, lookback 300, smoothing 5. Slower, rarer events, heavier hysteresis (2 up / 3 down). Use on 1D and above.
Custom : full manual control of ATR Period, Lookback Window, and Smoothing.
Core settings:
Horizon : selects the tuning bundle above. Start with Swing.
ATR Period (Custom) : Wilder ATR period for the volatility input, in BARS. 14 is the standard. Shorter = more reactive; longer = smoother. Applies only when Horizon = Custom.
Lookback Window (Custom) : rolling lookback the ATR% is percentile-ranked against. Larger = smoother distribution, fewer extreme reads, slower compression releases. Smaller = sharper, more events.
Smoothing (EMA) (Custom) : EMA bars applied to the percentile-rank for the visual DISPLAY layer (plot, ribbon, panel readouts). The RAW rank still drives tier, phase, and events - smoothing only calms the visual. Set to 1 to disable smoothing.
Playbook Lens:
Neutral (default) : factual regime read, heatmap stays gray. Use this to learn the engine.
Breakout : range-expansion context. Loaded Compression and Compression Release read favorable; already-stretched Elevated or Extreme states shift toward caution.
Trend : directional-movement context. Rising Elevated and Rising Normal regimes read favorable; topping or cooling volatility shifts toward caution.
Mean Reversion : contained-range context. Quiet, Cooling, and Normal/Falling regimes read favorable; Release, Elevated, and Extreme regimes shift toward caution.
Risk Control : stretched-volatility context. Compression reads calm; Elevated and Extreme states warn that bar ranges are wide.
The Lens NEVER changes the engine - same tier, same phase, same Compression Release, same Extreme Touch, same alerts. Only the panel Playbook row text, the Heatmap Strip color, and the optional candle tint move.
Display:
Show Compression Releases (hero): diamond on the line + pane background pulse on release. On by default.
Show Extreme Touches : circle on the peak bar at rawRank >= 90. On by default.
Show Price Chart Markers : mirrors Compression Release diamonds and Extreme bar tints onto the price chart. OFF by default to keep the price chart clean.
Show Raw Rank Line : faint unsmoothed percentile rank line behind the smoothed display line. OFF by default. Toggle on to debug fast vol changes.
Show Volatility Glow : halo that widens at the loaded extremes (Compression and Extreme) and tightens in Normal. On by default.
Show Info Panel : 6-row state panel. On by default.
Panel Position : Top Right (default), Top Left, Bottom Right, Bottom Left, Middle Right.
Theme : Auto (detect chart background), Dark, or Light.
Show Playbook Heatmap Strip : thick band at y = -5 that recolors with the Lens. On by default.
Tint Price Candles by Playbook Fit : paints price-chart candles with the Release / Extreme palette per the active Lens. OFF by default; disabled automatically when Lens = Neutral.
Appearance / Palette (6 color pickers):
Compression, Quiet, Normal, Elevated, Extreme, Release - each on its own line with a state-explainer tooltip. The Display Rank line, Raw Rank, Tier Ribbon fill, Volatility Glow, Heatmap Strip, panel tier text, candle tints, and event markers all reference these inputs so users can adapt the palette (color-blind, light-mode, brand themes) without forking the script.
════════════════════════════════════════════
△ LIMITATIONS
Warm-up : the lookback window must fill before any tier is assigned. On Swing (200) that is 200 bars; on Long-Term Hold (300) that is 300. Until then, the panel shows "Warming up" and the state engine refuses to fake a Normal read.
Visual smoothing lag : the visible line is intentionally calmer than the raw engine. ATR is a backward-looking Wilder-smoothed measure, and the display line is lightly EMA-smoothed on top, so fast volatility expansions can look slightly delayed in the visible plot. The rawRank engine is the sharper layer underneath and is what actually drives the tier, phase, events, and alerts. The smoothed line is the readable copy; do not read a slight visual delay as the event engine being slow.
Percentile is relative, not absolute : a "Compression" read on a chronically quiet asset can still be wider than an "Elevated" read on a chronically loud asset. The indicator compares each asset against ITS OWN history, not across markets.
Regime shifts shrink the window : a structural vol regime change (e.g. a quiet 2-year period followed by a sustained higher-vol regime) takes about one lookback window to fully recalibrate. The first few weeks after a regime shift can read noisier than the steady-state.
Compression Release is non-directional : the diamond and the pane pulse tell you the spring released, not which way price went. Combine with directional context (trend, structure, or a separate momentum tool) for direction.
Extreme Touch is a state read, not a reversal call : rawRank pinning above 90 means vol is rare for this market; it does not mean price is about to reverse. Cooling tells you the unwind has begun, not where the next leg goes.
Playbook Lens is interpretation, not validation : the Heatmap Strip recolors regime context based on the active Lens. It is not a backtested edge - it is a quick visual answer to "does my workflow want this regime?"
════════════════════════════════════════════
🔔 ALERTS
Four alert conditions are built in so you can monitor without checking every bar manually:
Compression Release : a sustained compression (>= 10 bars) confirmed above mid-rank within 5 bars. The hero event.
Extreme Touch : rawRank peaked above P90. Fires on the bar after the actual peak (peak detection requires the next bar to confirm the turn-down).
Cooling : the first confirmed bar after an Extreme where rawRank falls below 75 within 10 bars.
Compression Entry : rawRank dropped below P25 (sustained tier transition into Compression).
All four alerts fire on bar close (gated on barstate.isconfirmed). Each alert message is a pure JSON payload with ticker, price, timeframe, and timestamp fields for webhook routing.
Four alerts by design - concentrated on the signature events. Tier and phase transitions stay visible in the info panel for users who want them on the chart, but they do not fire alerts. Keeping the alert stream lean is what makes "subscribe and let the regime come to you" a useful workflow instead of a notification flood.
════════════════════════════════════════════
⌁ NOTES
Based on the classical ATR percentile-rank construction, with asymmetric hysteresis and a velocity-gated compression-release definition layered on top.
Repaint: intrabar-only. Closed-bar alerts are confirmed; current-bar visuals may update until the bar closes. All alert conditions are gated on barstate.isconfirmed. Peak-confirmed events (Extreme Touch) print on the bar AFTER the actual peak, on a one-bar offset, so the marker aligns with the true peak bar.
References: J. Welles Wilder Jr., New Concepts in Technical Trading Systems (1978), Trend Research; percentile-rank concept widely used across volatility studies.
Open-source under MPL 2.0. Free to use, fork, study.
NovaLens Indicator

Range Equilibrium Rotation Planner [AGPro Series]Range Equilibrium Rotation Planner
🧠 Core Idea
Is price rotating cleanly away from range equilibrium toward an edge, or is the midpoint still controlling the auction?
📌 Overview / What it does
Range Equilibrium Rotation Planner maps mature range structure and focuses on the midpoint equilibrium area instead of treating every range as a breakout setup.
The script displays the active range box, equilibrium band, edge rails, rotation room rail, failure rail, event labels, right-side tags, optional bar coloring, and a compact AG Pro dashboard with a 0-100 Rotation Score.
It does not predict range breaks. It helps organize range balance, midpoint control, directional rotation, edge room, failure risk, and next-action state.
🎯 Purpose & Design Philosophy
Many range tools focus on support, resistance, or breakout alerts.
This script was built for a different question: what happens inside the range before price reaches the edge?
It helps traders review whether price is still trapped around equilibrium or beginning a clean rotation from the midpoint toward the upper or lower edge.
⚡ Why This Script Is Different
Most range indicators draw a box and wait for a breakout.
This script does NOT center the workflow on range escape.
Instead, it evaluates range maturity, midpoint control, rotation quality, edge room, and failure back through equilibrium. The goal is rotation planning, not breakout prediction.
⚙️ Methodology
1. Range Maturity Detection
The script builds a rolling range using recent high and low structure, then checks whether the height and edge interactions are meaningful.
2. Equilibrium Mapping
The midpoint band is calculated around the center of the range and becomes the key control zone.
3. Rotation Evaluation
Price must move away from equilibrium with enough buffer before directional rotation is considered active.
4. Risk / Room Structure
The active edge becomes the room reference, while the opposite side of equilibrium becomes the failure area.
5. Visual Output
The chart receives a range box, equilibrium band, edge rails, room rail, failure rail, labels, right-side tags, optional bar coloring, and dashboard panel.
🗺️ How to Read the Chart
The range box marks the current high-to-low structure.
The equilibrium band shows the midpoint area where rotation control is evaluated.
The upper and lower rails mark the active range edges.
The room rail marks the edge being targeted by the active rotation.
The failure rail marks where rotation has moved back through the wrong side of equilibrium.
Labels highlight mature ranges, rotations from midpoint, equilibrium holds, edge reviews, and failed rotations.
Colors represent context:
• Teal → bullish rotation
• Pink → bearish rotation or failure
• Gold → equilibrium, room, or edge review
• Indigo → range structure or waiting context
The panel summarizes:
• Range
• Rotation Score
• Balance
• Room
• Action
🚦 Signals & States
• Range Ready → a mature range structure is available
• Bull Rotation → price rotated upward from equilibrium
• Bear Rotation → price rotated downward from equilibrium
• Midpoint Hold → price remains controlled by the equilibrium band
• Edge Review → price reached the active range edge
• Failed → rotation moved back through the failure rail
• READY → rotation quality and room are strong enough to monitor
• MONITOR → rotation is active but not fully ready
• WAIT RANGE → no mature range exists
• WAIT ROTATION → range exists but no clean rotation has started
🔔 Alerts Logic
Alerts can trigger when a mature range appears, when bullish or bearish rotation begins, when READY state appears, when midpoint hold appears, when an edge is reached, or when the rotation fails.
Alerts are attention markers only. They are not trade instructions.
🧩 Confluence Logic
The context becomes stronger when range maturity, balanced edge interaction, midpoint departure, edge room, and failure distance align.
The script avoids treating midpoint noise as a clean rotation without confirmation.
📊 When to Use
• Sideways markets with visible range structure
• Crypto, forex, indices, and liquid stocks
• 1H, 4H, and 1D market structure review
• Mean-reversion planning inside a range
• Range edge preparation without waiting for breakout-only logic
⚠️ When NOT to Use
• Strong one-directional trends with no range structure
• Thin symbols with unreliable highs and lows
• News-driven candles that distort range boundaries
• Very small ranges where spread or tick noise dominates
• Markets with unstable data or irregular sessions
🎛️ Key Inputs
• Range Lookback → controls the structure used to build the range
• Minimum / Maximum Range Height ATR → filters ranges that are too small or too wide
• Edge Touch Tolerance → controls how edge interactions are counted
• Equilibrium Band ATR → controls midpoint band width
• Rotation Break Buffer → controls how far price must move beyond equilibrium
• Minimum Ready Score → controls READY strictness
• Projection Bars → controls how far boxes, rails, and tags extend
• Visual settings → control labels, tags, panel location, theme, and font size
🖥️ Interface & Visual Design
The panel is designed to show the range state, rotation quality, balance, room, and action without overloading the chart.
The first row uses a merged AG Pro header. The chart layer keeps the range and equilibrium structure visible while leaving room for price action.
Labels are controlled with cooldown and maximum count settings to preserve a premium screenshot style.
🧪 Practical Usage Workflow
1. Read the panel.
2. Confirm a mature range exists.
3. Check whether price is still at equilibrium or rotating away.
4. Review room to the active edge.
5. Watch the failure rail if rotation loses control.
🔍 Interpretation Guidelines
A high score means range maturity, midpoint departure, and edge room are aligned.
A midpoint hold means equilibrium is still controlling the auction.
An edge review means the rotation has reached the active range edge and should be interpreted as context, not as an automatic exit.
A failed state means the active rotation moved back through its failure boundary.
🚫 What This Script Is NOT
This script is not a prediction engine.
It is not financial advice.
It is not an automated trading system.
It does not place orders.
It does not guarantee edge reach, reversal, breakout, or profitability.
⚠️ Limitations & Transparency
Range boundaries can shift as new highs or lows appear.
Different timeframes may show different range structures.
Large volatility events can temporarily distort range height and edge touch quality.
Low liquidity may create unreliable equilibrium or edge behavior.
The script is rule-based and should be interpreted within broader market context.
🧠 Market Context Notes
Equilibrium is often where the market decides whether price will rotate toward an edge or remain balanced.
The strongest rotation contexts usually appear when price leaves midpoint with room, while failure remains clearly defined.
This script is designed to make that inside-range decision point easier to read.
🧾 Use Case Examples
When price holds near midpoint and then closes above the equilibrium band, the script can begin tracking bullish rotation toward the upper range edge.
When price rotates downward from equilibrium and reaches the lower edge, the context shifts into edge review rather than fresh entry signaling.
When price moves back through the failure rail, the active rotation context fails.
🧱 System Philosophy
AGPro Series tools are built as decision-support systems.
They aim to convert market structure into readable context: what is active, what improves the plan, what invalidates it, and what should be reviewed next.
🔐 Non-Promise Statement
No script can provide certainty.
No signal guarantees outcome.
This tool provides structured context only.
📉 Risk Disclosure
Trading involves risk.
Markets can move quickly and unexpectedly.
Users are responsible for their own analysis, risk management, and decisions.
This script does not provide financial advice.
📚 Educational Note
Use this tool to study how range equilibrium, midpoint control, rotation quality, and edge room interact across different symbols and timeframes.
Indicator

Trend Exhaustion Snapback Planner [AGPro Series]Trend Exhaustion Snapback Planner
🧠 Core Idea
Is the current trend stretch becoming snapback-ready, or is momentum still supported enough to avoid calling exhaustion too early?
📌 Overview / What it does
Trend Exhaustion Snapback Planner is a rule-based trend exhaustion and mean-reversion planning tool. It measures how far price has stretched away from its trend mean, then evaluates whether that stretch is supported by pressure, efficiency loss, wick behavior, and room back toward value.
The script produces an exhaustion pocket, snapback rail, failure rail, room reference, event labels, right-side tags, optional bar coloring, and a compact AG Pro dashboard with a 0-100 Snapback Score.
It does not predict reversals. It helps organize trend stretch, exhaustion quality, snapback reclaim behavior, failure risk, and next-action state.
🎯 Purpose & Design Philosophy
Strong trends can stay stretched for longer than expected. At the same time, many reversals begin only after a trend becomes inefficient and price starts moving back toward value.
This script was built to help traders review that transition without relying on a simple overbought or oversold reading.
It supports a patient workflow: identify stretch, wait for reclaim behavior, evaluate room, then interpret the active state within broader market context.
⚡ Why This Script Is Different
Most exhaustion tools focus on RSI extremes, distance from a moving average, or isolated reversal candles.
This script does NOT treat every stretched move as a reversal.
Instead, it maps a live exhaustion pocket, scores stretch quality, tracks snapback reclaim behavior, defines where the idea fails, and shows whether there is room back toward the trend mean.
⚙️ Methodology
1. Trend Stretch Detection
The script measures price distance from a trend mean using ATR normalization.
2. Pressure Evaluation
RSI pressure, wick behavior, and trend-efficiency loss are reviewed to decide whether the extension is weakening.
3. Snapback Rail Mapping
Once a valid exhaustion pocket appears, the snapback rail becomes the first reclaim threshold.
4. Risk / Room Structure
The failure rail marks continuation risk, while the room rail shows the value or structure reference that price may test after reclaim.
5. Visual Output
The chart receives the exhaustion pocket, trend mean, snapback rail, failure rail, room rail, event labels, right-side tags, optional bar coloring, and dashboard panel.
🗺️ How to Read the Chart
The exhaustion pocket marks the stretch area created after price moves far away from its trend mean.
The snapback rail shows the reclaim level that improves the snapback context.
The failure rail marks where continuation risk invalidates the active snapback idea.
The room rail shows the next value or structure reference after the snapback begins.
Labels highlight stretch pockets, snapback reclaim, pocket pressure, room tests, and failed snapbacks.
Colors represent context:
• Teal → bullish snapback context
• Pink → bearish snapback context or failure
• Gold → room, waiting, or neutral review
• Indigo → pocket pressure or monitoring context
The panel summarizes:
• Pocket
• Snapback Score
• Stretch
• Room
• Action
🚦 Signals & States
• Bull Snapback Pocket → downside trend stretch with bullish snapback context
• Bear Snapback Pocket → upside trend stretch with bearish snapback context
• Snapback Reclaim → price reclaimed the active snapback rail
• Pocket Pressure → price is testing the exhaustion pocket without clean reclaim
• Room Test → price reached the active room reference
• Failed → price crossed the failure rail
• READY → reclaim and score quality are strong enough to monitor
• MONITOR → snapback context is active but not fully ready
• WAIT RECLAIM → pocket exists but reclaim has not confirmed
• EXPIRED → the pocket is too old to remain active
🔔 Alerts Logic
Alerts can trigger when a bullish or bearish snapback pocket appears, when price reclaims the snapback rail, when the READY state appears, when pocket pressure appears, when the room rail is reached, or when the context fails.
Alerts are attention markers only. They are not trade instructions.
🧩 Confluence Logic
The context becomes stronger when ATR stretch, RSI pressure, wick behavior, efficiency loss, snapback reclaim, and room back toward value align.
No single condition is treated as enough by itself.
📊 When to Use
• Mature directional moves
• Strong extensions away from trend mean
• Markets with visible impulse and reaction structure
• 1H, 4H, and 1D review where exhaustion context matters
• Crypto, indices, forex, and liquid stocks
⚠️ When NOT to Use
• Extremely illiquid symbols
• Very low-volume periods
• News shock candles with abnormal gaps
• Very tight ranges with no meaningful trend stretch
• Markets where spreads or wicks dominate the structure
🎛️ Key Inputs
• ATR Length → normalizes trend stretch and rail distances
• Trend Mean Length → controls the main value reference
• Minimum Stretch ATR → controls how stretched price must be before a pocket appears
• RSI Pressure → controls pressure thresholds for extended conditions
• Efficiency Length → controls how trend efficiency loss is measured
• Minimum Ready Score → controls how strict READY classification is
• Projection Bars → controls how far rails and zones extend
• Visual settings → control labels, tags, panel location, theme, and font size
🖥️ Interface & Visual Design
The panel is designed as a compact decision dashboard, not a large data table.
The first row uses a merged AG Pro header. The remaining rows show the pocket state, score, stretch context, room, and action.
The visual hierarchy is built so traders can read the active plan quickly without losing chart structure.
🧪 Practical Usage Workflow
1. Read the panel.
2. Check whether an exhaustion pocket is active.
3. Watch the snapback rail for reclaim behavior.
4. Review failure risk and room back toward value.
5. Interpret labels as context markers, not trade commands.
🔍 Interpretation Guidelines
A high score means the active stretch has multiple snapback conditions aligned.
A snapback reclaim improves the context, but it does not guarantee continuation toward the room rail.
A failed state means price crossed the continuation-risk boundary for that active pocket.
Use the script to organize the question, not to outsource the answer.
🚫 What This Script Is NOT
This script is not a prediction engine.
It is not financial advice.
It is not an automated trading system.
It does not place orders.
It does not guarantee reversal timing, target reach, or profitability.
⚠️ Limitations & Transparency
Trend exhaustion can remain extended for long periods.
Different timeframes may show different exhaustion and snapback contexts.
Volatility spikes can distort ATR-normalized distance.
Low liquidity can create false stretch pockets or unreliable wick behavior.
The script is rule-based and should be interpreted within broader market context.
🧠 Market Context Notes
Trend exhaustion is not the same as trend reversal.
The most useful snapback contexts often appear when price stretches away from value, momentum efficiency weakens, and reclaim behavior begins before the failure rail breaks.
The strongest readings usually come from alignment between structure, volatility, and reaction quality.
🧾 Use Case Examples
When price stretches far above the trend mean, RSI pressure rises, and the candle begins reclaiming back through the snapback rail, the bearish snapback context may become more meaningful.
When price stretches below the trend mean but cannot reclaim the snapback rail, the script may remain in WAIT RECLAIM or PRESSURE instead of READY.
When price reaches the room rail after reclaim, the context shifts into room review rather than fresh entry signaling.
🧱 System Philosophy
AGPro Series tools are built as decision-support systems.
They aim to convert market structure into readable context: what is active, what improves the plan, what invalidates it, and what should be reviewed next.
🔐 Non-Promise Statement
No script can provide certainty.
No signal guarantees outcome.
This tool provides structured context only.
📉 Risk Disclosure
Trading involves risk.
Markets can move quickly and unexpectedly.
Users are responsible for their own analysis, risk management, and decisions.
This script does not provide financial advice.
📚 Educational Note
Use this tool to study how trend stretch, momentum pressure, efficiency loss, and snapback behavior interact across different markets and timeframes.
Indicator

Pymander's EZ VWAPPymander's EZ VWAP
Standard VWAP indicators are great, but let’s be honest—they can be a bit "static." They show you where the price is relative to an average, but they don't tell you the story of the price action. That’s why I built EZ VWAP.
This isn't just a line on your chart; it’s a complete decision-making system designed to help you distinguish between a healthy trend and a trap.
What makes EZ VWAP stand out?
Most VWAPs just give you ±1, ±2, and ±3 standard deviations and call it a day. EZ VWAP is smarter. It classifies the market into logical zones:
The Fair Value Zone (±0.5σ): This is the "Chop Zone." If price is hanging out here, there’s no clear edge. We stay patient.
The Extension Zone (±1σ to ±2σ): This is where the magic happens for mean reversion.
The Exhaustion Zone (Beyond ±3σ): The "Danger Zone" where trends either blow off or reverse violently.
🛠️ Key Features You Won't Find in a Basic VWAP:
Acceptance vs. Rejection Logic: The biggest VWAP trap is shorting a "stretch" only for the price to keep mooning. Our Sweep + Reclaim signals only trigger when the price fails to hold above a band. It asks: "Did price accept the new high, or did it reject it?"
Momentum Dashboard: A quick-glance table in the corner tells you if the VWAP slope is Accelerating (momentum is expanding) or Decelerating (trend is weakening).
Dynamic Slope Coloring: The VWAP line itself changes color based on its "speed." Bright colors for strong trends, and neutral colors for weakening moves—perfect for timing your entries.
Three Modes in One: Whether you want a standard Session reset, a specific Anchored point (like a news event), or a Rolling window for a more responsive feel, we’ve got you covered.
Tailored Entries: Choose between Aggressive, Balanced, or Conservative entry models to match your personal risk tolerance.
How it helps you:
EZ VWAP stops you from "catching falling knives" by waiting for price to actually reclaim a level before signaling an entry. It helps you stay out of the chop and focus on the high-probability "stretch" areas where the big moves happen.
I’d love to hear how it’s working for you! If you have ideas for new features or tweaks, drop some feedback in the comments.
Wishing you all tons of luck and many, many green days!
-Pymander Indicator

Pymander's EZ Breakout FinderThe Momentum Breakout Highlighter is a versatile price-action tool designed to identify high-conviction breakout candles. Unlike standard breakout indicators that trigger on any breach of a high or low, this script uses a multi-layered filtering system to ensure that signals represent genuine market commitment rather than "noise" or low-volume fakeouts.
How It Works
The script monitors a user-defined lookback period to establish local resistance (highs) and support (lows). A signal is generated only when three distinct conditions are met:
The Breakout: Price must breach the highest high or lowest low of the lookback period. Users can choose whether this requires a Wick breach or a full Close beyond the level.
The Momentum Filter: The candle’s body size (Open to Close) is compared against the average body size of the lookback period. A signal only triggers if the candle shows "effort"—meaning its body is significantly larger than the recent average.
The Trend Context: Signals are filtered via a Volume Weighted Moving Average (VWMA). By default, it follows the trend (Longs above VWMA, Shorts below), but it also includes a Mean Reversion Mode for contrarian traders.
Key Features
Momentum Verification: Uses an adjustable multiplier to ensure breakout candles have the necessary "thrust" to sustain a move.
Mean Reversion Mode: A unique toggle that flips the trend logic, allowing you to find high-momentum exhaustion moves back toward the VWMA.
Advanced Signal Management:
Cooldown Timer: Prevents "signal clustering" by requiring a set number of bars to pass before a new signal can trigger.
Opposite Direction Filter: An optional mode that forces signals to alternate between Bullish and Bearish, perfect for swing traders looking for "one-way" entries.
Visual Clarity: Features bar highlighting, triangular plotshapes (arrows), and optional reference lines for the previous high/low levels.
What Makes It Stand Out?
Most breakout indicators fail during choppy markets because they lack a volatility component. This script solves that by integrating Body-to-Average momentum logic. By requiring the "breakout" candle to be larger than its predecessors, it filters out "exhaustion wicks" and low-liquidity drifts.
Furthermore, the inclusion of VWMA Trend Bias ensures you are always trading with volume-weighted support, and the Cooldown/Directional filters make it an excellent tool for automating alerts without being overwhelmed by repetitive signals during high-volatility spikes.
How to Use
For Trend Following: Use the default settings to catch high-momentum entries in the direction of the trend.
For Mean Reversion: Enable "Mean Reversion Mode" to catch "Blow-off tops" or "Panic bottoms" that break local ranges against the primary trend.
For Scalping: Lower the lookback period and cooldown for faster signals on lower timeframes.
Good luck and enjoy!
Indicator
