Watermark Pro @SafarTradesWatermark Pro
Watermark Pro is a customizable branding and metadata overlay for PulseWire charts. It helps create a clean, professional workspace while keeping important chart information consistently visible.
The indicator combines customizable branding, chart metadata, and account status badges into a single configurable layout, making it suitable for personal trading, screenshots, educational content, and social media publishing.
Branding Panel
Display a fully customizable title and subtitle with flexible positioning to maintain a consistent visual identity across all charts.
Account Status Badge
Display a customizable status badge (e.g., Live Account, Demo Account, Funded Account, Backtesting) with multiple styling options to clearly identify the chart environment.
Chart Metadata
Optionally display the current date, trading symbol, and timeframe in a dedicated information panel that updates automatically as charts change.
Customization
Every component can be customized independently, allowing you to configure the layout to match your personal workflow and visual preferences.
Theme presets
Branding panel
Account status badge
Chart metadata panel
Flexible positioning
Color and typography controls
Badge styling options
Intended Use
Watermark Pro is suitable for traders, educators, analysts, and content creators who want consistent chart branding and a clean presentation for trading, analysis, screenshots, and educational content. Indicator

Regime-Conditional Correlation [RC Tools]RC Tools — Regime-Conditional Correlation
─────────────────────────────────────────────────────────────
█ OVERVIEW
Plain rolling correlation between two assets is well-covered ground. The angle here: correlation is not a constant — it changes with the market regime. This tool computes rolling correlation against a second symbol of your choice and buckets it by the same regime framework as the Regime Classifier, so you can see whether a correlation you're relying on actually holds up across market conditions, or only shows up in one of them.
█ WHAT IT DOES
Plots rolling correlation (Pearson, default 20-bar window) between the current chart's symbol and a compare symbol you choose. Colours the background by the current market regime (Trending — Expansion/Exhaustion, Ranging — Quiet/Volatile), using the identical directionality × volatility-percentile logic as the Regime Classifier. A table shows the current regime and correlation, plus the average correlation, its standard deviation, and the sample count for each of the four regimes historically.
█ THE THEORY BEHIND IT
A single "the correlation is 0.8" number hides a lot. Two assets can be tightly linked during calm trending markets and decouple completely during volatile chop — or vice versa. Regime-conditioning the correlation surfaces that structure instead of averaging it away. This matters directly for anything relying on a stable cross-asset relationship: hedges, pairs, or diversification assumptions that quietly break exactly when you need them most (in the volatile regime).
█ HOW IT IS CALCULATED
CORRELATION: standard Pearson correlation between the current symbol's close and the compare symbol's close (fetched via request.security on the same timeframe), over a rolling window (default 20 bars).
REGIME: identical to the Regime Classifier — Efficiency Ratio for directionality, percentile-ranked realised volatility for volatility state, crossed to give four states. Regime is measured on the CURRENT chart's own price action, not the compare symbol. See the Regime Classifier's description for the full methodology.
The correlation reading and the regime are both "as of now" — contemporaneous — so unlike the Regime Classifier's forward-return table, no forward-looking attribution is needed here: each confirmed bar's correlation is added directly to the running average for whichever regime was active on that same bar.
█ SETTINGS & CONFIGURATION
• Compare Symbol (default BTCUSD) — the second asset to correlate against
• Correlation Length (default 20 bars)
• Regime settings mirror the Regime Classifier exactly (Efficiency Ratio lookback, directionality threshold, realised vol lookback, percentile window, volatility percentile threshold) — keep these in sync if you run both indicators together
• Paint Main Chart Background — off by default; enable on only one of the two indicators if running both, to avoid overlapping backgrounds
█ HOW TO USE IT
Check whether a correlation you're relying on is regime-dependent before trusting it. Example: if a hedge shows strong negative correlation in Ranging — Quiet but the average correlation flips or weakens in Ranging — Volatile, that hedge may not protect you exactly when volatility spikes. Always check the sample count (N) per regime before drawing conclusions — a regime with few historical bars hasn't been tested enough to trust its average.
█ LIMITATIONS
• Correlation is measured over a short rolling window and is noisy by nature — it will swing even when the underlying relationship is stable.
• The compare symbol is fetched via request.security on the same timeframe; illiquid symbols, different exchange sessions, or timezone misalignment can introduce lag or missing values.
• Regime classification carries the same caveats as the Regime Classifier: it is backward-looking by construction, unstable near threshold boundaries, and needs substantial history to be reliable.
• Per-regime correlation statistics accumulate only from where the chart's loaded history begins — early sample counts are small and not yet statistically meaningful.
• This script does NOT repaint. All classification and correlation display values update on confirmed bar close only.
█ DISCLAIMER
For educational and informational purposes only. Nothing here is financial advice. Past correlation between any two assets does not indicate future results. Trade at your own risk.
Indicator

Kalman Trailing Stop (KTS)█ OVERVIEW
The Kalman Trailing Stop (KTS) is an advanced, math-driven trend-following system designed to keep you in winning trades longer while dynamically filtering out market noise.
Instead of relying on static moving averages or basic ATR multipliers, KTS utilizes a 2D Kalman Filter combined with Statistical Digital Signal Processing (DSP) and Williams Market Structure. It adapts to volatility and volume in real-time, effectively distinguishing between genuine trend shifts and temporary liquidity sweeps.
█ CORE MECHANICS
1. 2D Kalman Adaptive Trailing Stop
At the heart of the indicator is a robust 2D Kalman filter that tracks both price level and velocity.
Volume-Weighted Variance: The trailing stop becomes highly responsive during high-volume pushes (high trust) and flattens out during low-volume consolidation (low trust), preventing premature stop-outs.
Sigmoid Smoothing & Structural Anchoring: Instead of jagged, abrupt jumps, the stop uses sigmoid transitions to smoothly glide to new structural floors/ceilings derived from recent Intermediate-Term Highs and Lows (ITH/ITL).
Slope Confirmation: The trailing stop will only flip its directional bias if the underlying Kalman baseline slope confirms the reversal, neutralizing fake-outs.
2. Statistical Plunger Logic (Liquidity Sweeps)
Markets frequently sweep liquidity beyond technical levels before reversing. The "Plunger" logic mathematically identifies these traps.
Dynamic Sweep Multiplier: By tracking the kurtosis (fat-tail distribution) of price returns, the script dynamically expands its sweep threshold during periods of wild volatility.
Wick Filtering: It detects deep wicks that pierce the Kalman bands and close strongly back within the bar's range, highlighting statistically validated exhaustion points.
3. Algorithmic Pyramiding & Volatility Warnings
Scale-In Detection: KTS monitors volume footprints to identify safe zones to add to your position. It looks for a sequence of volume "dry-up" during a pullback, followed by a volume-backed breakout past recent market structure.
Livermore Ejector Concept: The indicator flags abnormal, massive range expansions that occur against the prevailing trend, acting as an early warning system for sudden momentum shifts.
4. Built-in Risk & Performance Engine
Dynamic Position Sizing: Automatically calculates raw position and pyramid sizes based on your account equity, risk percentage, and maximum leverage.
Live Performance Dashboard: A built-in HUD tracks both the Global and Recent Profit Factor (PF) of the main trend signals, alongside the real-time distance to your trailing stop.
█ VISUAL GUIDE
Colored Gradient Band: The main Kalman Trailing Stop. Green indicates an active long trend; Red indicates an active short trend.
Large Diamonds (♦️): Main Trend Entries. Triggered when price breaks the Kalman Stop with slope confirmation.
Small Triangles (🔼/🔽): Bullish and Bearish Plunger signals. These indicate deep liquidity sweeps and wick rejections at statistical extremes.
Small Crosses (➕): Algorithmic Pyramid signals. Opportunities to scale into the current trend based on volume dry-ups and structural breakouts.
Yellow X-Crosses (❌): Abnormal Reaction Warnings. Signals a massive volatility spike moving against your active position.
█ SETTINGS
Kalman Trailing Stop Settings
Kalman Responsiveness: Adjusts how quickly the system reacts to price changes (1-100).
Trailing Stop Distance (SD): Sets the baseline width of the trailing stop from the Kalman-smoothed price, measured in standard deviations of the True Range. A higher value (e.g., 3.0) gives the trade more breathing room, while a lower value tightens the stop.
Disclaimer
This script is designed for educational and informational purposes only. Trading involves significant risk. The built-in performance table is an un-optimized raw calculation and should not be used as a guarantee of future system profitability. Indicator

Drawdown [WynTrader]Drawdown
Hello my friend
Before trading an unfamiliar asset, it's worth seeing how it survived its toughest moments — including major market crashes. This indicator reveals every significant decline a security has experienced: how far it dropped, and how long it took. Seeing a past drawdown of -54% over 13 months makes the next correction far less intimidating.
Use it to measure real risk, set realistic expectations, and trade with more confidence.
█ CONCEPTS
A drawdown is the decline from a price peak to the lowest point that follows. The indicator automatically detects every peak and trough, filtering out noise to keep only declines at or above your chosen threshold (default: 20%).
█ FEATURES
Threshold — Set the minimum decline to display, so only meaningful crashes appear.
Boxes & Labels — Each drawdown is highlighted on the chart from peak to trough, labeled with its duration and amplitude (e.g., 13M -54%).
History Table — Lists every recorded drawdown with start/end dates, span, and decline %. Sortable and adjustable in size.
█ CONCLUSION
Before investing, check an asset's drawdown history: how deep, how long, did it recover? These questions reveal its true volatility and resilience. A chart without this history tells only half the story.
█ WYNTRADER
I'm not a Pine Script programmer — just a trader building tools for my own analysis. A few rough edges may remain. Enjoy!
WynTrader Indicator

