ZenAlgo - DojiOverview
This indicator identifies Doji candles and adds two contextual filters before creating an alert: a relative volume expansion filter and a normalized directional-shift filter. Most Doji indicators simply detect candle shape. This script instead adds contextual conditions so that alerts appear only when the Doji occurs together with increased participation and a change in short-term directional pressure.
Doji candles appear frequently on their own, so the script focuses on situations where candle balance, elevated activity, and a directional shift occur at the same time.
How the indicator works
The script begins by evaluating candle structure. It measures the full candle range, the size of the body, and the size of the upper and lower wicks relative to the entire candle. A candle is considered a Doji when the body occupies only a small portion of the range.
After identifying the base Doji structure, the candle is classified into one of several common Doji types depending on the relative size of the wicks:
Dragonfly Doji – very small upper wick and long lower wick.
Gravestone Doji – very small lower wick and long upper wick.
Long-legged Doji – both wicks are relatively long.
Standard Doji – small body without the extreme wick proportions of the other types.
A Doji indicates that price moved during the bar but finished close to the opening level, suggesting temporary balance between buyers and sellers.
Volume context (PVSRA-style comparison)
After the candle structure is detected, the script evaluates trading activity.
Current volume is compared with the average volume over a recent lookback window. If current volume exceeds that average by a configurable multiple, the candle is considered to occur during elevated participation.
This step is important because a Doji formed during low activity may simply reflect quiet trading, while a Doji formed during higher participation means more trading occurred but the candle still closed near equilibrium.
Normalized price-change proxy
The script then evaluates short-term directional behavior.
It measures the percentage change between consecutive closing prices. This series is smoothed to reduce noise and then normalized relative to recent behavior. The normalization allows the script to determine whether the current directional movement is unusually positive or negative compared with recent activity.
The script compares this normalized value with the previous bar. An alert requires the value to change sign between the two bars, which indicates that the short-term directional pressure has flipped.
Why the components are combined
Each component describes a different aspect of market behavior:
The Doji describes temporary balance inside a candle.
The volume comparison measures whether that balance occurred during elevated participation.
The directional flip indicates a shift in short-term pressure.
Basic Doji markers highlight every small-body candle. This indicator is more selective because it only highlights cases where equilibrium, participation, and directional change appear together.
Final alert logic
An alert is created when the following conditions occur simultaneously:
A Doji is present on the current candle or the previous candle.
Volume exceeds the recent average by the configured multiple when the volume filter is enabled.
The normalized directional reading flips sign between two consecutive bars.
Alerts are separated into bullish and bearish categories according to the direction of the normalized reading after the flip.
How to interpret the alerts
A bullish alert means the script detected a Doji context with elevated volume and a positive directional flip.
A bearish alert means the same conditions occurred with a negative directional flip.
The alert marks a moment where price equilibrium, increased participation, and directional change appeared together. These conditions may appear near short-term transitions, pauses, or local turning points.
How to use the indicator
This indicator is intended as a contextual chart tool rather than a standalone trading system.
Use alerts to locate Doji candles confirmed by participation and directional change.
Interpret bullish alerts as possible upward transitions and bearish alerts as possible downward transitions.
Evaluate the alert location relative to support, resistance, or recent trend structure.
Combine the alerts with other analysis tools or higher timeframe context.
Why Heikin Ashi often works well
The script can be used on any chart type, but Doji detection often becomes clearer on Heikin Ashi candles.
Heikin Ashi candles smooth short-term price fluctuations by averaging values from multiple bars. Because the indicator relies on candle body and wick proportions, this smoothing reduces small random Doji created by short-term noise and produces clearer candle structures.
Limitations
Doji candles occur frequently and do not inherently indicate reversals.
Volume filters depend on the quality and meaning of the exchange’s volume data.
The directional proxy is based on price changes rather than direct order flow.
Different markets, timeframes, and preset settings can change how often alerts appear.
The indicator highlights situations where candle equilibrium, elevated participation, and directional change appear together, but it does not determine future price direction. Indicador

Indicador

Inducement [UAlgo]Inducement is a market structure tool designed to detect pullback liquidity levels that form during directional expansion and remain relevant until price comes back to sweep them. The script tracks directional legs, monitors the deepest retracement points that appear against the active move, and promotes those retracement extremes into active IDM levels once the trend resumes in the original direction.
The core idea is simple. During a bullish move, price often creates a temporary downside pullback before continuing upward. That pullback low can later act as an inducement point where liquidity rests below the market. In a bearish move, the opposite process happens, where an upside pullback forms before price continues lower. That pullback high can later become a bearish inducement point. This script automates that process and keeps those levels visible on the chart until they are eventually swept.
What makes the script useful is that it does not plot every fluctuation. It first filters out inside bars, tracks the active directional leg, records the most meaningful retracement extreme inside that leg, and only creates a new IDM when price resumes the main move by printing a fresh expansion. That makes the final levels cleaner and more structurally relevant.
Once an IDM is created, it is drawn as a horizontal reference with a label. If price later trades through that level, the script marks it as swept, updates the label, and changes the line style to reflect that the liquidity has been taken. This creates a very practical chart view for traders who want to monitor inducement behavior, liquidity sweeps, and the relationship between pullbacks and later price delivery.
🔹 Features
🔸 Directional Leg Tracking
The script maintains an internal bullish or bearish trend state and updates the active structural leg as price continues to expand. This gives the indicator a directional framework instead of treating each new bar independently.
🔸 Inside Bar Filtering
Inside bars are ignored for structural progression. This helps the script focus on meaningful range expansion rather than reacting to small compressive candles that do not add new directional information.
🔸 Pullback Extreme Detection
During a bullish leg, the script tracks the lowest downside pullback that forms before the next bullish expansion. During a bearish leg, it tracks the highest upside pullback before the next bearish expansion. These stored extremes are the raw candidates for inducement levels.
🔸 Automatic IDM Creation
A stored pullback extreme becomes an active IDM only when the market resumes the active leg and creates a fresh structural push. This means the indicator does not mark every retracement immediately. It waits for continuation confirmation.
🔸 Bullish and Bearish IDM Mapping
Bullish IDM levels are created from pullback lows inside bullish continuation.
Bearish IDM levels are created from pullback highs inside bearish continuation.
This gives the user a clean map of likely liquidity resting points below or above price.
🔸 Sweep Recognition
Once an IDM is active, the script checks every new bar to see whether price has swept it. Bullish IDM is considered swept when current low trades at or below the level. Bearish IDM is considered swept when current high trades at or above the level.
🔸 Live Visual State Changes
Active IDM levels are drawn with dashed lines and labeled as unswept. Once swept, the line style changes, the color becomes softer, and the label updates to show that the liquidity event has already occurred.
🔸 Lightweight Structure Display
The script keeps an internal array of active IDM levels and limits the array size to avoid uncontrolled growth. This keeps the display practical and suitable for live chart use.
🔹 Calculations
1) Defining the IDM Object
type InducementLevel
float price
int bIndex
int dir
line idmLine
label idmLabel
bool isSwept
This is the core data container used by the script.
Each inducement level stores:
its price,
the bar index where it originated,
its direction,
its line object,
its label object,
and whether it has already been swept.
The dir field controls the level type:
1 means bullish IDM
-1 means bearish IDM
So before any logic runs, the script already has a dedicated structure for tracking the full lifecycle of each inducement level from creation to sweep.
2) Drawing Active and Swept Levels
method draw(InducementLevel this, color c_bull, color c_bear) =>
color c = this.dir == 1 ? c_bull : c_bear
string txt = this.isSwept ? "IDM ✓" : "IDM ✗"
if na(this.idmLine)
this.idmLine := line.new(this.bIndex, this.price, bar_index, this.price, color=c, style=line.style_dashed)
else if not this.isSwept
this.idmLine.set_x2(bar_index)
if na(this.idmLabel)
this.idmLabel := label.new(bar_index, this.price, txt, style=label.style_none, textcolor=c, size=size.small, textalign=text.align_left)
else if not this.isSwept
this.idmLabel.set_x(bar_index)
this
This method is responsible for visualizing each inducement level.
First, it selects the correct color according to direction. Bullish levels use the bullish color input, and bearish levels use the bearish color input. Then it builds a text state:
"IDM ✗" means the level is still active and not yet swept.
"IDM ✓" means the level has already been swept.
If the line does not exist yet, the script creates a dashed horizontal line starting from the level’s origin bar to the current bar. If the line already exists and the level is still unswept, the line is extended to the latest bar.
The label follows the same logic. If no label exists, it is created. If the label already exists and the level is still active, its position is moved to the latest bar.
So visually, each active IDM behaves like a live horizontal liquidity reference that extends forward until price takes it.
3) Detecting Liquidity Sweeps
method checkSweep(InducementLevel this, float currLow, float currHigh, color c_bull, color c_bear) =>
if not this.isSwept
swept = false
if this.dir == 1 and currLow <= this.price
swept := true
else if this.dir == -1 and currHigh >= this.price
swept := true
This method determines whether an existing inducement level has been taken.
The logic is direction specific.
For bullish IDM:
if the current low trades at or below the level price, the level is considered swept.
For bearish IDM:
if the current high trades at or above the level price, the level is considered swept.
This matches the structural idea behind inducement. A bullish pullback low represents liquidity resting below price, and that liquidity is considered taken once price trades through it. A bearish pullback high represents liquidity resting above price, and that liquidity is considered taken once price pushes through it.
So this method is the event detector that turns an active liquidity level into a completed liquidity event.
4) Updating the Visual State After a Sweep
if swept
this.isSwept := true
color c = this.dir == 1 ? color.new(c_bull, 50) : color.new(c_bear, 50)
this.idmLine.set_color(c)
this.idmLine.set_style(line.style_dotted)
this.idmLine.set_x2(bar_index)
this.idmLabel.set_text("IDM ✓")
this.idmLabel.set_textcolor(c)
this.idmLabel.set_x(bar_index)
Once a sweep happens, the script changes both the internal state and the visual appearance.
The level is marked as swept with this.isSwept := true .
Then the line color becomes softer by applying transparency.
The line style changes from dashed to dotted.
The label text changes from IDM ✗ to IDM ✓ .
This is useful because it preserves the historical location of the inducement while also showing that the level is no longer pending. In other words, the chart keeps the context but changes the state.
5) Filtering Out Inside Bars
var float mHigh = high
var float mLow = low
bool isInside = high <= mHigh and low >= mLow
This small block is more important than it looks.
The script stores a reference range using mHigh and mLow . A bar is considered inside if its high is less than or equal to the stored high and its low is greater than or equal to the stored low.
In simple terms, an inside bar is a bar that remains contained within the prior meaningful structure range. The script ignores those bars for the purpose of leg progression.
This helps reduce noise because inside bars usually reflect compression rather than new structural information. By ignoring them, the indicator focuses on actual range expansion and meaningful pullback development.
6) Tracking Trend State and Leg Extremes
var int trend = 1
var float legHigh = high
var float legLow = low
var float pullbackLow = na
var int pullbackLowBar = na
var float pullbackHigh = na
var int pullbackHighBar = na
This block defines the internal market structure memory.
trend stores whether the script currently sees the market as bullish or bearish.
legHigh and legLow track the active structural extreme of the current leg.
pullbackLow and pullbackHigh store the most important retracement extreme that forms against the current trend.
So the script is always tracking two things at once:
the direction of the main move,
and the deepest retracement against that move.
That retracement extreme later becomes the candidate IDM if price resumes the original direction.
7) Bullish Leg Logic and Bullish IDM Creation
if trend == 1
if high > legHigh
if not na(pullbackLow)
activeIDMs.push(InducementLevel.new(pullbackLow, pullbackLowBar, 1, na, na, false))
pullbackLow := na
legHigh := high
else if brokeLow
if na(pullbackLow) or low < pullbackLow
pullbackLow := low
pullbackLowBar := bar_index
This is the heart of bullish inducement detection.
When the script is in bullish mode, it watches for two types of events.
First, if price makes a new leg high:
high > legHigh
That means bullish continuation has occurred. If a downside pullback low had been stored before this continuation, the script converts that pullback low into a new bullish IDM by pushing it into the active array.
That is the crucial idea:
the pullback low becomes inducement only after price proves continuation by printing a fresh high.
Second, if the current bar breaks below the stored micro range low:
brokeLow
Then the script updates pullbackLow if this new low is deeper than the previously stored pullback. This allows the script to keep tracking the deepest retracement inside the bullish leg until continuation happens.
So bullish IDM is created from the most meaningful downside retracement that occurs before the next bullish expansion.
8) Bearish Leg Logic and Bearish IDM Creation
else if trend == -1
if low < legLow
if not na(pullbackHigh)
activeIDMs.push(InducementLevel.new(pullbackHigh, pullbackHighBar, -1, na, na, false))
pullbackHigh := na
legLow := low
else if brokeHigh
if na(pullbackHigh) or high > pullbackHigh
pullbackHigh := high
pullbackHighBar := bar_index
This is the mirror image of the bullish logic.
When the script is in bearish mode, it waits for a new leg low:
low < legLow
If that happens and a prior upside pullback high was stored, the script converts that pullback high into a bearish IDM. This marks the retracement high as a future liquidity point above price.
If price does not yet continue lower but instead breaks upward inside the local structure:
brokeHigh
Then the script updates pullbackHigh if the new high is greater than the previously stored retracement high.
So bearish IDM is created from the strongest upside retracement that forms before the next bearish continuation.
9) Detecting Trend Reversal and Resetting the Pullback Memory
if low < legLow
trend := -1
legLow := low
pullbackLow := na
pullbackHigh := na
if high > legHigh
trend := 1
legHigh := high
pullbackHigh := na
pullbackLow := na
These blocks handle directional flips.
Inside bullish mode, if price breaks below the active leg low, the script changes its internal state to bearish.
Inside bearish mode, if price breaks above the active leg high, the script changes its internal state to bullish.
Whenever the trend flips, the stored pullback variables are cleared. That is important because retracement data from the old trend should not be reused after the market has structurally changed direction.
So the script always keeps its inducement logic aligned with the current structural leg rather than mixing information from opposite phases.
10) Updating the Reference Range After a Non Inside Bar
if not isInside
bool brokeLow = low < mLow
bool brokeHigh = high > mHigh
mHigh := high
mLow := low
This block updates the structure reference only when the current bar is not an inside bar.
Before resetting the reference range, the script checks whether the current bar expanded below the stored low or above the stored high. Those two booleans are then used in the bullish and bearish logic to decide whether the move represents pullback development or continuation.
After those checks are done, the reference high and low are updated to the current bar’s high and low.
So mHigh and mLow act like a rolling structural filter that helps the script ignore internal compression and focus on meaningful range expansion.
11) Managing All Active IDM Levels on Every Bar
if activeIDMs.size() > 0
for i = 0 to activeIDMs.size() - 1
idm = activeIDMs.get(i)
idm.checkSweep(low, high, colorBullIDM, colorBearIDM)
idm.draw(colorBullIDM, colorBearIDM)
This is the execution loop for all stored inducement levels.
On every bar, the script goes through each active IDM and does two things:
it checks whether the level has now been swept,
and it redraws or updates the level on the chart.
This means every stored level remains live and state aware. Unswept levels keep extending forward, while swept levels lock their appearance into a completed state.
So the script is always balancing two layers:
new IDM creation from ongoing structure,
and lifecycle management of previously created levels.
12) Limiting the Number of Stored Levels
if activeIDMs.size() > 50
activeIDMs.shift()
This last block keeps the internal IDM array from growing indefinitely.
If more than fifty inducement levels are stored, the oldest one is removed from the array. This helps keep memory usage under control and makes the indicator more practical for ongoing chart use.
The purpose here is not analytical. It is purely operational. The script limits historical storage so the active structure set remains manageable. Indicador

