top of page

Free indicators

Public·5 members

Kmeans Regime Scanner -NEW

PART 1: WEBSITE STRATEGY PAGE

KMeans Regime Scanner


SECTION A — MAIN STRATEGY PAGE


KMeans Regime Scanner

Machine learning meets market structure — backed by 27,000+ bars of ES 5-minute data.


What Is It?


Most indicators tell you where price is. This one tells you how the market is posturing — the subtle shift in structure that precedes a move, not the move itself.


The KMeans Regime Scanner uses an unsupervised machine learning algorithm — K-Means clustering — to continuously organize price into three dynamic zones. Each zone has a gravitational center (centroid) and a width defined by real intra-cluster volatility. The system then monitors how those zones move relative to each other, classifying the current market structure into one of 486 possible regime states.


When a specific structural pattern appears — the pattern discovered through analysis of over 27,000 bars of ES 5-minute continuous contract data — the indicator fires an entry signal.


The result: two long regimes with 80%+ historical win rates, validated through a combinatorial regime search pipeline built on the Strategy Factory system at MarketFragments.com.


For Traders (Plain English)


Think of the three bands as gravity zones.


Red is the lower zone. Yellow is the middle. Green is the upper. Price orbits these zones, and the zones themselves shift as the market breathes.


The key insight is this: we don't trade when price touches a band — we trade when the bands start moving in a specific way.


Imagine you're watching the lower band drift down while the middle band holds perfectly flat. On the surface, the market looks weak. But that middle band isn't breaking. Big players are absorbing selling pressure at the lower levels, and the anchor refuses to move. When sellers exhaust, price snaps upward through the middle band. That's the pattern. That's the edge.


Long Pattern 1 (80.6% historical win rate): Lower band drifting down, middle band flat, average drifting down — market in trending state, normal volatility. The coiled spring.


Long Pattern 2 (81.8% historical win rate): Both the bottom and lower-middle bands drifting down, but the anchor (C2, middle band) holding flat. Slightly more aggressive version of Pattern 1.


Short Pattern (62.3% historical win rate, included with caution): Middle band drifting down, others flat, average flat — a different structural profile. Weaker edge, smaller sample confidence — use this signal selectively or for confirmation only.


Signals fire on transition only — the first bar a regime appears, not every bar it persists. You're entering at the recognition moment, not after the move has already begun.

Reading the Chart

  Visual Element What It Means

  ──────────────────────────────────────────────────────────────────────

  Red band +cloud Lower cluster zone (C1)

  Yellow band + cloud Middle cluster zone (C2) — the anchor

  Green band + cloud Upper cluster zone (C3)

  Thick colored line Cluster average: green = trending up,  red = trending down, cyan = neutral

  Green triangle up Long entry signal — 80%+ regime detected

  Red triangle down Short entry signal — 62% regime (use with caution)

  Yellow line Entry price

  Red line + cloud Stop loss zone

  Green line + cloud Target zone

  Entry labels BTO with SL and TGT prices printed on chart

  Exit labels STC with P&L printed on chart

  Info table (top-right) Live regime state, signal status, centroid prices, trade info

  ──────────────────────────────────────────────────────────────────────


Risk Management — Don't Change the Stop


Default ATR stop multiple: 1.0x ATR Default target multiple: 1.5x ATR


These settings are intentional and pre-optimized. The 80%+ win rate edge is derived partly because of the tight stop — it filters out weak entries automatically. Do not widen the stop to "give it room." Widening the stop removes the edge. If the trade is wrong, it should be wrong quickly and cheaply.


When NOT to trade:

  • When the regime table shows "COMP" (compressed SD) — bands are too tight, volatility squeeze likely

  • When the regime table shows "EXP" (expanded SD) — volatility has already released

  • Outside regular US equity futures hours

  • When the table reads "No signal" — stay flat


Parameters (Pre-Optimized — No Changes Recommended)


Parameter Default Notes

Lookback 200 bars ~2.5 trading days on 5-min ES

K 3 Fixed — three clusters

Slope Threshold 0.1 ATR-normalized Classifies centroid slope as directional