Premium/Discount ML Zones [PickMyTrade]What does it do?
Builds a Premium / Equilibrium / Discount map from a higher-timeframe dealing range, then runs an online logistic regression over every price level inside that map to detect the exact band where the model currently reads a directional edge. Because the range is read from one anchor timeframe, the zones sit at the same prices whether you view the 5m, 1h or Daily chart.
────────────────────────────────────
The intellectual problem
Premium/Discount is a location framework: above the 50% equilibrium of a dealing range price is expensive, below it price is cheap. Two problems show up the moment you try to automate it.
First — the range is usually drawn on whatever chart you are looking at. A 5-minute chart finds 5-minute swings, so it anchors to a micro-range that may be a few points wide. The Daily chart finds a range a hundred times larger. The same price is then simultaneously "premium" on one timeframe and "discount" on another, and the label stops meaning anything. The conventional discipline is to define the range on a higher timeframe and drop down only to execute — never to redraw the range on the execution chart.
Second — location alone is not an edge. Knowing price is in the lower half of a range tells you it is cheap relative to that range. It does not tell you whether cheapness is currently being rewarded. In a strong downtrend every discount print keeps getting cheaper. Location is a filter; something else has to decide whether the location is worth acting on.
This indicator separates those two jobs. The dealing range and its three zones are the map , anchored once on a higher timeframe. A logistic regression trained on the chart's own history is the decision , and it is what marks the actionable band inside the map.
────────────────────────────────────
How the dealing range is anchored
The range is built from confirmed swing highs and lows read from the Dealing Range Timeframe (default Daily) via request.security(..., lookahead=barmerge.lookahead_off) . Each side re-anchors to its most recent confirmed swing, with guards that keep the pair coherent:
if not na(ph) and (na(swingLow) or ph > swingLow) swingHigh := ph if not na(pl) and (na(swingHigh) or pl < swingHigh) swingLow := pl
Those guards are what make the range track the current leg rather than a fixed lookback window. In an uptrend each new higher low pulls the low side up with price, instead of leaving equilibrium pinned to an ancient low that price has long since left behind.
From that range:
Equilibrium — the exact 50% midpoint, (rangeHigh + rangeLow) / 2 Equilibrium band — a neutral fair-value zone of ± Equilibrium Band × range around the midpoint (default ±10%, i.e. the middle 20%). No signals fire inside it. Premium — everything above the band. Discount — everything below it.
Break of structure — when price closes beyond the anchored range, the old range is stale until a new swing confirms. A bearish BOS blocks longs and a bullish BOS blocks shorts, so the model does not fade a breakout while waiting for the range to re-anchor.
────────────────────────────────────
How the logistic regression works
Step 1 — Three z-score normalised features
All three are standardised over the Z-Score Window (default 50) so the model is scale-invariant across instruments and timeframes.
F1 — Position in range : where the close sits between the range low and high, clamped to 0–1. This is the premium/discount coordinate itself. F2 — Dwell time : a rolling time-at-price measure — the fraction of the last N bars that closed within one price band of the current close. High dwell means price has spent real time here; a level touched once in a spike scores low. F3 — Momentum : rate of change over the momentum length, normalised. Distinguishes a discount that is stabilising from one that is still falling.
Step 2 — Online gradient descent with L2 regularization
There is no fixed training window and no retraining pass. Each confirmed bar is labelled from its forward return over the Label Horizon, and the weights take one gradient step per bar, always evaluated on the previous bar's features so no current-bar information leaks into the update:
_pred = f_sigmoid(w0 + w1f1 + w2f2 + w3*f3 ) _label = label_bull ? 1.0 : 0.0 _err = _label - _pred w1 := w1 + i_learn_rate * (_err * f1 - i_l2_lambda * w1)
The - i_l2_lambda * w1 term is weight decay: it pulls weights back toward zero each step, which stops any single feature from running away to an extreme value on a stretch of trending data. The bias term w0 is deliberately left unregularized — it carries the base rate, not a feature relationship.
Step 3 — Posterior
post_bull = f_sigmoid(w0 + w1f1 + w2f2 + w3*f3) post_bear = 1.0 - post_bull
Step 4 — The ML entry zone (what the model detects)
This is the part that does the work. Rather than only scoring the bar in front of it, the model scores every price level inside the discount half and the premium half — sweeping the position feature across the zone while holding dwell and momentum at their current values — and marks the contiguous band where its probability clears the Entry Threshold:
for j = 0 to i_nbins float p = rangeLow + (eq_bot - rangeLow) * j / i_nbins float f1p = ((p - rangeLow) / range_size - pos_mean) / pos_std float pbup = f_sigmoid(base + w1 * f1p) if pbup >= i_posterior_thresh ml_long_lo := na(ml_long_lo) ? p : math.min(ml_long_lo, p) ml_long_hi := na(ml_long_hi) ? p : math.max(ml_long_hi, p)
That band is the ML Buy / Sell Zone drawn on the chart. It is the exact price range in which a signal would fire right now — visible before price arrives there. Its thickness is meaningful: a thin band means only a sliver of the zone clears the threshold, a thick band means the model reads an edge across most of the zone. When nothing clears the threshold, the band disappears entirely rather than showing a level the model does not support.
────────────────────────────────────
Reading the indicator
PREMIUM box (orange) — upper region of the HTF range. Shorts are considered here only. EQUILIBRIUM box (grey) — the fair-value band around the 50% midpoint. Nothing fires here by design. DISCOUNT box (blue) — lower region. Longs are considered here only. ML BUY / SELL ZONE (bright band) — the model-detected band inside the discount/premium region, labelled with the peak probability found in that band. ● circle (blue) — high-conviction long: P(Bull) ≥ 0.85. ▲ triangle (blue) — standard long: P(Bull) ≥ threshold. ● circle (orange) — high-conviction short: P(Bear) ≥ 0.85. ▼ triangle (orange) — standard short: P(Bear) ≥ threshold. Dashed equilibrium line — the exact 50% midpoint. Dashed SL / TP lines — reference levels from the range extreme at ATR × multiplier and the Risk:Reward ratio.
Only the first bar of each signal cluster fires — if conditions stay true for several bars, only the transition bar is marked.
Info table (top-right)
● LIVE (green) — the model has taken ≥ Training Samples Needed gradient steps. ● WARMUP (yellow) — still accumulating; signals suppressed. Zone — Premium / Equilibrium / Discount, or BOS ↑ / BOS ↓ (yellow) when price has broken the range. P(Bull) / P(Bear) — live posterior at the current bar. N Trained — total gradient updates taken.
────────────────────────────────────
Inputs
Dealing Range Dealing Range Timeframe — whose swings define the map (default D). Set it equal to or higher than your execution chart. This is the input that makes the zones identical across timeframes. Swing Left / Right Bars — swing definition on the anchor timeframe (default 3/3). Right Bars is the confirmation delay: the range re-anchors that many anchor-timeframe bars after a swing forms. Equilibrium Band — half-width of the neutral zone as a fraction of range (default 0.10). Set 0 to collapse it to a single line.
Dwell-Time Feature Scan / Dwell Bands (default 20) — price resolution for the entry-zone scan and the dwell band width. Dwell Lookback (default 50).
Logistic Regression Training Samples Needed — gradient updates before signals activate (default 80). Entry Threshold — minimum probability to fire a signal and to light the ML zone (default 0.65). Learning Rate — gradient step size (default 0.05). Higher adapts faster but noisier. L2 Regularization — weight decay (default 0.001). 0 disables it. Label Horizon (default 5), Momentum Length (default 14), Z-Score Window (default 50).
Signal Levels Show SL/TP Lines, ATR Period, SL ATR Buffer (default 1.2), Risk:Reward (default 1.8).
Visual / Display Show Premium/Discount Map, Show ML Entry Zone, Zone Left Extent / Forward Extend, Show Equilibrium Line, Regime Background, zone colours. Zen Mode — hides SL/TP lines and the table; map and ML zone remain.
────────────────────────────────────
Three alerts included
PD ML - Long — discount long fired PD ML - Short — premium short fired PD ML - Any Signal — either direction
────────────────────────────────────
Technical notes
Swing detection on the anchor timeframe needs Swing Right Bars of that timeframe to confirm. With the Daily default that is a three-day confirmation delay before the range re-anchors. This is inherent to non-repainting swing detection, not a tunable away. request.security uses lookahead_off , so historical bars use only confirmed anchor-timeframe values. The developing anchor bar updates in real time, which is expected behaviour for a live higher-timeframe reference. The dwell feature counts closes within one band of the current close over the lookback — a bar-based proxy for time-at-price. It does not use tick or volume-profile data. The entry-zone scan holds dwell and momentum fixed while sweeping position. It answers "if price were at level X, with today's momentum and dwell, what would the model read?" — a counterfactual across location, not a forecast of the path. Logistic regression assumes a monotonic relationship between each feature and the log-odds. Real price behaviour is not always monotonic in position-within-range; the model captures the dominant direction of that relationship, not its curvature.
────────────────────────────────────
Requirements and limitations
The model needs Training Samples Needed gradient steps before signals activate; on short-history charts the table shows WARMUP and nothing fires. Weights are learned per chart and per timeframe — switching symbol or timeframe restarts the learning from zero.
Probabilities are the model's read of patterns in its own training history. They are not a probability of profit, and patterns that historically preceded a directional move may not repeat.
The equilibrium band is deliberately dead space. If you want signals nearer the midpoint, reduce the band toward 0 — but the closer to fair value you trade, the less the premium/discount premise is contributing.
If the Dealing Range Timeframe is left blank or set below your chart's timeframe, the range is computed on the chart timeframe and the cross-timeframe consistency is lost. That is the failure mode this indicator exists to avoid.
The three zones describe location within one dealing range. They carry no information about ranges above them — a Daily discount can sit inside a Weekly premium.
────────────────────────────────────
Risk disclosure
Nothing here forecasts price. The zones describe where price sits inside a measured range; the classifier reports what its training history associates with that location. Use with your own position sizing and risk management. Not financial advice.
Built natively in Pine Script® v6. Online logistic regression trained by per-bar gradient descent with L2 weight decay, a rolling dwell-time feature, and a higher-timeframe swing-anchored dealing range. No external libraries, no data feeds.
Open source — Mozilla Public License 2.0. Indicator

Indicator

Session Profitability Visualizer
What it shows
Session Profitability Visualizer breaks the trading day into its 24 hours and shows, for each hour, how price has historically behaved on your chart. It answers a simple statistical question: "When this market trades at 09:00 vs. 14:00 vs. 20:00, how have bars in that hour tended to move?"
For every hour with enough data it displays a table with:
- Hour — the hour-of-day bucket (00:00–23:00) in the symbol's exchange timezone
- Cum move — the cumulative close-minus-open of all completed bars in that hour (in points, or in % if you select the percent metric)
- Bars — how many completed bars contributed to that bucket (the sample size)
- % Pos — the share of those bars that closed above their open
Rows are tinted green or red by the sign of the cumulative move, with color intensity scaled by magnitude relative to the strongest hour, so the "heavier" hours stand out at a glance. An optional (off by default) background shading tints the chart by the historical statistics of the hour the current bar belongs to.
How it works
On every completed intraday bar inside the lookback window, the script:
1. Determines the bar's hour of day using the symbol's exchange timezone (syminfo.timezone).
2. Computes the bar's move — either close − open in points, or (close − open) / open × 100 in percent, depending on the Metric input.
3. Adds that move to the hour's running sum, increments the hour's bar count, and increments a positive-bar counter when the move is positive.
The per-hour sums, counts, and positive counts are held in three 24-element arrays. The table is rendered once on the last bar from those arrays. There is no request.security() call, no reference to future data, and only confirmed bars are counted — the statistics do not repaint on historical data (the live, still-forming bar is excluded until it closes).
Inputs
- Lookback (bars) — how many recent bars feed the statistics (default 5000). Larger windows are more stable; smaller windows react faster to regime changes.
- Metric — Points (close − open) or Percent (bar return %). Percent is more comparable across price levels and long histories.
- Min samples per hour — hours with fewer completed bars than this are hidden (default 30), so thin buckets don't masquerade as meaningful.
- Table position — where the table sits on the chart.
- Shade background — optional tint of the current bar's hour by its historical stats (off by default).
How to use it
Apply it to any intraday chart (15m or 1h are good starting points — on a 15m chart each hour bucket gets four bars per session). Look for hours where the cumulative move and the % positive rate agree and the sample count is healthy; those are the hours where the market has shown a persistent directional lean on your symbol. Compare the same symbol on different lookbacks to see whether the pattern is stable or an artifact of one period.
Limitations — please read
- Hour buckets use the symbol's exchange timezone, not your chart's display timezone. A "09:00" row on NASDAQ symbols means 09:00 America/New_York regardless of your local clock.
- Bar close-minus-open is a directional proxy, not trade P&L. It ignores spreads, slippage, position sizing, and intrabar path.
- The statistics are a historical observation, not a prediction. An hour that has drifted up for 5000 bars can stop doing so at any time; sample sizes shrink quickly on higher intraday timeframes.
- The script is intraday-only by design; on daily and above it shows an explanatory message instead of statistics.
This is a statistical visualization tool. It does not generate signals or recommendations of any kind.
Indicator