Indicador

Indicador

Indicador

Indicador

LOWESS Reversal & Continuation [UAlgo]LOWESS Reversal & Continuation is a trend sensitive signal indicator built around a local LOWESS style smoothing engine that adapts to both price structure and volatility. Its core objective is to separate meaningful directional shifts from routine market noise by combining smoothed trend estimation, ATR normalized slope analysis, acceleration filtering, and disciplined signal gating.
Instead of relying on a conventional moving average crossover model, the script fits a locally weighted regression over a rolling window of recent bars. This produces a smoother and more context aware estimate of price direction, while still reacting fast enough to identify emerging reversals and pullback continuation opportunities. Because the estimate is local and weighted, recent bars have greater influence than distant bars, which helps the line remain relevant to current market conditions.
The indicator classifies signals into two practical categories. Reversal signals aim to identify transitions where directional pressure flips from negative to positive, or from positive to negative. Continuation signals aim to identify pullback resumption behavior inside an already established directional regime. This makes the script suitable for traders who want a single tool that can highlight both early trend change candidates and trend following re entry points.
To improve robustness, the script also supports optional robust weighting passes. These passes reduce the influence of outlier bars on the LOWESS fit, which is especially useful during abnormal spikes, illiquid conditions, or isolated volatility shocks. In addition, all slope readings are normalized by ATR, allowing the trend filter to scale more consistently across instruments, timeframes, and volatility regimes.
From a workflow perspective, the script is designed for clean chart usage. It colors the LOWESS line according to directional bias, draws an adaptive ATR based band around the curve, supports optional signal labels, limits on chart label clutter through an internal object manager, and provides alert conditions for all signal classes. The result is a visually compact but analytically rich framework for tracking trend reversals and continuation setups in real time.
🔹 Features
🔸 LOWESS Style Local Trend Estimation
The heart of the script is a locally weighted linear regression model applied over a rolling lookback window. Each bar inside the window receives a distance based weight, meaning bars closer to the current bar have a larger impact on the estimate. This produces a smooth trend line that is more adaptive than many standard moving average techniques and better suited for identifying subtle turning points.
🔸 Optional Robust Regression Passes
The indicator can apply additional robust weighting iterations after the initial fit. Residuals are measured relative to the first regression pass, and bars with unusually large residuals receive progressively lower influence in later passes. This reduces distortion from extreme candles and helps the LOWESS curve remain stable during irregular price events.
🔸 ATR Normalized Slope Filter
The script does not use raw slope in isolation. Instead, the LOWESS slope is divided by ATR, creating a volatility adjusted slope metric. This makes the directional threshold more portable across markets and timeframes. A slope that may be meaningful on a slow instrument can be very different on a high volatility asset, so ATR normalization creates a more balanced regime filter.
🔸 Reversal Signal Detection
Bullish and bearish reversal signals are triggered when the ATR normalized slope crosses the zero line and is confirmed by directional acceleration and price location relative to the LOWESS line. In other words, the script looks for a meaningful change in smoothed directional pressure, not simply a visual bend in the curve. This makes reversal signals more selective and better aligned with structural momentum shifts.
🔸 Continuation Signal Detection
Continuation logic is designed to capture trend resumption after a pullback. The script first requires an established directional regime, then checks whether price recently interacted with the LOWESS line, and finally waits for price to reclaim the trend direction with positive confirming acceleration. This helps distinguish genuine continuation behavior from random sideways oscillation around the curve.
🔸 Pullback Validation Window
A dedicated pullback lookback parameter ensures that continuation signals only occur when price has interacted with the LOWESS line within a recent number of bars. This prevents stale continuation triggers and keeps the setup focused on recent retracement behavior rather than distant historical interactions.
🔸 Close Confirmation Option
Signals can be gated so they only become valid after bar close. This is useful for traders who want to avoid intrabar flicker and premature triggers on live candles. When disabled, the script can respond more aggressively in real time, which may suit faster execution styles.
🔸 Signal Cooldown Logic
To reduce repetitive clustering, the indicator tracks the last occurrence of each signal type and imposes a cooldown period before another signal of the same class can be printed. Separate cooldown tracking is maintained for bullish reversals, bearish reversals, bullish continuations, and bearish continuations.
🔸 Adaptive ATR Band
An optional ATR based band can be plotted around the LOWESS line. This band provides a visual sense of dynamic range around the smoothed path and can help contextualize whether price is moving in a relatively stretched or balanced position around the trend estimate.
🔸 Directional Visual Coloring
The LOWESS curve changes color according to directional bias derived from the ATR normalized slope. This gives the user an immediate visual read on whether the smoothed trend pressure is currently positive, negative, or unavailable due to insufficient historical data.
🔸 Lightweight Label Management
When signal labels are enabled, the script uses an internal label book to store and manage plotted objects. Older labels are automatically deleted once the configured maximum is exceeded, helping keep the chart readable and preventing uncontrolled label buildup.
🔸 Full Alert Support
Alert conditions are included for all four event classes:
Bullish LOWESS Reversal
Bearish LOWESS Reversal
Bullish LOWESS Continuation
Bearish LOWESS Continuation
This allows the script to be used not only as a visual analysis tool, but also as an event driven signal framework for scanning and real time notification workflows.
🔹 Calculations
1) Rolling LOWESS Window Construction
For every bar, the script loads the most recent length values of the selected source into an internal rolling window. This window becomes the data sample used for the local regression fit.
method loadWindow(LowessEngine this, float seriesValue) =>
for i = 0 to this.length - 1
array.set(this.y, i, seriesValue )
Interpretation:
The regression is always fit on the latest rolling block of data.
The rightmost point in the window corresponds to the current estimation point.
This makes the smoothing local rather than global.
2) Distance Based LOWESS Weights
The script uses a tricube kernel to assign weights based on each point’s distance from the current bar inside the regression window. Bars nearer to the most recent observation receive a larger weight, while distant bars contribute less.
method buildDistanceWeights(LowessEngine this, int spanBars) =>
int x0 = this.length - 1
float bandwidth = math.max(spanBars, 1)
for i = 0 to this.length - 1
float u = math.abs(i - x0) / bandwidth
float w = u < 1 ? math.pow(1 - math.pow(u, 3), 3) : 0.0
array.set(this.baseW, i, w)
Interpretation of the conditions:
x0 is the current evaluation point inside the rolling window.
u is normalized distance from each historical point to the current point.
The tricube weight decays smoothly as distance increases.
Bars outside the effective span receive zero weight.
This is what gives the LOWESS fit its local character and helps it stay focused on recent structure.
3) Weighted Local Linear Regression
After weights are built, the script solves a weighted linear regression over the local window. The output is a local intercept and local slope. The final LOWESS estimate is the fitted value at the most recent point in the sample.
method solveWeightedLinear(LowessEngine this, array weights) =>
float s0 = 0.0
float s1 = 0.0
float s2 = 0.0
float t0 = 0.0
float t1 = 0.0
for i = 0 to this.length - 1
float w = array.get(weights, i)
float x = array.get(this.x, i)
float y = array.get(this.y, i)
s0 += w
s1 += w * x
s2 += w * x * x
t0 += w * y
t1 += w * x * y
float den = s0 * s2 - s1 * s1
if s0 <= 1e-10 or math.abs(den) <= 1e-10
this.slope := 0.0
this.intercept := array.get(this.y, this.length - 1)
else
this.slope := (s0 * t1 - s1 * t0) / den
this.intercept := (t0 - this.slope * s1) / s0
float x0 = this.length - 1
this.yhat := this.intercept + this.slope * x0
Interpretation:
this.slope measures the local directional gradient of the LOWESS fit.
this.yhat is the current LOWESS value plotted on the chart.
If the weighted regression becomes numerically unstable, the script falls back to a flat slope and uses the latest source value as intercept.
4) Robust Reweighting Passes
To reduce the impact of outliers, the script can run additional robust passes after the initial fit. It first calculates the absolute residual of each point relative to the fitted line, then computes a median based scale estimate, and finally applies a bisquare style robust weighting function.
method updateRobustWeights(LowessEngine this) =>
for i = 0 to this.length - 1
float xi = array.get(this.x, i)
float yi = array.get(this.y, i)
float fit = this.intercept + this.slope * xi
array.set(this.residualAbs, i, math.abs(yi - fit))
float med = this.residualAbs.median()
float scale = med * 6.0
if na(scale) or scale <= 1e-10
for i = 0 to this.length - 1
array.set(this.robustW, i, 1.0)
else
for i = 0 to this.length - 1
float u = array.get(this.residualAbs, i) / scale
float rw = u < 1 ? math.pow(1 - math.pow(u, 2), 2) : 0.0
array.set(this.robustW, i, rw)
Interpretation:
Large residual bars are treated as less trustworthy observations.
The median residual acts as a robust scale anchor.
Higher residuals receive smaller robust weights in subsequent fits.
This improves stability during abnormal spikes and irregular candles.
5) ATR Normalized Slope and Acceleration
Once the LOWESS fit is complete, the script converts raw slope into a volatility aware slope by dividing it by ATR. It also computes a first-difference style acceleration term to measure whether directional pressure is strengthening or weakening.
float slopeAtr = not na(slope) and atr > 0 ? slope / atr : na
float accelAtr = slopeAtr - nz(slopeAtr )
Interpretation:
slopeAtr expresses trend slope in ATR units.
accelAtr measures change in normalized slope from one bar to the next.
Positive acceleration supports bullish developments.
Negative acceleration supports bearish developments.
This combination helps the script distinguish a genuine regime shift from a weak or decaying slope condition.
6) Directional Regime Classification
The script uses a user defined ATR normalized threshold to determine whether the current smoothed state qualifies as a bullish or bearish directional regime.
bool upRegime = not na(slopeAtr) and slopeAtr > slopeThreshold
bool downRegime = not na(slopeAtr) and slopeAtr < -slopeThreshold
Interpretation:
A positive but very small slope is not automatically treated as a valid uptrend.
A negative but very small slope is not automatically treated as a valid downtrend.
The threshold acts as a noise filter that requires the trend estimate to have enough magnitude before continuation logic becomes eligible.
7) Pullback Detection Relative to LOWESS
Continuation signals depend on recent interaction with the LOWESS line. The script checks how many bars have passed since price moved through the LOWESS curve in the opposite direction of the active regime.
int bullPbBars = int(nz(ta.barssince(low < lowess), 100000))
int bearPbBars = int(nz(ta.barssince(high > lowess), 100000))
bool bullPullbackRecent = bullPbBars <= pullbackLookback
bool bearPullbackRecent = bearPbBars <= pullbackLookback
Interpretation:
In a bullish regime, price must have recently dipped below the LOWESS line to qualify as a pullback.
In a bearish regime, price must have recently pushed above the LOWESS line to qualify as a pullback.
The pullbackLookback parameter controls how recent that interaction must be.
8) Reversal Signal Logic
Bullish and bearish reversal signals are built from zero line slope crossings, directional acceleration, and price confirmation relative to the LOWESS curve.
bool slopeCrossUp = ta.crossover(slopeAtr, 0)
bool slopeCrossDown = ta.crossunder(slopeAtr, 0)
bool bullRevRaw = enoughBars and slopeCrossUp and accelAtr > 0 and close > lowess
bool bearRevRaw = enoughBars and slopeCrossDown and accelAtr < 0 and close < lowess
Interpretation of the bullish reversal conditions:
slopeCrossUp means the normalized LOWESS slope has crossed from negative to positive.
accelAtr > 0 means the slope is improving, not merely touching zero.
close > lowess confirms that price is positioned above the smoothed trend estimate.
Interpretation of the bearish reversal conditions:
slopeCrossDown means the normalized LOWESS slope has crossed from positive to negative.
accelAtr < 0 confirms weakening trend pressure.
close < lowess confirms price is positioned below the LOWESS line.
This makes reversal signals more selective than a simple moving average crossover style event.
9) Continuation Signal Logic
Continuation signals are only allowed when a directional regime already exists, a recent pullback has occurred, price crosses back through the LOWESS line in trend direction, and acceleration confirms that the move is regaining strength.
bool priceCrossUp = ta.crossover(close, lowess)
bool priceCrossDown = ta.crossunder(close, lowess)
bool bullContRaw = enoughBars and upRegime and bullPullbackRecent and priceCrossUp and accelAtr > 0 and not bullRevRaw
bool bearContRaw = enoughBars and downRegime and bearPullbackRecent and priceCrossDown and accelAtr < 0 and not bearRevRaw
Interpretation of the bullish continuation conditions:
The LOWESS slope must already define an uptrend regime.
Price must have recently pulled back below the LOWESS line.
Price must cross back above the LOWESS line.
Acceleration must be positive.
A reversal signal takes priority, so continuation does not print if the same bar qualifies as a bullish reversal.
Interpretation of the bearish continuation conditions is the exact inverse.
10) Close Confirmation and Cooldown Control
The final signal is gated by an optional bar close confirmation and a per-signal cooldown filter.
bool gate = confirmClose ? barstate.isconfirmed : true
bool bullRev = gate and bullRevRaw and canBullRev(signalState, cooldownBars)
bool bearRev = gate and bearRevRaw and canBearRev(signalState, cooldownBars)
bool bullCont = gate and bullContRaw and canBullCont(signalState, cooldownBars)
bool bearCont = gate and bearContRaw and canBearCont(signalState, cooldownBars)
Interpretation:
When close confirmation is enabled, signals only become valid after the candle is closed.
Cooldown logic prevents repeated printing of the same signal class within a short number of bars.
This reduces visual clutter and avoids excessive re-triggering during choppy conditions.
11) Adaptive Band Construction
The script can draw an ATR-based envelope around the LOWESS line to provide volatility context.
float upperBand = showBand and not na(lowess) ? lowess + atr * bandAtrMult : na
float lowerBand = showBand and not na(lowess) ? lowess - atr * bandAtrMult : na
Interpretation:
The band expands and contracts with ATR.
This creates a dynamic visual frame around the LOWESS estimate.
It is not a signal by itself, but it helps contextualize the distance between current price and the smoothed trend path.
12) Visual Output and Alerts
The LOWESS line changes color according to slope direction, optional labels mark reversal and continuation events, and alert conditions are available for all four signal types.
alertcondition(bullRev, "Bullish LOWESS Reversal", "Bullish LOWESS reversal on {{ticker}}")
alertcondition(bearRev, "Bearish LOWESS Reversal", "Bearish LOWESS reversal on {{ticker}}")
alertcondition(bullCont, "Bullish LOWESS Continuation", "Bullish LOWESS continuation on {{ticker}}")
alertcondition(bearCont, "Bearish LOWESS Continuation", "Bearish LOWESS continuation on {{ticker}}")
In practical terms, this means the indicator can serve both as a visual discretionary analysis tool and as an alert driven framework for identifying smoothed trend reversals and pullback continuation opportunities with a volatility aware filter structure. Indicador

