Volatility Regime Trend Ribbon [Pineify]Volatility Regime Trend Ribbon
Overview
This overlay adapts smoothing as markets change. It ranks ATR, selects a regime, and adjusts trend speed and ribbon width.
Key Features
Three ATR percentile regimes.
Regime-specific trend lengths and band scales.
Optional colors, confirmed markers, and alerts.
How It Works
ATR is ranked over a rolling window. Low ranks select low volatility, high ranks select high volatility, and middle ranks select normal volatility. Warm-up uses the normal state.
The selected length drives a recursive EMA-style center. Ribbon edges equal the center plus or minus ATR times the base multiplier and regime scale. This is a price boundary, not a statistical confidence interval. Direction turns bullish after a confirmed close above the upper edge, bearish below the lower edge, and otherwise retains its prior state.
Trading Ideas and Insights
Colors separate quiet, ordinary, and elevated ranges. A band exit can frame a direction change; movement inside stays unresolved. Gaps or thin trading can add lag and false transitions. No output is an automatic trade.
How Multiple Indicators Work Together
ATR measures range, percentile rank adds context, adaptive smoothing changes speed, and the band supplies the direction threshold. They form one engine without external data.
Unique Aspects
The original design links volatility to smoothing speed and band scale, not just color. Retained direction inside the band adds hysteresis; alerts distinguish regime and direction changes.
How to Use
Apply it to a liquid market and let the percentile window warm up.
Tune lengths and band scales for the symbol and timeframe.
Read center color as direction and ribbon color as regime.
Use confirmed alerts with independent risk controls.
Customization
ATR Length controls range sensitivity; Percentile Lookback controls context. Thresholds define states, lengths set speed, and band inputs set transition distance. Display layers are optional. Current values can change intrabar; markers and alerts require a confirmed close.
Conclusion
This ribbon organizes volatility regime and ATR percentile context for 15-minute to daily charts. It uses past and present data, remains lagging and parameter-sensitive, and makes no performance claim.
Indicator

Percentile Momentum Rotation [Pineify]Percentile Momentum Rotation
Overview
Percentile Momentum Rotation is a Pine Script v6 oscillator that converts fast, medium, and slow rate of change into a comparable spectrum. It shows a centered score, horizon coherence, a fast-slow wave, and a dashboard for momentum context rather than prediction.
Problem Definition
Raw ROC is a percentage return over one window. An 8-bar ROC has a different range from a 55-bar ROC, and the same value can be ordinary in a volatile regime but unusual in a quiet one. Averaging raw readings lets the largest horizon dominate, while fixed thresholds change meaning with the distribution. The design must retain each horizon's information but remove its local scale before combination.
Design Rationale
Each ROC is ranked against its own history and centered from -100 to +100, avoiding an assumption of normal returns. A z-score was rejected because outliers can distort its mean and deviation; a raw blend was rejected because it keeps the scale mismatch. The centroid is discounted when horizon polarities disagree or ranks spread apart. This favors coherent states but reacts less to an early one-window turn. The visual hierarchy follows these variables: primary score first, explanatory layers second.
Key Features
Three independently normalized ROC percentile streams.
A coherence-weighted composite and fast-slow rotation wave.
A state-colored spectrum, horizon fan, confirmed alerts, and dashboard.
Balanced, fast-focus, and slow-focus weighting.
How It Works
The script calculates percentage ROC over fast, medium, and slow lengths. ta.percentrank compares each current ROC with its configured history. Percentile 50 maps to zero, 100 to +100, and 0 to -100. Positive therefore means high versus that horizon's recent distribution; it does not guarantee a positive raw return.
The centered ranks form a weighted centroid; the three profiles shift emphasis across horizons. Polarity checks whether ranks share a side outside the dead zone, while compactness measures dispersion. Their 0-to-1 coherence controls a 0.55-to-1.00 consistency factor applied to the score.
The wave is half the fast-minus-slow rank difference. Color encodes score direction, halo intensity encodes coherence, and fan width shows dispersion. Output remains empty through warm-up. Visuals update intrabar; diamonds and alerts require bar close.
How Multiple Indicators Work Together
This is one pipeline, not a mashup. ROC supplies horizon change; percentile rank removes local scale; the centroid summarizes location; polarity and dispersion test coherence; and the consistency factor forms the score. The wave exposes lead-lag behavior that the centroid hides, while the fan visualizes disagreement. Removing a stage either removes momentum, restores the comparability problem, or hides confidence.
Trading Ideas and Insights
Upper and lower states organize review of relative momentum expansion. Synchronization means all horizons are unusual versus their own histories, not that a trade must follow. The wave reveals whether fast momentum leads or lags the slow horizon; repeated zero crossings describe unstable context. Confirm with independent structure and risk controls.
Unique Aspects
ROC and percentile rank are standard; the contribution is their information architecture. Each horizon is normalized against itself, then the composite is discounted by both side agreement and compactness. It separates historical location, synchronization, and lead-lag rotation; the same variables control halo, fan, and wave. No retrieved code is reproduced.
How to Use
Allow the slow ROC plus percentile history to warm up.
Start with Balanced and read score, coherence, and wave together.
Treat synchronization as context, then assess price structure and risk separately.
Use confirmed alerts; current-bar plots may move before close.
Disable secondary layers for a cleaner chart.
Customization
Short ROC windows react faster but rotate more often; long windows add persistence and lag. Longer percentile history provides broader context but adapts more slowly after regime shifts. The dead zone sets how much near-median movement is directionless. Rotation thresholds define context and extremes; Synchronization Threshold sets required agreement. Weight profiles change the analytical question, so comparisons should keep settings consistent.
Assumptions and Limitations
The source and available history must be representative enough for ranking. Percentiles are relative: a high rank can occur while raw returns are negative if the decline is milder than recent declines. Results depend on lengths, lookback, and structural breaks. It is lagging and omits volume, execution, fundamentals, and structure. Visuals can change before close; alerts wait for confirmation. No future values or external data are used, but this does not establish performance.
Conclusion
Percentile Momentum Rotation turns incompatible ROC scales into an auditable spectrum. It keeps relative location, coherence, and lead-lag rotation distinct but connected, helping diagnose momentum context without treating thresholds as guaranteed entries.
Indicator

Range Budget [AFD]
Range Budget answers one question at a glance: **how much of a
typical session's range has today already used?**
A day that has spent 40% of its typical range and a day that has spent 130% are different trading environments. This indicator measures which one you are in, from this chart's own price history, and says so in one number, onecolour, and one word.
###What it does###
- **Headline percentage** — today's realized range so far, divided by thetypical completed-session range. Never clamped: a wide day reads 130%, not100%.
- **State word and meter** — ROOM → PAST HALF (50%) → NEAR FULL (80%) → OVER
TYPICAL (100%). The word, the meter and every state colour come from the same thresholds, so they cannot disagree.
- **Envelope levels** — session low + typical range, and session high − typicalrange, drawn as glowing lines with a gradient band between them. Aconditional identity, not a projection: IF the session finishes at itstypical size AND the low holds, the high lands exactly on the upper level. Once the day crosses its typical range, the levels take the state colour.
- **Percentile ladder** (optional) — where a finished day of each size (p25 /p50 / p75 / p90 of the lookback window) would top out, measured up fromtoday's low. Nearest-rank percentiles: every rung is a session range thatactually occurred, never an interpolation.
- **Dashboard** — distance left to (or past) typical in both price points andpercent, how many of the last N sessions ran wider than typical, and optional detail rows (range so far, typical range, percentile standing,widest/narrowest, envelope and ladder values). Compact by default; everycryptic cell explains itself on hover; the whole panel can be switched off.
###How it works###
- **Typical range is user-selectable**, and the chart always names the activestatistic:
- **ADR** — the average of the last N completed session ranges (high − low).
- **ATR RMA** — the average true range, so overnight gaps count. Seeded withthe first true range rather than an initial SMA, which is why it is labelled "ATR RMA" and will not match `ta.atr()` to the last digit. Under ATR the numerator is the live session's true range too, so the percentageis never a ratio of two different measures.
- **Median** — the middle completed session range, which is also theladder's p50 rung.
- The three are identical on a symbol that never gaps and diverge as gaps grow — on heavily gapping symbols ATR can run near 2.5× ADR. That is why the choice exists and why the active one is named on the chart.
- **Completed sessions only.** The live day never feeds its own denominator —a partial day would drag the typical range down as the day progressed and bias the percentage upward with no symptom. Statistics update when a session completes; the live day contributes only its running range.
- **One session rule for everything.** Regular hours or regular + extended:history and the live day follow the same rule, and if the filter cannot change anything on your chart (no extended-hours bars loaded), the dashboard says so instead of staying silent.
- **The sample is what your chart holds.** n is capped by the sessions actually loaded — roughly 64 completed regular-hours sessions on a 5-minute chart from 5,000 bars on a Basic plan, more on higher plans and higher timeframes. The dashboard shows the n actually in use, plus a spread figure ((p90 − p25) ÷ p50) that says whether recent sessions were similar in size
or mixed.
- Eleven plotted values sit in the Data Window (percentage, ranges, envelope percentiles, sample size and more), so every number on the panel can be read, checked and exported.
###How to use it###
1. Add it to a liquid intraday chart. The defaults are the intended reading: compact dashboard, ADR(20), regular hours.
2. Read the headline first. ROOM means the day is still small next to its recent finished sessions; OVER TYPICAL means it has already run further than a typical one.
3. Use the envelope as context for the day's remaining room under the stated conditions — the tooltip on every input spells those conditions out.
4. Turn on the ladder to see today against the whole recent distribution instead of one average: price between p50 and p75 means today has already matched a mid-sized finished day.
5. Hover the bottom row of the dashboard whenever a figure is unclear — the statistic, the sample and any active caveat (gap counted, filter inert, no completed session yet) are explained there.
###What it deliberately does not do###
**Realized range from OHLCV — not an implied or expected move.** Every number is measured from this chart's own price history. Nothing comes from options pricing, and the typical range describes completed sessions — a description of what happened, not a statement about what happens next.
- No alerts, no signals, no entries or exits.
- Counts stay counts — "Sessions over typical: 4 of last 20" describes this chart's history, and the indicator never converts a count into odds.
- The percentage is never capped at 100%, because a day past its typical range is the most informative reading the tool produces.
###Why it is original###
Range tools usually hand you one number (an ADR level pair) or one overlay (an ATR band). Range Budget treats the session range as a budget and reports its consumption: one percentage against a user-chosen, chart-named statistic, computed from completed sessions only, with its sample size, its spread and every degeneracy disclosed on the panel itself. The three statistics are not interchangeable and the tool is built around that fact rather than hiding it: the active one is named on the chart, the ATR path measures true range on both sides of the ratio, and the ladder shows the whole recent distribution so one average never has to stand in for it.
Open source under the Mozilla Public License 2.0. All calculations are native
Pine v6 — no security() calls, no external data. Indicator

Indicator

