Indicador

AxMan Exhaustion Detection Reversal Rider1. The "Exhaustion" Phase (The Warning)
The strategy first looks for a Yellow or Orange Diamond. This isn't a signal to buy yet; it’s a warning that the current trend is dying.
The Logic: It looks for a massive spike in volume combined with an "over-extended" RSI.
The Visual: Imagine a car slamming on its brakes at high speed. The tires smoke (Volume Spike), and the car skids (RSI Oversold).
The Filter: This prevents you from entering a trade when the market is "boring" or slowly drifting. You only care about the moments of peak panic or peak euphoria.
2. The "Locked & Loaded" Window (The 12-Candle Rule)
Once that "Exhaustion" diamond appears, the chart background changes color. The strategy is now hunting for a trade.
The Logic: It gives the market exactly 12 candles to prove it can reverse.
Why 12? If the market doesn't reverse within 12 candles, the "exhaustion" was just a pause, and the old trend is likely to continue. This rule keeps you out of "dead zones" where the price just goes sideways.
3. The "Trigger" (The Fast Entry)
This is where the strategy beats traditional indicators. It doesn't wait for a fancy moving average crossover.
The Logic: As soon as a candle closes above the high of the previous candle (for a Long) or below the low (for a Short), it enters.
The Goal: It gets you in at the absolute "bend" of the trend. By the time most traders see a trend change, this strategy is already in profit.
4. The "Ride" (The Exit)
This strategy is not about "scalping" small profits. It is designed to stay in the trade as long as the trend is healthy.
The Exit Rule: It only closes the trade if:
Opposite Exhaustion: It sees the same "panic" signal happening on the other side (The Target).
Trend Break: The price closes on the wrong side of the 50 EMA (The Safety Net).
The Result: This allows you to "Ride the Wave" during massive moon-shots or market crashes, often staying in a single trade for days on the 4H chart.
Why It’s "Adaptive"
Because it uses standard deviations for volume and previous candle breaks for entry, it behaves correctly whether you are looking at a 15-minute chart (fast day trading) or a Daily chart (long-term investing). It scales its "expectations" based on the timeframe you choose.
Summary in one sentence: "We wait for the sellers to get exhausted, wait for the buyers to step in and break one high, and then we hold until the buyers get tired too." Estrategia

Malaysian SnR Levels [UAlgo]Malaysian SnR Levels is a structure based support and resistance overlay that automatically plots three level types on the chart:
A-Levels, which act as resistance
V-Levels, which act as support
Gap Levels, which mark qualifying candle to candle price gaps
The script is built for traders who want clean horizontal reference levels that stay active until price decisively crosses through them. Instead of drawing every pivot forever, the indicator manages each level as a stateful object with freshness and activity tracking. A newly created level begins as fresh , becomes unfresh after its first wick interaction, and remains active until price fully crosses through it. Once broken, the level stops extending and is archived on the chart.
A major strength of this implementation is its optional multi timeframe workflow. You can leave the timeframe input empty to detect levels on the current chart, or select a higher timeframe to project higher timeframe A, V, and Gap levels onto a lower timeframe execution chart. This makes the script useful for both local chart structure and top down level mapping.
The result is a practical support and resistance engine focused on:
Pivot based resistance and support
Gap based structural levels
Fresh versus unfresh state tracking
Automatic break detection
Optional MTF level projection
🔹 Features
🔸 1) Automatic A-Levels and V-Levels
The script detects pivot highs and pivot lows and converts them into horizontal support and resistance levels:
A-Levels come from confirmed pivot highs and behave as resistance
V-Levels come from confirmed pivot lows and behave as support
These are built from pivot calculations on close , not on raw high and low extremes, which gives the levels a close based structural character.
🔸 2) Automatic Gap Levels
In addition to pivots, the script detects directional gap style levels when two consecutive candles move in the same direction and the open to prior close gap exceeds a minimum tick distance.
Bullish gap logic creates a gap level at the previous close.
Bearish gap logic also creates a gap level at the previous close.
This gives the indicator a third structural layer beyond classic pivot based support and resistance.
🔸 3) Fresh and Unfresh State Tracking
Every new level starts as fresh . A fresh level is considered untouched. Once price interacts with the level by wick, it becomes unfresh :
The line style changes to dashed
The width becomes thinner
The color shifts to the unfresh color theme
This helps traders quickly distinguish untouched levels from levels that have already been tested.
🔸 4) Active Until Full Break
A level stays active until price crosses through it. Once broken, the level:
Stops extending
Fixes its endpoint at the break time
Keeps the historical line visible
Stops updating as an active level
This is useful because old levels remain visible for review, while current active levels continue projecting forward.
🔸 5) Multi Timeframe Detection (Optional)
The script supports a selectable detection timeframe:
Leave it empty to use the current chart timeframe
Set it to a higher timeframe to project higher timeframe levels onto the current chart
This is especially useful when traders want to execute on a lower timeframe while respecting higher timeframe structure.
🔸 6) Minimum Gap Filter in Ticks
Gap levels are filtered by a configurable minimum distance in ticks. This avoids plotting tiny micro gaps and helps keep only more meaningful dislocations.
🔸 7) Duplicate Level Protection
Before adding a new level, the script checks whether an active level already exists near the same price. If another active level is within a small tick range, the new one is skipped.
This reduces clutter and prevents nearly identical levels from stacking on top of each other.
🔸 8) Separate Visibility Controls
Users can independently choose whether to display:
A-Levels
V-Levels
Gap Levels
This makes the tool adaptable for different workflows, such as only plotting pivot levels or only monitoring gap structure.
🔸 9) Full Visual Customization
The script provides separate color controls for:
Fresh A-Levels
Unfresh A-Levels
Fresh V-Levels
Unfresh V-Levels
Fresh Gap Levels
Unfresh Gap Levels
It also allows customization of:
Fresh line width
Unfresh line width
Label size
This makes it easy to fit the indicator into different chart styles.
🔸 10) Label Projection to the Right
Each active level includes a compact label showing its type:
A
V
Gap
The label is automatically pushed several time steps to the right of current price so it stays readable and aligned with the level.
🔸 11) Automatic Level Count Management
The script keeps the number of stored levels under control using a maximum active limit. When capacity is exceeded, it tries to remove an older inactive level first.
This helps maintain chart cleanliness and stay within TradingView object limits.
🔹 Calculations
1) Pivot Based A-Level and V-Level Detection
The script calculates pivots using close, not high or low:
float ph = ta.pivothigh(close, pivotLength, pivotLength)
float pl = ta.pivotlow(close, pivotLength, pivotLength)
Interpretation:
A-Level = confirmed close based pivot high
V-Level = confirmed close based pivot low
Because pivot confirmation requires bars on both sides, the level time is aligned to the true pivot bar using:
int ph_t = not na(ph) ? time : na
int pl_t = not na(pl) ? time : na
2) Gap Level Detection Logic
The script defines bullish and bearish gap conditions using consecutive candles in the same direction plus a minimum gap size measured in ticks.
Bullish gap:
bool bullishGap = prevBullish and isBullish and (open - close ) >= syminfo.mintick * minGapTicks
Bearish gap:
bool bearishGap = prevBearish and isBearish and (close - open) >= syminfo.mintick * minGapTicks
If either condition is true, the gap level is set at:
gap_price := close
So the reference price for the gap level is the previous candle’s close.
3) Multi Timeframe Data Selection
The script computes levels in a helper function and can either use:
Local chart data directly
Or higher timeframe data through request.security
= request.security(...)
If the timeframe input is empty, local values are used. Otherwise, the security values are used:
float ph = tf == "" ? loc_ph : sec_ph
This gives flexible MTF projection while keeping one consistent logic engine.
4) New Level Event Detection
To prevent the same pivot or gap from being added multiple times, the script checks whether the timestamp of the detected event changed:
bool new_ph = not na(ph_t) and ph_t != nz(ph_t )
bool new_pl = not na(pl_t) and pl_t != nz(pl_t )
bool new_gap = not na(gap_t) and gap_t != nz(gap_t )
This is an important implementation detail because it avoids a common Pine issue where na != na can propagate as na and block reliable detection.
5) Level Creation and Duplicate Protection
Before a new level is added, the script checks existing active levels and rejects duplicates that are too close:
if lvl.isActive and math.abs(lvl.price - p) < syminfo.mintick * 10
exists := true
This means levels within 10 ticks of an existing active level are treated as duplicates and not added.
6) Level Initialization
When a level is created, it starts as:
Fresh = true
Active = true
A line is drawn from the source time and extended to the right:
line.new(st, p, st + timeStep, p, xloc=xloc.bar_time, color=c, width=lineWidthFresh, extend=extend.right)
A label is also created and placed several time steps to the right:
label.new(cur_time + timeStep * 5, p, t, ...)
This keeps the label visually separated from the current candle.
7) Fresh to Unfresh Transition Logic
A level becomes unfresh when price first touches it by wick while the level is still active.
For A-Levels:
touchedWick := h >= this.price
For V-Levels:
touchedWick := l <= this.price
For Gap levels:
touchedWick := h >= this.price and l <= this.price
Once touched:
The level remains active
isFresh becomes false
The line becomes dashed
The width changes to the unfresh width
The line and label colors switch to the unfresh palette
This means a wick touch weakens the level visually, but does not break it.
8) Break / Deactivation Logic
A level becomes inactive only when price crosses through it, not merely when it is touched.
Cross up condition:
bool crossedUp = (o <= this.price and c > this.price) or (c_prev < this.price and c > this.price)
Cross down condition:
bool crossedDown = (o >= this.price and c < this.price) or (c_prev > this.price and c < this.price)
If either is true:
this.isActive := false
this.lvlLine.set_x2(curTime)
this.lvlLine.set_extend(extend.none)
this.lvlLabel.set_x(curTime)
Interpretation:
The level stops projecting and is fixed at the break time.
9) Time Step Handling
The script uses the current bar’s time distance to position and extend labels:
int timeStep = bar_index > 0 ? time - time : 60000
This is important because the script uses xloc.bar_time , so horizontal positioning is time based rather than bar index based.
10) Maximum Level Management
When the array exceeds the user defined maximum, the script tries to remove an inactive level first:
if this.size() > maxLevels
int removeIdx = 0
for i = 0 to this.size() - 1
SnRLevel lvl = this.get(i)
if not lvl.isActive
removeIdx := i
break
Then it deletes that level’s line and label.
Important implementation note:
If no inactive level is found, removeIdx remains 0, so the oldest level in the array is removed.
11) A-Level, V-Level, and Gap Interpretation
In this script:
A-Levels are close based pivot highs and function like resistance
V-Levels are close based pivot lows and function like support
Gap Levels are prior close reference levels from qualifying directional gaps
All three share the same lifecycle framework:
Fresh
Unfresh after wick touch
Inactive after a full cross through Indicador

