Obsidian Divergence Ledger [JOAT]Obsidian Divergence Ledger
Introduction
Obsidian Divergence Ledger is an open-source divergence engine built around confirmed pivot logic and a composite oscillator. It tracks regular and hidden divergence, draws ledger lines between the relevant pivot points, and can optionally project those same relationships onto price. The design is meant to make divergence readable as a structured event instead of a vague visual impression.
The problem this script solves is that many divergence tools are either too loose or too noisy. They often compare incompatible pivots, ignore volatility context, or signal before the pivot is confirmed. Obsidian avoids that by waiting for confirmed pivot structures, enforcing minimum spread requirements, and optionally filtering signals through baseline context and volatility expansion.
Core Concepts
1. Composite Oscillator Construction
The script does not depend on one oscillator only. It blends RSI, CMO, and ROC into one composite measure, then normalizes and smooths it. This helps reduce the chance that one indicator-specific quirk dominates the entire divergence decision.
2. Pivot-Confirmed Divergence Logic
Divergence is only evaluated after `ta.pivothigh()` and `ta.pivotlow()` confirm the turning points. That means the signal appears later than an unconfirmed visual guess, but it also means the structure is stable and suitable for non-repainting use.
pricePivotHigh = ta.pivothigh(high, leftBars, rightBars)
pricePivotLow = ta.pivotlow(low, leftBars, rightBars)
3. Regular and Hidden Divergence
The script distinguishes between reversal-type divergence and continuation-type divergence:
Regular bullish: price makes a lower low while the oscillator makes a higher low
Regular bearish: price makes a higher high while the oscillator makes a lower high
Hidden bullish: price makes a higher low while the oscillator makes a lower low
Hidden bearish: price makes a lower high while the oscillator makes a higher high
4. Ledger Line Visualization and Divergence Zoning
Each confirmed event is recorded visually with lines on the oscillator pane. When enabled, price-side lines are also drawn on the main chart using `force_overlay = true`. Regular divergence and hidden divergence use different color families and line styles so reversal and continuation structures are easy to distinguish. Fresh divergence events can also paint oscillator-side pivot zones and price-side context boxes so the compared structure is visible as an area, not just a single line.
5. Context, Freshness, and Impulse Framing
The script tracks whether a divergence is still fresh, whether it aligns with baseline context, and whether current volatility supports the signal. A central impulse ribbon and intensity band expand and contract with current state strength so the pane itself carries more information even when the dashboard is kept compact.
Features
Composite oscillator: RSI, CMO, and ROC blended into one smoother divergence source
Confirmed pivots only: No divergence state is confirmed before pivot confirmation
Regular and hidden divergence: Reversal and continuation structures handled separately
Optional volatility filter: Can require expansion before accepting signals
Optional baseline filter: Can require directional context relative to a baseline
Oscillator and price ledger lines: Divergence is drawn in both the pane and the price chart when enabled
Oscillator pivot zones: Fresh divergence events can stamp colored zones around the compared oscillator pivots
Price context boxes: The related price swing area can be boxed directly on the chart for faster structural reading
On-chart divergence tags: Compact labels identify regular-vs-hidden bullish and bearish events on the chart itself
Impulse ribbon and intensity band: The pane carries fresh-state emphasis through layered fills, not only through text
Compact dashboard summary: State, freshness, oscillator bias, and context remain available in a smaller top-right panel
Input Parameters
Composite Oscillator:
RSI Length
CMO Length
ROC Length
Normalization Window
Oscillator Smoothing
Divergence Engine:
Pivot Left Bars and Pivot Right Bars
Hidden Divergence toggle
Maximum Ledger Lines
Quality Filters:
Volatility Expansion toggle and length
Baseline Context toggle and baseline length
Minimum Oscillator Pivot Spread
How to Use This Indicator
Step 1: Wait for a Confirmed State
Use the dashboard's State and Freshness rows first. The script is designed to treat confirmed divergence as the event, not the early suspicion of divergence.
Step 2: Separate Reversal From Continuation
Regular divergence is generally more useful when looking for exhaustion. Hidden divergence is generally more useful when looking for pullback continuation. The script keeps those two ideas separate on purpose.
Step 3: Read Context Before Weighting the Signal
A bullish divergence below a weak baseline can still fail. A bearish divergence into expanding volatility can still continue. Use the Context and Volatility rows before deciding how much weight to give the latest signal.
Step 4: Use the Zones, Not Only the Lines
The oscillator pivot zones and price context boxes are there to show the compared structure as an area. This is useful when a divergence is technically valid but forms in a narrow or low-importance pocket. A wider, cleaner zone often carries more practical significance than a tiny local pivot mismatch.
Step 5: Use the Price Overlay Lines as Reference
The overlay lines show the exact price pivots involved in the latest comparison. The companion price labels and boxes make it easier to judge whether the divergence formed in an important location or in minor local noise.
Indicator Limitations
Pivot confirmation creates intentional delay because the script waits for bars on the right side of each pivot
Divergence can persist through multiple additional swings before price meaningfully reverses
A composite oscillator reduces single-indicator bias but cannot eliminate false positives
Hidden divergence is context-dependent and is less useful if the broader trend is weak or unclear
Fresh divergence boxes and labels describe the compared structure, but they do not guarantee that the marked zone will react again
Originality Statement
Obsidian Divergence Ledger is original in the way it structures divergence as a confirmed ledger of relationships rather than a simple shape marker. The script combines a custom composite oscillator, explicit regular-vs-hidden separation, freshness tracking, context filters, synchronized pane-plus-price ledger lines, oscillator pivot zoning, and price-context divergence boxes into one coherent tool.
Disclaimer
This script is provided for educational and informational purposes only. It is not financial advice. Divergence is a contextual condition, not a guarantee of reversal or continuation. False signals can occur frequently, especially in strong trends and low-liquidity markets. Use independent confirmation and risk management.
Indicator

Volumetric Trend Structure [BOSWaves]Volumetric Trend Structure - Pivot-Averaged Drift Detection with Volume-Normalized Band Visualization
Overview
Volumetric Trend Structure is a pivot-anchored trend identification system that constructs dynamic drift lines from the rolling average of confirmed swing highs and lows, where trend direction, band positioning, and volume histogram behavior are driven by structural pivot accumulation and statistically normalized volume measurement rather than fixed moving average thresholds or arbitrary volatility multiples.
Instead of relying on lagged moving average crossovers or static band calculations, trend state and directional reference levels are determined through confirmed pivot detection, multi-pivot averaging for drift line construction, and standard deviation-normalized volume scoring that adapts bar-by-bar to reflect genuine volume significance relative to recent history.
This creates a trend framework grounded in actual price structure rather than smoothed price derivatives. Drift lines move only when new confirmed pivots shift the structural average, trend state responds to price crossing structurally-derived boundaries, and the volume histogram mounted directly on the active band provides a continuously updating picture of volume participation intensity and directional character at the exact level that defines the current trend.
Price is therefore evaluated against drift boundaries that represent real swing structure rather than indicator-generated levels disconnected from market geometry.
Conceptual Framework
Volumetric Trend Structure is founded on the principle that robust trend boundaries should be derived from confirmed price structure pivots and their rolling averages, not from smoothed price series that shift continuously regardless of whether meaningful structural events have occurred.
Traditional trend-following methods anchor bands and trend references to exponential or simple moving averages that update on every bar and carry no structural significance in isolation. This framework replaces continuous-update logic with pivot-event-driven drift construction, where the upper and lower drift lines only shift when a new confirmed swing high or low is recorded, ensuring the boundaries reflect actual market structure rather than arithmetic price smoothing.
Three core principles guide the design:
Trend boundaries should emerge from confirmed pivot structure and their averages, providing structurally meaningful levels rather than arbitrary smoothed references.
Volume should be measured relative to its own statistical distribution, normalizing significance across instruments and timeframes rather than using raw absolute values.
Volume visualization should be anchored to the active structural boundary, directly connecting participation data to the trend level that defines current directional state.
This shifts trend analysis from continuous moving average mechanics into event-driven structural drift tracking with volume participation mapped directly onto the defining boundary.
Theoretical Foundation
The indicator combines confirmed pivot high and low detection, rolling pivot array averaging for drift line construction, standard deviation-normalized volume measurement, and directional volume gradient coloring across three configurable display modes.
Pivot highs and lows are confirmed using a configurable left-right bar requirement, ensuring only structurally validated swing points contribute to drift calculation. A rolling array of recent pivots feeds the upper and lower drift lines, with the average shifting only as new pivots register. Volume normalization divides raw volume by its rolling standard deviation, producing a dimensionless score that objectively ranks each bar's participation relative to recent history. Volume histogram bars are then plotted directly on the active drift band, scaled by the normalized score and oriented in the trend direction.
Four internal systems operate in tandem:
Pivot Detection and Array Management : Identifies confirmed swing highs and lows through the configurable pivot length parameter, maintaining rolling arrays of the most recent qualifying pivots for both upper and lower drift calculations.
Drift Line Construction : Averages the contents of each rolling pivot array to produce upper and lower drift lines that update only when new confirmed pivots register, anchoring the trend framework to real structural events.
Trend State Logic : Monitors price crossovers and crossunders of the upper and lower drift lines respectively, flipping trend state and reassigning the active band between the upper and lower drift lines based on current direction.
Volume Normalization and Histogram Engine : Calculates a standard deviation-based volume score, scales it to the chart's price range, and plots histogram bars on the active drift band with configurable directional coloring and spike detection.
This design allows trend structure to reflect genuine pivot-based market geometry while volume participation is measured and visualized with statistical objectivity.
How It Works
Volumetric Trend Structure evaluates price through a sequence of structure-aware processes:
Pivot Confirmation : Swing highs and lows are confirmed when the specified number of bars to the left and right all print lower highs or higher lows respectively, validating structural significance before the pivot is registered.
Array Update and Drift Recalculation : Each newly confirmed pivot is appended to its respective rolling array and the oldest entry removed if the array exceeds the configured pivot count, triggering immediate recalculation of the corresponding drift line average.
Trend Crossover Evaluation : On each bar, price is tested against both drift lines. A crossover above the upper drift establishes bullish state, and a crossunder below the lower drift establishes bearish state, with the previously opposing drift line becoming the new active band.
Active Band Assignment : In a bullish trend, the lower drift line serves as the active structural band providing support reference. In a bearish trend, the upper drift line serves as the active structural band providing resistance reference.
Volume Normalization : Each bar's raw volume is divided by its 200-bar rolling standard deviation, producing a normalized score capped at four standard deviations that objectively quantifies participation intensity.
Histogram Scaling : The normalized volume score is multiplied by a range-derived step size based on the 200-bar average bar range, producing price-unit histogram heights that scale appropriately to the chart without manual adjustment.
Volume Color Assignment : Depending on the selected color mode, histogram bars are colored by buy/sell pressure gradient derived from close position within the bar range (Delta), uniform trend direction (Trend), or trend direction with statistical spike highlighting (Trend + Spikes).
Spike Detection : Bars reaching four standard deviations of volume receive spike classification, triggering directional spike markers and overriding base color in applicable color modes.
Signal and Visual Output : Trend state transitions generate buy and sell triangle labels. Candles are colored with a volume-intensity gradient that brightens with participation strength. A trend fill extends between the active band and price for directional context.
Together, these elements form a continuously updating structural trend map where pivot geometry defines the boundaries and volume participation is measured and displayed with statistical precision directly on those boundaries.
Interpretation
Volumetric Trend Structure should be interpreted as a pivot-derived structural trend system with volume participation mapped onto the active directional boundary:
Bullish Trend State (Green) : Established when price closes above the upper drift line, with the lower drift line becoming the active support band and volume histogram projecting upward from it.
Bearish Trend State (Magenta) : Established when price closes below the lower drift line, with the upper drift line becoming the active resistance band and volume histogram projecting downward from it.
Drift Lines : Upper and lower structural boundaries derived from rolling averages of recent confirmed pivot highs and lows. These lines only shift when new confirmed pivots register, ensuring structural relevance.
Active Band : The drift line currently serving as the primary structural reference. The lower drift in a bullish trend and the upper drift in a bearish trend are displayed with a solid colored line and serve as the histogram anchor.
Trend Fill : Gradient fill between the active band and price provides a continuous visual representation of the distance and directional relationship between current price and the structural boundary.
Volume Histogram : Normalized volume bars extending from the active drift band reflect statistically scaled participation intensity on each bar, oriented upward in a bull trend and downward in a bear trend.
Delta Color Mode : Histogram bars colored by close-position gradient within the bar range, revealing whether volume on each bar was associated with buying or selling pressure regardless of trend direction.
Trend Color Mode : Uniform histogram coloring by current trend direction, providing a clean structural participation view without directional bar-level interpretation.
Trend + Spikes Mode : Trend-colored histogram with statistical spike bars highlighted in a distinct color, identifying exceptional participation events against the structural background.
◆ Spike Markers : Diamond labels plotted at bar highs in a bull trend and lows in a bear trend on statistically exceptional volume bars, marking participation outliers for immediate identification.
▲ / ▼ Trend Signals : Triangle labels at trend state transitions mark the crossover bar where the structural drift boundary was breached, providing clear visual anchoring of each directional change.
Colored Candles : Optional bar coloring reflects trend direction with intensity graduating from muted at low volume to fully saturated at peak participation, providing an immediate conviction reading. Note: The original chart candles must be disabled in chart settings for the trend-colored candles to display properly.
Drift line positioning, active band proximity, and volume histogram behavior at the structural boundary collectively provide more information than any element in isolation.
Signal Logic & Visual Cues
Volumetric Trend Structure presents two primary structural interaction signals alongside continuous volume participation monitoring:
Buy Signal (▲) : Green triangle appears when price closes above the upper drift line, marking the structural crossover that establishes bullish trend state and reassigns the lower drift as the active support band.
Sell Signal (▼) : Red triangle appears when price closes below the lower drift line, marking the structural crossunder that establishes bearish trend state and reassigns the upper drift as the active resistance band.
Volume spike detection provides continuous secondary context, with statistical outlier bars marked regardless of trend state to identify exceptional participation events that may precede structural developments.
Alert generation covers bullish and bearish trend state transitions for systematic structural monitoring workflows.
Strategy Integration
Volumetric Trend Structure fits within structural trend-following and volume-informed directional approaches:
Structure-Confirmed Entries : Use drift line crossovers as trend initiation points where price has demonstrated sufficient strength to breach a structurally-derived boundary, rather than reacting to moving average crossovers with no pivot significance.
Active Band Pullback Framework : Use the active drift band as a pullback reference within established trends, monitoring volume histogram behavior at the band for participation evidence supporting continuation.
Volume Spike Context : Treat spike events occurring near the active drift band as elevated-significance participation readings. Spikes confirming the trend direction at the band suggest strong structural support or resistance.
Delta Mode Flow Analysis : In Delta color mode, monitor the directional gradient of histogram bars at the active band to assess whether volume at the structural boundary is predominantly buying or selling pressure.
Pivot Count Sensitivity Adjustment : Reduce the Pivots to Average count for instruments requiring faster structural adaptation. Increase for markets where drift stability across more pivots better reflects the dominant trend.
Multi-Timeframe Structural Alignment : Apply higher-timeframe drift line positions as directional context, confirming that lower-timeframe entries align with the broader structural trend defined by multi-pivot averaging.
Technical Implementation Details
Core Engine : Confirmed pivot high and low detection with configurable left-right bar requirement
Drift Construction : Rolling array averaging of recent confirmed pivots with configurable array depth
Trend Logic : Drift line crossover and crossunder state switching with active band reassignment
Volume Normalization : Standard deviation-based scoring over 200-bar rolling window with four standard deviation cap
Histogram Scaling : Range-derived step sizing using 200-bar average bar range for chart-adaptive bar heights
Color Engine : Three-mode volume coloring with gradient delta, uniform trend, and trend with spike override
Visualization : Band-anchored volume histogram, trend fill gradient, volume-intensity candle coloring, and signal labels
Performance Profile : Optimized for real-time execution with max_bars_back configuration supporting deep historical pivot detection
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Intraday structural drift tracking with tighter pivot lengths for faster structural response
15 - 60 min : Session-level trend structure identification with balanced pivot and averaging settings
4H - Daily : Swing-level structural trend mapping with higher pivot counts for stable, well-defined drift lines
Suggested Baseline Configuration:
Pivot Length : 3
Pivots to Average : 4
Volume Size : 1.0
Volume Histogram : Enabled
Volume Color Mode : Trend + Spikes
Color Candles : Enabled (requires disabling original chart candles in chart settings)
Trend Fill : Enabled
These suggested parameters should be used as a baseline; their effectiveness depends on the instrument's structural characteristics, pivot frequency, and preferred trend sensitivity, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Too many trend flips : Increase Pivot Length to demand more structurally significant swing confirmations, reducing sensitivity to minor price swings that generate short-lived drift line crossovers.
Trend too slow to respond : Decrease Pivot Length toward 1 for faster pivot confirmation, or reduce Pivots to Average so fewer historical pivots influence the drift line position.
Drift lines too reactive : Increase Pivots to Average to smooth the drift calculation across more structural events, producing more stable trend boundaries that require more significant pivot shifts to move.
Drift lines too stable : Decrease Pivots to Average toward 2 for a more responsive drift that closely tracks the most recent structural swings rather than the broader pivot average.
Volume bars too large or too small : Adjust Volume Size to scale histogram height relative to the default range-derived step, adapting visibility to the instrument's typical price range and volatility.
Spike highlights too frequent : The spike threshold is fixed at four standard deviations and is not user-configurable. Select Trend color mode if spike highlighting creates excessive visual noise on a particular instrument.
Delta coloring unclear : Review whether close positioning within the bar range reliably reflects directional pressure on the target instrument before relying on Delta mode for flow analysis.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
Trending markets with clear swing structure where pivot highs and lows produce well-separated drift lines that provide unambiguous structural boundaries
Instruments with consistent volume patterns where standard deviation normalization accurately identifies statistically significant participation events
Structural pullback strategies monitoring price returns to the active drift band with volume confirmation
Markets where volume participation at swing pivots reliably reflects institutional activity and structural conviction
Reduced Effectiveness:
Choppy, trendless markets where frequent pivot formation causes rapid drift line convergence and repeated trend state flips without directional follow-through
Low-liquidity instruments where volume distribution is erratic and standard deviation normalization produces unreliable spike classifications
Markets with irregular pivot structure where swing confirmation requirements cause significant lag in structural boundary updates during fast-moving directional moves
Extremely compressed consolidation environments where upper and lower drift lines converge closely, reducing the structural differentiation required for reliable trend state assignment
News-driven or gap-heavy instruments where pivot confirmation mechanics miss the structural significance of impulsive moves that do not form clean swing geometry
Integration Guidelines
Confluence : Combine with BOSWaves momentum tools, order flow analysis, or exhaustion level mapping for structural and conviction-layer confluence
Active Band Respect : Monitor volume histogram behavior at the active drift band on each approach. Sustained low-volume retests suggest structural support, while high-volume penetration attempts warrant caution.
Pivot Count Awareness : Recognize that drift lines reflect the average of recent pivots rather than just the latest swing. Sharp structural moves may shift the drift line gradually as older pivots roll out of the averaging window.
Spike Utilization : Treat spike events as participation outliers deserving contextual analysis rather than automatic signals. Their directional significance depends on location relative to the active band and current trend state.
State Discipline : Maintain directional bias aligned with current trend state until the opposing drift line is breached. Short-term price excursions toward the inactive drift line within an established trend do not constitute state changes.
Disclaimer
Volumetric Trend Structure is a professional-grade pivot-derived trend and volume participation analysis tool. It uses confirmed swing pivot averaging with statistically normalized volume measurement but does not predict future price movements. Results depend on market conditions, instrument structural characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates momentum context, order flow analysis, and comprehensive risk management. Indicator