Median ATR SD OscillatorMedian ATR SD Oscillator
Median ATR SD Oscillator is a trend-following volatility oscillator that measures the distance between price and two independent reference levels — an ATR band and a standard deviation band — both anchored to a percentile-based median. The asymmetric design uses different volatility measures for long and short signals, creating a natural bias toward staying in bullish trends longer while reacting quickly to breakdowns.
The result is an area oscillator that expands above zero in a confirmed bullish state and contracts below zero in a bearish state, with a white EMA line as a momentum confluence filter.
How It Works
A percentile median is calculated from a configurable price source — giving a robust, noise-resistant central reference level that adapts to recent price behavior.
Two independent volatility bands are then derived from this median:
ATR Band — median plus ATR multiplied by a configurable factor. The short condition uses the ATR band — price must fall below it to confirm a bearish state
SD Band — median plus the standard deviation of close. The long condition uses the standard deviation band — price must break above it to confirm a bullish state
Once a directional state is confirmed, the oscillator measures the distance between price and its reference level. An EMA of this distance acts as a confluence filter — the final signal only confirms when the distance is not only positive or negative but also above or below its own EMA, ensuring momentum is genuinely building in that direction.
Why This Approach Works
Most oscillators use a single volatility measure for both long and short signals. The Median ATR SD Oscillator deliberately uses two different measures — ATR for shorts and SD for longs — because they capture different market dynamics and create a natural asymmetry between entries and exits.
This asymmetric design reflects the structural reality of markets like crypto — price spends more time trending upward than downward. Longs require a statistically significant breakout above the SD band, while shorts only need price to fall back below the ATR band. The result is a system that stays in bullish trends longer while reacting quickly when momentum fades.
Settings
Median Source — Price source for the percentile median calculation (default: hl2)
Median Length — Lookback period for the percentile median (default: 63)
ATR Length — Lookback period for the ATR calculation (default: 4)
ATR Factor — Controls the width of the ATR band (default: 1.0)
SD Length — Lookback period for the standard deviation calculation (default: 29)
Use EMA — Enables the EMA confluence filter (default: true)
EMA Length — Lookback period for the EMA confluence filter (default: 35)
Use Bar Coloring — Colors bars based on the current state (default: true)
Color Background — Enables background coloring of the chart based on the current state (default: false)
Background Transparency — Controls the transparency of the background color (default: 85)
How to trade it
Long — when the oscillator expands above zero and the area turns blue, a bullish state has been confirmed. This is the signal to look for long entries or to hold existing long positions
Short / Cash — when the oscillator contracts below zero and the area turns red, the momentum has faded. This is the signal to exit longs, move to cash, or look for short entries depending on your strategy
EMA line — when the area is above the white EMA line momentum is building, when it crosses below momentum is weakening
Recommended Usage
Best used on the 1D timeframe for clean and reliable signal generation
Should not be used alone for trade entries — combine with an additional confirmation indicator for best results
The asymmetric ATR/SD design makes this oscillator particularly well suited for bullish-biased markets like crypto
Higher ATR Factor values make short exits more sensitive — lower values make them less reactive
Higher SD Length values create more stable long signals — lower values make them more reactive to short-term price movements
All signals are confirmed on bar close. Indicator

Volatility Trail [EXCAVO]ATR Percentile Rank Painted as a Semi-Transparent Wave Beneath Every Candle
The Volatility Trail takes the four-state volatility regime classification
from the standard ATR-percentile model and renders it directly on the price
chart as a semi-transparent wave hanging under each candle. The wave reads at
a glance: blue under the candles means quiet markets, orange means heating up,
red means volatility extremes. No separate indicator pane is required.
This is not a basic ATR oscillator. The ATR is normalised against its own
historical distribution, smoothed, and classified into four bounded regimes
(Low / Normal / Elevated / Extreme) with adjustable thresholds. The on-chart
trail is the same engine as the standard Volatility Percentile indicator,
just drawn where you actually read price.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW TO USE
Step 1 → Add the indicator. A coloured wave appears beneath every
candle as soon as enough history is available for the percentile
lookback to be meaningful (default 200 bars).
Step 2 → Read the wave colour:
- Blue = Low volatility (compression, mean-reversion regime)
- Grey = Normal volatility
- Orange = Elevated volatility (trend regime)
- Red = Extreme volatility (top decile, exhaustion risk)
Step 3 → Watch transitions. A switch from blue to orange flags a
breakout out of compression. A switch from red back to orange
flags a release from extreme volatility - often the right side
of a spike. The floating state badge to the right of the last
candle shows the current regime name at a glance.
Step 4 → Check the dashboard. State, raw percentile, ATR, ATR / Price,
and Vol Trend show the current regime numerically. Use these to
size positions and pick filters that depend on volatility.
Step 5 → Combine with structure. The trail is a context tool, not a
directional one - it tells you HOW volatile the market is, not
WHICH way it will move. Pair it with your own setup criteria.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW IT CALCULATES
◆ ATR Percentile Rank
The base measure is Average True Range over the user-set length (default 14).
For every bar the current ATR is ranked against its own values over the
Lookback Period (default 200): percentile = 100 x rank / N. A value of 90
means current volatility is higher than 90 percent of bars in the lookback
window. This normalisation makes the reading comparable across instruments
and timeframes - 90th-percentile vol on BTC and on EURUSD are both rare even
though their absolute ATRs differ by orders of magnitude.
◆ Smoothing
The raw percentile is smoothed with a short SMA (default 3) to reduce single-
bar noise. Smoothing = 1 disables this step.
◆ Four-State Classification
The smoothed percentile is bucketed into four regimes:
- Low = below Low / Normal boundary (default 25)
- Normal = between Low / Normal and Normal / Elevated (default 25 to 60)
- Elevated = between Normal / Elevated and Elevated / Extreme (default 60 to 80)
- Extreme = at or above Elevated / Extreme (default 80)
All three boundaries are user-adjustable.
◆ Candle-Anchored Downward Wave
A semi-transparent band hangs directly under each candle. The upper edge
is the bar's low, lightly EMA-smoothed so single-bar wick spikes do not
poke through the ribbon. The lower edge drops below by an ATR-scaled
distance: drop = ATR x (1 + percentile x Wave Distance Scale). At calm
regimes the wave is a thin sliver under price; at volatile extremes it
extends well below. The colour is the active state colour, and the
opacity within each state band is gradient (see next item).
◆ Within-Band Opacity Gradient
The wave colour is the state colour (blue / grey / orange / red), but the
opacity is not flat across each state - it ramps from Min Opacity at the
LOWER edge of the band (regime just entered) to Max Opacity at the UPPER
edge (peak of the regime, about to graduate to the next state). So a fresh
red band that just crossed into Extreme is light red, while a red band at
percentile 95 is a deep saturated red. The same gradient applies inside
the Low / Normal / Elevated bands. This lets you read at a glance whether
the current regime is just beginning, peaking, or about to fade into the
next state - approach and exhaustion are separately readable inside every
band.
◆ Vol Trend
ATR is compared to its 20-bar SMA. Above 1.05x SMA = RISING, below 0.95x =
FALLING, else STABLE. Shown on the dashboard as a quick second-derivative
read of the regime.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ WHAT MAKES IT DIFFERENT
◆ Wave Lives On The Price Chart
Most volatility indicators occupy a separate pane and force the eye to jump
between price action and the oscillator. The wave overlays the same regime
information directly on the candles, so price and volatility are read
together in one view.
◆ Adaptive Across Instruments
Percentile-rank normalisation removes the absolute ATR units. A BTC chart
and a EURUSD chart use the same scale (0 to 100), so the same thresholds
work everywhere without manual tuning.
◆ Four Bounded Regimes Instead Of A Raw Line
A raw ATR plot tells you very little until you have a feel for what is
"normal" on that instrument. The four-state classification answers the
question directly - quiet, normal, elevated, or extreme - using
user-adjustable boundaries.
◆ Within-Band Opacity Gradient
Inside each state band the wave opacity ramps from light (just-entered
regime) to saturated (regime at its peak). A fresh red band reads as
pale red; a deep mature Extreme reads as a saturated red. Approach and
exhaustion are separately readable inside every regime, not just on
state transitions.
◆ Premium Visual Polish
A thin rim-light line follows the upper edge of the wave for definition,
and a contrast-aware state badge floats next to the last candle showing
the current regime name. The badge text colour is picked automatically
by the perceived luminance of the background so the label stays readable
on any state colour.
◆ Optional Bar Coloring And Background
For users who want the regime even more visible, bar-coloring and
background-highlight toggles tint the candles or the chart background with
the active state colour. Both default off so the wave stays as the primary
visual.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ DASHBOARD
Real-time panel (top right) with the current regime readout:
State - LOW / NORMAL / ELEVATED / EXTREME
Percentile - the smoothed ATR percentile (0 to 100)
ATR - raw Average True Range
ATR / Price - ATR as a percentage of close (instrument-independent)
Vol Trend - RISING / STABLE / FALLING based on ATR vs its 20-bar SMA
Lookback - the bar count used for the percentile rank
Legend table (bottom left) explains every colour. Both panels toggle in the
Dashboard settings.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ SETTINGS
Engine
ATR Length - 14 (period for the Average True Range)
Lookback Period - 200 (historical bars used for the percentile rank)
Smoothing - 3 (SMA length applied to the raw percentile; 1 disables it)
State Thresholds
Low / Normal - 25 (boundary between Low and Normal regimes)
Normal / Elevated - 60 (boundary between Normal and Elevated)
Elevated / Extreme - 80 (boundary between Elevated and Extreme)
Visualization
Low Vol Color - blue
Extreme Vol Color - red
Elevated Vol Color - orange
Wave Top Smoothing - 3 (EMA length applied to the wave top; 1 = raw bar low with sharp peaks, 3 to 5 rounds off single-bar spikes while staying tight to price)
Wave Distance Scale - 0.025 (controls how far the wave drops below each candle as volatility rises; drop = ATR x (1 + percentile x scale); default keeps drops modest - approximately 1 ATR at Low regime, 3.5 ATR at Extreme)
Min Opacity - 25 (wave opacity at the LOWER edge of every state band - just-entered regime; very transparent)
Max Opacity - 55 (wave opacity at the UPPER edge of every state band - peak of the regime; visible but kept semi-transparent so the candles stay readable)
Wave Top Highlight - ON (thin rim-light line along the upper edge of the wave; adds definition and a premium glow)
Right-edge State Label - ON (floating badge next to the last candle showing the current state name in the state color)
Bar Coloring - OFF (when ON, also tints the candles with the state color)
Background Highlight - OFF (when ON, tints the chart background)
Dashboard
Show Dashboard - ON
Dashboard Position - Top Right
Show Legend - ON
Alerts
JSON Alerts - OFF (when ON, emits a structured JSON payload via alert())
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ ALERTS
Extreme Volatility - state just transitioned into Extreme
Elevated Volatility - state just transitioned into Elevated
Normal Volatility - state just transitioned into Normal
Low Volatility - state just transitioned into Low
With JSON Alerts ON, the alert() call emits a structured payload with
ticker, state, percentile, atr_pct, price, timeframe, and indicator fields -
use "Any alert() function call" as the PulseWire alert event to receive
every state change as JSON on one alert.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best regards,
EXCAVO
Disclaimer
Trading involves significant risk. This indicator is a technical analysis tool
and does not constitute financial advice, investment recommendations, or a
guarantee of future results. Past indicator behavior does not guarantee future
performance. Always use proper risk management and your own judgment.
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