KDE Reversals [UAlgo]KDE Reversals is a statistical reversal oscillator that measures where the current price sits inside its recent distribution using a Kernel Density Estimation based cumulative probability model. Instead of relying on fixed momentum formulas or classic overbought and oversold oscillators, the script builds a rolling sample of recent source values, estimates a smoothed empirical distribution, and converts the current value into a percentile style reading from 0 to 100.
The result is a non parametric probability oscillator that answers a simple question: how extreme is the current price relative to the recent sample? Very high readings mean the current value is located near the upper tail of the recent distribution. Very low readings mean it is near the lower tail. The script then uses user defined upper and lower reversal zones to detect potential turning points when the percentile reading exits those extreme regions.
The indicator runs in a separate pane ( overlay=false ) and combines:
A rolling KDE based empirical CDF oscillator
Upper and lower statistical reversal zones
Gradient coloring based on percentile position
Background highlighting in extreme conditions
Optional reversal labels when the percentile exits an extreme zone
This makes the tool especially useful for traders who want a more distribution aware approach to reversal detection rather than a fixed oscillator threshold based only on momentum formulas.
Educational tool only. Not financial advice.
🔹 Features
🔸 1) KDE Based Empirical CDF Oscillator
The core output of the script is a percentile style oscillator built from Kernel Density Estimation. It estimates the cumulative distribution position of the current source value relative to a rolling lookback sample and expresses that result as a percentage from 0 to 100.
This gives a probabilistic location measure rather than a raw momentum reading.
🔸 2) Rolling Lookback Distribution Model
The script stores a rolling window of recent source values in an internal array. As new bars arrive, the oldest values are removed once the array reaches the configured length. This keeps the distribution adaptive to recent market behavior.
Because the model is rolling, the oscillator can adjust as the market shifts from one regime to another.
🔸 3) Non Parametric Reversal Logic
Unlike indicators that assume a fixed normal distribution of prices, this script uses a kernel smoothed empirical distribution. That means the reversal zones are based on the actual recent sample shape, not a rigid assumption about how price should be distributed.
This can make the signal more responsive to skewed, compressed, or uneven recent market structure.
🔸 4) Custom Upper and Lower Reversal Zones
Users can define:
An upper reversal zone in percentile terms
A lower reversal zone in percentile terms
These thresholds determine what counts as statistically stretched relative to the recent sample. This allows the indicator to be tuned for more aggressive or more selective reversal detection.
🔸 5) Reversal Triggers on Exit from Extremes
The script does not trigger simply because the oscillator enters an extreme zone. Instead, it triggers when the percentile reading exits the extreme zone:
A sell trigger occurs when the oscillator crosses back below the upper threshold
A buy trigger occurs when the oscillator crosses back above the lower threshold
This design aims to catch reversal confirmation after an extreme condition begins to unwind.
🔸 6) Dynamic Gradient Coloring
The percentile line is colored with a gradient between bullish and bearish colors based on its position between the lower and upper thresholds. This makes it easy to identify whether the current reading is leaning toward lower tail, neutral, or upper tail conditions.
🔸 7) Upper and Lower Zone Fills
The script includes gradient fills above and below the midline so the oscillator visually emphasizes upper tail and lower tail behavior. This improves readability and helps the user quickly identify whether the current reading is operating in a statistically stretched region.
🔸 8) Extreme Zone Background Highlighting
When the oscillator is above the upper threshold or below the lower threshold, the pane background is lightly highlighted. This creates an immediate visual cue that the current reading is inside a high probability reversal watch zone.
🔸 9) Optional Reversal Labels
When enabled, the script prints:
A downward label after a bearish reversal trigger
An upward label after a bullish reversal trigger
These labels are intentionally simple and keep the pane clean while still marking the event clearly.
🔸 10) Flexible Source Selection
The user can choose which source series to analyze, not only close. This allows the KDE engine to be applied to other price derived series if desired.
🔹 Calculations
1) Rolling Data Queue
The script stores recent source values in a custom KDEData object:
type KDEData
array prices
int length
Each bar, the new value is pushed into the array:
this.prices.push(val)
if this.prices.size() > this.length
this.prices.shift()
This creates a fixed length rolling sample used for the KDE calculation.
2) Interquartile Range (IQR) Calculation
To make the bandwidth estimate more robust, the script computes the interquartile range from a sorted copy of the rolling sample:
int q1_idx = int(math.floor(n * 0.25))
int q3_idx = int(math.floor(n * 0.75))
sorted.get(q3_idx) - sorted.get(q1_idx)
The IQR is later used as part of the spread estimate for kernel bandwidth selection.
3) Robust Spread Estimate
The script combines sample standard deviation and IQR based scaling:
float stdev = this.prices.stdev()
float iqr = this.get_iqr()
float spread = math.min(stdev, iqr / 1.34)
Interpretation:
iqr / 1.34 is a robust estimate of standard deviation under near normal assumptions.
Taking the minimum of stdev and iqr / 1.34 helps reduce the effect of extreme outliers when setting the kernel width.
If the spread collapses to zero, the script falls back to a very small positive value.
4) KDE Bandwidth Selection
The kernel bandwidth is computed using a Silverman style rule:
float h = 1.06 * spread * math.pow(n, -0.2)
This gives the smoothing width used in the Gaussian kernel estimation. Larger sample size reduces the bandwidth, while larger spread increases it.
If the calculated bandwidth is zero, the script forces a small fallback:
if h == 0
h := 0.0001
5) Gaussian Error Function Approximation
The script defines its own approximation of the error function:
erf(float x) =>
...
This function is then used to build the standard normal cumulative distribution function:
norm_cdf(float z) =>
float sqrt2 = math.sqrt(2)
0.5 * (1.0 + erf(z / sqrt2))
This is the mathematical core that converts standardized distances into cumulative probabilities.
6) KDE Based Empirical CDF Calculation
For the current price, the script computes a smoothed empirical CDF by averaging the Gaussian CDF centered on every historical sample point:
for i = 0 to n - 1
float xi = this.prices.get(i)
float z = (current_price - xi) / h
sum_prob += norm_cdf(z)
Then:
(sum_prob / n) * 100.0
Interpretation:
Each historical observation contributes a smooth cumulative probability curve.
Averaging them creates a KDE smoothed empirical percentile estimate for the current price.
This is more stable than a raw rank percentile because it smooths the distribution instead of using hard cutoffs only.
7) Warm Up Condition
The indicator only computes the KDE percentile once the rolling sample is fully populated:
if kde.prices.size() == lengthInput
cdf_percent := kde.get_kde_cdf(srcInput)
Before that, the output remains na , which prevents incomplete early calculations.
8) Oscillator Interpretation
The resulting cdf_percent is a percentile style value:
Near 0 means the current source is near the lower tail of the recent distribution
Near 50 means it is near the middle of the recent distribution
Near 100 means it is near the upper tail of the recent distribution
This is not a momentum ratio. It is a location measure inside the recent smoothed distribution.
9) Threshold Logic
The user defines:
float upperThreshold = input.float(95.0, ...)
float lowerThreshold = input.float(5.0, ...)
These thresholds define statistically extreme regions. For example:
A 95 reading means the source is near the top tail of the recent sample
A 5 reading means the source is near the bottom tail
10) Reversal Trigger Conditions
The script does not trigger on entry into the zone. It triggers when the oscillator exits the zone:
Bearish reversal trigger:
bool sellTrigger = ta.crossunder(cdf_percent, upperThreshold)
Bullish reversal trigger:
bool buyTrigger = ta.crossover(cdf_percent, lowerThreshold)
Interpretation:
A sell trigger means the percentile was above the upper threshold and then moved back below it.
A buy trigger means the percentile was below the lower threshold and then moved back above it.
This acts more like a reversion confirmation than an early warning.
11) Visual Gradient Line
The main oscillator line color is derived from its current percentile position:
color cdfColor = color.from_gradient(cdf_percent, lowerThreshold, upperThreshold, col_bull, col_bear)
This creates a smooth transition from bullish coloring in the lower reversal area toward bearish coloring in the upper reversal area.
12) Gradient Fill Zones
The script fills the area between the percentile line and the hidden midline (50) separately for upper and lower halves:
fill(p_cdf, p_mid, top_value=100, bottom_value=50, ...)
fill(p_cdf, p_mid, top_value=50, bottom_value=0, ...)
This gives the oscillator a cleaner and more informative visual structure than a plain line alone.
13) Background Highlighting
When the oscillator is inside an extreme zone, the pane background is lightly shaded:
bgcolor(cdf_percent >= upperThreshold ? ... : cdf_percent <= lowerThreshold ? ... : na)
This does not trigger a signal by itself. It simply highlights that the reading is currently in a statistically extreme region.
14) Reversal Labels
If labels are enabled, the script marks reversal exits with simple directional arrows:
For bearish reversal:
label.new(bar_index, cdf_percent + 3, "▼", ...)
For bullish reversal:
label.new(bar_index, cdf_percent - 3, "▲", ...)
The labels are plotted near the oscillator value, not on price, which keeps the indicator self contained in its own pane. Indicador

