Volatility Stop SelectorThe Volatility Stop Selector is a comprehensive trend-following tool designed to automatically identify the optimal volatility stop strategy. It features adjustable parameters and an integrated backtester that delivers institutional-grade insights into the recommended strategy. The model continuously adapts to new data in real time by evaluating multiple volatility length and factor combinations, determining the best-performing configuration, and presenting the backtest results in a clear, color-coded table that benchmarks performance against the buy-and-hold strategy.
At its core, the model systematically backtests a wide range of volatility stop combinations to identify the configuration that maximizes the selected optimization metric. Users can choose to optimize for absolute returns or risk-adjusted returns using metrics such as the Sharpe, Sortino, Martin, or Calmar ratios. The Martin ratio is particularly well suited for volatility-based risk management strategies, as it evaluates returns relative to the Ulcer Index, capturing both the depth and duration of drawdowns and therefore favoring smoother equity curves. Alternatively, users can enable manual optimization to test custom volatility length and factor settings and view the corresponding backtest results. The label displays the Compounded Annual Growth Rate (CAGR) of the strategy, with the buy-and-hold CAGR in parentheses for comparison. The table presents the backtest results based on the volatility length and factor displayed at the top:
Sharpe = CAGR per unit of standard deviation.
Sortino = CAGR per unit of downside deviation.
Calmar = CAGR relative to maximum drawdown.
Max DD = Largest peak-to-trough decline in value.
Beta (β) = Return sensitivity relative to buy-and-hold.
Alpha (α) = Excess annualized risk-adjusted returns.
Win Rate = Ratio of profitable trades to total trades.
Profit Factor = Total gross profit per unit of losses.
Expectancy = Average expected return per trade.
Trades/Year = Average number of trades per year.
This indicator is designed with flexibility in mind, enabling users to specify the start date of the backtesting period, the preferred volatility type, and the price source. Supported volatility types include the Average True Range (ATR), Standard Deviation (SD), and Mean Absolute Deviation (MAD). Supported price sources include Close, Heikin Ashi, HL2, HLC3, and OHLC4. To minimize overfitting, users can define constraints such as a minimum and maximum number of trades per year, as well as an optional optimization margin that prioritizes more robust combinations by requiring more reactive combinations to exceed this threshold. The table follows an intuitive color-coded logic that enables quick performance comparison against buy-and-hold (B&H):
Sharpe = Green indicates better than B&H, while red indicates worse.
Sortino = Green indicates better than B&H, while red indicates worse.
Calmar = Green indicates better than B&H, while red indicates worse.
Max DD = Green indicates better than B&H, while red indicates worse.
Beta (β) = Green indicates better than B&H, while red indicates worse.
Alpha (α) = Green indicates above 0%, while red indicates below 0%.
Win Rate = Green indicates above 50%, while red indicates below 50%.
Profit Factor = Green indicates above 2, while red indicates below 1.
Expectancy = Green indicates above 0%, while red indicates below 0%.
In summary, the Volatility Stop Selector is a powerful tool designed to help investors make data-driven decisions when selecting volatility-based trend-following strategies. By optimizing for risk-adjusted returns, investors can identify the best configurations using institutional-grade metrics. While results are based on the selected historical period, users should be mindful of overfitting, as past results may not persist under future market conditions. Since the model continuously recalibrates to incorporate new data, the recommended length and factor may evolve over time. 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

Squeeze Momentum Indicator [AGPro Series]Squeeze Momentum Indicator
🔷 OVERVIEW
Squeeze Momentum Indicator is a lower-pane volatility and momentum engine built for traders who want more structure than the classic squeeze workflow usually provides.
At its core, the script studies a very specific sequence in market behavior:
volatility compression,
compression release,
directional pressure after release,
and whether that pressure is strengthening, fading, or slipping back toward balance.
Most squeeze-style indicators stop at a simple yes/no squeeze condition and a basic momentum histogram around the zero line. This script is designed to go further without becoming noisy. It keeps the familiar Bollinger Band vs Keltner Channel compression logic that many traders already understand, but it rebuilds the momentum side around a different internal model so the post-squeeze move can be judged with more nuance.
The result is a more structured answer to an important practical question:
when volatility finally expands, is the move actually carrying useful directional pressure, or is it only a shallow release that may lose energy quickly?
🔷 WHAT THIS SCRIPT DOES
This indicator combines four layers into one compact oscillator workflow:
1. Volatility compression detection
It identifies squeeze conditions using Bollinger Band and Keltner Channel relationship logic.
2. Compression depth tracking
It does not only ask whether a squeeze exists. It also tracks how tightly the Bollinger envelope sits inside the Keltner envelope, which helps frame how compressed the market really is.
3. ATR-normalized momentum pressure
Instead of using the classic legacy-style squeeze momentum formula, this script blends:
- displacement from equilibrium
- directional velocity of that equilibrium
- path efficiency of recent price travel
This creates a momentum engine that is designed to evaluate the quality of directional pressure after release, not just whether a histogram is above or below zero.
4. Adaptive expansion / fade context
The script builds dynamic balance and burst zones around momentum, then classifies whether price is:
- compressing
- releasing with bullish pressure
- releasing with bearish pressure
- continuing directionally
- fading after an elevated move
- rotating back toward balance
This makes the tool especially useful for traders who want squeeze timing, but do not want to treat every release as equally meaningful.
🔷 WHAT MAKES THIS DIFFERENT FROM MOST SQUEEZE INDICATORS
The squeeze concept is widely known, but many public versions still revolve around the same structure:
a binary compression state and a very simple momentum histogram.
This script is intentionally different in several ways:
• It treats squeeze as a volatility gate, not as the full identity of the indicator.
• It uses an original blended momentum model rather than reusing the standard linear-regression style momentum formula associated with many older versions.
• It adds adaptive momentum zones so the oscillator can distinguish between ordinary movement and higher-energy expansion.
• It marks not only burst phases, but also momentum fade phases, which helps separate continuation pressure from cooling pressure.
• It includes restrained release labels, release boxes, and a compact information panel so the visual output stays premium and readable instead of overloaded.
In short, this script is not trying to be another cosmetic variation of an old squeeze formula.
Its objective is narrower and more analytical:
measure the quality of post-compression directional pressure in a clean lower-pane environment.
🔷 HOW THIS SCRIPT IS DIFFERENT FROM OTHER AGPRO TOOLS
This part matters because originality and role separation inside a script catalog are important.
Within the AGPro Series, this indicator is intentionally separate from nearby concepts:
• AG Pro Bollinger Bands Squeeze Map
That script is an on-chart volatility regime map built to show how compression and release behave directly on price.
This script is different.
It is a dedicated lower-pane momentum-quality engine focused on what happens after compression begins to resolve.
• AG Pro ROC Momentum Shift Map
That script studies momentum regime transitions through ROC behavior.
It is a broader momentum-state classifier.
This script is narrower by design and specifically anchored to squeeze-release behavior.
• AG Pro Structural Momentum Oscillator
That script evaluates momentum through internal price structure and bar behavior.
This script does not try to read momentum that way.
Its purpose is to organize volatility compression and post-compression expansion into a squeeze-specific workflow.
That distinction is central to this release:
this is not a re-labeled overlap script.
It is a purpose-built squeeze momentum tool with its own logic, its own visual model, and its own analytical role.
🔷 HOW THE ENGINE WORKS
The script begins with a standard compression framework:
- Bollinger Bands define the volatility envelope.
- Keltner Channels define the containment envelope.
- When the Bollinger structure contracts inside the Keltner structure, squeeze conditions are present.
From there, the script moves into a separate momentum model.
Instead of relying on one traditional oscillator formula, the engine blends three components:
1. Displacement from equilibrium
Measures how far price has moved from its equilibrium anchor relative to ATR.
2. Equilibrium velocity
Measures whether that equilibrium is moving directionally and how quickly.
3. Path efficiency
Measures how efficiently price has traveled over the selected lookback instead of simply how far it moved.
Those three components are blended into a normalized momentum-pressure read, then smoothed for cleaner interpretation.
The script then builds two adaptive internal thresholds:
- a balance band
- a burst band
These dynamic bands help classify whether momentum is:
- quiet / balanced
- directional but ordinary
- strong enough to qualify as a burst
- elevated but beginning to fade
This adaptive structure matters because a fixed threshold often reads very differently across symbols, volatility regimes, and timeframes.
🔷 VISUAL DESIGN
The visual design is built around premium clarity rather than signal overload.
The pane includes:
• A momentum histogram with four directional states
- bullish expansion strengthening
- bullish pressure fading
- bearish expansion strengthening
- bearish pressure fading
• Adaptive upper and lower momentum zones
These show where momentum is operating in balance versus expansion territory.
• Squeeze markers on the zero line
These quickly show whether volatility is still compressed or has just released.
• Optional release boxes
These create rectangular burst zones that make active expansion phases easier to scan visually.
• Restrained release / fade labels
Labels are intentionally filtered and spaced so the chart remains informative without looking crowded.
• AG Pro information panel
The panel summarizes squeeze state, phase, bias, momentum, energy, and current signal context.
The goal is to keep the script visually rich, but still clean enough for repeated real-world use.
🔷 HOW TO READ IT
A practical way to interpret the script:
• Squeeze ON
Volatility is compressed.
This is preparation, not directional confirmation.
• Bull Burst / Bear Burst
Compression has released and momentum has cleared the adaptive balance zone with directional pressure.
This is the main transition event in the workflow.
• Bull Drive / Bear Drive
The market is still carrying directional pressure after release.
• Bull Fade / Bear Fade
Momentum remains elevated, but acceleration is cooling.
This does not automatically mean reversal.
It means the move is no longer improving in quality.
• Balance
The market is not in an active burst condition and momentum is closer to neutral internal behavior.
This makes the script useful not only for timing expansion, but also for judging whether that expansion is still healthy or beginning to lose structure.
🔷 WHO THIS MAY BE USEFUL FOR
This script may be useful for traders who want to:
- track volatility compression and release in a dedicated oscillator pane
- filter squeeze releases by actual momentum quality
- distinguish stronger directional expansion from weaker post-release drift
- pair volatility timing with structure, trend, VWAP, or support/resistance analysis
- reduce overreaction to every simple zero-line shift
- organize post-squeeze behavior more cleanly in discretionary workflows
It is especially suitable for users who like the squeeze concept, but want more context than a traditional dot-plus-histogram implementation.
🔷 KEY INPUTS
Core settings include:
- BB Length
- BB StdDev
- KC Length
- KC ATR Multiplier
- True Range toggle for Keltner construction
Momentum settings include:
- Equilibrium Length
- Velocity Length
- Momentum Smoothing
- Adaptive Band Length
- Burst Band Multiplier
Visual and workflow settings include:
- Adaptive momentum zones
- Signal line
- Histogram width
- Release boxes
- Release box persistence
- Label spacing
- Label size
- Panel position
- Theme
- Panel font size
This gives users enough control to adapt the script to different symbols and timeframes without turning the interface into a settings overload.
🔷 LIMITATIONS AND TRANSPARENCY
This indicator is a chart-analysis tool.
It is not a guarantee of breakout continuation, not a prediction engine, and not a substitute for trade planning or risk management.
A few important points should be kept in mind:
- A squeeze can resolve in either direction.
- A valid release can still fail.
- Strong momentum can cool without immediately reversing.
- Some instruments will produce noisier momentum behavior than others.
- Settings may need adjustment depending on timeframe, volatility regime, and instrument structure.
The script is best treated as a decision-support layer for reading volatility expansion and momentum quality more clearly.
It is not presented as a standalone trading system.
🔷 IN ONE SENTENCE
Squeeze Momentum Indicator is designed to show not only when volatility is ready to move, but whether the actual post-squeeze move is carrying enough directional pressure, quality, and persistence to deserve attention. Indicator

Level Survival Map [AGPro Series]Level Survival Map
🔹 Overview
Level Survival Map is a premium support and resistance framework that does not just draw lines on the chart. Every detected level carries a live Survival Score between 0 and 100 that answers one simple question: how well is this level still defending itself right now. The map highlights a single Active Level with an interaction zone and a forward projection ribbon, while nearby weaker levels fade, so traders always know which level actually matters for the current decision.
🔸 Unique Edge
Most support and resistance tools either show static pivots or basic break or retest events. Level Survival Map goes further by measuring the quality of every interaction and turning it into a single composite health score per level. Instead of being left with a wall of equally important lines, the trader sees a ranked structural battlefield with one clearly identified Active Level, a visible interaction zone and a projection ribbon for planning. The Damage State readout, the Fresh and Eroded state semantics, the automatic flip from broken support to new resistance and the cluster fade for crowded weaker levels are designed to work together as one premium, low-noise workflow.
🔹 Methodology
Pivot detection builds the raw candidate levels from swing highs and swing lows using the standard pivot window. A merge filter removes duplicates that sit within a configurable ATR distance of an existing same-type level. Each active level then accumulates four independent components over time. Close Respect rewards closes that respect the level side, for example closes above a support. Penetration Damage penalises wicks and bodies that pierce through the level zone. Reaction Quality rewards strong rejection wicks and bodies moving away from the level after a test. Test Fatigue penalises repeated tests because levels tend to weaken with each new hit. These four components are weighted and combined into a single Survival Score, then clamped between 0 and 100. A structural break caps the score at 35, heavy damage across multiple tests caps it at 28, and a confirmed sequence of opposite-side closes flips the level type while resetting its history. The Active Level is chosen as the closest same-side level to price so that the focus always follows the real decision point.
🔸 Signals and Alerts
The visual output itself is the primary signal. Line colour and thickness communicate level strength at a glance. A focused Active Level is drawn with an interaction zone, a darker core band and a forward projection ribbon so that traders can see the exact price band where reaction is most likely, and how far into the future that band is expected to remain relevant. Labels carry the Survival Score directly, so the ranking of levels is always visible without opening any settings. Broken levels switch to a dashed style and faded colour, and once enough opposite-side closes accumulate they flip type automatically, giving a clear visual signature of structural change.
🔹 Key Inputs
Pivot Left Bars and Pivot Right Bars control how strict the swing detection is. Max Active Levels caps how many concurrent levels are tracked. Level Merge Distance and Interaction Zone are expressed in ATR units so the logic adapts across timeframes and instruments. Scoring weights for Close Respect, Penetration Damage, Reaction Quality and Test Fatigue can be tuned independently, together with the fatigue penalty per extra test and the number of closes required to confirm a flip. Visual inputs cover panel position, label size, line width, focus emphasis, non-focus transparency, cluster fade, focus zone width and projection ribbon length and thickness. A Clean Map Mode is provided for screenshot and publishing workflows where only the Active Level and the nearest valid support and resistance are labelled.
🔸 How to Use
Read the map top down. First, look at the summary panel for the Active Level, its Survival Score, Test Count and Damage State. A Fresh or Strong Active Level defending its side is a high-quality decision point. A Fragile or Eroded Active Level with a Severe Damage State is a warning that the next level below or above is likely to take over. Use the projection ribbon as a planning band for reaction rather than a mechanical entry. Use the ranked non-Active labels to understand where price is likely to travel if the Active Level gives way. The tool is designed to be used as a visual framework, in combination with the trader own execution method, trend context and risk management.
🔹 Limitations and Transparency
This indicator is a visual analytical framework, not a strategy, not a signal service and not financial advice. Survival Score, Damage State and flip logic are deterministic functions of price action and ATR, so different markets and timeframes will produce different characteristic score ranges. Pivot based detection is inherently lagging by the Pivot Right Bars window, which is the expected behaviour of any structural tool and not a defect. The Active Level projection ribbon is a visual planning aid, not a forecast. Past level behaviour does not guarantee future behaviour.
🔸 Risk Disclosure
Trading involves substantial risk and is not suitable for every investor. This script is published for educational and analytical purposes only. Users are solely responsible for their own trading decisions, position sizing and risk management. Always test any tool on your own instruments and timeframes before using it in a live environment. Indicator

