Indicateur

Indicateur

Auto Trend Channel & Breakout Expectancy in ROVERVIEW
An auto-drawn trend channel is easy. Knowing whether breaking it has ever paid on YOUR symbol is not — and it is the only thing that matters.
This tool draws the channel objectively and then does the part nobody else does: it forward-resolves every historical break through a real target and stop, and reports, in R, what breaks like the current one have actually returned. Not a prediction. A track record.
Expectancy exp +1.24R · need 15% @ RR 6.0
HV win/loss 38/59% n400 ✓
MV win/loss 32/65% n150 ✓
LV win/loss 17/83% n55
Null / net net 1.29R t=3.1 ✓
It is a research and framing tool. NOT a strategy, NOT a signal service, NOT a validated edge.
HOW THE CHANNEL IS BUILT — objectively, no hand-placed anchors
The support and resistance lines come from a CONVEX HULL over confirmed pivots, not from two points a human chose. The opposite boundary is drawn parallel, and the channel WIDTH becomes the measured-move target. Because the construction is mechanical, the same rule produces the same channel on every symbol and every timeframe — there is nothing to curve-fit.
HOW A BREAK IS GRADED — and why volume is split three ways
A break is a confirmed CLOSE beyond the boundary. Every break is then sorted by its break-bar volume percentile into HV / MV / LV (high / medium / low), and each tier is calibrated SEPARATELY.
That split is the point. "Breakouts need volume" is repeated everywhere and tested almost nowhere. Here you can read straight off the panel whether heavy breaks on your instrument actually pay more than thin ones — and often they do not, which is worth knowing before you wait for a volume confirmation that costs you the entry.
THE FORWARD TEST — expectancy in R, on identical geometry
Every break is resolved through a triple barrier: a target at the channel-width move, a stop at a fixed ATR distance, and a horizon. Win, loss, or chop. The expectancy is the exact realized R per trade — a win contributes +RR, a loss contributes −1, chop contributes 0 — so the win rate and the R:R are on the SAME footing, computed from the same resolved trades. There is no mixing of a win rate from one calculation with an R:R from another.
The R:R shown is the target-to-stop RATIO, and it is deliberately not the headline. A 6:1 target sounds wonderful and is reached maybe a third of the time; quoting it alone flatters a low-hit-rate system. So the panel leads with the realized EXPECTANCY, then states the breakeven win rate the geometry requires, then shows the win rate actually achieved. Expectancy first, because expectancy is the thing that is actually true.
Nothing is rated until a tier has at least 30 resolved trades. Below that, no checkmark, no verdict, no meta call — a Wilson floor on a dozen trials is too wide to certify anything, and pretending otherwise is how bad tiers get a green tick.
THE RANDOM-DIRECTION NULL — the honesty check
Here is the trap this defends against. A 6:1 target with a nearby stop is an asymmetric payoff, and on a drifting instrument an asymmetric payoff makes money in a RANDOM direction — the geometry earns, not the signal. So for every real break the script ALSO runs a coin-flip-direction trade with the identical target and stop, and reports its expectancy alongside.
If the null earns as much as the signal, the "edge" is just the geometry capturing drift, and you should believe the null. And it is now TESTED, not just displayed: a Welch t between the signal's realized-R distribution and the null's turns "net 1.29R" into "net 1.29R, t = 3.1, real" — or into "ns", not significant, which is the more common and more honest outcome.
THE OPTIONAL META-LABEL — a learned second opinion
An online logistic model trains on this script's own resolved outcomes and outputs a calibrated probability of follow-through for the current break. No hand-tuned weights; it self-corrects as more breaks resolve, and it reports its own reliability (the realized win rate inside each probability bin) so you can see whether its confidence is earned. It is off by default and it never overrides the forward test — it is a second opinion, not the verdict.
THE ANTI-BIAS GUARDS
ENTRY IS THE CLOSE (or, in retest mode, the line touch) — a break is a signal, not a fill, and entering at a better price than the trade actually offered would manufacture an edge.
Both barriers on one bar: the STOP is assumed first — conservative, and the only assumption that cannot flatter the result. Unresolved trades at the horizon are scored as chop (zero), not as wins.
THE NULL is direction-randomised on the same geometry, which is what isolates signal from payoff structure. Every rating is gated by a minimum sample and a Wilson lower bound, and the null gap is significance-tested. Nothing here is asserted that has not cleared a test.
NON-REPAINT
Confirmed pivots, confirmed-close breaks, and forward-resolved calibration that never looks ahead. The channel can extend and re-fit as new pivots confirm, but a resolved trade is never re-scored, and no barrier is evaluated on a bar that has not closed.
DATA AND SCOPE
Any symbol, any timeframe. ATR-normalised throughout. Volume is used for the tier split; without it the tiers collapse to one and everything else still works.
EXPORTS (Data Window — consume from other scripts via input.source())
Channel high, channel low, break direction, volume tier, entry, stop, target, per-tier expectancy, null expectancy, meta probability — see the Exports group.
CONCEPT CREDIT
The convex-hull approach to objective trendlines, the triple-barrier forward-labelling method and the meta-labelling idea are from Marcos Lopez de Prado ("Advances in Financial Machine Learning"). The trading-range break as a formal, testable rule was first studied at scale by Brock, Lakonishok and LeBaron (Journal of Finance, 1992); its vulnerability to data-snooping was shown by Sullivan, Timmermann and White (1999) — which is exactly why this tool measures the rule on your instrument instead of asserting it. Wilson score interval — E. B. Wilson (1927). Welch's t-test — B. L. Welch. ATR — J. Welles Wilder.
The convex-hull channel implementation, the volume-tier calibration, the random-direction null with its significance test, and the online meta-label are the author's own. Clean-room implementation; no third-party Pine code is reused. Not affiliated with, nor endorsed by, any of the above.
HONESTY AND LIMITATIONS
Calibration is IN-SAMPLE, fixed-barrier, and assumes idealised fills — no commission, no slippage, no partial fills. It describes the past; it does not predict the future. Real costs will reduce every number, and they reduce the low-hit-rate high-RR tiers most.
Overlapping windows mean the samples are not fully independent, so treat the t-stats as directional evidence, not exact p-values. A tier that is proven in-sample is not guaranteed out-of-sample.
The null being beaten is the single most important line on the panel, and on many instruments it will read "ns". That is a real result. A tool that cannot report "no edge here" is selling you something.
Nothing in this script predicts price.
DISCLAIMER
Research and educational tool only. NOT financial advice, NOT a recommendation, and NO guarantee of results. Entry, stop and target output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use. Indicateur

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.
Indicateur

Indicateur

Indicateur

Institutional Sniper Signal (Clean v7)This indicator is a Multi-Timeframe (MTF) quantitative system designed to trade pullbacks and breakouts in alignment with the higher timeframe macro trend.
Rather than relying on a single indicator to dictate the trend, this script utilizes a Consensus Voting Mashup. By aggregating data from 15 different structural and momentum indicators on a higher timeframe, it calculates a definitive directional bias, filtering out the noise of ranging markets.
⚙️ CORE MECHANICS (The Consensus Logic):
To avoid repainting and false signals, the script operates in three strict phases:
The Macro Consensus (4H Closed Candle): The engine pulls data from the last closed 4H candle across 15 distinct tools (including EMA 200, EMA 50, WMA 100, Parabolic SAR, Ichimoku Tenkan/Kijun, DEMA, TEMA, and standard deviation bands). Each indicator gets 1 "vote" (Buy or Sell). A trade is only authorized if a strict user-defined threshold is met (e.g., 10 out of 15 indicators agreeing on the same direction).
The Pullback Trigger (1H): Once the macro consensus is formed, the script monitors the 1H timeframe. It waits for the local price to retrace and touch the 1H 20 EMA, identifying a potential discounted entry area.
The Fractal Breakout (Execution): It does not enter at market price. Instead, it calculates a 5-bar Fractal High (for longs) or Fractal Low (for shorts). It then plots visual pending order lines (Buy Stop / Sell Stop) at these fractal extremes, adding a customizable price offset to avoid fakeouts.
🛡️ RISK MANAGEMENT:
ATR Stop Loss: The stop loss is dynamically plotted at the opposite fractal, buffered by an ATR multiplier to allow the trade to breathe.
Daily Limit: Includes a daily signal limiter to prevent overtrading during high-volatility sideways days.
🛠️ HOW TO USE:
Apply the script to your execution timeframe (e.g., 15m or 30m). Adjust the "Offset" input based on your asset (e.g., 0.0002 for Forex pairs or 2.0 for US Indices). When a valid consensus is met and the price pulls back, the indicator will plot horizontal lines with precise labels for your pending Entry and Stop Loss.
🇧🇷 (PORTUGUÊS)
Este indicador é um sistema quantitativo Multi-Timeframe (MTF) projetado para operar pullbacks e rompimentos alinhados com a tendência macro.
Em vez de usar apenas um indicador para definir a tendência, este script utiliza um Sistema de Votação por Consenso. Ele agrega dados de 15 indicadores diferentes no tempo gráfico maior para calcular um viés direcional definitivo.
⚙️ COMO FUNCIONA A LÓGICA:
Para evitar repintura (repainting), o script opera em 3 fases:
O Consenso Macro (Vela Fechada H4): O motor puxa os dados da última vela fechada de H4 em 15 ferramentas diferentes (EMA 200, Ichimoku, DEMA, SAR, etc). Cada indicador dá 1 "voto". O setup só é armado se a maioria esmagadora (ex: 10 de 15) concordar com a direção.
O Gatilho de Pullback (H1): Com o consenso formado, o script espera o preço retrair e tocar na EMA 20 do H1 (área de desconto).
O Rompimento do Fractal (Entrada): O indicador não entra a mercado. Ele mapeia a Máxima ou Mínima dos últimos 5 candles (Fractal) e desenha uma linha de ordem pendente (Buy Stop / Sell Stop) com um recuo (offset) customizável.
COMO USAR: Adicione no seu gráfico de execução (ex: M15). Ajuste o valor do "Offset" nas configurações de acordo com o ativo (ex: digite 0.0002 se for Forex ou 2.0 se for Índice). Aguarde as linhas de entrada e Stop Loss aparecerem na tela para posicionar suas ordens pendentes. Indicateur