Crowd Trap Engine (Exhaustion/Reversal) [Metrify]Crowd Trap Engine is designed to spot crowded / overextended market conditions where price may be running too hard in one direction and is more vulnerable to exhaustion, pause, or reversal.
It combines multiple factors (trend, momentum, breakout behavior, volatility, volume pressure, and stretch from equilibrium) to detect when traders are likely piling in late.
When a diamond appears, it signals a high probability that the market may “take a breath” (slow down, consolidate, or react) before continuing or changing direction.
What this indicator is best used for
Spotting possible exhaustion candles
Avoiding late entries due to FOMO
Adding context for reversal / pullback setups
Confirming when price looks too extended
Visuals
Crowd Mark (diamond) = Exhaustion marker
Bias Line = crowd pressure direction / equilibrium bias
Cloud = dynamic trap zone / pressure range
Note: Best used with market structure, support/resistance, and price action confirmation Indicador

Ornstein-Uhlenbeck Mean Reversion Probability Bands [UAlgo]Ornstein-Uhlenbeck Mean Reversion Probability Bands is a statistical mean reversion indicator that models price as a mean reverting process and projects dynamic probability style zones around an estimated equilibrium mean. The script uses a rolling lookback of closing prices, fits an Ornstein-Uhlenbeck inspired parameter set from recent behavior, and then converts that estimate into inner and outer deviation bands around the current mean.
The indicator runs directly on price ( overlay=true ) and is built to help traders identify when price is stretched away from its estimated equilibrium. Instead of using a fixed moving average and static standard deviation, the script attempts to infer a mean reverting structure from the data itself. It estimates the long term mean, the speed of reversion, and an equilibrium style dispersion measure, then plots two upside and two downside mean reversion zones.
When price pushes into the upper or lower band regions, the script calculates a standardized distance from the estimated mean and displays a probability style label with both the percentage score and the current z score. This gives the user a quick visual read of how statistically extended price is relative to the model.
A key strength of this script is that it combines:
A rolling Ornstein-Uhlenbeck style parameter estimation
Adaptive mean reversion zones
Probability style stretch labels at band events
A clean overlay presentation with visible upper and lower probability regions
Important note: The percentage label in this script is a normal distribution coverage style score derived from the current z score. It is best understood as a probabilistic stretch measure, not a literal exact OU first passage probability.
🔹 Features
🔸 1) Ornstein-Uhlenbeck Inspired Mean Reversion Model
The script estimates a mean reverting process from recent closing prices instead of relying only on a moving average. It uses a rolling regression style approach on consecutive price observations, then converts those estimates into Ornstein-Uhlenbeck style parameters.
This makes the indicator more model driven than a standard band tool.
🔸 2) Rolling Adaptive Mean Line
The central mean line is not a fixed average only. It is the estimated equilibrium level ( mu ) of the fitted process. As the rolling price sample changes, the model updates and the mean shifts with changing market structure.
The mean line also changes color depending on whether current price is above or below that estimated equilibrium.
🔸 3) Dual Mean Reversion Zones (Inner and Outer)
The script builds two sets of reversion bands around the mean:
Inner bands using the inner multiplier
Outer bands using the outer multiplier
This creates a layered framework where the inner zone marks an early stretch area and the outer zone marks a more extreme statistical extension.
🔸 4) Probability Style Stretch Labels
When price crosses into the upper or lower band regions, the script calculates a z score based on current distance from the estimated mean and converts it into a percentage style probability score.
The label shows:
A directional marker
The probability style percentage
The current z score
This gives the user both a visual event trigger and a numeric measure of extension.
🔸 5) Visual Zone Based Design
The indicator uses filled upper and lower zones rather than emphasizing the band lines themselves. This creates a cleaner chart display where the mean line stays visible and the stretch regions are highlighted as colored areas above and below it.
This makes the indicator easy to read during fast chart scanning.
🔸 6) Configurable Lookback, Time Step, and Band Width
Users can customize:
The rolling lookback period used for model estimation
The time step parameter ( dt ) used in OU conversion
The inner band multiplier
The outer band multiplier
This makes the script adaptable to different timeframes, instruments, and preferred sensitivity levels.
🔸 7) Built In Estimation Safeguards
The parameter estimation logic includes fallback protections. If the inferred model parameters are unstable or unrealistic, the script falls back to simpler sample statistics. This helps prevent unusable outputs during difficult market regimes or low quality fits.
🔸 8) Directional Touch Event Logic
The script tracks both upper side and lower side band interaction:
Upper side events can signal statistically stretched bullish price movement
Lower side events can signal statistically stretched bearish price movement
Labels are only created on crossing events, which helps reduce repeated prints while price remains outside the band.
🔹 Calculations
1) Rolling Price Queue Management
The script stores recent closing prices in an array with a fixed maximum length:
price_array.update_queue(close, length_input)
The queue update method behaves differently depending on bar state:
On a new bar, it pushes the latest value
On an updating live bar, it overwrites the last stored value
This keeps the rolling sample aligned with the current chart state without duplicating the active bar.
2) Fallback Mean and Dispersion Estimates
Before attempting the OU style fit, the script calculates simple fallback values:
float fallback_mu = src_array.avg()
float fallback_sigma = src_array.stdev()
These act as safety defaults if the regression based OU estimate is not reliable.
Important note:
In this script, fallback_sigma is a simple sample standard deviation of price levels, not return volatility.
3) AR(1) Style Regression on Consecutive Prices
The model estimation is built from consecutive price pairs:
x = price
y = price
The script computes:
Mean of x
Mean of y
Covariance between x and y
Variance of x
Then it estimates:
float b = sum_cov / sum_var_x
This creates an AR(1) style coefficient that is later translated into OU style parameters.
4) Conversion from AR(1) Form to OU Style Parameters
If the estimated b is within a valid range:
if b > 0.05 and b < 0.95
the script computes:
float a = mean_y - b * mean_x
float mu_exact = a / (1.0 - b)
float theta_exact = -math.log(b) / dt
Interpretation:
mu_exact is the estimated long run mean.
theta_exact is the implied mean reversion speed.
The conversion assumes the AR(1) relation is a discrete time representation of a mean reverting process.
5) Residual Variance and Equilibrium Dispersion
The script next measures residual error from the AR(1) fit:
float err = y_i - (a + b * x_i)
float var_err = sum_err_sq / (n - 1)
Then it converts that residual variance into an equilibrium variance estimate:
float var_eq = var_err / (1.0 - b * b)
Finally:
float calc_sigma = math.sqrt(var_eq)
Important implementation note:
The variable named sigma in this script is used as an equilibrium style standard deviation around the mean, not as the continuous time OU diffusion coefficient from the SDE form.
6) Stability Filter for the Estimated Sigma
Even if the AR(1) fit is mathematically valid, the script only accepts the calculated sigma when it is reasonably close to the fallback sample standard deviation:
if calc_sigma < fallback_sigma * 1.5 and calc_sigma > fallback_sigma * 0.5
If this test fails, the script keeps the fallback values instead.
This helps avoid unstable band widths caused by bad short term fits.
7) Final Parameter Output
The estimation method returns:
OU_Params.new(theta, mu, sigma_eq)
Where:
theta is the estimated reversion speed
mu is the estimated equilibrium mean
sigma_eq is the accepted equilibrium dispersion measure
These parameters are then used to build the bands.
8) Band Construction
The script computes four band levels around the estimated mean:
float up_out = mean_val + (dev_val * mult_outer)
float up_in = mean_val + (dev_val * mult_inner)
float dn_in = mean_val - (dev_val * mult_inner)
float dn_out = mean_val - (dev_val * mult_outer)
Interpretation:
Inner bands represent a milder deviation from the mean.
Outer bands represent a more extreme deviation from the mean.
9) Mean and Zone Visualization
The mean line is explicitly plotted:
p_mean = plot(ou_bands.mean, color=color_mean, linewidth=2, title="Mean")
The inner and outer band plots are also created, but their colors are fully transparent:
color color_inner_up = color.new(#ffb74d, 100)
color color_outer_up = color.new(#ef5350, 100)
...
This means the visible structure mainly comes from the zone fills:
fill(p_ui, p_uo, ...)
fill(p_li, p_lo, ...)
So the user sees clean upper and lower probability zones rather than several bright boundary lines.
10) Touch and Crossing Logic
The script first checks whether price is currently inside a stretch area:
bool touch_upper = close >= ou_bands.upper_inner
bool touch_lower = close <= ou_bands.lower_inner
Then it checks for fresh crossings:
bool cross_up_in = ta.crossover(close, ou_bands.upper_inner)
bool cross_up_out = ta.crossover(close, ou_bands.upper_outer)
bool cross_dn_in = ta.crossunder(close, ou_bands.lower_inner)
bool cross_dn_out = ta.crossunder(close, ou_bands.lower_outer)
Labels are only created when price is touching the region and a fresh crossing occurs. This avoids creating labels on every bar that remains outside the band.
11) Z Score Calculation
When an event occurs, the script calculates the standardized distance from the mean:
float current_z_score = dev_val != 0 ? math.abs(close - mean_val) / dev_val : 0.0
Interpretation:
A z score of 1 means price is one equilibrium standard deviation away from the estimated mean.
Higher values indicate a more statistically stretched condition.
12) Probability Style Score Calculation
The script converts the z score into a percentage style score using an approximation of the error function:
float x = math.abs(z_score) / math.sqrt(2.0)
...
float prob = erf_approx * 100.0
Because erf(|z| / sqrt(2)) corresponds to the probability mass within plus or minus that z distance under a normal distribution, the output behaves like a confidence or coverage score.
Important note:
This is not a direct OU mean reversion probability in the strict stochastic process sense. It is a normal distribution style stretch score based on the current z distance.
13) Upper Event Label Logic
When price crosses into the upper band region:
if (touch_upper and cross_up_in) or (touch_upper and cross_up_out)
the script prints a bearish styled label above the bar:
"▼ %" + str.tostring(probability, "#.##") + " (Z:" + str.tostring(current_z_score, "#.##") + ")"
This reflects the idea that price is statistically extended above the mean and may be vulnerable to reversion.
14) Lower Event Label Logic
When price crosses into the lower band region:
if (touch_lower and cross_dn_in) or (touch_lower and cross_dn_out)
the script prints a bullish styled label below the bar:
"▲ %" + str.tostring(probability, "#.##") + " (Z:" + str.tostring(current_z_score, "#.##") + ")"
This reflects the idea that price is statistically extended below the mean and may be vulnerable to reversion.
15) Role of the Time Step Input
The dt_input parameter affects the conversion from the AR(1) coefficient into the OU reversion speed:
float theta_exact = -math.log(b) / dt
A larger dt lowers the inferred theta for the same b .
A smaller dt raises the inferred theta for the same b . Indicador