ATR Stop Multiple 1.0 Tight — the edge depends on this

Target Multiple 1.5 1.5:1 reward-to-risk


All defaults were derived from backtesting on 27,000+ bars of unadjusted ES continuous contract data.


For Quants — Technical Architecture


Layer 1: K-Means Clustering K=3 clusters on price, initialized at the 25th/50th/75th percentile of the lookback price range. Per-bar cluster assignment uses ATR-normalized distance, ensuring that the distance metric scales with current volatility rather than nominal price. Intra-cluster standard deviations are computed and smoothed over a short window to produce the band widths. This is a rolling, online implementation — the algorithm updates every bar.


Layer 2: Band Structure Feature Extraction (L2 Features) Six features are computed simultaneously from the cluster structure:


  1. C1 slope direction (up / flat / down) — 10-bar linear slope, normalized by ATR, threshold ±0.1

  2. C2 slope direction (up / flat / down)

  3. C3 slope direction (up / flat / down)

  4. Cluster average slope direction (up / flat / down)

  5. Range state (trending / transitioning / ranging) — based on price distance from C2 and intra-cluster SD relative to rolling mean

  6. SD compression state (compressed / normal / expanded) — ratio of current avg SD to 50-bar rolling mean; compressed < 0.7, expanded > 1.3


Layer 3: Combinatorial Regime Search With 4 directional features (3 states each) × 1 range state (2 states) × 1 SD state (3 states), the full state space is 3⁴ × 2 × 3 = 486 possible regime combinations. The Python-based analysis pipeline (kmeans_regime_analyzer.py) enumerates all combinations, measures forward return distributions (win rate, Sharpe, avg MFE) for each, and filters by minimum sample size (≥30 trades). Long and short directions are searched independently.


The patterns implemented in this indicator were selected from the top-ranked combinations in that search.


Discovery Results (ES 5-min, ~27,487 bars):


Regime Pattern Win Rate Avg Fwd Return Trades Sharpe


flat_C1 + flat_C2 + down_C3 +

down_avg + trending + normal_SD 80.6% +0.43% 36 0.70

-----------------------------------------------------------------------------------------------------------------------------------------------------------

down_C1 + flat_C2 + down_C3 +

down_avg + trending + normal_SD 81.8% +0.27% 33 0.48

-----------------------------------------------------------------------------------------------------------------------------------------------------------

flat_C1 + up_C2 + flat_C3 + flat_avg

+ trending + normal_SD 78.9% +0.31% 38 0.55

-----------------------------------------------------------------------------------------------------------------------------------------------------------

flat_C1 + down_C2 + flat_C3 + flat_avg

+ trending + normal_SD 62.3% +0.18% 69 0.35 (Short)

-----------------------------------------------------------------------------------------------------------------------------------------------------


Walk-Forward Validation: 72.0% WR across 2,929 entries in pipeline Phase 3. Statistical significance: Binomial p < 0.001 vs. 50% null hypothesis for top regimes.


Important Disclaimers


  • All results are from backtesting on unadjusted ES continuous contract data

  • Sample sizes of 33–36 trades are statistically significant but narrow — 95% CI on WR is approximately 65%–92%

  • The short-side pattern (62.3%) has a weaker edge and wider confidence interval — use selectively

  • This strategy has not been forward tested in live markets

  • Live trading conditions including slippage, fills, and data adjustments may produce different results

  • This is a research and educational tool, not financial advice


SECTION B — K-MEANS RSI OSCILLATOR (Companion Tool — TOS ThinkScript)

Research Preview | Coming Soon to TradingView


K-Means RSI Oscillator


Adaptive momentum oscillator — K-Means applied to RSI values instead of price.


Note: This indicator is currently in research preview on ThinkOrSwim. A TradingView version is in development. Results have not yet been formally tested or backtested.


The Idea


Standard RSI uses fixed overbought and oversold levels — 70 and 30 — that never change regardless of the instrument, timeframe, or market regime. During a strong trending market, RSI can sit at 70+ for dozens of bars without a reversal. In a choppy, mean-reverting market, 70 barely matters at all.