Hidden Markov Reversal Finder [UAlgo]Hidden Markov Reversal Finder is a regime aware reversal detection indicator that uses a compact 3 state Hidden Markov style filter with online adaptation to classify market conditions and highlight potential top and bottom rotations. The script models price behavior as transitions between three regimes:
- Bull Expansion
- Balance
- Bear Stress
Instead of running a heavy Baum Welch retraining loop, this version is designed as a lightweight real time filter. It updates regime probabilities using a transition matrix plus a two dimensional Gaussian emission model built from two normalized observations:
Return observation as a smoothed log return z score
Volatility observation as a realized volatility z score
The indicator runs in its own pane ( overlay=false ) but can optionally paint chart bars and place reversal labels on price using force overlay. It also includes a clean dashboard panel showing the current state, confidence, observation values, score, posterior probabilities, stretch, and the current setup classification.
The reversal engine is built around a top rotation and bottom rotation concept. It looks for a probability peak in a regime, then a fade from that peak, combined with momentum flip conditions and a stretch filter measured in ATR units relative to a baseline EMA. Signals are gated by a confidence threshold and a cooldown period to reduce repetitive prints.
This makes the indicator useful as a regime driven reversal framework that integrates:
State probabilities and confidence
Regime score and momentum flip
ATR based stretch extremes
Peak fade rotation logic
Clean visual markers and dashboard transparency
🔹 Features
🔸 1) Three Regime Model
The script uses three explicit regimes with distinct roles:
Bull Expansion, intended to represent positive drift conditions
Balance, intended to represent neutral or mixed drift
Bear Stress, intended to represent negative drift and higher stress conditions
Each regime has its own mean and variance assumptions for return and volatility, which are then adapted online.
🔸 2) Two Dimensional Observation System (Return and Volatility)
The model does not rely on only returns. It uses both:
A normalized return feature
A normalized volatility feature
This helps distinguish clean bullish trends from choppy balance periods, and balance periods from bearish stress regimes.
🔸 3) Transition Matrix with Persistence Controls
Users can control how sticky each regime is through persistence settings:
Bull persistence
Balance persistence
Bear persistence
The transition matrix is constructed so that most probability remains in the same regime, while the remainder flows into other regimes using asymmetric weights that reflect realistic behavior.
🔸 4) Real Time Bayesian Filter Update
Each bar, the model performs:
Prediction step using the transition matrix
Update step using Gaussian emissions
Posterior normalization
Active state selection by arg max
This produces a smooth probability based regime tracker suitable for live use.
🔸 5) Adaptation
After filtering, the model adapts its internal means and variances using a learning rate scaled by posterior responsibility. This allows the state distributions to slowly adjust to changing market conditions without full retraining.
This keeps the indicator responsive while still stable.
🔸 6) Regime Score Output
The main score line is:
Bull posterior minus Bear posterior
This produces a continuous signal that ranges between negative and positive values and functions as a regime tilt meter. A confidence ribbon is also plotted as an area band derived from the dominant posterior.
🔸 7) Confidence Gating and Visual Strength
Confidence is defined as the largest posterior probability among the three regimes. The script uses confidence to:
Gate reversal signals
Determine bar tint transparency when bar coloring is enabled
Decide whether state shift tags should be printed
This reduces noise during low clarity periods.
🔸 8) Rotation Style Reversal Engine
The reversal finder is built on rotation logic:
A top rotation occurs after a Bull probability peak fades while Bear probability begins to rise
A bottom rotation occurs after a Bear probability peak fades while Bull probability begins to rise
This is a probabilistic rotation concept rather than a simple oscillator crossover.
🔸 9) Momentum Flip Confirmation
Signals require momentum confirmation through:
Regime score change direction
Return observation crossing a flip threshold
This is designed to reduce premature top and bottom calls when the regime probabilities shift but price momentum has not actually flipped.
🔸 10) ATR Based Stretch Filter
The script computes stretch as distance from an EMA baseline measured in ATR units. Signals require:
Top signals only when stretch is above a positive threshold
Bottom signals only when stretch is below a negative threshold
This ensures reversal signals occur when price is extended, not when it is near equilibrium.
🔸 11) Cooldown Control
A cooldown setting prevents consecutive buy or sell reversal signals from printing too frequently. This is especially useful when the market chops around an extreme and repeatedly triggers partial rotation conditions.
🔸 12) Dashboard Panel
A table dashboard displays key information on the last bar:
Active state name
Confidence
Return z score and volatility z score
Regime score
Posterior probabilities
Stretch in ATR units
Current setup text such as BUY REVERSAL, SELL REVERSAL, TOP WATCH, BOTTOM WATCH, WAIT
This makes the indicator transparent and easy to interpret.
🔸 13) State Tags and Reversal Labels on Chart
When enabled, the script prints:
State tags such as BULL, BASE, BEAR with arrows
Reversal markers with a vertical guide line and bold letter B or S
Tooltips include confidence, peak probability, stretch, and current posterior probabilities.
🔸 14) Optional Probability Curves and Bar Coloring
Users can toggle:
State probability plots
Signal markers and dots
Dashboard visibility
State tag visibility
Bar coloring by regime with confidence adjusted transparency
This makes the indicator adaptable for minimalist or fully informational workflows.
🔹 Calculations
1) Return Observation Construction
The script uses log returns:
float logReturn = math.log(close / nz(close , close))
It smooths return with an EMA:
float smoothedReturn = ta.ema(logReturn, returnSmoothLength)
Then normalizes by the return standard deviation:
float returnStdev = math.max(nz(ta.stdev(logReturn, returnZLength), EPS), EPS)
float returnObs = clampFloat(smoothedReturn / returnStdev, -obsClamp, obsClamp)
Interpretation:
Return observation is a clamped z score like feature, where positive values represent bullish return pressure and negative values represent bearish return pressure.
2) Volatility Observation Construction
Realized volatility is measured as the standard deviation of log returns:
float realizedVol = nz(ta.stdev(logReturn, volLength), EPS)
Then it is normalized relative to a baseline EMA and baseline standard deviation:
float volMean = nz(ta.ema(realizedVol, volBaselineLength), realizedVol)
float volStdev = math.max(nz(ta.stdev(realizedVol, volBaselineLength), EPS), EPS)
float volObs = clampFloat((realizedVol - volMean) / volStdev, -obsClamp, obsClamp)
Interpretation:
Volatility observation is a clamped z score like feature, where higher values indicate volatility expansion relative to baseline.
3) Warmup Logic
The model waits for enough history to compute stable normalized observations:
int warmupBars = math.max(returnZLength, volBaselineLength) + volLength
bool ready = bar_index > warmupBars and not na(returnObs) and not na(volObs)
Before ready, the script avoids producing live signals and uses the initial posterior distribution.
4) Transition Matrix Configuration
The transition matrix uses persistence values and asymmetric drift splits:
From Bull, most drift flows to Balance and a smaller portion to Bear
From Bear, most drift flows to Balance and a smaller portion to Bull
From Balance, drift splits evenly between Bull and Bear
Core setup:
this.setTransition(STATE_BULL, STATE_BALANCE, bullDrift * 0.78)
this.setTransition(STATE_BULL, STATE_BEAR, bullDrift * 0.22)
...
this.setTransition(STATE_BEAR, STATE_BALANCE, bearDrift * 0.78)
this.setTransition(STATE_BEAR, STATE_BULL, bearDrift * 0.22)
This design makes Balance act like a bridge regime and reduces unrealistic direct flip frequency.
5) Emission Model: 2D Gaussian Density
Each state computes an emission probability from return and volatility observations using a 2D Gaussian likelihood:
float exponent = -0.5 * ((retDeviation * retDeviation) / retVariance + (volDeviation * volDeviation) / volVariance)
float normalizer = 1.0 / (2.0 * math.pi * math.sqrt(retVariance * volVariance))
math.max(normalizer * math.exp(math.max(exponent, -24.0)), EPS)
Variances are floored at 0.12 to prevent collapse.
6) Prediction Step
The model predicts next probabilities using the transition matrix:
predictedProbability += posterior * transition(fromState, toState)
Then normalizes the predicted vector so it sums to 1.
7) Filter Update Step
The posterior is updated by multiplying predicted probabilities by emission likelihoods:
nextPosterior = predicted * emission(state, retObs, volObs)
Then normalized. The active state is the arg max of the posterior.
8) Online Adaptation
The model updates state means and variances using posterior responsibility times learning rate:
float responsibility = posterior * learningRate
Means update by moving toward the current observation:
nextMuRet = oldMuRet + responsibility * retError
nextMuVol = oldMuVol + responsibility * volError
Variances update toward squared error:
nextVarRet = oldVarRet + responsibility * (retError * retError - oldVarRet)
nextVarVol = oldVarVol + responsibility * (volError * volError - oldVarVol)
All parameters are clamped to stability ranges so the model does not explode.
9) Regime Score and Confidence
Score is defined as:
posterior - posterior
Confidence is the maximum posterior:
posterior
These values drive visuals and signal gating.
10) Stretch Calculation in ATR Units
Stretch uses an EMA basis of price and measures distance in ATR units:
float basis = ta.ema(close, stretchLength)
float atrValue = math.max(ta.atr(14), syminfo.mintick)
float stretch = (close - basis) / atrValue
Top stretch requires:
stretch >= stretchThreshold
Bottom stretch requires:
stretch <= -stretchThreshold
This ensures reversals occur when price is statistically extended relative to recent volatility.
11) Probability Peak and Fade Logic
The script measures recent peaks for bull and bear probabilities:
float bullPeak = ta.highest(bullProb , peakLookback)
float bearPeak = ta.highest(bearProb , peakLookback)
Fade is peak minus current:
bullFade = bullPeak - bullProb
bearFade = bearPeak - bearProb
Top rotation condition requires:
Bull peak above threshold
Bull fade above minimum
Bear probability rising
Bottom rotation requires the mirrored conditions.
This captures the idea of regime dominance peaking, then fading as the opposite side begins to regain influence.
12) Momentum Flip Confirmation
Momentum down requires:
Regime score decreasing
Return observation strongly negative below a flip threshold
Momentum up requires:
Regime score increasing
Return observation strongly positive above the flip threshold
This prevents signals when probabilities fade but momentum remains neutral.
13) Signal Gating and Cooldown
Signals require confidence above the threshold and a cooldown to avoid repeated triggers:
confidenceValue >= confidenceThreshold
bar_index - lastSignalBar > cooldownBars
14) Buy and Sell Reversal Signals
Buy reversal:
Bottom rotation
Momentum up
Bottom stretch
Confidence filter
Cooldown filter
Sell reversal:
Top rotation
Momentum down
Top stretch
Confidence filter
Cooldown filter
A Balance signal is also triggered when the state changes to Balance with sufficient confidence.
15) Visual Outputs
The indicator plots:
Regime score line with area fill around zero
Confidence ribbon as an area band
Optional posterior curves for Bull, Balance, Bear
Normalized stretch line scaled by the stretch threshold
Optional dots on the chart for reversal events
Optional bar coloring on the main chart
It also prints:
Reversal labels B and S with stretch, confidence, and peak probability tooltips
State tags on regime shifts
A dashboard panel summarizing live state and setup context Indicador