Institutional Sniper Signal (Clean v7)This indicator is a Multi-Timeframe (MTF) quantitative system designed to trade pullbacks and breakouts in alignment with the higher timeframe macro trend.
Rather than relying on a single indicator to dictate the trend, this script utilizes a Consensus Voting Mashup. By aggregating data from 15 different structural and momentum indicators on a higher timeframe, it calculates a definitive directional bias, filtering out the noise of ranging markets.
⚙️ CORE MECHANICS (The Consensus Logic):
To avoid repainting and false signals, the script operates in three strict phases:
The Macro Consensus (4H Closed Candle): The engine pulls data from the last closed 4H candle across 15 distinct tools (including EMA 200, EMA 50, WMA 100, Parabolic SAR, Ichimoku Tenkan/Kijun, DEMA, TEMA, and standard deviation bands). Each indicator gets 1 "vote" (Buy or Sell). A trade is only authorized if a strict user-defined threshold is met (e.g., 10 out of 15 indicators agreeing on the same direction).
The Pullback Trigger (1H): Once the macro consensus is formed, the script monitors the 1H timeframe. It waits for the local price to retrace and touch the 1H 20 EMA, identifying a potential discounted entry area.
The Fractal Breakout (Execution): It does not enter at market price. Instead, it calculates a 5-bar Fractal High (for longs) or Fractal Low (for shorts). It then plots visual pending order lines (Buy Stop / Sell Stop) at these fractal extremes, adding a customizable price offset to avoid fakeouts.
🛡️ RISK MANAGEMENT:
ATR Stop Loss: The stop loss is dynamically plotted at the opposite fractal, buffered by an ATR multiplier to allow the trade to breathe.
Daily Limit: Includes a daily signal limiter to prevent overtrading during high-volatility sideways days.
🛠️ HOW TO USE:
Apply the script to your execution timeframe (e.g., 15m or 30m). Adjust the "Offset" input based on your asset (e.g., 0.0002 for Forex pairs or 2.0 for US Indices). When a valid consensus is met and the price pulls back, the indicator will plot horizontal lines with precise labels for your pending Entry and Stop Loss.
🇧🇷 (PORTUGUÊS)
Este indicador é um sistema quantitativo Multi-Timeframe (MTF) projetado para operar pullbacks e rompimentos alinhados com a tendência macro.
Em vez de usar apenas um indicador para definir a tendência, este script utiliza um Sistema de Votação por Consenso. Ele agrega dados de 15 indicadores diferentes no tempo gráfico maior para calcular um viés direcional definitivo.
⚙️ COMO FUNCIONA A LÓGICA:
Para evitar repintura (repainting), o script opera em 3 fases:
O Consenso Macro (Vela Fechada H4): O motor puxa os dados da última vela fechada de H4 em 15 ferramentas diferentes (EMA 200, Ichimoku, DEMA, SAR, etc). Cada indicador dá 1 "voto". O setup só é armado se a maioria esmagadora (ex: 10 de 15) concordar com a direção.
O Gatilho de Pullback (H1): Com o consenso formado, o script espera o preço retrair e tocar na EMA 20 do H1 (área de desconto).
O Rompimento do Fractal (Entrada): O indicador não entra a mercado. Ele mapeia a Máxima ou Mínima dos últimos 5 candles (Fractal) e desenha uma linha de ordem pendente (Buy Stop / Sell Stop) com um recuo (offset) customizável.
COMO USAR: Adicione no seu gráfico de execução (ex: M15). Ajuste o valor do "Offset" nas configurações de acordo com o ativo (ex: digite 0.0002 se for Forex ou 2.0 se for Índice). Aguarde as linhas de entrada e Stop Loss aparecerem na tela para posicionar suas ordens pendentes. Indicateur

