PROTECTED SOURCE SCRIPT

MTF K-Means Price Regimes [matteovesperi]

72
⚠️ The preview uses a custom example to identify support/resistance zones. due to the fact that this identifier clusterizes, this is possible. this example was set up "in a hurry", therefore it has a possible inaccuracy. When setting up the indicator, it is extremely important to select the correct parameters and double-check them on the selected history.


📊 OVERVIEW

Purpose

MTF K-Means Price Regimes is a TradingView indicator that automatically identifies and classifies the current market regime based on the K-Means machine learning algorithm. The indicator uses data from a higher timeframe (Multi-TimeFrame, MTF) to build stable classification and applies it to the working timeframe in real-time.

Key Features

Automatic market regime detection — the algorithm finds clusters of similar market conditions
Multi-timeframe (MTF) — clustering on higher TF, application on lower TF
Adaptive — model recalculates when a new HTF bar appears with a rolling window
Non-Repainting — classification is performed only on closed bars
Visualization — bar coloring + information panel with cluster characteristics
Flexible settings — from 2 to 10 clusters, customizable feature periods, HTF selection

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

🔬 TECHNICAL DETAILS

K-Means Clustering Algorithm

What is K-Means?

K-Means is one of the most popular clustering algorithms (unsupervised machine learning). It divides a dataset into K groups (clusters) so that similar elements are within each cluster, and different elements are between clusters.

Algorithm objective:
Minimize within-cluster variance (sum of squared distances from points to their cluster center).

How Does K-Means Work in Our Indicator?

Step 1: Data Collection

The indicator accumulates history from the higher timeframe (HTF):
  • RSI (Relative Strength Index) — overbought/oversold indicator
  • ATR% (Average True Range as % of price) — volatility indicator
  • ΔP% (Price Change in %) — trend strength and direction indicator


By default, 200 HTF bars are accumulated (clusterLookback parameter).

Step 2: Creating Feature Vectors

Each HTF bar is described by a three-dimensional vector:

Vector = [RSI, ATR%, ΔP%]


Step 3: Normalization (Z-Score)

All features are normalized to bring them to a common scale:

Normalized_Value = (Value - Mean) / StdDev


This is critically important, as RSI is in the range 0-100, while ATR% and ΔP% have different scales. Without normalization, one feature would dominate over others.

Step 4: K-Means++ Centroid Initialization

Instead of random selection of K initial centers, an improved K-Means++ method is used:

  • First centroid is randomly selected from the data
  • Each subsequent centroid is selected with probability proportional to the square of the distance to the nearest already selected centroid
  • This ensures better initial centroid distribution and faster convergence