Gann Fan [UAlgo]Gann Fan is a structure driven Gann angle overlay that automatically builds a multi line fan from the most relevant recent swing anchor on the chart. Instead of requiring manual drawing, the script detects pivot highs and pivot lows, selects an active anchor based on the latest structure, and projects a full set of classic Gann style ratios from that anchor point.
The indicator runs directly on price and is designed to provide a clean visual map of potential dynamic support, resistance, and trend geometry. Once an anchor is chosen, the script draws a nine line fan that includes the key 1x1 line along with slower and faster angle ratios such as 1x8, 1x4, 1x3, 1x2, 2x1, 3x1, 4x1, and 8x1. These lines extend forward in time, creating a structured framework that traders can use for directional bias, reaction zones, and acceleration or deceleration analysis.
A major strength of this implementation is that it is not just a static angle pack. The script first builds an alternating pivot structure, filters same side pivots so only the more extreme one is retained, then automatically determines whether the active fan should be bullish or bearish when Auto mode is enabled. It also adds optional visual enhancements such as glow effects, filled fan zones between adjacent angles, angle labels, and an anchor label.
The result is a polished automatic Gann Fan tool focused on:
Recent swing structure
Auto or forced bullish / bearish direction
Multi angle projection
Visual zone segmentation
Clean right side angle labeling
🔹 Features
🔸 1) Automatic Gann Fan Projection
The script automatically draws a full Gann fan without requiring manual anchor placement. It detects recent pivots, determines the most relevant active anchor, and projects all fan angles from that point.
This makes it useful for traders who want a repeatable, rules based Gann framework rather than hand drawn discretionary lines.
🔸 2) Pivot Based Structural Anchoring
The fan is built from confirmed pivot highs and pivot lows using a configurable pivot strength setting. These pivots form the structural basis for the fan, so the projection adapts to actual swing development instead of arbitrary recent highs and lows.
🔸 3) Alternating Swing Logic for Cleaner Structure
The script does not blindly store every pivot. It enforces an alternating sequence of highs and lows:
If a new pivot is the same type as the most recent stored one, only the more extreme pivot is kept
If it is the opposite type, it is appended normally
This produces a cleaner swing map and avoids clutter from redundant same side pivots.
🔸 4) Auto, Bullish, or Bearish Fan Direction
Users can choose:
Auto mode
Forced Bullish
Forced Bearish
In Auto mode, the script decides direction based on which pivot type occurred most recently. This makes the fan respond naturally to the latest structural context.
🔸 5) Full Nine Angle Set
The indicator plots a broad set of classic Gann style ratios:
1x8
1x4
1x3
1x2
1x1
2x1
3x1
4x1
8x1
This creates a layered angle framework ranging from shallow to steep, with the 1x1 line visually emphasized as the main reference line.
🔸 6) Highlighted 1x1 Line
The 1x1 line receives its own dedicated width and stands out from the rest of the fan. This makes it easier to focus on the central balance angle that many traders treat as the most important Gann reference.
🔸 7) Optional Glow Effect
The script can render a wider translucent glow line beneath each fan line. This improves visibility, gives the fan a premium visual style, and helps the angle set stand out on busy charts.
🔸 8) Optional Fan Zones Between Angles
When enabled, the script fills the space between adjacent fan lines to create alternating fan zones. These colored bands make it easier to visually read the space between angles as active directional sectors.
This is especially useful when treating the fan as a dynamic channel structure rather than only a set of lines.
🔸 9) Right Side Angle Labels
Each fan angle can be labeled on the right side using the actual ratio name, such as 1x1 or 4x1 . The label position is user adjustable through the label shift setting.
This makes the fan immediately readable without needing to memorize line order.
🔸 10) Anchor Label Support
The script can place an anchor label at the origin point of the active fan, showing whether the current projection is bullish or bearish. This helps confirm which structural direction is currently active.
🔸 11) Customizable Line and Label Styling
Users can control:
Base line width
1x1 line width
Glow width
Label size
Label shift
Zone visibility
Glow visibility
Anchor label visibility
This makes the tool flexible for both minimalist and presentation focused layouts.
🔸 12) Structure Memory Control
The Max Stored Pivots setting controls how many swing points remain in memory. This helps the script stay efficient while still maintaining enough structural context for reliable anchor selection.
🔹 Calculations
1) Pivot Detection
The script identifies structural swing highs and lows using:
float ph = ta.pivothigh(high, pivotLen, pivotLen)
float pl = ta.pivotlow(low, pivotLen, pivotLen)
A pivot is only confirmed after pivotLen bars on both sides, so the stored pivot index is aligned to the actual pivot bar:
SwingPoint.new(bar_index - pivotLen, ph, true)
SwingPoint.new(bar_index - pivotLen, pl, false)
This ensures the fan anchor uses the true swing location, not the later confirmation bar.
2) Alternating Swing Storage
The script maintains a swing array that enforces alternating highs and lows:
if last.isHigh == candidate.isHigh
bool moreExtreme = (candidate.isHigh and candidate.price >= last.price) or (not candidate.isHigh and candidate.price <= last.price)
if moreExtreme
points.set(n - 1, candidate)
else
points.push(candidate)
Interpretation:
If two consecutive pivots are both highs, only the higher high is kept.
If two consecutive pivots are both lows, only the lower low is kept.
This keeps the swing structure cleaner and more meaningful.
3) Auto Direction Logic
In Auto mode, the script chooses bullish or bearish orientation based on which pivot type is most recent:
bool autoBull = not lastLow.isNa() and (lastHigh.isNa() or lastLow.idx > lastHigh.idx)
Interpretation:
If the latest valid pivot is a low, the script favors a bullish fan.
If the latest valid pivot is a high, the script favors a bearish fan.
The final direction can still be overridden by the Fan Direction input.
4) Bullish Anchor Construction
For a bullish fan, the script starts from the most recent low pivot:
SwingPoint lastLow = swings.lastPivot(false)
Then it looks for the most recent high pivot that occurred after that low:
SwingPoint ctrlHigh = swings.lastPivotAfter(true, lastLow.idx)
If such a high exists, it becomes the control point.
If not, the script uses the current bar and current high:
int x2 = ctrlHigh.isNa() ? bar_index : ctrlHigh.idx
float y2 = ctrlHigh.isNa() ? high : ctrlHigh.price
So the bullish fan is anchored from the latest significant low toward the next available structural high, or toward the live chart if that swing is still developing.
5) Bearish Anchor Construction
For a bearish fan, the script starts from the most recent high pivot:
SwingPoint lastHigh = swings.lastPivot(true)
Then it looks for the most recent low pivot that occurred after that high:
SwingPoint ctrlLow = swings.lastPivotAfter(false, lastHigh.idx)
If none is found yet, the script falls back to the current bar and current low:
int x2 = ctrlLow.isNa() ? bar_index : ctrlLow.idx
float y2 = ctrlLow.isNa() ? low : ctrlLow.price
So the bearish fan projects from the latest significant high toward the next structural low, or toward the live chart while the move is still unfolding.
6) Base Slope Calculation
Once the anchor is defined, the script computes the base slope between anchor point 1 and point 2:
(anchor.p2 - anchor.p1) / (anchor.idx2 - anchor.idx1)
This base slope is the reference slope used for the 1x1 line before applying the fan ratios.
7) Gann Ratio Projection
The script stores these ratios:
array.from(0.125, 0.25, 0.333333, 0.5, 1.0, 2.0, 3.0, 4.0, 8.0)
These correspond to:
1x8
1x4
1x3
1x2
1x1
2x1
3x1
4x1
8x1
For each ratio, the projected line value at any bar x is:
anchor.p1 + m * ratio * (x - anchor.idx1)
Where m is the base anchor slope.
This means:
Ratios below 1 create flatter angles than the base line
Ratio 1 creates the 1x1 line
Ratios above 1 create steeper angles than the base line
8) 1x1 Emphasis
The script gives the 1x1 line special treatment:
It uses mainLineWidth instead of baseLineWidth
Its glow can also be slightly wider than the other lines
This makes the central balance angle the visually dominant line in the fan.
9) Line Drawing and Extension
Each fan line is drawn from the anchor origin to the control index, then extended to the right:
line.new(
active.idx1, active.p1,
active.idx2, y2,
xloc = xloc.bar_index,
extend = extend.right,
...
)
This means the visible geometry is anchored in actual structure, but the line continues into the future as a projected guide.
10) Glow Layer Logic
If glow is enabled, the script first draws a wider translucent line underneath the main line:
line.new(... color = glowColor, width = gWidth)
Then it draws the normal fan line on top. This creates a soft highlight effect without changing the underlying geometry.
11) Angle Label Placement
If labels are enabled, the script places each label at a future bar location:
int xLabel = math.min(bar_index + labelShiftBars, bar_index + 500)
float yLabel = active.priceAt(ratio, xLabel)
This means the label stays attached to the correct projected fan angle while remaining offset from the live candles for readability.
12) Fan Zone Fill Logic
When zone fill is enabled, the script creates a fill between each adjacent pair of fan lines:
linefill.new(l1, l2, zoneColor)
The fill transparency alternates slightly from one band to the next:
int zoneAlpha = i % 2 == 0 ? 91 : 95
This creates subtle separation between fan sectors and improves visual depth.
13) Anchor Label Logic
If enabled, the script prints a label at the anchor origin:
string dirText = active.bullish ? "Bullish Gann Fan" : "Bearish Gann Fan"
This provides immediate confirmation of which structural direction is currently driving the fan. Indicador