[GYTS-CE] Kinetic Trend Envelope (adaptive trailing stop)Kinetic Trend Envelope (Community Edition)
🌸 Part of GoemonYae Trading System (GYTS) 🌸
🌸 --------- INTRODUCTION --------- 🌸
💮 What is the Kinetic Trend Envelope?
The Kinetic Trend Envelope (KTE) is an adaptive directional trailing stop in the lineage of SuperTrend, rebuilt around the premise that volatility is kinetic energy . It measures per-bar motion with five academically grounded volatility estimators, then widens the envelope as energy rises and contracts it as motion settles.
In an uptrend, the lower band ratchets higher and never retreats; in a downtrend, the upper band ratchets lower. The direction changes when the active stop is breached, after which the opposite side becomes the new trailing stop.
💮 Why Use This Indicator?
Conventional trailing stops typically combine a price anchor with one symmetric ATR-derived width. The KTE extends that model with:
Asymmetric volatility profiling — Bullish- and bearish-candle volatility shape the upper and lower bands independently.
Three direction-switch methods — High/low, close, or a smoothed estimator controls flip sensitivity without moving the band anchor.
Five volatility estimators — ATR plus Parkinson, Garman-Klass, Rogers-Satchell, and Yang-Zhang covers different treatments of gaps, drift, and intrabar range.
The outputs are calibrated to a common width basis, so Volatility Factor remains interpretable across estimators and price scales. Fine adjustment may still be useful, but switching estimators should not require re-tuning by orders of magnitude.
↑ The KTE on a trending instrument. The thick line is the active trailing stop; the thin line shows the opposing side of the envelope. Both expand and contract with market energy.
↑ KTE beside TradingView's built-in SuperTrend, both using ATR with a 10-bar lookback. KTE's asymmetric profile changes how each side responds to directional volatility while the monotonic active band avoids premature loosening.
🌸 --------- HOW IT WORKS --------- 🌸
💮 Core Concept
The bands share a smoothed price estimator as their anchor, but use separate volatility profiles:
Upper band = estimator + (factor × bullish-candle volatility)
Lower band = estimator − (factor × bearish-candle volatility)
In a bullish state, the lower band is active and can only rise. In a bearish state, the upper band is active and can only fall. This monotonic constraint prevents a live trailing stop from loosening within the trend.
The selected direction-switch method changes only the breach test. It does not change the smoothed estimator anchoring the envelope, so a wick-sensitive trigger cannot drag the bands around with the wick.
💮 The Five Volatility Estimators
Each estimator reads a different part of the OHLC bar:
ATR (Wilder, 1978) — Familiar baseline that handles gaps through true range.
Parkinson (1980) — Uses high-low range; efficient under continuous, low-drift conditions.
Garman-Klass (1980) — Adds open-close information; favours continuous sessions without material gaps.
Rogers-Satchell (1991) — Drift-independent and well suited to trending, continuously traded instruments.
Yang-Zhang (2000) — Combines overnight gaps, open-close movement, and Rogers-Satchell; the gap-aware default.
Statistical efficiency does not guarantee a visibly tighter stop. At slow Adaptation Speed settings, long averaging makes the estimators look similar; at fast settings, their different treatments of gaps, drift, and range become more visible. Choose according to the instrument's behaviour rather than expecting one estimator always to produce the narrowest band.
↑ ATR and Yang-Zhang at Adaptation Speed 2. The long profile memory (low speed) smooths away most of the difference, so the two envelopes nearly overlap.
↑ ATR and Yang-Zhang at Adaptation Speed 8. The short profile memory (high speed) exposes their different volatility readings, producing visibly distinct envelope widths.
💮 Asymmetric Volatility Profiling and Adaptation Speed
The KTE stores volatility from bullish and bearish candles separately. Bullish samples determine the upper width; bearish samples determine the lower width. This allows the two sides to respond differently when upward and downward motion carry different energy.
Adaptation Speed controls the memory of this profile, not the speed of the price estimator and not the distance of the stop by itself. Its 1–10 scale maps logarithmically to an internal window:
Speed 3 — approximately 878 bars: stable and slow to re-weight
Default 3.5 — approximately 570 bars: general-purpose smoothing
Speed 8 — approximately 11 bars: highly responsive to recent volatility
Speed 10 — approximately 2 bars: extremely reactive and noisy
Faster does not necessarily mean closer to price. During a volatility burst, a fast profile recognises the expansion sooner and may widen the band sharply. Because the active stop cannot loosen, it can then remain flat until the estimator catches up. A slow profile dilutes the same burst across much more history, so its narrower band may appear to follow price faster.
This is why two instances matched during a calm period can separate during a shock, especially when they also use different Volatility Factor values. Compare Adaptation Speed with the same factor first; matching lines in one regime does not make two configurations equivalent elsewhere.
The profiles are also direction-conditioned: bullish samples are replaced by later bullish candles and bearish samples by later bearish candles. A recent high-volatility sample can therefore persist through a run of opposite-colour candles, producing deliberate step-like plateaux in the relevant band.
↑ Asymmetric profiling in action: the upper and lower widths respond independently to bullish- and bearish-candle volatility.
💮 Direction Switch Methods
The breach source sets the balance between responsiveness and false flips:
On high/low — Uses the current bar's wick and can switch on the breach bar. Fastest and most sensitive to noise.
On close — Uses the previous confirmed close; the switch appears on the following bar.
On estimator — Uses the previous smoothed estimator; the most conservative default, also switching on the following bar.
↑ The three switch methods share the same band geometry but change direction at different times.
🌸 --------- KEY FEATURES --------- 🌸
💮 Eight Estimator Filters
The configurable price anchor includes:
Ultimate Smoother, 2- or 3-pole — Low-noise, near-zero-lag passband response; the 2-pole version is the default.
Super Smoother, 2- or 3-pole — Ehlers low-pass filters for progressively stronger smoothing.
BiQuad — Second-order low-pass filter with an adjustable Q-factor.
ADXvma — Adapts to trend strength and tends to flatten in ranges.
MAMA — Cycle-adaptive MESA moving average.
A2RMA — Adaptive recursive moving average with adjustable gamma.
They are provided by the open-source FiltersToolkit library.
💮 Visual Layering
The display separates function from context:
Active band — Thick directional trailing-stop line
Opposing band — Thin reference for the inactive side
Channel fill — Visual separation between the estimator and each band
Estimator — Optional smoothed anchor
Palette, light/dark mode, widths, and transparencies can be adjusted independently.
🌸 --------- USAGE GUIDE --------- 🌸
💮 Getting Started
Start with the defaults, observe several calm and volatile regimes, and change one dimension at a time:
Tune Volatility Factor for the preferred stop distance.
Tune Adaptation Speed for how quickly width should respond to regime changes.
Choose the direction-switch method for the preferred confirmation level.
Change the volatility estimator only when its assumptions better fit the instrument.
💮 Choosing a Volatility Estimator
Gapped equities — Yang-Zhang accounts for overnight movement.
Trending 24/7 markets — Rogers-Satchell is drift-independent without a separate gap component.
Continuous, range-led markets — Parkinson or Garman-Klass offers efficient range-based measurement under their assumptions.
Familiar baseline — ATR provides conventional true-range behaviour.
On continuous instruments, Rogers-Satchell and Yang-Zhang may look very similar because there are few gaps to distinguish them. Use the Volatility Toolkit to compare their raw behaviour on the intended instrument.
↑ Three estimators compared on one instrument, each reading a different combination of OHLC information.
💮 Tuning Width and Responsiveness
These controls solve different problems:
Volatility Factor — Sets the distance per unit of measured volatility.
Adaptation Speed — Sets the memory of the bullish/bearish profile; faster can widen the stop sooner during shocks.
Volatility Lookback — Sets how quickly the underlying per-bar volatility estimate changes.
Estimator Lookback — Sets the smoothness of the price anchor.
Use symptoms to guide adjustment:
Frequent flips on minor pullbacks — Increase Volatility Factor or use a more conservative switch method (e.g. "on estimator").
Excessive give-back — Decrease Volatility Factor or use a more responsive switch method (e.g. "on high/low").
Width reacts too slowly to regime changes — Increase Adaptation Speed or reduce Volatility Lookback.
Bands become erratic during shocks — Reduce Adaptation Speed or increase Volatility Lookback.
↑ A tight factor follows price more closely and flips more often; a loose factor tolerates larger pullbacks.
💮 Trading Applications
Discretionary trailing stop — Move a protective stop with the active band as it tightens.
Trend confirmation — Accept long signals only during a bullish KTE state, and short signals only while bearish.
Exit timing — Treat a direction change as an exit when the trade thesis is trend-following.
💮 Integration with GYTS Suite
The visible bands and estimator can be selected as sources by compatible Pine scripts. Two packed streams are also exposed:
🔗 STREAM KTE 🪜 Trailing Stoploss — Positive lower-band value in a bullish state; negative upper-band value in a bearish state.
🔗 STREAM KTE 🪜 Mechanism — Encodes the switch method and scale-invariant estimator relationship for compatible consumers.
The KTE is, first and foremost, a trailing stop, and these streams are built for stop management. The Order Orchestrator strategy consumes the Trailing Stoploss and Mechanism streams together : the first supplies the active stop level and its direction, the second makes the strategy's trailing-exit runner follow whatever switch method and estimator you set here. So the stop is configured once, in the KTE.
Beyond that primary role, the signed trailing-stop stream can also serve as a trend signal, since its sign flips with direction: it can be read through sign and magnitude as an entry/exit signal, including by Flux Composer . The KTE can also be paired with Market Regime Detector so flips are acted on only when the broader regime supports trend-following behaviour.
🌸 --------- LIMITATIONS --------- 🌸
Trailing-stop latency — Every trailing stop gives back some of the move between the trend extreme and the eventual breach.
Whipsaws in ranges — Low-energy chop can produce repeated flips; a regime filter may help when ranging conditions dominate.
Fast adaptation can widen the stop — Higher Adaptation Speed means faster volatility response, not guaranteed proximity to price.
Direction-conditioned memory — A bullish or bearish outlier remains in its own profile until enough matching-direction samples replace it, which can create plateaux after shocks.
Warm-up and sample size — Long profile windows need sufficient chart history; strongly one-sided markets may leave one side with few recent samples.
🌸 --------- CREDITS --------- 🌸
💮 Academic Sources
Wilder, J. W. (1978). New Concepts in Technical Trading Systems . Trend Research.
Parkinson, M. (1980). The Extreme Value Method for Estimating the Variance of the Rate of Return. Journal of Business, 53 (1), 61–65. DOI
Garman, M. B., & Klass, M. J. (1980). On the Estimation of Security Price Volatilities from Historical Data. Journal of Business, 53 (1), 67–78. DOI
Rogers, L. C. G., & Satchell, S. E. (1991). Estimating Variance from High, Low and Closing Prices. Annals of Applied Probability, 1 (4), 504–512. DOI
Yang, D., & Zhang, Q. (2000). Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices. Journal of Business, 73 (3), 477–491. DOI
Ehlers, J. F. (2024). The Ultimate Smoother. Technical Analysis of Stocks & Commodities , 2024-04. TASC
Ehlers, J. F. (2004). Cybernetic Analysis for Stocks and Futures . Wiley. Covers SuperSmoother, MAMA and more.
💮 Inspiration
Thanks to Trendoscope for inspiring us with the Supertrend - Ladder ATR (2021). It derives long-side stop distance from bearish-candle ATR and short-side distance from bullish-candle ATR, which is one of the mechanisms that we tried to develop further with the KTE.
💮 Libraries Used
FiltersToolkit — Ultimate Smoother, Super Smoother, BiQuad, ADXvma, MAMA, and A2RMA
VolatilityToolkit — Parkinson, Garman-Klass, Rogers-Satchell, and Yang-Zhang estimators
MathTransform — Logarithmic scaling for Adaptation Speed
ColourUtilities — Palette management and light/dark-mode colour adjustment
Indicateur

Indicateur