Percentile SD OscillatorPercentile SD Oscillator
Percentile SD Oscillator is a momentum oscillator that measures the distance between price and its own dynamic reference levels — derived from percentile bands and a volatility-adjusted standard deviation filter. Rather than using fixed overbought/oversold levels, it continuously adapts to recent price behavior and only confirms a directional state when price demonstrates genuine statistical strength beyond its own boundaries.
The result is a histogram that oscillates around a zero line — positive and blue when the market is in a confirmed bullish state, negative and red when bearish.
How It Works
A moving average of your choice is calculated on a configurable source and length. Two percentile bands are then derived from this MA — an upper band and a lower band — defining the statistical range of recent price behavior.
A standard deviation of the close price is then calculated and added to the lower percentile band, creating a volatility-adjusted long reference level called sd_long. Price must close above both the upper percentile band AND sd_long to confirm a long — requiring double confirmation before entering a bullish state.
For the short side, a simple and fast condition is used — price only needs to close at or below the lower percentile band. Once a short state is confirmed, the oscillator measures the distance between the close price and the upper percentile band plus standard deviation as the bearish momentum value.
An EMA of the oscillator value acts as a confluence filter — the final signal only confirms when the oscillator is not only positive or negative but also above or below its own EMA. This ensures the oscillator only shows a confirmed state when momentum is genuinely building in that direction.
Why This Approach Works
Most momentum oscillators use fixed thresholds that do not adapt to changing market conditions. By combining percentile bands with a close-based standard deviation filter, the Percentile SD Oscillator requires price to break beyond levels that are dynamically calculated from both recent price structure and current volatility.
The asymmetric design between long and short is intentional and reflects the structural reality of markets like crypto. Longs require double confirmation — price must clear both the upper percentile band and the volatility-adjusted SD level — ensuring only genuinely strong bullish moves trigger an entry. Shorts are deliberately simpler and faster — price only needs to break below the lower percentile band, allowing quick exits when support is lost. This asymmetry prevents premature long entries while ensuring fast risk-off behavior when the market weakens.
The bullish momentum is measured against the lower percentile band — this captures how far price has risen above its support zone, giving a direct measure of bullish momentum strength. The bearish momentum is measured against the upper percentile band plus standard deviation — this creates a wider reference that captures how far price has fallen from the resistance zone, giving a more meaningful picture of bearish momentum strength.
Settings
MA Type — Moving average type used as the basis for the percentile calculation: DEMA, EMA, SMA, WMA, HMA, RMA (default: DEMA)
MA Length — Lookback period for the moving average (default: 8)
MA Source — Price source for the moving average calculation (default: high)
Percentile Length — Lookback period for the percentile band calculation (default: 57)
Percentile Up — Upper percentile threshold defining the bullish boundary (default: 60)
Percentile Down — Lower percentile threshold defining the bearish boundary (default: 46)
SD Length — Lookback period for the standard deviation calculation (default: 19)
SD Multiplier — Controls the strength of the standard deviation filter. Set to 0 to disable the SD filter entirely (default: 1.0)
EMA Length — Lookback period for the EMA confluence filter (default: 48)
Background Transparency — Controls the transparency of the optional background color (default: 85)
Color Background — Enables background coloring of the chart based on the current state (default: false)
Use Bar Coloring — Colors bars based on the current state (default: true)
How to trade it
Long — when the histogram turns blue and rises above zero, a bullish state has been confirmed. This is the signal to look for long entries or to hold existing long positions
Short / Cash — when the histogram turns red and falls below zero, the bearish state has been confirmed. This is the signal to exit longs, move to cash, or look for short entries depending on your strategy
Avoid trading against the signal — if the histogram is red do not look for longs, if it is blue do not look for shorts
The EMA line acts as a dynamic reference — when the histogram is above the EMA momentum is building, when it crosses below the EMA momentum is weakening
Recommended Usage
Best used on the 1D timeframe for clean and reliable signal generation
Should not be used alone for trade entries — combine with a trend-following indicator for best results
Set SD Multiplier to 0 to rely solely on the percentile bands — useful when you want more frequent signals in trending markets
Higher SD Multiplier values increase signal quality at the cost of fewer signals — lower values make the indicator more reactive
The asymmetric design makes this oscillator particularly well suited for bullish-biased markets like crypto — long entries require double confirmation while short exits are fast and decisive
All signals are confirmed on bar close. Indicator

Volatility Percentile [EXCAVO]ATR Percentile Rank with Four-State Volatility Classification and Trend Detection
The Volatility Percentile measures where the current Average True Range stands
relative to its own history using a percentile rank. Rather than comparing ATR to a
fixed threshold, the indicator continuously evaluates whether current volatility is
low, normal, elevated, or extreme relative to the recent distribution - adapting
automatically to each instrument and timeframe.
This is not a basic ATR display. The percentile rank provides a normalized, context-aware
measure of volatility that remains comparable across assets, timeframes, and market cycles.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW TO USE
Step 1 → Add the indicator to a new pane. The histogram appears immediately,
colored by the current volatility state (blue, gray, orange, or red).
Step 2 → Read the state from the histogram color and dashboard. Blue = Low,
Gray = Normal, Orange = Elevated, Red = Extreme.
Step 3 → Note the percentile value. Above 80% indicates the current ATR is
in the top 20% of its historical range - unusually wide price swings.
Below 25% indicates unusually quiet conditions.
Step 4 → Check the Vol Trend row in the dashboard. RISING means the ATR is
accelerating above its 20-bar average. FALLING means it is contracting.
Step 5 → Set up state-change alerts to receive notifications when volatility
transitions between states on bar close.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW IT CALCULATES
◆ ATR Percentile Rank
The indicator computes ATR(length) on each bar, then applies ta.percentrank() over
the lookback period. The percentile rank answers: "Out of the last N bars, what
percentage had an ATR lower than today's?" A result of 80 means 80% of recent bars
had a smaller ATR - current volatility is in the top 20% historically. The rank
always falls between 0 and 100, making it directly comparable across instruments.
◆ Smoothing
The raw percentile rank is passed through a simple moving average of configurable
length (default 3 bars). This suppresses single-bar spikes that would otherwise
cause false state transitions. The smoothed value is used for both the histogram
display and state classification. Setting smoothing to 1 disables it entirely.
◆ Four-State Classification
The smoothed percentile is compared against three configurable thresholds to assign
one of four states: Low (below 25th percentile), Normal (25th to 60th), Elevated
(60th to 80th), or Extreme (above 80th). State boundaries are user-adjustable,
allowing calibration for instruments that spend more time at elevated volatility
levels (such as crypto) versus lower-volatility markets.
◆ Volatility Trend
A secondary calculation compares the current ATR to its 20-bar simple moving average.
ATR above 105% of the SMA is classified as RISING. ATR below 95% of the SMA is
classified as FALLING. Between those bands the trend is STABLE. This early-warning
layer detects momentum in volatility before a state boundary is crossed.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ WHAT MAKES IT DIFFERENT
◆ Percentile Rank vs Fixed Threshold
A fixed ATR threshold (e.g., "ATR > 500 = high volatility") fails when applied across
different instruments or timeframes. The percentile approach self-calibrates: the same
indicator works on BTCUSD hourly and EURUSD daily without parameter changes, because
it measures volatility relative to the instrument's own recent history.
◆ Four States Instead of Two
Most volatility filters use a binary high/low split. Separating Normal from Elevated
and Extreme provides more granular awareness: Elevated volatility may still be
tradable, while Extreme conditions warrant a different approach to position sizing.
The four-state model also makes transitions visible earlier - Elevated appears before
Extreme is reached.
◆ Volatility Trend Detection
The Vol Trend layer detects whether ATR is currently accelerating or decelerating,
independently of which state it is in. It is possible to be in Normal state with
RISING trend (volatility building) or in Elevated state with FALLING trend
(volatility contracting back toward normal). This combination is visible only in the
dashboard and is not represented by the histogram color alone.
◆ ATR / Price Ratio
The dashboard shows ATR expressed as a percentage of the current close price. This
normalized measure is directly comparable across instruments and useful for estimating
stop distance relative to price without manual calculation.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ DASHBOARD
Real-time panel showing current volatility conditions:
State - active volatility state (LOW / NORMAL / ELEVATED / EXTREME), colored by type
Percentile - current smoothed ATR percentile rank (0-100%)
ATR - raw ATR value in price units for the current bar
ATR / Price - ATR expressed as a percentage of close price
Vol Trend - volatility momentum (RISING / FALLING / STABLE) vs 20-bar ATR average
Lookback - active lookback period used for percentile calculation
Legend table (bottom left) explains histogram colors and boundary lines. Both panels
toggle in Dashboard settings.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ SETTINGS
Engine
ATR Length - 14 bars (period for Average True Range calculation)
Lookback Period - 200 bars (history window for percentile rank)
Smoothing - 3 bars (applied to raw percentile; 1 = no smoothing)
State Thresholds
Low / Normal - 25 (percentile boundary between Low and Normal states)
Normal / Elevated - 60 (percentile boundary between Normal and Elevated states)
Elevated / Extreme - 80 (percentile boundary between Elevated and Extreme states)
Visualization
Low Vol Color - default blue
Extreme Vol Color - default red
Elevated Vol Color - default orange
Show State Ribbon - OFF (colored markers at pane bottom)
Background Highlight - ON (subtle tint matching active state)
Alerts
JSON Alerts - OFF (enable for bot integration)
Dashboard
Dashboard Position - Top Right
Show Dashboard - ON
Show Legend - ON
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ ALERTS
Extreme Volatility - state transitioned to Extreme on bar close
Elevated Volatility - state transitioned to Elevated on bar close
Normal Volatility - state transitioned to Normal on bar close
Low Volatility - state transitioned to Low on bar close
Volatility State Change - any state transition detected on bar close
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best regards,
EXCAVO
Disclaimer
Trading involves significant risk. This indicator is a technical analysis tool
and does not constitute financial advice, investment recommendations, or a
guarantee of future results. Past indicator behavior does not guarantee future
performance. Always use proper risk management and your own judgment.
Indicator

Indicator