Indicador

BK AK-HA Window🖥️ BK AK–HA PnF Window 🖥️
🙏 All glory to G-d
Respect to AK — discipline, patience, clean execution.
HA Window is a compact “analysis panel” that lives on your chart.
It lets you toggle between two different ways of reading structure:
Heikin Ashi Window (normalized, consistent OB/OS framework)
Point & Figure Window (clean X/O structure with targets + pattern logic)
This is not financial advice and it’s not a promise of results. It’s a visual decision tool designed to help you track trend, structure, and reaction quality with fewer distractions.
1) Quick Start (60 seconds)
Content → Heikin Ashi if you want trend + turning-point context inside a fixed OB/OS framework.
Content → Point & Figure if you want clean structure (X/O columns), break/rotate behavior, and objective counting tools.
Keep Lock to Last Bar = ON and adjust:
Width (candles)
Height (ATR multiple or % range)
Future Offset to park the panel neatly to the right.
2) Mode A — Heikin Ashi Window (Normalized Oscillator Candles)
This mode takes Heikin Ashi OHLC and maps it into a stable window range with:
0 / Overbought / Oversold levels
Optional zone fills for quick “where are we?” context
HA candle rendering with spacing options (1-bar or centered 2-bar mode)
Built-in confirmations (optional)
EMA overlay on the HA close (bias + pullback structure)
Pivot highs/lows (structure markers)
Buy/Sell markers (HA color flip events)
Divergence detection (RSI or MFI) with swing filters (so it doesn’t spam)
Volume spike highlighting (Volume ROC) to flag “activity candles”
Session shading (Asia / London / RTH) for time-context
Pattern recognition (optional)
The window can tag common HA behaviors like:
Flat tops/bottoms (level sensitivity)
Acceleration vs deceleration
Compression/inside bars
Absorption / exhaustion signatures
These are presented as context labels, not “guaranteed signals.”
3) Mode B — Point & Figure Window (X/O Structure Map)
PnF is about structure without time noise. This mode builds X/O columns and renders them inside a clean grid.
Auto box sizing (important)
Instead of forcing one ATR length, the script can evaluate several ATR candidates and select the one that best matches price behavior over the chosen lookback. That means:
less arbitrary box size guessing
more consistent columns across symbols/timeframes
What’s included (optional)
PnF reversal detection (X→O / O→X) + alert conditions
Pattern recognition (double/triple breaks, ascending/descending triples, catapults)
Gann/PnF counting tools
Horizontal count (congestion width → projected objectives)
Vertical count (column height → objective projection)
45° trend lines (classic PnF rails)
Congestion zone box (where acceptance is forming)
Price level labels (turns the panel into a quick S/R ladder)
Volume weighting (opacity or glyph size)
Column “box count” + time-in-column
quick read on thrust vs rotation/absorption behavior
MTF + LTF direction badges
alignment = higher confidence context
disagreement = “slow down and verify”
4) How to Use It (simple workflow)
Step 1 — Bias:
HA mode: EMA + candle color + zone location
PnF mode: column direction + HTF badge
Step 2 — Location:
HA mode: OB/OS + pivots
PnF mode: congestion zones + price level ladder
Step 3 — Confirmation:
HA flip + divergence/pattern context
PnF reversal/pattern + timeframe alignment
Step 4 — Management:
Use structure (pivots / PnF rails / count objectives) to manage expectations
Don’t treat the panel as a “prediction machine” — treat it as a clarity tool
5) Settings Suggestions
For fast intraday:
Smaller window width, keep PnF rows capped for readability, let auto-box sizing do the work.
For higher timeframe:
Increase correlation lookback + window width
Use MTF badge to stay aligned with the bigger structure
🖥️ BK AK–HA Window 🖥️ Indicador

