Volumetric Inverse Fair Value Gap (VIFVG) [UAlgo]Volumetric Inverse Fair Value Gap is an imbalance analysis tool that tracks the full lifecycle of a Fair Value Gap and then focuses on what happens after that gap fails. Instead of stopping at the initial gap detection, the script stores qualifying bullish and bearish FVGs, waits for price to invalidate them from the opposite side, and then converts those failed imbalances into active Inverse Fair Value Gaps.
The main idea is rooted in role reversal. A bullish Fair Value Gap may initially represent an area of inefficiency below price, but if price later trades through that gap in the opposite direction, the same zone can flip into a bearish inverse area. The same logic applies in reverse for bearish gaps that later fail to the upside. This script automates that transition and keeps the resulting IFVG visible on the chart as long as it remains active.
What makes this version more distinctive is the volumetric overlay inside the inverse zone. Once an IFVG is created, the script attaches three internal metrics to it. The first estimates bullish participation, the second estimates bearish participation, and the third measures relative volume strength using percentile rank. These values are then displayed inside the box as horizontal progress bars, turning the IFVG into both a structural level and a compact participation summary.
The indicator also supports a ghost box that preserves the original FVG location from the moment it was created until the moment it became inverse. This gives the user a clearer narrative of how the imbalance formed and where the role reversal occurred. Combined with the active box, the result is a visually informative workflow for traders who want to study failed imbalances, structure flips, and how strong the inversion candle was when the role change happened.
In practical use, the script can help identify zones where a former inefficiency has turned into a reaction area, while also showing whether the inversion event carried more bullish pressure, more bearish pressure, or unusually strong participation relative to recent volume history.
🔹 Features
🔸 Fair Value Gap Detection With ATR Filtering
The script first detects classic three candle FVG structures, then filters them using a minimum gap size expressed in ATR units. This helps reduce noise and removes smaller gaps that may be less meaningful.
🔸 Strict and Non Strict Detection Modes
Strict mode requires actual wick separation between the first and third candle. Non strict mode allows close based confirmation instead. This gives the user control over how precise the gap definition should be.
🔸 Pending FVG Lifecycle Tracking
Detected FVGs are not immediately turned into inverse zones. They are first stored as pending gaps and monitored until price later crosses them in the opposite direction.
🔸 Automatic FVG to IFVG Conversion
When price invalidates a pending gap from the opposite side, the script creates a new Inverse Fair Value Gap object and begins tracking it as an active zone.
🔸 Ghost Box Support
The original FVG can be preserved visually as a dashed ghost box from the creation time of the imbalance to the inversion time. This makes it easier to see the original gap and the later role reversal event together.
🔸 Volumetric Breakdown Inside the IFVG
Each active inverse gap includes three stacked internal bars:
estimated bullish participation,
estimated bearish participation,
and relative strength.
This gives the zone more context than a normal box alone.
🔸 Participation Estimation From Candle Anatomy
Bullish and bearish participation are estimated from the inversion candle’s structure and volume. This creates a practical volume split model that helps describe how the inversion occurred.
🔸 Strength Metric From Volume Percentile Rank
The script measures how strong the inversion candle’s volume is relative to the last one hundred bars. This is displayed as a separate strength bar inside the IFVG.
🔸 Live Box Expansion
As long as an IFVG remains active, its container extends forward in time. The internal volumetric bars and text labels are updated continuously so the zone remains clear and readable.
🔸 Automatic Invalidation
A bullish IFVG is removed if price closes below its bottom. A bearish IFVG is removed if price closes above its top. This keeps the display focused on still valid inverse zones.
🔸 Controlled History Size
The script limits how many active IFVGs remain on the chart. Older ones are removed once the display exceeds the selected history count.
🔹 Calculations
1) Defining the Pending Gap and Active IFVG Objects
type PendingFVG
float top
float btm
bool is_bull_gap
bool processed
int created_time
type IFVG
int start_time
int origin_time
float top
float btm
bool is_bull_ifvg
float pct_bull
float pct_bear
float pct_strength
box container
box ghost_box
box bg_bull
box bar_bull
box bg_bear
box bar_bear
box bg_str
box bar_str
label lbl_bull
label lbl_bear
label lbl_str
bool active
This is the structural foundation of the script.
A PendingFVG stores an imbalance that has been detected but has not yet inverted. It contains the gap boundaries, whether the original gap was bullish or bearish, whether it has already been processed into an inverse gap, and the time when it was created.
An IFVG stores the full active inverse gap state. In addition to the price boundaries and direction, it also stores the three internal metrics, the container box, the optional ghost box, the internal background and progress bars, the labels, and the active state.
So the script is not just drawing boxes. It is managing two linked object lifecycles:
pending FVGs,
and active inverse FVGs.
2) ATR Filter for Gap Significance
float atr_val = ta.atr(14)
The ATR value is used as the script’s minimum significance filter.
Instead of accepting every visible gap, the script compares gap size against a fraction of ATR. This is useful because a fixed price threshold would behave very differently across markets and timeframes, while ATR gives a volatility aware reference.
So ATR acts as the noise filter that decides whether a newly found gap deserves to be tracked.
3) Estimating Bullish and Bearish Participation
calc_metrics(float o, float h, float l, float c, float v) =>
float rng = h - l
float buy_v = 0.0
if rng == 0
buy_v := v * 0.5
else
if c >= o
buy_v := v * ((math.abs(c - o) + (math.min(o, c) - l)) / rng)
else
buy_v := v * ((h - math.max(o, c)) / rng)
float sell_v = v - buy_v
float total = buy_v + sell_v
float p_bull = total > 0 ? buy_v / total : 0
float p_bear = total > 0 ? sell_v / total : 0
float p_str = ta.percentrank(v, 100) / 100.0
This function is one of the most important parts of the whole script.
Its goal is to turn one candle into three interpretable metrics:
bullish share,
bearish share,
and strength.
First, the script measures the candle range. If the candle has zero range, volume is split evenly.
If the candle has a real range, the script estimates buying pressure differently depending on candle direction.
For bullish candles, buy volume is influenced by the candle body plus the lower section of the candle.
For bearish candles, buy volume is approximated from the remaining upper section.
The result is not true exchange level aggressor volume, but it is a practical candle anatomy based estimate of how much of the inversion bar behaved more like buying versus selling.
Then the script converts those raw buy and sell estimates into proportions:
p_bull
and
p_bear
Finally, it calculates p_str using the percentile rank of current volume over the last one hundred bars. That means the strength value is not just raw volume. It describes how relatively strong the inversion candle was compared with recent history.
4) Reading the Current Candle Metrics
= calc_metrics(open, high, low, close, volume)
This line applies the volumetric function to the current bar.
These three values are later attached to a new IFVG at the moment of inversion. So each active inverse gap inherits the participation and strength profile of the candle that caused the role reversal.
That is important conceptually. The internal bars inside the IFVG are not random decorations. They represent the inversion event itself.
5) Detecting Bullish and Bearish FVGs
bool bull_cond = strict_mode ? (low > high ) : (close > high )
bool bear_cond = strict_mode ? (high < low ) : (close < low )
This block defines the actual Fair Value Gap logic.
In strict mode:
a bullish gap exists only when the current low is above the high from two bars ago,
and a bearish gap exists only when the current high is below the low from two bars ago.
That means actual wick separation is required.
In non strict mode:
the script relaxes this and allows close based confirmation instead.
So the user can choose whether the script should only accept clean wick gaps or allow a softer close based definition.
6) Measuring the Gap Size
float gap_size = 0.0
if bull_cond and close > open
gap_size := low - high
if bear_cond and close < open
gap_size := low - high
bool is_significant = gap_size >= (atr_val * fvg_threshold_atr)
Once a candidate FVG is found, the script measures how large the gap actually is.
For bullish gaps, the size is the distance between the current low and the high from two bars ago.
For bearish gaps, the size is the distance between the low from two bars ago and the current high.
The script also adds a candle direction filter on the middle bar:
bullish gaps require the middle candle to be bullish,
and bearish gaps require the middle candle to be bearish.
Finally, the measured gap must be at least as large as:
ATR × threshold
This removes smaller gaps that may simply be noise.
7) Storing a Pending FVG
if is_significant
PendingFVG p = PendingFVG.new()
p.created_time := time
p.processed := false
if bull_cond
p.is_bull_gap := true
p.top := low
p.btm := high
else
p.is_bull_gap := false
p.top := low
p.btm := high
array.push(pending_fvgs, p)
If the gap is significant, the script stores it as a pending FVG.
The gap is not drawn yet as an inverse zone. Instead, it is placed into the pending list with:
its direction,
its boundaries,
its creation time,
and a flag showing it has not yet been processed.
This is important because an FVG only becomes an IFVG after it fails. The pending list is the waiting room for that future role reversal.
8) Detecting the Inversion Event
if array.size(pending_fvgs) > 0
for i = array.size(pending_fvgs) - 1 to 0
PendingFVG p = array.get(pending_fvgs, i)
if not p.processed
bool inverted = false
bool to_bull = false
if not p.is_bull_gap and close > p.top
inverted := true
to_bull := true
if p.is_bull_gap and close < p.btm
inverted := true
to_bull := false
This is the core IFVG transition logic.
A pending bearish FVG becomes a bullish IFVG if price closes above its top.
A pending bullish FVG becomes a bearish IFVG if price closes below its bottom.
That is the actual role reversal event. Price has invalidated the original imbalance from the opposite side, so the gap flips into an inverse form.
The to_bull flag determines the direction of the new inverse zone.
9) Creating the IFVG Object
if inverted
IFVG obj = IFVG.new()
obj.start_time := time
obj.origin_time := p.created_time
obj.top := p.top
obj.btm := p.btm
obj.is_bull_ifvg := to_bull
obj.pct_bull := curr_p_bull
obj.pct_bear := curr_p_bear
obj.pct_strength := curr_p_str
obj.active := true
obj.create_drawings()
array.push(active_ifvgs, obj)
p.processed := true
Once inversion is confirmed, the script creates the active IFVG.
The new object inherits:
the original FVG boundaries,
the original creation time,
the inversion start time,
and the new inverse direction.
It also stores:
the bullish participation percentage,
the bearish participation percentage,
and the strength percentage from the inversion candle.
So the IFVG is a structural object with a built in event profile. It tells the user not only where the failed gap is located, but also what the inversion bar looked like in participation terms.
10) Creating the Ghost Box and Main Container
if show_ghost
this.ghost_box := box.new(
left=this.origin_time,
top=this.top,
right=this.start_time,
bottom=this.btm,
border_color=color.new(c_border, 20),
border_width=1,
border_style=line.style_dashed,
bgcolor=c_ghost,
xloc=xloc.bar_time
)
this.container := box.new(
left=this.start_time,
top=this.top,
right=time,
bottom=this.btm,
border_color=c_border,
border_width=1,
bgcolor=color(na),
xloc=xloc.bar_time
)
This is the first part of the IFVG drawing engine.
If ghost mode is enabled, the script draws a dashed box from the original FVG creation time to the inversion time. This visually represents the original gap before it failed.
Then it creates the main IFVG container box starting from the inversion time and extending to the current bar.
So the chart can show both:
where the original gap existed,
and where the inverse zone now lives.
11) Building the Internal Volumetric Bar Areas
this.bg_bull := box.new(this.start_time, this.top, time, this.top, border_width=0, bgcolor=c_bg_dark, xloc=xloc.bar_time)
this.bar_bull := box.new(this.start_time, this.top, this.start_time, this.top, border_width=0, bgcolor=c_bull_bar, xloc=xloc.bar_time)
this.bg_bear := box.new(this.start_time, this.top, time, this.top, border_width=0, bgcolor=c_bg_dark, xloc=xloc.bar_time)
this.bar_bear := box.new(this.start_time, this.top, this.start_time, this.top, border_width=0, bgcolor=c_bear_bar, xloc=xloc.bar_time)
this.bg_str := box.new(this.start_time, this.top, time, this.top, border_width=0, bgcolor=c_bg_dark, xloc=xloc.bar_time)
this.bar_str := box.new(this.start_time, this.top, this.start_time, this.top, border_width=0, bgcolor=c_str_bar, xloc=xloc.bar_time)
Inside every IFVG, the script creates three horizontal rows.
Each row has:
a dark background box,
and a colored progress bar box.
The three rows represent:
bullish participation,
bearish participation,
and strength.
Initially these boxes are created with minimal size. Their real geometry is set later during updates.
So the IFVG is designed as a mini information panel embedded directly inside the zone.
12) Slicing the IFVG Into Three Metric Rows
float total_h = this.top - this.btm
float h_slice = total_h / 3
float y1 = this.top
float y2 = this.top - h_slice
float y3 = this.top - 2 * h_slice
float y4 = this.btm
This block divides the IFVG vertically into three equal sections.
The full height of the box is measured, then split into thirds:
the first slice for bullish participation,
the second slice for bearish participation,
the third slice for strength.
This makes the internal visualization clean and consistent regardless of zone height.
13) Converting Percentages Into Horizontal Width
int now = time
int dur = now - this.start_time
if dur <= 0
dur := timeframe.in_seconds() * 1000
int w_bull = math.round(dur * this.pct_bull)
int w_bear = math.round(dur * this.pct_bear)
int w_str = math.round(dur * this.pct_strength)
This is how the script turns percentages into visible progress bars.
The available horizontal width is the elapsed time from the IFVG start to the current bar. That duration becomes the maximum usable width.
Then each stored metric is multiplied by that duration:
bullish percentage controls the bullish bar width,
bearish percentage controls the bearish bar width,
strength percentage controls the strength bar width.
So the internal bars behave like proportion meters stretched across the live duration of the zone.
14) Updating the Bull, Bear, and Strength Bars
this.bg_bull.set_left(this.start_time)
this.bg_bull.set_right(now)
this.bg_bull.set_top(y1)
this.bg_bull.set_bottom(y2)
this.bar_bull.set_left(this.start_time)
this.bar_bull.set_right(this.start_time + w_bull)
this.bar_bull.set_top(y1)
this.bar_bull.set_bottom(y2)
this.bg_bear.set_left(this.start_time)
this.bg_bear.set_right(now)
this.bg_bear.set_top(y2)
this.bg_bear.set_bottom(y3)
this.bar_bear.set_left(this.start_time)
this.bar_bear.set_right(this.start_time + w_bear)
this.bar_bear.set_top(y2)
this.bar_bear.set_bottom(y3)
this.bg_str.set_left(this.start_time)
this.bg_str.set_right(now)
this.bg_str.set_top(y3)
this.bg_str.set_bottom(y4)
this.bar_str.set_left(this.start_time)
this.bar_str.set_right(this.start_time + w_str)
this.bar_str.set_top(y3)
this.bar_str.set_bottom(y4)
These blocks physically place the three metric layers inside the IFVG.
Each background row spans the full current width of the active zone.
Each colored bar spans only the proportional amount determined by the stored metric.
So if bullish participation is high, the bullish bar stretches farther across its row. If strength is low, the strength bar remains shorter.
This gives the zone an at a glance internal profile.
15) Updating the Text Labels
this.lbl_bull.set_xy(center_x, mid_bull)
this.lbl_bull.set_text(str.format("Bull: {0}%", math.round(this.pct_bull * 100)))
this.lbl_bear.set_xy(center_x, mid_bear)
this.lbl_bear.set_text(str.format("Bear: {0}%", math.round(this.pct_bear * 100)))
this.lbl_str.set_xy(center_x, mid_str)
this.lbl_str.set_text(str.format("Str: {0}%", math.round(this.pct_strength * 100)))
The script also prints the numerical values inside the three rows.
Each label is placed at the center of its row and updated with the rounded percentage value.
So the user sees both:
the visual bar length,
and the exact stored percentage.
This makes the IFVG readable even when box width is large or when color alone is not enough.
16) IFVG Invalidation Logic
bool broken = false
if this.is_bull_ifvg and close < this.btm
broken := true
if not this.is_bull_ifvg and close > this.top
broken := true
if broken
this.active := false
this.remove()
An active IFVG only remains valid while price stays on the correct side of its structure.
For bullish IFVG:
if close falls below the bottom, the zone is broken.
For bearish IFVG:
if close rises above the top, the zone is broken.
When that happens, the IFVG is marked inactive and all associated objects are deleted.
So the indicator is not just drawing inverse gaps indefinitely. It actively monitors whether they continue to behave as valid reaction zones.
17) Display Limit Management
while array.size(active_ifvgs) > show_last_n
IFVG d = array.shift(active_ifvgs)
d.remove()
This final block controls how many IFVGs remain visible.
If the number of active inverse gaps exceeds the selected display limit, the oldest one is removed from the front of the array and all of its drawings are deleted.
This keeps the chart focused on the most recent inverse gaps and prevents excessive visual clutter. אינדיקטור