Trend Quality Band [EXCAVO]Volatility-Ranked SuperTrend That Tightens in Calm Markets and Widens in Volatile Ones
The Trend Quality Band is an adaptive trend-following indicator built on a
SuperTrend core whose band width is controlled entirely by ATR percentile rank. Instead
of a fixed multiplier, the band compresses when current volatility is historically
low and expands when it is historically high - giving the trend line room when it
needs it and keeping it tight when conditions allow.
This is not a standard SuperTrend with a different parameter. The driving mechanism
is a statistical rank: each bar, the current ATR is compared against its full
lookback history to produce a 0-100% rank, which then scales the band multiplier
non-linearly between configurable compress and expand factors.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW TO USE
Step 1 → Add the indicator. The adaptive trend band appears immediately.
Blue band below price = bullish trend. Red band above price = bearish.
Step 2 → Watch for flip signals. Triangles mark the bar where the trend
changed direction. Bullish flip = triangle below bar. Bearish = above.
Step 3 → Read the ATR Rank in the dashboard. Below 35% = low volatility
(compressed band, trend holds tight). Above 65% = high volatility
(expanded band, wider room before a flip fires).
Step 4 → Use the Regime label. "Low Vol" means the band is near its
narrowest - trends confirmed here are high quality. "High Vol"
means the band is expanded to filter noise in choppy conditions.
Step 5 → Set alerts for Bullish or Bearish Trend Flip to be notified
on confirmed direction changes.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW IT CALCULATES
◆ ATR Percentile Rank
On every bar, the indicator computes the ATR using the configured length, then
ranks it against its own history over the Rank Lookback period:
atr_rank = percentrank(ATR, lookback) / 100
This produces a value from 0 to 1. A rank of 0.1 means current ATR is lower
than 90% of recent history (unusually quiet). A rank of 0.9 means current ATR
exceeds 90% of recent history (unusually volatile).
◆ Non-Linear Multiplier Scaling
The rank is mapped to a scaling factor using three zones defined by the
Compress Below and Expand Above thresholds (default 0.35 / 0.65):
t = clamp((atr_rank - compress_thresh) / (expand_thresh - compress_thresh), 0, 1)
rank_scale = compress_factor + t x (expand_factor - compress_factor)
eff_mult = base_multiplier x rank_scale
When rank is below the compress threshold, rank_scale approaches the Compress
Factor (default 0.65). When rank exceeds the expand threshold, rank_scale
approaches the Expand Factor (default 1.55). Between the thresholds, the scale
interpolates linearly. The result: a multiplier that ranges from approximately
1.6x (base 2.5 x 0.65) to 3.9x (base 2.5 x 1.55) depending on regime.
◆ SuperTrend Ratchet Logic
The adaptive multiplier feeds a standard SuperTrend ratchet:
upper_raw = src + eff_mult x ATR
lower_raw = src - eff_mult x ATR
lower_band = close > lower_band ? max(lower_raw, lower_band ) : lower_raw
upper_band = close < upper_band ? min(upper_raw, upper_band ) : upper_raw
The ratchet means the active band can only move in the direction of the trend -
it never widens to catch a missed flip. A flip fires when price closes beyond
the active band. The direction variable tracks the current trend state.
◆ Regime Classification
The rank is compared against the two thresholds to produce a named regime:
Low Vol (rank < 0.35), Normal (0.35-0.65), or High Vol (rank > 0.65). This
regime label and the live multiplier value are shown in the dashboard so the
trader can see exactly why the band is positioned where it is.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ WHAT MAKES IT DIFFERENT
◆ ATR Percentile Rank as the Sole Driver
Most adaptive SuperTrend variants modulate bands using the Efficiency Ratio (a
directional momentum measure) or volatility ratios against a moving average.
This indicator uses a statistical rank: the current ATR is compared against its
entire recent history rather than a smoothed baseline. A rank of 80% means the
current bar is more volatile than 80% of recent bars - a precise, context-aware
signal that a fixed multiplier or a ratio cannot capture.
◆ Compress-and-Expand Band Behavior
The two-threshold system creates three distinct regimes. In the Low Vol regime
the band compresses toward the Compress Factor - trend flips require less
movement, keeping the indicator responsive during quiet trends. In the High Vol
regime the band expands toward the Expand Factor - preventing false flips during
breakouts and spike-heavy conditions. The Normal regime interpolates between
the two, creating a smooth transition rather than a step function.
◆ Live Multiplier Transparency
The dashboard shows the actual effective multiplier value on every bar. This
tells the trader exactly how wide the band currently is and why. When the
multiplier reads 1.6x the band is near its tightest. When it reads 3.8x the
band is near its widest. No guesswork about how the indicator is behaving.
◆ Non-Repainting by Default
Flip signals are gated by barstate.isconfirmed - they only fire on the closed
bar. The Allow Repainting input is available for users who prefer real-time
updates, but the default ensures historical flips on the chart are accurate.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ DASHBOARD
Real-time panel (top right by default) shows the current state:
Trend - BULLISH or BEARISH, colored by direction
ATR Rank - current ATR percentile rank as a percentage (0-100%)
Regime - Low Vol / Normal / High Vol based on rank thresholds
Multiplier - effective band multiplier currently in use
Band - current price level of the active trend band
Legend table (bottom left) identifies all visual elements on the chart:
━ (blue) - Bullish trend band
━ (red) - Bearish trend band
┅ (orange) - Midline EMA, color reflects volatility regime
▲ (blue) - Bullish trend flip
▼ (red) - Bearish trend flip
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ SETTINGS
Core Settings
ATR Length - 14 (lookback for ATR calculation)
Base Multiplier - 2.5 (center-point multiplier at rank = 0.5)
Source - 0 = HL2, 1 = Close, 2 = HLC3
ATR Rank Settings
Rank Lookback - 200 bars (history used for percentile rank)
Compress Below - 0.35 (rank threshold for low volatility regime)
Expand Above - 0.65 (rank threshold for high volatility regime)
Compress Factor - 0.65 (multiplier scale at minimum rank)
Expand Factor - 1.55 (multiplier scale at maximum rank)
Visualization
Bullish Color - blue (customizable)
Bearish Color - red (customizable)
Signal Color - orange (customizable)
Show Band Fill - ON (semi-transparent fill between band and price)
Show Flip Signals - ON (arrow shapes at trend flip bars)
Show Background - OFF (chart background colored by trend)
Show Smooth Band - ON (EMA-smoothed band line, removes staircase appearance)
Smooth Length - 5 (EMA period for band smoothing)
Show Midline - ON (EMA of price colored by volatility regime)
Midline Length - 20 (EMA period for the midline)
Dashboard
Show Dashboard - ON
Show Legend - ON
Dashboard Position - Top Right
Alert Settings
Allow Repainting - OFF
JSON Alerts - OFF
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ ALERTS
Bullish Trend Flip - trend changed from bearish to bullish on bar close
Bearish Trend Flip - trend changed from bullish to bearish on bar close
Trend Flip - any direction change
JSON payloads include action, direction, ticker, price, timeframe, and indicator.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best regards,
EXCAVO
Disclaimer
Trading involves significant risk. This indicator is a technical analysis tool
and does not constitute financial advice, investment recommendations, or a
guarantee of future results. Past indicator behavior does not guarantee future
performance. Always use proper risk management and your own judgment.
Indicator

Percentile Stretch Bands [AGPro Series]Percentile Stretch Bands
🔹 OVERVIEW
Percentile Stretch Bands is an empirical, distribution-free overextension map. Instead of plotting standard deviation envelopes that assume a normal distribution of price behavior, this indicator samples the actual historical distance between price and a chosen reference (EMA, VWAP, or Anchored VWAP) and draws context-specific Stretch and Extreme bands directly from the empirical percentile distribution. The result is a visual reference of how stretched price is relative to its own historical behavior, adapted to the asset and timeframe being viewed.
🔹 UNIQUE EDGE
Most "stretch" or "volatility band" tools on the platform rely on parametric assumptions — standard deviation multipliers, ATR multiples, or fixed percentage offsets. These approaches collapse when the underlying return distribution is skewed, fat-tailed, or regime-dependent, which is the rule rather than the exception across crypto and FX assets.
Percentile Stretch Bands takes a different path:
• Distribution-free: bands are drawn from the actual empirical percentile of price-to-reference distance, not from a Gaussian assumption.
• Side-specific sampling: upper and lower distances are collected into separate samples, so asymmetric behavior (trending markets, one-sided regimes) is preserved rather than averaged away.
• Regime-aware rendering: when Focus Active Side is enabled, each bar displays only the side relevant to price position, producing a clean single-story chart without visual competition.
• Readiness gating: bands appear only once a minimum number of observations is reached on the active side, with the status panel clearly indicating the collection stage.
🔹 METHODOLOGY
For every bar in the configured lookback window, the signed percent distance between close and the selected reference is computed and partitioned into two historical samples: positive distances (upper extensions) and negative distances in absolute terms (lower extensions).
Each sample is sorted and two percentile cut-offs are extracted independently:
• Stretch percentile (default 80) — the threshold beyond which a distance is considered materially extended.
• Extreme percentile (default 95) — the threshold beyond which a distance is statistically rare within the chosen lookback.
These cut-offs are then translated from percent-distance back into absolute price bands around the active reference, producing four levels: Upper Stretch, Upper Extreme, Lower Stretch, Lower Extreme. The current distance is also ranked against its side's sample and displayed as an ordinal percentile (for example, "Upper P87") in the status panel.
🔹 SIGNALS AND ALERTS
The indicator is a visual overextension map and does not generate directional trade signals. Four alert conditions are exposed for users who want to be notified of boundary events:
• Upper Stretch Cross — close crosses above the Upper Stretch band.
• Upper Extreme Cross — close crosses above the Upper Extreme band.
• Lower Stretch Cross — close crosses below the Lower Stretch band.
• Lower Extreme Cross — close crosses below the Lower Extreme band.
These alerts mark entries into statistically extended zones relative to the empirical sample. They are contextual flags, not trade recommendations.
🔹 KEY INPUTS
Reference
• Reference Mode — EMA, VWAP, or Anchored VWAP baseline
• EMA Length — smoothing length for the EMA reference
• AVWAP Anchor Time — starting timestamp for Anchored VWAP
Statistics
• Lookback — bars used to build the empirical distribution (default 500)
• Minimum Side Sample — observations required before bands appear
• Stretch Percentile — primary extension threshold (default 80)
• Extreme Percentile — rare-extension threshold (default 95)
Display
• Focus Active Side — regime-aware single-story rendering
• Show Active Stretch Zone Box — right-side zone anchor on the active side
• Zone Forward Projection — forward visibility of the active zone
• Band Color Profile — Soft, Premium, or Bold
• Panel Text Size and Label Text Size — Small, Normal, or Large
Level Tags
• Show Level Tags, Show Reference Tag, Tag Mode, Tag Offset Bars
🔹 HOW TO USE
1. Select a reference that fits the asset and timeframe. EMA is a robust default across all instruments. VWAP is suited to intraday equities and futures. Anchored VWAP is used when a specific event origin (earnings, news, structural low) is relevant.
2. Let the status panel reach the "Ready" state. The panel reports active samples and readiness — bands are intentionally withheld until the side-specific sample is sufficient.
3. Read the current percentile rank in the Zone cell. Values near the center indicate price trading close to the reference; values approaching P95 or above indicate the sample's rare extensions.
4. Treat Stretch and Extreme bands as context, not as triggers. A move into the Extreme zone reflects a statistically rare extension on the chosen sample, not a directional signal.
5. Combine with structural tools — trend context, market structure, higher-timeframe bias — before any discretionary decision.
🔹 LIMITATIONS AND TRANSPARENCY
• The indicator is descriptive, not predictive. Percentile bands describe past behavior within the lookback window; they do not forecast future price action.
• Regime shifts can temporarily invalidate historical bands. A sudden volatility expansion will push price beyond extreme levels while the sample re-stabilizes.
• Empirical percentiles require sufficient observations. On very new symbols or short lookbacks, the "Collecting" state is the correct and expected behavior.
• Anchored VWAP mode depends on a meaningful anchor choice. A poorly chosen anchor produces a reference line without structural relevance.
• The active stretch zone box is a visual anchor for screenshots and review, not a projection of future levels.
🔹 RISK DISCLOSURE
This script is a visual analytics tool and is not a strategy, signal service, or financial advice. It does not place orders, manage positions, or recommend directional exposure. Trading involves risk of loss. Users are responsible for their own analysis, risk management, and trading decisions. Indicator