Median Cascade Trend [BackQuant]Median Cascade Trend
Overview
Median Cascade Trend is a noise-resistant trend-following indicator that combines multiple causal median filters , an Ehlers-style two-pole Super Smoother , and a configurable chop-gating system .
Its purpose is to identify meaningful directional structure while rejecting the types of price movement that frequently cause conventional moving averages to whipsaw:
Single-bar spikes
Short-lived price shocks
Irregular wicks
Low-efficiency sideways movement
Weak slopes that do not represent genuine directional progress
The indicator processes price in three distinct stages:
A median-filter cascade removes impulsive and short-duration noise.
A two-pole low-pass filter smooths the remaining structural signal.
A chop gate decides whether a change in direction is strong enough to update the active trend state.
This creates a trend line that is intentionally more selective than a standard moving average. The line itself can continue evolving, but trend-state changes are only accepted when the underlying movement passes the chosen quality tests.
The result is a system that separates:
The estimated trend line
The raw direction of that line
The confirmed trend regime
That distinction is important. The indicator does not assume that every small turn in a smoothed line represents a valid trend reversal.
Core idea
Most trend filters are built around linear averaging. They combine historical prices using fixed or exponentially decaying weights.
Examples include:
SMA
EMA
WMA
HMA
DEMA
These filters are effective for general smoothing, but they have a weakness: a single extreme observation can influence the output immediately.
If one bar produces a large wick or temporary price shock, a moving average will usually be pulled toward that value because it includes the magnitude of every observation.
A median filter behaves differently.
Instead of averaging the values inside a window, it sorts them and selects the middle observation. This makes it highly resistant to isolated extremes.
Median Cascade Trend uses this property repeatedly before applying traditional low-pass smoothing.
The central idea is:
Remove impulsive noise first.
Smooth the cleaned signal second.
Confirm direction only when the movement is efficient or sufficiently steep.
This ordering is deliberate. Smoothing a noisy series and filtering noise before smoothing are not the same thing.
Where median filtering comes from
Median filters are widely used in digital signal processing, image processing, and engineering.
One of their best-known applications is the removal of impulse noise , sometimes called salt-and-pepper noise in image processing.
Impulse noise consists of isolated extreme observations that are not representative of the surrounding signal.
In market data, comparable events include:
Temporary liquidity gaps
Single-bar stop runs
Erroneous prints
Sharp wick reversals
News spikes that immediately retrace
A linear smoother such as an SMA or EMA cannot distinguish between an important sustained move and an isolated outlier. Both are included according to their numerical magnitude.
A median filter is nonlinear. It selects the central-ranked value rather than calculating an arithmetic mean.
For example, consider five observations:
100
101
102
103
140
The average is:
109.2
The median is:
102
The isolated value at 140 significantly distorts the average but has almost no effect on the median.
This is why median filtering is especially useful when the objective is to preserve structural turns while rejecting isolated noise.
What makes a median filter nonlinear
A normal moving average can be represented as a weighted sum of its inputs.
A median filter cannot.
Its output depends on the ordering of observations, not their arithmetic combination. This makes it a nonlinear filter.
That has several important consequences:
Outliers have limited influence.
Edges and structural shifts can be preserved more cleanly.
The response is not equivalent to ordinary low-pass averaging.
The filter may hold a value until enough observations confirm a change.
In trading terms, the median filter often behaves more like a structural selector than a conventional average.
What “causal” means
The median stages in this indicator are causal.
A causal filter uses:
The current bar
Past bars
It does not use future observations.
This matters because many visually smooth filtering methods can only produce their best result by centering the calculation around the current point, which requires future data.
This script does not do that.
Every value is calculated from information available at that bar, making the filter suitable for live use.
Why use a cascade of median filters
A single median filter can remove isolated spikes, but noise does not always occur as one extreme bar.
It can appear as:
Two-bar shocks
Short bursts of alternating movement
Small clusters of irregular candles
Residual distortion left after the first filtering pass
A cascade applies multiple median stages sequentially:
Stage 1 processes the original source.
Stage 2 processes the output of Stage 1.
Stage 3 processes the output of Stage 2.
Each stage removes a different layer of short-duration instability.
The process is similar to progressively cleaning a signal:
The first stage removes obvious impulse noise.
The second stage removes remaining short-term irregularity.
The third stage produces a more stable structural series before low-pass smoothing.
Median Stage 1
The first median stage is intended to reject isolated one-bar disturbances.
With a short setting such as 3:
The filter remains responsive.
Single-bar spikes are strongly suppressed.
Most genuine multi-bar movement remains visible.
This is the most tactical stage.
Median Stage 2
The second stage receives an already-cleaned input.
Its role is to remove:
Short-duration residual noise
Small alternating movements
Irregularity that survived the first stage
A slightly longer setting such as 5 creates stronger structural consistency.
Median Stage 3
The third stage provides the final nonlinear cleaning pass.
With a longer setting such as 7:
The output becomes more stable.
Short-lived reversals are reduced.
Only more persistent changes are passed into the low-pass stage.
This is the most conservative median stage.
Cascade Stages input
The user can select how many median stages are active:
1 stage: fastest and most responsive
2 stages: balanced noise rejection
3 stages: strongest impulse-noise suppression
The unused stages are still calculated internally, but the selected stage determines which output is sent into the Super Smoother.
Why cascade instead of one very long median
Applying several shorter filters is not always equivalent to applying one very long median filter.
A long median window can:
Delay structural changes heavily
Flatten shorter trend legs
Become insensitive to local turns
A cascade allows the filtering process to be distributed across stages.
This provides greater control over:
How aggressively isolated noise is removed
How much short-duration movement survives
How smooth the final structural input becomes
It also lets users build a progression such as 3, 5, and 7 rather than applying one blunt window.
The low-pass stage
After the median cascade, the signal is passed into a two-pole Super Smoother .
The median cascade removes nonlinear impulse noise, but its output can still contain:
Small step changes
Residual high-frequency movement
Sharp transitions caused by median replacement
The Super Smoother converts that cleaned but potentially stepped series into a smoother trend line.
This creates a hybrid filtering system:
Nonlinear median filtering for outlier rejection
Recursive low-pass filtering for smooth trend extraction
These components solve different problems.
Where the Super Smoother comes from
The Super Smoother is associated with John F. Ehlers’ application of digital signal processing techniques to financial markets.
It is based on the behavior of a two-pole low-pass filter and is designed to suppress high-frequency components more effectively than many conventional moving averages.
Traditional moving averages are simple smoothers, but they are not necessarily optimized as frequency-selective filters.
The Super Smoother uses recursively calculated coefficients derived from:
Exponential decay
Trigonometric terms
A selected cutoff period
The objective is to reduce high-frequency market noise while retaining lower-frequency directional structure.
What a low-pass filter does
A low-pass filter allows slow-moving components of a signal to pass while reducing fast-moving components.
In market terms:
Slow components represent broader trend structure.
Fast components represent short-term noise, rapid oscillation, and microstructure disturbance.
The Low-Pass Length determines the separation.
Lower values:
Allow more short-term movement through.
React faster.
Produce more turns.
Higher values:
Reject more high-frequency movement.
Produce a smoother trend line.
Respond later to structural changes.
Why use a two-pole filter
The number of poles broadly describes the order and steepness of a filter.
A two-pole filter generally provides:
Stronger attenuation of high-frequency noise than a one-pole filter.
A smoother output.
A more defined frequency response.
It also uses prior filter outputs recursively, allowing substantial smoothing without requiring an extremely long direct averaging window.
The full signal-processing chain
The calculation can be understood as:
Raw price source
Median Stage 1
Optional Median Stage 2
Optional Median Stage 3
Two-pole Super Smoother
Direction measurement
Chop-quality validation
Persistent trend state
Each layer has a distinct purpose.
Median cascade
Rejects isolated and short-lived noise.
Super Smoother
Reduces the remaining high-frequency variation.
Direction logic
Determines whether the final line is rising or falling.
Chop gate
Determines whether that directional change is trustworthy enough to update the confirmed trend.
Trend direction calculation
The raw direction is determined by comparing the current trend line with its value several bars ago:
Bullish if trendLine > trendLine
Bearish if trendLine < trendLine
Neutral if equal
The Direction Lookback controls how much movement is required before the line is classified as rising or falling.
A one-bar comparison is extremely responsive but can detect tiny slope changes.
A longer comparison:
Measures movement across a wider interval.
Reduces sensitivity to one-bar flattening.
Produces more stable raw direction.
Raw trend versus confirmed trend
One of the most important design choices is that the script separates:
Raw trend
Confirmed trend
The raw trend reflects the current direction of the filtered line.
The confirmed trend is persistent and changes only when:
The raw trend points in a new direction.
The chop gate is open.
If the line turns but the gate is closed:
The active trend state remains unchanged.
The attempted flip can optionally be displayed as blocked.
This prevents every small line turn from immediately becoming a regime reversal.
Why a chop filter is needed
Even an advanced smoother can turn repeatedly during sideways markets.
Smoothing reduces noise, but it does not determine whether movement is:
Directional
Efficient
Large enough relative to volatility
A line can move upward and downward in a range while making almost no net progress.
The chop gate addresses this by evaluating two separate properties:
Directional efficiency
ATR-normalized slope
Efficiency Ratio
The first gate component measures how efficiently the trend line has moved over a selected window.
The calculation compares:
Net movement
Total movement
Net movement is:
|trendLine - trendLine |
Total movement is:
Sum of |bar-to-bar changes in trendLine|
The Efficiency Ratio is:
Efficiency = Net Movement / Total Movement
The result ranges approximately from 0 to 1.
Efficiency near 1
The line has moved mostly in one direction.
Example:
It advanced 10 units.
Its total path was approximately 11 units.
This indicates a clean directional move.
Efficiency near 0
The line has moved back and forth without achieving much net progress.
Example:
It travelled 20 units in total.
But ended only 1 unit from where it started.
This indicates chop.
Where the Efficiency Ratio comes from
The Efficiency Ratio is commonly associated with Perry Kaufman’s work on adaptive market analysis and the Kaufman Adaptive Moving Average.
Its purpose is to distinguish directional movement from noisy movement.
It does not measure the size of a move alone.
It measures the quality of the path.
This makes it highly suitable as a trend gate.
A market can be volatile but inefficient. It can move aggressively in both directions and still make little progress.
The Efficiency Ratio helps identify that distinction.
Minimum Efficiency
The Minimum Efficiency input determines the directional quality required for the efficiency condition to pass.
Lower values:
Allow more irregular movement.
Open the gate more frequently.
Produce earlier but noisier trend changes.
Higher values:
Require cleaner directional travel.
Block more sideways flips.
Produce fewer but more selective regime changes.
ATR-Normalized Slope
The second gate component measures how large the trend-line movement is relative to current market volatility.
It calculates:
|trendLine - trendLine | / ATR
This converts the line’s movement into ATR units.
Without normalization, a slope of 10 points could be:
Large for one instrument
Negligible for another
Large in a quiet regime
Small during extreme volatility
ATR normalization makes the slope more comparable across assets and regimes.
What normalized slope measures
The Efficiency Ratio asks:
Was the movement directionally clean?
ATR-normalized slope asks:
Was the movement large enough to matter?
These are different questions.
A move can be highly efficient but extremely small.
For example:
A perfectly smooth drift of only 0.02 ATR may not justify a new trend regime.
A move can also be large but inefficient:
A violent range may travel several ATRs while repeatedly reversing.
Using both filters gives a more complete view of trend quality.
Minimum ATR-Normalized Slope
The Minimum ATR-Normalized Slope defines the movement threshold.
Lower values:
Accept weaker slopes.
React sooner.
Allow more low-energy flips.
Higher values:
Require stronger displacement.
Reduce weak trend transitions.
Delay signals until movement becomes more meaningful.
Gate modes
The indicator provides four chop-gate modes.
Efficiency Ratio
Only directional efficiency is required.
Best suited for users who care primarily about whether movement is clean, regardless of its exact magnitude.
ATR-Normalized Slope
Only slope strength is required.
Best suited for users who want movement to exceed a volatility-adjusted threshold, even if the path is not perfectly efficient.
Both
Both conditions must pass:
Efficiency must be high enough.
Slope must be strong enough.
This is the strictest mode and generally provides the strongest chop rejection.
Either
Only one condition must pass.
This is more permissive:
A very clean slow trend may pass through efficiency.
A powerful but less orderly move may pass through slope.
It provides a balance between responsiveness and filtering.
Gate behavior
When the gate is open:
A new raw direction can update the trend state.
Bullish and bearish flips can be confirmed.
When the gate is closed:
The previous confirmed trend persists.
Attempted changes are blocked.
The display can dim, turn neutral, or hide.
This means the indicator behaves like a regime-holding system during chop.
It does not constantly reset to neutral. It retains the last confirmed direction until sufficient evidence supports a new one.
Blocked flips
A blocked flip occurs when:
The filtered line attempts to change direction.
The attempted direction differs from the confirmed trend.
The chop gate is closed.
The raw direction has just changed.
These can optionally be displayed as small X markers.
Blocked flips are useful because they show:
Where a basic slope indicator would have reversed.
Where the chop filter rejected that reversal.
How much signal noise the gate is removing.
They are not trade signals. They are diagnostic information.
Trend persistence
The trend variable is persistent.
Once bullish:
It remains bullish until a valid bearish change passes the gate.
Once bearish:
It remains bearish until a valid bullish change passes the gate.
This persistence is central to the design.
The indicator is not merely coloring every local slope. It is maintaining a confirmed market regime.
Display modes when the gate is closed
The indicator offers three ways to display gated conditions.
Dim
The current trend color remains visible but becomes transparent.
This communicates:
The last confirmed trend is still active.
Current conditions are not strong enough to confirm a new direction.
This is useful when you want regime continuity without overstating conviction.
Neutral
The trend line and candles switch to the selected gate color.
This communicates:
The directional regime is being withheld.
Current conditions are considered non-trending or uncertain.
Hide
The trend line disappears while the gate is closed.
This is the strictest visual mode.
It communicates:
No actionable trend state should be displayed during the gated condition.
Trend line coloring
The base color is determined by the confirmed trend:
Bullish trend uses the long color.
Bearish trend uses the short color.
Uninitialized state uses gray.
The gate display can then modify the final presentation.
This allows the chart to show:
Direction
Confirmation status
Chop-filter activity
without needing a separate panel.
Gradient fill
The indicator fills the area between price and the trend line.
When price is above the trend line:
A bullish gradient is displayed.
When price is below the trend line:
A bearish gradient is displayed.
The fill is stronger near the trend line and fades toward price.
This emphasizes the trend line as the structural reference.
The fill color follows the gate display state:
Full trend color when active
Dimmed during a closed gate in Dim mode
Neutral when configured
Hidden when the trend line is hidden
Trend glow
A soft glow is created around the filtered line using a small ATR-scaled distance.
The glow width is:
ATR(14) × 0.06
Using ATR ensures the glow remains visually proportional across assets and price scales.
The glow does not affect the calculation. It improves readability and reinforces the line as the central structural output.
Candle coloring
Candles can be colored using the confirmed trend state.
When the gate is open:
Bull trend produces bullish candles.
Bear trend produces bearish candles.
When the gate is closed:
Dim mode fades the existing trend color.
Neutral mode uses the gate color.
Hide mode removes the candle override.
This gives an immediate full-chart view of both trend and gate status.
Signal logic
Signals only occur when the confirmed trend changes.
Bullish flip
A bullish signal requires:
The active trend becomes bullish.
The previous trend was bearish.
The gate accepted the change.
Bearish flip
A bearish signal requires:
The active trend becomes bearish.
The previous trend was bullish.
The gate accepted the change.
This is more selective than simply detecting a change in line slope.
How to interpret the indicator
Bullish confirmed regime
A bullish regime means:
The median-filtered and low-pass-smoothed trend line is rising.
The move satisfied the selected chop-filter conditions when the regime changed.
The last accepted direction remains bullish.
Bearish confirmed regime
A bearish regime means:
The final trend line is falling.
The bearish change passed the selected quality gate.
The last accepted direction remains bearish.
Gate closed in an existing trend
This means:
The market is no longer moving with sufficient efficiency or slope.
A new reversal cannot currently be confirmed.
The previous regime remains stored.
This often occurs during:
Consolidation
Pullbacks
Low-volatility drift
Transition phases
Repeated blocked flips
Repeated blocked changes suggest:
The filtered line is oscillating.
Directional quality is weak.
A normal trend-following system would likely be whipsawing.
This is exactly the environment the gate is designed to avoid.
How to use it in practice
1. Directional regime filter
Use the confirmed trend to filter other setups:
Favor long trades during bullish regimes.
Favor short trades during bearish regimes.
Reduce activity when the gate is closed.
2. Trend-following entries
Bullish and bearish flips can be used as directional entry triggers, especially when confirmed by:
Price structure
Breakouts
Volume expansion
Higher-timeframe alignment
3. Pullback framework
During an established trend:
Price returning toward the trend line may represent a pullback.
If the gate remains closed but the trend does not flip, the move may be consolidation rather than reversal.
If the opposite direction eventually passes the gate, the regime has changed more meaningfully.
4. Chop avoidance
The most direct use is avoiding repeated entries during low-quality conditions.
When the display is dim, neutral, or hidden:
Reduce confidence in new trend signals.
Wait for efficiency or slope to recover.
5. Diagnostic comparison
Enable blocked flips to see how often the raw trend attempts to reverse without confirmation.
This helps tune:
Efficiency threshold
Slope threshold
Gate mode
Input guide
Source
Selects the price series used by the median cascade.
Close is the standard choice.
Alternatives such as hl2 or hlc3 may produce a slightly smoother structural input.
Cascade Stages
Controls how many median filters are used.
1: responsive
2: balanced
3: strongest noise rejection
Median Stage Lengths
Control the window used at each stage.
Shorter values:
Preserve responsiveness.
Remove only very short-duration noise.
Longer values:
Produce stronger structural filtering.
Delay shorter turns.
Low-Pass Length
Controls the two-pole Super Smoother.
Lower:
Faster
More reactive
Higher:
Smoother
More conservative
Direction Lookback
Controls how far back the current line is compared when determining raw direction.
Lower:
Faster slope changes
Higher:
More stable directional measurement
Efficiency Length
Controls the window used to measure net movement versus total path movement.
Shorter:
More responsive efficiency reading
More sensitive to recent chop
Longer:
More stable directional-quality assessment
Minimum Efficiency
Controls how clean the directional path must be.
Higher values make the gate stricter.
Slope Length
Controls the interval across which trend-line movement is measured.
Slope ATR Length
Controls the ATR baseline used to normalize slope.
Minimum ATR-Normalized Slope
Controls the minimum volatility-adjusted displacement required.
Higher values require stronger movement.
Tuning examples
Faster trend configuration
1 or 2 median stages
Short median windows
Lower Super Smoother length
Direction Lookback of 1 or 2
Either gate mode
Lower efficiency and slope thresholds
Balanced configuration
2 or 3 median stages
Progressive windows such as 3, 5, 7
Moderate Super Smoother length
Both gate mode
Moderate thresholds
Conservative configuration
3 stages
Longer median windows
Higher Super Smoother length
Longer Direction Lookback
Both gate mode
Higher minimum efficiency and slope
How this differs from a normal moving average
A standard moving average:
Uses linear averaging.
Responds directly to outlier magnitude.
Changes direction whenever its slope changes.
Median Cascade Trend:
Uses nonlinear outlier-resistant preprocessing.
Applies a proper recursive low-pass stage.
Separates raw direction from confirmed regime.
Blocks changes during inefficient or weak movement.
How this differs from a normal median filter
A basic median filter only removes impulse noise.
This indicator extends the idea by adding:
Multiple median stages
Low-pass smoothing
Direction measurement
Efficiency gating
Volatility-normalized slope gating
Persistent trend states
Signals and alerts
It is not simply a median-smoothed line. It is a complete trend-regime system built on median preprocessing.
How this differs from a Supertrend
A Supertrend uses ATR bands around price and changes state when price crosses the trailing boundary.
Median Cascade Trend does not use a volatility band to define direction.
Instead:
Direction comes from the slope of the filtered trend line.
ATR is used only to normalize slope and scale visuals.
Trend changes are controlled by movement quality rather than price crossing a stop band.
Strengths
Strong rejection of isolated price spikes
Preserves broader structural movement
Combines nonlinear and linear filtering
Separates raw turns from confirmed trend changes
Configurable chop rejection
Volatility-normalized slope testing
Persistent directional regimes
Blocked-flip diagnostics
Fully causal calculation
Limitations
Strong filtering can delay genuine reversals.
Long median windows may suppress shorter trend legs.
Strict gate settings can hold the previous regime too long.
Loose gate settings reduce the benefit of chop filtering.
Median filters can produce stepped transitions before low-pass smoothing.
The indicator remains reactive rather than predictive.
Best use cases
Median Cascade Trend is particularly suited for:
Trend filtering in noisy markets
Reducing false reversals caused by wicks
Swing-trading regime identification
Filtering entries from faster systems
Dynamic trend-structure visualization
Avoiding sideways-market whipsaws
It can be applied across:
Equities
Indices
Futures
Forex
Cryptocurrency
Commodities
Alerts
The indicator provides alerts for:
Confirmed bullish trend changes
Confirmed bearish trend changes
Trend changes blocked by the chop filter
The blocked-flip alert is especially useful for monitoring when the line attempts to reverse but market quality remains insufficient.
Summary
Median Cascade Trend is a multi-stage trend extraction system designed to reject impulsive market noise before determining direction. It first applies up to three causal median filters, progressively removing isolated spikes and short-duration disturbances. The cleaned series is then passed through a two-pole Super Smoother to extract a stable low-frequency trend line.
Rather than accepting every change in slope, the indicator evaluates the quality of the movement using directional efficiency and ATR-normalized slope. Depending on the selected gate mode, trend changes can require clean directional travel, sufficient volatility-adjusted displacement, or both.
This produces a persistent trend state that changes only when the filtered line turns and the surrounding movement is strong enough to justify the reversal. The final result is a robust trend-following framework that combines outlier rejection, low-pass smoothing, directional-quality measurement, and chop suppression into a single overlay.
Indicator