Dynamic Trend Pivots [BOSWaves]Dynamic Trend Pivots - Conviction-Driven Trend Detection with Pulse-Adaptive Exhaustion Level Mapping
Overview
Dynamic Trend Pivots is a conviction-based trend identification and structural level mapping system that tracks directional price commitment through a pulse accumulation engine, where band width, trend confidence, and exhaustion level placement are driven by real-time measurement of close-position conviction across consecutive bars rather than arbitrary moving average relationships or fixed volatility multiples.
Instead of relying on standard crossover logic or static band thresholds, trend state, adaptive band behavior, and exhaustion level generation are determined through bar-level conviction scoring, pulse saturation modeling, and peak-to-trough saturation drop detection that identifies genuine momentum exhaustion events as they occur.
This creates a trend framework that reflects actual directional commitment rather than lagged price averages - tightening bands during high-conviction pulse saturation when trend confidence is elevated, expanding bands as conviction decays and directional commitment weakens, and planting structural exhaustion levels at the precise price points where pulse energy peaked before collapsing, marking locations of maximum prior commitment for future reference.
Price is therefore evaluated against bands and structural levels that respond to measurable conviction dynamics rather than conventional indicator thresholds.
Conceptual Framework
Dynamic Trend Pivots is founded on the principle that meaningful trend signals and structural reference levels emerge from the accumulation and exhaustion of bar-level directional conviction, not from price crossing smoothed averages or breaching fixed statistical bands.
Traditional trend-following approaches identify directional changes through indicator crossovers or band penetrations that treat all bars equally regardless of their internal structure and conviction quality. This framework replaces undifferentiated price-level logic with conviction-weighted pulse tracking that distinguishes between bars demonstrating genuine directional commitment and bars that merely move price without close-position confirmation.
Three core principles guide the design:
Trend conviction should be measured through close positioning within the bar range combined with directional agreement, not through price displacement alone.
Band width must dynamically reflect pulse saturation state, contracting during high-conviction conditions and expanding as conviction decays.
Structural reference levels should be planted at exhaustion events — the precise price points where accumulated conviction peaked before collapsing — rather than at arbitrary pivot formations.
This shifts trend analysis from static threshold detection into a continuously updating conviction framework anchored in measurable bar-level directional commitment.
Theoretical Foundation
The indicator combines close-position conviction measurement, pulse accumulation and decay modeling, MAD-based adaptive band construction, and saturation peak tracking for exhaustion event detection.
Conviction bars are identified through close positioning within the bar range: a bull conviction bar closes in the upper fraction of its range on an up-close bar, and a bear conviction bar closes in the lower fraction on a down-close bar. A pulse counter accumulates these conviction readings up to a configurable saturation cap, while decaying exponentially between conviction events. Saturation drives the band multiplier interpolation between tight and wide settings, reflecting real-time trend confidence. Exhaustion detection monitors saturation's relationship to its recent peak, planting structural levels when saturation drops sufficiently from that peak.
Four internal systems operate in tandem:
Pulse Accumulation Engine : Evaluates each bar for directional conviction based on close positioning within the high-low range, accumulating bull and bear pulse counters independently with configurable decay between conviction events.
Saturation Measurement System : Converts raw pulse counts into a normalized saturation reading relative to the pulse cap, providing the continuous 0-1 conviction metric that drives all adaptive behavior.
MAD Adaptive Band Construction : Applies Mean Absolute Deviation-scaled bands around an EMA baseline, with the band multiplier dynamically interpolating between minimum and maximum settings based on current saturation.
Exhaustion Level Engine : Tracks saturation peaks with their associated price and direction, planting structural zone levels when saturation drops below a configurable fraction of its recent peak, with lifecycle management including break detection, zone extension, and retest identification.
This design allows trend confidence and structural reference levels to reflect actual conviction dynamics rather than responding mechanically to price or indicator crossovers.
How It Works
Dynamic Trend Pivots evaluates price through a sequence of conviction-aware processes:
Conviction Bar Classification : Each bar's close position within its high-low range is measured; bars closing in the upper fraction on an up-close qualify as bull conviction bars, and bars closing in the lower fraction on a down-close qualify as bear conviction bars.
Pulse Counter Update : Bull or bear pulse counters increment by one on each qualifying conviction bar up to the saturation cap, and decay multiplicatively by the configured decay rate when conviction bars are absent.
Saturation Calculation : The dominant pulse counter (bull or bear) divided by the pulse cap yields a normalized saturation value, with signed directional pulse providing the complete conviction state.
Saturation Peak Tracking : The system continuously monitors saturation, recording the peak value, direction, associated price level (high for bull, low for bear), and bar index when each new saturation maximum is established.
Exhaustion Event Detection : When current saturation drops below the configured fraction of the recorded saturation peak, an exhaustion event fires, triggering structural level placement at the recorded peak price.
Adaptive Band Construction : The band multiplier interpolates between the minimum (saturated, tight) and maximum (exhausted, wide) settings based on current saturation, scaling MAD to determine upper and lower band distances from the EMA baseline.
Trend State Logic : Price crossing above the raw upper band triggers bullish state; crossing below the raw lower band triggers bearish state; state persists until the opposite breach occurs.
Signal Generation : State transitions from bearish to bullish produce buy labels; bullish to bearish transitions produce sell labels, both plotted at MAD-scaled offsets from price.
Exhaustion Level Lifecycle : Planted levels extend rightward with zone boxes, dashed midlines, and price labels until price closes beyond the zone boundary with ATR buffer confirmation, at which point the level is removed.
Retest Detection : When price re-enters an active exhaustion zone after the minimum origin bar offset, a retest signal fires with a configurable cooldown enforced between subsequent retests on the same level.
Together, these elements form a continuously updating conviction map that simultaneously tracks trend state and marks the structural fingerprints left by exhausted momentum.
Interpretation
Dynamic Trend Pivots should be interpreted as a conviction-weighted trend framework with exhaustion-derived structural reference levels:
Bullish Trend State (Green) : Established when price closes above the raw adaptive upper band, indicating a conviction-supported upward directional breach.
Bearish Trend State (Magenta) : Established when price closes below the raw adaptive lower band, signaling a conviction-supported downward directional breach.
Band Cloud : Visual gradient zone fills between the outer band edge and close, with opacity and color reflecting current trend state and providing a continuous conviction boundary reference.
Band Width Dynamics : Tight bands indicate high pulse saturation (elevated conviction), while wide bands reflect saturation decay (diminished conviction and increased caution).
▲ Buy Signals : Green upward triangles mark bullish state initiations at upper band crossovers, plotted below the bar at a MAD-scaled offset.
▼ Sell Signals : Red downward triangles mark bearish state initiations at lower band crossunders, plotted above the bar at a MAD-scaled offset.
Exhaustion Zone : ATR-scaled rectangular zones centered on the saturation peak price mark prior conviction exhaustion locations, with colored borders and subtle fills distinguishing bull from bear exhaustion origin.
Exhaustion Midline : Dashed line through the precise saturation peak price within each zone provides a high-precision structural reference at the exact level of maximum prior conviction.
◆ Origin Marker : Diamond label plotted on the bar where each exhaustion event occurred, marking the conviction peak location for retrospective analysis.
✦ Retest Signals : Small star diamonds mark price re-entry into active exhaustion zones after the origin buffer period, identifying potential reaction points within proven conviction regions.
Retest Extension Lines : Horizontal lines projected forward from retest bar highs or lows mark the retest price level for ongoing reference.
Colored Candles : Optional bar coloring reflects trend state and fades toward neutral as saturation decays, providing an immediate visual exhaustion cue. Note: The original chart candles must be disabled in chart settings for the conviction-colored candles to display properly.
Saturation state, band width dynamics, and exhaustion level proximity outweigh isolated price movements in isolation.
Signal Logic & Visual Cues
Dynamic Trend Pivots presents two primary trend interaction signals alongside a continuous exhaustion level monitoring system:
Buy Signal (▲) : Green triangle appears when trend state switches from bearish to bullish via upper band crossover, indicating conviction-supported directional shift to the upside.
Sell Signal (▼) : Red triangle displays when trend state switches from bullish to bearish via lower band crossunder, indicating conviction-supported directional shift to the downside.
Exhaustion zone retests provide secondary structural signals when price revisits prior conviction peak regions after the minimum origin offset, subject to per-level cooldown enforcement.
Alert generation covers bullish and bearish state switches, exhaustion events triggering new level placement, and both bullish and bearish retest occurrences for systematic structural monitoring.
Strategy Integration
Dynamic Trend Pivots fits within conviction-informed and structural level-based trading approaches:
Conviction-Confirmed Entries : Use band crossover signals as trend initiation points where saturation-supported conviction has driven price through the adaptive boundary, rather than acting on low-conviction crossovers during band expansion.
Saturation-Based Position Sizing : Scale exposure relative to current pulse saturation — favor larger positions during high-saturation fresh trend conditions and reduce sizing as conviction decays and bands widen.
Band-Width Risk Calibration : Expect tighter price ranges and more reliable directional follow-through during contracted band periods; treat expanded bands as a signal of reduced trend reliability requiring tighter risk management.
Exhaustion Level Trade Planning : Use planted exhaustion zones as anticipatory structural levels — price reactions at these zones reflect the influence of the same conviction dynamics that originally caused the momentum peak and collapse.
Retest-Based Re-entry : Treat exhaustion zone retests as lower-risk re-entry or continuation opportunities within established trends, using the midline as a precision reference for entry and invalidation.
Multi-Timeframe Conviction Hierarchy : Apply higher-timeframe trend state and exhaustion level locations as directional bias filters while using lower-timeframe pulse signals for entry precision.
Technical Implementation Details
Core Engine : EMA-based trend baseline with MAD volatility measurement
Conviction Model : Close-position ratio within high-low range with directional agreement gating
Pulse System : Capped accumulation with configurable multiplicative decay between conviction events
Band Construction : Linear interpolation between min/max multipliers based on saturation, scaling MAD offset from EMA baseline
Exhaustion Detection : Saturation peak tracking with configurable drop threshold triggering level placement
Visualization : Gradient-filled band cloud with ATR-scaled exhaustion zones, dashed midlines, and retest extension lines
Signal Logic : Raw band crossover state-switch detection with saturation-faded candle coloring
Performance Profile : Optimized for real-time execution with configurable level caps managing object count
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Micro-structure conviction tracking for scalping with responsive pulse and tight band settings
15 - 60 min : Intraday trend identification with balanced decay characteristics and moderate exhaustion sensitivity
4H - Daily : Swing-level conviction trend mapping with sustained pulse persistence and wider exhaustion zone tolerance
Suggested Baseline Configuration:
Trend Length : 21
Close Zone : 0.30
Pulse Decay : 0.85
Pulse Cap : 8
MAD Length : 17
Band Min (Saturated) : 1.4
Band Max (Exhausted) : 2.2
Exhaustion Drop : 0.4
Max Levels : 8
Break Buffer (ATR) : 0.25
Show Band Cloud : Enabled
Color Candles : Enabled (requires disabling original chart candles in chart settings)
Show Buy/Sell Signals : Enabled
These suggested parameters should be used as a baseline; their effectiveness depends on the instrument's volatility characteristics, conviction frequency, and preferred signal density, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Excessive signal noise : Increase Trend Length for a smoother baseline or tighten Close Zone toward 0.2 to demand more extreme close positioning before conviction is registered.
Missed conviction events : Widen Close Zone toward 0.4 for more inclusive bar qualification or decrease Trend Length for a more reactive baseline.
Pulse sustains too long : Decrease Pulse Decay toward 0.5 for faster conviction fade between qualifying bars, accelerating band expansion during low-conviction periods.
Pulse fades too quickly : Increase Pulse Decay toward 0.99 to sustain saturation longer between conviction events, maintaining tighter bands through minor pullbacks.
Bands too tight or wide across the board : Adjust Band Min and Band Max multipliers to rescale the full saturation-to-exhaustion band range for the instrument's volatility characteristics.
Too many exhaustion levels forming : Increase Exhaustion Drop threshold toward 0.6 to demand a more severe saturation collapse before a level is planted, filtering for higher-conviction exhaustion events only.
Levels not forming frequently enough : Decrease Exhaustion Drop toward 0.2 to plant levels on more modest saturation pullbacks, increasing structural level density.
Levels breaking too easily : Increase Break Buffer ATR multiplier to require a more decisive close beyond the zone boundary before invalidation occurs.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
Trending markets with clear conviction phases where pulse saturation builds and sustains before exhausting at structural turning points
Instruments with consistent bar structure where close positioning within the range reliably reflects directional commitment
Momentum continuation strategies entering on fresh pulse saturation signals with contracted bands
Structural level frameworks benefiting from exhaustion-derived reference zones rather than arbitrary pivot-based support and resistance
Reduced Effectiveness:
Choppy, low-conviction environments where close positioning provides unreliable directional signals and pulse saturation builds and collapses rapidly without sustained directional follow-through
Extremely gapped or news-driven markets where bar range structure becomes discontinuous and close positioning loses meaningful conviction interpretation
Mean-reversion dominant conditions where band breaches quickly reverse without sufficient pulse saturation to sustain directional state
Low-volatility compression periods where MAD scaling produces narrow bands that generate frequent false crossovers
Consolidation and sideways conditions where conviction builds in alternating directions without achieving the sustained saturation required for reliable trend state establishment
Integration Guidelines
Confluence : Combine with BOSWaves order flow tools, volume analysis, or multi-timeframe structure indicators for layered confirmation
Saturation Respect : Prioritize signals and level interactions occurring during high-saturation periods; treat low-saturation crossovers and retests with reduced confidence
Exhaustion Awareness : Monitor candle fade coloring as an early warning of declining conviction before formal signal generation confirms a state change
Level Hierarchy : Treat exhaustion levels planted during peak saturation events as higher-conviction structural references than levels formed during moderate saturation peaks
Retest Discipline : Use exhaustion zone retests as continuation confirmation rather than reversal triggers unless accompanied by opposing band crossover signals
Disclaimer
Dynamic Trend Pivots is a professional-grade conviction analysis and structural level mapping tool. It uses pulse accumulation modeling with adaptive band construction and exhaustion-driven level placement but does not predict future price movements. Results depend on market conditions, instrument conviction characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates order flow context, volume analysis, and comprehensive risk management. 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