Value Migration Bands [AGPro Series]Value Migration Bands
Value Migration Bands is a chart-first value migration engine that visualizes where the market's accepted-value region has been drifting over time. Instead of a single moving average, it builds a three-layer band (upper / middle / lower) from a rolling percentile window of typical price, then classifies the current environment as Rising, Flat, or Falling Value using an ATR-normalized slope of the migration midline. The result is a scale-invariant, regime-aware view of how "fair value" migrates across trending and ranging conditions — on crypto, equities, indices, forex and futures alike.
🔷 OVERVIEW
Most band-style indicators build their envelope from volatility (Bollinger, Keltner, Donchian). Value Migration Bands is built from acceptance — the region where price has actually spent its time during the lookback, captured as a percentile window of typical price (hlc3). The outer bands mark the edges of that accepted-value region. The midline marks its core. When the whole region drifts upward, the market is accepting higher prices (Rising Value). When it drifts downward, lower prices are being accepted (Falling Value). When it stays level, participants are agreeing on a stable range (Flat Value).
This reframes the classic "trend vs range" question in terms of value migration, which is a cleaner structural signal than price slope alone. You see not just where price is going, but where the market's center of gravity is going.
🔶 UNIQUE EDGE
Value Migration Bands is distinct from moving-average envelopes, volatility bands and standard channels in several structural ways:
• Percentile-based construction — the band is a percentile window of typical price, not a standard deviation or ATR multiple. This directly captures acceptance, not dispersion.
• Three-state migration classification — Rising / Flat / Falling Value, driven by an ATR-normalized slope of the midline. The classification is scale-invariant, so the same sensitivity works across BTC, SPX, EURUSD, gold and small-cap equities without retuning.
• Regime-aware event markers — Reclaim and Lost markers are filtered by the current regime. Reclaim events are suppressed when the market is in Falling Value; Lost events are suppressed in Rising Value. You only see the events that matter for the active regime.
• Strict Value Filter — during extreme compression, the indicator refuses to classify a regime until the band is meaningfully wide relative to ATR. This prevents false regime flags in low-volatility micro-bands.
• Distance + cooldown gating — new event markers require a minimum ATR distance from the previous event and a minimum bar spacing, producing a clean chart even on long histories.
🔷 METHODOLOGY
Band construction:
1. Typical price (hlc3) is sampled across a configurable lookback window (Band Length).
2. Two percentiles are computed — a lower percentile and an upper percentile, selected by the Band Width Mode (Tight, Balanced, Wide).
3. The midline is the mean of those two percentiles.
4. Light EMA smoothing (adaptive to Band Length) stabilizes the visual without adding structural lag.
Regime classification:
1. The midline slope is measured over a rolling window (adaptive to Band Length).
2. The slope is normalized by ATR(14) to make the threshold scale-invariant.
3. A user-controlled Migration Slope Sensitivity divides the normalized slope into Rising / Flat / Falling bands.
4. A 2-bar confirmation layer prevents rapid regime flipping during transitions.
Event detection:
• Reclaim — price re-enters the band from below after previously being lost.
• Lost — price falls out of the band after previously being inside.
Both pass a regime gate, an ATR-distance gate and a bar-cooldown gate before being plotted or alerted.
🔶 SIGNALS & ALERTS
Four built-in alert conditions:
• Value Band Shifted Up — fires when the confirmed regime transitions into Rising Value.
• Value Band Shifted Down — fires when the confirmed regime transitions into Falling Value.
• Band Reclaimed — fires when price re-enters the accepted-value region (regime-gated).
• Band Lost — fires when price falls out of the accepted-value region (regime-gated).
Alerts and on-chart markers share identical gating, so the alert log and the chart stay in sync.
🔷 KEY INPUTS
Band Engine:
• Band Length (default 100) — lookback for the percentile window.
• Band Width Mode — Tight, Balanced, Wide. Selects the percentile pair.
• Strict Value Filter — requires a minimum band width vs ATR before classifying a regime.
• Migration Slope Sensitivity (default 0.5) — threshold between Rising / Flat / Falling.
Visuals:
• Show Midline, Show Band Fill, Active State Label, Show Reclaim / Lost Markers, Show Info Panel.
• Panel Location — six options (Top / Middle / Bottom × Right / Left).
• Panel Font Size and Label Font Size — default Normal.
Colors:
• Rising Value Color, Falling Value Color, Flat Value Color.
• Band Fill Opacity.
Alerts:
• Individual toggles for the four alert conditions above.
🔶 HOW TO USE
Structural reading:
• Rising Value — treat Reclaim events as continuation confirmations, not counter-trend signals. Expect pullbacks to the midline to be bought.
• Falling Value — treat Lost events as continuation confirmations. Expect rallies back to the midline to be sold.
• Flat Value — neither regime is active. The band can be used as a range reference; directional events are suppressed because they do not carry regime confirmation.
Location reading:
• Inside Band — price is trading within the accepted-value region. This is the default state.
• Above Band — price is trading above accepted value. In Rising Value, this is constructive; in Falling Value, it is a rally to be evaluated.
• Below Band — price is trading below accepted value. In Falling Value, this is the dominant state; in Rising Value, it is a dip.
Timeframe guidance:
• 1H–4H — best balance for swing use with the default Band Length of 100.
• 15m–1H — reduce Band Length to 40–60 for intraday use.
• Daily — Band Length 100 gives a structural multi-month migration view.
Pairing suggestions:
• Higher-timeframe VMB for bias, lower-timeframe execution tools for entry.
• Combining with volume-based or anchored-VWAP tools can confirm whether value migration is participation-backed.
🔷 LIMITATIONS & TRANSPARENCY
• This is an analytical visualization tool, not a strategy. It does not backtest, does not place orders and does not generate buy / sell recommendations.
• Regime classification is based on historical midline slope. Like all rolling measures, it is a lagging read of structure — it describes what has been happening, not what will happen.
• During abrupt regime changes, the 2-bar confirmation layer introduces a small delay by design, trading reactivity for stability.
• Percentile bands are descriptive of past acceptance. Future acceptance may differ, especially around news events, regime breaks and illiquid sessions.
• The Strict Value Filter can force a Flat reading during extreme compression even when a visual direction appears present; this is intentional and protects against false regime flags.
🔶 RISK DISCLOSURE
This indicator is published for educational and analytical purposes. It is not financial advice, not a trading recommendation and not a guarantee of performance. Trading and investing involve substantial risk, including the risk of total loss. Past behaviour of any instrument does not guarantee future results. Users are solely responsible for their own decisions and should perform their own due diligence, including independent risk management and position sizing.
Published as open-source under the Mozilla Public License 2.0. Feedback, questions and discussion are welcome in the comments.
Indicator

Dynamic Acceptance Channel [AGPro Series]Dynamic Acceptance Channel
🔷 Overview
Dynamic Acceptance Channel is an adaptive volatility channel that builds a dynamic upper and lower edge around a robust median midpoint. The channel width breathes with the market's own return distribution and volatility regime, so it naturally widens when the market expands and tightens when it compresses. Every bar is classified as Inside, Breaching, or Respecting the channel, while the width itself is independently tracked as Compressed, Normal, or Expanded. The tool is designed to give traders a clean, consistent framework for reading acceptance, mean-reversion context, volatility squeezes, and adaptive range behavior across crypto, FX, and equities.
🟢 Unique Edge
Most channel indicators on the market rely on a single dispersion model — typically a moving average plus a fixed standard deviation or ATR multiplier. Dynamic Acceptance Channel takes a different route:
▪ Robust median midpoint instead of a simple mean, which stays stable when the market wicks or spikes and is not dragged around by outliers.
▪ Hybrid width model that combines the percentile spread of recent returns with a clamped ATR regime ratio. The user can switch between Hybrid, Return Percentile, or Volatility Regime, depending on whether distribution shape or raw volatility is the priority.
▪ Independent width regime classification (Compressed / Normal / Expanded) ranked against the channel's own history, with hysteresis applied so the regime does not flip-flop around threshold boundaries.
▪ Bar-level state machine (Inside, Breach, Respect) separated from the width regime, so traders can read location and regime as two orthogonal dimensions.
▪ Double-EMA smoothing on both the midpoint and the half-width, producing a calm, professional channel that is readable on any timeframe without looking jagged.
This combination is not found in common Bollinger Bands, Keltner Channels, or generic ATR channels.
🧭 Methodology
The midpoint is computed as a rolling median using linear-interpolation percentile logic, which is statistically more robust than an arithmetic mean when the return distribution is skewed or heavy-tailed. The half-width is then derived from two independent signals. The first is a return-percentile dispersion term: the script measures the 85th and 15th percentiles of recent per-bar returns, symmetrizes them, and scales by the square root of the lookback window to produce a percentile-based half-width proxy. The second is a volatility regime term: the current 14-bar ATR is compared to its own baseline over the adaptive window, and the resulting ratio is clamped between 0.6 and 1.8 to prevent explosive widths during regime shocks. The final half-width is either one of the two terms or their average, depending on the selected model, then scaled by a user-defined global multiplier and smoothed with double EMA. The width regime classification uses linear-interpolation percentiles of the channel width itself over a separate regime lookback, and a 10% hysteresis buffer prevents rapid state flipping around the Compressed and Expanded thresholds.
🎯 Signals & Alerts
▪ Channel Breached — fires on a fresh upper or lower breach, edge-triggered with a minimum three-bar gap to avoid clusters on choppy bars.
▪ Channel Compressed — fires when the width regime transitions into the Compressed state.
▪ Channel Expanded — fires when the width regime transitions into the Expanded state.
▪ Channel Respected — optional, fires when price wicked outside on the prior bar and closed back inside on the current bar, confirming a rejection at the edge.
Visuals include color-coded upper and lower lines, a regime-tinted fill, small circular breach markers on the breached line (no text labels to avoid clutter), and spaced Compressed or Expanded transition labels anchored outside the channel.
⚙️ Key Inputs
Adaptive Engine
▪ Adaptive Length — lookback window for the channel (default 60).
▪ Channel Width Model — Hybrid, Return Percentile, or Volatility Regime.
▪ Width Scale — global multiplier for tightening or loosening the channel.
▪ Channel Smoothing — EMA length for line smoothness.
▪ Strict Breach Logic — close-based versus wick-based breach.
Width Regime
▪ Compression Threshold — percentile below which the width is Compressed (default 25).
▪ Expansion Threshold — percentile above which the width is Expanded (default 75).
▪ Regime Lookback — lookback for the width percentile ranking (default 150).
Visuals
▪ Show Channel Fill, Show Midline, Show Breach Markers, Show Regime Transition Labels, Regime Label Spacing.
Panel
▪ Show / hide panel, Panel Location (6 options), Panel Font Size, Label Font Size.
Alerts
▪ Channel Breached, Compressed, Expanded, and Respected can be toggled independently.
🧠 How to Use
A common reading is to combine channel state with width regime. When the channel is Compressed and price is riding the edges, the market is often preparing for an expansion phase. When the channel transitions into Expanded, continuation on the active edge is more likely than immediate mean reversion. Respect events at either edge during Normal or Compressed regimes often line up with fade opportunities, while breaches during Expanded regimes often line up with trend continuation context. The midline can be used as a dynamic fair-value reference for pullback entries inside the channel. Traders typically overlay this script with their own structure, momentum, or higher-timeframe bias tools rather than using channel events in isolation.
⚠️ Limitations & Transparency
▪ The indicator is a context and structure tool. It does not generate buy or sell decisions and does not claim to identify every meaningful reversal or breakout.
▪ The channel is recomputed each bar from recent data, which means the current bar's channel values can refine until bar close.
▪ Width regime classification is relative to the regime lookback, not absolute. On instruments or timeframes with very low variance, the regime may behave differently than on highly volatile markets.
▪ The ATR ratio is intentionally clamped between 0.6 and 1.8. This prevents explosive widths but also means the channel will not fully mirror extreme volatility shocks; this is a deliberate design choice for readability.
▪ Alerts are configured to fire once per bar close to reduce noise. Intrabar conditions may change until close.
🛡 Risk Disclosure
This script is provided for educational and analytical purposes only. It is not a strategy, not financial advice, and not a trade recommendation. Past channel behavior on any instrument or timeframe does not imply future performance. Users are fully responsible for their own risk management, position sizing, and trading decisions. Indicator