TX Smooth ReversalOverview:
The CDSA Smooth Reversal is a quantitative trading tool designed to identify high-probability price exhaustion and reversal points. By combining Multi-Timeframe (MTF) alignment with a sophisticated Band Engine based on KAMA (Kaufman Adaptive Moving Average), this indicator filters out market noise and focuses on institutional-grade reversal zones.
Key Features:
KAMA-Adaptive Bands: Unlike standard Bollinger Bands, our bands use an Efficiency Ratio (ER) to adapt to market volatility, expanding during trends and contracting during consolidations.
Probabilistic Reversal Scoring: A proprietary logic that calculates the likelihood of a reversal based on price deviation, volume characteristics, and trend exhaustion.
MTF Fusion Gate: Ensures that signals only appear when multiple timeframes (Micro, Operational, and Regime) are in alignment, significantly reducing false signals.
Heikin Ashi Integration: Optional HA logic processing to smooth out erratic price action for long-term trend analysis.
Live Dashboard: Real-time monitoring of Bull/Bear reversal probabilities and MTF status directly on your chart.
How to Trade:
Bullish Reversal (BUY): Look for the "BUY" label when the Bull Probability is high (>75%) and price touches the lower outer bands.
Bearish Reversal (SELL): Look for the "SELL" label when the Bear Probability is high (>75%) and price reaches the upper outer bands.
MTF Confirmation: Ensure the "MTF Alignment" on the dashboard matches your trade direction for the highest win-rate setups.
Settings:
Algorithm Mode: Choose between Conservative (fewer, higher quality signals), Normal, or Aggressive.
Alignment Threshold: Adjust how strictly the different timeframes must agree before a signal is triggered. Indicador

Natural Visibility Graph [UAlgo]Natural Visibility Graph (NVG) is a structure detection indicator that treats price as a time series network. Each bar is interpreted as a node, and nodes are connected if they can “see” each other without intermediate bars blocking the line of sight. This is based on the Natural Visibility Graph concept introduced in complex network theory, where geometric visibility rules convert a time series into a graph.
In practical trading terms, NVG measures how structurally important a bar is by counting how many past bars remain visible from it. Bars with high visibility act like pivots that dominate their local environment because they are not easily obstructed by surrounding price action. The script computes this visibility for highs and lows separately, then flags exceptional nodes as hubs using a dynamic, volatility aware thresholding process.
The output is a chart overlay that highlights structural peaks and valleys with neon hub markers, draws a horizon style connection to the furthest visible bar, and optionally provides alerts when new hubs appear. It also colors bars according to hub status so structural events stand out instantly.
🔹 Features
1) Natural Visibility Graph Degree for Highs and Lows
The indicator calculates an in degree style connectivity score for each bar. Degree represents how many past bars are visible from the current bar under the NVG rule. Highs and lows are handled independently:
High graph measures visibility between swing peaks
Low graph measures visibility between swing valleys using an inverted obstruction rule
This separation helps detect both resistance like peaks and support like valleys without blending them into a single metric.
2) Lookback Controlled Structural Sensitivity
Visibility is computed only within a user selected lookback window. Larger values build stronger structural context and produce more selective hubs, but increase computation. Smaller values react faster but focus on local structure.
Visibility Lookback directly controls how far the algorithm searches for visible connections.
3) Dynamic Hub Detection with Adaptive Max Degree
Instead of using a fixed degree threshold, the script maintains a rolling maximum degree for highs and lows and applies a percentile style threshold. A slow decay mechanism reduces the max gradually over time so the reference level adapts when market structure changes.
This keeps hub detection stable across different regimes and helps avoid permanently locking into an old maximum degree that may no longer be reachable.
4) Hub Threshold Percentile Control
Hub Threshold defines how strict hub detection is. It is applied as a fraction of the current rolling maximum degree:
High hub when degreeH is greater than or equal to maxDegH times threshold
Low hub when degreeL is greater than or equal to maxDegL times threshold
Higher threshold values mark only the most dominant nodes. Lower values mark more frequent hubs.
5) Neon Web Visual Design
The script uses a neon palette to make structural events highly visible:
High hubs are marked with a cyan diamond above price
Low hubs are marked with a pink diamond below price
A dotted horizon beam connects the hub to its furthest visible past node, helping you interpret how far the hub’s influence extends in the visibility sense.
6) Bar Coloring for Instant Structural Context
Bars are colored by hub status:
Cyan for high hubs
Pink for low hubs
Muted gray for non hub bars
This provides a fast scan view of where the market is producing dominant structural events.
7) Alerts for Structural Peaks and Valleys
Alert conditions are provided for both hub types:
High Visibility Structural Peak Detected
High Visibility Structural Valley Detected
These can be used for structural monitoring, swing validation, or confluence with other tools.
🔹 Calculations
1) Natural Visibility Rule for Highs
For each past bar i within the lookback, the script checks if the straight line from the current high to the past high is unobstructed by intermediate highs. If no intermediate high reaches or exceeds the projected height on that line, the past bar is visible and the degree increases.
Core idea:
Current bar at index 0
Past bar at index i
Intermediate bars at index k where 1 is the nearest past bar and i minus 1 is just before the past bar
Slope and projection:
float slope = (high - high ) / float(i)
for k = 1 to i - 1
float y_projected = high - (slope * k)
if high >= y_projected
isVisible := false
break
If isVisible remains true, degreeH increments and furthestVisIdxH is updated to i, so the script remembers the furthest visible connection for drawing.
2) Natural Visibility Rule for Lows
Lows use the inverted valley logic. A past low is visible from the current low if intermediate lows do not fall at or below the projected line, because deeper lows block visibility in a valley sense.
float slope = (low - low ) / float(i)
for k = 1 to i - 1
float y_projected = low - (slope * k)
if low <= y_projected
isVisible := false
break
If visible, degreeL increments and furthestVisIdxL records the furthest visible low node.
3) Rolling Maximum Degree with Slow Decay
The indicator maintains rolling maximum degree values for highs and lows. Periodically it applies a slow decay so that the maximum can adapt downwards over time if structural connectivity decreases:
var int maxDegH = 5
var int maxDegL = 5
if bar_index % int(lookback/2) == 0
maxDegH := int(math.max(5, maxDegH * 0.95))
maxDegL := int(math.max(5, maxDegL * 0.95))
maxDegH := math.max(maxDegH, degreeH)
maxDegL := math.max(maxDegL, degreeL)
Interpretation:
The max degree never falls below 5
Decay runs every lookback divided by two bars
New degrees update the max immediately if a stronger hub appears
4) Hub Classification
A bar becomes a hub if its degree reaches a fraction of the current max degree:
bool isHubH = degreeH >= maxDegH * threshold
bool isHubL = degreeL >= maxDegL * threshold
threshold behaves like a percentile control over the observed maximum connectivity.
5) Hub Markers and Horizon Beam
When a hub is detected, the script plots a diamond label and draws a dotted line to the furthest visible bar for that hub type:
High hub:
label.new(bar_index, high, "◈", textcolor=colNeonCyan, style=label.style_label_down)
line.new(bar_index, high, bar_index - furthestVisIdxH, high , style=line.style_dotted)
Low hub:
label.new(bar_index, low, "◈", textcolor=colNeonPink, style=label.style_label_up)
line.new(bar_index, low, bar_index - furthestVisIdxL, low , style=line.style_dotted)
Interpretation:
The beam represents the furthest confirmed visibility connection and gives a visual sense of the hub’s visibility range.
6) Alert Conditions
The script exposes alert conditions tied to the hub booleans:
alertcondition(isHubH, "NVG High Hub", "High Visibility Structural Peak Detected")
alertcondition(isHubL, "NVG Low Hub", "High Visibility Structural Valley Detected")
Indicador