Daily MGI - OnlyFlowMGI (Market Generated Information) plots key daily reference levels used by auction market and order flow traders. It draws Prior Day High, Low, Mid, and Close, Overnight High/Low, Opening Range, Initial Balance, RTH VWAP, and Value Area levels — all with price labels extending to the current bar.
Each line originates from the bar where the level was actually printed, giving you immediate visual context on where the market established its boundaries.
Features:
- Full Day (ETH) or RTH Only mode for prior day levels
- Configurable Opening Range and Initial Balance durations with ±50/100/150/200% extensions
- RTH VWAP and session midline
- Approximate prior day Value Area (VAH/VAL/POC)
- All levels togglable with customizable colors and label sizes
- Lines draw from their origin point to the current bar
Built as a lightweight alternative to paid order flow packages. Designed for futures (ES, NQ, etc.) but works on any instrument with defined RTH/ETH sessions. Adjust the RTH and ETH session times in settings to match your market. Indicador

EBP + FibThis indicator automatically detects bullish and bearish EBP candles, highlights them visually, and generates an inverted Fibonacci framework used to plan continuation trades with precision.
🔍 What This Indicator Does
This tool fully automates the EBP workflow:
1. Detects Bullish & Bearish EBP Candles
Bullish EBP: price sweeps prior lows and closes strongly above the previous open/close.
Bearish EBP: price sweeps prior highs and closes strongly below the previous open/close.
EBP candles often serve as high-probability directional anchors, defining short-term and medium-term bias.
2. Plots an Inverted Fibonacci Framework
Once an EBP candle forms, the script builds a custom inverted fib projection using the candle’s high/low as anchor points.
The levels used:
1.0 – EBP extreme
0.75 / 0.65 / 0.50 / 0.25 / 0.0 – retracement levels
-0.25 / -0.50 – continuation targets
3. Clean Labeling & Custom Styling
You can customize:
Level colors
Line weights & styles
Label positions (left, middle, right)
Label text size
Vertical spacing (to separate labels from lines)
Labels show the actual fib value for fast reference during execution.
4. Directional Bias Made Simple
The indicator colors EBP candles and displays fib levels that express the market’s expected path:
Bullish: price is expected to retrace into 0.50–0.65, hold above the 1.0 extreme, and extend toward negative extensions.
Bearish: identical logic mirrored downward.
This makes bias extremely easy to read on any timeframe (1m → 4H → HTF).
5. Built-in Alerts
The indicator includes alert conditions for:
Bullish EBP detected
Bearish EBP detected
___________________________
___________________________
📈 How Traders Use This Tool
This indicator is designed for traders who want a clean, systematic framework for trading EBP-based continuation setups.
Common execution models:
🔹 Bullish EBP
A 1H or 4H bullish EBP forms → bullish bias.
Wait for price to retrace into the 0.65 or 0.50 level.
Look for lower-timeframe confirmation (BOS, sweep + reclaim).
Target 0, -0.25, or -0.50.
🔹 Bearish EBP
Mirror the process above.
This workflow is widely used in algorithmic price action, continuation models, and liquidity-based trading.
___________________________
___________________________
✨ Ideal For
Liquidity-based traders
Smart money / ICT-fluent traders
Continuation model traders
Systematic backtesters
Intraday ES/NQ/MNQ/MES traders
Crypto scalpers using HTF bias
Indicador

Indicador

Indicador

Indicador

Indicador

Failed 2 Evaluator v2.2-Failed 2 Evaluator & Continuation EngineDescription:
The Failed 2 Evaluator & Continuation Engine is an objective price-action analysis tool designed to categorize, visualize, and statistically track how Failed 2 candles behave when interacting with key market levels.
This indicator evaluates whether a breach of a level results in price expansion, choppy price action, or a strict structural failure (a "Failed 2" in Strat terminology), providing traders with a quantitative view of historical follow-through.
How It Is Calculated
The script operates in three distinct phases:
1. Level Generation & Trigger
The indicator establishes boundaries using either auto-calculated Pivot Highs/Lows (with user-defined left/right lengths) or manually inputted price levels. The evaluation sequence is triggered the moment a candle's total range (wick) physically breaches one of these active levels.
2. Strict Outcome Evaluation (On Close)
Once the triggering candle closes, the script strictly categorizes the outcome into one of three buckets:
Breakout/Breakdown Expansion: The candle successfully closes outside the breached level, indicating a continuation of the break.
Strict Failed 2 (F2U / F2D): The candle breaches the level but immediately reverses, failing to hold the extreme. To qualify as a true Failed 2, the script enforces a strict structural rule: the candle must close back inside the level and must be a directional reversal candle (e.g., an F2U requires the close to be below the level and below its own open).
Neutral Reclaim (Chop): The candle breaches the level and falls back inside, but fails the strict color/directional logic of a true Failed 2.
3. The Continuation Engine
When a strict Failed 2 is confirmed, the script activates a forward-looking continuation tracker. It records the closing price of the Failed 2 candle and waits a user-defined number of bars (e.g., 3 bars). It then checks if the price at that future bar successfully continued in the direction of the reversal, logging the historical frequency of structural follow-through.
Dashboard Features & Chart Visuals
Real-Time Watcher: A dynamic table row alerts the user when a live, unconfirmed candle is actively testing a level, prompting observation for either a Continuation or a Failed 2.
Historical Distribution: The dashboard calculates the exact percentage breakdown of Expansions, True Failed 2s, and Chop over a user-defined lookback window.
Chart Markers: Clean, unobtrusive visual tags pinpoint exactly where Breaks (B↑/B↓) and True Reversals (F2U/F2D) occurred on the chart for easy visual backtesting.
Analytical Purpose
The primary benefit of this tool is the removal of emotional bias and subjectivity from "false breakout" analysis. By rigidly defining what constitutes a failed move and statistically tracking its historical continuation rate, this indicator allows analysts to quantify an asset's unique behavior at range extremes. It transforms abstract price action theories into measurable, observable data. Indicador

Indicador