TrendPulse: 9 EMA + VWAP Continuation StrategyTrendPulse combines 9 EMA trend structure, VWAP positioning, and continuation logic into a chart-ready intraday strategy. It includes fully customizable visual aids, signal markers, dashboard metrics, and active trade overlays for entry, stop, target, and break-even visualization, allowing traders to tailor the display to their own strategy and charting preferences. Trade overlays appear only while a position is active and automatically disappear once the trade is closed to help keep charts clean and uncluttered.
TrendPulse combines 9 EMA trend structure, VWAP positioning, and continuation logic into a chart-ready intraday strategy built for traders who want both structure and flexibility. The script is designed to help identify trend alignment, continuation opportunities, and trade management levels while keeping the chart readable and customizable.
This strategy includes fully customizable visual aids, signal markers, dashboard metrics, and active trade overlays for entry, stop, target, and break-even visualization. All visual elements can be adjusted to better fit individual trading styles, chart layouts, and preferred market conditions. Active trade overlays appear only while a position is live and automatically disappear after the trade closes, helping reduce chart clutter.
How It Works
TrendPulse evaluates price structure using a combination of:
fast and slow EMA trend bias
a dynamic basis line
9 EMA context
VWAP positioning
volatility and regime conditions
volume and liquidity filters
optional benchmark confirmation
The strategy looks for breakout and continuation behavior when market conditions support trend movement. It is especially useful for traders who want a structured framework for momentum continuation setups while still having the ability to customize the chart presentation.
Key Features
9 EMA and VWAP overlays
Dynamic basis line with bullish, bearish, and neutral coloring
Breakout and continuation entry logic
Relative volume and dollar-volume liquidity filters
Optional market benchmark filter
Risk-based position sizing
Stop, target, and break-even trade overlays
Optional ATR-based trailing logic
Compact on-chart dashboard
Tiny buy/sell triangle signal markers
Fully customizable colors and visibility controls
Trade overlays shown only during active positions to reduce clutter
How To Use It
TrendPulse is best used as a structured intraday tool for identifying trend continuation conditions.
General long idea Look for:
bullish trend alignment
price holding above important structure
supportive VWAP positioning
improving momentum or continuation behavior
sufficient liquidity and relative volume
General short idea Look for:
bearish trend alignment
price staying below important structure
weak VWAP positioning
downside continuation behavior
sufficient liquidity and relative volume
Entry logic
Depending on the selected mode, the strategy can look for:
Breakout setups
Continuation setups
or Both
This lets traders adapt the script to different market conditions and personal preferences.
Risk management
The script can calculate:
entry
stop
target
optional break-even behavior
optional trailing behavior
The active trade lines are shown only while a trade is open, then removed automatically once the position closes so the chart stays clean.
Dashboard Guide
The TrendPulse dashboard is designed to help traders quickly assess market condition, directional quality, momentum participation, and whether price may already be extended.
State
Shows the current market regime: Trend, Expand, Quiet, or Noisy.
Trend suggests cleaner directional structure and better follow-through potential.
Expand suggests volatility is increasing, which can support strong momentum but also faster reversals.
Quiet suggests a slower or compressed market where breakouts may fail more often.
Noisy suggests mixed or unstable behavior with less reliable continuation.
How to use it: This is a context filter. Trend and Expand conditions are generally more favorable than Quiet or Noisy conditions for momentum-based setups.
L / S
Shows the current Long Score and Short Score.
A higher Long Score suggests stronger bullish alignment.
A higher Short Score suggests stronger bearish alignment.
If both are weak or close together, directional edge may be limited.
How to use it: Helps identify which side has better structure and quality. A clear score imbalance can support directional bias, while similar or weak scores may suggest patience.
Chop
Measures how choppy or directional recent price action has been.
Lower values generally suggest cleaner trend behavior.
Higher values usually suggest more back-and-forth movement.
How to use it: Lower Chop is generally more favorable for continuation-style setups. Higher Chop often means a greater chance of fakeouts, failed breakouts, or messy follow-through.
ATR Exp
Shows the ATR expansion ratio, which compares current volatility to its recent average.
Higher values suggest the market is becoming more active.
Lower values suggest a quieter or less energized environment.
How to use it: Helps gauge whether a move has enough energy behind it to continue. Rising ATR Exp can support momentum, but very high expansion can also mean the move is becoming aggressive and may be approaching exhaustion.
Trend
Shows the current directional bias: Bull, Bear, or Flat.
Bull favors long-side continuation thinking.
Bear favors short-side continuation thinking.
Flat suggests weaker directional edge.
How to use it: A quick directional filter to help traders stay aligned with broader short-term structure instead of trading against it.
% vs 9 EMA
Shows the percent distance of price from the 9 EMA.
Positive values mean price is above the 9 EMA.
Negative values mean price is below the 9 EMA.
How to use it: Helps judge short-term extension. The farther price moves from the 9 EMA, the more likely it may be becoming overextended or moving toward a capitulation/exhaustion phase. Smaller distances often reflect healthier continuation positioning, while larger distances can warn against chasing entries too late.
% vs VWAP
Shows the percent distance of price from VWAP.
Positive values mean price is above VWAP.
Negative values mean price is below VWAP.
How to use it: Helps judge how far price has moved from the session’s average traded value. A modest distance can support trend control, but a large distance may indicate emotional expansion, late-stage extension, or growing mean-reversion risk. If both the 9 EMA and VWAP distances are highly stretched in the same direction, the move may be strong but also increasingly vulnerable to pullback or exhaustion.
Vol
Shows relative volume compared with recent average volume.
Higher values suggest stronger participation.
Lower values suggest weaker participation.
How to use it: Stronger volume can support the credibility of a breakout or continuation move. Weak volume may mean the setup looks good visually but lacks enough participation to sustain follow-through.
Best practice
The dashboard works best when read as a group rather than field by field. For example, Trend or Expand state, strong directional score imbalance, lower Chop, healthy ATR expansion, and supportive volume can point to a cleaner continuation environment. On the other hand, high Chop, weak score separation, and very stretched distance from both the 9 EMA and VWAP may suggest caution, delayed entries, or increased exhaustion risk.
Customization
One of the main goals of TrendPulse is flexibility.
Users can customize:
visibility of moving averages, basis, channels, VWAP, and 9 EMA
signal marker colors
dashboard location, size, and theme
trade overlay colors
score label visibility and sizing
background regime highlights
This allows traders to simplify the chart or make it more information-rich depending on how they use it.
Best Instruments
TrendPulse is generally best suited for:
liquid stocks
active ETFs
high-volume intraday names
momentum-focused equities
It tends to be more useful on instruments where:
volume is meaningful
spreads are not excessive
VWAP and momentum behavior matter intraday
It may be less effective on:
illiquid symbols
very low-volume names
assets with inconsistent intraday movement
heavily erratic charts with poor liquidity
Best Timeframes
This strategy is primarily designed for intraday use.
Most suitable timeframes:
1 minute
3 minute
5 minute
15 minute
Some traders may also experiment with:
30 minute
As always, settings may need adjustment depending on the instrument and timeframe being traded.
Notes
This script is intended as a structured strategy and visualization tool.
Users should test settings across different symbols and timeframes.
No single parameter set is ideal for every market.
Traders may prefer different combinations of breakout, continuation, and filtering logic depending on their own process.
Disclaimer
For educational and research purposes only.
This script does not constitute financial advice.
Always forward test, validate settings, and manage risk appropriately before using any strategy in live markets.
If you find TrendPulse useful, consider saving it, sharing feedback, and adapting the visuals and filters to match your own trading workflow.
Stratégie

Quiet Period Box with Key Earnings LevelThe green box is the new programming for the "Quiet Period" to show when a company doesn't comment on anything about the prospects for the company which means that analysts can have an undue influence on the stock price during the quiet period.
Once the company reports earnings, a "Green Triangle" is created to include the day before and the day after the earnings announcement to then reveal the important price level, or "Key Level" which is the mid-point of this price action around the earnings release.
How to USE the indicator: The interesting part of this analysis is how these reference price levels have an influence in the future trading of shares. If a stock is in a bullish trend, the mid-point of the earnings release is the ideal, low-risk point to enter long with a stop 1, 2 or 3 ranges on the other side of the "Key Level" in case it doesn't work out. The target can be a variety of techniques from using the width of the "quiet period" range added to the "earnings level" to derive a price target.
The inverse would also be true. If the general trend of a stock was down, the mid-point of the 'earnings level' would provide supply and stop the price advance after a down move on earnings. You can see for yourself looking back over the history of the stock whether or not this method would be a profitable approach or not.
What I like is having the knowledge of where the important levels are on a stock chart so when the price gets there I can then decide whether or not to take a trade. You can set alerts on the "earnings level" and the highs and lows of the "quiet period" box to alert you to when a stock is worth looking at.
Over a year ago, I made the "Earnings Level" free to all users here at TradingView after keeping it a fee-based private indicator for close to 10 years. I feel a great debt of gratitude for TradingView for creating this wonderful platform for all of us to share ideas and I wanted everyone to have this powerful indicator to help investors and traders alike.
Now with this "Quiet Period" box publication, the patterns in the chaos of market action can be more easily found and you can be more at peace with the volatility in each stock when you can see the stock has been in a pre-defined time-zone for comparison.
Wishing you all the best of good fortune in your investing and trading and I look forward to hearing your questions.
A huge thank you goes to Ivan Labrie here at TradingView @IvanLabrie for writing the code for this indicator. He is a champion of technical analysis and the many methods of the Time@Mode, Key Earnings, Risk, Reward, Psychology, Trend and options strategies.
Indicateur