Delta Strike: Order Flow Absorption & Momentum Confirmation**Delta Strike** is a professional-grade quantitative tool designed for traders who prioritize institutional logic over simple price action. It moves beyond traditional "buy/sell" indicators by dissecting the battle between **Passive Absorption** and **Aggressive Initiative** using underlying Order Flow data.
### 🛡️ The Core Philosophy: "Wait for the Trap, Trade the Escape"
Markets rarely reverse instantly. **Delta Strike** follows a rigorous two-step verification process to filter out noise and hunt for high-probability institutional footprints:
1. **Phase 1: Institutional Absorption (Left-Side Setup)**
The system identifies "Base Bars" where high volume and extreme Delta (passive buying/selling) occur, but price fails to continue. This indicates that a large player is absorbing the current move.
2. **Phase 2: Aggressive Strike (Right-Side Confirmation)**
We do not "catch the knife." Instead, the indicator monitors the next **N bars** for a confirmed strike. A signal is only triggered when price engulfs the base bar and is backed by a significant **Active Delta Percentage**, proving that the "absorber" has now become the "aggressor."
### 🚀 Key Technical Features
* **Dual-Cycle Volume Matrix**: Unlike standard indicators, Delta Strike analyzes volume across two lookback periods simultaneously (Short-term 20 & Long-term 50). It classifies setups into three categories:
* 🔥 **Dual-Cycle Convergence** (Maximum Strength)
* ⚡ **Short-term Spike** (Local Volatility)
* 🌊 **Macro Volume Surge** (Long-term Accumulation)
* **Active Delta Intensity Filter**: Every confirmation bar is evaluated for its "Net Win Ratio." By filtering out low-conviction, low-volume breakouts, it ensures you only follow moves with real institutional backing.
* **RSI Environment Guard**: Integrated RSI logic ensures that bottom absorption is only hunted in "Oversold" zones and top absorption in "Overbought" zones, significantly reducing whipsaws in sideways markets.
* **Validated SuperTrend (Delta-Sync)**: A modified SuperTrend algorithm that requires a "Delta Handshake." A trend flip is only considered valid if price and Delta move in the same direction, preventing "fake-outs" during low-liquidity periods.
### 📊 Clean & Actionable UI
* **Base Bar Highlight**: When a setup is confirmed, the script retroactively draws a **Yellow (Bullish)** or **Fuchsia (Bearish)** box around the original absorption bar.
* **Trace Lines**: Dashed lines connect the original institutional entry to your current entry point, providing immediate visual context for the trade's logic.
* **Momentum Rating (🐂/🐻)**:
* **3 Stars (🐂🐂🐂)**: Extreme Delta Strike (>20% Net Win).
* **2 Stars (🐂🐂)**: High Conviction Strike (>10% Net Win).
* **1 Star (🐂)**: Standard Confirmation.
### 🔔 Smart Alert System
Equipped with a fully customizable alert suite. You can set alerts for:
* **Absorption Confirmations** (Long/Short)
* **Validated SuperTrend Breakouts**
*Note: For the most accurate results, it is recommended to use "Any alert() function call" and set frequency to "Once Per Bar Close" to avoid repainting during intra-bar fluctuations.*
---
### How to use:
1. Look for the ** ** label and highlighted box.
2. Wait for the **Strike icons (🐂/🐻)** to appear within the N-bar window.
3. Combine with your existing Support/Resistance levels for optimal strike rates.
--- Indicador

Liquidity Pools + Sweep Signals [Metrify]If breakouts feel like a scam, it’s because they often function like one.
Most charts are taught like they’re a clean story of supply and demand. But real price action is messier: it’s a sequence of tests, traps, and collections. The market doesn’t need to “respect” your line, it needs to find liquidity.
And liquidity usually sits in predictable places: swing highs, swing lows, prior reaction points, the levels everyone can see.
This Liquidity Sweep Canvas is a market-structure overlay that tracks liquidity pools built from swing highs/lows, then monitors how price interacts with those pools over time (touches → sweeps → breaks/expiry). The goal is not to “predict” — it’s to map where liquidity is parked, highlight when it’s raided with rejection, and keep a clean, visual “canvas” of relevant pools near current market.
It builds two sides:
SELL liquidity pools (from pivot highs, shown in red)
BUY liquidity pools (from pivot lows, shown in teal)
Each pool is zoned around the pooled level, merges nearby levels (optional aggressiveness), tracks hits, and can transition through states:
Active (building / being respected)
Swept (liquidity taken + rejection confirmed)
Ended (broken through or expired)
Sweep logic in plain terms
A sweep is detected when price pierces beyond a pool boundary and then closes back through the pool’s midline in the opposite direction (rejection).
Bear sweep (SELL liquidity): price wicks above a SELL pool, then closes back below the pool mid.
Bull sweep (BUY liquidity): price wicks below a BUY pool, then closes back above the pool mid.
Optionally, you can require a second-step confirmation:
Displacement confirm waits for follow-through (within a small window) where price breaks beyond the sweep candle’s reference (with a minimum body size in ATR). This filters some noise, at the cost of being delayed.
🔥 Scoring system (how “quality” is decided)
Sweeps are common. Clean sweeps are not. We uses a weighted scoring model (0–100) so you can filter out weak sweeps and keep the ones that show stronger intent.
A sweep starts when price penetrates beyond the pool boundary (takes liquidity) and reclaims back inside the zone (closes through the pool mid). From there, a score is built from two layers:
✅ Layer 1 —> Sweep candle “core bundle” (base part)
This is computed immediately on the sweep candle (or stored if you require displacement). The base bundle blends:
Penetration: how deep the wick pushed beyond the pool in ATR terms (not “deeper is always better”, it’s shaped to reward a realistic sweet spot).
Reclaim strength: how much of the candle reclaimed back (close relative to the range).
Wick ratio: rejection wick size vs body (controlled by 'Wick Ratio Scale').
Body bias: bullish body for bull sweeps / bearish body for bear sweeps gets rewarded.
EMA context: measures whether the sweep is happening with a favorable distance relative to EMA 200.
Line age/maturity: longer pools can score differently via a length score, then get penalized by a separate age penalty.
🧠 Layer 2 —> Context add-ons
After the base bundle, the final score can include:
MSS context: a simple structural reference (recent swing extreme lookback) to rate whether the sweep is happening with useful positioning.
Effort score: combines range expansion (ATR) with volume vs volume MA to reward sweeps that show actual participation.
Displacement score (optional): if enabled, the sweep is only confirmed after follow-through within a small window.
How to use it
1. Build a two-stage decision: location bias, then trigger selection
Use pools to decide directional bias before you even consider entries. If price is pressing into SELL pools repeatedly and the dashboard shows dense sell-side activity, your bias shifts toward expecting a sell-side raid (sweep up then rejection) rather than a clean breakout. If price is pressing into BUY pools, same logic for downside raid and bounce. Then decide your trigger style manually:
If you trade fast mean reversion, you can use immediate sweeps as the “first alarm” and enter on the reclaim + tight invalidation.
If you trade safer confirmation, require displacement confirm, and only act once price has proven it can leave the pool with force.
Either way, the script helps you separate where it matters (pools) from where it doesn’t (middle of nowhere).
2. Use hit count to judge liquidity density and trap probability
The LP xN hit count is a manual edge if you treat it correctly: more hits generally implies more eyes, more orders, more liquidity, and therefore more potential for a meaningful raid. When you see a pool with high hits near current price, don’t assume it’s “strong support/resistance.” Instead, assume it’s a liquidity magnet.
If price repeatedly taps a high-hit pool without breaking cleanly, it often sets up a sweep (stop run + reverse).
If price breaks and stays outside with follow-through, that’s not a sweep environment, it’s a continuation environment.
So you use hit count to anticipate which levels are likely to be hunted, then use candle behavior + displacement to judge whether the hunt was successful and rejected.
3. Turn sweeps into ‘event markers’ for post-move structure mapping
Instead of treating a sweep as “enter now,” treat it as: a structural event happened here.
After a sweep prints, manually re-map microstructure: identify the last minor swing before the sweep, then track whether price breaks it (MSS/BOS style) and whether the first pullback respects that break.
4. Use the channel read as a regime filter (premium/discount logic)
The nearest pool edges effectively form a liquidity channel. Use it like a regime filter:
Inside SELL zone / premium: prioritize short-side narratives
Inside BUY zone / discount: prioritize long-side narratives
Middle channel: treat as uncertainty, tighten your standards (or step aside).
5. Use scoring as a ‘quality gate’, then you do the narrative check”
If you enable scoring, stop thinking of it as “higher score = higher win.” Think of it as a gate that filters out low-effort pokes. Once a high-score sweep prints, manually audit it.
6. Use it as a ‘sweep journal’ to study your market’s behavior
A very “pro” use is not trading it at all for a week. Turn on historical traces and sweep markers, and just observe: Which sessions produce the cleanest sweeps? Do high-score sweeps outperform low-score? Do confirmed sweeps reduce chop at the cost of late entries? Does your instrument sweep more on highs or lows? The dashboard counts help you quantify frequency. After you collect observations, you tune inputs (Swing Length, Merge Distance, Minimum Score, Volume thresholds) to match the instrument’s microstructure.
This is how you turn a generic sweep concept into a market-specific playbook—and the script becomes your data-driven visual log, not a guessing machine.
⚙️ Tuning tips (fast)
Too many pools / too noisy → increase Swing Length / Merge Distance.
Sweeps trigger too often → enable Activate Scoring and raise Min Score.
Wick quality not valued enough → reduce Wick Ratio Scale.
Effort scoring feels too easy/hard → adjust Min Volume / MA and Volume MA Length.
A higher score is not a guarantee of a better trade, it simply means the sweep event matched more of the model’s criteria (penetration, reclaim, rejection wick, effort, context components, and optional displacement). Markets are adaptive: what high quality looks like changes by instrument, timeframe, and session. Use scoring to reduce noise, then manually validate. Indicador