Squeeze Impulse OscillatorSqueeze Impulse Oscillator (SIO)
Indicator Description
The Squeeze Impulse Oscillator is designed to detect moments when the market exits a consolidation phase (squeeze) and forms a strong impulsive move. The indicator analyzes candlestick patterns, the ratio of the body to the range, wick lengths, and price dynamics to assess the strength of the current trend and potential breakout from consolidation.
The core idea is to compare two components:
Impulse – shows how strong the price movement is, based on the body size relative to the range and the persistence of direction (consecutive bars in the same direction).
Squeeze – reflects the degree of market tightness, evaluated by wick length and range contraction. Longer wicks and narrower ranges indicate higher energy accumulation for a subsequent impulse.
The resulting SIO value = impulse − squeeze. Positive values indicate a dominance of the impulse component, negative values point to a squeeze phase. Additional threshold levels help identify confident impulse zones and extreme squeeze zones.
How It Works
Candle Evaluation
Relative body size (bodyEff) – ratio of the candle body to its full range. Larger body means stronger impulse.
Wick ratio (wickRatio) – total wick length relative to the range. Long wicks indicate indecision or accumulation.
Current range compared to its average (rangeRatio) – helps incorporate volatility.
Price Dynamics
Persistence factor (persist) equals 1 if the last two price changes are in the same direction, otherwise 0.
Component Calculation
impulseScore = bodyEff × rangeRatio × (0.5 + 0.5 × persist)
squeezeScore = wickRatio × (2.0 − rangeRatio) × (1.0 − persist × 0.5)
Oscillator
rawSIO = impulseScore − squeezeScore
Final sio value is smoothed with an exponential moving average (EMA) using the specified smoothing period.
Squeeze Counter
When sio drops below the squeeze threshold (i_sqzTh), a consecutive bar count begins. The counter resets when sio rises above zero.
Additional Line
Averaged wick bias (avgWickBias) is displayed, showing which side has longer wicks (positive → bullish bias, negative → bearish bias). Used for signal filtering.
Signals
The indicator generates three types of signals (enabled via Show Signals parameter):
Bull Impulse – green triangle at the bottom.
Conditions:
sio crosses above the impulse threshold (i_impTh);
preceded by at least the minimum number of squeeze bars (Min Squeeze Bars);
wick bias positive (avgWickBias > 0).
Interpretation: after a prolonged squeeze phase, price starts moving up, confirmed by bullish candle structure.
Bear Impulse – red triangle at the bottom.
Same conditions but wick bias ≤ 0.
Interpretation: expected downward move after a squeeze.
Squeeze Start – purple diamond at the top.
Occurs when sio crosses below the squeeze threshold. Warns of possible energy accumulation and an upcoming impulse.
Visual Elements
SIO Histogram – colored according to the state:
bright green/red (depending on candle direction) – above impulse threshold;
purple – below squeeze threshold;
gray – neutral zone.
Wick Bias Line (yellow) – scaled for better visibility.
Squeeze Counter – purple step line showing consecutive bars in squeeze.
Background Highlight – squeeze zones are marked with a semi‑transparent purple background.
Horizontal Levels: impulse threshold, zero line, squeeze threshold.
Input Parameters
Core
Period – period for average range calculation and wick bias moving average.
Smoothing – EMA smoothing of the final SIO value.
Impulse Threshold – level above which the value is considered impulsive.
Squeeze Threshold – level below which the value is considered a squeeze.
Signals
Show Signals – enable/disable signal plotting.
Min Squeeze Bars – minimum number of consecutive squeeze bars required for an impulse signal.
Highlight Squeeze Zones – enable/disable background highlighting.
Colors – custom colors for all visual elements.
Usage
The indicator helps identify entry points after consolidation phases. Buy/sell signals should be considered only with confirming factors: higher‑timeframe trend, volume, support/resistance levels. False signals may occur in low‑volatility markets or during news events. It is recommended to backtest and adapt thresholds for the specific instrument.
Disclaimer
This indicator is not financial advice. All calculations are based on historical data and do not guarantee future results. Use it as one of many analytical tools in combination with other methods. אינדיקטור

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. אינדיקטור

אינדיקטור

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. אינדיקטור

אינדיקטור

אינדיקטור

אינדיקטור

אינדיקטור

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. אינדיקטור

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 אינדיקטור

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. אינדיקטור

אינדיקטור

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 🖥️ אינדיקטור

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. אינדיקטור

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
אינדיקטור

אינדיקטור

אינדיקטור

אינדיקטור

אינדיקטור

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. אינדיקטור

אינדיקטור

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.
אינדיקטור