HTF Candle Profile [UAlgo]HTF Candle Profile is a higher timeframe candle visualization tool that rebuilds each selected HTF candle from the lower timeframe bars that form it, then projects a horizontal volume profile inside that HTF candle range. The goal is to make intrabar participation visible directly on the price chart, so you can see where volume concentrated within the candle, where it was thin, and where the dominant traded price level emerged.
Instead of treating a daily or four hour candle as a single block, the script aggregates the lower timeframe bars as they arrive and distributes their volume across price bins covering the HTF candle’s high to low range. The result is a compact profile drawn from the start time of the HTF candle toward the right, with width proportional to relative volume per bin and color intensity driven by a gradient. This provides a fast read of internal structure: balanced candles, directional candles, rejection wicks, and consolidation pockets become easier to interpret because you can see the volume distribution inside the candle.
The indicator draws on the main chart and keeps a small rolling history of recent HTF candles to stay responsive and to respect object limits.
🔹 Features
1) Multi Timeframe HTF Candle Reconstruction
The script listens for a new HTF candle event using the selected timeframe input. When a new HTF candle begins, the previous one is finalized and drawn. During the active HTF candle, each incoming lower timeframe bar updates the running OHLC and stores its high, low, and volume for profiling.
This approach enables a live building profile for the current HTF candle while preserving completed profiles for recent candles.
2) Intrabar Volume Profile Built from LTF Data
For each HTF candle, the price range from low to high is divided into a user defined number of bins. Each lower timeframe bar contributes volume into all bins it spans. Volume is distributed evenly across the spanned bins to approximate participation within that bar’s range. This produces a per bin volume distribution that is stable and visually interpretable even when lower timeframe candles have large ranges.
3) Gradient Based Profile Intensity
Each bin is drawn as a horizontal box. Its color comes from a gradient that maps low volume to a softer profile color and high volume to a stronger profile color. This makes it easy to spot high participation nodes and low participation voids within the HTF candle.
Inputs allow independent control for bullish and bearish candle coloring and for the low volume and high volume profile colors.
4) POC Line Option
The script can optionally plot a POC line representing the price level of maximum volume within the HTF candle. This is drawn as a dashed horizontal line that spans the candle’s start time to end time. POC is often used as a reference for acceptance, fair value, or a magnet level during retracements.
5) Candle Body, Wick, and Time Boundaries
To keep the profile anchored and readable, the script also draws:
A translucent body box from HTF open to HTF close
A vertical wick line from HTF high to HTF low
A dotted start boundary and a dotted end boundary for the HTF candle window
These elements provide context so the profile is always interpreted within the candle structure that produced it.
6) Object Management and Rolling History
To keep charts clean and avoid exceeding platform limits, the script maintains a small history of HTF candles and deletes drawings for older ones. Each candle owns its objects and can fully clear them when removed from the rolling window.
🔹 Calculations
1) New HTF Candle Detection
A new candle event is detected using timeframe change on the selected timeframe:
isNew = timeframe.change(tf)
When isNew is true:
The previous HTF candle is finalized by setting its end time and drawing it
A new HTF candle object is created and added to the array
Old candles beyond the history limit are removed and their drawings deleted
2) HTF Candle Aggregation from LTF Bars
Each incoming lower timeframe bar updates the active HTF candle:
method addLtf(HtfCandle this, float h, float l, float c, float v) =>
this.ltfData.push(LtfBar.new(h, l, v))
this.h := math.max(this.h, h)
this.l := math.min(this.l, l)
this.c := c
Interpretation:
High is updated to the maximum seen so far within the HTF candle window
Low is updated to the minimum seen so far
Close is updated to the most recent close
Each LTF bar is stored with its high, low, and volume for later bin distribution
3) Bin Construction Across the HTF Candle Range
When drawing a candle, the script divides the HTF range into binCount segments:
float step = (this.h - this.l) / bCount
for i = 0 to bCount - 1
this.bins.push(ProfileData.new(this.l + i * step, this.l + (i + 1) * step, 0.0, na))
Each bin stores:
minP and maxP boundaries
accumulated volume for that price segment
a box handle for drawing
4) Volume Distribution from Each LTF Bar into Bins
For each stored LTF bar, the script determines which bins the bar spans and distributes volume evenly across them:
int startIdx = int((ltf.l - this.l) / step)
int endIdx = int((ltf.h - this.l) / step)
startIdx := math.max(0, math.min(startIdx, bCount - 1))
endIdx := math.max(0, math.min(endIdx, bCount - 1))
int spanned = endIdx - startIdx + 1
float vPerBin = ltf.v / spanned
for j = startIdx to endIdx
ProfileData b = this.bins.get(j)
b.vol += vPerBin
Interpretation:
The bar range is mapped to bin indexes
Indexes are clamped so they remain inside the array
Volume is divided by the number of spanned bins
Each spanned bin receives an equal share of that bar’s volume
This is a robust approach for intrabar profiling without tick data.
5) POC Computation
The script finds the bin with the maximum accumulated volume and sets the POC price at the midpoint of that bin:
float maxVol = 0.0
float pocP = na
for b in this.bins
if b.vol > maxVol
maxVol := b.vol
pocP := math.avg(b.minP, b.maxP)
If enabled, a dashed POC line is drawn across the HTF candle window:
if sPoc and not na(pocP)
this.lPoc := line.new(x1=this.st, y1=pocP, x2=this.et, y2=pocP, xloc=xloc.bar_time, color=cPoc, style=line.style_dashed, width=2)
6) Profile Box Width Scaling
Each bin’s box width scales by its volume relative to the maximum volume bin. Width is capped as a fraction of the candle’s time duration:
int duration = math.max(this.et - this.st, 1)
int volWidth = int((duration * 0.40) * (b.vol / maxVol))
int boxRight = this.st + volWidth
Interpretation:
duration represents the HTF candle time width
0.40 is the maximum profile width fraction of the candle duration
b.vol / maxVol converts volume to a normalized ratio
boxRight is calculated so all profile boxes start at the candle start time and extend rightward based on volume
7) Gradient Coloring of the Profile
Each bin color is mapped from low volume to high volume using a gradient:
color gradColor = color.from_gradient(b.vol, 0, maxVol, cLow, cHigh)
This keeps low participation zones visually lighter and high participation zones more prominent.
8) Candle Body and Wick Drawing
The script draws an HTF candle body box and a wick line for context:
float topP = math.max(this.o, this.c)
float botP = math.min(this.o, this.c)
this.bBody := box.new(left=this.st, top=topP, right=this.et, bottom=botP, xloc=xloc.bar_time, bgcolor=color.new(c, 85))
this.lWick := line.new(x1=midTime, y1=this.h, x2=midTime, y2=this.l, xloc=xloc.bar_time, color=color.new(c, 30), width=2)
It also draws start and end boundary lines so the candle window is clearly defined in time.
Indicador