Heiken Ashi Break of Structure with Market Structure [by Hampeh]Description
This indicator is designed to identify high-probability trading entries by combining the trend-smoothing capabilities of Heiken Ashi candles with the powerful concept of a Break of Structure (BOS).
To enhance signal quality and reduce false signals, it incorporates a mandatory market structure confirmation filter, requiring a Higher Low (HL) to be established before a buy signal and a Lower High (LH) before a sell signal. The indicator automatically provides dynamic Stop Loss levels and generates real-time alerts to streamline the trading process.
How It Works
The indicator's logic is built upon several key components that work together to filter for high-quality setups.
1. Heiken Ashi Foundation The script uses Heiken Ashi candles as its foundation to reduce market noise and provide a clearer visualization of the underlying trend. This smoothing effect makes it easier to identify sustained directional moves.
2. Break of Structure (BOS) Identification The core entry trigger is a Break of Structure, defined as:
Bullish BOS (Buy Signal): The indicator first identifies a downtrend phase (red Heiken Ashi candles). It marks the opening price of this phase (redOpen). A buy signal is triggered when the trend reverses (turns green) and the Heiken Ashi close price breaks above this redOpen level.
Bearish BOS (Sell Signal): Conversely, it identifies an uptrend phase (green Heiken Ashi candles) and marks its opening price (greenOpen). A sell signal is triggered when the trend reverses (turns red) and the Heiken Ashi close price breaks below this greenOpen level.
3. Market Structure Confirmation (HL/LH Filter) This is the key filter that validates the strength of a potential new trend:
Higher Low (HL) for Buys: A buy signal is only considered valid if the low point of the most recent downtrend phase is higher than the low point of the previous downtrend phase. This confirms a classic "Higher Low" market structure, indicating that buying pressure is increasing.
Lower High (LH) for Sells: A sell signal is only considered valid if the high point of the most recent uptrend phase is lower than the high point of the previous uptrend phase. This confirms a "Lower High" structure, suggesting that selling pressure is building.
4. Dynamic Stop Loss Calculation The indicator provides a logical and dynamic Stop Loss for every signal:
For Buy Signals: The Stop Loss is automatically placed just below the lowest low (lowestLow) recorded during the entire preceding downtrend (red candle) phase.
For Sell Signals: The Stop Loss is placed just above the highest high (highestHigh) recorded during the entire preceding uptrend (green candle) phase.
5. Signal Generation and Visualization
A final BUY signal is generated only when all conditions are met: a bullish BOS occurs and it is preceded by a confirmed Higher Low.
A final SELL signal is generated only when all conditions are met: a bearish BOS occurs and it is preceded by a confirmed Lower High.
When a valid signal is triggered, a label appears on the chart displaying the entry price and the calculated Stop Loss. A corresponding alert is also fired with detailed trade information.
Summary of Strategy
In essence, this indicator waits for a pullback (a Heiken Ashi color change), confirms that the pullback respects bullish or bearish market structure (HL or LH), and then triggers an entry upon a Break of Structure in the intended direction.
Disclaimer : This indicator is a tool for technical analysis and does not guarantee profits. Trading financial markets involves significant risk. Always conduct your own research and practice proper risk management.
Indicador

Donchian Ribbon [UAlgo]Donchian Ribbon is a chart-overlay Donchian Channel ribbon that visualizes multiple lookback lengths at the same time. Instead of plotting a single Donchian Channel, the script builds a fixed stack of channels that increase in length and blends them into a clean, layered ribbon above and below price using progressive fills.
The goal is to make market structure and regime easier to read without clutter:
- When the ribbon expands and stays orderly (fast boundaries leading, slow boundaries following), it often reflects sustained range expansion and more directional flow.
- When the ribbon compresses and bands overlap frequently, it typically reflects consolidation, rotational behavior, and reduced clarity.
- The slowest channel provides the structural “outer frame” of the market’s recent range, while shorter channels react first and show how quickly the range is shifting.
This indicator is designed as a context tool. It does not attempt to “predict” direction by itself, but it gives a high-quality visual map of evolving highs/lows across multiple sensitivities so you can align entries, risk, and expectations with the current regime.
🔹 Features
1) Multi-Length Donchian Stack (Ribbon Engine)
The script constructs several Donchian Channels from a Base Length and a Step Length. Each band represents a different sensitivity level:
- Fast bands respond quickly to recent highs and lows.
- Slow bands respond more conservatively and define broader containment.
By stacking these lengths together, you can see short-term responsiveness and higher-level structure simultaneously.
2) Two-Sided Ribbon (Upper and Lower Envelopes)
The indicator visualizes both sides of the Donchian framework:
- Upper ribbon is built from stacked Donchian highs (highest highs per length).
- Lower ribbon is built from stacked Donchian lows (lowest lows per length).
This keeps interpretation intuitive: price pressing into the upper ribbon suggests pressure toward recent highs, while leaning into the lower ribbon suggests pressure toward recent lows.
3) Gradient Depth via Layered Fills (Clean Charts)
Instead of drawing many lines, the script fills the space between consecutive bands. Transparency is gradually adjusted from the fast band to the slow band, producing a smooth depth effect that stays readable even on busy charts.
Intermediate plots are intentionally hidden so the ribbon remains the main visual output.
4) Regime Readability (Expansion vs Compression)
Because each band has a different lookback length, the ribbon naturally communicates volatility and state:
- Expansion: spacing between fast and slow bands increases, commonly seen in stronger directional phases.
- Compression: spacing collapses and bands cluster, commonly seen in ranges, pauses, or choppy rotation.
This helps you quickly decide whether to treat price action as breakout-oriented, trend-continuation, or mean-reverting.
5) Trend Baseline Reference (Slow Midpoint)
A baseline is plotted using the midpoint of the slowest channel. This provides a stable reference that helps you judge whether price is operating in the upper or lower half of the broader range structure.
🔹 Calculations
1) Donchian High, Low, and Midpoint Per Band
Each Donchian band is computed from its own length:
- High = highest high over the lookback length
- Low = lowest low over the lookback length
- Mid = average of High and Low
id.high := ta.highest(id.length)
id.low := ta.lowest(id.length)
id.mid := math.avg(id.high, id.low)
2) Length Sequencing (Base Length + Step Length)
The indicator creates a fixed number of bands. Lengths are built as:
- Band 1: base_length
- Band 2: base_length + step_length
- Band 3: base_length + 2 * step_length
- ...
- Final band: base_length + (ribbon_count - 1) * step_length
This yields a consistent progression from fast to slow sensitivity.
int len = base_length + (i * step_length)
channels.push(DonchianChannel.new(len))
3) Iterative Updates with Arrays and Methods
All bands are stored in an array and updated every bar using a unified method call. This ensures every band follows identical rules and makes the logic scalable and maintainable.
for dc in channels
dc.update()
4) Upper Ribbon Construction (Layered Fills Between Highs)
The upper ribbon is created by filling between consecutive Donchian highs. Each layer uses the same upper tone with progressively stronger visibility toward the slow band.
fill(p_fast_high, p_mid1_high, color.new(col_upper, 90), "Ribbon Upper 1")
fill(p_mid1_high, p_mid2_high, color.new(col_upper, 80), "Ribbon Upper 2")
fill(p_mid2_high, p_mid3_high, color.new(col_upper, 70), "Ribbon Upper 3")
fill(p_mid3_high, p_slow_high, color.new(col_upper, 60), "Ribbon Upper 4")
5) Lower Ribbon Construction (Layered Fills Between Lows)
The lower ribbon is created by filling between consecutive Donchian lows with the lower tone, again using progressive transparency.
fill(p_fast_low, p_mid1_low, color.new(col_lower, 90), "Ribbon Lower 1")
fill(p_mid1_low, p_mid2_low, color.new(col_lower, 80), "Ribbon Lower 2")
fill(p_mid2_low, p_mid3_low, color.new(col_lower, 70), "Ribbon Lower 3")
fill(p_mid3_low, p_slow_low, color.new(col_lower, 60), "Ribbon Lower 4")
6) Trend Baseline (Slow Midpoint)
The baseline is the midpoint of the slowest Donchian band, plotted as a stable center reference for the broadest range framework.
plot(dc_slow.mid, "Trend Baseline",
color = color.from_gradient(0.5, 0, 1, col_lower, col_upper),
linewidth = 2)
7) Visualization Choice (Hidden Internals, Visible Structure)
To keep charts clean, most intermediate plots are hidden and the ribbon fills do the heavy lifting visually, while the slow boundaries remain visible as the outer frame.
p_fast_high = plot(dc_fast.high, "Fast High", color = color.new(col_upper, 80), display = display.none)
p_fast_low = plot(dc_fast.low, "Fast Low", color = color.new(col_lower, 80), display = display.none)
p_slow_high = plot(dc_slow.high, "Slow High", color = color.new(col_upper, 50))
p_slow_low = plot(dc_slow.low, "Slow Low", color = color.new(col_lower, 50))
Indicador