Indicator

Trailing Drawdown Line Futures PropFirmsSee the exact price where your trailing drawdown gets hit — before it happens.
Built for futures prop-firm traders (Apex, Topstep, MyFundedFutures, Tradeify, BluSky and similar). Enter your firm's trailing DD size, your buffer at entry and your contract count, then click your entry point on the chart. The indicator draws your liquidation line — the price where the account would breach the trailing max drawdown — and ratchets it the way the firm actually does: it trails the implied equity peak at the FULL drawdown distance, and if you enter below your prior peak the line starts closer but does not move until price beats that peak.
Features
• Works on any futures symbol automatically — the contract's point value is read from the symbol (ES, NQ, MNQ, MES, GC, CL, ZB, …). Non-USD contracts (e.g. FDAX) display in their quote currency.
• Three trailing models: Intraday (trails every new high/low — real-time-trailing firms), Bar close, and End of day (EOD-trailing firms; needs an intraday or 1D chart).
• Live buffer readout — dollars and points left before the line — in a dark info table and an on-chart label.
• Breach is latched: once the line is touched the status stays BREACHED, because a trailing max-DD hit is terminal, not a temporary state. On historical bars the intraday model errs toward flagging (the path inside a bar is unknowable) — confirm on a lower timeframe.
• Lock support: enter the price where your firm freezes the DD (breakeven lock), or let the script derive it from your start balance + equity at entry. Status flips to LOCKED.
• Exit time: set it when you close the trade — the line and buffer freeze, because real DD levels stop moving while you're flat.
• Two alert conditions: buffer below warning level, and line touched.
How to use: add to chart → click your entry point → set contracts, firm DD size and buffer at entry (from your firm dashboard) → pick the trailing model that matches your firm → optionally create the two alerts. Re-anchor for every new trade.
Honest limitations: models ONE fixed-size position on THIS symbol. Scaling in/out or holding other instruments changes your real equity path and is not modeled. Anchor on a low timeframe (1–5 min) for precision. Educational risk-visualization tool — always confirm your firm's exact drawdown rule on their own site. Indicator

