Picture of the author

TradingView-RU

06/23 00:01

Machine Learning Smart Money Concepts | GainzAlgo


What It Is

This is a TradingView indicator that fuses two ideas that don't usually share a chart:


Smart Money Concepts (SMC): classic structure-based trading, specifically Change of Character (CHoCH) detection off swing highs/lows.
K-Nearest Neighbors (KNN) : a simple, non-parametric machine learning method — used to score each new structure break against the most similar structure breaks that happened earlier on the same chart, and to project price targets from how those similar setups actually played out.


In plain terms: every time price breaks structure, the indicator asks 'what did the last several breaks that looked like this one actually do?' and uses that historical evidence to assign a probability and a set of price targets, instead of relying on a fixed, one-size-fits-all rule.

Structure first (the SMC layer)

The indicator finds swing points using ta.pivothigh / ta.pivotlow with a configurable pivot length. It tracks a simple internal trend state (marketTrend: up / down / neutral) and flags a CHoCH:

Bullish CHoCH: price closes above the last swing high while the prevailing state was not already bullish (i.e., a flip up).

Bearish CHoCH: price closes below the last swing low while the prevailing state was not already bearish (i.e., a flip down).

This is the standard SMC definition of "change of character", the first sign that the prior trend may be giving way to a new one.

Turning the break into an actionable trade

When a CHoCH fires, the script doesn't just say "structure broke", it measures how it broke, using three features computed over the bars since the prior swing point:


