OPEN-SOURCE SCRIPT

Regime-Adaptive kNN Breakouts + Kalman Predictor [TechnicalZen]

1 594
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:

  1. Constructs a feature vector from the four Kalman-filtered regime features
  2. Scans the history buffer using Manhattan distance to find similar past regime conditions
  3. Selects the k-nearest resolved neighbors — only TP (take-profit) and SL (stop-loss) outcomes vote; pending and time exits are excluded entirely
  4. Computes a distance-weighted classification score where closer neighbors have proportionally more influence
  5. 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


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

[size=16]SETTINGS GUIDE[/size]

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:

  1. Kalman filters denoise the four regime features on every bar, producing clean estimates of volume regime, volatility regime, trend strength, and price position
  2. kNN classifier operates on these Kalman-filtered features, comparing the current denoised regime against historically successful and unsuccessful breakout conditions
  3. 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.

คำจำกัดสิทธิ์ความรับผิดชอบ

ข้อมูลและบทความไม่ได้มีวัตถุประสงค์เพื่อก่อให้เกิดกิจกรรมทางการเงิน, การลงทุน, การซื้อขาย, ข้อเสนอแนะ หรือคำแนะนำประเภทอื่น ๆ ที่ให้หรือรับรองโดย TradingView อ่านเพิ่มเติมใน ข้อกำหนดการใช้งาน