Channel Breakout [EXCAVO]Automatic Convergent Channel Detection with Multi-Filter Breakout Confirmation
The Channel Breakout automatically detects convergent channel patterns — wedges, flags, and triangles — by fitting trendlines through confirmed swing pivots on both boundaries simultaneously. When price breaks out with volume and momentum confirmation, the indicator signals the direction with colored channel lines and an entry label on the breakout candle.
This is not a basic highest/lowest channel. The boundaries are built from verified pivot points, and a convergence filter ensures only genuinely contracting channels qualify — expanding ranges and sideways boxes are excluded.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW TO USE
Step 1 → Add the indicator. It begins scanning for convergent channel
patterns using swing pivots on the current timeframe.
Step 2 → Wait for a channel to form. The indicator draws the upper and
lower boundary lines in blue while price remains inside.
Step 3 → Watch for the breakout signal. When price closes beyond either
boundary with confirmation, channel lines turn blue (bull) or
red (bear), and an arrow label appears on the breakout candle.
Step 4 → Check the dashboard. It shows the current pattern state,
breakout strength (Strong / Medium / Weak), and the directional
bias score that built up while price was inside the channel.
Step 5 → Read the strength rating. Strong breakouts combine high volume,
deep body penetration, and RSI alignment. Weak breakouts show
fewer confirming factors and may warrant additional analysis.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW IT CALCULATES
◆ Pivot Detection
Swing highs and lows are identified with ta.pivothigh / ta.pivotlow using a
configurable lookback (Pivot Detection Length, default 5 bars each side). Only
confirmed, closed pivots are used — no repainting. All recent pivots within the
Max Channel Width lookback are stored and passed to the trendline fitting engine.
◆ Best-Fit Trendline Algorithm
For the upper boundary, the engine tests every pair of stored pivot highs (a, b).
For each candidate line through (a, b), it counts how many other pivot highs lie
within ATR × Touch Tolerance of the line while no pivot exceeds it by more than
ATR × Max Deviation. The line with the most qualifying touches becomes the upper
boundary. The same process runs independently for pivot lows to find the lower
boundary. Both boundaries must exist with at least Min Touches (default 2) to
form a valid channel.
◆ Convergence Filter
Once both boundaries are found, the engine measures channel width at the earliest
shared bar (widthStart) and at the current bar (widthNow):
convRate = 1 − (widthNow / widthStart)
A channel is only accepted when convRate >= Min Convergence Rate (default 0.02).
This rejects expanding wedges and flat ranges, keeping only contracting patterns.
◆ Breakout Detection and Strength Score
On each confirmed bar close, the engine projects both boundary lines to the current
bar. A bull breakout fires when close > upper boundary; a bear breakout when
close < lower boundary. The breakout strength score blends five components:
penetration depth relative to ATR (25%), candle body ratio (15%), body commitment
relative to the broken boundary (15%), volume vs SMA-20 spike (25%), and RSI
alignment above/below 50 (20%). Score >= 65 = Strong, >= 35 = Medium, < 35 = Weak.
◆ Confirmation Filters
Three optional filters gate the breakout signal. Volume Spike Multiplier requires
the breakout bar's volume to exceed 20-bar SMA by a configurable factor. Volume
Contraction Filter requires that average volume inside the channel was lower than
before the channel formed — confirming energy compression. Momentum Confirmation
requires RSI > 50 for bull breakouts and RSI < 50 for bear breakouts. Any filter
can be disabled for forex or low-volume instruments.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ WHAT MAKES IT DIFFERENT
◆ Pivot-Confirmed Boundaries
Most auto-channel scripts use ta.highest / ta.lowest, which anchors lines to the
highest wick in a window regardless of pattern shape. This indicator builds
boundaries only through confirmed swing pivot points, the same anchor logic a
trader would use when drawing manually.
◆ Convergence-Only Filter
The convRate filter rejects any channel that is not actively narrowing. Sideways
ranges, expanding wedges, and parallel channels are all excluded. Only patterns
where price is compressing toward a decision point qualify.
◆ Best-Fit Touch Counting
The engine evaluates every pair of pivots and selects the line with the highest
touch count, not just the first two pivots it finds. A channel supported by four
touches is stronger than one supported by two, and the algorithm reflects that
by preferring denser confirmation.
◆ Multi-Component Strength Score
The breakout strength is not a simple volume check. It combines five independent
signals — penetration depth, body ratio, body commitment relative to the broken
level, volume spike, and momentum direction — into a single 0-100 score that
classifies the breakout as Strong, Medium, or Weak.
◆ Directional Bias Score
While price is inside the channel, the dashboard tracks a real-time directional
bias built from channel slope (35%), RSI deviation from 50 (35%), and price
position within the channel range (30%). This gives a probabilistic lean on
which side of the channel is more likely to break before the signal fires.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ DASHBOARD
Real-time panel (top right) with key state metrics:
Status - Active (channel forming) / Bull Breakout / Bear Breakout / Scanning
Direction - directional bias with arrow and % while channel is active (e.g. ▲ 64%); BULLISH or BEARISH after breakout
Strength - Strong / Medium / Weak (breakout strength score); — while channel is forming
Convergence - narrowing rate of the active channel in %; — when no channel
Legend table (bottom left) explains every visual element. Toggle in Dashboard settings.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ SETTINGS
Main Settings
Pivot Detection Length - 5 (bars left/right for swing pivot confirmation; lower = more sensitive)
Min Touches per Boundary - 2 (minimum pivot touches required per trendline)
Max Channel Width (bars) - 120 (maximum lookback for channel search)
Min Convergence Rate - 0.02 (minimum narrowing ratio; higher = stricter contraction)
Filters
Volume Spike Mult - 1.2 (breakout bar volume vs SMA-20; set 0.5 to disable on forex)
Volume Contraction Filter - ON (require declining volume inside the channel)
Momentum Confirmation - ON (RSI > 50 for bull, < 50 for bear)
Visual
Show Channel Patterns - ON (draw boundary lines)
Show Pattern Background - OFF (subtle bgcolor while inside active channel)
Channel Lines
Line Width - 2 (boundary line thickness; 1-4)
Risk Management
Show Entry Labels - ON (arrow label on the breakout candle)
Dashboard
Show Dashboard - ON
Position - Top Right (Top Left / Top Right / Bottom Left / Bottom Right)
Font Size - Small (Small / Normal)
Advanced
Touch Tolerance (ATR) - 0.15 (pivot distance to count as a touch; 0.10-0.25)
Max Deviation (ATR) - 0.30 (maximum pivot overshoot from the line)
Min Channel Width (ATR) - 0.5 (minimum channel width filter)
Alerts
JSON Alerts - OFF (structured JSON payload for 3Commas, Wunderbit, and similar bots)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ ALERTS
Bull Breakout - price closes above the upper channel boundary with confirmation
Bear Breakout - price closes below the lower channel boundary with confirmation
Any Breakout - either direction; use for a single alert covering both signals
New Pattern - a new convergent channel has been detected and is now active
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best regards,
EXCAVO
Disclaimer
Trading involves significant risk. This indicator is a technical analysis tool
and does not constitute financial advice, investment recommendations, or a
guarantee of future results. Past indicator behavior does not guarantee future
performance. Always use proper risk management and your own judgment.
Indicator

Indicator