Absorption ReversalAbsorption Reversal detects institutional absorption patterns at the extremes of a trading range. When price reaches a range boundary, large limit orders from institutional players can "absorb" aggressive market orders — this creates a characteristic candle with high volume and a long rejection wick. The indicator identifies these setups and waits for confirmation before signaling a reversal.
Free & Open Source — no invite-only access, no paywall. Full source code, fully transparent.
## The Concept: What Is Absorption?
In order flow terms, absorption occurs when resting limit orders at a price level absorb incoming market orders without allowing price to break through. This is a core concept in Wyckoff analysis (Effort vs. Result) and institutional trading:
- High volume (Effort) + small price movement / long wick (no Result) = absorption
- The wick shows that price was pushed to the extreme but immediately rejected
- This typically happens at range boundaries where institutional players defend levels
The indicator automates this detection process with quantifiable rules.
## How It Works
The signal generation follows a strict 6-step process:
Step 1 — Range Detection: A Donchian Channel (highest high / lowest low) defines the current trading range boundaries.
Step 2 — Range Width Filter: The channel width must be below its own average — confirming the market is sideways/contracting, not expanding into a trend.
Step 3 — ADX Trend Filter: Wilder's ADX must be below the threshold (default 25) — no strong trend active. Absorption setups work best in range-bound markets.
Step 4 — Proximity Check: Price must be in the upper or lower proximity zone of the range (default: outer 15%). Absorption in the middle of a range is meaningless.
Step 5 — Absorption Bar: A candle that shows:
- Volume spike (default 1.5x average — significant participation)
- Long rejection wick (default 66% of candle range — strong rejection)
- Located at the range extreme (within proximity zone)
Step 6 — Confirmation: Within the next N bars (default 3), a follow-up candle must close back inside the range in the expected reversal direction. No confirmation = no signal.
## Chart Elements
- Range Lines — Donchian Channel upper (red) and lower (green) boundaries
- Proximity Zones — Optional shaded areas showing where absorption signals can trigger
- Orange Diamonds — Absorption bars detected (before confirmation)
- Green/Red Triangles + BUY/SELL Labels — Confirmed reversal signals only
## Dashboard
The real-time dashboard displays:
- Market Regime — Range or Trending (based on ADX + channel width)
- ADX Value — Current trend strength with classification
- Range Width — Contracting or Expanding
- Position — Where price sits in the range (Near High / Near Low / Middle)
- Volume — Current volume relative to average + spike detection
- Pending — Active absorption bars awaiting confirmation (with countdown)
## Settings
Range Detection: Donchian Channel Length (default 20), Proximity Zone % (default 15%)
Trend Filter: ADX Filter ON/OFF (default ON), Range Width Filter ON/OFF (default ON)
Absorption Criteria: Min Wick/Range Ratio (default 0.66), Volume SMA Length (default 20), Volume Spike Multiplier (default 1.5x)
Confirmation: Max Confirmation Bars (default 3)
## Alerts
4 alert conditions:
- Absorption Buy Signal — confirmed bullish reversal at range low
- Absorption Sell Signal — confirmed bearish reversal at range high
- Bullish Absorption Detected — absorption bar found, awaiting confirmation
- Bearish Absorption Detected — absorption bar found, awaiting confirmation
## Best Used For
- Identifying high-probability reversal setups at range boundaries
- Spotting institutional absorption activity via volume + wick analysis
- Range-trading strategies with clear entry signals
- Confluence tool alongside other indicators
- Works on all instruments: stocks, forex, crypto, futures, indices
## Technical Notes
- Pine Script v6 (latest version)
- Signals on confirmed bars only — no repainting
- State-based confirmation logic
- Open source, no external dependencies
- All inputs have tooltips
## Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. No signals should be interpreted as buy or sell recommendations. Past performance is not indicative of future results. Always implement proper risk management. Trade at your own risk. Indicador

Indicador

Indicador

Estrategia

Adaptive Harmonic Forecast [LuxAlgo]The Adaptive Harmonic Forecast indicator decomposes price action into multiple cyclical components and a linear trend to forecast future market movement.
By extracting the most dominant frequencies from recent price data, the tool projects a multi-harmonic model into the future to identify potential reversal points and trend continuations.
🔶 USAGE
The indicator provides a mathematical projection of price action based on the assumption that markets exhibit cyclical behavior. Users can utilize the forecast to anticipate upcoming shifts in momentum or to identify the underlying trend direction.
It is important to note that the forecast is dynamic and recalculates on the most recent bar; therefore, it is best used to confirm momentum shifts when price action aligns with the projected harmonic direction.
🔹 Historical Fit & Forecast
The script displays a solid line over the historical lookback period, representing how well the harmonic model fits the actual price data. Beyond the current bar, a dotted line extends the forecast. This forecast is color-coded: green represents projected upward movement, while red represents projected downward movement. The forecast should be viewed primarily as a timing tool rather than an exact price target, as it projects where the "rhythm" of the market is heading based on current harmonics.
🔹 Trend Line & Reversal Markers
A linear trend line is calculated alongside the sinusoids to show the overall bias (slope) of the lookback period. Additionally, the indicator can plot reversal markers (dots) at the specific points where the forecasted cycles reach a peak or trough. These markers highlight potential future turning points where the composite cycles converge to create a local maximum or minimum.
🔹 Detected Cycles Table
The "Detected Cycles" dashboard allows traders to identify if current price action is dominated by short-term "noise" cycles or larger "structural" cycles. By observing the period lengths (in bars), users can determine the frequency of market swings. If the detected periods are small relative to the lookback, the market is in a high-frequency state; if they are large, the market is exhibiting more stable, long-term cyclicality.
🔶 DETAILS
The script operates through a two-step mathematical process involving spectral analysis and matrix-based regression:
Periodogram Logic (Cycle Detection): The indicator first detrends the data within the lookback window using a linear fit. It then performs a spectral analysis by scanning a range of periods to calculate "spectral power" (the correlation between price and a specific frequency). It identifies "spectral peaks" where price variance is most concentrated, ensuring that only the most meaningful cycles are selected for modeling rather than random noise.
Multi-Harmonic OLS Regression: Once the dominant periods are identified, the script uses Ordinary Least Squares (OLS) regression to solve for the coefficients of a linear combination of basis functions. Specifically, it constructs a model consisting of multiple sine and cosine waves (representing the cycles) and a first-order polynomial (representing the trend). By solving the normal equation using matrix math, the script finds the optimal amplitudes and phases that minimize the squared error against historical price. This composite model is then solved for future time coordinates to create the extrapolation.
🔶 SETTINGS
🔹 Settings
Fit Lookback (N): Determines the number of historical bars used to analyze cycles and fit the model.
Extrapolation Bars: Sets how many bars into the future the forecast should extend.
Number of Sinusoids: The maximum number of individual cycles to include in the composite model (1-10).
🔹 Automatic Cycle Detection
Min Period: The shortest cycle length (in bars) the algorithm is allowed to detect.
🔹 Visuals
Show Reversal Dots: Toggles the markers at forecasted local highs and lows.
Dot Size: Adjusts the visual scale of the reversal markers.
Show Detected Periods: Toggles the data table showing the lengths of the dominant cycles.
🔹 Trend Line
Show Trend Line: Toggles the display of the underlying linear regression line.
Trend Line Color: Sets the color for the historical and projected trend line.
Indicador