The K-Means RSI Oscillator takes a different approach: it applies K-Means clustering directly to RSI values to discover where overbought and oversold actually are for the current instrument and market conditions — dynamically, over a rolling lookback window.


The result is three adaptive bands on the RSI oscillator: a green oversold zone, a yellow neutral zone, and a red overbought zone. These bands contract and expand with the momentum environment, not with a human-set static level.


As an additional layer, the RSI itself is computed using the Laguerre filter — a technique introduced by John F. Ehlers in Cybernetic Analysis for Stocks and Futures — which uses a four-pole recursive filter to produce a smoother, more responsive oscillator than standard RSI with significantly less lag.


The Gamma Factor — What Makes It Unique


The Laguerre RSI has one critical tuning parameter: gamma. Gamma controls the filter's damping — how quickly the oscillator responds to price changes versus how much noise it smooths out. Standard implementations use a single, manually-chosen gamma value.


This indicator takes gamma further. Seven different gamma calculation methods are available:


Gamma Type What It Measures

Standard Classic fractal energy — ratio of cumulative true range to total range, normalized by log(n)

Lanczos Gamma-function-based approximation for smoother fractional dimension estimates

MultifractalQM Average of fractal dimensions at q=1, q=2, q=4 moments — captures scaling behavior across multiple moment orders

MultifractalScale Fractal dimension computed at three time scales (n, 2n, n/2) and averaged — multi- scale view of self-similarity

VolatilityGK Standard fractal energy scaled by Garman-Klass volatility (OHLC estimator) — volatility-adjusted gamma

VolatilitySD Standard fractal energy scaled by normalized standard deviation of true range

EntropyShannon entropy of true range distribution across 10 bins — gamma reflects informational complexity


Each method produces a different characterization of the market's current "efficiency state" — how directional versus chaotic price movement is. The selected gamma value directly shapes how the RSI responds to that state.


Signal Modes


Crossover Mode: Classic signal — RSI crosses out of the oversold or overbought K-Means band. Simple, fast, traditional.


Compound State Mode: A more sophisticated two-stage entry. For longs: RSI must first cross below the dynamic overbought threshold (bearish push), then fall into the oversold zone (seller exhaustion), and only then does a signal fire on the next directional move. This pattern hunts for the momentum reversal within a structured sequence, reducing random crossover noise.


Confluence Signals: When a signal fires and RSI is at the outer edge of the extreme band (inside the oversold zone for longs), the signal is flagged as high-confluence — plotted in cyan rather than green.


What's Good About It


  • Adaptive zones: Overbought/oversold levels evolve with the market. No manual tuning required.

  • Seven gamma types: Each captures a meaningfully different view of market efficiency. Sophisticated users can align gamma selection with their market-structure thesis.

  • Re-centered oscillator: RSI is subtracted from the K-Means band average and scaled by 100, so the indicator oscillates around zero — visually intuitive and easier to interpret than 0–100 scale.

  • Cluster transition markers: Cyan dots on the RSI line show when the oscillator crosses into a new K-Means zone — a subtle but useful leading indicator of momentum regime change.

  • Dual signal logic: Two distinct entry mechanisms give traders flexibility to match their style.


What's Uncertain or Risky


  • Not yet tested: No backtesting has been performed on the RSI component. All observations are qualitative. Treat this as a research tool, not a proven strategy.

  • Gamma selection is not yet automated: Choosing the right gamma type for the current regime requires judgment. The wrong gamma on the wrong market can produce misleading signals. Future work will include a regime-conditioned gamma selector.

  • Combinatorial risk: With 7 gamma types × 2 signal modes × variable lookback, the parameter space is large. If tested empirically without proper walk-forward validation, overfitting risk is high.

  • Lag in fast markets: Despite the Laguerre filter's efficiency, K-Means clustering on a rolling lookback has inherent lag during rapid regime transitions. Signals may arrive late during sharp trend initiations.

  • Feedback between RSI and its own clustering: Because K-Means clusters the RSI values it's computing on, the bands are somewhat self-referential. In markets with unusual RSI distributions, this can produce band configurations that are difficult to interpret intuitively.