Volume delta: An estimate of buy vs. sell pressure on each bar (derived from where the close sits within the bar's range, weighted by volume), averaged over the move. Positive = buyers dominant, negative = sellers dominant.
Displacement: The size of the price move since the swing point, normalized by ATR. This tells you whether the break was a forceful, large-range move or a weak, barely-there one, independent of the instrument's raw volatility.
Velocity: Displacement divided by the number of bars it took (i.e., how fast the move happened.)


Finding lookalikes (the KNN engine)

The script keeps a rolling database (capped at 2,000 records, with a "Historical Memory Window" limiting how far back it'll search) of every previous CHoCH's fingerprint, along with what actually happened afterward.

For a new CHoCH, it:


Filters the database to past events of the same direction (bullish vs. bearish) within the memory window.
Computes Euclidean distance between the new fingerprint and every stored one.
Pulls the K nearest neighbors (default 5) — the most similar past setups.


Uses those neighbors to calculate:

1. A Significance Score = % of the K neighbors where price moved further in the favorable direction than the adverse direction (i.e., a "win rate" among lookalikes).
2. Three price targets, built from the distribution of how far those neighbor setups actually ran:


TP1 (mean × conservative scalar) — a toned-down average outcome.
TP2 (median) — the typical outcome.
TP3 (75th percentile) — a stretch/aggressive outcome.


These 3 targets are represented by a drawn box on the chart.

How the database learns (the "training" loop)

This is the part that makes it adaptive rather than a static rule set. On every bar, the script checks: did a CHoCH happen exactly lookahead bars ago (default 20)? If so, it now has enough hindsight to grade that old setup:


It walks forward through those 20 bars and finds the maximum favorable excursion and maximum adverse excursion from the price at the time of that old CHoCH.
It labels the outcome (favorable > adverse → success) and records the fingerprint as it existed at that time, plus the result, into the database.


So the model is continuously and only ever trained on fully resolved history, never on the bar currently forming. It's an online-learning loop: today's signal is scored against yesterday's already-graded outcomes, and today's setup itself won't be graded and added to the database until lookahead bars from now.

What's Drawn on the Chart


CHoCH connector line: solid line from the broken swing point to the breakout close.
Broken level marker: dashed line showing the swing high/low that got taken out, plus a short dotted line marking the actual break.
Wick trace: a stylized multi-layer glow line tracing the wicks leading into the break (purely visual/aesthetic).
CHoCH region fill: soft fill color between the wick trace and the broken level.
Probability badge: small label (▲/▼ + %) printed near the break; gets a ★ if direction confidence is ≥85%.
CHoCH tag: secondary tiny label showing "+CHoCH / −CHoCH" and the raw significance score.
Target box — a shaded box from TP1 to TP3 with a dotted TP2 line through the middle, extended a fixed number of bars to the right.
Dynamic Target Ribbon: a smoothed (SMA-based) pair of lines tracking the most recent bull/bear target, with a fill between them, giving a continuously-updating visual "zone."
Side panel (table): live readout of bias (bullish/bearish/neutral), current significance score, last TP1/TP2/TP3 with counts of how many of each tier are still outstanding (unhit), database size, current volume delta, the active swing high/low, and the K / Window settings.


Settings Guide

🧠 Quant Engine


Look-Ahead Window (Bars): how many bars forward the model waits before grading a past CHoCH and adding it to the database. Larger = more patient/accurate labeling but slower to build a dataset.

Historical Memory Window: how far back (in bars) the KNN search is allowed to look for neighbors. Smaller = more regime-adaptive (recent behavior only); larger = more data per query but less responsive to regime shifts.

K-Nearest Neighbors (K): how many lookalikes to average over. Lower K = more reactive/noisy; higher K = smoother but slower to reflect new behavior.

Min Significance Score (%): the threshold below which the indicator visually marks a signal as low-conviction (greyed badge) rather than colored.

ATR Period: used both for the displacement feature and for badge placement offsets.

Pivot Length: swing-point sensitivity; smaller = more (and earlier, but less confirmed) swings.

🎯 Target Levels




Conservative Scalar: multiplier applied to the mean neighbor outcome to produce TP1.

Target Extension (Bars): how far right the target box are drawn.

How to Use It


Wait for a CHoCH badge. Direction is shown by the arrow; the percentage is the KNN-derived probability that this break behaves like the favorable-outcome neighbors.
Check the significance score against your threshold. Setups below your Min Significance Score print in a neutral grey, treat these as "structure broke, but the model has no strong opinion" rather than as a clean signal.
Use the target box as a planning zone, not a guarantee. TP1 is the conservative/likely zone, TP2 the typical outcome among similar past moves, TP3 the stretch target, read it as a probability-weighted range, not a prediction.
Watch "DB Records" in the side panel. Early on a chart, or on a symbol with limited history, the database will be small and the KNN matches less statistically meaningful. The model gets more reliable as it accumulates more graded history.
Use the ★ marker as an extra filter. It only appears when directional confidence (not the raw significance score, but the bull/bear probability split) is ≥85%.
Cross-reference with the bias/volume-delta in the panel for a quick read on whether the broader trend state and the most recent candle pressure agree with the new signal.


Helpful Trade Tips

Tip 1: Works extremely well on larger timeframes. Sweet spot is hourly and daily, which positions this indicator well for swing traders. Let's take a look at some examples:

Example 1: SPY 30-Minute timeframe


Here, with extended hours disabled, SPY snagged 8/9 of its target boxes.

Example 2: QQQ Weekly



Here, QQQ touched all recent targets.

This highlights the strength of SMC to aid traders in having higher timeframe and longer range expectations based on the structural changes of the market.

Let's highlight a few other examples:

Example 3: BTCUSD on the Daily timeframe



Here, BTC shows its loyalty to SMC, hitting the majority of its targets on the daily timeframe.

Note: One thing to be aware of, to prevent the chart from looking overly cluttered, the box length has been sized to the immedate range to prevent a messy looking chart. However, you can manually adjust the size by using the "Manual Extension (Bars)" feature in the settings menu to increase the width of the target boxes. Here is an example:



Alerts

You can set custom alerts with this indicator to trigger buy and sell signals based on a probability threshold. You can set the probability thresholds for bearish and bullish conditions within the indicators setting menus. Then, toggle over to the alerts menu and set your Buy and Sell alerts. From there, you will be notified when there is a CHoCH that meets your specific probability threshold.
#World Cup Predictions: 100,000 USDT Daily#TradFi Trading Strategies Sharing Challenge#1$ Margin Trade
1Поделиться

Все комментарии0НовыеВ тренде

avatar
НовыеВ тренде