Market Phase Detector [JOAT]Market Phase Detector
Introduction
Market Phase Detector is an open-source market structure classification engine that continuously identifies whether price is operating in a Bullish Trend, Bearish Trend, or Range state. The classification uses three independent inputs that must align simultaneously before a regime is confirmed, making the output robust against single-factor noise and false positives that plague simpler trend detectors.
The problem Market Phase Detector solves is context. Trend-following entries during range conditions produce whipsaws. Mean-reversion entries during strong trending moves produce losses against the dominant flow. Knowing the regime before interpreting any other signal improves the relevance of every decision made from it. Market Phase Detector makes that determination automatically, updates it bar by bar, and visualizes both the current regime and every structural event that contributed to it — including labeled BOS and CHoCH events with horizontal level lines, live swing extension lines at the right edge, and an institutional-grade dashboard.
Core Concepts
1. Swing Detection and Pivot Tracking
Price structure is derived from pivot highs and lows confirmed using ta.pivothigh() and ta.pivotlow() with a configurable symmetric lookback. The lookback controls sensitivity — a value of 5 requires 5 bars on each side of the pivot to confirm it, producing only the most structurally significant swings. Each confirmed pivot updates the tracked level and resets its broken flag to allow new break detection on the next cycle:
pivHi = ta.pivothigh(high, swingLen, swingLen)
pivLo = ta.pivotlow(low, swingLen, swingLen)
if not na(pivHi)
topLevel := pivHi
topBroken := false
2. Break of Structure vs Change of Character
Two structural event types are distinguished and tracked independently. A Break of Structure (BOS) occurs when price closes through the previous swing extreme in the same direction as the current structural bias — confirming continuation. A Change of Character (CHoCH) occurs when price closes through the previous swing extreme against the current structural bias — signaling a potential regime flip:
bosBull = bullBreak and structureBias == 1
chochBull = bullBreak and structureBias != 1
Every event is labeled directly on the chart with a horizontal line at the break level and a text label (BOS +, BOS -, CHoCH +, CHoCH -). Running counts of each type are tracked and displayed in the dashboard.
3. Three-Factor Regime Gate
The regime classification evaluates all three inputs simultaneously before assigning a state. Structure bias is set by BOS and CHoCH events. The volatility gate compares current ATR to a moving average of ATR multiplied by a contraction threshold — when ATR falls below this level the market is classified as compressed and the regime defaults to Range regardless of structure or momentum. Momentum uses a smoothed rate-of-change that must confirm the structural direction:
if isLowVol
regime := 0 // Range — volatility gate overrides everything
else if strBias == 1 and roc > 0
regime := 1 // Bullish
else if strBias == -1 and roc < 0
regime := -1 // Bearish
else
regime := 0 // Inconclusive — range
A confidence score (1-3) counts how many of the three factors currently agree and is displayed in the dashboard, allowing the trader to distinguish a fully confirmed 3/3 regime from a weaker 2/3 reading.
4. Swing Level Extension Lines
The current unbroken swing high and swing low are extended as dotted horizontal lines to the right edge of the chart with price labels. These serve as the nearest structural reference levels — the next points where a BOS or CHoCH could occur. They are deleted and redrawn each bar using barstate.islast so they remain current without consuming the indicator's line budget:
if barstate.islast and showSwingExt
line.delete(swingHiLine)
swingHiLine := line.new(topBar, topLevel, bar_index + 4, topLevel,
color=color.new(#E65100, 45), style=line.style_dotted, width=2)
5. Regime Background Shading
The chart background is tinted according to the current regime — faint teal for Bullish, faint orange for Bearish, neutral gray for Range. This gives immediate context at a glance without adding visual noise to the price action.
Features
Three-state regime output: Bullish, Bearish, and Range states derived from structure, volatility, and momentum alignment
BOS and CHoCH event labels: Every structural break labeled on-chart with event type, direction, and horizontal level line
Independent BOS and CHoCH counters: Running totals of each structural event type in the dashboard
Swing level extension lines: Dotted right-edge lines at the current unbroken swing high and low with price labels
ATR-based volatility gate: Low-volatility contraction forces a Range classification regardless of structure or momentum
Smoothed momentum confirmation: Rate-of-change must align with structure before a trending regime is confirmed
Confidence scoring (1/3 to 3/3): Quantifies how many of the three classification factors are currently aligned
Regime background shading: Chart background tint reflects the current regime in real time
Institutional dashboard (top right): 15-row table with regime state, confidence, last break direction and age, BOS and CHoCH counts, swing levels, and ATR
Fully configurable colors: Bullish, bearish, and ranging tints plus structure line colors are independently adjustable
All signals confirmed bar only: No repainting — all structural events fire on barstate.isconfirmed
Input Parameters
Structure Detection:
Swing Lookback: Left/right bars required for pivot confirmation (default: 5)
ATR Period: ATR calculation length (default: 14)
Regime Classification:
Volatility MA Length: MA length for ATR comparison (default: 20)
Range Contraction Multiplier: ATR fraction below which the market is classified as ranging (default: 0.7)
Momentum Lookback: Rate-of-change lookback and EMA smoothing period (default: 10)
Display:
Regime Background Shading toggle
Show Dashboard toggle
Show Structure Lines toggle
Show Swing Level Extensions toggle
How to Use This Indicator
Step 1: Read the Current Regime
Check the REGIME row in the dashboard. BULLISH, BEARISH, or RANGE appears in its corresponding color. This is the primary output. Use it to establish directional bias before consulting any other signal source.
Step 2: Check Confidence Score
The Confidence row shows how many of the three inputs align (e.g., 2/3). A 3/3 reading means structure, volatility, and momentum all agree. A 2/3 reading means one factor is diverging. Weight directional decisions higher during full 3/3 alignment.
Step 3: Monitor CHoCH Events
Each CHoCH label marks a structural break against the current bias — a warning that the regime may be shifting. When a CHoCH appears, watch whether subsequent bars confirm a new opposing BOS or whether the previous regime resumes.
Step 4: Use Swing Extension Lines as Forward Reference
The dotted right-edge lines mark the current unbroken swing levels — the nearest structural break zones. Knowing how close price is to these levels frames where the next BOS or CHoCH could occur.
Step 5: Apply Regime as a Filter
Market Phase Detector is designed as a context layer, not a standalone signal generator. Apply the regime output as a filter to your existing tools: only take long signals when the regime is Bullish, only take short signals when Bearish, and step aside or apply mean-reversion logic when Range is active.
Indicator Limitations
Pivot detection confirms swingLen bars after the pivot forms, creating a natural offset between the candle where the swing occurred and when it is labeled. This is intentional non-repainting behavior
The volatility gate may temporarily classify a new trend as Range immediately after a volatility expansion if ATR has not yet risen above the threshold. This resolves within a few bars as ATR normalizes
In slow, grinding markets, momentum may repeatedly lag structure, resulting in extended Range readings during mild trends
Market Phase Detector classifies current market state. It does not predict future price direction or generate entry/exit signals
Originality Statement
Market Phase Detector is original in its three-factor gate requiring independent alignment of structure, volatility, and momentum before any regime is confirmed. This indicator is published because:
The combination of CHoCH and BOS structural logic, an ATR contraction gate, and a smoothed momentum filter into a single lightweight classifier that produces a confidence score is uncommon in published open-source Pine Script v6
Distinguishing BOS from CHoCH within the same indicator — with independent event counts and labeled historical events — provides structural context that standalone trend indicators do not offer
The confidence scoring system (1-3) quantifies the strength of the current regime reading across three independent analytical dimensions, not just a single oscillator value
Swing level extension lines provide live structural reference at the right edge of the chart without requiring the user to manually draw levels or add a separate pivot indicator
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Regime classifications are based on historical price data and do not guarantee any future market behavior. All three factors can produce inaccurate readings in atypical market conditions. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Regression Flux Candles [JOAT]Regression Flux Candles
Overview
Regression Flux Candles renders a parallel candle series on top of price using linear regression applied independently to each of the four OHLC components. The result is a noise-filtered "flux candle" — a linearised representation of current price action that removes the erratic intrabar variation of raw candles and reveals the underlying trend direction with far greater clarity. A signal line (SMA of regression close) produces crossover buy/sell signals. Pivot-anchored support/resistance zones mark structural confluence areas. A six-timeframe MTF trend table provides session bias context.
The Linear Regression Candle Concept
Standard Japanese candlesticks display the raw open, high, low, and close of each bar — capturing every tick-driven fluctuation including news spikes, stop hunts, and market-maker manipulation. Linear regression candles replace each OHLC component with the endpoint of a linear regression line fitted over the last N bars:
- LR Open = ta.linreg(open, length, 0)
- LR High = ta.linreg(high, length, 0)
- LR Low = ta.linreg(low, length, 0)
- LR Close = ta.linreg(close, length, 0)
The regression fits a straight line through the last N values of each component and returns the value of that line at the current bar. The resulting candle series is significantly smoother than raw price and acts like a weighted moving average of price structure without introducing the directional lag of traditional MAs. Bullish flux candles (LR close >= LR open) render in teal; bearish in purple.
Signal Line and Crossover Logic
A simple moving average of the LR close (default 7-bar SMA) acts as a signal line. When the LR close crosses above the signal line, a potential buy signal is generated. When it crosses below, a potential sell signal is generated. Crossovers are filtered by:
- Volume filter: Volume must exceed the 20-bar volume SMA (configurable). This ensures signals occur during genuine participation, not thin-market noise.
- RSI filter: Buy signals are blocked when RSI(14) >= 70 (overbought); sell signals are blocked when RSI(14) <= 30 (oversold). This prevents buying into extended moves and selling into oversold conditions.
- Warmup gate: All signals are suppressed until max(LR_length * 3, EMA_length + 5) bars have elapsed. This prevents the statistical noise of early LR calculations from generating false signals.
- Confirmed-bar gate: Signals only fire on barstate.isconfirmed — the final tick of a closed bar — preventing any repainting.
Trend EMA
A 200-period EMA (configurable length) is plotted as a gold line representing the macro trend bias. Position of price relative to the 200 EMA serves as a context filter that traders can apply manually: long signals above the EMA are higher quality, short signals below it are higher quality.
Pivot S/R Zones
Swing pivot highs and lows (configurable left/right bars) generate semi-transparent S/R boxes:
- Resistance zones (from pivot highs): drawn in the bear colour with 89% transparency
- Support zones (from pivot lows): drawn in the bull colour with 89% transparency
Each zone extends forward by a configurable width in bars (default 40) from the pivot bar, or can be extended infinitely to the right. A maximum of 6 zones (configurable) are maintained; older zones are deleted as new ones form.
Daily Signal Counter
The dashboard tracks how many buy and sell signals have fired on the current trading day, resetting at each new daily session (detected via ta.change(time("D"))). This provides a quick intraday reference for signal frequency — useful for understanding whether a session is particularly active or quiet.
Multi-Timeframe Trend Table
Six independently configurable timeframes are assessed using the same linear regression logic: LR close >= LR open on each HTF = bullish; below = bearish. Each cell displays BULL or BEAR in its directional colour. An alignment counter shows how many of the six timeframes agree with the current LR direction. 5+ aligned = strong directional bias (teal); 1 or fewer = strong counter-trend warning (red); middle values show gold.
Inputs Reference
Regression Engine
- LR Length (11) — lookback for all four linear regression calculations
- Signal SMA Length (7) — SMA applied to LR close for crossover signal line
- Trend EMA Length (200) — macro bias reference line
Filters & Signals
- Volume Filter on Signals — require volume > volume SMA
- Volume SMA Length (20)
- RSI Filter on Signals — block overbought/oversold crossovers
- RSI Length (14)
S/R Zones
- Pivot Left/Right Bars (15/10) — pivot detection sensitivity
- Show S/R Zones
- Extend Zones to Right — infinite extension toggle
- Zone Width (40 bars) — forward extension length when not extending to right
- Max Zones to Show (6)
MTF Dashboard
- Show MTF Table
- TF 1–6 — six configurable timeframes (default: 1, 5, 15, 60, 240, D)
Visual
- Bull / Bear Candle Color — OHLC candle colours for flux candles
- Signal Line Color — signal SMA line colour
- EMA Color — trend EMA line colour
- Show Dashboard
How to Use
1. Apply to any liquid market. Use LR length of 9–15 for intraday charts; 20–30 for swing trading.
2. Watch for flux candle colour transitions: a sustained sequence of teal candles above the signal line confirms an uptrend; purple candles below confirm a downtrend.
3. BUY labels appear below the bar when LR close crosses above the signal line with volume and RSI conditions met. SELL labels appear above the bar on crossunders.
4. Prefer signals where the flux candle direction (teal/purple) aligns with the EMA bias AND the MTF table shows 4+ timeframes in agreement.
5. S/R zones from prior pivots serve as target levels and potential reversal points — align entries near these zones for improved risk/reward.
Non-Repainting Design
All signals require barstate.isconfirmed. MTF data uses lookahead_off. LR calculations use only confirmed historical bars (offset 0 is the current bar's regression endpoint based on past data). Signal labels never move after being stamped on a closed bar.
Limitations
- Linear regression candles reduce volatility information. In sharp, impulsive markets, the flux candle series will understate the actual price range. Raw candles should be viewed alongside the indicator for context.
- Short LR lengths (< 7) make the flux candles nearly identical to raw candles; very long lengths (> 30) introduce significant lag into the signal line crossovers.
- The volume and RSI filters may suppress signals during thin trading hours on forex pairs (e.g., Asian session on EUR/USD pairs). Disabling filters during these sessions is a valid adjustment.
- S/R zones are drawn from the pivot confirmation bar, not the pivot bar itself (due to the right-bar confirmation delay). Zone left edges are placed correctly but appear N bars after the actual pivot.
Disclaimer
This indicator is for educational and informational purposes only. Linear regression candles and crossover signals are technical analysis tools and do not predict future price movement. Always use proper risk management and conduct your own analysis.
Made with passion by officialjackofalltrades
Indicator

PivotStructureOutline_UtilitiesThis library contains reusable pivot structure outline helpers for Pine scripts that already work with confirmed pivot highs and lows. It is designed to provide the reusable outline and anchor-box layer for scripts that already have their own pivot-confirmation logic, so those scripts can keep their structure visuals consistent without repeatedly rebuilding the same framework.
It brings together the parts of the workflow that are often rewritten in structure-based scripts: resolving pivot-close anchors, selecting wick vs close anchor behavior, building live outline geometry, building pivot structure anchor-box geometry, and managing the line and box objects that render those visuals.
Everything on the example chart is materially driven by the library, whether through the selected outline anchor source, the outline geometry itself, the midpoint-start logic, the pivot structure anchor boxes, or the shared line/box lifecycle helpers used to keep those visuals updated cleanly on the chart.
How to use
Import the library near the top of your script in global scope, alongside any other imports, before you start calling its helpers. This mirrors the import-first usage pattern shown on your recent library page.
Typical placement:
//@version=6
indicator(...) or strategy(...)
import MYNAMEISBRANDON/PivotStructureOutline_Utilities/1 as PSOutils
This library is engine-agnostic. It does not confirm pivots for you. Instead, it expects your script to already know its confirmed high/low pivot indexes and anchor values, then uses those resolved inputs to build the outline and anchor-box layer.
➖Outline Line Style Helpers➖
These helpers convert simple UI-facing style strings into Pine line style enums so scripts can keep one consistent style resolver across outline lines, midpoint lines, and connector lines.
outlineLineStyle(styleIn)
Resolves a Pine line style from a string input.
Parameters:
styleIn (simple string): Style string. Expected values: "Solid", "Dashed", or "Dotted"
Returns:
Pine line style enum
➖Pivot Structure Outline Helpers➖
These helpers build the actual pivot structure outline framework from already-confirmed high/low pivot anchors. They let a script resolve a pivot-close anchor, choose whether the outline should use wick or close anchors, and generate the live geometry needed for the top line, bottom line, midpoint, and left-side connectors.
outlinePivotCloseFromIdx(pivotIdx, closeValue)
Returns the close value belonging to a confirmed pivot index.
Parameters:
pivotIdx (int): Confirmed pivot bar_index
closeValue (float): Close series
Returns:
Confirmed pivot close value
outlineSelectedAnchors(anchorMode, highWickAnchor, lowWickAnchor, highCloseAnchor, lowCloseAnchor)
Selects the active outline anchors from Wick or Close mode.
Parameters:
anchorMode (simple string): Anchor mode. Expected values: "Wick" or "Close"
highWickAnchor (float): Confirmed high-side wick anchor
lowWickAnchor (float): Confirmed low-side wick anchor
highCloseAnchor (float): Confirmed high-side close anchor
lowCloseAnchor (float): Confirmed low-side close anchor
Returns:
Selected high anchor, selected low anchor, is outline-valid
outlineGeometry(highPivotIdx, lowPivotIdx, highAnchor, lowAnchor, connectorSourceMode, midlineStartMode, highValue, lowValue, closeValue)
Returns the live geometry for the pivot structure outline system.
Parameters:
highPivotIdx (int): Confirmed high pivot bar_index
lowPivotIdx (int): Confirmed low pivot bar_index
highAnchor (float): Selected top outline anchor
lowAnchor (float): Selected bottom outline anchor
connectorSourceMode (simple string): Connector source mode. Expected values: "Wick" or "Close"
midlineStartMode (simple string): Midline start mode. Expected values: "Most Recent Pivot" or "Left Outline"
highValue (float): High series
lowValue (float): Low series
closeValue (float): Close series
Returns:
ok, leftX, rightX, midX1, topY, bottomY, midY, leftTopConnectorY, leftBottomConnectorY
➖Pivot Structure Anchor Box Helpers➖
These helpers build directional top and bottom pivot structure anchor boxes from confirmed pivot bars. They let a script choose whether those boxes use wick-only extension from the candle body or the full candle body, then return the live coordinates needed to render those boxes forward to the current bar.
outlineAnchorBoxGeometry(highPivotIdx, lowPivotIdx, boxAreaMode, openValue, highValue, lowValue, closeValue)
Returns the live geometry for top and bottom pivot structure anchor boxes.
Parameters:
highPivotIdx (int): Confirmed high pivot bar_index
lowPivotIdx (int): Confirmed low pivot bar_index
boxAreaMode (simple string): Box area mode. Expected values: "Wick" or "Body"
openValue (float): Open series
highValue (float): High series
lowValue (float): Low series
closeValue (float): Close series
Returns:
showHighBox, showLowBox, highLeftX, lowLeftX, boxRightX, highTopY, highBottomY, lowTopY, lowBottomY
➖Line Object Helpers➖
These helpers manage the lifecycle of live line objects so scripts can create, update, or delete outline-related lines without rewriting that object-management logic each time.
outlineManageLine(enabled, ln, x1, y1, x2, y2, col, width, style)
Creates, updates, or deletes a line object.
Parameters:
enabled (bool): Whether the line should exist
ln (line): Existing line reference
x1 (int): Start x position
y1 (float): Start y position
x2 (int): End x position
y2 (float): End y position
col (color): Line color
width (int): Line width
style (string): Line style
Returns:
Updated line reference
➖Box Object Helpers➖
These helpers manage the lifecycle of live box objects so scripts can create, update, or delete pivot structure anchor boxes without repeating the same box-management code in every script.
outlineManageBox(enabled, bx, left, top, right, bottom, bgColor, borderColor, borderStyle, borderWidth)
Creates, updates, or deletes a box object.
Parameters:
enabled (bool): Whether the box should exist
bx (box): Existing box reference
left (int): Left x position
top (float): Top y position
right (int): Right x position
bottom (float): Bottom y position
bgColor (color): Box background color
borderColor (color): Box border color
borderStyle (string): Box border style
borderWidth (int): Box border width
Returns:
Updated box reference
Library

Break-Retest Quality [AGPro Series]Break-Retest Quality
🎯 OVERVIEW
Break-Retest Quality is a precision-focused structure toolkit that detects pivot-based breaks of structure (BOS) and grades the first retest of the broken level using a transparent, multi-factor quality score. Instead of only drawing a break line and leaving you to guess whether the retest "looked clean", the script quantifies the retest with a 0-100 score and an A / B / C / F letter grade so you can quickly separate high-conviction pullbacks from low-quality ones. It is a discretionary context tool built for price action traders, SMC / ICT practitioners and anyone who builds setups around break-and-retest logic.
The system is fully automated, non-repainting after confirmation, and works on any symbol and timeframe that PulseWire supports.
📐 UNIQUE EDGE — WHAT MAKES IT DIFFERENT
Most break-of-structure indicators stop at drawing a line and an arrow. Break-Retest Quality goes further:
🔹 Every retest is scored on six independent factors and translated into an A / B / C / F grade
🔹 The acceptance zone is an ATR-scaled rectangle that changes color and state as the setup evolves (live WATCH → graded RETEST)
🔹 A "Min Grade To Display" filter keeps weak retests off the chart, so the visual footprint stays clean
🔹 A right-edge WATCH tag pins the currently active level so you never lose track of the live setup
🔹 A compact two-line retest marker shows grade, score and a short outcome tag in a minimal footprint
🔹 Built-in cooldown and single-retest-per-break logic prevent label clutter on choppy price action
This is not a repackaged BOS indicator — it is a quality filter on top of BOS / retest logic.
🧪 METHODOLOGY
1. STRUCTURE DETECTION
Pivot highs and lows are detected with a user-defined Pivot Length. A break is registered when price clears the most recent pivot by at least Min Break ATR Filter × ATR, either on a close (default) or on a wick.
2. RETEST TRACKING
After a confirmed break, the script opens an acceptance zone of ± Retest Tolerance ATR × ATR around the broken level and watches for the first price revisit within Max Bars For Retest.
3. QUALITY SCORING (0-100)
The first retest is graded on six weighted factors:
🔸 Reclaim (25 pts) — how decisively the close reclaims the correct side of the level
🔸 Rejection (20 pts) — wick / body composition on the retest bar
🔸 Depth (20 pts) — how close the extreme of the retest bar lands to the level (no excessive overshoot)
🔸 Speed (15 pts) — how quickly the retest prints after the break
🔸 Volatility (10 pts) — bar range discipline relative to ATR
🔸 Volume (10 pts, optional) — relative volume vs 20-bar SMA
Final score → Grade: A ≥ 80, B ≥ 65, C ≥ 50, F < 50.
4. CONFIRMATION LOGIC
A retest is marked "confirmed" only if the score meets the Min Grade For Confirmation threshold AND the close lands on the correct side of the broken level.
🔔 SIGNALS & ALERTS
Three PulseWire alert conditions are exposed:
🔹 Structure Break Detected — fires the moment a valid break is registered
🔹 First Retest Detected — fires on the first qualifying revisit inside the acceptance zone
🔹 High-Quality Retest Confirmed — fires only when the graded retest meets the confirmation threshold
⚙️ KEY INPUTS
STRUCTURE
• Pivot Length, Use Close Confirmation, Min Break ATR Filter, ATR Length
RETEST
• Max Bars For Retest, Retest Tolerance ATR, Cooldown Bars After Completed Setup, Resolved Zone Extension
SCORING
• Show Numeric Score / Grade, Use Volume Confirmation, Min Grade For Confirmation, Min Grade To Display
VISUALS
• Show Break Line / Labels / Retest Marker / Retest Zone / Watch Zone Text / Resolved Zone Text / Active Level Glow / Right-Edge Watch Tag / Invalidation Line / Outcome Text, Use Grade Colors, Zone Forward Extension, Label Size
PANEL
• Show Panel, Panel Position, Panel Font Size, Show Last Result Row
RUNTIME
• Keep Last Setups (controls how many historical setups stay on the chart)
🧭 HOW TO USE
1. Add Break-Retest Quality to any chart and timeframe. Adjust Pivot Length to match the structure you care about (lower on intraday, higher on swing).
2. Wait for a BRK▲ or BRK▼ label to print — this confirms a structure break.
3. Observe the live acceptance zone and the right-edge WATCH tag. These mark the level and the remaining retest window.
4. When price returns to the zone, read the two-line retest marker: grade + score on the top line, short outcome tag (Strong / Valid / Weak / Failed) on the bottom line.
5. Use the panel to monitor live state, active level, remaining window and the last completed result with its full outcome description.
6. Combine with your own confluences — higher-timeframe bias, liquidity levels, session context, volume profile — before acting on any signal.
⚠️ LIMITATIONS & TRANSPARENCY
🔹 This is an analytical and educational tool, not a strategy. It does not generate buy / sell orders and does not measure historical performance.
🔹 Grades describe the geometric and relative-volume quality of the retest bar at the moment it prints. They are not predictions of future price movement.
🔹 Scores calculated at bar close are final; intra-bar readings can shift until the bar closes.
🔹 The volume factor depends on exchange-supplied volume data. Turn it off on instruments where volume is unreliable or missing.
🔹 Pivot-based structure is sensitive to the Pivot Length setting. Choose it deliberately for the timeframe and symbol you are analyzing.
📢 RISK DISCLOSURE
Trading involves substantial risk and is not suitable for every investor. Past price behavior is not indicative of future results. This indicator is provided for educational and analytical purposes only and does not constitute financial advice, investment advice, or a solicitation to trade any instrument. Always perform your own research and risk management before acting on any signal. Indicator

Auto Trendlines MTF - Break/Retest [AGPro Series]Auto Trendlines MTF - Break/Retest
🔹 OVERVIEW
Auto Trendlines MTF - Break/Retest is a multi-timeframe trendline visualization engine that automatically detects and draws the most structurally significant trendlines across three complementary scales: Micro (current timeframe), Meso (intermediate pivots), and Mega (HTF weekly/monthly overlay). Instead of relying on a single pivot scan, the engine builds a ranked candidate pool from each scale and selects the lines that best represent the active market structure around current price.
The script is designed as a pure analytical visualization tool — it does not generate trading decisions, forecasts, or directional recommendations. Its purpose is to give the chart a clean, hand-drawn-quality trendline layer that updates automatically as new pivots form.
🎯 UNIQUE EDGE
Most auto-trendline tools scan one timeframe and draw whatever fits. This engine operates differently in four specific ways:
• Three-scale MTF engine. Micro pivots on the current TF, Meso pivots with wider sensitivity, and Mega trendlines derived from Weekly/Monthly HTF pivots are computed independently and rendered together with a visual hierarchy (Mega dominant, Meso intermediate, Micro active).
• Log-space geometry. All trendline math runs in log-price space, so long-dated diagonals on volatile assets (crypto, growth stocks) do not distort visually when the chart is viewed in logarithmic mode.
• Touch-weighted ranking with violation penalty. Each candidate line is scored by touch count, line age, slope sanity, price proximity, and intra-line violations. Weak geometry, over-sloped lines, and frequently violated lines are demoted automatically.
• Q quality score (0–100) and confluence tags (x2/x3). Every drawn line carries a Q score that blends touches, freshness, geometry, relevance, and violations into a single number. Confluence tags surface when a Micro line and a Meso line sit within the same ATR band near price, highlighting multi-scale structure overlap.
🧠 METHODOLOGY
1. Pivot detection. Separate pivot streams are maintained for Micro (tight sensitivity), Meso (wider sensitivity), and Mega (HTF pivots via request.security).
2. Candidate generation. For each scale, the engine pairs anchor pivots with subsequent pivots to form line candidates, discards over-sloped ones, and computes touches, violations, and break status in log space.
3. Ranking. Candidates are scored by a weighted combination of touch count, time span, slope sanity, relevance to current price (distance in ATR), and violation count. The best non-duplicate lines are kept per scale.
4. Clutter guards. A minimum ATR separation rule prevents near-duplicate lines from stacking. Smart Focus hides far-from-price lines in Minimal/Balanced density modes to keep the chart readable.
5. Stability mode. In Locked mode, selected lines persist bar-to-bar and are only replaced when they break or fall out of the candidate pool — reducing visual repainting on lower TFs.
6. Break/Retest detection. Once a line is drawn, the engine tracks close-based breaks (with configurable tolerance) and subsequent retests within a time window, emitting labeled signals on TF ≤ 1D.
⚙️ SIGNALS & ALERTS
Break and retest events are plotted for each scale with short ASCII tags:
• µR / µS = Micro Resistance / Support break
• mR / mS = Meso Resistance / Support break
• MR / MS = Mega Resistance / Support break
• rµ / rm / rM = retest on Micro / Meso / Mega respectively
A dedicated alertcondition is exposed for every break and retest event, plus two aggregate alerts (Any BR, Any RT) for users who prefer a single alert stream. A Min Q filter lets the user suppress low-quality signals.
🛠️ KEY INPUTS
• Profile Mode. Auto by Timeframe or Manual (Clean Trader, Balanced, Analyst, Presentation, Custom).
• Density Override. Minimal, Balanced, or Bold visual density.
• Line Weight Override. UltraThin, Thin, or Normal.
• Labels / Signals / Stability / Broken-line behavior. All individually overridable.
• Mega Overlay. Full (lines + cloud + label), Lines Only, or Off.
• Advanced panels. Micro Engine, Meso Engine, Mega Engine, Ranking, Visuals, and Signals each expose their own fine-tuning controls for experienced users.
• HUD. Position, theme (Classic Gray, Premium Accent, Color Coded, Showcase), and text size.
📘 HOW TO USE
• Add the script to any liquid symbol and start on a 1H or 4H chart.
• Leave Profile Mode on "Auto by Timeframe" for a balanced default that adapts to the active TF.
• Read the HUD in the top-right corner to see the active profile, how many Micro/Meso lines are drawn, whether Mega is active, and current Q scores.
• When a line carries a Q score above ~65 and a Conf tag (x2 or x3) appears nearby, that zone is a multi-scale structural pocket — use it as a planning reference, not as a trade trigger on its own.
• Use the Break/Retest tags for situational awareness around drawn lines; combine with your own confirmation logic before acting.
⚠️ LIMITATIONS & TRANSPARENCY
• Lines are drawn from historical pivots and can only confirm after a pivot is established. The engine avoids repainting in Locked mode but cannot predict future pivots.
• Q scores and confluence tags describe structural quality, not directional probability. A high-Q line can still break.
• Mega lines depend on HTF pivot availability; on very young symbols or thin charts, Mega may fall back to a Macro-pivot source or remain hidden.
• The script is published as Public, Open Source so that every ranking rule, weight, and threshold is fully auditable in the source code.
🛡️ RISK DISCLOSURE
This script is a visualization and analysis tool only. It is not financial advice, not a trading strategy, and not a signal service. No performance claims are made or implied. Past structural behavior of trendlines does not guarantee future behavior. All trading decisions, risk sizing, and execution remain the sole responsibility of the user. Indicator

Pivot Channel Map [AGPro Series]Pivot Channel Map
🔹 OVERVIEW
Pivot Channel Map is a structural channel engine that automatically detects and classifies market structure channels from confirmed swing pivots. It organises every qualified channel into a clear 8-family taxonomy (Major / Minor × External / Internal × Up / Down) and renders them as a living map of trend, range and reversal context. The script works on all instruments and timeframes, with a focus on intraday and swing analysis.
Instead of plotting a single trendline or band, the engine maintains a continuously updated structural map: active channels, their midlines, interaction pockets around the rails, preserved broken channels, and post-break retest / reclaim signals. A compact right-corner panel summarises live channel counts, qualification state, nearest channel distance in ATR units, and the prevailing Major tilt.
The goal is to give discretionary traders a moderation-safe, clutter-controlled view of where price is inside the broader structure — not to predict future prices.
🔸 UNIQUE EDGE
Most channel indicators draw one or two parallel lines and call it a day. Pivot Channel Map adds structural classification, qualification, memory and post-event follow-through on top of the channel geometry:
- Eight channel families instead of a single pair of rails
- ATR-normalised qualification engine (Off / Balanced / Strict) to filter structurally weak channels
- Broken Channel Memory that preserves invalidated structure as faded historical context
- Interaction Zones (right-edge ATR pockets) around active channel rails
- Post-Break Retest / Reclaim tracker that tags the first valid touch after a confirmed break
- Break and React event markers on Major channels
- ATR-based distance tagging in the info panel (Near / Mid / Wide / Far)
The result is a richer structural read than a standard channel script, while still staying visually clean through emphasis, opacity and clutter controls.
🔹 METHODOLOGY
1. Pivot detection. A configurable Pivot Period drives ta.pivothigh and ta.pivotlow to produce confirmed swing pivots. The script then classifies each pivot into H / HH / LH / HL / LL / L roles and promotes / demotes them between Major (M*) and Minor (m*) status based on close breaks versus the current Major range.
2. Channel construction. From the classified pivot stream, eight channel families are built:
- Major External Up / Down
- Major Internal Up / Down
- Minor External Up / Down
- Minor Internal Up / Down
External channels trace structural HH/LL extremes, Internal channels trace LH/HL interior swings.
3. Qualification. Each candidate channel is width-measured against ATR and span-measured in bars. The Qualification Engine (Off / Balanced / Strict) filters out structurally weak channels before they are drawn.
4. Life-cycle management. Active channels are redrawn and extended forward each bar until an origin-rail or channel-rail break is confirmed. On break, the previous structure can be preserved by Broken Channel Memory (Off / Major Only / All) with its own style and opacity.
5. Event detection. Confirmed origin-rail breaks produce BREAK events; wick-through-then-close-back moves produce REACT events on Major channels. A cooldown and an ATR-based price-distance filter prevent label clusters when price oscillates around the same rail.
6. Post-break follow-through. After a confirmed break, the script tracks the first valid touch inside a configurable window and tags it as RETEST (channel-rail break) or RECLAIM (origin-rail break).
🔸 SIGNALS & ALERTS
On-chart events:
- BREAK — confirmed close-based break of a Major channel rail
- REACT — wick through the Major rail with a close back inside, filtered by bar cooldown and ATR distance
- RETEST / RECLAIM — first valid touch of the broken rail inside the post-break window
- Interaction Zone contact — visual ATR pocket around active channel rails
- Channel Quick Tags (MEX / MIN / mEX / mIN, Up / Dn) — compact family labels on active channels
Alert conditions (all 16 toggleable, Major alerts On by default, Minor Off by default):
- Break: Major External Up / Down
- React: Major External Up / Down
- Break: Major Internal Up / Down
- React: Major Internal Up / Down
- Break: Minor External Up / Down
- React: Minor External Up / Down
- Break: Minor Internal Up / Down
- React: Minor Internal Up / Down
Message frequency is configurable (All / Once Per Bar / Once Per Bar Close). Alerts include symbol, timeframe, time zone and event description.
🔹 KEY INPUTS
- Pivot Engine: Pivot Period (default 5)
- Per-family Visibility: 8 Show / Delete-Previous / Color / Style / Extend / Width groups
- Channel Qualification: Mode (Off / Balanced / Strict), Apply To (All / Major Only / Minor Only), ATR Length
- Broken Channel Memory: Scope (Off / Major Only / All), Keep (Last 1 / Last 2), Style
- Channel Midline: Show, Apply To, Scope, Style, Width, Opacity
- Active Map Clarity: Line Emphasis, Base-Line Focus, Event Markers, React Cooldown, React Min Price Distance, Quick Tags, Tag Scope, Tag Size, Event / Quick Tag Vertical Offsets
- Interaction Zones: Scope, Rails, Zone Width ATR, Extend Bars, Opacity, Zone Text
- Post-Break Retest / Reclaim: Scope, Window Bars, Label Offset ATR
- Panel: Show, Position, Font Size
- Alerts: 16 per-family Break / React toggles, Alert Name, Frequency, Time Zone
🔸 HOW TO USE
Getting started:
1. Apply the indicator on any symbol and timeframe.
2. Start with default settings: Qualification Off so the full structural map is visible.
3. If the chart feels busy on lower timeframes, switch Qualification to Balanced or Strict.
Reading the panel:
- Major Live / Minor Live — active channels per class
- Nearest Channel — closest active channel, with ATR distance and Near / Mid / Wide / Far tag
- Qualification — current filter mode and scope
- Interaction — interaction zone scope and rails
- Post-Break — tracker scope, window and prevailing Major tilt
Common workflows:
- Trend continuation: wait for price to hold an Active Major channel and look for a REACT at the rail inside the channel direction.
- Break-and-retest: after a BREAK event, watch for the RETEST / RECLAIM label inside the Post-Break window.
- Confluence: use Interaction Zones to spot where Major and Minor rails meet at the right edge of the chart.
- Higher-timeframe context: open a higher timeframe tab with the same script to map macro structure around your execution timeframe.
Suggested defaults:
- Intraday traders: 15m–1H base TF, Balanced qualification
- Swing traders: 4H–1D base TF, Balanced or Off qualification
- Higher-timeframe context: 1D–1W with Qualification Off
🔹 LIMITATIONS & TRANSPARENCY
- Pivot-based. Pivots require the configured number of bars to confirm, so the most recent swing always lags by Pivot Period bars. This is a structural property of confirmed pivots, not a bug.
- Redraw behaviour. Active channels are extended forward each bar until a break is confirmed on close. Channel end-points can therefore adjust as new pivots qualify.
- Alerts fire on confirmed conditions. Break and React alerts require barstate.isconfirmed, so intra-bar touches do not trigger alerts.
- Timeframe behaviour. On very high timeframes with limited history (e.g. weekly / monthly on newer instruments), the total pivot count can be small. Keep Qualification at Off on higher timeframes to avoid over-filtering.
- This is a visualisation / structure tool. It is not a trading strategy, it does not manage risk, and it does not generate buy / sell recommendations. All entries and exits are the trader’s responsibility.
🔸 RISK DISCLOSURE
This script is a technical analysis tool intended for educational and analytical purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any asset. Past chart behaviour does not guarantee future results. Trading involves significant risk and can result in the loss of capital. Always do your own research, use proper risk management, and consider consulting a licensed financial advisor before making trading decisions. Indicator

Compression Pressure Map [AGPro Series]Compression Pressure Map
⚡ Overview
────────────────────────────────────────
Compression Pressure Map is a structural context tool that measures how tightly price is compressing against the nearest pivot-based level, and evaluates two behavioral scenarios in parallel: breakout anticipation and reversal watch. The output is a visual map of where pressure is accumulating — rendered as an evolving pressure zone that moves through BUILDING, ARMED and READY states.
This is not a signal engine, not a forecast, and not a trading strategy. It is a visualization layer that answers a single question: where is compression building around the active level, and in which direction is that pressure leaning.
🧭 Unique Edge
────────────────────────────────────────
Most compression indicators reduce behavior to a single direction. CPM separates compression into two parallel scoring engines that run on the same structural core:
🔹 Breakout Anticipation — pressure building for a directional break through the level
🔹 Reversal Watch — pressure building for a rejection at the level
In Auto mode the dominant scenario is rendered on the chart (cleaner visual), while the panel shows both scores side by side for transparency. Power users can lock the engine to a single mode. The active level is stabilized with a clustered pivot refinement and a drift-control lock, so the displayed level stays consistent instead of jumping on every new pivot. A compression gate keeps the pressure score aligned with the compression core: when compression is weak, pressure cannot escalate into high states.
🧪 Methodology
────────────────────────────────────────
The pressure score is a weighted composite of six structural components, measured on the active scenario:
🔹 Range compression (short-window range vs long-window range)
🔹 ATR compression (short-window ATR vs long-window ATR)
🔹 Body tightness (average body size relative to average range)
🔹 Quiet-bar persistence (how many recent bars qualify as calm)
🔹 Proximity to the active level (normalized by ATR)
🔹 Directional posture (slope, close position in bar)
Reversal scoring adds wick-rejection weight at the active level (average lower-wick size for bull reversals, upper-wick size for bear reversals). Breakout scoring adds approach slope weight toward the active level. A shared EMA smoothing step produces calmer state transitions. A dominance margin and cooldown prevent rapid scenario flipping. The final score is driven through a BUILDING → ARMED → READY state machine with hysteresis on the zone visibility to avoid flicker.
🎯 Signals & Alerts
────────────────────────────────────────
The state machine produces four transition alerts plus two pace alerts:
🔹 Pressure Armed Near Level — score crosses the armed threshold with an active scenario
🔹 Ready Zone Reached — score crosses the ready threshold with an active scenario
🔹 Armed Bullish / Bearish Scenario — directional armed transitions
🔹 Ready Bullish / Bearish Scenario — directional ready transitions
🔹 Pressure Rising — score is climbing while the zone is live
🔹 Pressure Released — the active scenario resolves (through the level or by decay)
On the chart, state transitions are marked with discrete A and R markers on the active side. A score label near price always shows the current pressure value, bias and state for quick reading without opening the panel.
⚙️ Key Inputs
────────────────────────────────────────
🔹 Engine Mode — Auto, Breakout Anticipation, or Reversal Watch
🔹 Compression Length — main lookback for range, ATR and body tightening
🔹 Trigger Distance (ATR) — how close price must be to a level to start evaluating
🔹 Hold Distance (ATR) — how far price can drift before the active context is cleared
🔹 Pivot Left/Right and Cluster Tolerance — pivot strength and blending behavior
🔹 Compression Gate and Gate Threshold — compression-first discipline control
🔹 Armed / Ready / Zone On / Zone Off Thresholds — state machine calibration
🔹 Full visual controls — zone width, band extend, line width, label size, panel position and font
All defaults are tuned for mid-volatility crypto pairs on 1H and 4H timeframes, but the engine adapts across symbols and timeframes through its ATR-normalized distance logic.
📘 How to Use
────────────────────────────────────────
🔹 Open the indicator in Auto mode and observe which scenario the panel highlights
🔹 Wait for the pressure zone to appear on the chart (BUILD → LIVE transition)
🔹 Read the state: BUILDING means the setup is forming, ARMED means the setup is mature, READY means compression and proximity are both at peak
🔹 Cross-reference with your own structural read — CPM describes the compression landscape, the decision is yours
🔹 If you prefer one behavioral lens only, lock the engine to Breakout Anticipation or Reversal Watch
🔹 Use the Compression Gate to enforce compression-first discipline — when compression is weak, the pressure score stays in WATCH
🔹 The tool is timeframe-agnostic; try it on 15m, 1H, 4H and 1D to see how compression contexts nest
CPM is designed to sit alongside your strategy, not replace it. It maps the compression field; you read the context.
⚠️ Limitations & Transparency
────────────────────────────────────────
🔹 CPM is a context visualization tool, not a signal generator — it does not issue buy or sell calls
🔹 The pressure score is a structural measurement, not a probability estimate
🔹 State transitions describe the compression field at the moment they print; they do not imply what happens next
🔹 Active level refinement is intentionally conservative — the level may feel slower to update than raw pivots, by design
🔹 Very high volatility regimes may keep the compression score low for extended periods, which is the intended behavior
🔹 The tool is deterministic on closed bars; intrabar values are provisional until bar close
CPM is released as Public, Open-source under MPL 2.0. The source is fully readable and auditable.
🛡️ Risk Disclosure
────────────────────────────────────────
This indicator is published for educational and analytical purposes only. It is not financial advice, not a trading strategy, and not a recommendation to buy or sell any asset. Past behavior of any level or pressure state does not predict future behavior. Markets carry risk of loss; users are solely responsible for their own decisions and risk management. Always do your own research and consider consulting a qualified professional before making trading or investment decisions. Indicator

Aura Pivot S/R Matrix [Pineify]Aura Pivot S/R Matrix
This indicator turns confirmed swing pivots into volatility-adaptive support and resistance zones rather than single horizontal lines. The thickness of each zone is derived from a 200-bar ATR snapshot taken at the pivot bar itself — so a level formed during a quiet consolidation gets a narrower zone than one formed during a wide-range expansion, without any manual tuning per instrument. Each zone tracks forward with price until a full close breaks through it, at which point the zone is frozen and labeled as a breakout or breakdown.
Key Features
ATR-scaled zone thickness anchored to the volatility regime at the pivot bar, not the current bar
Forward-extending zones that visually "track" price until broken, then freeze as a historical record
Close-based break detection that filters out wick probes and test-and-reject candles
Per-zone state management via a user-defined type — each zone behaves as an independent object with its own lifecycle
Breakout and breakdown labels printed at the exact bar of confirmation
How It Works
Each zone is built through a three-stage pipeline — pivot confirmation, volatility-scaled construction, and lifecycle tracking.
A swing is detected when a bar's high is higher than the surrounding pivotLen bars on both sides (for resistance), or the low is lower (for support). Because the right-side requires N bars of confirmation, zones appear with a deterministic pivotLen -bar lag and do not repaint once drawn
At the moment a pivot confirms, the script measures the 200-bar ATR as it existed pivotLen bars ago — that is the volatility context at the actual swing bar, not the current bar. The zone is then drawn as a box extending ±(ATR/2) around the pivot price
Each zone is stored in an SRZone user-defined type that bundles its box, midline, label, pivot level, and a boolean broken flag. Two arrays — one for resistance, one for support — hold the active inventory
On every bar, unbroken zones have their right edge extended forward. When the close exceeds the top of a resistance zone (or falls below the bottom of a support zone), the zone stops extending, is marked broken, and a labeled marker is drawn at the break bar
How the Components Work Together
Three design decisions interact to produce the final behavior.
The pivot detection answers where market structure previously turned — these are locations where orders likely clustered and will likely cluster again on retest. The ATR scaling answers how wide the reaction range around that pivot should be, because a pivot formed during a low-volatility session does not represent the same defensive range as one formed during a volatile expansion. Combining the two produces zones that are structurally anchored but volatility-proportional.
The close-based break filter then handles the noise problem. The most common false break is a wick that tags the level, prints a panic candle, and reverses immediately. By requiring a full close beyond the zone, the indicator rewards conviction moves and ignores exploratory probes — the break is registered only when price has committed to the new regime.
Trading Ideas and Insights
Repeated tests of a fresh resistance zone without a closing break frequently precede a sustained reversal. The more times a zone is defended, the more meaningful the eventual breakout becomes
When a resistance zone breaks and then holds as support on retest, that flip is a classic structural shift — an opportunity to align with the new direction using the flipped zone as a clear invalidation level
Support zones broken during strong trending conditions rarely hold on retest. Support broken during ranging conditions often reforms because the market was simply oscillating — context from the broader trend matters
A cluster of multiple pivots at similar prices (three or four zones stacking) marks a confluence area that carries more weight than an isolated swing
Past behavior at these levels does not guarantee future reactions. Treat zones as bias filters rather than standalone signal generators.
Unique Aspects
Most S/R indicators use fixed-distance zones, round numbers, or percentage bands. This one scales zone thickness to a rolling ATR measured at the exact bar of the pivot — so a 2020 level and a 2024 level on the same chart can have very different zone widths depending on the volatility regime that produced them
Zones freeze on break rather than being deleted, preserving a visual history of which structural levels have been tested and lost. This acts as a passive context map for traders reading price action
State is managed through a UDT array rather than a flat set of lines, which makes the extend-until-broken behavior clean and predictable — each zone owns its own break detection logic
How to Use
Add the indicator to any chart and timeframe you actively trade. 1H and 4H are good starting points for swing traders; lower timeframes work but will produce more zones and benefit from a higher pivot lookback value
Identify the nearest active support zone (green) and resistance zone (red) — these are the first levels price is likely to react to
Watch for one of two outcomes: a controlled approach followed by rejection (fade setup), or a decisive close through the zone (breakout setup). The indicator labels the breakout or breakdown automatically
When a level breaks, expect a retest. Retests often offer better reward-to-risk entries than chasing the initial breakout bar itself
Customization
Pivot Lookback Length (default: 15) — Bars required on each side of a swing for confirmation. Lower values (5-10) produce smaller, more frequent zones suitable for scalping. Higher values (20-30) isolate only major structural swings and reduce chart clutter
Zone Width (ATR Multiplier) (default: 1.0) — Scales the ATR-derived zone thickness. Raise to 1.5-2.0 on volatile instruments where zones should absorb normal noise; lower to 0.5 for tighter precision-entry levels
Support / Resistance Color — Visual differentiation between bullish and bearish zones, their midlines, and labels
Zone Transparency (default: 85) — Controls the fill opacity of zone boxes. Values around 80-90 keep price action readable inside the zone
Limitations to Be Aware Of
The pivot confirmation delay equals the lookback length. A 15-bar lookback means the zone is drawn 15 bars after the actual swing high or low. This is fine for levels (they do not repaint) but unsuitable for entries at the exact swing bar
Zones do not automatically merge. When multiple pivots form within an ATR of each other, their zones will overlap on the chart. Increasing the pivot lookback reduces this visual clutter
Break detection uses close , not wicks. A bar can spike well beyond the zone and return inside without triggering a break — by design, but worth remembering on volatile instruments with large intrabar swings
Conclusion
Rather than plotting dozens of static lines, the Aura Pivot S/R Matrix treats each structural pivot as a live object with a volatility-scaled range and a clear lifecycle — active, then broken. The ATR scaling grounds each zone in the volatility context of its own formation, and the close-based break detection emphasizes conviction moves over noise. Most useful as a structural framework for swing and position traders who want to see where the market has been defended, where those defenses have been lost, and how the battleground has evolved across different volatility regimes.
Indicator

Reaction Efficiency Meter [AGPro Series]Reaction Efficiency Meter
A pure observation lens that scores every pivot-based support and resistance reaction from 0 to 100 and classifies it as WEAK, LIMITED, FAIR, STRONG or EFFICIENT. Designed to answer one specific question on any chart: how well did price actually react when it touched that level? Not a strategy, not a signal generator — a quality meter for S/R reactions.
🔹 Overview
Reaction Efficiency Meter watches pivot-based support and resistance levels and, the moment price touches any of them, opens a fixed reaction window to observe what happens next. At the end of that window the reaction is scored from 0 to 100 using four weighted components — strength, speed, cleanliness, follow-through — and then classified into a five-tier hierarchy. The result is printed directly on the chart as a color-coded label (BULL or BEAR), while a side panel keeps a live summary of the last bullish reaction, last bearish reaction and the currently active event window. The indicator is built as a post-event quality lens for traders who already work with horizontal levels, pivot zones, or structural S/R and want an objective readout of reaction quality instead of a subjective eyeball assessment.
🔸 Unique Edge
Most support and resistance indicators stop at drawing lines or zones. Reaction Efficiency Meter goes one step further and evaluates the reaction itself on a fixed, reproducible scale. Four distinct quality dimensions are blended into a single 0-100 score, and a separate adverse-excursion penalty reduces the score when price violated the level before reacting. The result is a transparent number tied to a five-tier verbal classification (WEAK / LIMITED / FAIR / STRONG / EFFICIENT), which makes reactions directly comparable across symbols and timeframes. There are no repainting signals, no lagging smoothers and no hidden strategy logic — the scoring is purely descriptive and fires only after the reaction window closes on a confirmed bar.
🔹 Methodology
The engine has four clear stages:
1. Level detection. Classic pivot highs and lows are tracked as dynamic resistance and support. Only the most recent N levels per side stay active — older ones are retired, so the chart never clutters.
2. Touch detection. A touch is registered when the bar's range enters a tolerance band around any active level (expressed in ATR units so the logic auto-scales across volatility regimes). A cooldown of N bars between tests on the same level prevents noise from restarting an event too quickly.
3. Event tracking. Once a touch fires, a reaction window of N bars is opened. During that window the script tracks (a) the best favorable excursion in ATR units, (b) the worst adverse excursion in the wrong direction, (c) which bar produced the peak favorable move, (d) the net retained move at window close.
4. Scoring and classification. At window close the four components are combined with a penalty:
• Strength (0-35): best favorable excursion relative to 1.5 ATR reference.
• Speed (0-20): how early the peak favorable bar occurred inside the window.
• Cleanliness (0-20): reduced linearly by adverse excursion.
• Follow-through (0-15): how much of the peak move was retained at window close.
• Adverse penalty (up to -15): applied when price broke through the level.
Final score is clamped 0-100 and mapped to: WEAK (<25), LIMITED (25-44), FAIR (45-64), STRONG (65-79), EFFICIENT (80+).
🔸 Signals & Alerts
The indicator does not emit buy or sell alerts. Its outputs are purely descriptive:
• A color-coded reaction label (BULL or BEAR with score and tier) plotted after each completed window.
• Active zone rectangle and reaction corridor drawn around the touched level while the window is open.
• Touch markers on the bar where a new event begins.
• Live status tag showing BULL WINDOW x/N or BEAR WINDOW x/N during an active event.
• A stateful side panel with Status, Last Bull, Last Bear, Window progress and Mode rows.
All visuals render on confirmed bars only, so the score and tier of a completed reaction do not change afterwards.
🔹 Key Inputs
• Pivot Length — bar distance used to qualify pivot highs and lows.
• Max Active Levels / Side — how many recent resistance and support levels stay active.
• ATR Length — volatility reference for tolerance, corridor depth and scoring.
• Touch Tolerance (ATR) — how close to the level a bar must come to count as a touch.
• Reaction Window Bars — fixed observation length per event.
• Minimum Bars Between Tests — cooldown on the same level.
• Reaction Corridor Depth (ATR) — vertical span of the reaction corridor drawn during the window.
• Display group — toggles for levels, tags, markers, labels, active zone, corridor, panel.
• Theme & Layout — panel theme (Auto / Dark / Light), position, font size, line width and opacity controls.
🔸 How to Use
The indicator is intended as a companion lens, not a standalone system. Typical workflows include:
• Confluence study. Compare reaction scores at different levels on the same chart to see which zones historically produced stronger reactions.
• Bias assessment. Watching whether BULL and BEAR labels on a given timeframe skew toward higher or lower tiers can inform directional bias for discretionary decisions made elsewhere.
• Framework validation. Add it on top of an existing S/R, order block or pivot framework to quantify whether the levels those tools produce actually generate efficient reactions.
• Multi-timeframe scanning. Running the indicator on multiple timeframes shows where strong reactions cluster — often useful for context, not entry timing.
The tool is descriptive and retrospective. It is not designed to replace risk management, structural analysis or the user's own trading plan.
🔹 Limitations & Transparency
• The reaction window is fixed per event. Very fast V-reversals may still register as WEAK if most of the favorable move happens after the window closes; conversely, slow grind reactions may score lower on the Speed component even when the net outcome is good.
• Pivot-based levels are, by definition, confirmed with a lag equal to Pivot Length bars.
• Scores are descriptive — a STRONG tag on a past reaction does not imply that the next test of the same level will also react strongly.
• All scoring uses confirmed-bar logic, so the indicator is non-repainting by design.
🔸 Risk Disclosure
This indicator is provided for educational and analytical purposes only. It is not financial advice, not a trade signal generator, and not a recommendation to buy or sell any instrument. Trading involves substantial risk of loss. Past reactions do not guarantee future reactions. Users are solely responsible for their own trading decisions and risk management. Indicator

Fixed Range Control Box [AGPro Series]Fixed Range Control Box
🔹 Overview
Fixed Range Control Box isolates a single high-conviction price range on your chart and classifies who is in control inside it. The tool draws one clean hero box around the most recent structural range, places a volume-weighted Control Line inside it, and tracks state transitions in real time: Inside, Upper, Lower, or Failed. When price structurally breaks the box, the range freezes, locking the reference so you can study the aftermath without visual drift.
Four range-definition modes are available — Pivot, Lookback, Compression, and Manual-Date — so the tool adapts to discretionary range traders, systematic rotation traders, and anyone who wants a fixed reference zone for backtesting or journaling.
🔸 Unique Edge
Most range tools on PulseWire draw many boxes and leave the user to guess which one matters. Fixed Range Control Box is built around a different philosophy: one range, one story, one decision. The hero box is the visual focus; historical ranges fade into the background; the Control Line tells you which side of the range is winning the statistical argument.
Three design choices separate this from standard range-box scripts:
- Volume-weighted Control Line. Rather than dropping a midpoint line, the Control Line is computed from the volume-weighted typical price across the life of the range, with an edge-fallback to midpoint if the line drifts too close to either boundary. This produces a structurally meaningful reference instead of a geometric one.
- Retrospective fill on range rebuild. When a new range is committed, the script walks back through the range window and retroactively computes touch count, hold quality, and the Control Line. You see a fully-formed box with accurate statistics the moment it appears, not an empty box that slowly populates.
- Freeze-on-failure. When price closes beyond the range and the state transitions to Failed, the box locks at the break bar. No more drifting endpoints on broken structures — the reference stays where the story ended.
🔷 Methodology
The script cycles through four stages on every bar:
1. Range detection. Depending on the selected mode, the script looks for a qualifying range: confirmed swing pivots (Pivot), rolling highest/lowest (Lookback), short-ATR over long-ATR compression (Compression), or a user-defined date window (Manual). Gating rules — minimum lifespan, minimum width percentage, and a failed-state cooldown — prevent rapid re-triggers on noisy conditions.
2. Commit and retrospective fill. Once a range qualifies, the script snapshots the old range into history, installs the new one, and walks back through the window to compute the Control Line, touch count, and hold quality in a single pass. No warm-up period.
3. State machine. Each confirmed bar feeds the state machine. Strict logic requires bar closes on one side of the Control Line for the configured number of bars before switching to Upper or Lower; a close beyond either range boundary transitions to Failed.
4. Rendering. On the last bar, the hero box, Control Line, origin marker, and state badge are rebuilt from scratch. Historical ranges persist as muted boxes up to a configurable cap.
🔶 Signals & Alerts
Three alert conditions cover the full range lifecycle:
- New Control Box. Fires once per bar close when a new range is committed.
- Line Reclaimed (Bull or Bear). Fires when state transitions into Upper or Lower control, confirming directional bias inside the range.
- Control Failed. Fires once when price closes beyond the range and the box is frozen.
All alerts use alert() calls with once-per-bar-close frequency.
🔹 Key Inputs
- Range Mode — Auto-Pivot, Auto-Lookback, Auto-Compression, or Manual-Date.
- Pivot Length / Lookback Bars / Compression Window — window controls for each detection mode.
- Min Range Lifespan / Min Range Width % — structural filters to suppress micro-ranges.
- Failed Cooldown — bars to wait after a broken range before searching for a new one.
- Strict Control Logic + Reclaim Confirmation — governs how the Control Line state machine transitions.
- Visual controls — fade old boxes, max boxes kept, show state badge, show range origin, future projection bars, panel and label font sizes.
🔸 How to Use
1. Start on your primary timeframe and select the Range Mode that matches your style: Pivot for discretionary swing structures, Lookback for mechanical windows, Compression for auto-locking onto consolidations, Manual-Date for backtesting a specific episode.
2. Tune Min Range Width % and Min Range Lifespan so only structurally meaningful ranges appear.
3. Read the panel top-down: Mode confirms what you are tracking, Control tells you which side of the Control Line is winning, Range Age and Touches describe maturity and confluence, Hold Quality summarizes how cleanly price has respected the range, and State shows the live classification.
4. Use alerts to monitor the range lifecycle without staring at the chart.
🔻 Limitations & Transparency
- This is an analytical tool, not a strategy. It does not generate buy or sell recommendations and does not compute entries, stops, or targets.
- Past range behavior does not forecast future range behavior. Structural breaks can occur at any time.
- In very thin or illiquid markets, the volume-weighted Control Line can drift toward a boundary; the edge-fallback defaults to midpoint to protect against degenerate cases.
- Auto-Compression mode requires sufficient ATR history; expect a warm-up period on very recent symbols.
- The script is overlay-only and does not access other timeframes.
🔶 Risk Disclosure
Nothing in this script constitutes financial advice. Trading involves substantial risk of loss and is not suitable for every investor. Always do your own research and manage risk appropriately. Indicator

HH/HL/LH/LL Structure Tracker [AGPro Series]HH/HL/LH/LL Structure Tracker
🔹 Overview
HH/HL/LH/LL Structure Tracker automatically classifies every confirmed swing on your chart using pure Dow Theory — the original price-action framework that precedes and underlies every modern market-structure methodology. Each pivot high is labeled as a Higher High (HH) or Lower High (LH), and each pivot low as a Higher Low (HL) or Lower Low (LL). The sequence of the last four swings derives a live trend state: Bullish, Bearish, or Ranging.
No oscillators. No lagging averages. Just the raw geometry of price.
💎 What Makes This Different
While most "market structure" indicators focus on Break-of-Structure or Change-of-Character logic layered with Smart Money terminology, this script returns to the foundation: the four-swing classification that Charles Dow documented over a century ago. The result is an uncluttered, universally readable overlay that communicates structural context at a glance — regardless of which higher-level methodology you apply next (SMC, Wyckoff, Elliott, or classical technical analysis).
Key differentiators versus generic HH/HL scripts on the public library:
• Live structure range zone that dynamically recolors with the trend state (bullish teal, bearish pink, ranging amber).
• Bull Streak and Bear Streak counters — a quantifiable measure of trend persistence (e.g. "3 consecutive HH-HL swings").
• Semantic break classification: the panel distinguishes a continuation break (HH or LL broken in trend direction) from a reversal break (LH or HL broken against the prior structure).
• Progressive label offset algorithm: when several same-type swings cluster without an intervening opposite swing, each subsequent label is offset further from price, eliminating the overlap that plagues most swing scripts on fast-moving charts.
• AGPro design language: premium info panel, adjustable font size and theme, and a disciplined color palette.
🧠 Methodology
1. Pivot detection. A confirmed swing high is a bar whose high exceeds the preceding and following N bars (N = Pivot Length, default 5). Confirmed swing lows mirror the rule. Confirmation occurs N bars after the pivot bar, never repaints.
2. Swing classification. Each new confirmed high is compared to the previous confirmed high. If greater, it is HH; if lesser, LH. Lows are compared to the previous low: greater means HL, lesser means LL.
3. Trend derivation. If the most recent high is HH and the most recent low is HL, the trend state is Bullish. If LH and LL, Bearish. Any mixed sequence (HH + LL, LH + HL) returns Ranging.
4. Structure range zone. A rectangle is drawn between the most recent swing high and most recent swing low. The zone is always current: as new swings confirm, the zone updates in place. Zone color tracks the trend state.
5. Structure break. A close above the most recent swing high (or below the most recent swing low) fires a break event. The type of swing broken is reported — breaking an LH or HL typically precedes a trend reversal; breaking an HH or LL typically signals continuation.
📊 Signals & Alerts
Three optional alert types are available, each using "once per bar close" frequency to prevent intrabar noise:
• New Higher High confirmed — fires when a fresh HH is classified.
• New Lower Low confirmed — fires when a fresh LL is classified.
• Structure break — fires on a close outside the current structure range, labeled as either (reversal signal) or (continuation).
The live info panel reports: Trend state, Bull Streak, Bear Streak, Last High (with type and price), and Last Break (with type and price).
⚙️ Key Inputs
• Pivot Length — sensitivity of swing detection (2 to 50). Lower values capture minor structure; higher values isolate major swings only. Typical: 3–8 intraday, 5–15 swing trading.
• Max Visible Labels — caps the number of historical labels kept on the chart to preserve a premium uncluttered look.
• Label & Panel Font Size — five sizes from Tiny to Huge, default Normal.
• Label Distance from Price (ATR) — base vertical offset of labels from pivot candles.
• Structure Range Zone — toggle, transparency, and border.
• Trend Background Tint — subtle bullish or bearish chart shading.
• Info Panel — toggle, location (six positions), and theme (Dark or Light).
• Alerts — independent toggles for new HH, new LL, and structure break.
🎯 How to Use
Context tool, not a standalone signal generator. Use the trend state to filter entries from your primary methodology: take long setups only while Trend is Bullish and Bull Streak is building, or vice versa. The structure range zone highlights the active battleground between buyers and sellers — trades taken inside the zone are counter-trend by definition, trades taken on a decisive break of the zone align with the emerging new trend.
Reversal breaks (LH or HL broken) are high-information events — they are often the first objective signal that a prevailing trend is losing conviction, ahead of any moving-average cross or momentum divergence. Continuation breaks (HH or LL broken) are confirmation events that validate staying with the trend.
Works on all markets and all timeframes. Particularly effective on liquid instruments with clear structural rhythm: major crypto pairs, FX majors, index futures, and large-cap equities.
⚠️ Limitations & Transparency
• Pivot confirmation requires N bars after the swing; the most recent unconfirmed swing is never labeled.
• In low-volatility sideways regimes, pivot clustering is inevitable — the Pivot Length input should be raised to filter noise on ranging charts.
• The trend state is derived from only the last two swings; it does not account for higher-timeframe context. Pair with a higher-timeframe version of the same script for multi-timeframe confluence.
• Does not provide entry, stop, or target levels. It is a structural framework, not a complete trading system.
📌 Risk Disclosure
This indicator is for educational and analytical purposes only. It does not constitute financial advice, a trading recommendation, or a guarantee of future performance. All trading involves risk of loss. Past structural patterns do not guarantee future outcomes. Always conduct your own due diligence and use appropriate risk management. Indicator

Stop Loss Optimizer Engine [AGPro Series]Stop Loss Optimizer Engine
🔹 OVERVIEW
Stop Loss Optimizer Engine compares four independent stop-loss methodologies side by side on a single chart, so traders can see at a glance where each approach would place protection and which one has historically held up best on the current symbol and timeframe. Every method is calculated for both LONG and SHORT, giving eight reference levels plus a compact panel with distance-to-price and a historical hold-rate statistic per method. A Risk Zone highlights the area between current price and the method with the strongest historical hold-rate, providing a clean S/R-style visual anchor for position sizing and R-multiple planning.
🔹 UNIQUE EDGE
Most stop-loss indicators on the platform commit to a single philosophy — pure ATR, pure Chandelier, or pure structure. Traders who want to compare approaches end up loading multiple scripts and eyeballing the differences. Stop Loss Optimizer Engine is built around a different premise: volatility, structure, trailing and recent-extreme stops each have environments in which they work well, and the trader should decide based on evidence rather than habit. The indicator renders all four on one chart, adds a per-method hold-rate measured on the active instrument, and flags the highest-hold-rate method with a star marker so the comparison is always a single glance away. The Risk Zone is drawn using the current-best method, which means the visual anchor adapts to whichever approach is statistically holding up best on that symbol and timeframe right now.
🔹 METHODOLOGY
The four engines are independent and each produces a LONG and a SHORT level:
ATR-SL — close minus or plus ATR × multiplier. Volatility-adaptive, widens in turbulent markets, tightens in calm ones.
Pivot-SL — the most recent confirmed pivot low or pivot high. Respects market structure, places the stop beyond the last reversal point rather than at an arithmetic distance.
Chandelier-SL — highest high minus ATR × multiplier for LONG, lowest low plus ATR × multiplier for SHORT. The classic Le Beau / Elder trailing stop, designed to follow strong trends without premature exits.
Swing-SL — the lowest low or highest high over a short lookback. A simple, robust baseline that works well for shorter trades and scalping.
Hold Rate — for every historical bar in the lookback window, the indicator records the SL level that each method would have produced at that bar, then checks whether price breached that level within a fixed forward window. Hold Rate is the percentage of evaluated bars in which the SL was not breached. This is a pure historical observation, not a forward performance projection.
🔹 SIGNALS & ALERTS
Visual — dotted lines for LONG stops (plotted below price), dashed lines for SHORT stops (plotted above price). Each method uses a distinct color. Labels sit at the right edge of each line with the method name and exact price. A dedicated anti-overlap resolver repositions labels vertically whenever two or more methods produce near-identical levels, so the rightmost chart panel stays readable in tight clusters.
Risk Zone — a shaded rectangle between current close and the highest-hold-rate SL on the trend-dominant side, extending forward from the current bar. Color matches the selected best method.
Panel — four-column layout showing method, LONG price (and distance %), SHORT price (and distance %), and Hold Rate, with a star marker beside the method currently holding the highest rate. A trend footer reports Bullish or Bearish based on the EMA50 filter.
Alerts — four pre-configured conditions for price breaching the ATR and Chandelier SL levels on either side.
🔹 KEY INPUTS
Method toggles for each of the four engines. Length and multiplier inputs per method, with balanced defaults (ATR 1.5× / 14, Pivot length 5, Chandelier 2.5× / 22, Swing lookback 7). Hold-rate statistics lookback and forward window, defaulting to 1000 and 10 bars. Visual controls for long-side lines, short-side lines, labels, the Risk Zone and a trend-based dimming of the counter-trend side. Panel location (six positions), panel theme (Dark or Light), and adjustable font sizes for panel and labels, all defaulting to Normal.
🔹 HOW TO USE
Open the indicator on any symbol and any timeframe. Read the panel first — the starred method is the one with the best historical hold-rate on the current chart. Pick a method that matches the trade plan: ATR for volatility-aware scalps, Pivot for structural setups, Chandelier for trend-following swings, Swing for simple quick trades. Use the Hold Rate column as secondary evidence, not as a standalone forecast. Read the SL price and the distance percentage next to it to size position accordingly — a 2% stop and a 6% stop are not the same trade, even on the same entry. The Risk Zone is a convenience visual for the trend-dominant side and should be interpreted together with the other levels, not in isolation.
🔹 LIMITATIONS & TRANSPARENCY
Hold Rate is a backward-looking statistic computed on historical bars of the active chart. It describes what would have happened under a fixed forward-window assumption on past data and does not guarantee any future behavior. The forward-window length, lookback size and method parameters all influence the resulting numbers; changing inputs changes the statistic. The Pivot-SL method depends on the availability of confirmed pivots in the lookback window and will fall back to a conservative ATR-based placeholder when a pivot is not yet confirmed. Risk Zone selection is based on hold-rate ranking, which can switch between methods as markets evolve. This script is a decision-support tool for discretionary risk management, not a trade-entry signal generator. Always combine with independent analysis and sound position sizing. Past performance of any stop-loss method does not guarantee future results.
🔒 RISK DISCLOSURE
This script is provided for educational and informational purposes only. It is not financial, investment or trading advice. Trading involves substantial risk of loss; use at your own discretion and risk. Indicator

Reversal Probability & SignalsThis indicator is designed to forecast critical market turning points by predicting the formation of TOPs (Pivot Highs) and BOTTOMs (Pivot Lows).
To achieve this, the script utilizes a simplified K-Nearest Neighbors (KNN) machine learning algorithm built directly within Pine Script. By analyzing a wide spectrum of Commodity Channel Index (CCI) values, it calculates the real-time probability that the current price action will result in a structural Pivot reversal.
How It Works (The Engine)
The script functions as a real-time pattern recognition engine. It operates in three main steps:
Feature Extraction: It concurrently calculates 8 different lengths of the CCI (from very short to long-term periods like 10 to 200). This acts as the feature set of the current market momentum.
Data Collection (Training): Whenever the market makes a significant structural Top or Bottom (based on Pivot points), the script records the specific state of those 8 CCIs at that exact moment. It also collects random "non-target" samples to build a balanced historical database.
KNN Classification (Prediction): On every new bar, the algorithm calculates the mathematical Euclidean distance between the current 8 CCI values and the historically saved samples. It looks at the "K" nearest historical neighbors. If the majority of those closest historical neighbors were market bottoms, the indicator outputs a high "Bottom Probability."
Key Features
Dynamic K-Value Adjustment: To ensure stable and accurate calculations even shortly after applying the indicator (when the historical sample pool is still growing), the "K" value dynamically scales down based on the available data size and automatically adjusts to odd numbers to prevent tie-breaking ambiguity.
Two-Step Smart Signal Logic: To prevent premature entries during strong, ongoing trends, this script uses a dual-threshold confirmation system:
Standby: The probability must first surge above an Upper Threshold (Default: 80%), indicating extreme conditions.
Trigger: The actual signal is only plotted when the probability peaks and subsequently drops below a Lower Threshold (Default: 50%). This confirms that the extreme momentum has broken and the reversal is underway.
Target Selection: Easily switch the engine's focus between predicting a "BOTTOM" or a "TOP" via the settings panel.
Visual Enhancements & Alerts: Includes intuitive dynamic bar coloring (changing based on probability intensity), a clear histogram, distinct signal shapes on the chart, and fully integrated alert conditions for automation.
Settings & Configuration
Prediction Target: Toggle between BOTTOM (Pivot Lows) and TOP (Pivot Highs).
Feature Parameters (CCI): Customize the 8 periods used for momentum extraction. Default settings range from 10 to 200 to capture micro-fluctuations up to macro-trends.
KNN Model Settings: * K-Value: The baseline number of nearest neighbors to compare.
Max Samples: The memory limit for historical data points (higher = more stability, but heavier computation).
Signal Settings: Customize the Upper and Lower thresholds for the two-step signal generation.
How to Trade with It
Select your target: Decide if you are looking for long opportunities (BOTTOM) or short opportunities (TOP).
Watch the Buildup: Observe the histogram or candlestick colors. When the probability goes above 80%, the market is showing conditions highly similar to historical reversals. Do not enter yet.
Wait for the Trigger: Wait for the momentum to break. When the probability drops back below the 50% threshold, a triangle shape will appear on the chart. This is your signal that the reversal pattern is executing.
Disclaimer:
This script uses historical pattern matching and experimental mathematical models. It does not guarantee future results. Please use it in conjunction with broader market context, other technical indicators, and strict risk management. Indicator

Market Pivot LevelsTired of automated support and resistance indicators that clutter your chart with dozens of overlapping, noisy lines?
The Market Pivot Levels indicator is designed to map core market structure exactly like a professional technician would—cleanly, precisely, and without the noise. Instead of drawing a line at every single minor fluctuation, this script uses advanced filtering logic to identify true structural zones and spaces them out beautifully across your chart.
Key Features:
ATR Proximity Filter (No Clutter): Standard pivot scripts often stack lines on top of each other during consolidation. This script uses an Average True Range (ATR) proximity filter. If a new pivot forms too close to an existing major level, it ignores it, ensuring your chart only displays distinct, well-spaced tradeable zones.
Psychological Price Snapping: Human traders don't draw lines at random decimals like $196.19—they look for clean, psychological numbers. This script automatically takes the exact wick of a structural swing and snaps it to the nearest whole dollar (e.g., $196.00), mimicking a human hand.
Flush Right-Aligned Labels: Forget hovering over lines to see their value. Custom price tags are dynamically magnetized to the far right of your screen, sitting perfectly flush with your standard price axis for immediate readability.
Stealth UI: We believe in clean charts and clean interfaces. All underlying parameters (lookbacks, ATR multipliers, line thickness) are hardcoded and hidden from the settings menu to keep your PulseWire UI completely minimalist. It is strictly plug-and-play.
How it Works Under the Hood:
By default, the script looks for highly granular micro-swings (1-bar lookback), but relies on the 1.0 ATR distance multiplier to filter out the noise. The result is a highly responsive, custom price grid that adapts to the specific volatility of whatever ticker you are trading. It keeps a maximum of 20 active levels on the screen, automatically cleaning up old, irrelevant zones as new price action develops.
How to Use It:
Simply drop it onto any chart timeframe. Use the automatically generated yellow zones for breakout entries, strict stop-loss placements, or profit targets during extended trends. Indicator

Liquidity Thermal Map [JOAT]Liquidity Thermal Map
Introduction
The Liquidity Thermal Map is an overlay indicator that identifies and visualizes liquidity pockets — price zones where trapped participants are likely clustered — and ranks their significance using a heat-mapped color scale driven by volume and price range data. Rather than treating all swing highs and lows equally, it weights each zone by the liquidity activity present at that pivot bar, then applies power-law contrast stretching so that the most significant zones immediately stand out from background noise.
The goal is not to predict where price will go. The goal is to surface which untested zones carry the most liquidity weight, so a trader can make their own informed decisions about potential targets or areas of interest.
---
Core Concepts
1. Pivot Detection
Zones are seeded at confirmed swing pivots using Pine Script's built-in pivot functions:
pivH = ta.pivothigh(high, leftPiv, rightPiv)
pivL = ta.pivotlow(low, leftPiv, rightPiv)
A pivot high marks a bar where bears may have been trapped above — price reached that level, reversed, and left unfilled orders behind. A pivot low marks the mirror situation for trapped bulls. The left bars and right bars inputs control how many confirming bars are required on each side, balancing sensitivity against noise.
2. Liquidity Metric and Heat Normalization
Each pivot is scored using one of three selectable metrics:
Vol x Range (default): volume * (high - low) * 100 — rewards bars with both high volume and wide price movement
Volume only: raw volume at the pivot bar
Range only: the high-low spread at the pivot bar
Raw scores are normalized across all active pockets using a rolling min-max calculation:
norm = (metric - min) / (max - min)
heat = math.pow(norm, heatContrast)
The power-law contrast stretch (controlled by the Heat Contrast input) compresses lower-significance pockets toward zero and expands higher-significance ones toward one. A contrast value below 1.0 spreads pockets more evenly; above 1.0, only the highest-scoring pockets register strong color.
3. Zone Construction
Each pocket is drawn as a box:
Short liquidity pocket (at a pivot HIGH, bears trapped above): top = pivotHigh + ATR * bandWidth, bottom = pivotHigh
Long liquidity pocket (at a pivot LOW, bulls trapped below): top = pivotLow, bottom = pivotLow - ATR * bandWidth
ATR scaling ensures band width adapts to current volatility rather than using a fixed pip or point value. Short pockets color from yellow (low heat) through deeper yellows. Long pockets color from a faded cyan through solid cyan-blue. Both gradients are computed with color.from_gradient(heat, 0, 1, faded_base, solid_base) , making the heat ranking immediately readable at a glance.
4. Three-State Lifecycle
Every pocket passes through a defined state machine:
Active: The zone is untested. The box extends rightward each bar by the Extend Bars amount, keeping it visible on the current chart.
Hit (Frozen): Triggered when price sweeps through the midpoint of the zone (high >= midpoint AND low <= midpoint on the same bar). The box stops extending, color fades, and the label is removed — signaling that the pocket has been swept and liquidity likely absorbed.
Expired: When a pocket's age exceeds the Lookback setting without being hit, it is removed entirely and all associated arrays are cleaned up.
This lifecycle gives real-time feedback: solid, bright zones are intact and untested; faded zones have been swept; only the most recent, significant pockets within your lookback window are visible.
5. Scale Legend
A 24-cell gradient table is drawn on-chart running from the short liquidity color to the long liquidity color, providing a continuous reference for the heat scale being applied to all visible pockets.
---
Features
Pivot-anchored liquidity zones for both long and short trapped-participant scenarios
Three selectable liquidity metrics: Vol x Range, Volume only, Range only
Power-law contrast stretching for visual prioritization of high-significance zones
ATR-scaled zone width that adapts to current market volatility
Three-state lifecycle (Active → Hit → Expired) per pocket with visual state changes
Dual-color gradient system — cyan-blue for long pockets, yellow for short pockets
On-chart 24-cell heat scale legend
Configurable max pocket count to manage chart performance
Visual toggles for boxes, labels, and the legend table
---
Input Parameters
Pivot Left Bars (default 10): Bars required to the left of a pivot for confirmation. Higher values = fewer, more significant pivots.
Pivot Right Bars (default 5): Bars required to the right of a pivot for confirmation. Increasing this delays detection but improves pivot quality.
Lookback / Max Age (default 200): Maximum bar age before a pocket expires and is removed.
Max Pockets (default 50): Upper limit on simultaneous active pockets. Reducing this improves performance on lower-end charts.
ATR Length (default 14): Period for the ATR calculation used in band width scaling.
ATR Band Width (default 0.5): Multiplier applied to ATR to set zone height. Higher values create wider zones.
Extend Bars (default 50): How many bars ahead each active pocket box extends on each update.
Heat Contrast (default 0.5): Power-law exponent for contrast stretching. Values below 1.0 spread pockets more evenly; above 1.0 increases contrast between high and low scoring zones.
Metric Mode: Selects the liquidity scoring metric — Vol x Range, Volume, or Range.
Show Boxes / Show Labels / Show Legend: Individual visibility toggles for each visual component.
---
How to Use
Identifying high-priority zones: Bright, fully saturated boxes represent the highest-scoring untested liquidity pockets within your lookback window. These are the zones where the most volume-weighted trapped participants may be present.
Tracking swept zones: When a box fades, the pocket has been hit — price moved through its midpoint. Faded zones can serve as reference for areas that have already seen liquidity absorption.
Adjusting sensitivity: Increasing the left/right pivot bars reduces the total number of pivots detected, focusing only on more structurally significant swing points. Decreasing them creates a denser map suitable for shorter timeframes.
Interpreting the legend: The 24-cell scale legend in the corner maps the full gradient range, from the lowest-heat short pocket color to the highest-heat long pocket color.
Timeframe considerations: On higher timeframes (4H, Daily), fewer pivots form and each carries more weight. On lower timeframes, tightening the ATR band width and increasing heat contrast helps reduce visual clutter.
---
Limitations
Pivot detection is inherently lagging — a pivot is only confirmed after the right-side bars have closed, meaning the zone is plotted some bars after the pivot actually formed.
The liquidity metric scores a pocket by activity at the pivot bar itself , not the full swing sequence leading to it. A pivot formed on a single high-volume bar will score higher than one formed over a gradual, multi-bar move.
Volume data quality varies by broker and data feed. On instruments with unreliable or synthetic volume (some forex pairs, CFDs), the Vol x Range metric may not reflect true market participation.
The indicator does not account for partial fills or iceberg orders. A zone being "hit" means price swept through the midpoint — it does not confirm full liquidity absorption.
No indicator, including this one, predicts future price movement. A high-heat untested zone is an area of potential interest, not a guaranteed reversal or reaction point.
Performance may degrade on very active charts with high Max Pocket settings. Reduce Max Pockets if chart rendering slows.
The heat scale is relative to the current set of visible pockets. Adding more historical data (longer lookback) changes the normalization range and will recolor all currently visible pockets.
---
Originality Statement
Most liquidity mapping tools mark swing highs and lows with equal visual weight — every pivot gets the same line, box, or label. This indicator departs from that approach in three ways:
First , each pocket is scored by the product of volume and price range at its pivot bar (or volume/range alone as alternatives), producing a liquidity significance score rather than a binary present/absent mark.
Second , power-law contrast stretching is applied to the normalized scores, which means the visual encoding (color saturation) is non-linear. Minor pockets compress toward the faded end of the gradient; truly significant pockets expand toward the saturated end. This is a deliberate perceptual design choice — not simply coloring zones by value, but stretching the gradient to maximize discriminability at the high end.
Third , the three-state lifecycle (Active → Hit → Expired) treats each pocket as a dynamic object that responds to price action in real time. The visual state change on hit provides immediate feedback without requiring the trader to manually track which levels have been tested. The combination of significance scoring, contrast-stretched heat mapping, and lifecycle state management in a single overlay tool is the core contribution of this indicator.
---
Disclaimer
This indicator is provided for informational and educational purposes only. It does not constitute financial advice, investment advice, or a recommendation to buy or sell any asset. Past behavior of price around liquidity zones does not guarantee future behavior. All trading involves risk. You are solely responsible for your own trading decisions.
-Made with passion by officialjackofalltrades
Indicator

Indicator

Statistical Zone Engine [JOAT]Statistical Zone Engine
Introduction
Statistical Zone Engine is an open-source overlay indicator that builds pivot-cluster support and resistance zones with walk-forward statistical scoring. Each zone is backed by a full expected value computation: the indicator counts historical touches and bounces from the zone's price range over a configurable lookback, computes a win rate, and derives an EV score in units of R. Zones are tiered into four strength categories — Weak, Moderate, Strong, and Institutional — based on their live touch count, with border thickness and fill opacity scaling proportionally to the EV and tier. Labels display R:R, win rate, EV, and touch count, all updated live each bar.
The core problem this indicator solves is that conventional support and resistance drawing tools are entirely qualitative — the trader decides what is significant by eye. The SZE replaces that subjective judgment with a quantitative framework: zone strength is computed from actual price behavior over the lookback window, not from the visual prominence of the swing. A zone that has been tested eight times with seven bounces carries an objectively different statistical weight from one that was tested twice with one bounce, and the SZE communicates that difference through its tier system, border rendering, and live EV label. Cluster merging prevents adjacent pivots at nearly the same price from spawning overlapping zones that would misrepresent true strength.
Core Concepts
1. Pivot Cluster Zones
The indicator uses ta.pivothigh and ta.pivotlow with a configurable swing length. When a new pivot high is confirmed and no existing resistance zone is within ATR * clusterTol of the pivot price, a new zone is created. The cluster merge check prevents nearby pivots from generating duplicate zones at the same structural level — if a zone already exists within the tolerance radius, no new zone is spawned. This means zones represent genuinely distinct price levels, not just the most recent pivot above an existing zone.
2. Walk-Forward Expected Value Computation
For each new zone, the indicator scans the prior lookback bars and counts every bar where the high-low range overlapped with the zone. For each touch, it checks whether the close exited the far side of the zone — if so, it counts as a bounce. Win rate = bounces / touches. EV = winRate * tpRR - (1 - winRate) * slRR. A positive EV means the zone has historically resolved in the bounce direction more often than not, weighted by the configured R:R ratio.
3. Four-Tier Strength System
Zone tier is determined by live touch count:
Weak: 1-2 touches — thin border (width 1), low opacity fill
Moderate: 3 touches — medium border (width 1), moderate opacity fill
Strong: 4-5 touches — thicker border (width 2), more opaque fill
Institutional: 6+ touches — widest border (width 3), most opaque fill
Both the border width and the border transparency scale with tier, producing a visual system where the most historically significant zones dominate the chart. The fill opacity also scales with EV — zones with positive EV are more opaque, zones with negative EV are more transparent.
4. Live Label Updates
Each zone carries a label at its right edge displaying: type (RES/SUP), tier name, touch count, win rate percentage, and EV in R units. The label is recalculated and updated every bar when price is inside the zone, ensuring the statistics reflect current behavior. The label text color also scales with tier — more significant zones use brighter text.
5. Sweep Detection
When price closes fully through a zone boundary — above the top for resistance, below the bottom for support — the zone is marked as mitigated. If volume exceeds 1.4x the SMA(20) at the mitigation bar, a BREAK label fires above or below the zone. The total sweep count accumulates in the dashboard. After a break, zone fill fades to near-transparent, clearly communicating that the level has been closed through.
Features
Pivot-Cluster Zone Detection: Swing-pivot based zone creation with ATR-cluster merge deduplication — nearby pivots do not spawn overlapping zones
Walk-Forward EV Computation: Historical touch/bounce counting over configurable lookback produces win rate and R-unit EV scores for each zone
Four-Tier Strength System: Weak / Moderate / Strong / Institutional tiers based on touch count — border width and opacity scale with tier
EV-Scaled Fill Opacity: Positive EV zones are more opaque, negative EV zones are more transparent — fill intensity communicates statistical quality
Live Label Updates: Type, tier, touch count, win rate %, and EV in R units update every bar when price is inside the zone
Sweep Detection with Volume Filter: BREAK label fires on zone close-through when volume exceeds 1.4x SMA(20)
Post-Break Zone Fade: Broken zones fade visually, clearly delineating active versus mitigated levels
Proximity Markers: Diamond plotchar fires when price first enters a zone neighborhood
Min Touches Filter: Only zones with at least the configured minimum historical touches are displayed, eliminating freshly-formed single-touch zones
Zone Trim Management: Oldest zones are removed when arrays exceed the maximum zone count, keeping memory bounded
9-Row Dashboard: Active resistance and support zone counts, near-zone states, total sweep count, TP and SL R:R ratios, ATR
4 Alertconditions: Zone entry for resistance and support, new zone creation for both sides
Input Parameters
Zone Detection:
Swing Length: Pivot confirmation lookback period — higher values detect fewer, more significant pivots (default 10)
Cluster ATR Tolerance: Pivots within ATR * this of an existing zone are merged rather than spawning a new zone (default 0.4)
Zone ATR Width: Half the zone height as an ATR multiple — controls vertical thickness (default 0.35)
Max Active Zones: Maximum concurrent zones per direction before oldest are trimmed (default 12)
Min Touches To Show: Minimum historical touches required to display a zone (default 2)
Statistics:
EV Lookback (bars): Historical bar window for touch/bounce counting (default 200)
TP R:R Ratio: Take-profit distance in R units used for EV calculation (default 2.0)
SL R:R Ratio: Stop-loss distance in R units used for EV calculation (default 1.0)
Visuals:
Toggles for zone labels, sweep labels, and dashboard
Resistance Color (default orange #f97316), Support Color (default sky blue #38bdf8)
How to Use This Indicator
Primary Setup — Statistical Zone Entry:
Look for Institutional or Strong zones with positive EV — these are the levels with the longest bounce history weighted by your R:R parameters. When price enters a zone, the live label shows the current win rate. Enter at the zone edge with a stop beyond the far edge and a target at your TP R:R ratio from entry.
EV as a Selection Filter:
Multiple zones may be on the chart simultaneously. Prioritize zones with positive EV labels (e.g., EV: 1.25R) over zones with negative EV. A zone with 4 touches and 75% win rate at 2R:1R produces an EV of +1.25R per trade — objectively worth trading. A zone with 3 touches and 33% win rate at the same R:R produces EV of -0.33R — not worth trading regardless of how prominent it looks.
Using the Sweep Count:
The total sweep count on the dashboard accumulates every time a zone break is detected with high-volume momentum. Rising sweep counts in one direction indicate the market is consistently breaking through levels on that side — a sign of trending pressure rather than range behavior. Adjust bias accordingly.
Cluster Merge and Fresh Zones:
When a new pivot forms near an existing zone and is merged rather than spawning a new zone, the existing zone's historical statistics remain unchanged. A fresh zone with no historical data will show EV close to 0 — treat these as unproven until more touches accumulate.
Indicator Limitations
EV computation scans up to the full lookback on every qualifying pivot — on very long lookback settings and active pivot instruments, this can increase calculation time
The walk-forward EV uses the same zone size (ATR * width at creation time) for historical counting. If ATR changes significantly between creation time and the historical scan, the touch count may include bars where the equivalent zone boundaries would have been different
Cluster merging uses the current ATR at detection time. In periods of sharply rising or falling ATR, two zones that appear to merge at one ATR level may have been distinct at a different level, potentially underrepresenting zone density
The touch count displayed on the label is the live count updated each bar. The historical bounce count used for EV is computed at creation time and is not re-scanned dynamically — the label win rate reflects creation-time statistics
The minimum touches filter removes zones with fewer historical touches than the threshold. On fresh instruments or small lookbacks, most zones may be filtered out, especially on less-traded timeframes
Originality Statement
This indicator is original in its walk-forward EV scoring framework, four-tier visual strength system driven by live touch counts, and the cluster merging deduplication approach. The publication is justified because:
Walk-forward EV computation in R units provides a quantitative quality signal not found in standard support/resistance tools — each zone is backed by a historically derived expected value, enabling objective zone selection
The four-tier visual system (border width and opacity scaling with tier and EV) embeds the statistical quality directly into the zone appearance, eliminating the need to read labels to gauge significance
ATR-cluster merge deduplication prevents pivot-dense markets from generating overlapping zones at the same structural level, producing a cleaner, more meaningful map than raw pivot-based zone tools
Live label updates during zone interaction show the evolving win rate and EV as each new touch is counted, providing real-time statistical feedback not present in static zone indicators
The post-break fade combined with the total sweep count dashboard provides a structural memory of how many levels have been invalidated, enabling a directional bias gauge derived from zone lifecycle data
Disclaimer
This indicator is provided for educational and informational purposes only and does not constitute financial advice or a recommendation to buy or sell any financial instrument. Past performance of any pattern or signal does not guarantee future results. All trading involves substantial risk. Always use proper risk management and conduct your own independent analysis.
— Made with passion by officialjackofalltrades
Indicator

Trend Pulse [BigBeluga]🔵 OVERVIEW
Trend Pulse is a structure-driven trend detection indicator that identifies bullish and bearish regime shifts using confirmed pivot breaks and an adaptive volatility-aware trend band.
Instead of relying on momentum oscillators or fixed moving averages, Trend Pulse focuses on market structure, price expansion, and trend aging to determine when a trend starts, matures, and potentially exhausts.
The indicator is designed to visually communicate trend state directly on price using adaptive bands and progressive color transitions.
🔵 CONCEPT
Structure First — Trend direction is defined by confirmed pivot lows and their breaks, not by indicators crossing indicators.
Adaptive Trend Band — A volatility-adjusted SMA band expands over time during bearish phases, making late trend reversals harder to trigger.
Break-Based Trend Shifts — Bullish trends are confirmed only when price breaks above the adaptive band; bearish trends are confirmed by breaking below structural pivots.
Trend Aging — Trend strength is visualized by time-based color gradients that reflect how long a trend has been active, not momentum.
🔵 KEY FEATURES
Pivot-Based Bearish Detection
A bearish trend is triggered only after a confirmed pivot low is broken. This avoids reacting to temporary pullbacks or intrabar noise.
Real-time pivot low level tracking
During a bullish trend, the indicator displays the most recent pivot low level and extends it to the latest bar. This helps identify a potential level where the bullish trend may reverse into a downtrend.
Adaptive Volatility Band
The trend band is built from:
A dynamically expanding SMA length
ATR-based offset for volatility normalization
As the bearish trend matures, the band widens, requiring stronger price expansion to flip the trend back bullish.
Bullish Trend Confirmation via Band Break
A bullish trend is confirmed only when price breaks above the adaptive band, signaling genuine upside expansion rather than a weak bounce.
Automatic Band Reset
On bullish trend shifts, the adaptive band resets to a shorter length, allowing faster reaction to early trend stages.
Time-Based Trend Coloring
Trend color transitions from:
Fresh → Mature
Bullish → Bearish
based purely on how long the trend has persisted since the last flip.
Clear Structural Markers
The indicator plots:
- Confirmed pivot lows
- Bearish breakdown points
- Bullish breakout points
directly on the chart for structural clarity.
Full Candle Coloring
Candles inherit the current trend color, allowing instant visual recognition of market regime without additional indicators.
🔵 HOW TO USE
Use bearish trend shifts to identify structural breakdowns, not just momentum pullbacks.
Treat bullish breaks as confirmation of real trend reversals, not early counter-trend signals.
Use trend color aging to gauge whether a move is early-stage or potentially mature.
Avoid fading trends solely based on color maturity — use it as context, not a reversal signal.
Combine Trend Pulse with structure tools (order blocks, liquidity zones, volume) for higher-confidence entries.
🔵 CONCLUSION
Trend Pulse is a structure-aware trend engine built around confirmed pivots, adaptive volatility logic, and time-based trend visualization.
By separating trend direction from trend age , it avoids common indicator pitfalls such as over-sensitivity and late momentum signals.
This makes Trend Pulse especially effective for traders who want clear regime definition, disciplined trend confirmation, and visual clarity directly on price — without relying on lagging oscillators or fixed moving average systems. Indicator

AG Pro Stop Hunt Map Engine [AGPro Series]AG Pro Stop Hunt Map Engine
Overview / What it does
AG Pro Stop Hunt Map Engine is a price-action overlay designed to map potential trap zones after liquidity sweeps. The script focuses on moments where price briefly moves beyond an important reference level, rejects that move, and then closes back through the swept area. In practical terms, this helps traders visualize where a failed breakout or failed breakdown may have left trapped positioning behind.
The engine can work with pivot-based liquidity references, previous day high / previous day low references, or both at the same time. This makes it useful for traders who want a structured way to monitor classic stop-hunt behavior without relying on a single interpretation of liquidity. Instead of treating every wick beyond a level as meaningful, the script applies reclaim logic and filtering rules so that only sweeps with stronger reversal characteristics are highlighted.
The core goal is not to predict every reversal. The goal is to organize sweep events into a readable map: where the sweep happened, which side may be trapped, which zones remain active, and which levels are still relevant as price moves forward. That is why the script is built as a map engine rather than a simple marker tool.
This publication is especially suited to traders who study rejection structure, failed continuation, stop runs, and liquidity-driven reversals. It can be used as a visual context layer inside a broader workflow that may already include structure, trend, momentum, or higher-timeframe bias analysis.
Unique Edge
Many liquidity-sweep tools only mark a wick beyond a prior level and stop there. This script takes a more selective approach. It requires a reclaim condition, supports wick-to-body quality filtering, allows optional fake-sweep filtering, and maintains the resulting event as an actionable mapped zone rather than a one-bar marker.
Its main differentiation is the emphasis on post-sweep structure. Once a sweep qualifies, the script builds and extends a zone so the trader can continue monitoring that area after the original event. This provides a cleaner framework for seeing whether the market is respecting that trap region, moving away from it, or invalidating it.
Another important distinction is the visual hierarchy. The script is designed to separate nearest relevant zones from older or weaker context. This helps keep the chart readable while still preserving useful background information. Instead of cluttering the screen with every historical event at equal importance, the engine highlights what is currently closest and most relevant.
Methodology
The script first defines the liquidity source. Users can choose pivot highs and lows, previous day high and previous day low, or a combined mode that monitors both.
For a bullish trap scenario, price must sweep below a valid downside reference and then reclaim it according to the selected conditions. For a bearish trap scenario, price must sweep above a valid upside reference and then reclaim it. This creates two independent directional engines: one for bullish recovery after downside liquidity is taken, and one for bearish rejection after upside liquidity is taken.
The detection logic is built around several layers:
1. Sweep source selection
The engine checks whether price has moved beyond a chosen pivot or previous-day level.
2. Wick / body filter
The script can require a minimum wick-to-body relationship so that weak or low-conviction candles are filtered out.
3. Reclaim close requirement
The user can require price to close back through the swept level before the event is accepted.
4. Fake sweep filter
An optional penetration filter limits how deep price can move beyond the level before the event is treated as lower quality.
5. Zone persistence
Qualified sweep-and-reclaim events are not left as isolated markers. They are stored and extended forward as zones so the trader can monitor their ongoing relevance.
6. Nearest-zone emphasis
The display engine highlights the nearest bull and bear trap zones so current context is easier to read.
The result is a framework that treats sweep events as evolving market context rather than isolated historical dots.
Signals & Alerts
The script identifies two primary event types:
Bull Trap Reclaim
This appears when price sweeps below a valid reference level and then closes back above it, suggesting that downside liquidity may have been taken and rejected.
Bear Trap Reclaim
This appears when price sweeps above a valid reference level and then closes back below it, suggesting that upside liquidity may have been taken and rejected.
Visual elements can include:
- Sweep zones
- Trap labels
- Right-edge state tags
- Nearest-zone emphasis
- Origin markers on qualifying sweep bars
- A summary panel showing current state and nearest bull / bear trap information
Alert conditions are included for:
- Bullish trap reclaim events
- Bearish trap reclaim events
These alerts are event-based. They identify when a qualifying reclaim occurs according to the active settings.
Key Inputs
Sweep Source
Choose whether the engine uses pivots, previous day levels, or both.
Pivot Strength
Controls how strict the pivot reference detection should be.
Require Reclaim Close
Requires price to close back through the swept level before a zone is created.
Min Wick / Body Ratio
Filters low-quality sweeps by requiring stronger rejection candles.
Use Fake Sweep Filter
Enables an additional penetration-depth filter to reduce weaker events.
Max Penetration (ATR Multiple)
Sets the maximum allowed overshoot beyond the swept level when fake-sweep filtering is enabled.
Chart Mode
Allows a cleaner publish-style view or a more detailed analysis-style view.
Label Mode
Controls how aggressively labels are shown on the chart.
Highlight Nearest Bull / Bear Zones
Emphasizes the closest active zones for faster visual interpretation.
Summary Panel
Shows the current trap state, active bull and bear zone counts, nearest trap levels, and the last detected events.
Limitations & Transparency
This script is not a prediction engine and does not guarantee reversals. A sweep-and-reclaim event can still fail, especially in strong directional environments where price continues expanding after a temporary rejection.
Reference choice matters. Pivot-based detection and previous-day level detection describe different types of liquidity behavior. Depending on the instrument, timeframe, and volatility regime, one source may be more relevant than the other.
Filtering also changes behavior significantly. Tight wick/body requirements or stricter fake-sweep settings will reduce signal frequency. Looser settings will create more events but may also admit weaker structures.
Zones are contextual tools, not standalone trade instructions. Many traders may still want to combine the script with higher-timeframe structure, trend bias, volatility context, or execution rules before making decisions.
As with any chart overlay, visual cleanliness depends on timeframe, market conditions, and user configuration. Different settings may be appropriate for intraday charts versus higher-timeframe swing charts.
Risk Disclosure
This script is for chart analysis and market structure visualization only. It does not provide financial advice, trade recommendations, or guaranteed outcomes. Markets can remain irrational longer than a trap setup appears logical, and any liquidity sweep signal can fail.
Always apply independent judgment, position sizing discipline, and risk management. No single indicator should be used in isolation for live trading decisions.
Indicator