CVD Multi Exchange PercentileCVD Multi Exchange Percentile
Aggregated order flow across four major crypto derivatives exchanges — with historical percentile ranking to measure how extreme today's session really is.
A Cumulative Volume Delta (CVD) indicator with daily reset, divergence detection, and absorption signals, built for perpetual futures.
It combines Binance, Bybit, OKX, and Bitget into a single aggregated flow, then ranks it against its own history to give you objective context.
█ 🧩 KEY FEATURES
🔹 Multi Exchange Aggregation
Four sources (Binance, Bybit, OKX, Bitget) can be toggled independently. The aggregated delta captures cross-exchange order flow that single-source CVD cannot detect — especially during liquidations or arbitrage-driven moves.
🔹 Historical Percentile System
Each session's peak CVD is stored in a rolling buffer, separated by direction (bull vs bear). The current session is ranked against this distribution to measure how extreme the flow is compared to recent history.
🔹 Live Percentile
A real-time percentile tracks the current CVD value as the session develops — no need to wait for session close.
🔹 Swing Divergence
Detects divergences between price and CVD structure:
- Bullish: price makes lower low, CVD makes higher low
- Bearish: price makes higher high, CVD makes lower high
Filtered by percentile threshold and optional trend filter.
🔹 Volume Absorption
Highlights conditions where price and CVD move in opposite directions under high volume:
- Bullish absorption: price down, CVD up
- Bearish absorption: price up, CVD down
Requires elevated volume and percentile confirmation.
🔹 Visual Encoding
Histogram color reflects direction and momentum. Signal markers:
- Divergence bullish: dark green triangle up
- Divergence bearish: blue triangle down
- Absorption bullish: orange circle
- Absorption bearish: purple circle
Optional info table provides real-time stats.
Signal examples on TRXUSDT.P (1H) — three signal types visible:
- Orange circle (Absorption Bull): price dropping but CVD rising on high volume — buying pressure hidden under falling price
- Blue triangle (DIV- Bearish): price making higher high but CVD making lower high — selling pressure building despite rising price
- Purple circle (Absorption Bear): price rising but CVD falling on high volume — selling pressure hidden under rising price
Signal examples on ETHUSDT.P (1H) — bullish signals visible:
- Dark green triangles (DIV+ Bullish): price making lower lows but CVD making higher lows — buying pressure increasing despite falling price, signaling potential reversal
- Orange circle (Absorption Bull): same logic as above — hidden buying under selling candles
█ 🔧 HOW IT WORKS
The script fetches lower-timeframe OHLCV data from each exchange using `request.security_lower_tf()`.
Each intrabar volume is classified using a CLV-based model (close location within range) to estimate buying vs selling pressure. The resulting deltas are summed across all exchanges and accumulated into a daily CVD, resetting at the start of each new UTC session.
█ 📖 HOW TO USE
Apply the indicator to Perpetual Futures charts (.P).
The symbol is auto-detected from the chart and mapped across all supported exchanges — no manual input needed.
Suggested timeframe: 1H (default percentile lookback is 336 bars, which equals ~14 days on 1H charts).
Signals are contextual, not standalone triggers. Use them to identify:
- flow/price divergences
- potential absorption zones
- extreme participation conditions
█ ⚙️ SETTINGS
Data Sources (Perpetual Futures Only) — Enable/disable Binance, Bybit, OKX, Bitget
Settings — Intrabar precision (1/5/15/60), daily reset
Signals — Percentile lookback (default 336 bars, ~14 days on 1H), min percentile for divergence (75), swing length (8), trend filter SMA (20), absorption volume lookback (10) and multiplier (1.5), show/hide toggles for divergences, absorption, trend filter, and info table
█ 💡 WHAT MAKES THIS DIFFERENT
Most CVD indicators rely on a single exchange and lack statistical context.
This script aggregates flow across venues and ranks it using a percentile system, providing a clear measure of whether current activity is extreme or routine.
Bull and bear distributions are handled separately, avoiding distortion from mixed data.
█ ⚠️ LIMITATIONS
— Works only on perpetual futures (.P required)
— Delta is estimated from OHLCV, not tick-level order book data
— Exchange data availability may vary by symbol
— Intrabar resolution affects precision and performance
█ 📌 DISCLAIMER
This is a contextual analysis tool, not a signal generator.
It does not provide buy/sell signals and should not be used as a standalone trading system. Always apply proper risk management.
Indicator

AG Pro Bollinger Bands Squeeze Map [AGPro Series]AG Pro Bollinger Bands Squeeze Map
Overview
AG Pro Bollinger Bands Squeeze Map is a Bollinger-based compression and release mapping tool designed to show how volatility contracts, matures, expands, and sometimes fails directly on price.
Instead of reducing the entire process to a simple binary squeeze dot, this script organizes the behavior into a visual regime map. It tracks when compression is only beginning, when it becomes more meaningful, when it reaches deeper squeeze conditions, and when price transitions into a release phase. It also highlights failed releases and re-compression behavior, which can be useful when an expansion loses follow-through and the market slips back into a tighter volatility regime.
The goal of the script is not to predict the next move in advance, and it is not presented as a standalone trade system. Its purpose is to provide structured context around Bollinger Band compression so the user can evaluate whether the market is still coiling, already expanding, or losing expansion quality after an initial move.
This script is plotted directly on the chart and is built to remain readable without requiring a separate lower panel. The design prioritizes chart-first interpretation, moderate visual hierarchy, and state clarity.
Unique Edge
Many Bollinger squeeze tools stop at a yes/no condition or a single timing marker. This script takes a broader approach.
Its primary difference is that it treats squeeze behavior as a sequence of states rather than as a single event. That means the script does not only ask whether a squeeze exists. It also asks:
- Is compression only building, or is it already active?
- Has the squeeze become deep or mature?
- Did the first release show better or weaker expansion quality?
- Did the move fail and rotate back toward the basis?
- Is the market entering a re-compression phase after release?
This state-based mapping framework is the main distinction of the indicator. The intent is to help the user see volatility structure more clearly, rather than to provide a simplistic breakout label.
What the Script Does
The script combines Bollinger Band structure, normalized band width, width percentile logic, optional Keltner Channel confirmation, and release-state scoring into a single on-chart map.
In practice, the indicator can highlight:
- Building Compression
- Active Squeeze
- Deep Squeeze
- Mature Squeeze
- Up Release
- Down Release
- Failed Release
- Re-Compression
The result is a visual progression from contraction to expansion, with added context about the quality of that transition.
Methodology
1) Bollinger Band Structure
The script begins with a standard Bollinger Band framework built from a basis line and upper/lower deviations. This establishes the primary price envelope used throughout the tool.
2) Normalized Band Width
Raw band width is normalized relative to the basis so that compression can be assessed more consistently across changing price levels.
3) Width Percentile Regime Detection
The script evaluates current band width against a lookback window using percentile rank logic. This allows the user to frame current compression relative to recent history rather than relying only on absolute width values.
4) Optional Keltner Confirmation
An optional Keltner containment component can be used to strengthen squeeze filtering. Depending on the selected mode, the script can use percentile logic, Keltner logic, or a hybrid of both.
5) Compression State Classification
Compression is not handled as one flat condition. The script distinguishes between building compression, active squeeze, deep squeeze, and mature squeeze based on percentile thresholds and persistence.
6) Release Quality Scoring
When price exits a squeeze state, the script evaluates the release using a score that incorporates bar body behavior, close location, width expansion, distance from basis, and wick influence. The output is grouped into quality labels such as Weak, Clean, or Strong.
7) Failed Release Logic
A release is not automatically treated as durable. If the move loses structure and rotates back through the basis within the monitoring window, the script can classify that behavior as a failed release.
8) Re-Compression Detection
After release, markets do not always trend cleanly. Sometimes they compress again. The re-compression logic is included to identify this return into tighter volatility conditions.
Signals and Alerts
The script includes deterministic alert conditions tied to state transitions. These alerts are intended to notify the user when a specific structural condition appears on the chart.
Available alert categories include:
- Active Squeeze
- Deep Squeeze
- Mature Squeeze
- Up Release
- Down Release
- Failed Release
- Re-Compression
These alerts describe indicator states. They are not guarantees of continuation, reversal, or trade outcome.
Visual Design
The indicator is designed to work as an on-chart map rather than as a lower-pane oscillator.
The visual structure includes:
- Bollinger Bands
- Optional Keltner Channel
- Compression and release zone fills
- State labels
- Compact information panel
The zone rendering is intentionally state-weighted. More important states such as release, deeper squeeze regimes, and failure/re-compression conditions receive stronger visual emphasis, while lower-priority compression states can remain lighter to reduce chart clutter.
Key Inputs
The script includes adjustable controls for:
- Detection mode
- Bollinger Band length and multiplier
- Percentile lookback and thresholds
- Keltner Channel length and ATR multiplier
- Minimum bar requirements for deeper squeeze states
- Release persistence window
- Failure and re-compression windows
- Label size and offset
- Band and channel visibility
- Map intensity
- Theme selection
- Panel position and font size
These controls allow the user to adapt the script to different assets, volatility profiles, and charting preferences.
How to Interpret It
A practical way to read the script is to think in phases.
When the indicator shows Building Compression, volatility is tightening but may not yet be at a stronger squeeze threshold.
When the indicator shifts into Active, Deep, or Mature squeeze conditions, compression is becoming more statistically notable relative to the selected lookback.
When a release label appears, the script is identifying a transition out of compression. The associated quality label is meant to describe the character of that release, not to certify future follow-through.
If a failed release appears, the script is signaling that the initial expansion did not maintain structure within the observation window.
If re-compression appears, the market may be moving from expansion back into tighter volatility conditions.
This framework is often more useful for context and filtering than for isolated signal-chasing.
Use Cases
This tool may be useful for users who want to:
- study volatility contraction and expansion directly on price
- compare weaker and cleaner releases after squeeze conditions
- identify failed expansion behavior
- add context to existing discretionary workflows
- use squeeze structure as a filter rather than a complete decision engine
It can also be used alongside structure analysis, trend analysis, support/resistance mapping, or broader workflow-based chart review.
Limitations and Transparency
This script is a volatility-structure tool. It is not a prediction engine and does not forecast future price direction with certainty.
Several important limitations should be kept in mind:
- A squeeze can resolve in either direction.
- A strong-looking release can still fail.
- A failed release does not automatically imply a reversal trend.
- Different symbols and timeframes may require different threshold settings.
- Very noisy instruments may produce more frequent state changes.
Because of this, the script should be interpreted as a structured context layer rather than as a standalone execution model.
Open-source access does not remove the need for user judgment. Inputs still need to be reviewed and adjusted where appropriate for the instrument and timeframe being studied.
Risk Disclosure
This indicator is for chart analysis and educational use. It does not provide financial, investment, legal, or tax advice.
Any decision based on this script remains the responsibility of the user. Markets can behave unpredictably, and no indicator can eliminate risk. Users should evaluate signals, states, and visual conditions in the context of their own methodology, time horizon, and risk framework. Indicator

Indicator