Multi-Timeframe Trend Matrix [JOAT]Multi-Timeframe Trend Matrix
Reads several timeframes with several methods at once and scores their agreement into a single alignment signal — without lookahead.
What it is
Trading a single timeframe blinds you to the larger context; watching many by eye is slow and inconsistent. This indicator evaluates a grid of timeframes and trend methods, turns the whole grid into one alignment score, and signals when top-down agreement forms. It is an original multi-timeframe aggregation tool built to avoid the common pitfalls of higher-timeframe requests.
How it works
• The matrix — a set of higher and lower timeframes is each assessed by several independent trend methods (such as a moving-average relationship, a directional trend measure and a momentum read). Each cell of the grid returns simply bullish or bearish, so the picture is easy to interpret.
• No lookahead — every higher-timeframe value is pulled with lookahead disabled, so the indicator never borrows future data from an unclosed higher-timeframe bar. This is a deliberate, disclosed design choice that keeps the signals honest and non-repainting on historical bars.
• Alignment score — the grid is condensed into one signed score representing how strongly all timeframes and methods agree. Full agreement produces a strong reading; a split grid produces a weak, near-neutral one.
• State-machine signals — a Buy fires when alignment turns sufficiently bullish from a non-bullish state; a Sell is the mirror. Requiring a state change means the matrix will not re-signal the same direction repeatedly — the signals are self-spacing.
Trade levels
Each signal draws a red risk box to the ATR stop and a green reward box to the third target, with inner dividers and right-edge labels for entry, stop and each take-profit at your R multiples.
The dashboard
An adjustable alignment-matrix panel displays every timeframe-by-method cell as bullish or bearish, a bipolar alignment-score headline, the active signal, a conviction estimate, and a live first-target-before-stop tally from closed bars only. The grid shows exactly which timeframes agree and which disagree.
How to use it
• Works on any asset; pick a base timeframe and let the grid supply the higher-timeframe context.
• Favour entries when the grid is broadly aligned; be cautious when it is mixed.
• Use it as a top-down filter alongside your own entry method, or take its aligned signals directly.
Settings
The set of timeframes, the methods and their lengths, the alignment threshold, ATR risk multiple and target R multiples, plus visual and dashboard controls.
Originality and usefulness
The contribution is the aggregation framework: a disciplined, lookahead-free multi-timeframe, multi-method grid condensed into one transparent alignment score with a state-machine trigger. Seeing the full grid — not just a final arrow — is what lets a trader trust or override the signal for themselves.
Notes and limitations
• Higher-timeframe values update only as those bars close, so alignment can shift when a higher-timeframe bar completes — this is expected and prevents lookahead bias.
• Strong alignment can still precede a reversal; agreement is context, not certainty.
• The tally reflects only past bars on the current chart and is not a forecast.
• Educational and analytical tool, not financial advice.
— made with passion by officialjackofalltrades
Indicateur

Indicateur

Indicateur

Indicateur

RTI Trend State + MacroCoverRTI Trend State + MacroCover
A trend-state oscillator built on the Relative Trend Index (RTI) — a stochastic-position measure of where price sits inside its recent high/low range, then EMA-smoothed:
raw = 100 * (close - lowest(low, n)) / (highest(high, n) - lowest(low, n))
RTI = EMA(raw, smooth) -> a 0-100 line
How the state works
The 0-100 RTI is converted into a persistent LONG / FLAT / SHORT state through a hysteresis band , so it does not flip on noise around the mid-line:
RTI above the upper band -> LONG
RTI below the lower band -> SHORT
in between -> holds the last state
The gap between the two bands is the hysteresis — widen it for fewer, steadier flips; narrow it for a more reactive read.
MacroCover (optional long bias)
When the state would be SHORT but price trades above a slow EMA (default 200), the short is covered to FLAT — i.e. it won't fight the higher-timeframe uptrend. Turn MacroCover off for a symmetric long/short reading.
On the chart
The RTI line (0-100) colored by state: green long, red short, gray flat.
Dashed upper/lower bands and a dotted mid-line.
State background tint and flip markers where the state changes.
A compact table with the current RTI value, state and macro side.
The RTI value plus state_-1_0_1 and ema_macro are available in the Data Window for tooltips and cross-checks.
Inputs
RTI engine — Lookback n (30), EMA smoothing (3), upper/lower bands (55 / 45).
MacroCover — on/off and macro EMA length (200).
Timeframe — use the chart timeframe, or lock the calculation to a fixed resolution.
Visual — toggle the state background, flip markers and table.
Notes
Works on any symbol and any timeframe.
Non-repainting : values are computed on confirmed bars, and the optional higher-timeframe request uses lookahead_off.
This is a discretionary / confluence tool, not financial advice or a complete trading system.
Indicateur