This tool is free, shared in the spirit of open research. If you test it and have results, we want to hear from you. MarketFragments.com is building toward a community of rigorous, data-driven traders — and the RSI oscillator is an invitation to collaborate.


PART 2: TRADINGVIEW PUBLICATION DESCRIPTION


KMeans Regime Scanner

by MarketFragments.com | AI Strategy Factory


Plain English First

This indicator uses machine learning to find three dynamic price zones on your chart — think of them as gravitational bands that price orbits around. It then watches how those bands move, not where price is. When the bands form a specific structural pattern discovered in 27,000+ bars of ES 5-minute data, it fires an entry signal.


The edge: two long regimes with 80%+ historical win rates on ES 5-min data.

The key insight is that when the lower band drifts down while the middle band holds flat, the market is showing institutional accumulation — sellers pressing the lower boundary while the anchor refuses to break. When sellers exhaust, the move is typically sharp. You're positioned at the coiled spring, not after it releases.


Signals

🟢 Long Pattern 1 — 80.6% Win Rate C1 flat | C2 flat | C3 down | Average down | Trending | Normal SD

🟢 Long Pattern 2 — 81.8% Win Rate C1 down | C2 flat | C3 down | Average down | Trending | Normal SD

🔴 Short Pattern — 62.3% Win Rate (use with caution) C1 flat | C2 down | C3 flat | Average flat | Trending | Normal SD

Entry fires on state transition only — the first bar the regime appears, not every bar it persists.


Chart Features

  • 3 colored bands with SD clouds (red / yellow / green)

  • Thick cluster average line — color-coded by direction

  • Green/red trade zones (entry → target and entry → stop)

  • Entry labels with stop and target prices printed directly on chart

  • Exit labels with P&L

  • Full info table (top-right): regime state, signal name, trade direction

  • Bar coloring while in trade


Parameters (Pre-Optimized — No Changes Needed)


All defaults are tuned from backtesting on 27,000+ bars of unadjusted ES continuous contract. Key settings:


  • Lookback: 200 bars (~2.5 trading days on 5-min)

  • K: 3 (fixed)

  • Slope Threshold: 0.1 ATR-normalized

  • ATR Stop Multiple: 1.0 (tight — the edge IS the tight stop)

  • Target Multiple: 1.5 (1.5:1 R:R)


Technical Summary (For Quants)


Layer 1 — K-Means Clustering: K=3 clusters with ATR-normalized distances. Centroids initialized at price percentiles. Rolling online implementation, updates every bar.


Layer 2 — 6-Feature Regime Classification: Four centroid slope directions (3 states each) + range state (trending/transitioning/ranging) + SD compression state (compressed/normal/expanded) = 3⁴ × 2 × 3 = 486 possible states evaluated.


Layer 3 — Combinatorial Discovery: Python pipeline enumerated all 486 states, measured forward returns at 1.0 ATR stop / 1.5 ATR target, filtered by ≥30 trade minimum. Results sorted by win rate with Sharpe ratio as secondary filter.


Walk-forward: 72.0% WR across 2,929 entries (Phase 3 pipeline validation). Statistical significance: Binomial p < 0.001 vs. 50% null hypothesis.


Disclaimers

  • Backtesting results only — not forward tested

  • 33–36 trades per top regime = small sample. 95% CI on WR: approximately 65%–92%

  • Short signal (62.3%) is weaker and should be used selectively

  • Results based on unadjusted ES continuous contract data

  • Live slippage and fills will affect outcomes

  • Not financial advice


Free for public use. Shared by MarketFragments.com — a quantitative research community for serious traders and developers.


Attached:

TOS Bands:


TradingView:


TOS RSI:



51 Views
Brain with financial data analysis.

Inquiries at :

Important Risk Notice: Trading involves substantial risk of loss. This is educational content only—not advice. Full details here  ------------>  

Proceed only if you're prepared.

tel#: (843) 321-8514

bottom of page