Percentile Context [RC Tools]RC Tools — Percentile Context
─────────────────────────────────────────────────────────────
█ OVERVIEW
Not "is RSI over 70" — "where does today's reading actually sit in its own history?" This tool takes a metric of your choice (realised volatility, RSI, volume, rate of change, or any custom source you plug in) and ranks it as a percentile against its own trailing distribution. It's the statistical primitive underneath most technical analysis, made explicit instead of buried in a fixed threshold.
█ WHAT IT DOES
Plots a 0–100 percentile-rank line for the selected metric, flags "extreme" zones (default: below the 10th percentile or above the 90th), and shows a stats table with the current value, current percentile, all-time min/max seen on the chart, and how many bars it's been since the metric last hit either extreme.
█ THE THEORY BEHIND IT
Fixed thresholds ("RSI > 70 = overbought") assume a metric's meaningful range never changes. It does — across assets, and across time on the same asset. A percentile rank fixes this by asking a relative question instead of an absolute one: given everything this metric has done over its own trailing window, how unusual is today's reading? This is the same idea underneath the Regime Classifier's volatility-state measure, generalised to any metric.
█ HOW IT IS CALCULATED
The selected metric is computed per bar:
• Realised Volatility: stdev(log(close/close ), N)
• RSI: standard Wilder RSI
• Volume: raw bar volume
• Rate of Change %: (close − close ) / close × 100
• Custom Source: whatever series you plug into the source input (e.g. another indicator's plot)
The metric is then percentile-ranked against its own trailing window (default 750 bars ≈ 3 years on daily): what percentage of the last N readings were below today's value. Display values update ONLY on confirmed bar close — nothing here repaints.
█ SETTINGS & CONFIGURATION
• Metric (default Realised Volatility) — what gets ranked
• Custom Source — only used when Metric = Custom Source
• Realised Volatility / RSI / Rate of Change lookbacks (defaults 20 / 14 / 20)
• Percentile Ranking Window (default 750 bars) — longer = more stable, needs more history
• Low / High Extreme Thresholds (default 10 / 90)
• Paint Main Chart Background — off by default to avoid clashing with the Regime Classifier's background if you run both at once
█ HOW TO USE IT
Use it to calibrate how seriously to take a "normal" indicator reading. Example: RSI at 75 means something different on a stock that's rarely above 60 than on one that regularly touches 85 — the percentile rank makes that comparison explicit for the SAME asset over time. Also useful for volatility context ahead of position sizing: current realised vol at the 95th percentile is a different risk environment than the same absolute vol reading at the 40th percentile.
Works on any asset and timeframe with sufficient history for the percentile window.
█ LIMITATIONS
• Percentile rank describes the past relative to itself — it says nothing about direction or what happens next. A metric at its 99th percentile can stay there.
• Needs substantial history for a stable ranking. On short-history assets, treat the percentile as unreliable.
• "Extreme" is relative to the metric's OWN range. A percentile extreme on a low-volatility asset is not directly comparable in absolute terms to one on a high-volatility asset — that's the point of the tool, but it means percentiles aren't comparable across symbols.
• All-time min/max and "bars since" stats are only as long as the chart's available history, not a fixed universal record.
• This script does NOT repaint. Display values update on confirmed bar close only.
█ DISCLAIMER
For educational and informational purposes only. Nothing here is financial advice. Past behaviour of any metric does not indicate future results. Trade at your own risk.
Indicator

Geometry Academy# geometry academy — projection, levels and market timing
geometry academy is an educational indicator dedicated to market geometry, price levels, projections and timing.
it combines several classical methods inside a single interface:
* fibonacci retracements and extensions
* golden pocket
* ab=cd projection
* double top and double bottom
* ichimoku system
* andrews pitchfork
* session vwap
* anchored vwap
* approximate volume profile
* poc, vah and val
* linear regression channel
* cycle interval estimation
* relative strength against a benchmark
* confluence scanner
* educational lessons
* reference curriculum
* built-in glossary
the objective is not to generate automatic entries or promise a result. the indicator is designed to explain where important zones are located, why they exist and how several independent methods can converge around the same area.
a single line represents one piece of information. several independent levels grouped in the same area form a confluence zone worth studying.
---
## general operation
geometry academy uses confirmed pivots to build its geometry.
a pivot high or pivot low becomes available only after the number of bars defined in the “swing · right bars” setting has closed.
this means a swing is never known exactly when it forms. it is confirmed several bars later and then displayed on its original bar.
this behavior prevents an unfinished high or low from being treated as a definitive pivot.
rolling tools such as vwap, volume profile, regression and relative strength naturally continue to update as new bars are added.
---
# indicator modules
## fibonacci retracement
the fibonacci module measures the retracement depth of the latest confirmed leg.
the available levels are:
* 0.0
* 0.236
* 0.382
* 0.5
* 0.618
* 0.786
* 1.0
on a bullish leg, the levels help study pullback zones below the latest high.
on a bearish leg, they help study rebound zones above the latest low.
the levels are not buy or sell signals. they only identify areas where a reaction may become relevant.
## golden pocket
the golden pocket is the zone between the 0.618 and 0.65 retracement levels.
it is displayed as a zone rather than a precise line because market reactions do not always occur at one exact price.
a trade should not be decided only because price touches this area. price reaction, structure and other nearby levels must also be studied.
## fibonacci extensions
the 1.272, 1.618 and 2.0 extensions project targets beyond the reference leg.
they are mainly intended for studying potential objectives after the original movement resumes.
an extension is generally more useful when it aligns with:
* a previous high or low
* a vah or val
* a poc
* a pitchfork median
* an ab=cd projection
* a regression band
## ab=cd projection
the ab=cd model studies symmetry between two price legs.
the distance from a to b is projected from point c to estimate a potential point d.
point d is a mathematical completion zone. it does not guarantee a reversal.
a projection becomes more relevant when:
* bc is a coherent retracement of ab
* cd moves in the same direction as ab
* point d aligns with another important zone
* the duration of cd remains close to the duration of ab
* price shows a confirmed reaction around d
## double top and double bottom
the module looks for structures such as:
* high, low, high for a double top
* low, high, low for a double bottom
the tolerance between the two highs or two lows is calculated with atr.
the second high or low only creates the initial structure.
a double top is confirmed when price closes below the neckline.
a double bottom is confirmed when price closes above the neckline.
before the neckline breaks, the pattern remains a possibility rather than a confirmed setup.
## ichimoku kinko hyo
the ichimoku system is displayed with:
* tenkan-sen
* kijun-sen
* senkou span a
* senkou span b
* kumo
* chikou span
simplified interpretation:
* price above the kumo: bullish regime
* price below the kumo: bearish regime
* price inside the kumo: neutral or uncertain regime
* tenkan above kijun: positive short-term momentum
* tenkan below kijun: negative short-term momentum
the cloud is intentionally projected forward. chikou is intentionally shifted backward. these displacements are part of the standard ichimoku construction.
a tenkan and kijun cross must always be interpreted within context. a bullish cross below a bearish cloud does not carry the same meaning as a bullish cross above a bullish cloud.
## andrews pitchfork
the pitchfork is built from three alternating confirmed pivots.
the median line begins at the first pivot and passes through the midpoint of the next two pivots.
the two outer lines are parallel to the median.
the pitchfork helps study:
* the geometric direction of the swing
* returns toward the median
* acceleration toward an outer line
* structural weakness after a breakout
* areas where the median aligns with another level
the pitchfork depends directly on the quality of the three selected pivots. when a new significant swing is confirmed, the geometry may be recalculated.
## session vwap
vwap represents the session’s volume-weighted average price.
simplified interpretation:
* price above a rising vwap: intraday advantage for buyers
* price below a falling vwap: intraday advantage for sellers
* return toward vwap: return toward the session’s weighted average
* loss and reclaim of vwap: potential intraday control change
vwap is especially useful on markets with meaningful volume data.
## anchored vwap
anchored vwap begins its calculation from the selected date.
it can be used to study the volume-weighted average price since a specific event:
* origin of a movement
* breakout
* important high or low
* monthly open
* asset launch
* fundamental event
* regime change
anchored vwap does not reveal the exact price paid by every market participant. it represents a weighted average from the selected anchor.
the quality of the level therefore depends directly on the relevance of the selected date.
## volume profile
the volume profile distributes the lookback volume across several price zones.
it provides:
* poc
* vah
* val
* an optional horizontal histogram
the poc represents the profile row that received the largest allocated volume.
the vah is the upper boundary of the value area.
the val is the lower boundary of the value area.
simplified interpretation:
* price near poc: potential high-acceptance zone
* price between vah and val: price located inside the value area
* price above vah: price above the studied value zone
* price below val: price below the studied value zone
this profile is an approximation calculated from the ohlcv data available on the chart. it does not replace a native profile built from more detailed intrabar data.
## linear regression channel
the center line represents the best-fit linear trend over the selected period.
the bands are calculated using the dispersion of residuals around that line.
the module helps study:
* the statistical direction of price
* the distance between price and its central trend
* periods of extension
* returns toward the mean
* slope changes
a band touch is not automatically a reversal signal.
in a strong trend, price may remain close to an outer band for several bars.
## cycle projection
the cycle module measures the intervals between several confirmed swing lows.
it uses their average spacing to project a potential future time window.
this projection represents an area of attention rather than a guaranteed reversal date.
cycles may contract, expand or disappear during a regime change.
price level must always be studied separately from timing.
## relative strength
relative strength compares the chart symbol with a benchmark.
it is calculated using the ratio:
asset divided by benchmark
simplified interpretation:
* rising ratio: the asset is outperforming the benchmark
* falling ratio: the asset is underperforming the benchmark
* bullish turn in the ratio: improving relative performance
* bearish turn in the ratio: weakening relative performance
this relative strength measure is not the rsi oscillator.
for an altcoin, btc may be used as the benchmark. for a stock, a sector index or broad market index may be more appropriate.
---
# explanation of every input
## anchors
### swing · left bars
defines the number of bars located to the left of the pivot.
a higher value selects more significant swings and reduces the number of detected pivots.
a lower value detects more minor movements.
### swing · right bars
defines the number of bars required after the pivot before it becomes confirmed.
a higher value produces more stable geometry but increases confirmation delay.
a lower value reacts faster but includes more market noise.
---
## fibonacci
### auto-fibonacci on the active leg
enables or disables the automatic fibonacci drawn on the latest confirmed leg.
### extension targets
enables the 1.272, 1.618 and 2.0 projections.
### highlight the golden pocket
displays the area between 0.618 and 0.65.
### 0.0
displays the reference end of the movement.
### 0.236
displays a shallow retracement, mainly useful in strong trends.
### 0.382
displays a moderate retracement.
### 0.5
displays the midpoint of the movement. this is not a pure fibonacci ratio, but it is widely used.
### 0.618
displays the retracement related to the inverse golden ratio.
### 0.786
displays a deep retracement near the full invalidation of the leg.
---
## ab=cd symmetry
### project the ab=cd completion
enables or disables the point d projection based on the latest compatible pivots.
---
## chart patterns
### detect double top / double bottom
enables the search for double top and double bottom structures.
### twin-peak tolerance
defines the maximum allowed distance between the two highs or two lows.
the tolerance is expressed as an atr multiple.
example:
* 0.3 atr: strict detection
* 0.6 atr: balanced setting
* 1.0 atr: more permissive detection
---
## ichimoku kinko hyo
### ichimoku cloud
enables the ichimoku system.
### tenkan-sen
defines the period of the fast conversion line.
the classical setting is 9.
### kijun-sen
defines the period of the base line.
the classical setting is 26.
### senkou span b
defines the period used for the second cloud boundary.
the classical setting is 52.
### cloud displacement
defines how far the cloud is projected into the future.
the classical setting is 26.
### chikou span
enables the current close displayed backward according to the ichimoku displacement.
---
## andrews pitchfork
### andrews pitchfork from last 3 anchors
enables the pitchfork built from the latest three confirmed alternating pivots.
---
## vwap
### session / rolling vwap
enables the standard session vwap.
### anchored vwap
enables the vwap calculated from a specific date.
### anchor date
defines the starting point of the anchored vwap.
it is better to choose a date linked to an event that had real importance on the chart.
---
## volume profile
### volume profile
enables the profile, poc, vah and val.
### profile lookback
defines the number of bars included in the calculation.
a short lookback follows recent structure.
a long lookback describes a broader market area but reacts more slowly.
### number of price bins
defines the vertical resolution of the profile.
fewer bins:
* simpler profile
* wider levels
* lighter calculation
more bins:
* more detailed profile
* more precise levels
* greater sensitivity to noise
### value area %
defines the percentage of allocated volume included around the poc.
the classical setting is 70%.
### draw the profile histogram
shows or hides the horizontal profile bars while keeping the main levels.
---
## regression channel
### linear regression channel
enables the regression channel.
### regression length
defines the number of bars used to calculate the linear trend.
a small value follows price quickly.
a large value represents a slower and more structural trend.
### channel width
multiplies the dispersion of residuals around the center line.
a low value produces a narrow channel.
a high value produces a wider channel.
---
## market cycles
### project the next cycle low
enables the projection of the next time window based on the average spacing between confirmed swing lows.
---
## relative strength
### benchmark symbol
selects the asset used as the reference.
examples:
* btc to compare an altcoin
* a broad market index to compare a stock
* a sector index to compare a company with its industry
* another currency pair to study relative rotation
### rs lookback
defines the period used to measure the change in the asset-to-benchmark ratio.
a low value reacts quickly.
a high value measures a more persistent relative trend.
---
## education ui
### panel · geometry dashboard
displays the main dashboard.
it summarizes:
* ichimoku regime
* tenkan and kijun relationship
* nearest fibonacci level
* poc
* vah and val
* price position inside the value area
* pitchfork median
* anchored vwap
* regression position
* ab=cd target
* relative strength
### dashboard position
defines the position of the main dashboard.
### panel · level-confluence scanner
enables the scanner that compares current price with the calculated levels.
### confluence position
defines the position of the confluence scanner.
### confluence cluster tolerance
defines the maximum distance between current price and a level for that level to be considered nearby.
the distance is expressed in atr.
example:
* 0.25 atr: very tight confluence
* 0.5 atr: precise confluence
* 0.75 atr: balanced setting
* 1.0 atr or more: wide zone
a tolerance that is too large may classify too many levels as nearby.
### panel · deep lesson
enables the panel containing a detailed educational lesson.
### lesson topic
allows the selection of one of twelve subjects:
1. fibonacci retracement
2. fibonacci extension
3. ab=cd and harmonic patterns
4. chart patterns
5. elliott wave
6. ichimoku
7. andrews pitchfork
8. vwap and anchored vwap
9. volume profile
10. regression channels
11. market cycles
12. relative strength
### panel · source curriculum
displays the main historical and methodological references associated with the modules.
### panel · glossary
displays quick definitions of the terms used in the indicator.
---
## style
### bull / support
defines the color used for bullish information and support areas.
### bear / resistance
defines the color used for bearish information and resistance areas.
### accent / value
defines the color used for value levels, poc, medians and important elements.
### geometry accent
defines the main color of the geometry tools and panel titles.
### secondary text
defines the color of secondary text and neutral information.
### panel background
defines the background color of the panels and selected labels.
---
# mini tutorial
## step 1 — begin with the default settings
keep the following values for a first use:
* swing left: 8
* swing right: 8
* fibonacci enabled
* ichimoku enabled
* pitchfork enabled
* vwap enabled
* volume profile enabled
* regression length: 120
* confluence tolerance: 0.75 atr
these settings provide a balanced view of structure, levels and context.
## step 2 — identify the regime
begin by observing the kumo:
* above the cloud: mainly bullish context
* below the cloud: mainly bearish context
* inside the cloud: uncertain context
then check tenkan and kijun.
a bullish projection should not be interpreted the same way in a bearish regime.
## step 3 — locate price
observe:
* the active fibonacci retracement
* the golden pocket
* vah and val
* poc
* vwap
* anchored vwap
* pitchfork median
* regression bands
the objective is to determine whether price is:
* inside a value zone
* inside an extension zone
* near a potential reaction level
* in the middle of an area with no clear advantage
## step 4 — check confluence
open the confluence scanner.
several tools located near the same price may identify an area worth monitoring.
example:
* 0.618 fibonacci
* val
* anchored vwap
* lower regression band
this combination does not guarantee a bounce, but it describes a technically more important zone than a single isolated level.
## step 5 — wait for the reaction
then observe actual price behavior:
* wick rejection
* close above or below the level
* vwap reclaim
* neckline break
* structure change
* volatility expansion
* improvement or deterioration in relative strength
geometry provides the area. price provides the confirmation.
---
# use cases
## example 1 — pullback in a bullish trend
context:
* price above the kumo
* tenkan above kijun
* latest confirmed movement is bullish
* price is retracing
procedure:
1. identify the 0.382, 0.5, 0.618 and 0.786 levels
2. check whether the golden pocket aligns with val or anchored vwap
3. check the pitchfork median
4. consult the confluence scanner
5. wait for a bullish close or reaction around the zone
an entry in the middle of the movement generally provides less structure than an entry studied around a pullback into confluence.
## example 2 — range market
context:
* price inside the kumo
* nearly flat regression
* price between vah and val
* frequent returns toward poc
procedure:
1. treat poc as the center of rotation
2. observe vah as the upper value boundary
3. observe val as the lower value boundary
4. avoid interpreting every internal move as a new trend
5. wait for a close and acceptance outside the value area before considering a breakout
in this context, fibonacci extensions are often less useful than volume profile and regression.
## example 3 — double top
context:
* first confirmed high
* pullback toward a pivot low
* second high close to the first one
procedure:
1. confirm that both highs respect the atr tolerance
2. identify the neckline at the intermediate pivot low
3. do not treat the pattern as confirmed at the second high
4. wait for a close below the neckline
5. use the height of the structure as a theoretical projection
6. check whether the target aligns with val, an extension or previous support
## example 4 — studying an altcoin against btc
context:
* chart symbol: an altcoin
* benchmark: binance:btcusdt
procedure:
1. study the normal trend of the asset
2. study its relative strength against btc
3. favor assets that are also gaining against the benchmark
4. remain cautious when the asset rises in usd but underperforms btc
5. combine relative strength with structure, volume profile and ichimoku
## example 5 — projection target
context:
* valid ab=cd structure
* point d close to a 1.618 extension
* vah or a previous high in the same area
* upper regression band nearby
procedure:
1. treat the area as a potential objective
2. do not automatically assume a reversal
3. observe price reaction on arrival
4. distinguish a simple pause from a real structure break
5. use confluence to organize the analysis
---
# available alerts
## price entered bullish regime
triggers when price closes above the ichimoku cloud.
## price entered bearish regime
triggers when price closes below the ichimoku cloud.
## tenkan/kijun bullish cross
triggers when tenkan crosses above kijun.
## tenkan/kijun bearish cross
triggers when tenkan crosses below kijun.
## avwap reclaimed
triggers when price reclaims anchored vwap.
## avwap lost
triggers when price loses anchored vwap.
## relative strength turned up
triggers when relative strength begins rising again.
## relative strength turned down
triggers when relative strength begins falling again.
to reduce intrabar alerts, use a bar-close frequency in the pulsewire alert settings.
---
# multi-timeframe use
a simple method is to separate context from execution.
swing example:
* daily chart: ichimoku regime, volume profile and relative strength
* 4-hour chart: fibonacci, pitchfork and regression
* 1-hour chart: price reaction and confirmation
intraday example:
* 1-hour chart: general structure
* 15-minute chart: value area, vwap and fibonacci levels
* 5-minute chart: reaction around the zone
pivot settings should be adapted to the timeframe.
on a low timeframe, slightly increasing the pivot values may reduce noise.
on a high timeframe, pivot settings that are too large may produce very few new structures.
---
# data behavior
pivots are confirmed only after several bars.
a pivot may therefore appear on an earlier bar only after its confirmation.
fibonacci levels, pitchfork and ab=cd projection change when a new confirmed pivot updates the active geometry.
volume profile, vwap, regression, cycles and relative strength are rolling calculations. their values change as each new bar is added.
no projection tool should be interpreted as certainty about the future.
---
# good practices
* begin with only a few visible modules
* add tools gradually
* do not use one line as a complete signal
* identify the regime before looking for an entry
* separate projection from confirmation
* adapt pivot settings to the timeframe
* choose a meaningful anchored vwap date
* choose a coherent benchmark
* keep a reasonable confluence tolerance
* study price reaction before making a decision
* use the lessons and glossary to understand each tool
geometry academy is designed as an educational and analytical environment. it helps connect structure, value, geometry, timing and relative strength inside an organized market-reading process.
Indicator

AI K-Means Clustering [TradingFinder] Machine Learning Zones🔵 Introduction
K-Means clustering is an unsupervised machine learning algorithm that groups similar data points around repeatedly updated cluster centers. Each observation is assigned to its nearest center, the centers are recalculated, and the process continues until the clusters converge. In financial market analysis, this structure can separate recurring patterns in price movement, trend direction, volume pressure, and volatility without depending entirely on fixed thresholds. As a result, the same candle may be interpreted differently in a quiet market, a directional trend, or a volatility shock, because its meaning is evaluated in relation to the surrounding market data.
This PulseWire indicator applies K-Means machine learning through several connected analysis modules. The Market State engine studies trend bias, price slope, and relative volume pressure to classify the current market regime as an active bullish trend, active bearish trend, soft bullish trend, soft bearish trend, neutral range, or low-volume range. It also compares the current cluster with the dominant cluster across recent candles, helping the trend classification remain more stable when a single large candle, temporary spike, or short-lived price reversal appears.
The Price Zones engine clusters pivot points, historical highs, and historical lows to create dynamic K-Means support and resistance zones. Traders can display all price cluster centers, the nearest K-Means zone, or separate support and resistance lines. Raw, Smooth, and Locked Steps modes control how quickly the zones respond to new price data, while the nearest line changes color according to the detected bullish, bearish, or ranging market state. A Stochastic moving average heatmap is also plotted between the outer zones, adding a visual layer for momentum, overbought and oversold conditions, trend strength, and changing market pressure.
The indicator also combines volatility analysis, price action recognition, cluster quality scoring, and alert conditions. The volatility engine uses normalized ATR, candle range, and return volatility to identify low-volatility compression, normal volatility, high volatility, and volatility shock. The Price Action module evaluates the latest closed candle for bullish and bearish zone breakouts, rejection patterns, momentum candles, and indecision near a clustered price level. A dedicated Quality and Reliability section then measures zone strength, cluster fit, zone width, price distance, and RMSE, helping traders understand whether the current machine learning calculations are strong enough for practical analysis or should be treated only as additional market context.
🔵 How to Use
The easiest way to read this indicator is not to search for one isolated green or red message. Its main value comes from combining several layers of market information: K-Means market state classification, adaptive price zones, price action, volatility conditions, and calculation quality. Each module answers a different question, and the strongest setups usually appear when several modules point in the same direction.
Start with the Market State row in the analysis table. This module applies multidimensional K-Means clustering to trend bias, trend slope, and relative volume pressure. The current cluster shows where the latest market data has been assigned, while the dominant cluster represents the most frequent cluster across the selected state window. The Strength value shows how dominant that cluster is within the recent sample.
The Market State analysis can return the following conditions :
Active Bullish Trend : Positive trend structure supported by stronger relative volume.
Soft Bullish Trend : Positive directional structure, but with weaker participation or less convincing momentum.
Active Bearish Trend : Negative trend structure supported by stronger relative volume.
Soft Bearish Trend : Bearish directional structure that still requires confirmation.
Neutral Range : Trend bias and slope are not strong enough to define a clear direction.
Low-Volume Range : Sideways structure accompanied by relatively weak volume participation.
The distinction between the current and dominant cluster is important. A single large candle can move the current data point into another cluster, but the dominant state may remain unchanged if the broader recent structure still belongs to the previous market regime. This can help prevent every temporary spike, pullback, or abnormal candle from being interpreted as a complete trend reversal.
The next section is Price Zones. Here, K-Means clustering is applied to historical pivot levels, sampled highs, and sampled lows. Instead of drawing a level from only one swing point, the algorithm groups similar historical prices and calculates a center for each price cluster. These cluster centers become adaptive K-Means price zones that may act as support, resistance, breakout references, or reaction areas.
The table displays :
Near : The cluster currently closest to price.
Strength : The percentage of sampled price levels assigned to the nearest cluster.
Nearest : The closest stabilized K-Means zone.
Support : The nearest valid cluster center below the market.
Resistance : The nearest valid cluster center above the market.
A higher Zone Strength means a larger share of the sampled levels belongs to that cluster. However, this should not be interpreted as a guaranteed support or resistance level. It simply shows that more historical observations were grouped around the same price area.
On the chart, users can choose between three visual approaches. Show All K-Means Zone Centers plots the complete set of clustered price levels. Show Nearest Zone displays only the closest stabilized level, while Show K-Means Support/Resistance plots the nearest support and resistance separately.
The nearest line changes color with the detected market state :
Green indicates a bullish market state.
Red indicates a bearish market state.
Blue indicates a neutral or ranging market state.
The zone lines can also be displayed in Raw, Smooth, or Locked Steps mode. Raw mode follows newly calculated cluster centers directly. Smooth mode gradually moves the plotted level toward the new center, creating a more stable visual structure. Locked Steps mode keeps the previous level in place until the new cluster center has moved by a meaningful ATR-based distance.
Between the outer K-Means zones, the indicator draws a Stochastic Moving Average Heatmap. This heatmap is based on a 100-period Stochastic value smoothed with a 50-period exponential moving average. Lower smoothed Stochastic values appear toward the blue and purple side of the color range, middle values move through cyan and green, and higher values progress toward yellow, orange, and red. The heatmap should be read as a visual momentum layer rather than as a standalone buy or sell signal.
The Price Action row studies candle structure in relation to the nearest K-Means zone and recent price behavior. It uses the candle body, upper wick, lower wick, previous high, previous low, and the location of the nearest zone to identify several possible conditions:
Bullish or bearish zone breakout.
Bullish or bearish rejection from a zone.
Bullish or bearish momentum candle.
Indecision at a K-Means zone.
General indecision.
No clear price action.
The Body, Upper Wick Ratio, and Lower Wick Ratio values represent the relative size of the candle body, upper wick, and lower wick compared with the candle’s total range. These values help explain why the indicator classified a candle as momentum, rejection, or indecision. Price Action should always be read together with Market State and Volatility. For example, a bullish momentum candle inside a bearish market state does not automatically create a bullish setup.
The Volatility module runs a separate K-Means model using normalized ATR, candle range percentage, and return volatility. The clustered volatility data is then used to identify four practical market conditions:
Low Volatility Compression : Market movement has contracted and a future expansion may develop;
Normal Volatility : Current movement is close to its recent reference level;
High Volatility : Price movement is elevated and may require smaller position size or wider risk parameters;
Volatility Shock : Abnormal expansion is present, making immediate entries more sensitive to slippage, unstable movement, and rapid reversals.
Volatility acts as a risk filter for the rest of the analysis. Even when Market State and Price Action point in the same direction, a High Volatility or Volatility Shock reading should reduce the confidence placed on an immediate entry.
Finally, review the Quality row. This section provides an internal assessment of how compact, representative, and consistent the current K-Means calculations are. It does not measure future profitability or win rate. Instead, it evaluates the statistical structure of the active price clusters.
The main values include :
Price Q : A combined score based on zone strength, width, fit, and price distance;
Trust : A weighted score combining price-zone quality, market-state dominance, and volatility-cluster dominance;
Fit RMSE : The normalized root mean squared error of the price clusters;
Width : The average dispersion of the nearest cluster around its center;
Reliability : A descriptive grade derived from the internal Trust score.
A narrow cluster with reasonable strength and lower fitting error will usually receive a better score than a wide, weak, or poorly fitted cluster. Use this section to decide how much weight should be given to the current analysis. A weak Quality score does not make the chart unusable, but it suggests that the levels and classifications should be treated as secondary context.
🟣 Bullish Market Reading
A bullish setup becomes more meaningful when the market state, K-Means zones, candle behavior, volatility, and quality readings support the same interpretation.
Check the Market State first : An Active Bullish Trend indicates stronger bullish structure and relative participation. A Soft Bullish Trend still favors the upside, but entries should normally wait for additional confirmation.
Locate price relative to the nearest zone : When price is above the nearest K-Means zone, that level may become an adaptive support reference. A pullback toward the green nearest-zone line can be watched for continuation or rejection behavior.
Look for bullish price action : A Bullish Rejection From Zone suggests that price tested a clustered level and closed with a stronger lower-wick reaction. A Bullish Zone Breakout shows that the candle crossed above the zone with a sufficiently large body. A Bullish Momentum Candle confirms upward pressure, but it is more useful when the Market State is already bullish.
Use the support line as a reference, not an automatic entry : The K-Means support level can help define the area where bullish structure remains valid. A decisive move below it may weaken the long scenario, especially if the Market State also changes.
Confirm volatility conditions : Normal Volatility is generally easier to manage than High Volatility or Volatility Shock. During compression, traders may wait for a confirmed breakout rather than entering before expansion begins.
Review Quality and Reliability : Stronger Quality, Trust, and Zone Strength readings increase the internal consistency of the analysis. Weak scores suggest that the zone may be broad, poorly fitted, or based on a less concentrated cluster.
A practical bullish sequence may therefore look like this: the table shows a Soft or Active Bullish Trend, price remains above or retests a green K-Means zone, a bullish rejection or breakout appears, volatility is not classified as a shock, and Quality remains acceptable. None of these elements guarantees continuation, but their alignment creates a clearer bullish context than any single reading alone.
🟣 Bearish Market Reading
Bearish analysis follows the same process in reverse. The objective is to identify whether downward market structure, clustered resistance, candle behavior, and volatility are supporting the same scenario.
Begin with the Market State : An Active Bearish Trend represents stronger negative bias, slope, and relative volume pressure. A Soft Bearish Trend favors short-side analysis but still requires confirmation before treating the move as established.
Observe price relative to the nearest zone : When price is below the nearest K-Means zone, that level may act as an adaptive resistance reference. A return toward the red nearest-zone line can be monitored for rejection or continuation.
Wait for bearish price action : A Bearish Rejection From Zone appears when price tests a clustered area and forms a stronger upper-wick reaction. A Bearish Zone Breakout indicates that price has crossed below the zone with a sufficiently large bearish body. A Bearish Momentum Candle carries more weight when the broader Market State is already bearish.
Use the resistance line to define context : The K-Means resistance level can help identify where bearish continuation remains structurally reasonable. A sustained break above it may weaken the short scenario, particularly if Market State also shifts toward bullish or neutral conditions.
Do not ignore volatility warnings : A bearish candle during Volatility Shock may be followed by a sharp continuation, but it can also produce rapid retracement and unstable execution. In this condition, the indicator explicitly favors additional confirmation or reduced risk.
Check cluster quality before relying on the level : A weak or wide price cluster may produce a less precise resistance reference. Higher Quality and Reliability readings indicate a more compact and internally consistent zone, not a guaranteed bearish outcome.
A clearer bearish sequence may include a Soft or Active Bearish Trend, price trading below or retesting a red K-Means zone, bearish rejection or breakout behavior, manageable volatility, and an acceptable Quality score. When these components disagree, for example, a bullish momentum candle inside a bearish trend, the table should be read as a warning that momentum alone is not enough to confirm a reversal.
The built-in alert conditions can be used to monitor bullish and bearish K-Means zone breakouts and rejections. Alerts are most useful as notifications that a specific price-action condition has appeared; the final interpretation should still include Market State, Volatility, zone position, and Quality before any trading decision is made.
🔵 Settings
🟣 K-Means Engine Settings
Market State Lookback : Number of recent bars used to cluster trend bias, slope, and relative volume for market-state classification.
Price Zone Lookback : Number of recent bars used to build K-Means price zones from pivots, highs, and lows.
Volatility Lookback : Number of recent bars used to cluster ATR percentage, candle range, and return volatility.
Market State Clusters : Number of clusters used by the Market State model.
Price Zone Clusters : Number of price clusters used to calculate adaptive zone centers.
Volatility Clusters : Number of clusters used by the Volatility model.
Max K-Means Iterations : Maximum number of center-update cycles allowed during each clustering calculation.
Dominant State Window : Number of recent cluster assignments used to determine the dominant market state.
Fast Volatility State Window : Number of recent volatility assignments used to determine the dominant short-term volatility cluster.
Convergence Tolerance : Minimum center movement required to continue the K-Means iteration; lower values increase precision but may require more processing.
🟣 Price Zone Settings
Pivot Length : Number of bars used on each side of a candle to confirm pivot highs and pivot lows.
High/Low Sampling Step : Controls how frequently historical highs and lows are added to the price-zone dataset; lower values use more samples.
Minimum Near-Zone Distance (%) : Minimum percentage distance used to classify price as testing a K-Means zone.
🟣 Execution Control Settings
Historical Calculation Bars : Number of recent historical bars on which calculations and visual outputs are processed.
Refresh Every N Bars : Runs the main K-Means modules once every selected number of bars and always updates them on the latest bar.
🟣 Zone Stabilizer Settings
Zone Plot Mode : Selects how zone lines are displayed: Raw follows new centers directly, Smooth moves gradually, and Locked Steps updates only after a meaningful price shift.
Zone Smooth Length : Controls the smoothing speed in Smooth mode; higher values produce slower and more stable zone movement.
Zone Lock ATR Multiplier : Defines the minimum ATR-based movement required before a zone updates in Locked Steps mode.
Nearest Zone Switch Margin ATR : Prevents frequent switching between nearby zones by requiring the new zone to be closer by an ATR-based margin.
🟣 Display Settings
Show Analysis Table : Shows or hides the market analysis table.
Table Text Size : Sets the size used inside the table.
Table Position : Selects the table location on the chart.
Show All K-Means Zone Centers : Displays all calculated K-Means price-zone centers.
Show Nearest Zone : Displays the stabilized zone closest to the current price, colored by the detected market state.
Show K-Means Support/Resistance : Displays the nearest clustered support below price and resistance above price.
🔵 Conclusion
This indicator brings K-Means clustering, market state analysis, adaptive price zones, volatility classification, and price action context into one structured workflow. Instead of reducing the chart to a single signal, it separates the market into several readable layers: directional behavior, clustered support and resistance areas, candle reactions, volatility conditions, and the internal quality of the current calculations. This makes it easier to understand whether price is trending, ranging, testing a K-Means zone, reacting to a clustered level, or moving through an unstable volatility phase.
Its strongest use comes from confirmation rather than prediction. A bullish or bearish reading becomes more meaningful when the Market State, nearest K-Means zone, Price Action module, Volatility analysis, and Quality score support the same scenario. When these components disagree, the table highlights that uncertainty instead of hiding it. Used this way, the tool works as a machine learning market analysis framework that helps organize recent price data, compare changing market regimes, and identify areas where further confirmation is still required. Indicator

Indicator

Indicator

Indicator

PBO / Selection Bias CalculatorA calculator for selection bias in strategy backtests, based on the False Strategy Theorem. Enter the number of strategy variants you searched, the variance of their Sharpe ratios, and your single best variant's Sharpe; it returns the expected maximum Sharpe a no-edge search of that size would produce, and flags whether your best clears that screen.
How to read it
If your best Sharpe does not beat the expected maximum under the null, it is plausibly just the luckiest of many trials. Important: clearing the expected maximum is a screening threshold, not a statistical significance test.
Honest by design
- No buy/sell signals. It reads no price data; it is a pure analytics table computed from your inputs.
- Non-repainting by construction.
Open-source and MIT licensed. The underlying statistics (PSR, Deflated Sharpe, PBO via CSCV, Harvey-Liu haircut) follow the published papers cited in the code.
Disclaimer: impersonal educational and analytics tool. This is not investment advice, not a personalised recommendation, and carries no performance guarantee. Past results do not predict future results. You are solely responsible for your own trading decisions. Indicator

GEX Levels - Dealer Gamma Exposure GEX DAILY LEVELS — Dealer Gamma Exposure Levels
This indicator plots dealer gamma exposure (GEX) levels as horizontal lines, computed from index option chain data and supplied via a compact text string. It is designed for NQ/NDX but works with any instrument given matching data.
█ METHODOLOGY
The levels follow the standard "naive" dealer positioning convention (dealers long calls, short puts). Per-strike net GEX = gamma × open interest × contract multiplier × spot² × 1%, summed with calls positive and puts negative.
- Call Wall / Put Wall — strikes holding the maximum positive / most negative net GEX across expiries. Dealer hedging around these strikes dampens moves toward them in positive gamma (pinning) and defines major resistance/support.
- 0DTE Walls — the same computation restricted to the current session's expiry, isolating the most reactive intraday hedging flows.
- Gamma Flip — the spot level where aggregate dealer gamma changes sign, obtained by recomputing Black-Scholes gamma across a grid of hypothetical spot prices. Above it, hedging is mean-reverting; below it, hedging amplifies moves.
- Expected Move — the at-the-money straddle price for the nearest expiry: the move the options market is pricing for the day. Fractional bands (e.g. ±50%, ±150% of the straddle) are included because the straddle approximates 0.8 standard deviations, giving each band a defined statistical meaning.
- 1D Min/Max — the one-day range implied by annualized ATM volatility (IV/√252), a complementary volatility-based estimate.
- Max Pain — the strike minimizing total option holder payout at the nearest expiry.
- G+/G− — remaining top strikes ranked by absolute net GEX.
█ WHY A TEXT STRING INPUT
Open interest is static intraday, so gamma levels are constant for the session. Injecting them as data rather than recomputing on chart makes the indicator repaint-free, lookahead-free and provider-agnostic: any gamma data source, or your own option-chain computation, can feed it.
Format: price,label,kind;price,label,kind;...
Kind codes: res, sup (walls) · res0, sup0 (0DTE walls) · flip · emh, eml (expected move) · emb (fractional bands) · ivh, ivl (1D range) · mpain · gpos, gneg
Example: 21100.0,Call Wall,res;20950.5,Gamma Flip,flip;20800.0,Put Wall,sup
█ FEATURES
- Per-family styling: visibility, color, width (1–5), line style for each level type
- Alerts on price crossing walls, 0DTE walls or the gamma flip
- Proximity table showing the nearest level above and below current price with distances
- Label size, offset and price display options
█ LIMITATIONS
Levels are a pre-session snapshot; walls do not move intraday since open interest is settled overnight. The gamma flip may legitimately be absent in strongly positive gamma regimes. Educational tool; nothing here is financial advice. Indicator

Volume Footprint, Absorption & Imbalance Analysis by GurujamesHere is a breakdown of exactly what the tool does and how it helps you analyze the market.
1. Intrabar Order Flow Splitting (Delta Calculation)
Instead of just showing total volume, the script peers into the 1-minute timeframe inside your current candle to calculate the Volume Delta.
What it does: It separates aggressive market buying from aggressive market selling.
Why it matters: It tells you who is actually in control. A candle might close green, but if the delta is heavily negative, it means sellers were aggressively hitting the bid, but buyers held the line.
2. Trapped Trader Detection (Absorption Bubbles)
The script identifies exact moments when aggressive traders get trapped by passive limit orders from larger participants.
What it does: When extreme selling pressure fails to push the price down (leaving a bullish wick), or extreme buying pressure fails to push the price up (leaving a bearish wick), it triggers an absorption event.
Visual Output: It plots a circular bubble above or below the wick. Inside the bubble is the exact percentage of that candle's total volume that was absorbed.
Example: A green bubble reading "72%" means 72% of the bar's volume was aggressive selling that completely failed to move the market down.
3. Institutional Imbalance Zones (Extending Boxes)
This feature finds areas where the market became extremely one-sided, leaving a "vacuum" in the order book.
What it does: It scans for high-volume candles where one side outpaced the other by 300% or more (a 3:1 ratio).
Visual Output: It draws a semi-transparent, extending box (Green for Buy Imbalances, Red for Sell Imbalances) originating from the extreme of the candle.
Why it matters: These areas act as high-probability Supply and Demand zones. Because the move was so aggressive, liquidity was skipped. The market will very often retrace back to these boxes to "mitigate" or fill the skipped orders. The boxes auto-delete after an hour (configurable) to keep your chart clean once they become stale.
4. Unfinished Liquidity Magnets (Missed Auctions / Poor Extremes)
In auction market theory, a healthy market sweeps the high or low until volume tapers off to zero. When it doesn't, it creates a "poor" high or low.
What it does: It detects candles that close at their absolute highest or lowest tick while both buyers and sellers are still actively transacting high volume.
Visual Output: It highlights the upper or lower body of that specific candle with a bright extending box (Green for Missed Buys, Red for Missed Sells), accompanied by a small cross ().X
Why it matters: These zones represent "unfinished business." The market is highly likely to revisit these exact levels later to properly sweep the liquidity that was left hanging. You can toggle these visual zones on or off in the settings.
5. Real-Time Analytics Dashboards
The script paints two distinct data tables on your chart to give you micro and macro perspectives without having to do any math yourself.
The Macro Table (Top Right): Keeps a rolling 7-day memory of market aggressiveness. It shows you the total percentage of volume over the last week that resulted in trapped buyers vs. trapped sellers, helping you gauge the broader structural trend.
The Micro Table (Bottom Right): Acts as a live ticker for the active, moving candlestick. It updates tick-by-tick to show you the current bar's absorption percentages, whether an imbalance has triggered, and explicitly states the structural status (e.g., "BULLISH (Absorbing Sells)" or "Neutral"). Indicator

RS Rating (Relative Strength) - Clean Table UIThis indicator calculates the Relative Strength (RS) Rating of a stock compared to the S&P 500 (SPY) and displays it as a clean, simple numerical value in a customizable table on your chart.
Unlike many complex swing data indicators that clutter your screen with moving averages, background colors, and multiple data points, this script is specifically designed for minimalist traders, day traders, and scalpers who only need to see the core RS Rating score at a single glance.
How It Works:
Core Calculation: It uses the standard weighted formula for 1-year performance (40% for the most recent quarter, and 20% for each of the previous three quarters) compared against the S&P 500 benchmark.
Percentile Ranking (1-99): Using market environment seed data, the raw score is converted into a true 1 to 99 percentile ranking. For example, an RS Rating of 85 means the stock is currently outperforming 85% of the overall market.
Color-Coded Signals: The numerical value automatically changes color based on the stock's momentum:
Green (>= 80): Strong market leader.
Red (<= 40): Weak laggard.
Custom/White: Neutral performance.
Features:
Zero Chart Clutter: No lines or shapes plotted over your candles. Just a single, elegant table.
Fully Customizable: You can easily change the table's position (Top/Bottom, Left/Right) and text size (Normal, Large, Huge) directly from the indicator settings to fit your exact workspace layout.
(Credits to the original open-source community and Fred6724 for the percentile mapping seed function utilized to power this clean UI version). Indicator

XG Boost Lite: Reversals | GainzAlgoWe are excited to release this indicator, which uses our brand-new Arbor library for gradient boosting! This engine brings true, high-performance machine learning natively into Pine Script v6, bypassing the need for external webhooks or API layers. By utilizing iterative, tree-based models on your chart, XGBoost Lite: Reversals adapts directly to the historical structure of the asset you are trading, identifying precise pivot exhaustion points with high statistical conviction.
🧠 Understanding Gradient Boosting & XGBoost
To trade successfully with machine learning, it helps to understand exactly what is happening beneath the hood of the asset's data.The Core TheoryGradient Boosting is a powerful machine learning technique used for regression and classification tasks. Unlike deep learning networks that process data through abstract node layers, gradient boosting relies on an ensemble of simple decision trees, often called "weak learners" or "stumps".
The training process works sequentially:
The Initial Guess: The model makes a basic baseline prediction.Calculating the Error (Residuals): It checks where its prediction missed the actual historical market outcome.
Correcting the Mistakes: A new decision tree is built specifically to predict those errors (the gradient of the loss function).
Iterative Learning: The model repeats this process for several rounds. Each new tree focuses entirely on correcting the flaws of the previous ones, scaling its adjustments by a Learning Rate to maintain stability.
What Makes XGBoost Special?
XGBoost (Extreme Gradient Boosting) optimizes this framework for speed, scalability, and performance. It applies strict regularization techniques to minimize overfitting, ensuring the model doesn't just "memorize" past market noise but instead learns genuine structural behaviors.By evaluating multiple market features simultaneously, it estimates the probability of a specific event occurring.
🛠️ About the Indicator
XGBoost Lite: Reversals is a machine learning-driven technical indicator designed to catch exhaustion and reversal setups.
The Machine Learning Pipeline
Dual Engines: The script fits four separate models simultaneously—a classifier and a regressor for Longs, and a classifier and a regressor for Shorts.
Dynamic Retraining: Rather than remaining static, the model automatically flushes its memory and retrains its internal mathematical weights every n bars to adapt to evolving market regimes.
Strict Non-Repainting Execution: A critical upgrade in this framework forces features and calculations to compute and lock strictly on bar close. Signals, dynamic entry points, and risk metrics are only printed once the triggering candle is finalized, ensuring what you see on the historical chart matches real-time execution perfectly.
The Core Features Evaluated
The model processes a combination of multi-dimensional market inputs to generate a unified prediction:
RSI (14): Evaluates traditional momentum expansion and contraction.
Relative Volume (20): Evaluates institutional engagement by dividing current volume against its 20-period SMA.
Z-Score (20): Measures how far the current price has deviated from its statistical mean.
ADX (14): Gauges the overall strength of the macro trend to prevent trading directly into a runaway freight train.
📊 How to Use the Indicator
The Real-Time Dashboard: When applied to your chart, the indicator renders an advanced Feature Importance Scatter Plot in the right-hand margin.
Distribution Scatter: The horizontal bars plot the historical density of successful signals. Darker, tightly packed nodes represent highly concentrated, high-probability clusters discovered by the algorithm.
Visualizing Signals
When a market pivot is detected (e.g., a structural swing low or high) and the classifier hits your target confirmation probability, a signal arrow prints on the chart displaying the mathematical certainty ($e.g., 74.2\%$) of the reversal.
⚙️ The Settings Inputs
The indicator’s interface is neatly categorized into three primary functional groups:
⚙️ XGBoost Model Settings:
Training Lookback (Bars): (Default: 250) The historical window used to feed the training arrays. Max capped at 300 to remain computational within Pine Script limits.
Retrain Frequency: (Default: 50) Determines how often (in bars) the model recalibrates its trees. Boosting Rounds: (Default: 20) The number of sequential trees (stumps) trained per model. Higher numbers capture deeper complexities but risk overfitting.
Learning Rate: (Default: 0.3) The step size applied to each boosting round to prevent the model from learning too quickly. Min Probability for Signal: (Default: 0.65) The minimum confidence threshold ($65\%$) required from the classification model to trigger an active trade.
ADX Length / Minimum Filter: (Default: 14 / 20.0) Prevents counter-trend signals if the prevailing macro trend is too strong.
🛡️ Target & Risk Management
SL Wick Buffer ×ATR: (Default: 0.25) Sets how much breathing room is given below a swing low wick or above a swing high wick, scaled by ATR.
TP1 ×Risk (R-multiple): (Default: 1.0) Targets a clean 1:1 Risk-to-Reward ratio for the initial profit take.
TP3 Min ×Risk (Floor): (Default: 2.0) The minimum target floor for the machine learning regression objective.
Break-Even After TP1: (Default: True) Automatically moves the Stop Loss to the exact entry price the moment TP1 is captured, eliminating risk on the remainder of the trade.
📈 How to Trade the Indicator
Trading with the machine learning model requires blending quantitative probabilities with standard structural execution:
The Entry: Wait for a Bullish (Neon Purple) or Bearish (Neon Pink) arrow to finalize on a closed candle. The percentage printed indicates the model's confidence.
Placing Risk: The system automatically draws a solid line anchoring your Stop Loss tightly to the local structural wick pivot, applying an ATR buffer to account for minor noise.
Scaling Targets:
Target 1 (TP1): Landed at a symmetrical 1:1 distance. When hit, the indicator dynamically updates your Stop Loss to your entry line, locking in a "scratch-or-better" runner.
Target 2 (TP2): Represents the mathematical midpoint between your baseline risk and the macro ML objective.
Target 3 (TP3): Driven directly by the XGBoost Regression Model. The regressor estimates the potential mathematical expansion based on current market features—if volatility is expanding, TP3 will automatically stretch further to ride major trend changes.
📊 Deep Dive: The Feature Importance & Scatter Plot Dashboard
The dashboard rendered on the right side of the chart acts as the "brain" of the indicator. It provides real-time transparency into exactly how the machine learning model is weighing data and evaluating current market conditions.
Feature Importance Bars (The Relative Weights): The horizontal progress bars display the mathematical percentage weight allocated to each of the four indicators processed during the model's most recent training cycle. These values change dynamically every time the model triggers a retraining block (default: every 50 bars) as it adapts to shifting market conditions. For example, if the market moves into a heavy trending phase, you will notice metrics like the ADX or Z-Score capture a higher percentage of the model's attention, whereas the RSI will frequently become the dominant driver if the asset is range-bound.
The Holographic Scatter Plot (Historical Feature Density): Layered over the progress bars is an advanced distribution scatter plot consisting of individual circular glyphs (○, ◉, ●) that plot a rolling record of the last 30 historical signal points. The horizontal position of each dot shows exactly where the feature value landed relative to its historical extremes (0 on the far left, 1 on the far right). The script introduces a subtle vertical "jitter" to separate these dots so you can visually identify high-density clusters where successful reversal setups frequently occur, while the shifting style of the glyphs flags tightly packed clusters of solid nodes (●) to indicate highly concentrated mathematical sweet spots discovered by the XGBoost classifier.
Indicator

DTC Initial Balance ProWHAT THIS DOES
Every trading session has an "Initial Balance" — the first chunk of time
after the open (default: the first hour, 09:30-10:30 New York) where the
market sets its early high and low. Traders have long believed that
WHICH ONE FORMS FIRST — the high or the low — hints at which way the
rest of the day tends to go.
The problem: on a normal chart, you can't actually tell which came
first just by looking at a candle. A single 15-minute or 1-hour candle
can have both a new high AND a new low in it, and the candle's color
tells you nothing about the order they happened in.
This indicator solves that by secretly rebuilding the entire session
minute-by-minute in the background (even if your chart is on 15m, 1H,
or Daily), so it can tell you EXACTLY which one happened first — based
on real timestamps, never a guess.
HOW TO READ IT
- A colored box appears over the session: green means the low formed
first, red means the high formed first. Gray means it's still
forming.
- A small label shows the result once the session ends.
- A table (top-right by default) shows the full breakdown: exact
prices, exact times, and a "Bias" (Long/Short) reading.
THE PART THAT MAKES THIS DIFFERENT
Most tools stop at "which formed first." This one keeps going and
actually checks your chart's history to answer the follow-up question:
"okay, but does that actually mean anything?" It tracks, for every
past session, what price did AFTERWARD — did it break above the
session high, or below the session low — and shows you the real
percentages. So instead of trusting a rule of thumb, you can see
whether it's actually held up on the exact symbol and timeframe you
trade.
It also projects price targets above and below the session (simple
multiples of the session's range) and shows how often price has
historically reached each one.
FEATURES
- Works on any chart timeframe - internally always reconstructed from
1-minute (or 5-minute, for older history) data
- Fully customizable session times, not locked to the NY open
- Adjustable colors, box/line styles, and label sizes
- A statistics table with three sections: current session detail,
all-time stats, and post-session breakout odds
- Price target lines (+0.5x to +3.0x the session range) with their own
historical hit-rate table
- Alerts for session completion and for each outcome
- No repainting - once a session ends, its result is permanently frozen
A NOTE ON HONESTY
This indicator will tell you "Simultaneous" instead of guessing when
the high and low happen too close together to tell apart (this is a
hard limit of how granular historical data can get, not a shortcut).
Older history beyond what 1-minute data allows automatically falls back
to 5-minute reconstruction, clearly labeled in the table so you always
know the precision you're looking at.
This is an analytical tool for understanding market structure, not financial advice.
Historical statistics describe the past
they are not a guarantee of future behavior.
Indicator

Indicator