Delivery Regime Map [AGPro Series]Delivery Regime Map
🔹 Overview
Delivery Regime Map classifies the market's delivery character into four distinct regimes — Balanced, Directional, Fragmented, and Exhausted — giving traders instant context on whether the tape is trending with conviction, consolidating, breaking into volatile chop, or fading after an extended move. Rather than asking "is this bullish or bearish?", DRM answers a more useful question: "what kind of market am I in, and what kind of setup is appropriate here?"
The indicator overlays a soft state ribbon across the chart, prints confirmed regime shift labels at the moment of transition, and maintains a compact status panel with the active regime, a composite conviction score, regime duration, and time since the last shift. All outputs are confirmed on bar close with dwell-based hysteresis to suppress noise.
🎯 Unique Edge
Most regime or trend-strength tools collapse the market into a single linear axis (strong ↔ weak, bullish ↔ bearish). Delivery Regime Map is categorical, not linear — it identifies the qualitative character of price delivery by fusing four independent dimensions:
• Displacement quality (how much of each bar's range is body vs. wick)
• Directional persistence (close-to-close consistency + EMA slope alignment)
• Continuity (same-side runs penalized by gap noise)
• Range expansion (current range normalized by ATR baseline)
These dimensions combine into a composite score, but the regime classification uses banded thresholds with hysteresis — meaning a Directional tape must decisively lose its edge before flipping to Fragmented or Exhausted. This produces sparse, high-conviction transitions rather than the constant flipping typical of single-value strength meters.
⚙️ Methodology
The engine computes five rolling metrics across a user-defined window (default 20 bars):
1. Displacement Quality — |close − open| / range, smoothed. High values mean strong, decisive bars with minimal wick rejection.
2. Directional Persistence — average signed close direction plus an EMA slope-alignment check. Rewards tapes that move one way without reversing.
3. Continuity — the proportion of consecutive same-side candles, penalized by an average gap-size term (opens far from prior closes indicate fractured delivery).
4. Range Expansion — current range vs. ATR baseline, clipped to . High expansion combined with low continuity flags Fragmented tapes.
5. Exhaustion Proxy — the decay rate of displacement quality after a period of high persistence. Triggers near trend terminations where bars shrink while direction lingers.
A classifier selects the active regime by priority (Directional → Exhausted → Fragmented → Balanced), and a dwell-bar confirmation (default 5 bars, or 8 under Strict mode) plus a minimum-gap filter (default 10 bars) prevent whipsaw transitions.
🚦 Signals & Alerts
Four alert conditions are built in, each firing only on a confirmed regime shift:
• Regime shifted to Directional — conviction is rising; the tape is trending
• Regime shifted to Fragmented — wide, disconnected bars; chop risk elevated
• Regime shifted to Exhausted — prior trend is losing steam; mean-reversion risk
• Regime shifted to Balanced — low-conviction state; breakout potential building
All alerts include the ticker and interval in the message payload.
🎛️ Key Inputs
• Regime Window (8–60) — length of the measurement window
• Regime Sensitivity (Low / Normal / High) — hysteresis band width
• Strict Classifier — extends dwell requirement from 5 to 8 bars
• Minimum Bars Between Shifts — anti-chop spacing filter
• Show State Ribbon / Regime Shift Labels — visual toggles
• Panel Position + Font Size — 6 anchor positions, 5 size options
• Label Font Size — matches user's chart density preference
Every input carries an inline tooltip explaining its behavior and tradeoffs.
📚 How to Use
• Use Directional regimes to favor trend-following entries and trailing stops
• Use Balanced regimes to prepare for breakouts; volatility compression often precedes expansion
• Use Fragmented regimes as a caution flag — reduce size, widen stops, or stand aside
• Use Exhausted regimes to tighten trailing stops on open trend positions; the edge may be fading
DRM is designed to be asset-agnostic and timeframe-agnostic. On lower timeframes (1m–15m), consider Strict mode and a larger minimum-gap value. On daily charts, defaults typically work well. Combine with any entry framework — order blocks, breakout levels, VWAP reclaims — as a regime filter that answers "should I even be looking for a setup here?"
⚠️ Limitations & Transparency
• The classifier is reactive, not predictive — it confirms regime changes on close, so a Directional label appears a few bars after the trend has begun. This is by design: dwell confirmation is the primary noise filter.
• Regime definitions are categorical interpretations of price statistics. They are not forecasts.
• The composite score reflects regime conviction, not directional bias. A high score in Fragmented means "confidently choppy", not "confidently bullish".
• This indicator is not a strategy. It produces no entry signals, no take-profit targets, and no stop-loss levels. It is a market-context tool intended to be combined with a trader's existing framework.
• Past regime behavior does not guarantee future regime behavior. Market character can change abruptly on news or macro events.
📜 Risk Disclosure
This indicator is published for educational and analytical purposes only. It does not constitute financial advice, a trading recommendation, or an offer to buy or sell any instrument. Trading and investing carry risk of loss, and past performance does not guarantee future results. Users are solely responsible for their own decisions and should consult qualified professionals before committing capital. Indicator

Trend Stability Ribbon [AGPro Series]Trend Stability Ribbon
🔹 OVERVIEW
Most trend tools tell you WHICH WAY price is going. Trend Stability Ribbon tells you HOW WELL it is getting there. By pairing an ATR-normalized slope engine with a Kaufman path-efficiency score, it projects every bar into one of four rules-based states — Stable Up, Noisy Up, Stable Down, Noisy Down — and paints them onto a clean, adaptive ribbon that stays out of the candles' way. The result is a context layer that separates decisive trending from directional-but-choppy travel, without adding a second indicator pane.
🧭 UNIQUE EDGE — WHY THIS IS NOT "JUST ANOTHER TREND INDICATOR"
Direction alone is cheap. Every moving-average cross, every supertrend, every slope color tells you "up" or "down" — and then leaves you holding the bag when the trend is technically up but structurally a mess.
Trend Stability Ribbon adds the missing second dimension: path quality. The same 34-bar window that defines direction also feeds a Kaufman efficiency calculation (net travel divided by total path travel). An ER near 1.00 means price walked a near-straight line; an ER near 0.00 means it zig-zagged its way to the same point. Mapping that score against a calibrated threshold band produces the four composite states — and a visual language that finally distinguishes "trend worth trusting" from "trend worth fading".
Additional design choices that set it apart:
• Dual-layer event engine — direction flips, stability upgrades, and stability downgrades are tracked as independent transitions, each with its own alert.
• Badge/alert separation — on-chart badges are throttled by a cooldown for visual hygiene, but alerts are always raw so automation pipelines never miss an event.
• Reset state — when the slope-confirmation filter rejects a direction, the ribbon goes neutral instead of flipping false. Chop gets ignored, not misreported.
🧪 METHODOLOGY
1. TREND DIRECTION ENGINE
• A slow EMA (default length 34) anchors the trend path and serves as the ribbon centerline.
• Slope is measured over a 3-bar lookback and normalized by a 14-period ATR, making it instrument-agnostic across crypto, FX, equities, and futures.
• With Slope Confirmation enabled (default), direction is only accepted when price position AND slope agree. Disagreement returns a Reset state.
2. PATH EFFICIENCY (STABILITY) ENGINE
• ER = |close − close | ÷ Σ|close − close | over the same trend window.
• Three classes: Stable (ER ≥ 0.45), Noisy (ER ≤ 0.25), Mixed (between). Thresholds scale with the Stability Sensitivity input.
• The Mixed zone is a deliberate dead-band — during uncertain phases the previous state persists rather than flickering.
3. COMPOSITE STATE MACHINE
• Direction × Stability yields five possible states: Stable Up, Noisy Up, Stable Down, Noisy Down, Reset.
• Bars-in-state is tracked live, giving a simple persistence read on each state.
4. RIBBON RENDERING
• Ribbon is anchored to the EMA centerline with height driven by ATR × a user-selected multiplier (Thin / ATR-Adaptive / Thick).
• Fill opacity and border weight shift by state — Stable states are saturated, Noisy states are faded, Reset is a soft amber.
🔔 SIGNALS & ALERTS
Three transition events are detected and exposed as separate, user-toggled alerts:
• Trend State Flipped — direction changed (Up ↔ Down). Raw, never throttled.
• Stability Improved — path upgraded from Noisy to Stable while direction held. Raw — delivered regardless of badge cooldown.
• Stability Degraded — path downgraded from Stable to Noisy while direction held. Raw — delivered regardless of badge cooldown.
Matching on-chart badges appear at the same moments, subject to the Stability Badge Cooldown for visual cleanliness. Direction-flip badges are never throttled.
⚙️ KEY INPUTS
Engine
• Trend Length (default 34) — lookback for both direction and path-efficiency windows.
• Stability Sensitivity (default 1.0) — scales the Stable / Noisy thresholds.
• Require Slope Confirmation (default on) — enforces price-and-slope agreement; rejects chop.
Ribbon & Badge
• Ribbon Height — Thin / ATR-Adaptive / Thick.
• Show State Badge — toggle on-chart transition labels.
• Label Font Size — tiny / small / normal / large (default normal).
• Minimal Mode — hides panel and badges for pairing with other overlays.
• Stability Badge Cooldown (default 5 bars) — visual throttle for stability transitions.
Info Panel
• Panel Position, Panel Font Size, Efficiency Ratio display, Active Thresholds display.
Alerts
• Independent toggles for each of the three transition events.
🧠 HOW TO USE
• CONTEXT FILTER — use Stable states as a "green light" for continuation setups on your primary system; treat Noisy states as a headwind.
• REGIME BREAKS — a Stability Degraded event mid-trend is often an early warning that the move is maturing, even before price has flipped.
• CLEAN ENTRIES — pair a direction flip (Trend Up / Trend Down) with an immediate Stable classification to filter out whipsaw-prone breakouts.
• CHOP AVOIDANCE — when the ribbon sits in a Reset or Mixed state, the script is telling you the underlying path is not tradeable as a trend. Stand aside or switch to range tactics.
• PAIRING — with Minimal Mode on, the ribbon layers cleanly under structure tools, VWAPs, or S/R zones without visual conflict.
⚠️ LIMITATIONS & TRANSPARENCY
• This is an indicator, NOT a strategy. It does not generate buy or sell orders, has no backtest, and makes no claim of performance.
• Efficiency Ratio is a lagging measure — it describes the path already travelled. The ribbon should be read as context, not as a leading signal.
• The Mixed zone is intentional persistence; expect the composite state to hold through brief chop rather than flipping on every bar.
• Lower timeframes (<5m on thin-liquidity markets) can push ER values into erratic ranges. Start with the defaults on 15m–4h and tune from there.
• All calculations are closed-bar. Intra-bar values may shift until the bar confirms.
🛡️ RISK DISCLOSURE
This script is published for educational and analytical purposes only. It is not financial advice, not a signal service, and not a solicitation to buy or sell any instrument. Past behavior of markets does not predict future results. Always do your own research, apply proper risk management, and consult a licensed professional before making trading decisions. The author assumes no responsibility for losses incurred through use of this indicator. Indicator

Haar Wavelet RSI [Jamallo]Author's Note
This is the oscillator companion to the Haar Wavelet Range Filter. Both indicators share the same MODWT Haar wavelet foundation, creating a synergistic effect when used together — trend and momentum derived from the same mathematical decomposition of price.
Introduction
The Haar Wavelet RSI is a momentum oscillator that replaces the standard price-difference input of a traditional RSI with wavelet detail coefficients derived from a Maximal Overlap Discrete Wavelet Transform (MODWT) with a Haar basis. Instead of measuring bar-to-bar price change, it measures momentum at a specific frequency scale — filtering out the noise above and below that scale before the RSI calculation even begins.
How It Works
MODWT Haar Wavelet Decomposition
The script decomposes hl2 through up to 5 wavelet levels using a shift-invariant Haar transform. At each level, the detail coefficients capture the local price delta at that specific scale — Level 1 is 2-bar momentum, Level 3 is 8-bar momentum, Level 5 is 32-bar momentum. These detail coefficients become the input to the RSI in place of raw price change, meaning the oscillator is measuring directional energy at a single isolated frequency rather than the full noisy price series.
Wavelet RSI Calculation
The selected detail coefficient is split into its upward and downward components, smoothed with Wilder's RMA, and fed into the standard RSI formula. The math is identical to a conventional RSI — the only difference is what it is measuring. Because the detail coefficients are already frequency-isolated, the resulting RSI is inherently cleaner than applying RSI to raw price.
Adaptive Deadband Step-Hold
The wavelet RSI output is then passed through an adaptive deadband filter. The threshold is self-derived from the RSI's own recent volatility — a short rolling average of absolute RSI changes — scaled by the deadband multiplier. The RSI only updates when it departs from its held value by more than this threshold. Below the threshold it holds flat. This eliminates the continuous micro-oscillation that makes standard RSI difficult to read on noisy bars, producing a stepped line that moves with conviction or not at all.
Closing
This is not a standard RSI with cosmetic changes. The wavelet decomposition fundamentally changes what the oscillator is measuring — momentum at a defined frequency scale rather than raw bar-to-bar noise. The decomposition level is the most important setting: lower levels suit faster timeframes and shorter momentum cycles, higher levels filter more aggressively and are better suited to swing-level momentum reads. Indicator

Adaptive Keltner Channel [NovaLens]Adaptive Keltner Channel detects when price is doing something exceptional versus simply moving within its expected range. It wraps price in ATR-based bands around an EMA center, optionally adjusts band width to the current volatility regime, and includes built-in squeeze detection and context-aware center reclaim signals.
════════════════════════════════════════════
◉ HOW IT WORKS
The indicator builds on the Keltner Channel concept introduced by Chester Keltner (1960) and refined into the modern ATR-based variant by Linda Bradford Raschke:
Center line : EMA of close
Upper band : Center + multiplier x ATR
Lower band : Center - multiplier x ATR
In static mode, the multiplier is fixed:
Upper = EMA(Close, Length) + Multiplier x ATR
Lower = EMA(Close, Length) - Multiplier x ATR
In adaptive mode, the multiplier scales with the current ATR percentile rank. When ATR is low relative to recent history, the channel widens to filter routine noise. When ATR is already elevated, the channel tightens so a band break still represents a genuine expansion rather than getting absorbed inside an overly wide envelope.
This is the opposite of how Bollinger Bands behave. Bollinger Bands widen mechanically as volatility rises because they use standard deviation. The adaptive Keltner deliberately tightens its multiplier in high-vol regimes to preserve the usefulness of a breakout signal across different conditions.
The script also includes squeeze detection: when Bollinger Bands contract inside the Keltner Channel, it flags that volatility has compressed. Compressed conditions can precede larger-than-normal moves, though the squeeze does not indicate which direction or guarantee that the expansion will follow through.
════════════════════════════════════════════
◈ HOW TO READ IT
Band interactions:
Price above upper band: upside expansion beyond the recent channel range
Price below lower band: downside expansion beyond the recent channel range
Center reclaims and losses:
Price reclaims center after a lower-band touch: downside extension did not hold
Price loses center after an upper-band touch: upside extension did not hold
These are not simple center crosses. The indicator tracks which band was touched most recently and only fires a reclaim or loss signal when that context is present. A center cross after sideways consolidation is a different event from a center cross following a failed band extension. This logic filters out a significant amount of the noise that makes naive center-cross signals unreliable.
Squeeze and trend:
Orange fill and center color: squeeze is active, volatility compressed
Squeeze intensity builds visually as the compression persists
Green center line: short-term trend pressure is up
Red center line: short-term trend pressure is down
Teal X-cross marker below bar: squeeze just released
The outer bands are intentionally neutral gray. Direction comes from price behavior, center slope, and the interaction signals.
════════════════════════════════════════════
✦ HOW WE USE IT: VOLATILITY CONTEXT
We use this channel as a volatility context layer rather than a standalone signal source. The question it answers: is the current price behavior routine or exceptional for this market's recent history?
When the channel is in squeeze state and the info panel reads "Compressed" with the bar count climbing, that is a low-conviction environment for new directional entries but a high-attention environment for preparation. On BTC 4H with Balanced settings, in our observation squeeze conditions often persist for 8-15 bars while the fill gradually deepens to orange. During that window, we are watching, not acting.
When the squeeze releases and price pushes through a band with the center slope already confirming, that combination (squeeze release, band break, center slope alignment) carries more weight than a random band break during an already-volatile session. No single element alone is the trigger.
On the reversion side, when price flushes to the lower band and then reclaims the center, the state-aware logic recognizes that the last band touched was the lower band. It treats that center cross as a meaningful reclaim rather than noise. This matters because price often consolidates between a band touch and the center for several bars. A naive center-cross indicator would miss the connection. This one remembers.
The practical workflow: use the channel to characterize whether price is inside its expected range, expanding beyond it, or compressed. Layer your directional signals on top of that context.
════════════════════════════════════════════
✦ OTHER APPLICATIONS
Breakout context : band breaks after compression, confirmed by center slope and price acceptance on subsequent bars
Mean reversion : in sideways conditions, band touches can frame moves back toward the center, especially when the center line is flat rather than sloped
Trend pullbacks : the center line as a dynamic support/resistance during directional moves
Risk management : use the center or opposite band as a trailing reference that adapts to current volatility
Alert-driven workflow : set alerts on squeeze start, squeeze release, breakout up/down, or center reclaim/loss and check the chart only when conditions change
════════════════════════════════════════════
⚙ GETTING STARTED
Adaptive Keltner Channel ships with reactivity presets:
Reactive : EMA 10 / Mult 1.5 / ATR 10. Tighter bands that respond quickly. Useful when you want the channel to track recent behavior more closely.
Balanced : EMA 20 / Mult 2.0 / ATR 14. The default. A reasonable starting point for most assets. Start here unless you have a specific reason not to.
Smooth : EMA 50 / Mult 2.5 / ATR 20. Wider and calmer. Useful on higher timeframes or when you want the channel to only flag larger-scale events.
Custom : Full manual control for specific setups.
Core settings:
Reactivity : selects the behavior profile. Start with Balanced.
Adaptive Band Width : on = regime-aware scaling, off = classic static Keltner. The difference is most visible when the market transitions between calm and volatile periods.
Adaptive Lookback : how far back ATR is ranked. 100 bars covers roughly 5 months on daily, 4 days on 1H. Increase for assets with long volatility cycles. Decrease for assets that shift regimes quickly.
Adaptive tuning:
Adaptive Max Multiplier (calm) : scales your base multiplier up in quiet conditions. Default 1.25 means the effective multiplier becomes 25% wider than the base (e.g., base 2.0 becomes 2.5). Increase if you are seeing too many false band touches during low-vol periods.
Adaptive Min Multiplier (vol) : scales your base multiplier down in volatile conditions. Default 0.75 means the effective multiplier becomes 25% narrower than the base (e.g., base 2.0 becomes 1.5). Decrease if breakouts are still not clearing the bands during high-vol sessions.
Squeeze settings:
Show Squeeze Detection : enables Bollinger-inside-Keltner squeeze logic
BB Length / BB Multiplier : default 20/2.0 matches standard Bollinger. Generally no reason to change unless comparing against a non-standard Bollinger on the same chart.
Display:
Show Info Panel : 4-row panel showing current state, volatility, trend direction, and price location as a channel percentage. Hover any label for a plain-English explanation.
Show Squeeze Background : subtle background tint during active squeezes. Off by default.
Light Theme Mode : adapts panel colors for light backgrounds.
════════════════════════════════════════════
△ LIMITATIONS
Lagging structure : the center is an EMA and the bands use historical ATR. Sharp reversals can outrun the channel. This is inherent to any channel overlay.
Squeeze is not directional : a squeeze tells you volatility has contracted, not which way the next move goes. The release can fail, reverse, or stall.
False band breaks : in noisy conditions, price can poke through a band and return inside on the next bar. Adaptive scaling is designed to help with this, but does not eliminate it.
Mean-reversion risk in trends : using center reclaims as reversion entries during a strong trend can stay wrong longer than expected. The center keeps moving with the trend.
History requirement : adaptive scaling needs enough bars to fill the Adaptive Lookback window (default 100 bars) before it adjusts properly. Squeeze detection also needs sufficient Bollinger and Keltner history. Early bars on any chart will have less reliable readings.
════════════════════════════════════════════
🔔 ALERTS
Six alert conditions are built in so you can monitor without watching the chart:
Breakout Up / Breakout Down : price closes beyond the upper or lower band
Squeeze Started : Bollinger Bands have contracted inside the Keltner Channel
Squeeze Released : squeeze just ended, volatility expanding
Center Reclaim : price crossed above the center after previously touching the lower band
Center Loss : price crossed below the center after previously touching the upper band
All alerts fire on bar close by default for confirmed signals.
════════════════════════════════════════════
⌁ NOTES
Original concept by Chester Keltner (1960), modern ATR-based variant by Linda Bradford Raschke
Uses ATR-based bands with optional volatility-regime adaptation via percentile ranking
Includes Bollinger-inside-Keltner squeeze detection with visual intensity buildup
Center reclaim/loss signals use state-aware logic that tracks which band was last touched
Values update in real time on the current bar and are confirmed at bar close
Open-source: inspect the logic directly in the Pine editor
Indicator

AlphaEngine █ ALPHAENGINE v1.0
The Adaptive Consensus Trading Algorithm
Self-optimizing signal engine that runs 6 independent "Expert" sub-systems simultaneously, tracks their real-time accuracy, and dynamically adjusts their influence using an Adaptive Consensus algorithm inspired by the Multiplicative Weight Update method. The result: an indicator that learns which strategies work best in the current market — and automatically amplifies them while suppressing underperformers. All in real-time, on every single bar.
Free and Open Source.
█ THE 6 EXPERTS
1. Trend Expert
Triple EMA alignment (Fast/Mid/Slow) combined with ADX trend strength. Detects directional bias and amplifies signals when the trend is strong.
2. Momentum Expert
Blends RSI zone analysis (40%), Stochastic crossover (30%), and Rate-of-Change velocity (30%) into a single momentum score. Catches acceleration and deceleration in price moves.
3. Volume Expert
On-Balance Volume trend direction combined with real-time volume spike detection. Confirms signals with institutional participation. Volume must agree with price direction for full score.
4. Volatility Expert
Bollinger Band position mapping combined with ATR expansion/contraction analysis. Includes Squeeze Detection that alerts before major breakout moves.
5. Supertrend Expert
ATR-based dynamic support/resistance with distance scaling. Stronger signals when price is firmly above/below the supertrend line.
6. Structure Expert
Higher-timeframe EMA bias using auto-selected HTF (e.g., 1H chart checks 4H, 5m chart checks 1H). Ensures signals align with the macro trend.
█ THE ADAPTIVE WEIGHTING ENGINE
Unlike traditional indicators that treat all components equally, AlphaEngine tracks which experts are actually performing well in the current market conditions:
Each expert's predictions are validated against real price movement
A rolling accuracy score (exponential decay) measures recent performance
Weights are computed as accuracy squared — creating clear differentiation
Experts with high accuracy get amplified, poor performers get dampened
The engine adapts to any market environment automatically
In a strong trending market, the Trend and Supertrend experts naturally gain weight. In a ranging/choppy market, Momentum and Volume experts take over. The engine adapts automatically.
█ SIGNAL GRADING: A/B/C
A-Grade (75%+ consensus) — High quality. Strong agreement among key experts.
B-Grade (60%+ consensus) — Standard. Moderate agreement. Use with additional confirmation.
C-Grade (50%+ consensus) — Weak. Minimal consensus. For analysis only. Filterable via settings.
Signal labels are visual: A-grade signals are larger and prominent. B/C are smaller and subtle. A minimum grade filter lets you hide weaker signals.
█ RISK MANAGEMENT
Take Profit + Stop Loss:
TP1 — ATR-based take profit target with visual line and hit detection
SL — Dynamic ATR-based stop loss, adapts to current volatility
Visual checkmark when TP1 is reached, X marker when SL triggers. Both levels are always proportional to market conditions — never fixed distances.
█ VISUAL FEATURES
Smart Candle Coloring — 6-level gradient from deep green to deep red based on consensus strength
Trend Background — Subtle gradient overlay showing macro direction
Volatility Bands — Dynamic Bollinger-based bands with squeeze highlight
Squeeze Detection — Diamond dots below price when volatility contracts
Supertrend Line — Color-coded dynamic support/resistance
EMA Lines — Optional Fast/Mid/Slow EMA visualization
█ DASHBOARD
Compact 10-row real-time analytics panel: Current signal + grade + consensus %, visual consensus bar, each expert's direction + rolling accuracy %, and volatility state (Squeeze/Expand/Contract/Normal).
█ ALERTS (7 CONDITIONS)
Signal: Buy/Sell, A-Grade Buy/Sell
Risk: TP1 Hit, SL Hit
Volatility: Squeeze Start
█ PRO VERSION
The PRO version adds:
VWAP Expert — 7th expert for institutional fair-value bias with timeframe auto-scaling
Trading Style Presets — Auto/Scalping/Intraday/Swing/Position/Custom with automatic parameter tuning
Asset Auto-Optimization — Crypto/Forex/Stocks/Futures multipliers for volatility and volume sensitivity
RSI Divergence Detection — Regular + Hidden divergences with visual labels and connecting lines
S-Grade Signals — Elite setup grade (90%+ consensus) for highest probability entries
Multi-Target TP — TP1/TP2/TP3 system with sequential hit detection and R:R ratio display
Premium Dashboard — 17-row analytics panel with all expert weights, divergence status, and TP tracking
17 Alert Conditions — Including divergence alerts, squeeze breakout, trend flip, and grade-specific triggers
█ NON-REPAINTING
All calculations use standard non-repainting indicators (EMA, RSI, ADX, ATR, OBV, Stochastic, Bollinger Bands). Multi-timeframe data uses confirmed prior-bar values. No repainting.
█ WORKS ON
Crypto, Forex, Stocks, Futures, Indices, Commodities and Bonds — any timeframe from 1 second to Monthly.
█ DISCLAIMER
This indicator is for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. No indicator can predict market movements with certainty. Always implement proper risk management. Use this tool as one component of a comprehensive trading strategy, not as a standalone decision-making system.
Indicator

AG Pro ATR Envelope Breakout Quality [AGPro Series]AG Pro ATR Envelope Breakout Quality
Overview / What it does
AG Pro ATR Envelope Breakout Quality is a volatility-aware breakout framework built around a dynamic ATR envelope rather than a static horizontal level, fixed box, or session-defined range. The script tracks when price closes outside an ATR-based outer band, then evaluates whether that move shows enough quality to be treated as a meaningful breakout instead of a weak expansion, short-lived overshoot, or low-conviction push.
The core logic is centered on three linked questions. First, did price achieve a valid close outside the active envelope? Second, was that move supported by enough momentum and relative participation to deserve attention? Third, what happened when price came back toward the broken area? This progression allows the script to move beyond a simple breakout marker and present a more structured breakout-quality workflow.
Because the reference structure is dynamic, the script adapts to changing market conditions instead of forcing all setups into a fixed box logic. In periods of contraction, the envelope tightens and makes outside acceptance more meaningful. In periods of expansion, the envelope widens and helps separate true continuation pressure from ordinary volatility noise. This makes the tool especially useful for traders who want to judge whether an expansion is merely visible or genuinely tradable.
The visual design is intentionally clean and overlay-first. The envelope defines the active volatility shell, breakout markers show where price escapes that shell, the throwback zone highlights the key acceptance pocket after the move, and the optional target line provides a simple expansion objective. A compact panel then summarizes the current state without taking over the chart. The result is a script that aims to look premium while still keeping the main story readable in a publish screenshot.
Unique Edge
The main distinction of this script is that it does not evaluate breakout quality from a static support/resistance line, a consolidation rectangle, a Donchian extreme, or an opening range boundary. It evaluates breakout quality from a moving ATR envelope. That difference is not cosmetic. It changes the entire logic of what counts as a breakout, how follow-through is judged, and how retests are interpreted.
In several classic breakout tools, the market is asked to escape a fixed historical structure. Here, the market is asked to achieve acceptance outside a live volatility shell. This creates a different analytical lens. A move that looks impressive relative to a flat level may not be meaningful relative to a volatility-adjusted envelope. On the other hand, a clean close outside an adaptive outer band can reveal expansion quality that a simple line break would miss.
This also separates the script from our other AG Pro tools. It is not a consolidation breakout evaluator, because its reference structure is not a box. It is not a Donchian breakout tool, because it is not based on period highs and lows. It is not an opening-range breakout model, because it is not session-box dependent. It is not a standard break-retest script, because the retest here happens around a dynamic envelope acceptance area rather than around a static horizontal level.
That distinction matters both analytically and visually. Analytically, the script focuses on volatility-adjusted breakout acceptance. Visually, it produces a different type of chart story: an active envelope, a breakout event, a throwback pocket, and a projected path. This gives the script its own place inside the AG Pro catalog rather than making it feel like a variation of an existing breakout family member.
Methodology
The script begins with an ATR-based envelope built around a moving basis. This creates an adaptive upper and lower band that expand or contract with market volatility. A bullish breakout candidate appears when price closes outside the upper band. A bearish breakout candidate appears when price closes outside the lower band. Wick-only excursions are not enough. The script is designed to care about acceptance, not mere contact.
Once an outside close is detected, the script evaluates breakout quality through a compact scoring framework. Momentum contribution helps measure whether the breakout candle shows real displacement or just a hesitant push. Volume contribution helps detect whether the breakout is supported by stronger-than-usual participation or whether it lacks confirmation. The combined result becomes the displayed breakout-quality score.
After the initial breakout, the script monitors the first return toward the broken band area. This is where the throwback logic becomes important. Instead of treating every pullback the same way, the script classifies what happens around the envelope area and updates the state accordingly. A successful hold suggests that the market accepted the breakout. A failure suggests that the move lost structural quality after the initial expansion.
An optional target line can be used to project a simple post-breakout objective. This is not presented as a promise of outcome. It is a visual planning reference intended to show a possible expansion path if the breakout continues to behave constructively. Together, the envelope, the breakout signal, the throwback state, and the target framework create a full breakout-quality sequence rather than a single event label.
Signals & Alerts
The script is designed to organize the breakout workflow into visible states rather than flooding the chart with constant commentary. The main states include bullish breakout, bearish breakout, throwback monitoring, throwback hold, breakout failure, and target hit. This makes the chart easier to read and helps the user understand where the setup currently stands.
Bullish and bearish breakout markers appear when price achieves a confirmed outside close beyond the relevant envelope band. These are the initial expansion events. They are then followed by a monitoring phase in which the script watches how price behaves around the broken band area. If the return is constructive, the script can label that behavior as a successful hold. If the move loses quality and breaks down, the script can classify it as a failure.
The target marker is optional and functions as a planning aid, not as a certainty engine. It simply shows that the projected expansion objective has been reached based on the chosen configuration. In practical use, this can help traders separate the breakout event itself from the later progression of the move.
The alert set is intended to remain deterministic and chart-state aware. It focuses on confirmed breakout events, throwback behavior, breakout failure, and target completion. This keeps the script aligned with workflow clarity instead of turning it into a noisy alert generator.
Key Inputs
The envelope settings control the moving basis, ATR length, and multiplier that define the adaptive breakout shell. These settings determine how sensitive the script is to changing volatility and how demanding the outside-close condition becomes.
The breakout filter settings allow the user to regulate confirmation quality. Depending on the selected configuration, the script can require stronger momentum, clearer outside distance, and optional volume confirmation. This helps users decide whether they want a more selective or more responsive model.
The throwback analysis settings define how the script interprets the first return toward the broken envelope area. These settings influence how deeply price can revisit the area before the move is treated as weak, failed, or still acceptable.
The target settings control whether the projected objective is shown and how far it is placed from the breakout area. The visual settings then manage panel visibility, panel placement, font sizing, historical object behavior, and label density so the script can remain clean in live use and in publish screenshots.
Limitations & Transparency
This script is a breakout-quality framework, not a prediction engine. It does not know in advance whether a breakout will continue. It evaluates the quality of a breakout after a valid outside-close event occurs and then tracks how price behaves afterward. That distinction is important.
The ATR envelope is an adaptive reference, which means the same market move may be classified differently under different volatility regimes. That is intentional. The script is designed to respond to changing market structure, but any adaptive model will also reflect the sensitivity of its settings. Users should therefore expect the behavior of the tool to vary across symbols, timeframes, and volatility environments.
Volume inputs may also behave differently across markets and data feeds. On some instruments, volume can add useful confirmation. On others, it may be less informative. For that reason, volume should be treated as a supporting factor rather than as an absolute truth layer.
The target projection is a chart-planning feature, not a guaranteed outcome. Likewise, a breakout failure label does not mean the market cannot later recover, and a target hit does not mean the move was universally optimal. The script is meant to help structure chart reading, not replace trade management, context analysis, or personal decision-making.
How this script differs from our other AG Pro tools
Within the AG Pro lineup, this script is intentionally positioned as a volatility-envelope breakout tool. It does not compete with our box-based breakout logic, our period-high/low breakout logic, or our static break-retest logic. Its role is to answer a different question: did price achieve meaningful acceptance outside an adaptive ATR shell, and did that acceptance survive the first return test?
That makes it especially useful when traders want a volatility-adjusted view of expansion quality. In markets where static levels are repeatedly pierced, an adaptive envelope framework can provide a cleaner read on whether the move is truly escaping current volatility conditions or simply stretching within ordinary noise.
In that sense, the script is not a replacement for our other breakout-oriented tools. It is a separate layer with a different reference model, different retest logic, and a different chart story. That separation is deliberate and is one of the reasons the script belongs in its own category inside the broader AG Pro collection.
Risk Disclosure
This script is an analytical chart tool designed to visualize volatility-adjusted breakout conditions, breakout quality, and post-breakout behavior. It is not financial advice, not a signal service, and not a guarantee of future price direction.
All breakout conditions can fail. Momentum can fade, volume can be inconsistent, and throwback behavior can change quickly. Markets remain uncertain, and no indicator can eliminate risk. Users should always apply their own market judgment, risk controls, and execution rules.
Use the script as a structured decision-support layer, not as a stand-alone trading instruction. Confirmation from broader context, trend conditions, liquidity structure, and personal risk management remains essential.
Indicator

Adaptive Pressure Trail [JOAT]Adaptive Pressure Trail
Introduction
Adaptive Pressure Trail is an open-source overlay indicator that combines an HMA-based adaptive ratchet trail with a custom volume-weighted Money Flow Index to classify bars into bull pressure, bear pressure, and neutral states. The system uses a three-layer visual architecture — an outer volatility cloud, an inner ratchet band fill, and a core gradient pressure fill between the HMA baseline and candle mid-body — to create a clear, spatially organized picture of momentum and direction on any chart. Volatility squeeze detection identifies compression phases before potential breakouts, and high-confidence signals fire when a squeeze releases simultaneously with pressure alignment.
The core problem this indicator solves is that most trail-based systems are either too reactive (flipping constantly on noise) or too slow (missing meaningful moves). The HMA ratchet addresses this: the upper band only falls and the lower band only rises after a direction flip, preventing whipsaw while remaining responsive when momentum is genuine. Layering a volume-weighted MFI filter on top means a directional trail alone is not sufficient — volume-backed money flow must confirm the move before the indicator reports active pressure.
Core Concepts
1. HMA Adaptive Ratchet Trail
The trail baseline is computed using a Hull Moving Average, which provides low lag while remaining smooth. ATR-scaled upper and lower bands are applied around the HMA. The ratchet rule prevents band noise: the upper band can only move downward (or reset when price closes above it), and the lower band can only move upward (or reset when price closes below it). Direction flips when price closes through the active band. This creates a one-directional drift that is far more stable than a raw crossover trail:
The trail direction variable persists with var and updates each bar. Direction == 1 means the lower band is the active trail (bullish), direction == -1 means the upper band is the active trail (bearish).
2. Custom Volume-Weighted MFI
Rather than using a standard price-only momentum oscillator, the pressure engine uses a custom volume-weighted Money Flow Index. Positive flow is volume multiplied by HLC3 on bars where HLC3 increased; negative flow is volume multiplied by HLC3 on bars where HLC3 decreased. These are summed over the MFI length and converted to a 0-100 scale using the RSI formula. The result is smoothed with an HMA for responsiveness. This produces a momentum measure that is inherently volume-weighted — large-volume moves carry more influence than low-volume drift. The MFI is further smoothed to distinguish sustained pressure from transient spikes.
3. Pressure Regime Classification
Bull pressure is active when the trail direction is bullish AND the smoothed MFI is above the bull threshold. Bear pressure is active when the trail direction is bearish AND MFI is below the bear threshold. Neutral is everything else. This dual-condition structure means you need both directional commitment from the ratchet trail AND volume-backed momentum to enter a pressure state. Either condition alone is insufficient.
A rolling 50-bar history tracks what percentage of recent bars were in an active pressure state, producing a Pressure Strength percentage that indicates whether the current regime has been sustained or is a brief spike.
4. Squeeze Detection
Band width — the distance between the upper and lower ratchet bands — is compared to its own SMA. When band width drops below 72% of its recent average, the market is compressing. A squeeze start fires a golden diamond marker at the trail level. A squeeze release fires a larger circle marker. The high-confidence signal fires when a squeeze release coincides with an active pressure state, identifying the highest-probability setups where compressed volatility breaks out in a confirmed directional context.
5. Three-Layer Visual Architecture
The chart renders three nested visual layers:
Outer Cloud: The ATR envelope (cloudMult * ATR from HMA center) filled with a very transparent directional color — gives spatial context to where price is within the volatility range
Inner Band Fill: The ratchet upper and lower bands filled with medium transparency — shows the active directional channel
Core Pressure Fill: A gradient fill between the HMA baseline and the candle mid-body — transparent at the HMA, saturated at the body, colored by pressure state
The trail line itself uses three stacked plots at widths 10, 5, and 2 to create a neon glow shadow effect. Bar coloring uses color.from_gradient driven by MFI intensity, producing increasingly saturated candles as momentum builds.
Features
HMA Ratchet Trail with Triple-Layer Glow: Direction-persistent adaptive trail rendered as a neon glow (widths 10/5/2) using the bullish lime or bearish fuchsia color
Outer ATR Volatility Cloud: Wide ATR envelope filled directionally, providing spatial context at a glance
Inner Ratchet Band Fill: Gradient-filled active channel between upper and lower ratchet bands
Core Pressure Gradient: Background-to-body gradient between HMA and mid-body, colored by current pressure state
HMA Skeleton Reference: Subtle neutral line showing the raw HMA baseline beneath all fills
Volatility Squeeze Markers: Golden diamonds during compression, circle flash on breakout
High-Confidence Signal: Starred HC LONG / HC SHORT labels when squeeze releases into confirmed pressure alignment — the highest-quality setup the system produces
Volume Impulse Labels: When a strong directional candle exceeds the volume threshold, a label shows the volume ratio (e.g., 2.1x vol) at the bar
MFI Cross Markers: Small triangles on the trail when MFI crosses the 50 level, marking momentum regime shifts
TP Signals: Labeled plotshapes when MFI reaches overbought/oversold extremes in the trail direction
Pressure Strength Percentage: Rolling 50-bar % of time spent in active pressure — distinguishes sustained trends from brief spikes
Gradient Bar Coloring: color.from_gradient driven by MFI intensity — bars saturate as momentum builds and fade as it weakens
11-Row Dashboard: Pressure state, trail direction, MFI reading, pressure score, pressure strength %, volatility state, band width, trend bars, trail price, ATR
Input Parameters
Adaptive Trail:
Trail HMA Length: Period for the HMA baseline (default 21)
Trail ATR Multiplier: Width of inner ratchet bands (default 1.8)
Trail ATR Length: ATR lookback for band calculation (default 14)
Outer Cloud ATR Width: Outer envelope width multiplier (default 3.2)
Squeeze Reference Bars: SMA period for band-width baseline (default 20)
Pressure Filter:
MFI Length: Volume-weighted money flow lookback (default 14)
MFI Smoothing: HMA smoothing on raw MFI (default 7)
MFI Bull/Bear Thresholds: Activation levels for pressure states (default 62/38)
Signals:
TP Overbought/Oversold Levels: MFI levels that trigger TP signals (default 78/22)
Impulse Volume Multiplier: Volume multiple above SMA required for impulse label (default 1.3)
Visuals:
Toggles for entry signals, TP signals, glow, cloud, pressure fill, squeeze markers, and dashboard
Bull Color (default lime #a3e635), Bear Color (default fuchsia #e879f9), Neutral Color (default slate #94a3b8)
How to Use This Indicator
Primary Setup — Trend Following with Pressure Confirmation:
Look for the trail to flip direction (circle marker on trail). Wait for MFI to cross the bull or bear threshold, confirming the pressure state activates. Enter in the trail direction once the pressure fill color saturates. Trail your stop at the active trail line. Exit on a TP signal or when the pressure state deactivates.
High-Confidence Setup:
Wait for squeeze markers (golden diamonds) to appear, indicating compression. When the squeeze releases (larger circle flash) and the pressure state is simultaneously active, the HC LONG or HC SHORT label fires. These are the setups where compressed volatility breaks out with momentum behind it.
Filtering with Pressure Strength:
The dashboard Pressure Strength percentage tells you how sustained the current move has been. Values above 60% indicate a mature trend. Values below 30% indicate the pressure state is new or unstable. Adjust position sizing accordingly.
Reading Impulse Candles:
Volume impulse labels (e.g., "2.1x vol") mark bars where a strong directional move was accompanied by significantly elevated volume. These often mark the start or acceleration of a pressure phase and can serve as reference points for support/resistance.
APT dashboard showing bull pressure active, MFI at 71.2, P-Score 7.1/10, P-Strength at 64%, band width expanding after a squeeze release, and the trail at current price with ATR reference
Indicator Limitations
The ratchet trail requires a confirmed close through the active band to flip direction. On higher-timeframe charts with large candle bodies this can mean the flip is confirmed well after the actual turning point
The volume-weighted MFI requires volume data. On instruments with unreliable volume reporting (some forex pairs, synthetic indices) the pressure filter may be less meaningful than on equities or futures
Squeeze detection uses a 72% band-width threshold. In persistently low-volatility instruments this threshold may trigger too frequently; adjusting the Squeeze Reference Bars parameter can help
High-confidence signals require both a squeeze release and active pressure simultaneously. On trending markets with no compression phase, HC signals will be rare
MFI thresholds at 62/38 are defaults designed for balanced use; highly trending instruments may require raising the bull threshold and lowering the bear threshold to reduce false pressure activations
Originality Statement
This indicator is original in its combination of a ratchet-constrained HMA trail with a custom volume-weighted MFI, the three-layer nested visual system, and the squeeze-breakout confluence signal. While HMA trails and MFI oscillators exist independently, this publication is justified because:
The ratchet logic applied to HMA (rather than ATR midline or EMA) reduces lag while preventing the constant flipping common in standard trail indicators
The custom volume-weighted MFI differs from the standard MFI by using HLC3 as the price component with RSI-formula normalization, producing a smoother measure with better noise rejection
The three-layer nested fill architecture (outer cloud, inner band, core pressure gradient) provides a spatially organized visual system where the distance between layers communicates volatility context
Squeeze detection integrated with pressure confirmation for HC signals is a novel combination that identifies setups at the intersection of volatility compression and momentum alignment
The Pressure Strength rolling percentage provides a trend maturity measure not present in standard trail indicators
Disclaimer
This indicator is provided for educational and informational purposes only and does not constitute financial advice or a recommendation to buy or sell any financial instrument. Past performance of any pattern or signal does not guarantee future results. All trading involves substantial risk. Always use proper risk management and conduct your own independent analysis.
— Made with passion by officialjackofalltrades
Indicator

Indicator

Adaptive Regime Filter + Divergence (AER-VN) [KEYALGOS]Adaptive Regime Filter + Divergence (AER-VN)
Professional Grade Market Regime Classification with Advanced Divergence Detection
Precision trend identification using Adaptive Efficiency Ratio methodology
Volatility-normalized thresholds that adjust to real-time market conditions
Automatic divergence detection (Regular and Hidden) with visual confirmation lines
Four distinct market regimes with color-coded clarity
Zero-lag signal generation with confirmation logic
OVERVIEW
The Adaptive Regime Filter with Volatility Normalization (AER-VN) represents a sophisticated evolution of traditional trend filtering methodologies. This proprietary indicator combines Kaufman's Efficiency Ratio principles with dynamic volatility adaptation to classify market conditions into four actionable regimes: Uptrend, Downtrend, Choppiness, and Consolidation.
The integrated Divergence Detection System operates as a secondary analytical layer, identifying momentum exhaustion and trend continuation patterns through comparative analysis of price action versus efficiency metrics. Unlike standard oscillators that measure raw momentum, this system evaluates the quality of price movement, providing earlier and more reliable reversal signals.
METHODOLOGY AND TECHNIQUE
1. Adaptive Efficiency Ratio (AER) Core
Traditional efficiency ratios utilize static thresholds that fail across varying volatility environments. The AER-VN methodology introduces dynamic threshold calculation that self-adjusts based on current volatility relative to historical norms.
Displacement Measurement: Calculates net price movement over the lookback period
Path Distance Analysis: Sums absolute bar-to-bar movements to determine movement quality
Efficiency Calculation: Ratio of displacement to path distance (0.0 to 1.0 scale)
Threshold Adaptation: Baseline efficiency requirements scale proportionally with the ATR ratio
When volatility expands (ATR above mean), the system automatically raises the efficiency threshold required to qualify as "trending." This prevents false trend signals during volatile chop. Conversely, during low volatility periods, the threshold contracts to capture subtle trending behavior.
2. Volatility Normalization Engine
The Volatility Normalization component creates a relative volatility index by comparing current ATR readings against a rolling historical average. This produces an ATR Ratio that serves as the scaling factor for dynamic threshold calculation.
Current ATR: Short-term volatility measurement (default 14 periods)
Mean ATR: Long-term volatility baseline (default 50 periods)
Adaptive Scaling: Raw threshold = Base Threshold x ATR Ratio
Ceiling Protection: Maximum threshold cap prevents mathematically impossible requirements during extreme volatility events
3. Four Regime Classification System
Uptrend (Teal): Efficiency exceeds dynamic threshold with positive price displacement. Indicates high-quality upward movement with minimal retracement.
Downtrend (Maroon): Efficiency exceeds dynamic threshold with negative price displacement. Indicates sustained selling pressure with directional clarity.
Choppiness (Orange): Efficiency below threshold during above-average volatility. Characterized by noisy, directionless movement with large wicks and whipsaws.
Consolidation (Gray): Efficiency below threshold during below-average volatility. Represents quiet, range-bound markets with compressed price action.
4. Zero-Lag Divergence Detection
The divergence system employs confirmed swing detection to identify pivotal highs and lows without repainting. Once a swing point is confirmed (price violates the extreme), the system evaluates four divergence classifications:
Regular Bearish Divergence: Price records higher highs while Efficiency Ratio records lower highs. Indicates trend exhaustion and potential reversal to the downside.
Regular Bullish Divergence: Price records lower lows while Efficiency Ratio records higher lows. Indicates selling exhaustion and potential reversal to the upside.
Hidden Bearish Divergence: Price records lower highs while Efficiency Ratio records higher highs. Suggests continuation of the current downtrend after a pullback.
Hidden Bullish Divergence: Price records higher lows while Efficiency Ratio records lower lows. Suggests continuation of the current uptrend after a retracement.
Visual confirmation lines connect the relevant swing points on the indicator panel, allowing traders to verify divergence validity visually.
INPUT PARAMETERS AND CONFIGURATION
Efficiency Ratio Settings
ER Lookback (N)
Default: 10 | Range: 2+
The calculation period for efficiency measurement. Shorter values increase sensitivity to recent price action, suitable for scalping lower timeframes. Longer values smooth the oscillator, better for swing trading higher timeframes.
Base ER Threshold
Default: 0.25 | Range: 0.05 to 0.80 | Step: 0.05
The foundational efficiency level required in normalized volatility conditions. Higher values demand cleaner, more directional movement to trigger trending regime classification. Lower values allow noisier price action to qualify as trending.
Max Threshold Cap
Default: 0.65 | Range: 0.10 to 0.99 | Step: 0.05
The absolute ceiling for the dynamic threshold. This safety mechanism prevents the threshold from rising to levels mathematically impossible to achieve during extreme volatility expansion.
Volatility Normalization Settings
ATR Length
Default: 14 | Range: 1+
The lookback period for Average True Range calculation. Determines how quickly the system responds to changing volatility conditions.
ATR Mean Lookback
Default: 50 | Range: 5+
The historical window for establishing the volatility baseline. Longer periods create a smoother volatility reference, while shorter periods adapt more quickly to regime changes in volatility.
Divergence Detection Settings
Swing Definition Length
Default: 10 | Range: 3+
The lookback window for identifying swing highs and lows. Determines the minimum number of bars required to establish a pivot point. Lower values detect micro-swings (more signals, more noise). Higher values detect major swings (fewer signals, higher quality).
Visual Display Toggles
Show Regular Div Markers: Display circle markers for Regular Bearish and Regular Bullish divergences
Show Hidden Div Markers: Display circle markers for Hidden Bearish and Hidden Bullish divergences
Line: Regular Bearish: Draw connecting lines between swing highs for Regular Bearish divergences (Red)
Line: Regular Bullish: Draw connecting lines between swing lows for Regular Bullish divergences (Lime)
Line: Hidden Bearish: Draw connecting lines for Hidden Bearish divergences (Orange)
Line: Hidden Bullish: Draw connecting lines for Hidden Bullish divergences (Aqua)
Visual Settings
Color Price Bars
Toggle to apply regime colors directly to price candles/bars on the main chart. Uptrend (Teal), Downtrend (Maroon), Choppiness (Orange), Consolidation (Gray).
INTERPRETATION GUIDE
Reading the Oscillator
The main panel displays three critical elements:
Efficiency Ratio Line: The primary oscillator colored by current regime. Values near 1.0 indicate perfect efficiency (strong trend). Values near 0.0 indicate complete inefficiency (chop).
Dynamic Threshold: The white crossed line representing the current volatility-adjusted efficiency requirement. When the ER line crosses above this threshold, the regime shifts to trending.
Base Threshold Reference: The gray dotted line showing the static baseline (0.25 default) for reference.
Divergence Signal Interpretation
Red Circle (Regular Bearish): Momentum divergence at highs. Consider reducing long exposure or preparing short entries. Highest probability when appearing near resistance or after extended uptrends.
Lime Circle (Regular Bullish): Momentum divergence at lows. Consider reducing short exposure or preparing long entries. Highest probability when appearing near support or after extended downtrends.
Orange Circle (Hidden Bearish): Trend continuation signal in downtrends. Pullback likely ending, downtrend resumption probable.
Aqua Circle (Hidden Bullish): Trend continuation signal in uptrends. Retracement likely ending, uptrend resumption probable.
TRADING APPLICATIONS
Strategy 1: Regime-Based Trend Following
Enter long positions only when the indicator displays Teal coloring (Uptrend regime) and short positions only during Maroon coloring (Downtrend regime). Exit positions when the regime shifts to Orange or Gray, indicating the trending condition has ended.
Best for: Directional traders and trend followers
Timeframe: M15 and higher recommended for stability
Confluence: Combine with moving average alignment or breakout patterns
Strategy 2: Divergence Reversal Trading
Monitor for Regular Divergences (Red or Lime circles) as early warning systems. Wait for price confirmation (engulfing candles, pin bars) at the divergence point before entering. Use the connecting lines to visualize the divergence strength.
Best for: Counter-trend scalpers and swing traders
Timeframe: M5 to H1 depending on swing length settings
Confluence: Combine with support/resistance levels and volume analysis
Strategy 3: Chop Avoidance and Consolidation Breakout
Use the Orange (Choppiness) and Gray (Consolidation) regimes as "No Trade" zones or reduction zones. Wait for a divergence to form within these regimes, then enter when the regime shifts back to trending (Teal or Maroon), capturing the breakout momentum.
Best for: Patience-based traders seeking high-probability setups
Timeframe: Effective across all timeframes
Confluence: Combine with volume expansion on regime change
Strategy 4: Hidden Divergence Continuation
In established trends (Teal lasting 5+ bars), look for Hidden Bullish Divergences (Aqua) on pullbacks to enter additional long positions. In established downtrends (Maroon), look for Hidden Bearish Divergences (Orange) on rallies to add to shorts.
Best for: Position traders adding to winners
Timeframe: H1 to Daily for best results
Confluence: Combine with Fibonacci retracement levels
OPTIMIZATION GUIDELINES
For Lower Timeframes (M1 to M5)
Reduce ER Lookback to 6-8 for faster response
Lower Base ER Threshold to 0.15-0.20 to account for noise
Reduce Max Threshold Cap to 0.50-0.55
Shorten ATR Mean Lookback to 20-30
Reduce Swing Definition Length to 6-8 for micro-structure
For Higher Timeframes (H1 to Daily)
Increase ER Lookback to 14-21 for smoother readings
Maintain or increase Base ER Threshold to 0.30+ for quality control
Increase ATR Mean Lookback to 50-100 for stable volatility baselines
Increase Swing Definition Length to 10-20 for major pivots only
ALERTS AND NOTIFICATIONS
The indicator includes built-in alert conditions for:
Regular Bearish Divergence Detection
Regular Bullish Divergence Detection
Configure PulseWire alerts to trigger on these conditions to monitor markets without constant chart watching.
BEST PRACTICES AND RISK MANAGEMENT
Always confirm divergence signals with price action patterns (engulfing candles, pin bars, break of structure) rather than entering immediately on marker appearance.
Avoid trading divergence signals that occur deep within the Choppiness (Orange) regime without waiting for a regime shift confirmation.
Use the regime colors as a position sizing guide: Full size in Teal/Maroon, half size in Gray, flat or minimal in Orange.
The indicator excels when combined with support/resistance analysis. Divergences forming at key S/R levels carry significantly higher probability.
In ranging markets, decrease the Base ER Threshold to reduce whipsaws. In strongly trending markets, consider increasing it to filter out minor retracements.
TECHNICAL NOTES
The indicator does not repaint. Swing points require confirmation on the subsequent bar to print, ensuring signals remain fixed after formation.
All calculations utilize Pine Script v6 native functions for optimal performance and minimal resource usage.
The Volatility Normalization component prevents the common failure mode of static efficiency indicators during periods of expanding volatility.
Connecting lines for divergences are managed with automatic cleanup protocols to prevent chart clutter on extended runs.
SUPPORT AND UPDATES
This indicator is maintained by KeyAlgos. All users receive automatic updates as methodology improvements are implemented. For questions regarding parameter optimization or implementation strategies, utilize the PulseWire comments section on this publication.
Disclaimer: This indicator is a technical analysis tool designed to assist with market analysis, not a guaranteed profit system. Always practice proper risk management and use stop losses. Past performance of indicator signals does not guarantee future results. Indicator

AG Pro KAMA Efficiency Zones [AGPro Series]AG Pro KAMA Efficiency Zones
Overview
KAMA stands for Kaufman’s Adaptive Moving Average.
AG Pro KAMA Efficiency Zones is built around KAMA not as a simple trend-following line, but as an adaptive market reference for evaluating how efficiently price is moving. Instead of focusing only on direction, the script is designed to classify the quality of directional travel and separate cleaner movement from noisier, lower-clarity conditions.
The core idea is straightforward: markets do not move with the same quality all the time. Some phases show relatively efficient directional travel where price stays organized around an adaptive path. Other phases become mixed, unstable, or reversion-prone, where direction weakens and noise becomes more dominant. This script is designed to map those changes visually through adaptive KAMA-based zones, state labels, and a compact panel that summarizes the current condition.
This makes the tool structurally different from a basic moving average overlay. The objective is not to present KAMA as a one-line signal source. The objective is to use KAMA as the center of a state engine that helps users distinguish efficient trend phases from transitional or noisy environments.
What this script does
AG Pro KAMA Efficiency Zones evaluates price behavior around a Kaufman’s Adaptive Moving Average and organizes that behavior into visual market states. It does this by combining adaptive smoothing, slope behavior, distance from KAMA, and persistence around the KAMA path.
The result is a chart framework that can help answer questions such as:
• Is price moving in an efficient bullish or bearish path?
• Is the market entering a mixed transition phase?
• Has movement quality deteriorated into a noisier reversion-prone environment?
• Is the adaptive path becoming stronger, weaker, or less stable?
By turning those questions into zones and state-based chart feedback, the script aims to improve context rather than replace judgment.
Unique edge
The distinguishing feature of this script is that it does not treat KAMA as a standard moving average. Instead, it uses KAMA as the center of a layered efficiency model.
That model focuses on the quality of movement, not just the existence of movement.
Many tools emphasize momentum, volatility, volume pressure, or overbought/oversold conditions. This script is designed for a different purpose. It is a movement-quality map. It attempts to show whether price is traveling in a relatively efficient path or whether that path is degrading into a noisier condition where directional clarity may be weaker.
This means the script is less about predicting a move and more about classifying the environment in which a move is taking place.
How it works
The script begins with KAMA, or Kaufman’s Adaptive Moving Average. KAMA is useful because it adapts its responsiveness according to market behavior. In cleaner directional phases it can respond more quickly, while in noisier phases it can become more conservative. That makes it a practical centerline for an efficiency-based state model.
On top of KAMA, the script evaluates several components:
1. Efficiency behavior
The script measures how directly price is moving relative to its recent path. This helps estimate whether price action is acting efficiently or becoming more erratic.
2. KAMA slope behavior
The slope of KAMA is normalized so that directional angle can be evaluated in a more consistent way. Stronger and more persistent slope behavior supports higher-quality trend classifications.
3. Price-to-KAMA relationship
Price position around KAMA helps determine whether movement is aligned with the adaptive path or drifting around it without clear structure.
4. Persistence
The script also looks at how consistently price remains on one side of KAMA. That persistence can help distinguish a more stable move from a weaker and less durable one.
These components are blended into a composite efficiency model that drives the active state and the corresponding visual zone.
States and zones
The script classifies market behavior into four main states:
Efficient Bull Trend
This state reflects a comparatively organized bullish environment where price and adaptive slope are aligned in a cleaner upward path.
Efficient Bear Trend
This state reflects a comparatively organized bearish environment where price and adaptive slope are aligned in a cleaner downward path.
Transition
This is a mixed condition. Direction may be weakening, changing, or failing to achieve the quality required for an efficient trend classification.
Noise / Reversion
This state reflects lower movement quality, weaker slope behavior, or a more unstable relationship between price and the adaptive path.
The visual zone structure is designed to reinforce those classifications on the chart. Instead of using only one line, the script builds layered KAMA-centered bands so the user can read not only direction, but also how structured or fragile the current condition may be.
How to read the chart
The KAMA line is the adaptive spine of the script.
The outer and inner bands represent zone structure around that adaptive path. In stronger trend states, the script increases the visual emphasis of the KAMA path and its supporting zone layers. In weaker or more mixed conditions, the script softens those visuals and allows the chart to communicate reduced clarity.
State labels appear when the script confirms a meaningful shift in condition. These labels are intended to highlight a change in market state, not to promise a trade outcome.
The on-chart panel summarizes the active reading using fields such as State, Efficiency, Score Band, Adaptive Bias, Active Zone, and Stability. This gives the user a compact interpretation layer without requiring every decision to be made directly from raw chart inspection.
Key inputs
KAMA Efficiency Length
Controls the lookback used in the KAMA efficiency logic. Lower values react faster. Higher values smooth more noise.
KAMA Fast Response and KAMA Slow Response
Define the adaptive responsiveness range of the KAMA engine.
ATR Length
Used to normalize slope and distance so the tool behaves more consistently across different symbols and volatility conditions.
KAMA Slope Lookback
Controls how the script measures directional slope over time.
Persistence Length
Influences how much consistency price must show around KAMA before a move is treated as more structured.
Efficient Trend Threshold and Noise Threshold
These thresholds help determine when the model classifies a move as higher quality or lower quality.
Zone Band ATR Width
Adjusts the width of the adaptive visual zone.
State Hold Bars
Helps reduce rapid state flipping by requiring a condition to persist before the active state changes.
Panel Font Size and Label Size
Allow visual customization for different chart layouts and monitor sizes.
Alerts
The script includes state-oriented alerts intended to notify the user when market condition changes. These are designed around state transitions and movement-quality shifts rather than promotional “buy now” style messaging.
Examples include bullish and bearish efficiency shifts, transition detection, noise-zone detection, efficiency recovery, efficiency breakdown, and trend strengthening.
Alerts should be interpreted as contextual information. They are intended to support review and analysis, not to function as a standalone decision system.
What this script is not
This script is not a guarantee engine.
It does not predict future price with certainty.
It does not eliminate risk.
It is not a substitute for broader market structure analysis, execution planning, or risk management.
It should not be treated as a self-sufficient entry/exit system without additional confirmation and user judgment.
Limitations and transparency
All adaptive models are sensitive to parameter choices. Changing responsiveness, thresholds, smoothing, or persistence settings can materially affect the way states appear on the chart.
Because the script is state-based, some shifts will naturally occur after the earliest turning point in price. That is part of the tradeoff involved in using confirmation and persistence to reduce noise.
In highly erratic or news-driven conditions, classification can also become less stable. During those periods, transition or noise-oriented readings may occur more often, and users should interpret the visual output in that context.
The script is best viewed as an analytical framework for movement quality and adaptive context, not as a promise of directional success.
Practical use cases
Users may find the script useful for:
• separating cleaner trend phases from mixed or unstable phases
• filtering chart environments before applying another workflow
• evaluating whether direction is gaining or losing efficiency
• adding adaptive context to discretionary analysis
• comparing how different symbols behave around a KAMA-centered efficiency structure
Risk disclosure
This script is for analytical and educational use. It does not provide financial advice, investment advice, or guaranteed outcomes. Market conditions can change quickly, and any indicator can produce false, delayed, or incomplete signals. Users remain responsible for their own decisions, validation process, and risk management.
In short, AG Pro KAMA Efficiency Zones is designed to help read the quality of movement, not just the direction of movement. It uses KAMA as an adaptive reference point and converts that reference into a structured zone and state model so users can assess whether price behavior appears efficient, transitional, or noisy.
Indicator

ADXVMA Multi-TF Overlay & Alerts [HYPR-run]DESCRIPTION:
ADXVMA across three lookback periods on one chart. A moving average that
uses the ADX (Average Directional Index) as its smoothing factor; fast in
trends, flat in chop. Price crossing above or below a selected ADXVMA
fires a webhook-ready alert for automated execution.
Based on Linnsoft's ADXvma implementation, combining Chande's Variable
Moving Average (VIDYA) with Wilder's ADX as the volatility measure. When
ADX is high (strong trend), the MA tracks price closely. When ADX is low
(choppy), the MA barely moves. This makes it naturally adaptive without
manual adjustment.
DISCOVERING EDGE
Adaptive MAs are popular (KAMA, VIDYA, DEMA), but most still treat
every directional change as a trend signal, producing false signals. This indicator adds a fuzzy factor dead zone that creates a third state, "fuzzy flat" that must exceed a noise threshold
before registering a directional change. We found the fuzzy flat signal to be a powerful signal for confirming consolidation within a trend on shorter look back periods and with the longer period for identifying ranging distribution/accumulation regimes.
Fuzzy ADXVMA vs ADXVMA
The fuzzy dead zone forces a consolidation state (yellow
flat) where a pivot or trend change would present otherwise. When the MA finally turns green or
red, it exceeds the noise floor and considered a more reliable directional
commitment, not a minor fluctuation.
- Flat duration before the cross determines signal quality; XO after
15+ bars flat = base resolved (high conviction), XO after 3 bars
flat = noise (low conviction).
- 7-tier regime gradient (D Trend at score 5 down to Potential Chop
at 0) shows the trend proving itself bar by bar across multiple
lookbacks.
- Two alert systems with multi-layer filtering (not vanilla crossovers).
Regime-confirmed fires only at early pivots. Volatility-confirmed
fires only when bar participation validates the MA shift.
FEATURES
- Three lookbacks: short, long, weekly
- Fuzzy flat detection (dead zone prevents false trend changes in chop)
- Optional ATR volatility scaling (shorter period in high-vol regimes)
- Dashboard with 7-tier regime gradient and event badge
- Two alert systems with multi-layer filtering (not vanilla crossovers)
- Regime-confirmed: price vs ADXVMA, only at early pivots (score 1-2)
- Volatility-confirmed: ADXVMA momentum shift + ATR bar expansion
- Select which lookback triggers regime-confirmed alerts
- Color-coded: green (up), red (down), yellow (flat)
- Dashboard dark/light theme toggle for any chart background
HOW IT WORKS
ADX measures trend strength on a 0-1 scale and feeds it directly into
the MA smoothing factor. High ADX = MA tracks price. Low ADX = MA holds
still. The fuzzy factor adds a dead zone so tiny movements register as
flat instead of false trend changes. Three simultaneous lookbacks give
you short-term, medium-term, and weekly context without switching charts.
DASHBOARD
Regime state at a glance. The header row shows a badge that flags
conflicting events; the second row shows the current regime label with
a 7-tier color gradient; the third row shows direction pivot events.
ALERTS
Two independent alert systems, both multi-layer filtered. Regime-confirmed:
the regime pivot is the signal; price crossing the selected ADXVMA is just
the trigger. Only fires at early pivots (score 1-2), ignoring mid-trend
crosses entirely. Volatility-confirmed: the ATR bar expansion is the
signal; the ADXVMA momentum shift is the trigger. Only fires when the bar
shows real participation (high/low extends beyond open +/- ATR), ignoring
low-range bars. Both fire JSON payloads; works with any webhook receiver.
CREDITS
ADXVMA: Linnsoft
ADX: J. Welles Wilder (1978)
VIDYA: Tushar S. Chande, TASC March 1992 Indicator

Adaptive Volatility Bands [AVB]Adaptive Volatility Bands (AVB) is a volatility-aware trend-following overlay indicator built on the Kaufman Adaptive Moving Average (KAMA) and dynamically adjusted Bollinger-style bands.
**Mathematical Foundation:**
The core of AVB is the Kaufman Efficiency Ratio (ER), which measures the ratio of directional price movement to total price movement over a lookback period. An ER near 1.0 indicates a strong trend with minimal noise; an ER near 0.0 indicates choppy, range-bound conditions. The KAMA uses this ratio to automatically adjust its smoothing constant — responding quickly during trends and slowly during consolidation.
The bands around the KAMA are not static standard deviations. Instead, they use an adaptive standard deviation that widens when the Efficiency Ratio is low (noisy markets) and tightens when ER is high (trending markets). This creates bands that contract during consolidation (squeeze) and expand during breakouts.
**Signal Logic:**
Buy signals are generated when price touches the lower band with RSI in oversold territory during an uptrend, or when a squeeze releases with price above the KAMA. Sell signals fire at the upper band with RSI overbought during a downtrend, or at squeeze release below KAMA. Volume confirmation is applied to filter low-conviction signals.
**Features:**
- Kaufman Adaptive Moving Average with adjustable fast/slow smoothing periods
- Adaptive volatility bands that respond to market efficiency
- Volatility squeeze detection with bar coloring
- RSI and volume filters for signal confirmation
- ATR-based stop-loss and take-profit levels
- Real-time dashboard showing efficiency ratio, RSI, volatility regime, and trend direction
- Fully customizable colors and parameters
**Use Cases:**
Suitable for forex, crypto, commodities, and equities across all timeframes. Works well on 15-minute to daily charts.
Indicator

Adaptive Trend ChannelAdaptive Trend Channel is designed to find the most reliable short-term and long-term trend channels automatically, instead of forcing the user to work with one arbitrary lookback length. The script scans a broad range of candidate periods, builds a regression-based channel for each one, and then compares them through a multi-factor selection process. The goal is not just to find a channel that looks clean, but one that is statistically solid and structurally meaningful. To do that, the indicator favors channels with strong linearity, efficient trend behavior, sufficient directional strength, good price containment inside the bands, controlled width, and stable quality across nearby lengths. This helps avoid weak or accidental fits and gives priority to channels that are more robust in practice.
For best results, it is strongly recommended to use a logarithmic chart and to enable the option "Enable for logarithmic price scale" in the indicator settings. This is especially important on assets with large percentage moves over time, because the channel geometry then reflects percentage-based price movement more accurately.
Color is also important and very simple to read:
if a very robust channel is found, it is displayed in blue by default. This means the selected channel passed the eligibility filters and qualified as a strong structure. If no channel is robust enough, the script can still display the best available candidate, but it will appear in gray by default.
OVERVIEW
Adaptive Trend Channel helps identify the best short-term and long-term trend channels without manually testing many different lengths. Instead of relying on fixed settings, it adapts to the market structure by selecting the channels that best balance fit, strength, consistency, and usability.
The indicator can display:
- the best short-term channel
- the best long-term channel
- an optional midline
- an optional data table with channel diagnostics
HOW IT WORKS
For each tested lookback period, the script builds a regression-based trend channel and measures its quality.
Two selection modes are available:
1. Pearson r
This mode focuses mainly on linear fit quality.
2. Robust Composite
This mode uses a broader decision framework and combines several factors to favor channels that are not only well fitted, but also more reliable as usable trend structures.
In Robust Composite mode, the selection can include:
- Pearson correlation
- trend efficiency
- ADX trend strength
- price containment inside the channel
- channel width control
- local stability across neighboring tested lengths
A channel is considered eligible only if it passes the minimum filters defined by the user, such as:
- minimum absolute Pearson r
- minimum ADX
- minimum containment ratio
- maximum allowed channel width
If at least one eligible channel is found, the strongest one is selected and displayed in blue by default.
If none qualifies, the script still displays the best available fallback channel, but in gray by default.
WHY THIS APPROACH
A fixed-length channel can work well in one market condition and fail badly in another. This script addresses that problem by testing multiple candidate lengths and ranking them with a more complete selection logic.
The method is designed to reduce three common issues:
- choosing an arbitrary lookback period
- overvaluing channels that only look good visually
- accepting channels that fit price poorly or are too unstable
By combining fit quality, structure, strength, containment, and stability, the indicator aims to produce channels that are more trustworthy and easier to interpret.
HOW TO READ IT
- The short-term channel helps track the active market structure.
- The long-term channel helps frame the broader trend.
- Blue by default means a robust eligible channel was found.
- Gray by default means the displayed channel is the best available one, but it did not pass the eligibility filters.
- The position of price inside the channel helps show whether price is near the upper band, lower band, or midline.
FEATURES
- Automatic search for the best short-term and long-term channels
- Adaptive selection across multiple lookback lengths
- Robust eligibility filtering
- Blue default color for robust eligible channels
- Gray default color for fallback non-eligible channels
- Support for linear and logarithmic mode
- Optional midline display
- Optional table with channel metrics
- Two detection methods: Pearson r or Robust Composite
TABLE METRICS
Depending on your settings, the table can display:
- best length
- selection metric
- stability
- trend efficiency
- Pearson r
- ADX
- annualized channel return
- annualized channel price return
MAIN INPUTS
- Show Best Short-Term Channel
- Show Best Long-Term Channel
- Enable for logarithmic price scale
- Display Deviation Multiplier
- Best Channel Detection
- minimum eligibility filters for Pearson r, ADX, containment, and width
- optional table settings
NOTES
- For best interpretation, use logarithmic mode on a logarithmic chart.
- Blue by default means the channel passed the eligibility filters and was considered robust.
- Gray by default means the script is showing the best fallback channel, but it is not eligible.
- Annualized return metrics are intended for daily, weekly, and monthly timeframes.
Adaptive Trend Channel is built for traders who want a more objective, adaptive, and robust way to identify high-quality trend channels. Indicator

AI Neural Trend Predictor [identityKa]The AI Neural Trend Predictor is a professional-grade, zero-lag trend tracking system designed to keep traders in massive moves while aggressively filtering out market noise. Traditional moving averages suffer from two fatal flaws: they either lag heavily behind the price, or they whipsaw the trader out of positions during minor pullbacks. This script solves both issues by combining a zero-lag mathematical smoothing algorithm with a dynamic volatility shield.
Core Mechanics & Detection
Zero-Lag Base Engine: The core of the algorithm utilizes a highly responsive, smoothed proxy to track the live price instantly, eliminating the delayed entry problem found in SMA or EMA based indicators.
Volatility Shield (Noise Filter): Instead of flipping signals the moment price crosses the baseline, the engine projects a dynamic ATR-based shield around the trend. During a bullish run, minor price drops will simply compress into the shield without triggering a premature SELL signal. The trend only flips when the institutional order flow breaks through the true volatility threshold.
Clear BUY / SELL Labels: The engine prints highly visible, definitive BUY (Green) or SELL (Red) labels directly on the chart, taking the guesswork out of your entries.
HUD Dashboard & AI Logic
The strictly positioned on-chart intelligence panel evaluates the live market state:
Dangerous (Orange): Displayed actively whenever the internal volatility ratio drops below the algorithmic threshold, indicating a Choppy or Ranging market. This warns the trader to avoid taking new positions until momentum returns.
LONG / SHORT: The engine generates a clear directional bias when the market shifts to a "TRENDING" state and the volatility shield remains unbreached in the direction of the trend.
How to Use It
This tool is built for capturing massive swings. When an AI BUY label appears, you ride the trend until the opposing SELL label is printed. Do not panic-sell during minor red candles (pullbacks); trust the Volatility Shield to keep you in the trade. For optimal results, ignore signals generated while the dashboard reads "Dangerous." Indicator

Omni-Flow Consensus [LuxAlgo]The Omni-Flow Consensus indicator is a high-performance momentum and liquidity oscillator designed to visualize the directional pressure behind price movements through volume-weighted aggression and adaptive smoothing. It provides a comprehensive view of market regimes, identifying high-conviction capital injections while filtering out low-probability market noise.
🔶 USAGE
The indicator is designed to be used as a primary trend-confirmation tool. Unlike standard oscillators that only track price, Omni-Flow incorporates volume and candle body relativity to determine if a move has "weight" behind it.
🔹 Momentum Regimes
Bullish Flow (Cyan): Occurs when the main flow line is above zero and expanding toward the upper bands. This indicates aggressive buying pressure. Bearish Flow (Red): Occurs when the main flow line is below zero and expanding toward the lower bands. This indicates aggressive selling pressure. Accumulation/Neutral (Gray): When the flow line stays within the "Zero Zone" (±10), the market is in a contraction phase. Users should exercise caution as this is often a "no-trade" zone.
🔹 Impulse Injections
The indicator plots small diamond shapes within the oscillator pane. These represent "Flow Injections"—moments where momentum has been confirmed by the Signal Strictness logic and has broken out of the neutral threshold. These are high-probability entry or trend-continuation points.
🔹 Gradient Candle Coloring
The script features a cinematic gradient coloring system for price bars. Instead of binary "Up/Down" colors, the candles transition smoothly between Bullish, Neutral, and Bearish states based on the flow intensity. This allows traders to visually "feel" the momentum fading or building before a crossover actually occurs.
🔶 HOW TO USE
Traders can utilize the Omni-Flow Consensus to filter entries and manage trend expectations:
Trend Confirmation: Look for the main flow line to cross the Zero Axis. A cross above zero suggests a shift toward bullish dominance, while a cross below suggests bearish dominance. Identifying Injections: Pay attention to the Diamond symbols. These appear when the flow line crosses its signal line and maintains its direction for a set number of bars (defined by Strictness). These are often the start of volatile "expansion" phases. Volatility Monitoring: When the flow line remains flat near the zero line and the dashboard displays "ACCUMULATION," it indicates a lack of directional conviction. Traders may use this as a signal to avoid trend-following strategies until an injection occurs. Exhaustion Signals: When the flow line enters the glow bands (±70 to ±90), the market is in an extreme state. While trends can persist here, a crossover of the signal line within these bands often precedes a mean reversion or deep pullback.
🔶 DETAILS
🔹 Smart-Flow Engine
To ensure the tool works across all assets (including Forex, which lacks centralized volume), the script uses a "Smart-Flow" proxy. If volume data is available, it calculates (Close - Open) / (High - Low) * Volume. If volume is missing, it automatically swaps to a Volatility Proxy using True Range, ensuring consistent behavior on any chart.
🔹 Adaptive Spectral Filter (ASF)
The main flow line uses an adaptive alpha-based smoothing technique. This allows the indicator to remain reactive during high-volatility spikes (reducing lag) while smoothing out "whipsaws" during sideways consolidation.
🔹 Stochastic Normalization
The values are mapped to a fixed -100 to +100 range using a double-lookback window. This ensures the oscillator utilizes the full vertical space of the pane, making Overbought and Oversold levels much easier to identify compared to standard Z-score oscillators.
🔶 SETTINGS
🔹 Core Logic
Flow Sensitivity: Adjusts the primary lookback for the flow calculation. Higher values result in a slower, more macro view. Spectral Smoothing: Controls the responsiveness of the Adaptive Spectral Filter. Signal Boost: A non-linear multiplier that "magnifies" movements near the zero line to make crossings more distinct.
🔹 Signal Filtering
Smooth Signals: When enabled, uses the Strictness and Threshold logic to remove false "whipsaw" signals. Signal Strictness: Defines how many bars the flow must maintain its position to confirm an "Impulse." Momentum Threshold: The level the flow must break (e.g., ±15) before a signal is considered valid.
🔹 Aesthetics
Gradient Candle Coloring: Toggles the smooth color transitions on the price chart. Glow Intensity: Adjusts the visual brightness of the "Momentum Fill" between the main and signal lines. Flow Dashboard: Enables a real-time HUD showing the current Regime, Flow Intensity %, and Signal Status. Indicator

Regime-Adaptive kNN Breakouts + Kalman Predictor [TechnicalZen]Regime-Adaptive kNN Breakout Classifier + Kalman Price Predictor
Why This Indicator Exists
Most breakout indicators treat every compression pattern equally. In reality, a volatility contraction forming during a high-ADX trending environment with surging volume behaves very differently from the same pattern in a choppy, low-volume consolidation.
This indicator addresses that gap by combining three distinct analytical engines:
Multi-Period Compression Detection — Scans across multiple bar periods to find the tightest range relative to recent history, identifying genuine volatility contraction zones where expansion is statistically likely.
Regime-Adaptive kNN Classification — A machine learning gate that evaluates the market regime surrounding each compression zone using Kalman-filtered features. Only setups with sufficient similarity to historically successful breakouts are allowed through.
Kalman Price Predictor — A state-space estimator tracking price position and velocity, enabling forward projection with a widening uncertainty cone.
The result is an indicator that learns which market conditions produce successful breakouts and provides a probabilistic price forecast — not just pattern detection.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW IT WORKS
1. Multi-Period Compression Detection
The engine evaluates bar ranges across 2 to 20 periods, computing each period's range (highest high minus lowest low) and comparing it against the minimum range observed within an adaptive lookback window. When the current range is tighter than any historical range in the window, a compression zone is identified. The smallest qualifying period is selected — representing the most extreme volatility contraction.
An optional Inside Bar filter adds a complementary signal when the current bar's range is entirely contained within the prior bar.
2. ADX-Adaptive Lookback Window
The comparison window dynamically adjusts based on trend strength:
High ADX (strong trend) — shorter lookback, more responsive to compression during momentum phases
Low ADX (ranging market) — longer lookback, requiring more extreme contraction before triggering
This prevents the indicator from being too sensitive in trending markets or too sluggish in ranging conditions.
3. Kalman-Filtered Feature Space
Four market regime features are computed on every bar and smoothed through independent Kalman filters using a position + velocity state-space model. The Kalman filter reduces noise while tracking each feature's rate of change — achieving smoothing without the lag penalty of traditional moving averages.
The kNN classifier operates entirely on these Kalman-filtered features:
Relative Volume — Volume / SMA(Volume, 100) — captures participation surge or drought, Kalman-smoothed to filter out single-bar volume spikes
Relative ATR — ATR(14) / SMA(ATR, 100) — captures volatility expansion vs contraction regime, Kalman-smoothed for stable regime identification
ADX Normalized — ADX / 50 — measures trend strength (direction-agnostic), Kalman-smoothed to track trend momentum
Distance from MA — (Close - Trend MA) / ATR — price position relative to trend, Kalman-smoothed to reduce whipsaw noise
By filtering the feature space through the Kalman estimator before classification, the kNN operates on cleaner, denoised regime signals rather than raw noisy measurements. This is the critical link between the Kalman filter and the kNN — the classifier's accuracy depends on the quality of its input features.
4. kNN Breakout Classification
When a compression zone triggers a breakout, the classifier:
Constructs a feature vector from the four Kalman-filtered regime features
Scans the history buffer using Manhattan distance to find similar past regime conditions
Selects the k-nearest resolved neighbors — only TP (take-profit) and SL (stop-loss) outcomes vote; pending and time exits are excluded entirely
Computes a distance-weighted classification score where closer neighbors have proportionally more influence
Compares the score against the user-defined confidence threshold
If the score falls below the threshold, the setup is silently skipped. The classifier has learned which combinations of volume regime, volatility regime, trend strength, and price position tend to produce winning breakouts.
Key design choices:
Adaptive k — k = floor(sqrt(resolved outcomes)), clamped between user-defined min/max. The number of neighbors consulted grows naturally as the classifier accumulates experience, preventing overfitting to sparse early data.
Warmup phase — During the first N resolved outcomes, all setups pass through to build the training set. The classifier only begins filtering after accumulating sufficient data.
Feedback loop — Every exit writes its outcome back to the history buffer. TP exits score 1.0, SL exits score 0.0. The classifier genuinely learns from the specific chart and timeframe it is applied to.
Distance-weighted voting — Prevents outlier neighbors from distorting the classification. A very close TP neighbor outweighs several distant SL neighbors, producing more nuanced probability estimates.
5. Kalman Price Predictor
A fifth Kalman filter runs on price itself, maintaining three estimates simultaneously:
Filtered position — optimal smoothed price estimate
Velocity — estimated rate of price change per bar
Covariance matrix — estimation uncertainty and cross-correlations
The velocity component enables forward projection: Predicted Price = Filtered Position + Velocity x Projection Bars . The uncertainty cone is scaled by ATR and widens proportionally to the square root of the projection horizon — reflecting the theoretical uncertainty growth of price over time.
Projection trail: The last 5 projections are displayed with graduated transparency (50% to 90%), creating a visual history of how the forecast has evolved. A consistent, parallel trail suggests strong directional conviction; a diverging or oscillating trail signals uncertainty.
6. Trend-Aware Exit System
The exit system uses four complementary mechanisms, each feeding outcomes back to the kNN:
Take Profit — R-multiple target (default 2R, where R = compression zone range). Scored as 1.0 in kNN feedback.
Stop Loss — Opposite side of compression zone, optionally requiring price to also be wrong-side of the Trend MA. This trend-aware condition reduces whipsaw stops in strong trends. Scored as 0.0 in kNN feedback.
Trailing Stop — Activates after 1R profit, trails by ATR x multiplier. Dynamic protection that locks in gains.
Time Exit — Maximum bars in trade before forced exit. Scored as 0.5 (neutral) — neither rewarding nor penalizing the kNN for inconclusive setups.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VISUAL GUIDE
Chart Elements
Compression boxes — Colored zones marking detected volatility contraction (green = bullish breakout, red = bearish)
Extended levels — Dotted lines projecting the high and low of each compression zone forward
Entry labels — Direction and kNN confidence percentage (e.g., "Long 72.5%")
Exit labels — TP / SL / T markers with R-multiple detail in tooltip
Projection line — Dashed line extending forward from Kalman-filtered price
Uncertainty cone — ATR-scaled filled area widening into the future
Projection trail — 5 fading historical projections showing forecast evolution
Kalman price line — Optional smoothed price curve (off by default)
Dashboard (bottom-right)
Win Rate — Percentage of resolved trades hitting TP (tinted green or red)
Trades — Win / Loss count
Mode — Distance-weighted classification
Phase — Warmup (building data) or Active (filtering enabled)
k — Current adaptive k value
Score — Latest kNN confidence score
History — Buffer fill level (e.g., 45/60)
Projection — Predicted price with directional arrow
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SETTINGS GUIDE
Detection
Enable Inside Bar (default: On) — Include Inside Bar patterns alongside compression detection
Adaptive kNN
Enable kNN Filter (default: On) — Toggle the ML classification gate
k Min / k Max (default: 2 / 10) — Bounds for adaptive k. Auto-scales with sqrt of resolved outcomes
Confidence Threshold (default: 0.25) — Minimum kNN score to accept a setup. Lower values are more permissive; higher values are more selective
Min Resolved to Activate (default: 15) — TP/SL outcomes needed before the classifier begins filtering
History Buffer Size (default: 60) — Maximum stored breakout patterns for comparison
Kalman Filter
Process Noise Q (default: 0.01) — Controls how much the filter expects the underlying signal to change between bars. Higher values make the filter more responsive but noisier
Measurement Noise R (default: 0.10) — Controls how much the filter distrusts each new measurement. Higher values produce smoother output with more lag
Show Price Projection (default: On) — Display the forward projection line and uncertainty cone
Projection Bars (default: 10) — How far forward to project price
Projection Color (default: Aqua) — Color for all projection elements
Show Uncertainty Cone (default: On) — Display the ATR-scaled confidence band
Cone Width (default: 1.0 ATR) — Width multiplier for the uncertainty cone. Adjustable per instrument
Show Kalman Price Line (default: Off) — Display the smoothed Kalman price estimate on chart
Trend Filter
Enable Trend Filter (default: On) — Restrict breakouts to trend-aligned direction only
Trend MA Mode (default: Adaptive) — Static = fixed MA length; Adaptive = MA length scales dynamically with the compression lookback
MA Type (default: EMA) — Exponential or Wilder's (RMA) moving average
Adaptive Multiplier (default: 2.0) — Lookback x Multiplier = MA length in adaptive mode
Static MA Length (default: 200) — Fixed MA length when in static mode
Adaptive Look Back
Look Back Mode (default: ADX Adaptive) — Static = fixed comparison window; ADX Adaptive = window scales with trend strength
ADX Length (default: 14) — Period for ADX calculation
ADX Low / High (default: 10 / 35) — ADX range mapped to lookback bounds. Higher ADX compresses the lookback
LB Min / LB Max (default: 20 / 120) — Minimum and maximum lookback window size
Exits
TP (R-multiple target) (default: On) — Take-profit at R-multiple of compression zone range
SL (opposite side) (default: On) — Stop-loss at opposite boundary of compression zone
Target R (default: 2.0) — Take-profit distance as multiple of range
Trend-Aware SL (default: On) — SL only triggers when price is also wrong-side of Trend MA
Trailing Stop (default: On) — Trails by ATR x multiplier after 1R profit
Trail ATR Multiplier (default: 1.5) — Trail distance = ATR(14) x this value
Time Exit (default: On, 50 bars) — Force exit after maximum bars in trade
Visual Settings
Bull / Bear / Time colors — Customizable directional colors
Box Fill / Border Transparency — Compression zone box appearance
Extend Levels (default: 50 bars) — Forward projection distance for compression zone levels
Level Width / Style — Line appearance for projected levels
Max Patterns Kept (default: 120) — Maximum drawing objects maintained on chart
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
THE KALMAN-kNN PIPELINE
The two ML components are not independent — they form a pipeline:
Kalman filters denoise the four regime features on every bar, producing clean estimates of volume regime, volatility regime, trend strength, and price position
kNN classifier operates on these Kalman-filtered features, comparing the current denoised regime against historically successful and unsuccessful breakout conditions
Kalman price filter independently tracks price dynamics, projecting the estimated trajectory forward with quantified uncertainty
The classifier's accuracy fundamentally depends on the quality of its input features. By feeding Kalman-filtered signals rather than raw measurements, the kNN compares regime states rather than noisy observations — producing more stable and meaningful similarity assessments.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CREDITS AND ACKNOWLEDGMENTS
This indicator builds upon concepts from two published works:
Smart NR2–NR20 and Inside Bar by Zeiierman — multi-period compression detection, adaptive lookback via ADX, and breakout trigger architecture
kNN Market Architecture by LuxAlgo — application of k-nearest neighbors classification to filter market signals using relative volatility and volume features
Original contributions in this indicator:
Kalman filter state-space estimation for feature smoothing (position + velocity model with full covariance tracking)
Kalman-to-kNN pipeline — classifier operates on denoised regime features, not raw measurements
Regime-adaptive kNN classification with distance-weighted voting on resolved outcomes only
Real-time feedback loop where exit outcomes update the kNN training data
Adaptive k scaling based on accumulated classifier experience
Kalman price predictor with forward projection and ATR-scaled uncertainty cone
Graduated projection trail showing forecast evolution
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This indicator is for educational and informational purposes only. It does not constitute financial advice. All investments involve risk, and past performance does not guarantee future results. The kNN classifier learns from historical patterns on the specific chart and timeframe it is applied to — its effectiveness may vary across different instruments and market conditions. Always conduct your own analysis and risk management.
Indicator

Adaptive Statistical Smoother [Pineify]Adaptive Statistical Smoother
The Adaptive Statistical Smoother is an overlay trend-following indicator that combines a forward-backward zero-lag EMA approximation with an R-Squared trend filter to produce an adaptive moving average that tightly tracks price during trending markets and deliberately diverges during ranging conditions — solving the core problem of traditional moving averages that generate excessive whipsaw signals in sideways price action. Instead of using a fixed smoothing period or a single-pass EMA, the indicator first constructs a bidirectional (zero-phase-shift) EMA baseline that virtually eliminates the lag inherent in standard exponential averages, then modulates how closely the final adaptive MA follows this baseline based on the real-time R-Squared coefficient of determination. When R-Squared confirms a strong linear trend, the MA converges toward the zero-lag target proportionally to trend strength; when R-Squared indicates a ranging market, the MA actively pushes away from price in the last known trend direction, creating a natural buffer zone that suppresses false crossovers. Dynamic standard-deviation volatility bands and R-Squared-filtered buy/sell signals complete the system, giving traders a statistically grounded, self-adjusting trend tool with built-in noise rejection.
Key Features
Forward-backward zero-lag EMA approximation — a two-pass EMA computation (forward pass followed by a backward iteration over historical values) that closely approximates a bidirectional filter, virtually eliminating the phase lag that causes standard EMAs to react late to trend changes.
R-Squared adaptive trend filter — the Pearson correlation coefficient squared (R²) between price and bar index measures how well a linear trend fits recent data. Values above 0.5 indicate trending conditions; values below indicate ranging. This statistical metric drives the core adaptive behavior of the MA.
Dual-regime moving average — during trending markets (R² > 0.5), the adaptive MA blends toward the zero-lag target proportionally to R², tracking price closely. During ranging markets (R² ≤ 0.5), the MA diverges from price in the last known direction, creating a buffer that prevents whipsaw crossovers.
Dynamic volatility bands — standard deviation of the source price over the statistical window, scaled by a user-defined multiplier, creates upper and lower bands that automatically expand during volatile periods and contract during quiet ones.
R-Squared-filtered buy/sell signals — crossover signals between price and the adaptive MA are only generated when R² exceeds 0.3, ensuring signals fire only when there is statistically meaningful trend strength and suppressing noise during flat markets.
Trend-adaptive coloring — the MA line, volatility cloud fill, and bar colors all dynamically switch between bullish and bearish colors based on the current trend state, providing instant visual identification of the prevailing direction.
How It Works
The indicator follows a multi-stage calculation pipeline that transforms raw price data into an adaptive, statistically filtered trend line:
Forward-backward zero-lag baseline: A standard EMA is first computed on the source price. Then a second pass iterates backward over the historical EMA values, applying the same EMA alpha (2 / (smooth + 1)) at each step across the lookback window. This two-pass approach approximates a zero-phase-shift filter — the resulting baseline tracks price turns almost immediately, without the half-period delay of a conventional EMA. This baseline serves as the "target" that the adaptive MA will converge toward when the market is trending.
R-Squared trend detection: The Pearson correlation between closing prices and bar indices over the statistical window is squared to produce R². This coefficient of determination measures the proportion of price variance explained by a linear trend. R² near 1.0 means price is moving in a clean, directional manner; R² near 0.0 means price is oscillating without a clear direction. The 0.5 threshold divides the market into "trending" and "ranging" regimes.
Adaptive MA computation: In trending mode (R² > 0.5), the adaptive MA is computed as a weighted blend: R² × target + (1 − R²) × previous MA. Stronger trends (higher R²) pull the MA closer to the zero-lag target; weaker trends allow it to lag slightly, providing natural smoothing. In ranging mode (R² ≤ 0.5), the MA moves away from price by the magnitude of the target's recent change, in the direction of the last known trend bias. This deliberate divergence creates separation between price and the MA, preventing the repeated false crossovers that plague fixed-parameter moving averages in choppy markets.
Volatility bands and signal generation: Standard deviation bands are added around the adaptive MA to visualize the current volatility regime. Buy and sell signals are generated on price crossovers of the MA, but only when R² exceeds 0.3 — a secondary filter that ensures even the crossover signals carry minimum statistical trend evidence.
Trading Ideas and Insights
Trend-following entries with lag reduction: The zero-lag baseline allows the adaptive MA to respond to trend initiations significantly faster than a standard EMA of equivalent smoothing. When a BUY signal fires (price crosses above the MA with R² > 0.3), the entry is closer to the actual trend start than what a conventional moving average crossover would provide, improving the risk/reward ratio of trend-following trades.
Whipsaw avoidance in ranging markets: The adaptive divergence mechanism during low-R² periods is specifically designed to prevent the most common failure mode of moving average systems — repeated false crossovers during sideways consolidation. Traders can trust that when a signal does fire, the statistical environment supports a directional move.
Volatility band breakout confirmation: When price breaks above the upper band or below the lower band while the adaptive MA is already in the corresponding trend state, it confirms a high-volatility directional expansion. These breakouts can be used to add to existing positions or to set trailing stops at the opposite band.
R-Squared as a standalone filter: Even without acting on the buy/sell signals, traders can use the implicit R-Squared regime (visible through the MA's behavior — tight tracking vs. divergence) as a filter for other strategies. Apply your existing entry rules only when the MA is tightly tracking price (trending regime), and stand aside when the MA visibly separates from price (ranging regime).
Multi-timeframe trend alignment: Apply the indicator on both a higher timeframe (e.g., daily) and a lower timeframe (e.g., 1-hour). Take lower-timeframe BUY signals only when the higher-timeframe adaptive MA is in bullish state, and SELL signals only when the higher-timeframe is bearish. This multi-timeframe alignment leverages the adaptive nature of the indicator across different time horizons.
How Multiple Indicators Work Together
The Adaptive Statistical Smoother integrates three distinct analytical components into a unified adaptive system, each addressing a specific weakness of traditional moving averages:
Forward-backward zero-lag EMA (lag elimination): Standard moving averages inherently lag price by approximately half their lookback period. The bidirectional EMA approximation addresses this by running a second smoothing pass in reverse over historical values, canceling out the phase shift. This gives the adaptive MA a responsive baseline to track during trends — without the noise sensitivity that comes from simply using a very short-period EMA.
R-Squared trend filter (regime detection): The R-Squared coefficient provides an objective, statistical answer to the question "is the market trending right now?" This replaces subjective visual assessment or fixed-threshold approaches (like ADX) with a measure rooted in linear regression theory. R² directly controls how the adaptive MA behaves — it is not merely a signal filter but the core adaptive mechanism that switches the MA between trend-tracking and range-diverging modes.
Standard deviation volatility bands (context visualization): The bands add a volatility dimension that neither the zero-lag baseline nor the R-Squared filter provides. They show traders the expected range of price movement around the adaptive MA, helping to distinguish between normal retracements within a trend (price stays within bands) and genuine trend reversals (price breaks through bands and crosses the MA).
The synergy is structural: zero-lag EMA (responsive baseline) → R-Squared (regime classification) → adaptive blending/divergence (the adaptive MA itself) → volatility bands (context envelope) → R²-filtered crossover signals (actionable entries/exits). The zero-lag baseline ensures the MA has a fast, accurate target to track; R-Squared determines whether to track it or diverge; and the volatility bands provide the visual context for interpreting the MA's position relative to price. Each component compensates for a specific weakness — lag, false signals in ranges, and lack of volatility context — that would undermine the system if any single component were used alone.
Unique Aspects
Statistical regime switching: Unlike adaptive moving averages that use volatility or momentum to adjust their speed (e.g., KAMA, VIDYA), the Adaptive Statistical Smoother uses R-Squared — a measure of trend linearity — to switch between two fundamentally different behaviors: convergence toward a target during trends and deliberate divergence during ranges. This is a qualitatively different approach that directly addresses the root cause of whipsaw (lack of trend) rather than a symptom (high volatility).
Bidirectional EMA approximation in Pine Script: True zero-phase-shift filters require processing the entire dataset in both directions, which is not natively possible in real-time bar-by-bar computation. The forward-backward loop in this indicator approximates this by iterating over historical forward-EMA values within the lookback window, achieving near-zero lag without requiring future data — a practical implementation of signal processing theory within Pine Script's constraints.
Directional divergence mechanism: During ranging markets, the adaptive MA does not simply freeze or slow down — it actively moves away from price in the last known trend direction. This creates increasing separation that requires a genuine trend resumption (not just noise) to produce a crossover, providing a self-adjusting buffer proportional to the ranging market's volatility.
Dual-threshold R-Squared filtering: The indicator uses two R-Squared thresholds for different purposes: 0.5 for the MA's adaptive regime switch (trending vs. ranging behavior) and 0.3 for signal generation (minimum trend evidence for crossover signals). This layered approach means the MA adapts its behavior at a stricter threshold while still allowing signals in moderately trending conditions, balancing responsiveness with noise rejection.
How to Use
Add the indicator to your chart. It overlays directly on the price chart, displaying the adaptive MA line, upper and lower volatility bands, and a shaded volatility cloud between the bands.
Observe the adaptive MA line (thick colored line). When it is green and tightly tracking price, the market is in a statistically confirmed uptrend. When it is red and tracking price closely, the market is in a confirmed downtrend. When the MA visibly separates from price, the R-Squared filter has detected a ranging market and the MA is in divergence mode.
Watch for BUY signals (green "BUY" labels below bars) — these fire when price crosses above the adaptive MA and R-Squared exceeds 0.3, indicating a bullish crossover with minimum statistical trend support. Consider entering long positions or closing short positions.
Watch for SELL signals (red "SELL" labels above bars) — these fire when price crosses below the adaptive MA and R-Squared exceeds 0.3, indicating a bearish crossover with trend confirmation. Consider entering short positions or closing long positions.
Use the volatility bands (shaded cloud) to gauge the expected price range around the adaptive MA. Price touching the upper band in an uptrend suggests extended momentum; price touching the lower band in a downtrend suggests extended selling pressure. Reversals from band extremes back toward the MA can serve as mean-reversion opportunities within the prevailing trend.
Monitor bar colors for a quick visual scan of the current trend state across the chart — green bars indicate bullish trend, red bars indicate bearish trend.
Adjust the Statistical Window to match your trading timeframe. Shorter windows (10–15) make the R-Squared filter more responsive to recent price behavior — suitable for intraday or short-term swing trading. Longer windows (25–50) provide a more stable trend assessment — suitable for position trading on daily or weekly charts.
Customization
Statistical Window (default: 20): The lookback period for both the R-Squared calculation and the standard deviation bands. This is the most impactful parameter. Shorter values make the indicator more responsive — the R-Squared filter reacts faster to regime changes and the volatility bands adjust more quickly. Longer values produce smoother, more stable readings that filter out short-term noise but may delay regime detection. Start with 20 for daily charts and adjust based on your asset's typical trend duration.
Forward-Backward Smoothing (default: 10): Controls the EMA period used in the zero-lag approximation. Lower values (5–7) produce a baseline that tracks price very closely, making the adaptive MA highly responsive during trends but potentially more sensitive to noise. Higher values (15–20) produce a smoother baseline with slightly more residual lag but better noise rejection. The interaction between this parameter and the Statistical Window determines the overall character of the indicator.
Volatility Multiplier (default: 1.5): Scales the standard deviation bands around the adaptive MA. Higher values (2.0–3.0) produce wider bands that contain more price action — useful for volatile assets or for identifying only extreme deviations. Lower values (0.5–1.0) produce tighter bands that price breaks more frequently — useful for identifying smaller volatility expansions or for more active trading styles.
Bullish / Bearish Colors: Fully customizable colors applied to the adaptive MA line, volatility bands, cloud fill, signal labels, and bar coloring. Adjust to match your chart theme or to improve visibility on different background colors.
Conclusion
The Adaptive Statistical Smoother brings a statistically rigorous approach to trend following by combining a forward-backward zero-lag EMA approximation with an R-Squared-driven adaptive regime filter. The zero-lag baseline eliminates the inherent delay of conventional moving averages, while the R-Squared coefficient provides an objective, real-time assessment of whether the market is trending or ranging. During trends, the adaptive MA converges toward the responsive baseline proportionally to trend strength; during ranges, it deliberately diverges to create a whipsaw-resistant buffer zone. Dynamic volatility bands add a contextual envelope, and dual-threshold R-Squared filtering ensures that buy and sell signals carry minimum statistical trend evidence. Whether used as a standalone trend-following system or as an adaptive trend filter for other strategies, the Adaptive Statistical Smoother provides a self-adjusting framework that adapts its behavior to the current market regime — tracking trends closely when they exist and stepping aside when they do not.
Indicator