Breakout & Retest Entry Signals & the Break-vs-RetestOVERVIEW
"Wait for the retest" is the most repeated piece of advice in breakout trading. It is also, as far as I can tell, completely untested by the people who repeat it.
This tool settles it — on your instrument, with your settings — by taking BOTH entries on the SAME breaks and grading them against the same control:
PER-TRADE EDGE expectancy vs control · n
Break entry +0.09R +0.02R · n=412
Retest — CLEAN +0.31R +0.02R · n=118
Retest — DEEP -0.04R +0.02R · n=76
clean vs deep (t) 3.41 CLEAN IS BETTER
BUT — HOW OFTEN DO YOU GET IT?
Breaks that ever retested 47.0% (194/412)
after a run of >3 closes 31.2% vs 55.8% otherwise
False-break rate 13.3%
EXPECTED VALUE PER BREAK
Take every break +0.09R (100% of breaks)
Wait for the retest +0.06R (47% of breaks)
VERDICT NO DIFFERENCE — pick either
That last block is the entire point. A better per-trade edge is worthless if you only get the trade half the time — so the WAIT policy is scored as P(retest) x E , because on every break that never retests you get NOTHING. The two are then compared with a significance test, and the verdict is allowed to be "no difference".
It is a research and framing tool. NOT a strategy, NOT a signal service, NOT a validated edge.
WHAT IT ALREADY FOUND — measured live on NIFTY futures
timeframe breaks retested false breaks verdict
1m 334 49.4% 29.6% NO DIFFERENCE
3m 323 53.3% 13.6% NO DIFFERENCE
5m 328 53.4% 14.0% NO DIFFERENCE
15m 306 51.0% 12.7% TAKE THE BREAK
1h 274 50.0% 16.4% NO DIFFERENCE
TWO THINGS JUMP OUT.
The retest rate is 50-53% on every timeframe. Bulkowski, measuring throwbacks across 10,348 chart patterns on US daily stocks, found 50-60%. A completely different market, a completely different method, and the same number. That is a real phenomenon, not an artefact of the detector.
The false-break rate is 26.5% on the 1m and 13-15% everywhere else. THE ONE-MINUTE BREAK IS TWICE AS LIKELY TO BE A LIE. That is not folklore, it is this instrument's own number, and it is exactly the kind of thing a trader should know before choosing a timeframe.
And the verdict, on four of the five: NO DIFFERENCE — pick either. Once the geometry is honest and the test is a real one, the great break-versus-retest argument simply does not resolve on this instrument at most speeds. On the 15m it does resolve — and it says TAKE THE BREAK, which is the opposite of what almost everyone will tell you.
That is what a measurement looks like. It disagrees with the folklore on one timeframe, refuses to take a side on four others, and does not care what you were hoping for. No tool that needs to sell you a signal would ever print "NO DIFFERENCE".
THE ONE THING EVERYONE GETS BACKWARDS
Thomas Bulkowski measured throwbacks and pullbacks across 10,348 chart patterns. His finding:
"Do throwbacks hurt performance? YES: 97% of the time chart patterns with upward breakouts
perform better post-breakout WITHOUT a throwback."
"Do pullbacks hurt performance? YES: 91% of chart pattern types with downward breakouts
perform better if a pullback does NOT occur."
Read that again. The retest is not a gift. It is a SYMPTOM — evidence that the move is weak, that supply came back, that the break did not have the strength to run.
And yet "wait for the retest" is good advice for a completely different reason: it gives you a better price and a tighter stop.
BOTH ARE TRUE AT ONCE. They are two opposing effects on the same trade, and they have never been put on one scale and netted out. That is what this script does. The retest may still win — a better entry can outweigh a weaker move — but nobody has ever checked, and the answer is different on every instrument and every timeframe.
A CLEAN RETEST AND A DEEP ONE ARE NOT THE SAME EVENT
Bulkowski again, and this is his sharpest single finding on the subject: during a throwback, if price REMAINS ABOVE the breakout price the subsequent rise averages 40%. If it drops BELOW the breakout price and then recovers, the rise averages 29%. That is 400 samples versus 2,767.
Pooling those two throws away the strongest signal in the whole idea. So they are separated:
CLEAN retest — price came back and touched the level, but never CLOSED back through it.
DEEP retest — price CLOSED back through the level, then recovered.
They are graded separately, tested against each other, and labelled separately on the chart. If clean beats deep on your instrument, then "wait for the retest" is not one rule — it is two, and only one of them works.
AND CAN YOU SEE IT COMING?
The real, unpriced cost of a WAIT policy is that roughly half the time you never get filled. So it matters enormously whether you can predict which breaks will retest.
Bulkowski found that if price has more than three consecutively higher closes ending the day before the breakout, the throwback probability drops materially. So the panel reports the retest rate SPLIT BY THAT:
after a run of >3 closes 31.2% vs 55.8% otherwise
If the split is real on your instrument, then after a strong run into the break you should simply TAKE IT — because the retest you are waiting for is probably never coming.
IS YOUR VOLUME FILTER EARNING ITS KEEP?
Every trader is taught that a breakout must be confirmed by volume. Bulkowski's volume study says that after an ABOVE-average-volume breakout, FAILURES DOUBLE and the likelihood of a throwback TRIPLES, while the move itself is barely better.
That is testable — but only if the low-volume breaks are allowed into the sample. So VOLUME IS NOT A GATE ON THE RECORD. Every break is recorded; volume gates only the SIGNAL. The panel then reports what your filter is actually worth:
Break ON volume +0.11R n=246
Break OFF volume +0.06R n=166
on vs off (t) 0.82 no difference — it is doing nothing
The record is a fact about the market. The filter is a decision about the trade. They are kept apart, and this is what happens when you stop assuming and start measuring.
IDENTICAL GEOMETRY — and why this is not a detail
The target used to be THE NEXT OPPOSING LEVEL. That quietly destroyed the entire experiment.
The BREAK entry sits PAST the level (it closed through it). The RETEST entry sits BACK AT the level. So the retest is systematically FARTHER from the next opposing level, and was therefore being handed a BIGGER R:R for the SAME RISK — on every single trade, by construction. Live, that produced an R:R of 5.0 on one timeframe and 0.66 on another, and the on-chart key was cheerfully claiming "identical geometry" while the geometry was tilted toward the retest.
The trade now uses a FIXED R multiple, identical for the break, the retest and the control. The next opposing level is still drawn, and still tested — separately, as a descriptive statistic, with its hit rate reported next to its distance in R.
THE ANTI-BIAS GUARDS
ENTRY IS THE CLOSE, for both entries and for the control. Entering the retest AT the level — a better price than the close — while the break enters at its close would hand the retest a free head start on every trade, and settle the oldest argument in trading by rigging it.
THE CONTROL IS DIRECTION-MATCHED. Breaks run with the trend, so a direction-skewed event set measured against a symmetric 50/50 control inherits the drift for free and calls it an edge. Longs are compared only with control longs, shorts only with control shorts, and the control is blended back using the events' OWN direction mix.
EVERY VERDICT IS A TEST, NOT A COMPARISON. Break-vs-wait, clean-vs-deep, volume-on-vs-off — each is a Welch t-test that has to clear |t| > 1.96 before it is allowed to be a finding. For the wait policy, the variance of P(retest) x E is propagated by the delta method, because it is a product of two estimates and both carry error. A verdict that flips on a tenth of an R is not a verdict, it is noise wearing a costume.
Both barriers on one bar: the STOP is assumed first — conservative, and the only assumption that cannot flatter the result. Unresolved trades at the horizon are marked to market, not booked as losses.
THE LEVELS
Levels come from the extrema of a KERNEL-SMOOTHED price series (Nadaraya-Watson) rather than raw pivots, so they track the structure rather than the noise. A break requires a CLOSE beyond the level with displacement, not a wick. A false break is one that closes back inside quickly. All of it is computed on confirmed bars; the kernel is causal and never looks forward.
NON-REPAINT
The kernel confirms an extremum a half-window late, so a level appears some bars AFTER the swing that created it. That lag is the price of not repainting and it is paid deliberately. Levels, breaks, false breaks, retests, signals and every calibration event are computed on CONFIRMED bars only. Nothing is drawn and then moved.
DATA AND SCOPE
Any symbol, any timeframe. ATR-normalised throughout. Volume improves the SIGNAL but is not required, and it never gates the RECORD.
EXPORTS (Data Window — consume from other scripts via input.source())
EXP_Level, EXP_Break, EXP_FalseBreak, EXP_Retest, EXP_Entry, EXP_Stop, EXP_Target, EXP_NextLevel, EXP_WaitEdge
CONCEPT CREDIT
Support/resistance, polarity and the breakout-retest idea are long-standing public trading concepts with no single author; the written tradition runs through Charles Dow, Richard Wyckoff and Edwards & Magee. The formal TRADING-RANGE BREAK was first tested at scale by William Brock, Josef Lakonishok and Blake LeBaron, Journal of Finance 47(5), 1992 — and their results were later shown to be vulnerable to data-snooping (Sullivan, Timmermann and White, 1999), which is exactly why this tool measures the rule on YOUR instrument rather than asserting it.
The throwback and pullback statistics that motivate the clean/deep split, the run-length predictor and the volume test are from Thomas Bulkowski ("Encyclopedia of Chart Patterns"; thepatternsite.com). His numbers are measured on US daily stocks. Whether they hold on YOUR instrument is precisely the question this script exists to answer — and it may well answer "no".
Nadaraya-Watson kernel regression — Nadaraya and Watson (1964); its use for technical pattern recognition — Lo, Mamaysky and Wang, Journal of Finance 55(4), 2000. Triple-barrier forward labelling — Marcos Lopez de Prado. Welch's t-test — B. L. Welch. ATR — J. Welles Wilder.
The break-vs-wait availability weighting, the delta-method significance test, the clean/deep retest split, the volume-filter test and the direction-matched control are the author's own. Clean-room implementation; no third-party Pine code is reused. Not affiliated with, nor endorsed by, any of the above.
HONESTY AND LIMITATIONS
Calibration is IN-SAMPLE, with no costs or slippage, and uses overlapping windows. A proven in-sample edge is NOT a guarantee out-of-sample. Real fills, spreads and commissions will reduce it — and they will hurt the break entry more than the retest entry, because the break enters into momentum.
Bulkowski's throwback statistics are measured on US daily stocks over decades. They are the reason the questions are asked. They are NOT the answer, and this tool will tell you so if your instrument disagrees.
The verdict is allowed to be "NO DIFFERENCE — pick either", and on many instruments it will be. That is a real result. A tool that cannot report its own failure is an advertisement, not a measurement.
Nothing in this script predicts price.
DISCLAIMER
Research and educational tool only. NOT financial advice, NOT a recommendation, and NO guarantee of results. Entry, stop and target output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use.
Indicateur

Anchored VWAP Hand-Off 2.03Anchored VWAP Hand-Off 2.03 is a multi-leg cascading VWAP indicator. It starts with a classic Anchored VWAP from a user-selected date (Leg 1), then automatically creates new "hand-off" VWAP legs (up to 24) every time price crosses the previous VWAP. Each new leg resets its calculation from the bar of the cross, creating a dynamic chain of VWAPs that follow price action.
Key Features:
Source: Typically close (customizable).
Trigger: EMA(1) of the source (essentially price itself).
Color Logic: Each VWAP leg changes color based on whether price is above (bullish) or below (bearish) it. Supports unified color mode.
Up to 24 cascading legs (user controls how many are shown).
Visual anchor line at the start date.
Main Use Cases:
Dynamic Support & Resistance
The multiple VWAP legs act as adaptive moving support/resistance zones. Traders watch for bounces off these lines or breaks through several legs at once.
Trend Strength & Momentum
Strong trends often break multiple hand-off legs quickly.
Choppy/consolidating markets produce many frequent hand-offs (more lines clustering).
Mean Reversion Setups
Price tends to return to the nearest active VWAP legs. Useful for fade-the-extreme strategies.
Breakout / Breakdown Confirmation
When price decisively breaks through several VWAP legs in sequence, it often signals a high-probability directional move.
Intraday & Swing Trading
Particularly popular on stocks, futures, and crypto for finding "fair value" shifts after news events or strong moves. The hand-off mechanism makes it more responsive than a single static anchored VWAP.
Visual Market Structure
Helps traders see how "value" is migrating over time as new legs form.
Best Timeframes: Works on all, but especially useful on 5min to daily charts.Pro Tip: Start with 8–12 legs. Too many legs can make the chart noisy. Use the anchor date on significant events (earnings, breakout days, macro events, etc.).This indicator is an evolution of standard Anchored VWAP, designed to solve the problem of a single anchored VWAP becoming stale after big moves.
Indicateur

Indicateur