Delta Ladder Order Flow [UAlgo]Delta Ladder Order Flow is an overlay order flow visualizer that builds a per bar delta ladder using lower timeframe candles as an intrabar proxy. For each recent bar, the script pulls the underlying lower timeframe open, high, low, close, and volume arrays, then distributes volume into discrete price buckets. Each bucket accumulates estimated buy volume and sell volume, producing a ladder that resembles a footprint style view.
The display focuses on three core outputs:
A delta heatmap ladder where each price level is colored by net delta dominance
A Point of Control highlight that marks the highest total volume level inside the bar
A stacked imbalance detector that scans diagonally across levels to identify aggressive one sided participation and optionally projects that stack forward
The system is designed with stability controls for real world chart conditions. It includes dynamic scaling to prevent excessive level counts on high range bars, object budgeting through bars to draw limits, and text filtering to reduce clutter.
🔹 Features
1) Intrabar Resolution via Lower Timeframe Data
The ladder is constructed using request.security_lower_tf. You select an Intrabar Resolution timeframe that must be lower than the chart timeframe. The script then receives arrays of LTF candles for each chart bar and uses them as a proxy for footprint style aggregation.
This approach provides a practical order flow approximation on TradingView charts without requiring native tick level data.
2) Ladder Aggregation with Tick Size Multiplier
Price levels are aggregated using the symbol mintick multiplied by a user multiplier. Increasing the multiplier produces thicker ladder steps and fewer levels. Decreasing it produces finer granularity but increases the number of boxes drawn.
This control is critical for balancing detail versus performance across different symbols and volatility regimes.
3) Dynamic Scaling to Prevent High Range Bar Overload
A single volatile bar can contain too many price steps if the granularity is too fine. To prevent crashes, the script estimates how many steps would be required for the bar and increases the effective step size when the raw step count exceeds Max Levels per Bar.
This keeps rendering stable even during high volatility events while still maintaining a consistent ladder representation.
4) Buy, Sell, and Neutral Volume Attribution
Each LTF candle’s direction is inferred from its open and close:
Close above open is treated as buy side volume
Close below open is treated as sell side volume
Close equal open is treated as neutral and split evenly between buy and sell
Volume is then distributed across the price buckets covered by the LTF candle range so that wide candles spread their influence across multiple levels.
5) Delta Heatmap Ladder with Intensity Scaling
Each price bucket computes delta as buy volume minus sell volume and total volume as the sum of both. Ladder cells are colored positive or negative based on delta sign, and transparency is scaled by how dominant the delta is relative to the maximum total volume level inside that bar. This yields a compact heatmap where strong imbalances visually stand out.
A square root curve is applied to intensity to improve mid tone visibility without making everything fully opaque.
6) Point of Control Highlight
The ladder tracks the price level with the highest total volume and marks it as the Point of Control. When enabled, the POC row uses a dedicated border color and a stronger border width so the acceptance anchor is immediately visible.
7) Stacked Imbalance Detection and Projection
The script can detect stacked diagonal imbalances. It compares volume across adjacent price levels using a diagonal logic similar to footprint tools:
Bullish diagonal checks buy volume at a level versus sell volume at the level below
Bearish diagonal checks sell volume at a level versus buy volume at the level above
An imbalance requires the winning side to exceed the losing side by the configured Imbalance Ratio and also exceed a minimum volume threshold to filter low volume noise. When consecutive imbalanced levels reach the Stacked Levels count, the stack is marked and optionally extended forward as a zone.
Stack members also override normal heatmap coloring and are rendered more solid for emphasis.
8) Clean Visual Controls
Several options support readability:
Bars to Draw limits workload and object count
Show Delta Values can be toggled on or off
Min Delta to Show Text filters small prints
Ladder Width percent controls how wide the ladder is relative to the bar space
Text size can be adjusted for different chart zoom levels
Box outline can be hidden by default for a cleaner footprint aesthetic
🔹 Calculations
1) Intrabar data acquisition (lower timeframe arrays)
The script requests arrays of LTF OHLCV values for each chart bar using request.security_lower_tf.
ltf_open = request.security_lower_tf(syminfo.tickerid, tf_input, open)
ltf_close = request.security_lower_tf(syminfo.tickerid, tf_input, close)
ltf_high = request.security_lower_tf(syminfo.tickerid, tf_input, high)
ltf_low = request.security_lower_tf(syminfo.tickerid, tf_input, low)
ltf_vol = request.security_lower_tf(syminfo.tickerid, tf_input, volume)
These arrays contain the lower timeframe candles that make up each chart bar. Each chart bar index has its own embedded array.
2) Base tick step (bucket size control)
Bucket size starts from mintick multiplied by Tick Size Multiplier.
var float base_tick_step = syminfo.mintick * tick_size_mult
This is the baseline price increment used to build the ladder levels.
3) Last bar execution model (performance design)
The script only builds and draws ladders when barstate.islast is true. It then reconstructs the last N bars using an index offset.
if barstate.islast
int start_idx = math.max(0, bar_index - bars_to_draw + 1)
for i = start_idx to bar_index
int offset = bar_index - i
float arr_o = ltf_open
float arr_c = ltf_close
float arr_h = ltf_high
float arr_l = ltf_low
float arr_v = ltf_vol
This design dramatically reduces CPU and memory load compared to updating every bar.
4) Dynamic scaling per bar (anti crash protection)
For each bar, the script estimates how many price steps would be needed using the current bucket size. If that count exceeds Max Levels per Bar, it increases the step size only for that bar.
float bar_h = high
float bar_l = low
float bar_range = bar_h - bar_l
float raw_steps = bar_range / base_tick_step
int scaler = 1
if raw_steps > max_levels_per_bar
scaler := int(math.ceil(raw_steps / max_levels_per_bar))
float current_tick_step = base_tick_step * scaler
Result:
Calm bars use fine granularity
High range bars are automatically compressed into fewer buckets
5) LTF candle direction classification (buy, sell, neutral)
Each LTF candle is classified using its open and close. Neutral candles split volume evenly.
bool is_buy = c > o
bool is_sell = c < o
bool is_neutral = c == o
This is a heuristic proxy for aggressor side. It is not true bid ask data.
6) Align LTF candle range to bucket grid
The candle low and high are rounded to the current tick step so bucket prices align cleanly.
float low_aligned = math.round(l / current_tick_step) * current_tick_step
float high_aligned = math.round(h / current_tick_step) * current_tick_step
7) Step counting and volume per step
The script computes how many bucket levels the candle touches and divides volume equally across them.
int steps = int(math.round((high_aligned - low_aligned) / current_tick_step)) + 1
if steps > 500
steps := 500
float vol_per_step = v / steps
This means wide candles distribute volume across more ladder cells, while tight candles concentrate volume into fewer cells.
8) Writing volume into the ladder map (PriceLevel storage)
Each chart bar owns a DeltaLadder with a map of price to PriceLevel. Each PriceLevel stores buy and sell volume. Volume is added step by step.
type PriceLevel
float price
float buy_vol = 0.0
float sell_vol = 0.0
type DeltaLadder
int bar_idx
map levels
float min_price = 10000000.0
float max_price = 0.0
float max_vol_level = 0.0
float poc_price = na
float poc_vol = 0.0
The add method updates volumes and also tracks max volume and POC:
method add_volume(DeltaLadder this, float price, float vol, bool is_buy, bool is_neutral) =>
if not this.levels.contains(price)
this.levels.put(price, PriceLevel.new(price))
PriceLevel lvl = this.levels.get(price)
if is_neutral
lvl.buy_vol += vol * 0.5
lvl.sell_vol += vol * 0.5
else if is_buy
lvl.buy_vol += vol
else
lvl.sell_vol += vol
float t = lvl.total()
if t > this.max_vol_level
this.max_vol_level := t
if t > this.poc_vol
this.poc_vol := t
this.poc_price := price
The main loop calls this method for each bucket level touched by each LTF candle:
for p = 0 to steps - 1
float level_price = low_aligned + (p * current_tick_step)
ladder.add_volume(level_price, vol_per_step, is_buy, is_neutral)
9) Delta and total volume formulas
Delta and total are defined as methods on PriceLevel.
method delta(PriceLevel this) =>
this.buy_vol - this.sell_vol
method total(PriceLevel this) =>
this.buy_vol + this.sell_vol
These values drive both coloring and POC selection.
10) Stacked imbalance detection (diagonal footprint logic)
Prices are sorted so neighbor comparisons are correct. A stack_map stores whether each price belongs to a bullish or bearish stacked run.
float prices = ladder.levels.keys()
array.sort(prices)
map stack_map = map.new()
Diagonal comparisons:
Bullish diagonal compares BuyVol at level i with SellVol at level below i minus 1
Bearish diagonal compares SellVol at level i with BuyVol at level above i plus 1
Bullish check includes a zero handling rule:
if i > 0
float p_below = array.get(prices, i-1)
PriceLevel lvl_below = ladder.levels.get(p_below)
if lvl_below.sell_vol == 0
if lvl.buy_vol > imb_min_vol
direction := 1
else
if lvl.buy_vol > lvl_below.sell_vol * imb_ratio and lvl.buy_vol > imb_min_vol
direction := 1
Bearish check includes symmetric logic:
if i < array.size(prices) - 1
float p_above = array.get(prices, i+1)
PriceLevel lvl_above = ladder.levels.get(p_above)
if lvl_above.buy_vol == 0
if lvl.sell_vol > imb_min_vol
direction := -1
else
if lvl.sell_vol > lvl_above.buy_vol * imb_ratio and lvl.sell_vol > imb_min_vol
direction := -1
Runs are tracked and only accepted if the number of consecutive levels meets the stacked requirement:
if math.abs(i - run_start_idx) >= stack_count
for k = run_start_idx to i - 1
stack_map.put(array.get(prices, k), run_dir)
The script also draws a projected zone for the detected stack band:
box.new(right_time, p_top + current_tick_step/2, right_time + 1000 * 60 * 60 * 24, p_bot - current_tick_step/2,
xloc=xloc.bar_time, border_width=0, bgcolor=color.new(c_stack, 85), extend=extend.right)
11) Heatmap intensity and transparency mapping
For each price level, intensity is computed as abs(delta) relative to the maximum total volume level in the bar, then curved and mapped into transparency.
float intensity = ladder.max_vol_level > 0 ? math.abs(delta) / ladder.max_vol_level : 0
intensity := math.min(intensity, 1.0)
float curved_intensity = math.sqrt(intensity)
float transp = 97 - (curved_intensity * 57)
Stacked members force stronger visibility:
if stack_map.contains(p)
intensity := 1.0
transp := 30
12) POC marking in the drawing pass
POC is detected during volume accumulation, then used in rendering to upgrade the border style for that cell.
bool is_poc = show_poc and (p == ladder.poc_price)
color border_c = is_poc ? col_poc : col_outline
int border_w = is_poc ? 2 : 1
13) Delta text rendering filter
Text labels are optional and can be filtered by a minimum absolute delta threshold.
if show_text and math.abs(delta) >= text_threshold
string txt = str.tostring(delta, format.volume)
label.new(int((left_time + right_time)/2), p, txt,
xloc=xloc.bar_time, style=label.style_none,
textcolor=txt_col, size=text_size)
Indicador

HTF Candle Dynamics [LuxAlgo]The HTF Candle Dynamics indicator provides traders with a comprehensive view of Higher Timeframe (HTF) price action and volume distribution directly on their lower timeframe charts. By projecting the current developing HTF candle and its internal volume characteristics to the right of the price, users can maintain high-level context without switching tabs.
Note: Ensure the chart timeframe is lower than the selected HTF setting for the indicator to function correctly.
🔶 USAGE
This tool is designed to bridge the gap between execution timeframes and higher-level market structures. It is particularly useful for scalpers and day traders who need to stay aware of Daily or Weekly levels while trading on 1-minute or 5-minute charts.
🔹 HTF Candle Projection
Visualizes the current HTF period (e.g., Daily, Weekly) as a dynamic candle on the right side of the chart. It includes projections for the HTF Open, High, Low, and Close levels. These levels often act as significant psychological barriers where price might find support or resistance.
🔹 Intraday Volume Profile
Generates a volume profile specifically for the current HTF period. This allows traders to see where the most volume is being transacted within the developing candle. Identifying "High Volume Nodes" within the current HTF candle can signal where institutional interest is concentrated.
🔹 Dynamic POC Tracking
A polyline tracks the movement of the Point of Control (POC) throughout the HTF period, showing how the most traded price level has shifted over time. If the POC is trending upward alongside price, it confirms a healthy bullish trend; if price moves away from a static POC, it might indicate a potential mean reversion back to that high-volume level.
🔹 How to Use
Traders can utilize this indicator to align their intraday trades with the broader market direction:
Identifying Value : Use the Intraday Volume Profile to spot the Point of Control. If the price is trading above the POC, the market is currently in a premium zone for that HTF. If it is below, it may be considered "discounted" relative to the volume transacted so far.
Breakout Confirmation : When price breaks the High or Low of the projected HTF candle, traders look for volume expansion within the profile to confirm if the breakout has significant participation.
Mean Reversion : The Dynamic POC line acts as a magnet. If price overextends significantly from the POC line, traders often look for signs of exhaustion to play a move back toward the high-volume area.
🔶 DETAILS
The indicator uses security calls to fetch historical HTF data while calculating the current developing period in real-time. A dedicated status table ensures the selected HTF is valid relative to the chart timeframe to prevent calculation errors.
🔹 History Dashboard
The dashboard provides a statistical breakdown of the previous three HTF candles (T-1, T-2, T-3). This is crucial for "Contextual Trading." By seeing the OHLC values and Volume Delta of the previous periods, you can determine if the market is experiencing "Expansion" (increasing volume and candle size) or "Contraction" (decreasing volume and tighter ranges).
🔹 Volume Delta
The Volume Delta shown in the history dashboard is an approximation calculated by summing volume based on the direction of individual intraday candles.
🔶 SETTINGS
HTF Setting : Defines the timeframe for the candle projection and volume profile (default is "D").
Right Offset : Adjusts the horizontal position of the projected candle and labels to avoid overlapping with price.
Visuals : Full control over bullish/bearish colors, POC lines, and projection offsets.
Volume Profile : Toggle the profile visibility and customize the number of rows or the maximum width of the bars.
History Dashboard : Toggle the history dashboard and adjust its position (Top Right, Bottom Right, etc.) or size.
Indicador