Price Percentile Heatmap [QuantAlgo]🟢 Overview
This indicator visualizes where price currently stands within its recent historical distribution, displayed as a dynamic gradient heatmap directly on the chart. It is built on the concept of percentile ranking: rather than using lagging momentum oscillators or fixed overbought/oversold thresholds, it measures price relative to every bar within a user-defined lookback window and expresses that position as a smooth, continuous gradient. The result is an at-a-glance read of whether price is historically cheap, historically expensive, or somewhere in between, all without leaving the main chart.
The defining visual feature is the thermal color gradient applied to the price bars, background, and source line. Bullish colors represent price trading near the top of its recent range, signaling historically elevated conditions. Bearish colors represent price trading near the bottom of its range, signaling historically depressed conditions. A built-in Heat Thermometer reinforces this reading by showing exactly where the current percentile rank falls along the full spectrum in real time.
🟢 How It Works
The foundation of the indicator is a per-bar percentile rank calculated over a rolling lookback window. For each bar, the selected price source is compared against every value within the lookback period to determine what percentage of historical bars traded below the current price:
percentile_rank = ta.percentrank(price_source, lookback_length)
A rank of 100 means the current price is higher than every bar in the lookback sample. A rank of 0 means it is lower than all of them. A rank of 50 places price exactly at the median of its recent distribution. This single value drives every visual output in the indicator.
The raw rank is then mapped directly into a continuous color gradient, transitioning smoothly from the bearish color at rank 0 to the bullish color at rank 100:
gradient_color = color.from_gradient(percentile_rank, 0, 100, bearish_color, bullish_color)
Because the rank is recalculated on every bar using a rolling window, the gradient never relies on fixed thresholds or static levels. It adapts continuously to the most recent price history, meaning the same absolute price level can read bullish in one market environment and bearish in another depending on what has happened within the lookback period.
The lookback length is the primary tuning parameter. Short periods (10 to 30) make the rank reactive to recent moves and suit scalping and intraday setups. Medium periods (50 to 100) provide a balanced read suitable for swing trading. Long periods (150 to 500) produce a slow-moving, macro-level view best suited for position trading and identifying historically extreme conditions.
🟢 Key Features
1. Thermal Color Gradient
Every visual element on the chart, including the source line, the bar colors, and the background tint, reflects the current percentile rank through a smooth color transition.
▶ Bullish Color: Applied when price ranks high within its recent distribution, drawing attention to historically elevated price levels.
▶ Bearish Color: Applied when price ranks low, highlighting historically depressed conditions and potential mean-reversion or continuation setups.
▶ Bar Coloring: Each individual candlestick is colored according to the current rank, giving instant bar-by-bar feedback without requiring a separate panel.
▶ Background Coloring: The full chart canvas receives a semi-transparent tint that reinforces the heatmap reading across the entire visible price area. Transparency is fully adjustable so price action is never obscured.
▶ Color Presets: Six pre-configured schemes, Classic, Aqua, Cosmic, Cyber, Neon, and Custom, allow you to match the heatmap to any chart theme or personal preference.
2. Heat Thermometer
An optional thermometer panel displays the full bearish-to-bullish color spectrum and marks exactly where the current percentile rank sits along that spectrum with a real-time arrow indicator.
▶ Real-Time Positioning: The arrow updates on every bar, giving an immediate visual anchor for the current rank without needing to read a number.
▶ Resolution: The number of gradient segments in the thermometer is adjustable from 5 to 20, letting you choose between a clean simplified display or a finer, smoother gradient.
▶ Position and Size: The thermometer can be placed in any of nine chart positions and its text size is independently adjustable, making it easy to integrate into dense multi-indicator layouts or standalone setups.
🟢 Practical Applications
▶ Mean Reversion Setups: When price reaches an extreme low percentile rank, it is historically cheap relative to recent bars, a potential entry signal for mean reversion strategies. The opposite applies at high ranks.
▶ Trend Confirmation: In a strong trend, the percentile rank will persistently hue toward one color. A sustained bullish gradient confirms trend strength; a persistent bearish gradient confirms sustained selling pressure.
▶ Multi-Timeframe Alignment: Apply the indicator across multiple timeframes and look for gradient agreement. When both a higher and lower timeframe show the same extreme color, the percentile signal carries significantly more weight. Indicator

Monte Carlo Simulation BandsMonte Carlo Simulation v2.4.2
Plots a one-bar-ahead price distribution band built from many simulated paths. The green band shows empirical percentiles of simulated final prices—these are distribution bounds, not a confidence interval of the mean.
What It Does
Simulates many one-bar price paths using a directional random walk with volatility scaling (uniform shocks, not Gaussian GBM).
Plots Mean Forecast, Median Forecast, and configurable percentile bounds (default 5th/95th).
Optional rolling HTF-days mean line (yellow) for trend context.
Optional labels and forward projection lines.
Alerts when the confirmed close breaks above or below the percentile band.
Non-Repainting & HTF Behavior (Fail-Closed)
All calculations are gated to confirmed bars only via explicit no_repaint_ok gate (barstate.isconfirmed).
If you select an HTF Resolution, the script uses a strict request.security(..., lookahead_off, gaps_off) pipeline.
If HTF data is unavailable, outputs are na—no silent fallback to chart timeframe.
A separate "HTF Alignment (lagged)" plot shows the prior HTF close (htf_price ) as visual proof of no look-ahead.
Volatility Source & Scaling
If "Use Historical Volatility" is enabled, volatility is estimated from log returns on the selected resolution (HTF if set, otherwise chart).
Annualization adapts to session type:
Equities: 6.5 hours/day, 252 trading days/year
Crypto: 24 hours/day, 365 days/year
Substeps increase path smoothness within the same one-bar horizon—they do not extend the forecast to multiple bars.
Key Inputs
• Prob Up / Prob Down — Must satisfy Prob Up + Prob Down ≤ 1.0. If violated, simulation is skipped and table shows "✗ PROB>1".
• # Simulations / # Substeps — Higher = smoother/more stable, but slower. Default 100×100 is a good balance.
• Lower/Upper Percentile — Define the band width (e.g., 5 and 95 for a 90% distribution band).
• Run On Last Bar Only — Performance mode (recommended). Skips historical computation; updates on each new confirmed bar.
• Resolution (HTF) — Leave blank for chart timeframe, or set to Weekly/Monthly for HTF-aligned simulation.
• Crypto 24/7 Session? — Enable for crypto markets to use correct annualization (365d, 24h).
How to Use (Quickstart)
Start with defaults and keep Run On Last Bar Only = true for speed.
Set Prob Up and Prob Down so their sum ≤ 1.0 (e.g., 0.5 + 0.5 = 1.0 for neutral).
Enable "Use Historical Volatility" and set a Volatility Lookback (e.g., 20 bars) for data-driven vol.
Set Resolution (HTF) if you want the model to run on higher timeframe data (e.g., 1W). Expect updates only when a new HTF interval starts.
Choose percentiles (e.g., 5 and 95) to define your distribution band width.
Enable alerts for "Price Above Upper Percentile" or "Price Below Lower Percentile" to get notified of breakouts.
Limitations & Disclosures
Forecast horizon is one bar only. Substeps do not create a multi-bar forecast.
Model uses uniform shocks with direction chosen from Prob Up/Down. This is not Geometric Brownian Motion (GBM) and is not calibrated to any option-implied distribution.
Bounds are percentiles of final simulated prices, not a statistical confidence interval of the mean.
HTF mode updates at the start of a new HTF interval (first chart bar where the HTF timestamp changes), so the band appears "step-like" in realtime.
Historical volatility requires enough bars for the selected lookback; until then, values may be na.
Performance depends on Sims × Substeps; extreme settings (e.g., 500×500) can be slow.
This indicator does not predict direction—it shows a probabilistic range based on your inputs.
Indicator

IV Rank & Percentile Suite V1.0What This Indicator Does
The IV Rank & Percentile Suite provides the volatility context options traders need to time entries. It calculates two complementary metrics—IV Rank and IV Percentile—using historical volatility as a proxy, then displays clear visual zones to identify favorable conditions for premium selling strategies.
Stop guessing if volatility is "high" or "low." This indicator tells you exactly where current volatility sits relative to recent history.
The Two Metrics Explained
IV Rank (0-100) Measures where current volatility sits within its 52-week high-low range.
IV Rank = (Current HV - 52w Low) / (52w High - 52w Low) × 100
70 means current volatility is 70% of the way between the yearly low and high
Sensitive to extreme spikes (a single high reading affects the range)
IV Percentile (0-100) Measures what percentage of days in the lookback period had lower volatility than today.
IV Percentile = (Days with lower HV / Total days) × 100
70 means volatility was lower than today on 70% of days in the past year
More stable, less affected by outlier spikes
Why Both?
IV Rank reacts faster to volatility changes. IV Percentile is more stable and statistically robust. When both agree (e.g., both above 50), you have stronger confirmation. Divergence between them can signal transitional periods.
Zone System
The indicator divides readings into three zones:
Zone ------- Default Range ---- Meaning ------------------ Premium Selling
🟢 High ≥ 50 Elevated volatility Favorable
🟡 Neutral 25-50 Normal volatility Selective
🔴 Low ≤ 25 Compressed volatility Avoid
An additional Extreme threshold (default 75) highlights prime conditions when volatility is significantly elevated.
Zone thresholds are fully customizable in settings.
How to Use It
For Premium Sellers (Iron Condors, Credit Spreads, Strangles)
Wait for IV Rank to enter the green zone (≥50)
Confirm IV Percentile agrees (also elevated)
Enter premium selling positions when both metrics align
Avoid initiating new positions when in the red zone
For Premium Buyers (Long Options, Debit Spreads)
Low IV Rank/Percentile means cheaper options
Red zone can favor directional debit strategies
Avoid buying premium when both metrics are in the green zone
General Principle:
Sell premium when volatility is high (it tends to revert to mean). Buy premium when volatility is low (if you have a directional thesis).
Inputs
Volatility Calculation
HV Period — Lookback for historical volatility calculation (default: 20)
Trading Days/Year — 252 for stocks, 365 for crypto
Lookback Periods
IV Rank Lookback — Period for high/low range (default: 252 = 1 year)
IV Percentile Lookback — Period for percentile calculation (default: 252)
Zone Thresholds
High IV Zone — Readings above this are highlighted green (default: 50)
Low IV Zone — Readings below this are highlighted red (default: 25)
Extreme High — Threshold for "prime" conditions alert (default: 75)
Display Options
Toggle IV Rank, IV Percentile, and raw HV display
Show/hide zone backgrounds
Show/hide info panel
Panel position selection
Info Panel
The panel displays:
Field ------- Description
IV Rank ------- Current reading with color coding
IV Pctl ------- Current percentile with color coding
HV 20d ------- Raw historical volatility percentage
52w Range ------- Lowest to highest HV in lookback period
Zone ------- Current zone status
Premium ------- Signal quality for premium selling
Lookback ------- Days used for calculations
R/P Spread ------- Difference between Rank and Percentile
Alerts
Six alerts are available:
Zone Transitions
IV Entered High Zone — Favorable for premium selling
IV Reached Extreme Levels — Prime conditions
IV Dropped to Low Zone — Caution for premium sellers
Threshold Crosses
IV Rank Crossed Above High Threshold
IV Rank Crossed Below Low Threshold
IV Percentile Above 75
IV Percentile Below 25
Set up alerts to get notified when conditions change without watching charts.
Technical Notes
Volatility Calculation Method
This indicator uses close-to-close historical volatility as an IV proxy:
Calculate log returns: ln(Close / Previous Close)
Take standard deviation over HV Period
Annualize: multiply by √(Trading Days)
This method correlates well with implied volatility for most liquid instruments. On highly liquid options underlyings (SPY, QQQ, major stocks), HV and IV tend to move together, making this a reliable proxy for IV Rank analysis.
Non-Repainting
All calculations use confirmed bar data. Values are fixed once a bar closes.
Lookback Requirement
The indicator needs sufficient history to calculate accurately. For a 252-day lookback, ensure your chart has at least 300+ bars of data.
Best Used On
ETFs: SPY, QQQ, IWM, DIA
Indices: SPX, NDX
High-volume stocks: AAPL, TSLA, NVDA, AMD, META
Timeframe: Daily (recommended), Weekly for longer-term view
The indicator works on any instrument but is most meaningful on underlyings with active options markets.
Important Notes
⚠️ This indicator uses historical volatility as a proxy for implied volatility. While HV and IV are correlated, they are not identical. For precise IV data, consult your options broker's platform.
⚠️ High IV Rank does not guarantee profitable premium selling. It indicates favorable conditions, not guaranteed outcomes. Position sizing and risk management remain essential.
⚠️ Past volatility patterns do not guarantee future behavior. Volatility regimes can shift, and historical ranges may not predict future ranges.
Suggested Workflow
Add to daily chart of your preferred underlying
Set up alert for "IV Entered High Zone"
When alerted, check both IV Rank and IV Percentile
If both elevated, evaluate premium selling opportunities
Use your broker's actual IV data for final entry decisions
Questions? Leave a comment below. Indicator