Step 5: Iterative Optimization (Lloyd's Algorithm)


Repeat until convergence (or maxIterations):
1. Assignment step:
For each point find the nearest centroid and assign it to this cluster

2. Update step:
Recalculate centroids as the average of all points in each cluster

3. Convergence check:
If centroids shifted less than 0.001 → STOP


Euclidean distance in 3D space is used:

Distance = sqrt((RSI1 - RSI2)² + (ATR1 - ATR2)² + (ΔP1 - ΔP2)²)


Step 6: Adaptive Update

With each new HTF bar:
  • The oldest bar is removed from history (rolling window method)
  • New bar is added to history
  • K-Means algorithm is executed again on updated data
  • Model remains relevant for current market conditions


Real-Time Classification

After building the model (clusters + centroids), the indicator works in classification mode:

  • On each closed bar of the current timeframe, RSI, ATR%, ΔP% are calculated
  • Feature vector is normalized using HTF statistics (Mean/StdDev)
  • Distance to all K centroids is calculated
  • Bar is assigned to the cluster with minimum distance
  • Bar is colored with the corresponding cluster color


Important: Classification occurs only on a closed bar (barstate.isconfirmed), which guarantees no repainting.

Data Architecture


Persistent variables (var):
├── featureVectors[] - Normalized HTF feature vectors
├── centroids[] - Cluster center coordinates (K * 3 values)
├── assignments[] - Assignment of each HTF bar to a cluster
├── htfRsiHistory[] - History of RSI values from HTF
├── htfAtrHistory[] - History of ATR values from HTF
├── htfPcHistory[] - History of price changes from HTF
├── htfCloseHistory[] - History of close prices from HTF
├── htfRsiMean, htfRsiStd - Statistics for RSI normalization
├── htfAtrMean, htfAtrStd - Statistics for ATR normalization
├── htfPcMean, htfPcStd - Statistics for Price Change normalization
├── isCalculated - Model readiness flag
└── currentCluster - Current active cluster


All arrays are synchronized and updated atomically when a new HTF bar appears.

Computational Complexity

  • Data collection: O(1) per bar
  • K-Means (one pass):
    - Assignment: O(N * K) where N = number of points, K = number of clusters
    - Update: O(N * K)
    - Total: O(N * K * I) where I = number of iterations (usually 5-20)


Example: With N=200 HTF bars, K=5 clusters, I=20 iterations:
200 * 5 * 20 = 20,000 operations (executes quickly)

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

📖 USER GUIDE

Quick Start

1. Adding the Indicator


TradingView → Indicators → Favorites → MTF K-Means Price Regimes


Or copy the code from mtf_kmeans_price_regimes.pine into Pine Editor.

2. First Launch

When adding the indicator to the chart, you'll see a table in the upper right corner:


┌─────────────────────────┐
│ Status │ Collecting HTF │
├─────────────────────────┤
│ Collected│ 15 / 50 │
└─────────────────────────┘


This means the indicator is accumulating history from the higher timeframe. Wait until the counter reaches the minimum (default 50 bars for K=5).

3. Active Operation

After data collection is complete, the main table with cluster information will appear:


┌────┬──────┬──────┬──────┬──────────────┬────────┐
│ ID │ RSI │ ATR% │ ΔP% │ Description │Current │
├────┼──────┼──────┼──────┼──────────────┼────────┤
│ 1 │ 68.5 │ 2.15 │ 1.2 │ High Vol,Bull│ │
│ 2 │ 52.3 │ 0.85 │ 0.1 │ Low Vol,Flat │ ► │
│ 3 │ 35.2 │ 1.95 │ -1.5 │ High Vol,Bear│ │
└────┴──────┴──────┴──────┴──────────────┴────────┘


The arrow ► indicates the current active regime. Chart bars are colored with the corresponding cluster color.

Customizing for Your Strategy

Choosing Higher Timeframe (HTF)

Rule: HTF should be at least 4 times higher than the working timeframe.


| Working TF | Recommended HTF |
|------------|-----------------|
| 1 min | 15 min - 1H |
| 5 min | 1H - 4H |
| 15 min | 4H - D |
| 1H | D - W |
| 4H | D - W |
| D | W - M |


HTF Selection Effect:
  • Lower HTF (closer to working TF): More sensitive, frequently changing classification
  • Higher HTF (much larger than working TF): More stable, long-term regime assessment


Number of Clusters (K)


K = 2-3: Rough division (e.g., "uptrend", "downtrend", "flat")
K = 4-5: Optimal for most cases (DEFAULT: 5)
K = 6-8: Detailed segmentation (requires more data)
K = 9-10: Very fine division (only for long-term analysis with large windows)


Important constraint:
clusterLookback ≥ numClusters * 10

I.e., for K=5 you need at least 50 HTF bars, for K=10 — at least 100 bars.

Clustering Depth (clusterLookback)

This is the rolling window size for building the model.


50-100 HTF bars: Fast adaptation to market changes
200 HTF bars: Optimal balance (DEFAULT)
500-1000 HTF bars: Long-term, stable model


If you get an "Insufficient data" error:
  • Decrease clusterLookback
  • Or select a lower HTF (e.g., "4H" instead of "D")
  • Or decrease numClusters


Color Scheme

Default 10 colors:

  • Red → Often: strong bearish, high volatility
  • Orange → Transition, medium volatility
  • Yellow → Neutral, decreasing activity
  • Green → Often: strong bullish, high volatility
  • Blue → Medium bullish, medium volatility
  • Purple → Oversold, possible reversal
  • Fuchsia → Overbought, possible reversal
  • Lime → Strong upward momentum
  • Aqua → Consolidation, low volatility
  • White → Undefined regime (rare)


Important: Cluster colors are assigned randomly at each model recalculation! Don't rely on "red = bearish". Instead, look at the description in the table (RSI, ATR%, ΔP%).

You can customize colors in the "Colors" settings section.

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

⚙️ INDICATOR PARAMETERS

Main Parameters

Higher Timeframe (htf)
  • Type: Timeframe selection
  • Default: "D" (daily)
  • Description: Timeframe on which the clustering model is built
  • Recommendation: At least 4 times larger than your working TF


Clustering Depth (clusterLookback)
  • Type: Integer
  • Range: 50 - 2000
  • Default: 200
  • Description: Number of HTF bars for building the model (rolling window size)
  • Recommendation:
    - Increase for more stable long-term model
    - Decrease for fast adaptation or if there's insufficient historical data


Number of Clusters (K) (numClusters)
  • Type: Integer
  • Range: 2 - 10
  • Default: 5
  • Description: Number of market regimes the algorithm will identify
  • Recommendation:
    - K=3-4 for simple strategies (trending/ranging)
    - K=5-6 for universal strategies
    - K=7-10 only when clusterLookback ≥ 100*K


Max K-Means Iterations (maxIterations)
  • Type: Integer
  • Range: 5 - 50
  • Default: 20
  • Description: Maximum number of algorithm iterations
  • Recommendation:
    - 10-20 is sufficient for most cases
    - Increase to 30-50 if using K > 7


Feature Parameters

RSI Period (rsiLength)
  • Type: Integer
  • Default: 14
  • Description: Period for RSI calculation (overbought/oversold feature)
  • Recommendation:
    - 14 — standard
    - 7-10 — more sensitive
    - 20-25 — more smoothed


ATR Period (atrLength)
  • Type: Integer
  • Default: 14
  • Description: Period for ATR calculation (volatility feature)
  • Recommendation: Usually kept equal to rsiLength


Price Change Period (pcLength)
  • Type: Integer
  • Default: 5
  • Description: Period for percentage price change calculation (trend feature)
  • Recommendation:
    - 3-5 — short-term trend
    - 10-20 — medium-term trend


Visualization

Show Info Panel (showDashboard)
  • Type: Checkbox
  • Default: true
  • Description: Enables/disables the information table on the chart


Cluster Color 1-10
  • Type: Color selection
  • Description: Customize colors for visual cluster distinction
  • Recommendation: Use contrasting colors for better readability


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

📊 INTERPRETING RESULTS

Reading the Information Table


┌────┬──────┬──────┬──────┬──────────────┬────────┐
│ ID │ RSI │ ATR% │ ΔP% │ Description │Current │
├────┼──────┼──────┼──────┼──────────────┼────────┤
│ 1 │ 68.5 │ 2.15 │ 1.2 │ High Vol,Bull│ │
│ 2 │ 52.3 │ 0.85 │ 0.1 │ Low Vol,Flat │ ► │
│ 3 │ 35.2 │ 1.95 │ -1.5 │ High Vol,Bear│ │
│ 4 │ 45.0 │ 1.20 │ -0.3 │ Low Vol,Bear │ │
│ 5 │ 72.1 │ 3.05 │ 2.8 │ High Vol,Bull│ │
└────┴──────┴──────┴──────┴──────────────┴────────┘


"ID" Column
Cluster number (1-K). Order doesn't matter.

"RSI" Column
Average RSI value in the cluster (0-100):
  • < 30: Oversold zone
  • 30-45: Bearish sentiment
  • 45-55: Neutral zone
  • 55-70: Bullish sentiment
  • > 70: Overbought zone


"ATR%" Column
Average volatility in the cluster (as % of price):
  • < 1%: Low volatility (consolidation, narrow range)
  • 1-2%: Normal volatility
  • 2-3%: Elevated volatility
  • > 3%: High volatility (strong movements, impulses)


Compared to the average volatility across all clusters to determine "High Vol" or "Low Vol".

"ΔP%" Column
Average price change in the cluster (in % over pcLength period):
  • > +0.05%: Bullish regime
  • -0.05% ... +0.05%: Flat (sideways movement)
  • < -0.05%: Bearish regime


"Description" Column
Automatic interpretation:
  • "High Vol, Bull" → Strong upward momentum, high activity
  • "Low Vol, Flat" → Consolidation, narrow range, uncertainty
  • "High Vol, Bear" → Strong decline, panic, high activity
  • "Low Vol, Bull" → Slow growth, low activity
  • "Low Vol, Bear" → Slow decline, low activity


"Current" Column
Arrow shows which cluster the last closed bar of your working timeframe is in.

Typical Cluster Patterns

Example 1: Trend/Flat Division (K=3)


Cluster 1: RSI=65, ATR%=2.5, ΔP%=+1.5 → Bullish trend
Cluster 2: RSI=50, ATR%=0.8, ΔP%=0.0 → Flat/Consolidation
Cluster 3: RSI=35, ATR%=2.3, ΔP%=-1.4 → Bearish trend


Strategy: Open positions when regime changes Flat → Trend, avoid flat.

Example 2: Volatility Breakdown (K=5)


Cluster 1: RSI=72, ATR%=3.5, ΔP%=+2.5 → Strong bullish impulse (high risk)
Cluster 2: RSI=60, ATR%=1.5, ΔP%=+0.8 → Moderate bullish (optimal entry point)
Cluster 3: RSI=50, ATR%=0.7, ΔP%=0.0 → Flat
Cluster 4: RSI=40, ATR%=1.4, ΔP%=-0.7 → Moderate bearish
Cluster 5: RSI=28, ATR%=3.2, ΔP%=-2.3 → Strong bearish impulse (panic)


Strategy: Enter in Cluster 2 or 4, avoid extremes (1, 5).

Example 3: Mixed Regimes (K=7+)

With large K, clusters can represent condition combinations:
  • High RSI + Low volatility → "Quiet overbought"
  • Neutral RSI + High volatility → "Uncertainty with high activity"
  • Etc.


Requires individual analysis of each cluster.

Regime Changes

Important signal: Transition from one cluster to another!

Trading situation examples:
  • Flat → Bullish trend → Buy signal
  • Bullish trend → Flat → Take profit, close longs
  • Flat → Bearish trend → Sell signal
  • Bearish trend → Flat → Close shorts, wait


You can build a trading system based on the current active cluster and transitions between them.

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

💡 USAGE EXAMPLES

Example 1: Scalping with HTF Filter

Task: Scalping on 5-minute charts, but only enter in the direction of the daily regime.

Settings:
  • Working TF: 5 min
  • HTF: D (daily)
  • K: 3 (simple division)
  • clusterLookback: 100


Logic:

IF current cluster = "Bullish" (ΔP% > 0.5)
→ Look for long entry points on 5M

IF current cluster = "Bearish" (ΔP% < -0.5)
→ Look for short entry points on 5M

IF current cluster = "Flat"
→ Don't trade / reduce risk


Example 2: Swing Trading with Volatility Filtering

Task: Swing trading on 4H, enter only in regimes with medium volatility.

Settings:
  • Working TF: 4H
  • HTF: D (daily)
  • K: 5
  • clusterLookback: 200


Logic:

Allowed clusters for entry:
- ATR% from 1.5% to 2.5% (not too quiet, not too chaotic)
- ΔP% with clear direction (|ΔP%| > 0.5)

Prohibited clusters:
- ATR% > 3% → Too risky (possible gaps, sharp reversals)
- ATR% < 1% → Too quiet (small movements, commissions eat profit)


Example 3: Portfolio Rotation

Task: Managing a portfolio of multiple assets, allocate capital depending on regimes.

Settings:
  • Working TF: D (daily)
  • HTF: W (weekly)
  • K: 4
  • clusterLookback: 100


Logic:

For each asset in portfolio:

IF regime = "Strong trend + Low volatility"
→ Increase asset weight in portfolio (40-50%)

IF regime = "Medium trend + Medium volatility"
→ Standard weight (20-30%)

IF regime = "Flat" or "High volatility without trend"
→ Minimum weight or exclude (0-10%)


Example 4: Combining with Other Indicators

MTF K-Means as a filter:


Main strategy: MA Crossover
Filter: MTF K-Means on higher TF

Rule:
IF MA_fast > MA_slow AND Cluster = "Bullish regime"
→ LONG

IF MA_fast < MA_slow AND Cluster = "Bearish regime"
→ SHORT

ELSE
→ Don't trade (regime doesn't confirm signal)


