OPEN-SOURCE SCRIPT

ML Liquidity Zone Classifier [PhenLabs]

33 483
📊 ML Liquidity Zone Classifier [PhenLabs]

Version: PineScript™ v6

snapshot

📌 Description

ML Liquidity Zone Classifier brings machine-learning-based filtering to liquidity mapping. Instead of drawing every possible order block, equal high, equal low, or volume zone, it evaluates current market conditions and only renders zones that score above a configurable confidence threshold.

The script uses a rolling k-Nearest Neighbors (k-NN) classifier built directly in Pine Script. Each potential zone is described using three normalized features: relative volume, higher-timeframe alignment, and displacement strength. Those features are compared against a rolling training set of prior bars to estimate whether the current setup resembles historically meaningful liquidity events.

The result is a cleaner liquidity tool designed to reduce chart clutter, improve selectivity, and help traders focus on zones with stronger contextual backing.

🚀 Points of Innovation

• Built-in k-NN classifier for liquidity zone confidence scoring
• Uses normalized multi-factor features instead of binary pattern logic alone
• Non-repainting delayed labeling system for training samples
• Auto higher-timeframe alignment that scales with the chart timeframe
• Zone overlap control, mitigation logic, and max-height clamping for cleaner structure
• Confidence-gated rendering so weak setups never reach the chart

🔧 Core Components

• KNN Classifier: Measures similarity between the current setup and prior labeled setups using Euclidean distance across three features
• Feature Engine: Converts volume, HTF proximity, and candle displacement into normalized 0 to 1 inputs
• Zone Detection Layer: Detects bullish and bearish order blocks, equal highs, equal lows, and high-volume nodes
• Zone Quality Gate: Filters zones by confidence, spacing, overlap, and size constraints
• Zone Lifecycle Manager: Maintains arrays for boxes and labels, prunes old zones, and removes mitigated ones
• Dashboard: Displays last detected zone, confidence score, and higher-timeframe directional bias

🔥 Key Features

• Machine-learning confidence score from 0 to 100 for every valid setup
• Automatic higher-timeframe selection based on current chart timeframe
• Support for bullish and bearish order blocks using ATR-based displacement logic
• Equal high and equal low detection using ATR-derived tolerance bands
• High-volume node detection using rolling average volume and local peak validation
• Zone deduplication to avoid stacked boxes at the same price area
• Optional mitigation that deletes broken zones after price closes through them
• Compact dashboard for live context and last-zone tracking

🎨 Visualization

• Confidence-based zone coloring with stronger opacity and border emphasis for higher-quality zones
• Labels printed directly on each zone with the zone type and confidence percentage
• Right-extended boxes so active liquidity areas remain visible into future price action
• Dashboard in the top-right corner showing Last Zone, Confidence, and HTF Bias
• Bullish zones are displayed in green tones, bearish zones in red tones, and lower-confidence zones fade toward orange or gray

📖 Usage Guidelines

KNN Classifier Settings

• K (neighbors) — Default: 5 — Controls how many historical neighbors are used when calculating confidence. Lower values react faster; higher values smooth the model.
• Training window — Default: 100 — Sets the maximum number of historical labeled samples stored in the rolling training set. Larger values add context but may slow adaptation.

HTF Alignment Settings

• Auto HTF — Default: true — Automatically selects a higher timeframe proportional to the current chart timeframe.
• Auto HTF multiplier — Default: 12.0 — Multiplies the current chart period to estimate the target higher timeframe.
• Manual HTF — Default: D — Used only when Auto HTF is disabled.

Zone Detection Settings

• Volume spike multiplier — Default: 1.5 — Minimum volume expansion required for a high-volume node.
• Order block ATR mult — Default: 1.5 — Minimum candle body size relative to ATR required to qualify as a displacement candle.
• Equal H/L tolerance — Default: 0.1 — ATR-based tolerance used to compare pivot levels for equal highs and equal lows.

Zone Quality Settings

• Min confidence to draw a zone — Default: 65 — Minimum classifier score required before a zone is rendered.
• Min bars between zones — Default: 5 — Cooldown period between newly drawn zones.
• Merge distance (ATR) — Default: 0.75 — Distance threshold used to reject overlapping or near-duplicate zones.
• Max zone height (ATR) — Default: 2.0 — Maximum vertical size of a zone before it is clamped.
• Remove zones when price breaks them — Default: true — Deletes support or resistance zones once price closes through them.
• Max visible zones — Default: 6 — Keeps only the most recent zones visible on the chart.

Advanced Settings

• ATR length — Default: 14 — Used for displacement measurement, tolerance scaling, and size normalization.
• Volume average length — Default: 20 — Rolling baseline for relative volume calculations.
• Volume node peak window — Default: 20 — Lookback used to confirm whether a bar is a true local volume peak.
• Pivot length — Default: 5 — Controls sensitivity for equal-high and equal-low pivot detection.
• Label evaluation window — Default: 10 — Number of bars waited before assigning a training label to a past setup.
• Label move threshold (ATR) — Default: 1.0 — Required future move in ATR units for a past setup to be labeled high probability.
• Show dashboard — Default: true — Enables or disables the on-chart summary table.

✅ Best Use Cases

• Traders who want fewer but higher-quality liquidity zones
• SMC and ICT-style workflows that need stronger filtering on OB and EQH/EQL logic
• Multi-timeframe traders who value HTF context in zone selection
• Intraday traders trying to avoid clutter from weak or repeated structure levels
• Quant-minded users who prefer confidence-based rendering over raw pattern detection

⚠️ Limitations

• The classifier is still a lightweight Pine implementation, not a full external ML model
• Confidence depends on the quality of recent market history inside the selected training window
• The script needs time to build its training set before meaningful zones begin to appear
• In highly abnormal volatility regimes, recent historical neighbors may be less representative
• This tool is a probability filter, not a guaranteed reversal or continuation signal

💡 What Makes This Unique

• Applies a true rolling k-NN classification process to liquidity-zone filtering inside Pine Script
• Combines market structure logic with volume, HTF context, and ATR displacement in one scoring model
• Keeps the chart clean by combining confidence gating, overlap suppression, cooldown spacing, mitigation, and pruning
• Gives traders an interpretable probability score instead of forcing all detected zones to appear equally important

🔬 How It Works

1. Feature Extraction

Each confirmed bar is converted into a three-feature vector. The script measures relative volume versus its moving average, distance to the nearest higher-timeframe OHLC level in ATR terms, and candle displacement strength based on body size versus ATR.

2. Delayed Labeling

After a configurable number of future bars passes, the script checks whether price moved far enough from the original bar. If that move exceeds the ATR-based threshold, the historical sample is labeled as high probability; otherwise it is labeled low probability.

3. KNN Confidence Scoring

When a new liquidity event appears, the script compares its feature vector against the rolling training set. It finds the nearest historical samples using Euclidean distance and converts their votes into a 0 to 100 confidence score.

4. Zone Validation

A zone is only drawn if the confidence exceeds the minimum threshold and the candidate zone does not overlap an existing one too closely. Oversized zones are clamped, repeated zones are filtered out, and only one new zone can be placed within the cooldown window.

5. Live Zone Management

Once drawn, zones extend to the right and remain active until mitigated. If price closes through a bullish zone from above or a bearish zone from below, the zone can be automatically removed to keep the display current.

Note:
This script is designed to be selective. If you use stricter confidence thresholds, larger gap settings, and mitigation enabled, you will typically see fewer but cleaner zones. Lowering the quality filters will increase signal frequency, but also increases chart noise.

Wyłączenie odpowiedzialności

Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.