Machine Learning Price Bands Kernel Regression SignalsOVERVIEW
Every "AI band" on this platform draws two lines and asserts them. None of them can tell you how often price actually stays inside.
This one can — because it is built on a method that comes with a MATHEMATICAL COVERAGE GUARANTEE, and then it CHECKS WHETHER IT KEPT THE PROMISE, live, on your chart:
Coverage (empirical vs nominal) 89.1% vs 90% n = 20,266
Is the miss REAL? -0.9 pp z = -4.3 (real)
Verdict undercovering — real, but small
That is not a band. That is a prediction interval that has been audited, and it is the whole reason this tool exists.
It is a research and framing tool. NOT a strategy, NOT a signal service, NOT a validated edge.
THE MACHINE LEARNING, SPELLED OUT — no buzzwords, here is the actual model
1. NADARAYA-WATSON KERNEL REGRESSION. Non-parametric: no functional form is assumed, the data chooses the shape. Each past bar votes on the current estimate with a Gaussian weight that decays with distance. This is the same estimator Lo, Mamaysky and Wang used in the Journal of Finance to make chart-pattern recognition objective. It is real machine learning, and it is sixty years old.
The kernel here is CAUSAL. It only ever looks backwards. A centred kernel — the kind most "Nadaraya-Watson envelope" scripts use — peeks at bars that have not happened yet, and that is why their historical fit looks so much better than their live one.
2. BANDWIDTH BY PREDICTIVE MODEL SELECTION. The bandwidth h is the only real parameter, and it is not a magic number: several candidates are run in parallel and scored on their ROLLING ONE-STEP-AHEAD SQUARED ERROR. The winner is used. That is honest model selection — the criterion you would use to choose any forecaster — rather than a knob you turn until the chart looks nice.
3. CONFORMAL PREDICTION INTERVALS. The half-width is the (1-alpha) empirical quantile of the recent ABSOLUTE one-step-ahead errors. Under exchangeability this carries a FINITE-SAMPLE coverage guarantee, with NO distributional assumption at all: no normality, no GARCH, no volatility model. The model's own recent mistakes size the band — which is why it widens when the model starts being WRONG, not merely when price starts moving.
4. ADAPTIVE CONFORMAL INFERENCE — Gibbs and Candes, NeurIPS 2021.
Here is the problem with plain conformal prediction on markets, stated plainly: its guarantee holds under EXCHANGEABILITY, and financial returns are the textbook counterexample. Volatility CLUSTERS. So a residual quantile computed over a trailing window is always a step behind, the band is too narrow exactly when it matters, and the misses bunch together. Coverage lands quietly under nominal. Measured live on NIFTY futures before this was added: 89.1% against a nominal 90%, on the 1m, the 3m and the 1h, every one of them roughly four standard errors below target. Not a bug. The assumption breaking.
ACI makes the miscoverage level a LEARNED parameter:
alpha(t+1) = alpha(t) + gamma * (alpha - err(t))
Miss the interval and alpha falls, so the quantile rises and the band WIDENS. Cover it and alpha creeps back, so the band TIGHTENS. Long-run coverage provably converges to the target IRRESPECTIVE OF THE DATA GENERATING PROCESS — no exchangeability assumption anywhere.
A band that notices it is undercovering and fixes itself. Watch the alpha row: where it settles BELOW nominal is a direct measurement of how badly exchangeability fails on your instrument.
MEASURED, ON THE SAME INSTRUMENT, BEFORE AND AFTER:
timeframe plain conformal with ACI
1m 89.1% 90.1%
3m 89.1% 90.1%
5m 89.1% 90.1%
15m 90.1% 90.1%
1h 89.1% 90.1%
(nominal 90%)
Five timeframes, a four-standard-error undercoverage on four of them, closed. The binomial test now returns "calibrated — within sampling noise" and means it. That is not a backtest of a trading rule. That is a mathematical promise being kept, and being checked.
5. NORMALISED NONCONFORMITY — Papadopoulos et al. (2008), Lei et al. (2018).
The plain score |price - fit| is a SCALAR, which means the band is THE SAME WIDTH in a dead tape and in a crash. It therefore OVERCOVERS in calm and UNDERCOVERS in chaos — and the single marginal coverage figure is the average of those two errors, looking correct while being wrong in both directions.
Normalising divides each residual by a local scale estimate before taking the quantile, and multiplies it back when drawing:
score = |price - fit| / sigma band = fit +/- q * sigma
The band now scales with LOCAL DIFFICULTY — and note it is the MODEL'S difficulty, not the market's volatility. Related, but not the same thing, and the first one is what a prediction interval is actually about.
6. THE COVERAGE AUDIT. A guarantee you do not verify is just a claim.
TWO QUESTIONS ABOUT THE COVERAGE, AND THE PANEL ANSWERS BOTH
IS THE MISS REAL? That is a binomial z-test and it needs no tolerance at all. Each bar is a Bernoulli trial with p = nominal, so the standard error of the observed coverage is sqrt(p(1-p)/n).
IS THE MISS BIG ENOUGH TO CARE ABOUT? That is a judgement, and you set it.
These are NOT the same question, and conflating them is how a band gets waved through as "calibrated". Measured live on NIFTY futures: at n = 20,266 the standard error is 0.21 pp, so an empirical coverage of 89.1% against a nominal 90% is a 0.9 pp miss — FOUR STANDARD ERRORS. Unmistakably real. Arguably too small to trade differently. A 5 pp tolerance called that "calibrated", which was the headline row of the script asserting the one thing the script exists to verify, and asserting it wrongly.
The panel now reports the size of the miss, its significance, and a verdict that distinguishes "within sampling noise" from "real, but small" from "MISCALIBRATED — do not trust the band". You get to decide which of those matters to you, and you get the numbers to decide with.
AND THEN THE ROW NOBODY HAS: CONDITIONAL COVERAGE
Coverage 90.0% vs 90% n = 20,178
calm / normal / turbulent 96.4% · 90.1% · 83.2%
A single marginal number can read a perfect 90% while the interval covers 96% of quiet bars and 83% of violent ones. Ninety per cent is then the AVERAGE OF TWO ERRORS — it looks right while being wrong in both directions, and it is wrong in the direction that costs you money exactly when it costs you money.
Exact conditional coverage is provably impossible without strong assumptions. But you can always MEASURE it, and almost nobody does. Bars are split into calm, normal and turbulent thirds by the percentile rank of ATR, and coverage is scored inside each. If the three numbers fan apart, the band is not breathing — and the normalised score is what closes the gap.
Turn the normalised score off and watch those three fan out. That is the demonstration.
FADE OR FOLLOW? THE TOOL DOES NOT PRETEND TO KNOW
Price leaving a 90% interval is statistically unusual. Whether to FADE it (an outlier, so bet on reversion) or FOLLOW it (the model has broken, so bet on the new regime) is an EMPIRICAL question, and the honest answer is often neither.
So both are logged, both are graded, and BOTH ARE TESTED AGAINST EACH OTHER.
That last part matters more than it sounds. Knowing that fading beats an unconditional control, and that following also beats an unconditional control, does not answer the question a trader is actually asking at a band break — which of the two should I do? They are mutually exclusive responses to the SAME event. So they are run head to head with a Welch t-test, and the answer is allowed to be:
FADE or FOLLOW? NEITHER — the break does not tell you which
If the difference does not clear the noise, then on this instrument the break carries no directional information, and saying so IS the finding. A tool that cannot report its own failure is an advertisement, not a measurement.
And the chart agrees with the panel. An unproven direction is still drawn — it is arithmetic, and you may want it — but it is drawn MUTED and labelled "(not proven)". It used to print "Follow the break" in full colour while the panel directly beneath it said "neither proven". The paint has to agree with the code.
THE ANTI-BIAS GUARDS
ENTRY IS THE CLOSE, for the event and for the control alike. A band break is a SIGNAL, not a fill. Entering at the band — a better price — while the control enters at the close hands every signal a free head start and manufactures an edge out of nothing.
THE CONTROL IS DIRECTION-MATCHED. In a downtrend there are more break-downs than break-ups, so FOLLOW skews short and FADE skews long. A direction-skewed event set measured against a 50/50 control inherits the index drift for free and calls it an edge. Longs are compared only with control longs, shorts only with control shorts, and the control is blended back using the events' OWN direction mix.
IDENTICAL GEOMETRY. Every event and every control trade uses the same stop and the same R multiple, so the comparison is apples to apples.
Both barriers on one bar: the STOP is assumed first — conservative, and the only assumption that cannot flatter the result. Unresolved trades at the horizon are marked to market, not booked as losses. Nothing is marked proven below t = 1.96.
NON-REPAINT
The kernel is causal, the bandwidth is chosen on past error only, the interval is built from past residuals, and coverage is scored by asking whether the actual close landed inside the interval that was published BEFORE it. Everything is computed on confirmed bars. Nothing is drawn and then moved.
WHY THESE PARTS ARE ONE TOOL
The regression gives the trend. Without the interval, a band is a guess. Without model selection, the bandwidth is a knob you turn until you like the picture. Without the coverage audit, a conformal interval is an unverified promise. And without the signal calibration, "price left the band" is folklore. Each piece is worthless alone — which is exactly why they ship together.
DATA AND SCOPE
Any symbol, any timeframe. ATR-normalised throughout. No volume required.
EXPORTS (Data Window — consume from other scripts via input.source())
EXP_Fit, EXP_Upper, EXP_Lower, EXP_Bandwidth, EXP_Coverage, EXP_Miscal, EXP_Signal, EXP_Entry, EXP_Stop, EXP_Target
CONCEPT CREDIT
Nadaraya-Watson kernel regression — E. A. Nadaraya and G. S. Watson (1964). Its use for technical pattern recognition in finance — Andrew W. Lo, Harry Mamaysky and Jiang Wang, "Foundations of Technical Analysis", Journal of Finance 55(4), 2000. Conformal prediction — Vladimir Vovk, Alexander Gammerman and Glenn Shafer; the split/inductive form used here follows Papadopoulos et al. and Lei et al. Triple-barrier forward labelling — Marcos Lopez de Prado. Welch's t-test — B. L. Welch. ATR — J. Welles Wilder.
The causal-kernel implementation, the parallel bandwidth selection, the live coverage audit, the binomial calibration test and the fade-versus-follow head-to-head are the author's own. Clean-room implementation; no third-party Pine code is reused. Not affiliated with, nor endorsed by, any of the above.
HONESTY AND LIMITATIONS
Conformal coverage is guaranteed under EXCHANGEABILITY. Financial returns are NOT exchangeable — volatility clusters, regimes shift — so the guarantee is approximate in practice. THAT IS PRECISELY WHY THE COVERAGE IS AUDITED LIVE INSTEAD OF ASSUMED. When empirical coverage drifts from nominal you are watching the assumption break, in real time, and you should believe what you see rather than the label.
A prediction interval says where price is LIKELY TO BE. It says nothing about DIRECTION, and it is not a forecast. Coverage being correct does not make band breaks tradeable — those are two different claims, and the tool tests them separately for exactly that reason.
Calibration figures are IN-SAMPLE, with no costs or slippage, and use overlapping windows. A proven in-sample edge is NOT a guarantee out-of-sample. Nothing here predicts price.
DISCLAIMER
Research and educational tool only. NOT financial advice, NOT a recommendation, and NO guarantee of results. Entry, stop and target output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use. Indicateur