This dramatically reduces false signals in unsuitable market conditions.

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

📈 OPTIMIZATION RECOMMENDATIONS

Optimal Settings for Different Styles

Day Trading

Working TF: 5M - 15M
HTF: 1H - 4H
numClusters: 4-5
clusterLookback: 100-150


Swing Trading

Working TF: 1H - 4H
HTF: D
numClusters: 5-6
clusterLookback: 150-250


Position Trading

Working TF: D
HTF: W - M
numClusters: 4-5
clusterLookback: 100-200


Scalping

Working TF: 1M - 5M
HTF: 15M - 1H
numClusters: 3-4
clusterLookback: 50-100


Backtesting

To evaluate effectiveness:

  • Load historical data (minimum 2x clusterLookback HTF bars)
  • Apply the indicator with your settings
  • Study cluster change history:
    - Do changes coincide with actual trend transitions?
    - How often do false signals occur?
  • Optimize parameters:
    - If too much noise → increase HTF or clusterLookback
    - If reaction too slow → decrease HTF or increase numClusters


Combining with Other Techniques

Regime-Based Approach:

MTF K-Means (regime identification)

+---+---+---+
| | | |
v v v v
Trend Flat High_Vol Low_Vol
↓ ↓ ↓ ↓
Strategy_A Strategy_B Don't_trade


Examples:
  • Trend: Use trend-following strategies (MA crossover, Breakout)
  • Flat: Use mean-reversion strategies (RSI, Bollinger Bands)
  • High volatility: Reduce position sizes, widen stops
  • Low volatility: Expect breakout, don't open positions inside range


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

📞 SUPPORT

Report an Issue

If you found a bug or have a suggestion for improvement:

  • Describe the problem in as much detail as possible
  • Specify your indicator settings
  • Attach a screenshot (if possible)
  • Specify the asset and timeframe where the problem is observed

Отказ от ответственности

Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.