Machine Learning Moving Average [BackQuant]Machine Learning Moving Average
A powerful tool combining clustering, pseudo-machine learning, and adaptive prediction, enabling traders to understand and react to price behavior across multiple market regimes (Bullish, Neutral, Bearish). This script uses a dynamic clustering approach based on percentile thresholds and calculates an adaptive moving average, ideal for forecasting price movements with enhanced confidence levels.
What is Percentile Clustering?
Percentile clustering is a method that sorts and categorizes data into distinct groups based on its statistical distribution. In this script, the clustering process relies on the percentile values of a composite feature (based on technical indicators like RSI, CCI, ATR, etc.). By identifying key thresholds (lower and upper percentiles), the script assigns each data point (price movement) to a cluster (Bullish, Neutral, or Bearish), based on its proximity to these thresholds.
This approach mimics aspects of machine learning, where we “train” the model on past price behavior to predict future movements. The key difference is that this is not true machine learning; rather, it uses data-driven statistical techniques to "cluster" the market into patterns.
Why Percentile Clustering is Useful
Clustering price data into meaningful patterns (Bullish, Neutral, Bearish) helps traders visualize how price behavior can be grouped over time.
By leveraging past price behavior and technical indicators, percentile clustering adapts dynamically to evolving market conditions.
It helps you understand whether price behavior today aligns with past bullish or bearish trends, improving market context.
Clusters can be used to predict upcoming market conditions by identifying regimes with high confidence, improving entry/exit timing.
What This Script Does
Clustering Based on Percentiles : The script uses historical price data and various technical features to compute a "composite feature" for each bar. This feature is then sorted and clustered based on predefined percentile thresholds (e.g., 10th percentile for lower, 90th percentile for upper).
Cluster-Based Prediction : Once clustered, the script uses a weighted average, cluster momentum, or regime transition model to predict future price behavior over a specified number of bars.
Dynamic Moving Average : The script calculates a machine-learning-inspired moving average (MLMA) based on the current cluster, adjusting its behavior according to the cluster regime (Bullish, Neutral, Bearish).
Adaptive Confidence Levels : Confidence in the predicted return is calculated based on the distance between the current value and the other clusters. The further it is from the next closest cluster, the higher the confidence.
Visual Cluster Mapping : The script visually highlights different clusters on the chart with distinct colors for Bullish, Neutral, and Bearish regimes, and plots the MLMA line.
Prediction Output : It projects the predicted price based on the selected method and shows both predicted price and confidence percentage for each prediction horizon.
Trend Identification : Using the clustering output, the script colors the bars based on the current cluster to reflect whether the market is trending Bullish (green), Bearish (red), or is Neutral (gray).
How Traders Use It
Predicting Price Movements : The script provides traders with an idea of where prices might go based on past market behavior. Traders can use this forecast for short-term and long-term predictions, guiding their trades.
Clustering for Regime Analysis : Traders can identify whether the market is in a Bullish, Neutral, or Bearish regime, using that information to adjust trading strategies.
Adaptive Moving Average for Trend Following : The adaptive moving average can be used as a trend-following indicator, helping traders stay in the market when it’s aligned with the current trend (Bullish or Bearish).
Entry/Exit Strategy : By understanding the current cluster and its associated trend, traders can time entries and exits with higher precision, taking advantage of favorable conditions when the confidence in the predicted price is high.
Confidence for Risk Management : The confidence level associated with the predicted returns allows traders to manage risk better. Higher confidence levels indicate stronger market conditions, which can lead to higher position sizes.
Pseudo Machine Learning Aspect
While the script does not use conventional machine learning models (e.g., neural networks or decision trees), it mimics certain aspects of machine learning in its approach. By using clustering and the dynamic adjustment of a moving average, the model learns from historical data to adjust predictions for future price behavior. The "learning" comes from how the script uses past price data (and technical indicators) to create patterns (clusters) and predict future market movements based on those patterns.
Why This Is Important for Traders
Understanding market regimes helps to adjust trading strategies in a way that adapts to current market conditions.
Forecasting price behavior provides an additional edge, enabling traders to time entries and exits based on predicted price movements.
By leveraging the clustering technique, traders can separate noise from signal, improving the reliability of trading signals.
The combination of clustering and predictive modeling in one tool reduces the complexity for traders, allowing them to focus on actionable insights rather than manual analysis.
How to Interpret the Output
Bullish (Green) Zone : When the price behavior clusters into the Bullish zone, expect upward price movement. The MLMA line will help confirm if the trend remains upward.
Bearish (Red) Zone : When the price behavior clusters into the Bearish zone, expect downward price movement. The MLMA line will assist in tracking any downward trends.
Neutral (Gray) Zone : A neutral market condition signals indecision or range-bound behavior. The MLMA line can help track any potential breakouts or trend reversals.
Predicted Price : The projected price is shown on the chart, based on the cluster's predicted behavior. This provides a useful reference for where the price might move in the near future.
Prediction Confidence : The confidence percentage helps you gauge the reliability of the predicted price. A higher percentage indicates stronger market confidence in the forecasted move.
Tips for Use
Combining with Other Indicators : Use the output of this indicator in combination with your existing strategy (e.g., RSI, MACD, or moving averages) to enhance signal accuracy.
Position Sizing with Confidence : Increase position size when the prediction confidence is high, and decrease size when it’s low, based on the confidence interval.
Regime-Based Strategy : Consider developing a multi-strategy approach where you use this tool for Bullish or Bearish regimes and a separate strategy for Neutral markets.
Optimization : Adjust the lookback period and percentile settings to optimize the clustering algorithm based on your asset’s characteristics.
Conclusion
The Machine Learning Moving Average offers a novel approach to price prediction by leveraging percentile clustering and a dynamically adapting moving average. While not a traditional machine learning model, this tool mimics the adaptive behavior of machine learning by adjusting to evolving market conditions, helping traders predict price movements and identify trends with improved confidence and accuracy.
Indicator

Indicator

Volume Percentile Supertrend [BackQuant]Volume Percentile Supertrend
A volatility and participation aware Supertrend that automatically widens or tightens its bands based on where current volume sits inside its recent distribution. The goal is simple: fewer whipsaws when activity surges, faster reaction when the tape is quiet.
What it does
Calculates a standard Supertrend framework from an ATR on a volume weighted price source.
Measures current volume against its recent percentile and converts that context into a dynamic ATR multiplier.
Widens bands when volume is unusually high to reduce chop. Tightens bands when volume is unusually low to catch turns earlier.
Paints candles, draws the active Supertrend line and optional bands, and prints clear Long and Short signal markers.
Why volume percentile
Fixed ATR multipliers assume all bars are equal. They are not. When participation spikes, price swings expand and a static band gets sliced.
Percentiles place the current bar inside a recent distribution. If volume is in the top slice, the Supertrend allows more room. If volume is in the bottom slice, it expects smaller noise and tightens.
This keeps the same playbook usable across busy sessions and sleepy ones without constant manual retuning.
How it works
Volume distribution - A rolling window computes the Pth percentile of volume. Above that is flagged as high volume. A lower reference percentile marks quiet bars.
Dynamic multiplier - Start from a Base Multiplier. If bar is high volume, scale it up by a function of volume-to-average and a Sensitivity knob. If bar is low volume, scale it down. Smooth the result with an EMA to avoid jitter.
VWMA source - The price input for bands is a short volume weighted moving average of close. Heavy prints matter more.
ATR envelope - Compute ATR on your length. UpperBasic = VWMA + Multiplier x ATR. LowerBasic = VWMA - Multiplier x ATR.
Trailing logic - The final lines trail price so they only move in a direction that preserves Supertrend behavior. This prevents sudden flips from transient pokes.
Direction and signals - Direction flips when price crosses through the relevant trailing line. SupertrendLong and SupertrendShort mark those flips. The plotted Supertrend is the active trailing side.
Inputs and what they change
Volume Lookback - Window for percentile and average. Larger window = stabler percentile, smaller = snappier.
Volume Percentile Level - Threshold that defines high volume. Example 70 means top 30 percent of recent bars are treated as high activity.
Volume Sensitivity - Gain from volume ratio to the dynamic multiplier. Higher = bands expand more when volume spikes.
VWMA Source Length - Smoothing of the volume weighted price source for the bands.
ATR Length - Standard ATR window. Larger = slower, smaller = quicker.
Base Multiplier - Core band width before volume adjustment. Think of this as your neutral volatility setting.
Multiplier Smoothing - EMA on the dynamic multiplier. Reduces back and forth changes when volume oscillates around the threshold.
Show Supertrend on chart - Toggles the active line.
Show Upper Lower Bands - Draws both sides even when inactive. Good for context.
Paint candles according to Trend - Colors bars by trend direction.
Show Long and Short Signals - Prints 𝕃 and 𝕊 markers at flips.
Colors - Choose your long and short palette.
Reading the plot
Supertrend line - Thick line that hugs price from above in downtrends and from below in uptrends. Its distance breathes with volume.
Bands - Optional upper and lower rails. Useful to see the inactive side and judge how wide the envelope is right now.
Signals - 𝕃 prints when the trend flips long. 𝕊 prints when the trend flips short.
Candle colors - Quick bias read at a glance when painting is enabled.
Typical workflows
Trend following - Use 𝕃 flips to initiate longs and ride while bars remain colored long and price respects the lower trailing line. Mirror for shorts with 𝕊 and the upper trailing line. During high volume phases the line will give more room, which helps stay in the move.
Pullback adds - In an established trend, shallow tags toward the active line after a high volume expansion can be add points. The dynamic envelope adjusts to the session so your add distance is not fixed to a stale volatility regime.
Mean reversion filter - In quiet tape the multiplier contracts and flips come earlier. If you prefer fading, watch for quick toggles around the bands when volume percentile remains low. In high volume, avoid fading into the widened line unless you have other strong reasons.
Notes on behavior
High volume bar: the percentile gate opens, volRatio > 1 powers up the multiplier through the Sensitivity lever, bands widen, fewer false flips.
Low volume bar: multiplier contracts, bands tighten, flips can happen earlier which is useful when you want to catch regime changes in quiet conditions.
Smoothing matters: both the price source (VWMA) and the multiplier are smoothed to keep structure readable while still adapting.
Quick checklist
If you see frequent chop and today feels busy: check that volume is above your percentile. Wider bands are expected. Consider letting the trend prove itself against the expanded line before acting.
If everything feels slow and you want earlier entries: percentile likely marks low volume, so bands tighten and 𝕃 or 𝕊 can appear sooner.
If you want more or fewer flips overall: adjust Base Multiplier first. If you want more reaction specifically tied to volume surges: raise Volume Sensitivity. If the envelope breathes too fast: raise Multiplier Smoothing.
What the signals mean
SupertrendLong - Direction changed from non-long to long. 𝕃 marker prints. The active line switches to support below price.
SupertrendShort - Direction changed from non-short to short. 𝕊 marker prints. The active line switches to resistance above price.
Trend color - Bars painted long or short help validate context for entries and management.
Summary
Volume Percentile Supertrend adapts the classic Supertrend to the day you are trading. Volume percentile sets the mood, sensitivity translates it into dynamic band width, and smoothing keeps it clean. The result is a single plot that aims to stay conservative when the tape is loud and act decisively when it is quiet, without you having to constantly retune settings.
Indicator