RSL Wert (Levy)Although Robert Levy originally designed the indicator purely as a trend-following tool (true to the motto: "Buy the strongest and stick to assets with an RSL greater than 1.0"), mathematically it measures exactly what you described: the percentage deviation of the current price from its moving average (MA 130).If you use the RSL as an overbought indicator (an oscillator for extreme zones), you should pay attention to two main things:1. Historical Context of the Individual AssetAn RSL of, for example, $1.25$ means that the price is trading 25% above its 130-day moving average.For a sluggish blue-chip stock, this can already represent extreme overheating, which historically has almost always led to a correction (mean reversion).For a highly volatile tech stock or crypto asset in a massive trend phase, an RSL of $1.25$ might be completely normal, with actual overheating only setting in at $1.40$ or higher.2. Interplay with the Trend DirectionIn a bull market: A high RSL does signal overheating, but it is often a sign of extreme momentum. Here, "overheating" frequently leads to a sideways consolidation where the moving average catches up, rather than a sharp crash.At a trend reversal: If the RSL spikes to historical extremes during an already mature trend phase and then abruptly loses momentum, it serves as a classic warning sign to take profits.Rule of thumb: The further the price stretches away from the MA 130 like a rubber band (resulting in a high RSL), the greater the short-term risk of a pullback to the average.
Robert Levy hat den Indikator zwar ursprünglich als reines Trendfolgewerkzeug konzipiert (frei nach dem Motto: „Kaufe das Stärkste und halte dich an Werte mit einer RSL größer als 1,0“), aber mathematisch misst er genau das, was du beschreibst: die prozentuale Abweichung des aktuellen Kurses von seinem gleitenden Durchschnitt (GD 130).
Wenn man den RSL als Überhitzungs-Indikator (Oszillator für Extremzonen) nutzt, sollte man auf zwei Dinge achten:1.
Historischer Kontext des einzelnen WertesEin RSL von z. B. 1,25 bedeutet, dass der Kurs 25% über seinem 130-Tage-Durchschnitt notiert.Für eine träge Standardaktie kann das bereits eine extreme Überhitzung sein, die historisch fast immer zu einer Korrektur (Mean Reversion) geführt hat.
Für einen hochvolatilen Tech-Wert oder Krypto-Asset in einer massiven Trendphase kann ein RSL von 1,25 dagegen völlig normal sein, bevor die eigentliche Überhitzung erst bei 1,40 oder höher ansetzt.2.
Das Zusammenspiel mit der TrendrichtungIm Bullenmarkt: Ein hoher RSL zeigt zwar Überhitzung an, ist aber oft ein Zeichen von extremer Dynamik (Momentum). Hier führt die „Überhitzung“ häufig eher zu einer Seitwärtskonsolidierung, bei der der Durchschnitt nachzieht, anstatt zu einem scharfen Crash.Bei der Trendwende: Schießt der RSL in einer ohnehin schon reifen Trendphase auf historische Extremwerte und verliert dann schlagartig an Dynamik, ist das ein klassisches Warnsignal für Gewinnmitnahmen.Als Daumenregel lässt sich festhalten: Je weiter sich der Kurs elastisch wie ein Gummiband vom GD 130 nach oben entfernt (hoher RSL), desto größer wird kurzfristig das Risiko eines Rücksetzers zum Durchschnitt. Indicateur

RSL Wert (Levy)Robert Levy hat den Indikator zwar ursprünglich als reines Trendfolgewerkzeug konzipiert (frei nach dem Motto: „Kaufe das Stärkste und halte dich an Werte mit einer RSL größer als 1,0“), aber mathematisch misst er genau das, was du beschreibst: die prozentuale Abweichung des aktuellen Kurses von seinem gleitenden Durchschnitt (GD 130).
Wenn man den RSL als Überhitzungs-Indikator (Oszillator für Extremzonen) nutzt, sollte man auf zwei Dinge achten:1.
Historischer Kontext des einzelnen WertesEin RSL von z. B. 1,25 bedeutet, dass der Kurs 25% über seinem 130-Tage-Durchschnitt notiert.Für eine träge Standardaktie kann das bereits eine extreme Überhitzung sein, die historisch fast immer zu einer Korrektur (Mean Reversion) geführt hat.
Für einen hochvolatilen Tech-Wert oder Krypto-Asset in einer massiven Trendphase kann ein RSL von 1,25 dagegen völlig normal sein, bevor die eigentliche Überhitzung erst bei 1,40 oder höher ansetzt.2.
Das Zusammenspiel mit der TrendrichtungIm Bullenmarkt: Ein hoher RSL zeigt zwar Überhitzung an, ist aber oft ein Zeichen von extremer Dynamik (Momentum). Hier führt die „Überhitzung“ häufig eher zu einer Seitwärtskonsolidierung, bei der der Durchschnitt nachzieht, anstatt zu einem scharfen Crash.Bei der Trendwende: Schießt der RSL in einer ohnehin schon reifen Trendphase auf historische Extremwerte und verliert dann schlagartig an Dynamik, ist das ein klassisches Warnsignal für Gewinnmitnahmen.Als Daumenregel lässt sich festhalten: Je weiter sich der Kurs elastisch wie ein Gummiband vom GD 130 nach oben entfernt (hoher RSL), desto größer wird kurzfristig das Risiko eines Rücksetzers zum Durchschnitt.
Although Robert Levy originally designed the indicator purely as a trend-following tool (true to the motto: "Buy the strongest and stick to assets with an RSL greater than 1.0"), mathematically it measures exactly what you described: the percentage deviation of the current price from its moving average (MA 130).If you use the RSL as an overbought indicator (an oscillator for extreme zones), you should pay attention to two main things:1. Historical Context of the Individual AssetAn RSL of, for example, $1.25$ means that the price is trading 25% above its 130-day moving average.For a sluggish blue-chip stock, this can already represent extreme overheating, which historically has almost always led to a correction (mean reversion).For a highly volatile tech stock or crypto asset in a massive trend phase, an RSL of $1.25$ might be completely normal, with actual overheating only setting in at $1.40$ or higher.2. Interplay with the Trend DirectionIn a bull market: A high RSL does signal overheating, but it is often a sign of extreme momentum. Here, "overheating" frequently leads to a sideways consolidation where the moving average catches up, rather than a sharp crash.At a trend reversal: If the RSL spikes to historical extremes during an already mature trend phase and then abruptly loses momentum, it serves as a classic warning sign to take profits.Rule of thumb: The further the price stretches away from the MA 130 like a rubber band (resulting in a high RSL), the greater the short-term risk of a pullback to the average. Indicateur