Harmonic Resonance Oscillator [LuxAlgo]The Harmonic Resonance Oscillator indicator provides a specialized oscillator that decomposes price action into multiple harmonic cycles to identify confluence in market rotations.
By isolating short, medium, and long-term frequencies, the tool aims to pinpoint exhausted price movements and potential reversal zones through the concept of cyclic resonance.
🔶 USAGE
The Harmonic Resonance Oscillator can be used to identify market turning points by observing when the aggregate cycle resonance reaches extreme levels. Unlike standard oscillators that rely on a single lookback period, this tool aggregates multiple filtered cycles to provide a more robust view of market momentum and exhaustion.
When the oscillator enters the dynamic overbought (upper) or oversold (lower) zones, it indicates that the various price cycles are aligning at an extreme, often preceding a corrective move or a trend reversal.
🔹 Harmonic Multipliers
The script uses a Reference Period combined with three multipliers to define the cycles:
The Short Multiplier captures fast, intraday-style fluctuations.
The Medium Multiplier focuses on the primary trend rhythm.
The Long Multiplier tracks broader market cycles.
When all three cycles reach peak or trough levels simultaneously, the oscillator displays a "resonance" peak, which is highlighted by background coloring if the signal exceeds the dynamic thresholds.
🔶 DETAILS
The indicator is built upon three primary technical pillars:
🔹 Ehlers' Bandpass Filter
At its core, the indicator uses John Ehlers' Cycle decomposition method. The bandpass filter is designed to pass only price components within a specific frequency range while attenuating everything else. This allows the script to "tune in" to specific market rhythms without the lag typically associated with moving averages.
🔹 Normalization & Resonance
Each isolated cycle is normalized onto a scale of 0 to 100 using a specific lookback length. The final "Harmonic Resonance" signal is the arithmetic mean of these three normalized cycles. A value of 50 represents a neutral state, while values approaching 0 or 100 represent extreme harmonic alignment.
🔹 Dynamic Volatility-Adjusted Zones
The Overbought and Oversold thresholds are not static. They adjust dynamically based on the standard deviation of the resonance signal. During periods of high cyclic volatility, the bands expand to require stronger confluence for a signal; during low volatility, the bands contract to stay sensitive to smaller market rotations.
🔶 SETTINGS
🔹 Harmonic Settings
Reference Period: The base period used to calculate the harmonic cycles.
Short Multiplier: Multiplier applied to the reference period for the short-term cycle.
Medium Multiplier: Multiplier applied to the reference period for the medium-term cycle.
Long Multiplier: Multiplier applied to the reference period for the long-term cycle.
Bandwidth: Controls the "tightness" of the bandpass filter. Lower values isolate specific cycles more precisely.
🔹 Normalization Settings
Normalization Lookback: The window used to scale the cycles and calculate the volatility of the resonance signal.
🔹 Overbought / Oversold Control
Overbought Threshold: The base level for the upper dynamic zone (default 80).
Oversold Threshold: The base level for the lower dynamic zone (default 20).
🔹 Style
Bullish Color: Color of the oscillator when above the 50 midpoint.
Bearish Color: Color of the oscillator when below the 50 midpoint.
Overbought Color: Color of the upper dynamic threshold.
Oversold Color: Color of the lower dynamic threshold.
Show Background Highlighting: Toggles the background coloring when resonance reaches extreme levels.
Indicador

Indicador

Estrategia

Neural Probability Channel [AlgoPoint]The Neural Probability Channel (NPC) is a next-generation volatility and trend analysis tool designed to overcome the limitations of traditional bands (like Bollinger Bands) and smoothing filters (like standard Moving Averages).
Unlike traditional indicators that rely on linear deviation or simple averages, the NPC utilizes a Rational Quadratic Kernel—a concept derived from machine learning regression models—to calculate a non-repainting, highly adaptive baseline (Fair Value). This allows the indicator to distinguish between market noise and genuine trend shifts with superior accuracy.
The volatility bands are dynamically calculated using a hybrid of Standard Error (Mean Deviation) and ATR, ensuring the channels adapt organically to market conditions—expanding during high-impact moves and contracting during consolidation.
How It Works
- The Neural Baseline (Center Line): Instead of a standard Moving Average, the NPC uses a Rational Quadratic Kernel weighting system. This assigns "importance" to price data based on both recency and similarity. It acts as a "Center of Gravity" for price, providing a smoother yet responsive trend detection line without the lag associated with SMAs or EMAs.
Crucially, the math is causal (no lookahead), meaning it does not repaint.
- Adaptive Volatility Bands: The channel width is not fixed. It uses a Hybrid Volatility Model:
- Inner Channel: Represents the "Probability Zone" (approx. 70% confidence). Price staying here indicates a stable trend.
- Outer Channel: Represents "Extreme Deviation" (Statistical Anomalies). When price touches or breaches these outer bands, it is statistically overextended (Overbought/Oversold).
Signal Generation:
- Reversion Signals: Generated when price breaches the Outer Bands and closes back inside. This suggests a "Snap-back" or Mean Reversion event.
- Trend Confirmation: The color of the baseline and the fill zones changes based on the slope of the Kernel, giving an instant visual read on market bias.
How to Use It
- Mean Reversion Strategy: Look for price action extending beyond the Outer Bands (Thinner lines). If price leaves a wick and closes back inside, it signals a high-probability reversal toward the Neural Baseline.
- Green Signal: Potential Long (Reversal from Lows).
- Red Signal: Potential Short (Reversal from Highs).
- Trend Following: Use the Neural Baseline (Thick Center Line) as a dynamic support/resistance level.
If price is holding above the baseline and the cloud is green, the trend is Bullish.
If price is holding below the baseline and the cloud is red, the trend is Bearish.
- Squeeze Detection: When the Inner and Outer bands compress significantly, it indicates low volatility and often precedes an explosive breakout.
Settings
- Lookback Window: Determines the depth of the Kernel analysis.
- Smoothness (Bandwidth): Higher values create a smoother baseline (better for trends), while lower values make it more reactive (better for scalping).
- Regression Alpha: Controls the weight distribution of the Kernel.
- Channel Multipliers: Adjust the width of the Inner and Outer bands to fit your specific asset's volatility profile. Indicador

Adaptive Nadaraya-Watson (Non Repainting) [Metrify]To understand this implementation of the Nadaraya-Watson estimator, we have to look at the core equation governing non-parametric regression. This script aren't trying to average prices; we are trying to find the probability density of where price should be relative to its recent history.
1. The Kernel Physics (Bandwidth Modulation)
In standard kernel regression, you have a bandwidth parameter (h). This controls the "smoothness" of the curve. If h is too low, the curve jitters with every tick of noise. If h is too high, it acts like a sluggish SMA.
A static h fails because market volatility is dynamic. When the market explodes (high volatility), a tight bandwidth generates false signals. When the market sleeps, a wide bandwidth misses the micro-trends.
It try solving this by making h a function of the Asset's volatility ratio:
heff=h×max(0.5,min(SMA(ATR20,100)ATR20,2.0))
If the current ATR(20) is double the long-term average (100), the bandwidth doubles. This forces the estimator to "zoom out" during chaos, effectively ignoring noise that would otherwise look like a reversal.
vol_ratio = use_vol ? vol_raw / (vol_base == 0 ? 1 : vol_base) : 1.0
vol_mod = math.max(0.5, math.min(vol_ratio, 2.0))
h_eff = h_val * vol_mod
2. The Gaussian Loop (Endpoint Estimation)
Standard Nadaraya-Watson scripts repaint because they calculate the regression over a full window centered on the bar. To make this usable for live trading, we must calculate the Endpoint Estimate.
We iterate backward from the current bar (i=0) to the lookback limit. For every historical price Xi, we calculate a weight wi based on how far away it is in time (distance).
The weight is derived from the Gaussian Kernel function:
wi=exp(−2heff2i2)
Price data closer to the current bar (i=0) gets a weight near 1.0. Data further away (i=50) decays exponentially toward 0.
for i = 0 to lookback by 1
float dist = float(i)
float w = math.exp(-math.pow(dist, 2) / (2 * math.pow(h_eff, 2)))
num := num + w * src
den := den + w
3. Statistical Deviation (MAE vs. StDev)
Most Bollinger Band-style indicators use Standard Deviation (Root Mean Square). The problem with StDev is that it squares the errors, which heavily penalizes large outliers. In crypto or volatile forex pairs, one wick can blow out the bands for 20 bars.
This one use Mean Absolute Error (MAE) instead.
MAE=N1∑∣Price−y^∣
MAE is linear. It measures the average distance price strays from the kernel estimate without squaring the penalty. This creates "tighter" bands that adhere closer to price action during normal trend behavior but don't expand ridiculously during a flash crash.
Pine Script
float error = math.abs(src - y_hat)
float mae = ta.sma(error, lookback)
We project two sets of bands:
Inner Band (Balanced): The "Noise Zone". Price inside here is considered random walk.
Outer Band (Precision): The "Exhaustion Zone". Price reaching here is statistically unlikely (2.8x MAE).
Input & Visual Summary
Kernel Physics:
h_val: The base smoothness. Lower (e.g., 6) = faster, noisier. Higher (e.g., 10) = slower, smoother.
use_vol: Keep this TRUE. It prevents the bands from being too tight during news events.
Envelope Statistics:
mult_in / mult_out: These are your risk settings. 1.5/2.8 is a standard deviation-like setting suited for MAE.
Indicador

Indicador
