Adaptive Baseline Suite | NAL1. Overview
Adaptive Baseline Suite | NAL is a multi-baseline trend indicator that compares price against five different adaptive baseline systems. Instead of relying on one smoothing method, it builds separate volatility bands around a Kijun Sen, DEMA, Median, Laguerre Filter, and Gaussian Filter.
Each baseline produces its own bullish or bearish state. These states are then averaged into a final TPI-style score, giving a broader view of whether price is generally trading above or below its adaptive baseline structure.
2. Calculation
The indicator starts by calculating five independent baselines:
baseline_1 = math.avg(ta.lowest(baseline1i), ta.highest(baseline1i))
baseline_2 = ta.dema(source, baseline2i)
baseline_3 = ta.median(source, baseline3i)
baseline_4 = f_laguerre(source, baseline4i)
baseline_5 = gaussianFilter(source, baseline5i, baseline5is)
Each baseline represents a different way of defining the market’s fair-value zone. The Kijun Sen captures midpoint structure, DEMA reacts faster to trend changes, Median reduces noise, Laguerre smooths price recursively, and the Gaussian Filter applies weighted smoothing around a bell-curve distribution.
After the baselines are created, volatility bands are calculated around each one. The indicator measures the residual between price and the baseline, then applies a MAD (Mean aggregate deviation) volatility estimate:
residual = srcPrice - srcBase
_mad = ta.sma(math.abs(residual - ta.sma(residual, volLen)), volLen) * 1.4826
volatility = volSmooth > 1 ? ta.ema(_mad, volSmooth) : _mad
upper = srcBase + volatility * mult
lower = srcBase - volatility * mult
This creates adaptive upper and lower bands around every baseline. A bullish state triggers when price closes above the upper band. A bearish state triggers when price closes below the lower band.
Each baseline receives a score:
score := close > upper_band ? 1 : close < lower_band ? -1 : score
The five scores are then averaged into the final output:
tpi_score = math.avg(score_1, score_2, score_3, score_4, score_5)
A positive final score means most baselines are in bullish expansion. A negative score means most baselines are in bearish expansion.
3. Key Features
Multi-baseline trend model using five different smoothing structures.
Adaptive volatility bands based on residual MAD-style volatility.
Final TPI-style score showing the average bullish or bearish state.
Optional plotting for each baseline’s upper and lower bands.
Candle coloring and histogram visualization for quick regime identification.
4. Use
Use it to identify when price is breaking away from several adaptive baseline models at the same time. A positive score suggests price is trading above the majority of its volatility-adjusted baselines, indicating bullish expansion. A negative score suggests price is trading below the majority of its baselines, indicating bearish expansion.
The individual baseline plots can be enabled when you want to inspect which smoothing model is driving the signal. When most baseline scores agree, the final score becomes more decisive. When the score is mixed or near zero, price is usually inside its adaptive fair-value zone and has not confirmed a clear directional regime. Indicator

Pymander's EZ Key LevelsHey everyone! Pymander here. I’m excited to share EZ Key Levels, a tool I built to solve one of the biggest problems we face as intraday traders: chart clutter.
We all know that "levels are king," but when your screen is a spiderweb of Daily, Weekly, and Session lines, it’s easy to get lost in the noise. This indicator is designed to give you total clarity so you can focus on execution.
What is EZ Key Levels?
At its core, this is a hybrid indicator. It combines High Timeframe (HTF) logic with Machine Learning (K-Means Clustering) to map out the most important psychological and volume-based zones on your chart.
How It Works & Why It’s Different:
Solid Until Mitigated: This is the real game-changer. Every level starts as a solid line (meaning it's fresh and untested). The moment price "mitigates" it—either by a wick touch or a candle close—the line automatically turns dotted. You’ll never have to guess if a level is still "fresh" again.
Volume-Weighted Clustering: Instead of just looking at where price sat, our dynamic clusters use VWAP logic to find where the most volume actually traded. It identifies the true "Value Areas" of the last few days.
Premium Proximity & Focus Mode: Most indicators show you everything at once. EZ Key Levels identifies the 4 levels closest to price and highlights them in Rose (Above) and Emerald (Below). Turn on Focus Mode, and every other line disappears, leaving you with a clean, "pro-style" chart that only shows what matters right now.
All-In-One Session Logic: It automatically tracks Asia, London, and NY session highs/lows and projects them infinitely so you can see how those ranges act as support or resistance days later.
How This Helps You:
This tool is built for the 3-5 minute trader who needs to make split-second decisions. By identifying high-confluence zones (where a V-Cluster lines up with a PDH or Session Low) and highlighting them automatically, it removes the "analysis paralysis" that kills so many trades.
I’d love to hear your thoughts! If you have any feedback or ideas on how to make this even better for your workflow, please let me know.
Wishing you all the best of luck and many, many green days!
-Pymander
Indicator

Hull MA Trend Zones [AGPro Series]Hull MA Trend Zones
📌 Overview
Hull MA Trend Zones is a premium HMA trend overlay built for traders who want a cleaner way to read Hull Moving Average direction, slope quality, and pullback behavior.
The script is centered on one clear idea: a strong HMA trend should not only move above or below a moving average; it should show measurable slope, orderly ribbon structure, and controlled pullback behavior around the active HMA path.
Instead of presenting a crowded moving average wall, the script uses a focused three-line HMA structure, a subtle pullback band, and concept-native trend zones that are tied directly to the active Hull MA state.
⚙️ How It Works
The engine calculates a fast HMA, an anchor HMA, and a slow HMA.
The anchor HMA is the main decision line. Its slope is normalized with ATR so the script can judge whether the current Hull MA movement is weak, transitional, or directional.
The ribbon structure then checks whether the fast, anchor, and slow HMA lines are aligned. This separates clean trend movement from mixed or unstable movement.
Finally, the pullback layer evaluates whether price is extending away from the HMA, testing the HMA zone, holding the HMA zone, rejecting from the HMA zone, or failing the active trend path.
🧭 What The Script Shows
- HMA ribbon for clean trend direction.
- ATR-based HMA pullback band around the anchor HMA.
- Rectangular HMA slope zones created from active directional states.
- Confirmed, quality-gated Bull Turn and Bear Turn labels.
- Optional Hold and Reject labels for pullback events.
- A compact AGPro panel with HMA State, Slope Strength, Pullback Status, and Quality Score.
📊 AGPro Panel
The panel is designed for fast scanning without taking over the chart.
HMA State shows whether the active read is bullish, bearish, transitional, or neutral.
Slope Strength converts the anchor HMA slope into a clear percentage-style reading.
Pullback Status explains whether price is extending, testing, holding, rejecting, or failing the HMA trend zone.
Quality Score combines slope strength, ribbon alignment, and pullback behavior into a single 0-100 reading.
🎯 What Makes It Different
Hull MA Trend Zones is not a generic moving average ribbon, not a ribbon compression map, and not a broad support/resistance tool.
Its focus is narrower and more practical: HMA slope, HMA trend-zone behavior, and pullback-to-HMA quality.
The rectangular zones are not drawn as generic support or resistance. They are HMA slope zones created from the active trend state and the ATR-sized HMA pullback area. This keeps the script visually useful while avoiding overlap with broader zone, corridor, or compression-style indicators.
The default visual design is intentionally restrained. Pullback labels are optional, turn labels require confirmation and a minimum quality score, and old zones are capped so the chart keeps a cleaner premium look on both intraday and higher-timeframe charts.
🔧 Key Settings
Fast HMA Length controls the responsive side of the ribbon.
Anchor HMA Length controls the main trend path, slope state, pullback band, and panel logic.
Slow HMA Length helps identify whether the HMA ribbon is aligned or still transitional.
Slope Lookback and Trend Slope Threshold control how selective the HMA state engine is.
Zone Width ATR controls the height of the HMA pullback band and slope-zone area.
Zone Forward Bars controls how far the active slope zone projects while the same trend state remains valid.
Turn Confirmation and Minimum Turn Label Score control how selective the default turn labels are.
Label Cooldown Bars, Max Visible Labels, and Label Offset ATR keep chart density suitable for publication-quality screenshots.
Panel Location, Panel Theme, Label Font Size, and Panel Font Size are adjustable.
✅ Suggested Use
Use Hull MA Trend Zones to study trend continuation, Hull MA pullback quality, HMA slope transitions, and cleaner moving-average trend behavior.
It is especially useful when you want an HMA-focused overlay that remains readable on active charts and avoids the clutter of large multi-average systems.
The script is designed as a public-free AGPro Series tool with a clean visual identity, a focused HMA concept, and a PulseWire-safe publication structure. 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

Level Survival Map [AGPro Series]Level Survival Map
🔹 Overview
Level Survival Map is a premium support and resistance framework that does not just draw lines on the chart. Every detected level carries a live Survival Score between 0 and 100 that answers one simple question: how well is this level still defending itself right now. The map highlights a single Active Level with an interaction zone and a forward projection ribbon, while nearby weaker levels fade, so traders always know which level actually matters for the current decision.
🔸 Unique Edge
Most support and resistance tools either show static pivots or basic break or retest events. Level Survival Map goes further by measuring the quality of every interaction and turning it into a single composite health score per level. Instead of being left with a wall of equally important lines, the trader sees a ranked structural battlefield with one clearly identified Active Level, a visible interaction zone and a projection ribbon for planning. The Damage State readout, the Fresh and Eroded state semantics, the automatic flip from broken support to new resistance and the cluster fade for crowded weaker levels are designed to work together as one premium, low-noise workflow.
🔹 Methodology
Pivot detection builds the raw candidate levels from swing highs and swing lows using the standard pivot window. A merge filter removes duplicates that sit within a configurable ATR distance of an existing same-type level. Each active level then accumulates four independent components over time. Close Respect rewards closes that respect the level side, for example closes above a support. Penetration Damage penalises wicks and bodies that pierce through the level zone. Reaction Quality rewards strong rejection wicks and bodies moving away from the level after a test. Test Fatigue penalises repeated tests because levels tend to weaken with each new hit. These four components are weighted and combined into a single Survival Score, then clamped between 0 and 100. A structural break caps the score at 35, heavy damage across multiple tests caps it at 28, and a confirmed sequence of opposite-side closes flips the level type while resetting its history. The Active Level is chosen as the closest same-side level to price so that the focus always follows the real decision point.
🔸 Signals and Alerts
The visual output itself is the primary signal. Line colour and thickness communicate level strength at a glance. A focused Active Level is drawn with an interaction zone, a darker core band and a forward projection ribbon so that traders can see the exact price band where reaction is most likely, and how far into the future that band is expected to remain relevant. Labels carry the Survival Score directly, so the ranking of levels is always visible without opening any settings. Broken levels switch to a dashed style and faded colour, and once enough opposite-side closes accumulate they flip type automatically, giving a clear visual signature of structural change.
🔹 Key Inputs
Pivot Left Bars and Pivot Right Bars control how strict the swing detection is. Max Active Levels caps how many concurrent levels are tracked. Level Merge Distance and Interaction Zone are expressed in ATR units so the logic adapts across timeframes and instruments. Scoring weights for Close Respect, Penetration Damage, Reaction Quality and Test Fatigue can be tuned independently, together with the fatigue penalty per extra test and the number of closes required to confirm a flip. Visual inputs cover panel position, label size, line width, focus emphasis, non-focus transparency, cluster fade, focus zone width and projection ribbon length and thickness. A Clean Map Mode is provided for screenshot and publishing workflows where only the Active Level and the nearest valid support and resistance are labelled.
🔸 How to Use
Read the map top down. First, look at the summary panel for the Active Level, its Survival Score, Test Count and Damage State. A Fresh or Strong Active Level defending its side is a high-quality decision point. A Fragile or Eroded Active Level with a Severe Damage State is a warning that the next level below or above is likely to take over. Use the projection ribbon as a planning band for reaction rather than a mechanical entry. Use the ranked non-Active labels to understand where price is likely to travel if the Active Level gives way. The tool is designed to be used as a visual framework, in combination with the trader own execution method, trend context and risk management.
🔹 Limitations and Transparency
This indicator is a visual analytical framework, not a strategy, not a signal service and not financial advice. Survival Score, Damage State and flip logic are deterministic functions of price action and ATR, so different markets and timeframes will produce different characteristic score ranges. Pivot based detection is inherently lagging by the Pivot Right Bars window, which is the expected behaviour of any structural tool and not a defect. The Active Level projection ribbon is a visual planning aid, not a forecast. Past level behaviour does not guarantee future behaviour.
🔸 Risk Disclosure
Trading involves substantial risk and is not suitable for every investor. This script is published for educational and analytical purposes only. Users are solely responsible for their own trading decisions, position sizing and risk management. Always test any tool on your own instruments and timeframes before using it in a live environment. Indicator

Dynamic Acceptance Channel [AGPro Series]Dynamic Acceptance Channel
🔷 Overview
Dynamic Acceptance Channel is an adaptive volatility channel that builds a dynamic upper and lower edge around a robust median midpoint. The channel width breathes with the market's own return distribution and volatility regime, so it naturally widens when the market expands and tightens when it compresses. Every bar is classified as Inside, Breaching, or Respecting the channel, while the width itself is independently tracked as Compressed, Normal, or Expanded. The tool is designed to give traders a clean, consistent framework for reading acceptance, mean-reversion context, volatility squeezes, and adaptive range behavior across crypto, FX, and equities.
🟢 Unique Edge
Most channel indicators on the market rely on a single dispersion model — typically a moving average plus a fixed standard deviation or ATR multiplier. Dynamic Acceptance Channel takes a different route:
▪ Robust median midpoint instead of a simple mean, which stays stable when the market wicks or spikes and is not dragged around by outliers.
▪ Hybrid width model that combines the percentile spread of recent returns with a clamped ATR regime ratio. The user can switch between Hybrid, Return Percentile, or Volatility Regime, depending on whether distribution shape or raw volatility is the priority.
▪ Independent width regime classification (Compressed / Normal / Expanded) ranked against the channel's own history, with hysteresis applied so the regime does not flip-flop around threshold boundaries.
▪ Bar-level state machine (Inside, Breach, Respect) separated from the width regime, so traders can read location and regime as two orthogonal dimensions.
▪ Double-EMA smoothing on both the midpoint and the half-width, producing a calm, professional channel that is readable on any timeframe without looking jagged.
This combination is not found in common Bollinger Bands, Keltner Channels, or generic ATR channels.
🧭 Methodology
The midpoint is computed as a rolling median using linear-interpolation percentile logic, which is statistically more robust than an arithmetic mean when the return distribution is skewed or heavy-tailed. The half-width is then derived from two independent signals. The first is a return-percentile dispersion term: the script measures the 85th and 15th percentiles of recent per-bar returns, symmetrizes them, and scales by the square root of the lookback window to produce a percentile-based half-width proxy. The second is a volatility regime term: the current 14-bar ATR is compared to its own baseline over the adaptive window, and the resulting ratio is clamped between 0.6 and 1.8 to prevent explosive widths during regime shocks. The final half-width is either one of the two terms or their average, depending on the selected model, then scaled by a user-defined global multiplier and smoothed with double EMA. The width regime classification uses linear-interpolation percentiles of the channel width itself over a separate regime lookback, and a 10% hysteresis buffer prevents rapid state flipping around the Compressed and Expanded thresholds.
🎯 Signals & Alerts
▪ Channel Breached — fires on a fresh upper or lower breach, edge-triggered with a minimum three-bar gap to avoid clusters on choppy bars.
▪ Channel Compressed — fires when the width regime transitions into the Compressed state.
▪ Channel Expanded — fires when the width regime transitions into the Expanded state.
▪ Channel Respected — optional, fires when price wicked outside on the prior bar and closed back inside on the current bar, confirming a rejection at the edge.
Visuals include color-coded upper and lower lines, a regime-tinted fill, small circular breach markers on the breached line (no text labels to avoid clutter), and spaced Compressed or Expanded transition labels anchored outside the channel.
⚙️ Key Inputs
Adaptive Engine
▪ Adaptive Length — lookback window for the channel (default 60).
▪ Channel Width Model — Hybrid, Return Percentile, or Volatility Regime.
▪ Width Scale — global multiplier for tightening or loosening the channel.
▪ Channel Smoothing — EMA length for line smoothness.
▪ Strict Breach Logic — close-based versus wick-based breach.
Width Regime
▪ Compression Threshold — percentile below which the width is Compressed (default 25).
▪ Expansion Threshold — percentile above which the width is Expanded (default 75).
▪ Regime Lookback — lookback for the width percentile ranking (default 150).
Visuals
▪ Show Channel Fill, Show Midline, Show Breach Markers, Show Regime Transition Labels, Regime Label Spacing.
Panel
▪ Show / hide panel, Panel Location (6 options), Panel Font Size, Label Font Size.
Alerts
▪ Channel Breached, Compressed, Expanded, and Respected can be toggled independently.
🧠 How to Use
A common reading is to combine channel state with width regime. When the channel is Compressed and price is riding the edges, the market is often preparing for an expansion phase. When the channel transitions into Expanded, continuation on the active edge is more likely than immediate mean reversion. Respect events at either edge during Normal or Compressed regimes often line up with fade opportunities, while breaches during Expanded regimes often line up with trend continuation context. The midline can be used as a dynamic fair-value reference for pullback entries inside the channel. Traders typically overlay this script with their own structure, momentum, or higher-timeframe bias tools rather than using channel events in isolation.
⚠️ Limitations & Transparency
▪ The indicator is a context and structure tool. It does not generate buy or sell decisions and does not claim to identify every meaningful reversal or breakout.
▪ The channel is recomputed each bar from recent data, which means the current bar's channel values can refine until bar close.
▪ Width regime classification is relative to the regime lookback, not absolute. On instruments or timeframes with very low variance, the regime may behave differently than on highly volatile markets.
▪ The ATR ratio is intentionally clamped between 0.6 and 1.8. This prevents explosive widths but also means the channel will not fully mirror extreme volatility shocks; this is a deliberate design choice for readability.
▪ Alerts are configured to fire once per bar close to reduce noise. Intrabar conditions may change until close.
🛡 Risk Disclosure
This script is provided for educational and analytical purposes only. It is not a strategy, not financial advice, and not a trade recommendation. Past channel behavior on any instrument or timeframe does not imply future performance. Users are fully responsible for their own risk management, position sizing, and trading decisions. Indicator

AG Pro ATR Envelope Breakout Quality [AGPro Series]AG Pro ATR Envelope Breakout Quality
Overview / What it does
AG Pro ATR Envelope Breakout Quality is a volatility-aware breakout framework built around a dynamic ATR envelope rather than a static horizontal level, fixed box, or session-defined range. The script tracks when price closes outside an ATR-based outer band, then evaluates whether that move shows enough quality to be treated as a meaningful breakout instead of a weak expansion, short-lived overshoot, or low-conviction push.
The core logic is centered on three linked questions. First, did price achieve a valid close outside the active envelope? Second, was that move supported by enough momentum and relative participation to deserve attention? Third, what happened when price came back toward the broken area? This progression allows the script to move beyond a simple breakout marker and present a more structured breakout-quality workflow.
Because the reference structure is dynamic, the script adapts to changing market conditions instead of forcing all setups into a fixed box logic. In periods of contraction, the envelope tightens and makes outside acceptance more meaningful. In periods of expansion, the envelope widens and helps separate true continuation pressure from ordinary volatility noise. This makes the tool especially useful for traders who want to judge whether an expansion is merely visible or genuinely tradable.
The visual design is intentionally clean and overlay-first. The envelope defines the active volatility shell, breakout markers show where price escapes that shell, the throwback zone highlights the key acceptance pocket after the move, and the optional target line provides a simple expansion objective. A compact panel then summarizes the current state without taking over the chart. The result is a script that aims to look premium while still keeping the main story readable in a publish screenshot.
Unique Edge
The main distinction of this script is that it does not evaluate breakout quality from a static support/resistance line, a consolidation rectangle, a Donchian extreme, or an opening range boundary. It evaluates breakout quality from a moving ATR envelope. That difference is not cosmetic. It changes the entire logic of what counts as a breakout, how follow-through is judged, and how retests are interpreted.
In several classic breakout tools, the market is asked to escape a fixed historical structure. Here, the market is asked to achieve acceptance outside a live volatility shell. This creates a different analytical lens. A move that looks impressive relative to a flat level may not be meaningful relative to a volatility-adjusted envelope. On the other hand, a clean close outside an adaptive outer band can reveal expansion quality that a simple line break would miss.
This also separates the script from our other AG Pro tools. It is not a consolidation breakout evaluator, because its reference structure is not a box. It is not a Donchian breakout tool, because it is not based on period highs and lows. It is not an opening-range breakout model, because it is not session-box dependent. It is not a standard break-retest script, because the retest here happens around a dynamic envelope acceptance area rather than around a static horizontal level.
That distinction matters both analytically and visually. Analytically, the script focuses on volatility-adjusted breakout acceptance. Visually, it produces a different type of chart story: an active envelope, a breakout event, a throwback pocket, and a projected path. This gives the script its own place inside the AG Pro catalog rather than making it feel like a variation of an existing breakout family member.
Methodology
The script begins with an ATR-based envelope built around a moving basis. This creates an adaptive upper and lower band that expand or contract with market volatility. A bullish breakout candidate appears when price closes outside the upper band. A bearish breakout candidate appears when price closes outside the lower band. Wick-only excursions are not enough. The script is designed to care about acceptance, not mere contact.
Once an outside close is detected, the script evaluates breakout quality through a compact scoring framework. Momentum contribution helps measure whether the breakout candle shows real displacement or just a hesitant push. Volume contribution helps detect whether the breakout is supported by stronger-than-usual participation or whether it lacks confirmation. The combined result becomes the displayed breakout-quality score.
After the initial breakout, the script monitors the first return toward the broken band area. This is where the throwback logic becomes important. Instead of treating every pullback the same way, the script classifies what happens around the envelope area and updates the state accordingly. A successful hold suggests that the market accepted the breakout. A failure suggests that the move lost structural quality after the initial expansion.
An optional target line can be used to project a simple post-breakout objective. This is not presented as a promise of outcome. It is a visual planning reference intended to show a possible expansion path if the breakout continues to behave constructively. Together, the envelope, the breakout signal, the throwback state, and the target framework create a full breakout-quality sequence rather than a single event label.
Signals & Alerts
The script is designed to organize the breakout workflow into visible states rather than flooding the chart with constant commentary. The main states include bullish breakout, bearish breakout, throwback monitoring, throwback hold, breakout failure, and target hit. This makes the chart easier to read and helps the user understand where the setup currently stands.
Bullish and bearish breakout markers appear when price achieves a confirmed outside close beyond the relevant envelope band. These are the initial expansion events. They are then followed by a monitoring phase in which the script watches how price behaves around the broken band area. If the return is constructive, the script can label that behavior as a successful hold. If the move loses quality and breaks down, the script can classify it as a failure.
The target marker is optional and functions as a planning aid, not as a certainty engine. It simply shows that the projected expansion objective has been reached based on the chosen configuration. In practical use, this can help traders separate the breakout event itself from the later progression of the move.
The alert set is intended to remain deterministic and chart-state aware. It focuses on confirmed breakout events, throwback behavior, breakout failure, and target completion. This keeps the script aligned with workflow clarity instead of turning it into a noisy alert generator.
Key Inputs
The envelope settings control the moving basis, ATR length, and multiplier that define the adaptive breakout shell. These settings determine how sensitive the script is to changing volatility and how demanding the outside-close condition becomes.
The breakout filter settings allow the user to regulate confirmation quality. Depending on the selected configuration, the script can require stronger momentum, clearer outside distance, and optional volume confirmation. This helps users decide whether they want a more selective or more responsive model.
The throwback analysis settings define how the script interprets the first return toward the broken envelope area. These settings influence how deeply price can revisit the area before the move is treated as weak, failed, or still acceptable.
The target settings control whether the projected objective is shown and how far it is placed from the breakout area. The visual settings then manage panel visibility, panel placement, font sizing, historical object behavior, and label density so the script can remain clean in live use and in publish screenshots.
Limitations & Transparency
This script is a breakout-quality framework, not a prediction engine. It does not know in advance whether a breakout will continue. It evaluates the quality of a breakout after a valid outside-close event occurs and then tracks how price behaves afterward. That distinction is important.
The ATR envelope is an adaptive reference, which means the same market move may be classified differently under different volatility regimes. That is intentional. The script is designed to respond to changing market structure, but any adaptive model will also reflect the sensitivity of its settings. Users should therefore expect the behavior of the tool to vary across symbols, timeframes, and volatility environments.
Volume inputs may also behave differently across markets and data feeds. On some instruments, volume can add useful confirmation. On others, it may be less informative. For that reason, volume should be treated as a supporting factor rather than as an absolute truth layer.
The target projection is a chart-planning feature, not a guaranteed outcome. Likewise, a breakout failure label does not mean the market cannot later recover, and a target hit does not mean the move was universally optimal. The script is meant to help structure chart reading, not replace trade management, context analysis, or personal decision-making.
How this script differs from our other AG Pro tools
Within the AG Pro lineup, this script is intentionally positioned as a volatility-envelope breakout tool. It does not compete with our box-based breakout logic, our period-high/low breakout logic, or our static break-retest logic. Its role is to answer a different question: did price achieve meaningful acceptance outside an adaptive ATR shell, and did that acceptance survive the first return test?
That makes it especially useful when traders want a volatility-adjusted view of expansion quality. In markets where static levels are repeatedly pierced, an adaptive envelope framework can provide a cleaner read on whether the move is truly escaping current volatility conditions or simply stretching within ordinary noise.
In that sense, the script is not a replacement for our other breakout-oriented tools. It is a separate layer with a different reference model, different retest logic, and a different chart story. That separation is deliberate and is one of the reasons the script belongs in its own category inside the broader AG Pro collection.
Risk Disclosure
This script is an analytical chart tool designed to visualize volatility-adjusted breakout conditions, breakout quality, and post-breakout behavior. It is not financial advice, not a signal service, and not a guarantee of future price direction.
All breakout conditions can fail. Momentum can fade, volume can be inconsistent, and throwback behavior can change quickly. Markets remain uncertain, and no indicator can eliminate risk. Users should always apply their own market judgment, risk controls, and execution rules.
Use the script as a structured decision-support layer, not as a stand-alone trading instruction. Confirmation from broader context, trend conditions, liquidity structure, and personal risk management remains essential.
Indicator

Bastion Execution Protocol [JOAT]Bastion Execution Protocol
Introduction
The Bastion Execution Protocol is an open-source automated trading strategy built in Pine Script v6. It combines regime detection, market structure analysis, dual momentum confirmation (RSI + Stochastic Momentum Index), order flow validation (CVD), candle pattern recognition, session filtering, and dynamic risk management into a single institutional-grade execution framework. The strategy is designed to take high-confluence directional trades only when multiple independent factors align — regime, structure, momentum, volume flow, and session — while managing risk through ATR-based stop losses, configurable reward-to-risk ratios, trailing stops, regime-adaptive position sizing, daily trade limits, and end-of-day forced closes.
This is not a "set and forget" black box. It is a transparent, fully configurable framework where every entry condition, risk parameter, and filter can be adjusted. The strategy is published open-source so traders can study the logic, understand why each trade is taken, and adapt the parameters to their instruments and timeframes.
Why This Strategy Exists
Most published strategies on PulseWire fall into two categories: overly simple (single indicator crossover) or overly complex (dozens of conditions that overfit to historical data). This strategy occupies the middle ground — it requires meaningful confluence from independent analytical dimensions without over-optimizing to specific historical patterns:
Multi-Factor Entry Gate: Every trade requires agreement from regime detection, market structure, momentum oscillators, and optionally CVD order flow and candle patterns. No single factor can trigger a trade alone.
Regime-Aware Execution: The strategy only trades in trending regimes by default. It avoids squeeze conditions and can be configured to require specific regime states. Position sizing automatically reduces in volatile or uncertain regimes.
Session Intelligence: Trades are filtered by session (London, New York, Kill Zones) and day of week. The strategy avoids low-quality periods and forces position closure at end of day.
Dynamic Risk Management: ATR-based stop losses adapt to current volatility. Trailing stops activate after a configurable profit threshold. Position sizing is calculated from account equity and risk percentage, then adjusted by regime conditions.
Performance Tracking: Real-time HUD displays win rate, profit factor, max drawdown, daily trade count, and current position status.
Strategy Architecture — 9 Modules
The strategy is organized into 9 sequential modules, each responsible for a specific aspect of the trading process:
Module 1: Regime Detection
The regime engine classifies the market into four states using SMA alignment and VWAP slope:
Trend Up: SMA 20 > 50 > 200 (bull alignment) AND positive VWAP slope — clear upward momentum
Trend Down: SMA 20 < 50 < 200 (bear alignment) AND negative VWAP slope — clear downward momentum
Squeeze: Bollinger Band width in the bottom 10th percentile — volatility compression
Range: No SMA alignment and flat VWAP slope — sideways conditions
The VWAP slope is normalized by ATR to make it comparable across instruments with different price scales. The regime state directly controls whether trading is allowed — by default, the strategy requires a trending regime.
Module 2: Market Structure
Swing-based structure tracking identifies the directional bias:
Pivot highs and lows are detected using configurable lookback
When price closes above the last swing high while structure was bearish or neutral, structure flips bullish
When price closes below the last swing low while structure was bullish or neutral, structure flips bearish
Structure must agree with the regime for entries — regime bullish + structure bullish = long allowed
Displacement candle detection identifies aggressive institutional order flow — candles with body >= 70% of range and body >= 1.8x the 20-bar average body. These serve as entry triggers when all other conditions are met.
Module 3: Momentum Confirmation
Dual momentum confirmation requires both RSI and SMI to agree:
RSI: Must be above the bull threshold (default 55) for longs, below the bear threshold (default 45) for shorts
Stochastic Momentum Index: Must be positive for longs, negative for shorts. The SMI measures where price sits relative to the midpoint of its recent range, double-smoothed for noise reduction.
Both must agree — RSI bullish AND SMI bullish = momentum confirmed for longs
Module 3B: CVD Order Flow Confirmation
When enabled, Cumulative Volume Delta must support the trade direction:
Buy volume is estimated from bullish candles (close > open = full volume, otherwise proportional)
Sell volume = total volume minus buy volume
CVD = cumulative sum of (buy volume - sell volume)
CVD must be above its moving average for longs, below for shorts
This ensures that actual volume flow supports the intended trade direction
Module 3C: Candle Pattern Detection
When enabled, the strategy detects institutional candle patterns as entry triggers:
Bullish Engulfing: Current bullish candle fully engulfs the prior bearish candle's body, with volume above average
Bearish Engulfing: Current bearish candle fully engulfs the prior bullish candle's body, with volume above average
Bullish Pin Bar: Lower wick > 2x body, upper wick < 0.5x body — rejection of lower prices
Bearish Pin Bar: Upper wick > 2x body, lower wick < 0.5x body — rejection of higher prices
Patterns serve as alternative entry triggers alongside displacement candles. Either a displacement candle, a pattern, or price above SMA20 + VWAP can trigger entry when all other conditions are met.
Module 4: Session Filter
The session filter controls when trading is allowed:
Four session windows: NY Kill Zone (7-10am), London Kill Zone (2-5am), NY Session (9:30am-4pm), London Session (3am-9:30am)
Each session can be individually enabled/disabled
Day of week filter allows disabling specific days (e.g., avoid Mondays or Fridays)
Configurable timezone (default: America/New_York)
End-of-day forced close at configurable time (default: 3:45pm)
Module 5: Daily Trade Counter
A daily trade counter prevents overtrading:
Resets at the start of each new day
Configurable maximum trades per day (default: 3)
Combined with squeeze avoidance and regime filtering for comprehensive trade gating
Module 6: Entry Signal Generation
Entry signals require ALL of the following to be true simultaneously:
// Long entry requires full confluence:
// 1. Regime = Trend Up
// 2. Structure trend = Bullish (swing break confirmed)
// 3. RSI > bull threshold AND SMI > 0
// 4. CVD above its MA (if enabled)
// 5. Bar is confirmed (barstate.isconfirmed)
// 6. Trade is allowed (daily limit, session, no squeeze)
// 7. Trigger: displacement candle OR pattern OR price > SMA20 + VWAP
This multi-gate approach ensures that trades are only taken when regime, structure, momentum, volume flow, session, and a specific trigger all agree. The probability of a random signal passing all gates is very low, which is by design.
Module 7: Risk Calculations
Risk is calculated dynamically for each trade:
Stop Loss: ATR * configurable multiplier (default 1.5x) below entry for longs, above for shorts
Take Profit: SL distance * reward-to-risk ratio (default 2.0x)
Position Size: (Account Equity * Risk Percentage * Regime Multiplier) / SL Distance
Regime-Adaptive Sizing: When enabled, position size is reduced to 50% during squeeze conditions and 70% during non-trending conditions. Full size is used only in trending regimes.
Module 8: Trade Execution
Entries are executed using strategy.entry() with calculated position size. The strategy tracks active trade parameters (entry price, SL, TP) for trailing stop management.
Module 9: Exit Management
Three exit mechanisms operate simultaneously:
Fixed SL/TP: strategy.exit() with the calculated stop loss and take profit levels
Trailing Stop: When enabled, activates after price moves a configurable multiple of R in profit (default 1.0R). The trail distance is ATR * configurable multiplier (default 1.0x). The trailing stop only moves in the favorable direction and replaces the fixed SL when it is tighter.
End-of-Day Close: All positions are closed at the configured time to avoid overnight risk
Performance Tracking
The strategy tracks and displays real-time performance metrics:
Win Rate: Wins / (Wins + Losses) as a percentage
Profit Factor: Gross Profit / Gross Loss — values above 1.5 indicate a healthy edge
Max Drawdown: Peak-to-trough equity decline as a percentage
Net P&L: Total net profit/loss
Daily Trade Count: Current day's trades vs maximum allowed
Strategy Settings and Backtesting Notes
The strategy is configured with realistic default parameters:
Initial Capital: $100,000
Default Position Size: 2% of equity
Risk Per Trade: 1.5% (configurable)
Commission: Not included by default — users should add commission appropriate to their broker in the strategy settings
Slippage: Not included by default — users should add slippage appropriate to their instrument
calc_on_every_tick: false — the strategy only evaluates on confirmed bar closes to prevent repainting
calc_on_order_fills: true — allows trailing stop updates on fill events
Important: Before evaluating backtest results, users should:
Add realistic commission for their broker (e.g., $5 per trade for stocks, 0.1% for crypto)
Add realistic slippage (e.g., 1-2 ticks for liquid instruments)
Verify that the backtest period includes different market conditions (trending, ranging, volatile)
Check that the number of trades is sufficient for statistical significance (100+ trades recommended)
Understand that past performance does not guarantee future results
Input Parameters
Risk Management:
Risk Per Trade %: Percentage of equity risked per trade (default: 1.5%)
Reward:Risk Ratio: TP distance as multiple of SL distance (default: 2.0)
SL ATR Multiplier: Stop loss distance as ATR multiple (default: 1.5)
ATR Length: Period for ATR calculation (default: 14)
Use Trailing Stop: Enable/disable trailing (default: true)
Trail After X R Profit: Profit threshold to activate trail (default: 1.0R)
Trail ATR Multiplier: Trail distance as ATR multiple (default: 1.0)
Max Trades Per Day: Daily trade limit (default: 3)
Regime-Adaptive Sizing: Reduce size in non-trending conditions (default: true)
Regime Filter:
VWAP Slope Lookback: Period for slope calculation (default: 20)
Slope Threshold: Normalized threshold for trend detection (default: 0.12)
Bollinger Length/Multiplier: BB parameters for squeeze detection (default: 20/2.0)
Avoid Squeeze Entries: Skip entries during squeeze (default: true)
Require Trend Regime: Only trade in trending conditions (default: true)
Structure:
Swing Lookback: Pivot detection length (default: 5)
Displacement Min Body Ratio: Minimum body/range for displacement (default: 0.7)
Displacement Body Multiplier: Minimum body vs average for displacement (default: 1.8)
Momentum:
RSI Length/Thresholds: RSI parameters (default: 14, bull 55, bear 45)
SMI Lookback/Smoothing: SMI parameters (default: 13/25/2)
Session Filter:
Enable Session Filter: Toggle session-based trade gating
Individual session toggles: NY KZ, London KZ, NY, London
Day of week toggles: Monday through Friday
Force Close End of Day: Toggle EOD position closure
Close Hour/Minute: EOD close time (default: 15:45)
Order Flow:
CVD Confirmation: Require delta direction to match entry (default: true)
CVD Lookback: Period for CVD moving average (default: 10)
Candle Patterns:
Use Pattern Confirmation: Enable pattern detection as entry trigger (default: true)
Pattern Volume Multiplier: Minimum volume for pattern confirmation (default: 1.3x)
How to Use This Strategy
Step 1: Configure for Your Instrument
Adjust the ATR multiplier and displacement thresholds for your instrument's volatility. Add realistic commission and slippage in PulseWire's strategy settings.
Step 2: Set Your Risk Parameters
Choose a risk percentage that matches your risk tolerance. The default 1.5% with 2:1 R:R is conservative. Adjust the trailing stop parameters based on your preference for locking in profits vs giving trades room.
Step 3: Configure Sessions
Enable the sessions relevant to your instrument. For US equities, NY KZ and NY Session are most relevant. For forex, both London and NY Kill Zones are important. Disable days you prefer not to trade.
Step 4: Run the Backtest
Apply the strategy to your chart and review the backtest results. Check win rate, profit factor, max drawdown, and number of trades. Ensure results are realistic and not the product of overfitting.
Step 5: Forward Test
Before trading live, run the strategy in paper trading mode for at least 2-4 weeks to verify that live performance matches backtest expectations.
Best Practices
Always add commission and slippage before evaluating backtest results
The strategy works best on liquid instruments with reliable volume data
Higher timeframes (15m+) produce fewer but higher-quality trades
The multi-gate entry system means trades are infrequent by design — this is a feature, not a bug
Regime-adaptive sizing is recommended — it automatically reduces exposure in uncertain conditions
The daily trade limit prevents revenge trading and overexposure
End-of-day forced close eliminates overnight gap risk for intraday strategies
Monitor the HUD during live trading for real-time regime, momentum, and session context
If win rate drops below 40% or profit factor drops below 1.0, re-evaluate parameters for current market conditions
Limitations
The strategy uses lagging indicators (SMAs, RSI, SMI) for entry conditions. Entries occur after the trend has started, not at the exact turn.
Regime detection can lag regime changes. The strategy may miss the first portion of a new trend or take a trade just as a trend is ending.
CVD is estimated from candle direction, not true order flow data. This is an approximation.
Backtest results are hypothetical and do not account for real-world execution issues (partial fills, requotes, connectivity).
The strategy is designed for intraday/swing trading. It is not optimized for scalping or long-term position trading.
Session filtering is based on EST timezone. Instruments traded primarily in other timezones may need different session definitions.
The multi-gate entry system can be too restrictive in some market conditions, producing very few trades. This is intentional — the strategy prioritizes quality over quantity.
Past performance in backtesting does not guarantee future results. Market conditions change, and strategies that worked historically may not work in the future.
Technical Implementation
Built with Pine Script v6 using:
calc_on_every_tick=false for non-repainting execution
barstate.isconfirmed gating on all signal generation
9-module architecture with clear separation of concerns
ATR-based dynamic stop loss and take profit calculation
Trailing stop with configurable activation threshold and trail distance
Regime-adaptive position sizing with squeeze and non-trending penalties
Session detection with timezone support and day-of-week filtering
Daily trade counter with automatic reset
End-of-day forced close mechanism
Real-time performance tracking (win rate, profit factor, max drawdown)
Dual momentum confirmation (RSI + SMI)
CVD order flow validation
Candle pattern detection (engulfing, pin bar) with volume confirmation
6 alert conditions covering entries, regime changes, EOD close, patterns, and drawdown
Originality Statement
This strategy is original in its multi-dimensional confluence framework. While individual components (RSI, SMI, SMA alignment, session filtering) are established concepts, this strategy is justified because:
The 9-module architecture creates a clear, auditable decision pipeline where each module's contribution to the final trade decision is transparent
The multi-gate entry system (regime + structure + dual momentum + CVD + session + trigger) requires an unusually high level of confluence, reducing false signals
Regime-adaptive position sizing automatically adjusts exposure based on market conditions, a feature rarely seen in published strategies
The combination of trailing stops with regime-aware sizing creates a dynamic risk framework that adapts to changing conditions
Session filtering with Kill Zone preference and day-of-week controls provides institutional-grade time management
CVD order flow confirmation adds a volume-based validation layer that pure price-based strategies lack
The real-time HUD with performance tracking provides transparency into strategy behavior that most published strategies do not offer
The Volcanic theme provides a cohesive visual identity where every color choice carries meaning (lava = entry, amber = warning, teal = VWAP, crimson = bearish)
Disclaimer
This strategy is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Backtested results are hypothetical and do not represent actual trading. Past performance does not guarantee future results. The strategy involves risk of loss, including the potential loss of the entire investment. Commission, slippage, and other real-world execution costs are not included in the default configuration and must be added by the user for realistic evaluation. The author makes no claims about the profitability of this strategy and is not responsible for any losses incurred from its use. Always use proper risk management, trade with capital you can afford to lose, and consider consulting a qualified financial advisor before trading.
-Made with passion by officialjackofalltrades
Strategy

[ A L P H A X ] Dynamic Liquidity Matrix
AlphaX Dynamic Liquidity Matrix — Volume-Weighted Liquidity Heatmap, Fair Value Gap Overlay, Sweep Detection & Live Bias Dashboard
AlphaX Dynamic Liquidity Matrix is a professional-grade liquidity mapping system that identifies where stop-loss clusters and unfilled liquidity pools accumulate across the recent price range — and tracks them in real time. Unlike a static volume profile that simply measures historical volume at price, this indicator builds a fully dynamic heatmap from volume-weighted pivot extremes, recalculates on every bar, and only displays zones that price has not yet revisited. These are the active pockets that institutions and smart money systematically target for liquidity sweeps.
Built on the AlphaX brand framework, the indicator combines four distinct analytical layers: a dynamic liquidity profile, a Fair Value Gap (imbalance) overlay, a sweep detection engine, and a live market context dashboard — all unified under a single, clean visual system.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔬 The Dynamic Liquidity Profile — How It Works
Most volume profiles are passive historical tools. The AlphaX Dynamic Liquidity Matrix is active and forward-looking.
On every bar within your configured lookback window, the indicator identifies swing highs and swing lows and assigns each one a volume weight based on the smoothed cumulative volume at that moment — normalized against the maximum volume within the entire lookback window. This produces a volume score (0–100%) for every extreme, which represents the relative significance of the liquidity pool at that price.
These volume-weighted extremes are then distributed across a configurable number of price bins (resolution levels) spanning the full high-to-low range of the lookback window. Each bin accumulates the total volume from every pivot that maps into it. The result is a real-time heatmap profile showing exactly where liquidity is concentrated — heavier at some levels, lighter at others.
The ATR is used to scale the pivot offset distance dynamically, meaning the profile adapts automatically to the current volatility regime. On high-volatility instruments and timeframes, the pivot offsets expand; on quiet markets, they contract. No manual recalibration is required.
What makes this different from a standard Volume Profile:
Standard volume profiles measure how much volume traded at a price — they are backward-looking and include already-filled orders
AlphaX DLM tracks unmitigated pivot extremes — zones where stops and unfilled orders still exist because price has NOT revisited them since they formed
Every pivot that gets swept by price is automatically removed from the profile — keeping the map clean and relevant at all times
The profile rebuilds every bar, so it reflects the current state of the market's liquidity landscape, not a snapshot from hours or days ago
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Profile Visualization
The profile is displayed as horizontal bars extending to the right of the current price, with each bar representing one price bin. The visual system communicates multiple layers of information simultaneously:
Color Logic
Yellow-green bars — bins where the current close is above the bin midpoint (buy-side liquidity / demand zones)
Red bars — bins where the current close is below the bin midpoint (sell-side liquidity / supply zones)
Orange highlight — the Point of Control (POC) bin, the single highest-volume level in the entire profile
Gradient Depth
Each bar uses a gradient that scales from near-transparent at low volume to fully opaque at high volume. At a glance, the most significant liquidity concentrations stand out immediately — no need to read numbers or hover over elements.
Volume Labels
For bins with above-average volume accumulation, the raw volume figure is displayed inside the bar. A percentage label on the left side of each bar shows what proportion of the maximum bin volume that level represents. This gives you both absolute and relative context for every zone.
POC Line
The Point of Control — the level with the highest accumulated liquidity in the profile — is marked with a full dashed horizontal line that extends across the entire lookback window. This makes it easy to see how price has historically reacted around the dominant liquidity level: rejected it, consolidated around it, or broken through it cleanly. A labeled marker on the right identifies the POC precisely.
Liquidity Level Lines
Each active bin above the noise floor is also represented by a dotted horizontal line on the chart itself. The line starts from the bar where price last tested that level and runs to the current bar, giving you a visual connection between the historical pivot origin and the current profile position. Line width scales with the bin's relative volume weight — heavier lines mean more significant zones.
Buy / Sell Split Mode
An optional split view separates each profile bar into its buy-side and sell-side components, stacked side by side. This lets you see at a single level whether it is dominated by buy-side stop clusters (below price), sell-side stop clusters (above price), or a balanced mix — critical for anticipating which direction a liquidity sweep is more likely to run.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Fair Value Gap (Imbalance) Overlay
A Fair Value Gap is a three-candle imbalance where the body of the middle candle is not overlapped by the wicks of the surrounding candles, creating a gap in price delivery. These gaps represent unfilled orders left by rapid, one-sided moves — and price has a strong statistical tendency to return to fill them.
AlphaX DLM detects and displays these gaps directly on the chart as shaded rectangular zones:
Bullish FVG — the low of the current candle is higher than the high of the candle two bars prior. Price moved up so quickly it left an unfilled gap below. Displayed in yellow-green.
Bearish FVG — the high of the current candle is lower than the low of the candle two bars prior. Price moved down so quickly it left an unfilled gap above. Displayed in red.
Mitigation Tracking
Once price returns and closes inside a FVG zone (mitigating it), the box is automatically removed from the chart. Only genuinely unmitigated gaps remain visible at all times — the overlay stays clean and actionable regardless of how many gaps have formed historically.
ATR-Scaled Minimum Size Filter
A configurable minimum FVG size (expressed as a multiple of the current ATR) filters out micro-gaps caused by normal spread or noise. Only structurally significant imbalances that represent real impulsive moves are displayed.
Background Highlight
When the current close is inside an active FVG zone — meaning price is currently sitting inside an unmitigated imbalance — the chart background highlights in a subtle amber tone. This is a real-time alert that price is at a decision point within institutional supply or demand.
How to trade FVGs with the Liquidity Matrix:
When a FVG aligns with a high-volume liquidity bin on the profile, the confluence is significant — two independent reasons for price to react at the same level
Bullish FVG zones near buy-side liquidity clusters are high-priority long re-entry areas
Bearish FVG zones near sell-side liquidity clusters are high-priority short re-entry areas
A sweep into a zone followed by an immediate close back through it (a sweep-and-reverse pattern) is one of the cleanest entry setups the indicator can flag
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 Liquidity Sweep Detection
Liquidity sweeps are the mechanism by which institutional players clear stop-loss orders before reversing price in the opposite direction. Identifying sweeps in real time gives retail traders the opportunity to enter after the stops have been taken — in alignment with the direction the institution is positioning.
AlphaX DLM detects sweeps using the following logic:
Bullish Sweep (⚡ SWEEP LOW)
The current bar's low breaches the lowest low of the configurable sweep lookback window, but the bar closes above that low and closes as a bullish candle. This pattern indicates that sell-side stops below the recent range were triggered, absorbed, and reversed — a classic stop hunt before an upside move.
Bearish Sweep (⚡ SWEEP HIGH)
The current bar's high breaches the highest high of the sweep lookback window, but the bar closes below that high and closes as a bearish candle. Buy-side stops above the recent range were triggered and absorbed — a stop hunt before a downside move.
Visual Presentation
Bullish sweeps are labeled with a cyan "⚡ SWEEP LOW" marker below the sweep candle
Bearish sweeps are labeled with an orange "⚡ SWEEP HIGH" marker above the sweep candle
The sweep candle itself is barcolored in the respective sweep color — immediately visible on the chart without needing to look for the label
The most recent 20 sweep labels are retained on the chart, automatically pruning the oldest when new ones form
How to use Sweep Detection with the Liquidity Profile:
A sweep into a high-volume buy-side liquidity bin followed by a close back above that bin is a high-conviction long entry signal
A sweep into a high-volume sell-side liquidity bin followed by a close back below that bin is a high-conviction short entry signal
When a sweep coincides with a FVG zone AND a high-volume profile bin, the three-way confluence represents the highest quality trade setup the indicator can identify
The sweep lookback can be tightened (lower value) for more sensitive detection on fast-moving instruments, or widened for cleaner, less-frequent signals on slower timeframes
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 Live Market Context Dashboard
A compact real-time dashboard displays the current state of all indicator systems at a glance. It is divided into four sections:
Profile Section
Active Pivots — total number of unmitigated pivot extremes currently mapped in the profile. Higher counts indicate a richer, more complex liquidity landscape.
Buy Pivots — number of unmitigated buy-side (demand) extremes
Sell Pivots — number of unmitigated sell-side (supply) extremes
Liquidity Bias — overall directional lean of the liquidity map. BUY SIDE means more unmitigated demand zones exist; SELL SIDE means more supply zones exist; BALANCED means roughly equal. This is not a trade signal on its own, but it tells you where the more significant unfilled orders are positioned.
Sweep Section
Last Sweep — whether the current bar is a bullish or bearish sweep, highlighted in the respective sweep color when active
Sweep Lookback — the currently configured lookback window for sweep detection
Fair Value Gap Section
Active FVGs — total number of unmitigated fair value gaps currently displayed on the chart
FVG Split — the breakdown between active bullish and bearish FVGs. When bullish FVGs dominate, unmitigated demand imbalances outnumber supply imbalances — and vice versa.
Market Context Section
ATR — current ATR value and its percentage of price. Color-coded: green for low volatility, orange for moderate, red for elevated. High ATR readings mean liquidity zones will be wider and stops should be placed further from entry.
Normalized Volume — current volume expressed as a percentage of the maximum volume within the lookback window, labeled VERY HIGH / HIGH / NORMAL / LOW / VERY LOW. Elevated volume on a sweep candle significantly increases the probability of follow-through.
Price in Range — where the current close sits within the full liquidity range as a percentage, labeled as upper zone / mid-range / lower zone. This tells you at a glance whether price is approaching a range extreme (potential sweep target) or sitting in the middle of the distribution.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 How to Identify Trade Opportunities — Step by Step
Step 1 — Assess the Liquidity Landscape
Load the indicator and check the profile: are liquidity bins densely clustered in a narrow zone, or spread across a wide range?
Check the Liquidity Bias in the dashboard: does the map lean buy-side or sell-side?
Identify the POC line — this is the dominant reference level for the session
Step 2 — Identify High-Value Target Zones
Look for thick profile bars with high volume percentages — these are the zones that price is most likely to revisit for a sweep
Note any FVG boxes that overlap with high-volume bins — these dual-layer confluences are the strongest setups
Mark the POC: if price is approaching from below with buy-side bias, the POC is a likely magnet. If approaching from above with sell-side bias, the same applies.
Step 3 — Wait for a Sweep into a Liquidity Zone
Watch for price to push into a high-volume bin — especially below a cluster of buy pivots or above a cluster of sell pivots
A sweep label (⚡ SWEEP LOW or ⚡ SWEEP HIGH) confirms the stop-hunt pattern has occurred
The sweep candle will be highlighted in cyan (bull sweep) or orange (bear sweep) for instant identification
Step 4 — Confirm the Reversal
The most important confirmation is the close: the sweep candle must close back on the opposite side of the liquidity zone it spiked through
If price is also inside a FVG zone and closes back out of it, the reversal confluence is stronger
Elevated normalized volume on the sweep candle (VERY HIGH or HIGH) significantly increases the conviction of the setup
Step 5 — Enter and Manage
Enter in the direction of the sweep reversal — long after a bullish sweep, short after a bearish sweep
Place your stop loss below the sweep wick low (for longs) or above the sweep wick high (for shorts) — the stop hunt has already occurred, so price should not need to revisit that level
Target the POC level, the next high-volume bin on the profile, or the opposite side of an active FVG zone
If the Liquidity Bias matches your trade direction (e.g., BUY SIDE bias on a long trade), hold with greater conviction — the overall liquidity landscape supports continuation
Step 6 — When NOT to Trade
If the profile is extremely thin (very few active pivots), the liquidity landscape is unclear — wait for the profile to rebuild
If the ATR is very low (quiet, compressed market), FVGs and sweep signals may be less reliable — tighten the FVG minimum size filter
If price is in mid-range with BALANCED bias and no nearby FVGs, there is no clear structural edge — wait for price to approach a zone with confluence
Do not chase a sweep candle — the entry is on the confirmation close, not the spike
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙ Settings Reference
Core Settings
Lookback Bars — how many bars back the indicator scans for pivot extremes and builds the liquidity profile (default: 300). Increase for a broader, more historical view; decrease for a tighter, more immediate profile focused on the current session.
Profile Resolution — the number of price bins the range is divided into (default: 50). Higher values give finer granularity; lower values produce a smoother, broader profile. Recommended range: 30–70.
Volume Smoothing — the rolling sum window for volume normalization (default: 10). Higher values reduce the effect of individual volume spikes; lower values make the profile more reactive to each candle's volume.
ATR Length — the lookback period for the ATR calculation used to scale pivot offsets (default: 14). Match this to your typical ATR analysis setting.
Profile Display
Show Profile Bars — toggle the horizontal heatmap bars on/off
Show Volume % Labels — toggle volume figures and percentage labels inside and beside each bar
Show POC Line — toggle the full-width dashed POC level line and label
Show Liquidity Level Lines — toggle the dotted horizontal lines connecting each pivot's origin to the current bar
Split Buy / Sell Bars — splits each profile bar into its buy-side and sell-side volume components displayed side by side
Bar Offset from Price — controls the gap between the current bar and where the profile starts rendering (default: 20 bars). Increase if the profile overlaps with recent candles.
Max Bar Width — controls the maximum horizontal length of the widest profile bar in bars (default: 50). Adjust based on your chart's zoom level.
Fair Value Gaps
Show Fair Value Gaps — toggle the FVG overlay on/off
Min FVG Size (ATR mult) — minimum gap size as a multiple of ATR for a gap to qualify as a valid FVG (default: 0.1×). Increase to filter out minor imbalances; decrease to show all gaps.
Max FVGs to Display — maximum number of unmitigated FVGs shown simultaneously (default: 8). Oldest gaps are pruned first when the limit is reached.
Sweep Detection
Highlight Sweeps — toggle sweep labels and candle barcolor on/off
Sweep Lookback (bars) — the window used to define the recent high/low for sweep detection (default: 5). Lower values detect micro-sweeps on fast instruments; higher values detect only significant structural sweeps.
Colors
Buy Liquidity — color for buy-side profile bars and bullish FVGs (default: yellow-green #c8e624)
Sell Liquidity — color for sell-side profile bars and bearish FVGs (default: red #ff1744)
POC / Max Level — color for the Point of Control bar, POC line, and FVG background highlight (default: orange #ff9800)
Sweep Bull Label — color for bullish sweep labels and barcolor (default: cyan #00e5ff)
Sweep Bear Label — color for bearish sweep labels and barcolor (default: orange #ff9100)
Dashboard Background / Text / Neutral — dashboard theme colors
Dashboard
Show Dashboard — toggle the live context dashboard on/off
Position — choose Top Left, Top Right, Bottom Left, or Bottom Right
Text Size — Tiny, Small, or Normal
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔔 Alert Conditions
Bullish Liquidity Sweep — fires when a bullish sweep pattern is confirmed on bar close
Bearish Liquidity Sweep — fires when a bearish sweep pattern is confirmed on bar close
Any Liquidity Sweep — fires on either sweep direction — use for a single catch-all alert
Bullish FVG Created — fires when a new unmitigated bullish fair value gap forms
Bearish FVG Created — fires when a new unmitigated bearish fair value gap forms
Price Entered FVG — fires when the current close moves inside any active unmitigated FVG zone
All alert messages include {{ticker}} and {{interval}} placeholders for clean webhook and bot integration.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Key Features
🔬 Fully dynamic volume-weighted liquidity heatmap — rebuilds every bar, not a static historical snapshot
🗑 Auto-removal of swept/mitigated pivot levels — the profile always reflects only active, unvisited liquidity
📊 ATR-adaptive pivot offsets — automatically scales to the current volatility regime, no manual recalibration
🟡 Volume-gradient profile bars with buy/sell split mode — see the composition of every liquidity zone
◆ POC full-width level line with label — the dominant liquidity reference level clearly marked at all times
⚡ Fair Value Gap overlay with real-time mitigation tracking — only unmitigated imbalances remain visible
🌐 FVG background highlight — instant visual alert when price is sitting inside an active imbalance
🎯 Liquidity sweep detection with barcolor — cyan for bull sweeps, orange for bear sweeps
📋 Live dashboard — active pivots, buy/sell count, liquidity bias, sweep status, FVG split, ATR, normalized volume, and price-in-range percentage
🎨 Full AlphaX brand theme — yellow-green / red / orange / dark background, consistent with the AlphaX indicator suite
🔔 6 alert conditions — sweep entries and FVG events with clean ticker/interval message formatting
⚙ Fully configurable — all lookback windows, resolution, sensitivity, colors, and display toggles adjustable from the settings panel
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
👥 Who This Is For
🥇 Smart Money Concept (SMC) traders — the entire indicator is built around the core SMC concepts of liquidity pools, stop hunts, and fair value gaps. It automates the manual process of mapping where stops are likely clustered and where imbalances need to be filled.
📊 Order flow and volume profile traders — the dynamic heatmap provides a volume-at-price context that updates in real time, giving a live picture of the market's liquidity distribution.
⚡ Intraday scalpers and day traders — the sweep detection and FVG alerts fire on bar close, making them practical for fast timeframe traders on instruments like XAUUSD, indices, and forex majors.
🧠 Traders who struggle with entry timing — the sweep reversal pattern gives a precise, rules-based entry trigger rather than a subjective "it looks good" decision.
📈 Traders who want confluence, not single indicators — when a sweep, a high-volume bin, and a FVG all align at the same level, the three-layer confluence removes ambiguity and provides an objective framework for decision-making.
🎯 Traders building systematic approaches — all signals are rule-based, non-repainting, and confirmed on bar close. The dashboard provides quantitative context — not just visuals — for every condition the indicator monitors.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 Notes
All signals are non-repainting — every sweep label, FVG box, and profile bar is confirmed on bar close and does not move or disappear retroactively
The profile renders only at the last bar (barstate.islast) and redraws on each new bar — this is by design and standard practice for all right-side profile indicators. Historical profile positions are not stored.
On very low timeframes (sub-1-minute) or extended chart history windows, PulseWire's 500-box and 500-line limits apply — the indicator operates within these limits by design. Reducing the lookback or bins will always keep rendering within limits.
The ATR-adaptive offset means the indicator self-adjusts across different instruments and timeframes without requiring separate configurations for each. The same settings work on XAUUSD 1-minute and EURUSD 15-minute with no manual changes needed.
For best results, use in combination with AlphaX Vision (Fusion Trend Engine) — the Liquidity Matrix identifies where to enter within the zones that Vision's trend system defines as directionally favored.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Disclaimer
This indicator is a technical analysis and visualization tool intended for educational and informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any financial instrument. All signals are generated from historical and real-time price data using mathematical calculations — their accuracy or profitability is not guaranteed. Past performance of any signal type does not guarantee future results. Always conduct your own analysis, use proper risk management, and consult a licensed financial advisor before making any trading decisions. The author accepts no responsibility for any losses incurred from the use of this indicator.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built for traders who read the market at the level where institutions operate.
Indicator

Adaptive Linear Regression Structure [MarkitTick]💡 This indicator, is a sophisticated analytical tool designed to bridge the gap between classical statistical modeling and modern price action theory. By leveraging high-performance Ordinary Least Squares (OLS) calculations, it dynamically identifies the most statistically significant market structures—specifically linear regression channels—based on historical pivot points. Unlike static channels that rely on arbitrary lookback periods, this script scans a historical "horizon" of structural pivots to find the model with the highest mathematical "fit," providing traders with a non-repainting, objective view of trend exhaustion and volatility boundaries.
✨ Originality and Utility
● Dynamic Model Selection
Most linear regression indicators require the user to manually define a start and end point, or they use a fixed lookback period. This script is original because it treats the starting point of the regression as a variable. It scans multiple historical pivots (Highs and Lows) and performs a competitive analysis between different potential channels. The channel that is eventually displayed is the one that achieves the highest performance score, calculated via a combination of the Coefficient of Determination ($R^2$) and the natural log of the duration. This ensures the channel is both mathematically reliable and structurally relevant.
● Market Structure Integration
The utility of the indicator is enhanced by its "Market Structure Registry." Instead of calculating regressions on every single bar blindly, the script identifies "Pivot Highs" and "Pivot Lows" to use as anchors. This aligns the statistical modeling with the way professional traders view the market, focusing on major turning points rather than noise.
● Institutional-Grade Telemetry
The inclusion of a real-time HUD (Heads-Up Display) dashboard provides traders with immediate transparency into the model's health. By displaying the $R^2$ value and Z-Score, the indicator moves beyond simple "lines on a chart" and offers a quantitative assessment of how well the current price action respects the established trend.
🔬 Methodology and Concepts
● The OLS Kernel
At the heart of the script is a custom-built OLS (Ordinary Least Squares) method. It calculates the slope ($\beta$) and the intercept ($\alpha$) of the best-fit line through the closing prices of the selected period. The mathematical goal is to minimize the sum of the squared errors ( LSE:SSE $), ensuring the median line represents the "true" equilibrium of price over that duration.
● Heuristic Performance Scoring
The indicator does not just look for the highest correlation. It uses a "Performance Score" heuristic:
Score = $R^2$ * ln(Duration)
This formula rewards models that maintain a high degree of linearity over longer periods. A short-term channel with a high $R^2$ might be dismissed in favor of a long-term channel that has a slightly lower $R^2$ but significantly more structural weight.
● Volatility-Adjusted Envelopes
The upper and lower boundaries are not arbitrary. They are calculated based on the standard deviation of the residuals (the distance between actual price and the regression line). By applying a user-defined "Deviation Factor," the script creates volatility bands that expand or contract based on how "noisy" the trend is.
🎨 Visual Guide
● The Regression Channel
• Median Vector: A solid line representing the linear mean of the current trend. It is colored Cyan for bullish slopes and Orange for bearish slopes.
• Volatility Bands: Two solid lines flanking the median. These represent the "Deviation Factor" boundaries (defaulting to 2.0 standard deviations).
• Fill Core: A transparent background fill between the upper and lower bands, allowing for easy visualization of the "fair value" zone. The color dynamically shifts between Cyan and Orange based on the trend bias.
● Signal Labels
• LONG Labels: Cyan labels appearing below price when a "Mean Reversion" setup is detected (price crossing above the lower band).
• SHORT Labels: Orange labels appearing above price when a "Mean Reversion" setup is detected (price crossing below the upper band).
• Details: Labels include the Entry Price (EP), Take Profit (TP) at the median, and a suggested Stop Loss (SL).
● Telemetry Dashboard (HUD)
• Model Quality (R²): A value between 0.0 and 1.0. Values above 0.7 indicate a very strong trend.
• Trend Bias: Explicitly states "BULLISH" or "BEARISH."
• Deviation (Z-Score): Measures how many standard deviations the current price is away from the mean.
• Duration: Displays how many bars the current model covers.
📖 How to Use
● Mean Reversion Strategy
The primary use case is identifying overextended price action. When price moves outside the volatility bands (high Z-Score) and then crosses back inside, it suggests a return to the median "equilibrium" price.
• Bullish Entry: Look for a Cyan "LONG" label when price recovers from the lower band.
• Bearish Entry: Look for an Orange "SHORT" label when price pulls back from the upper band.
● Trend Strength Assessment
Use the $R^2$ value in the dashboard to filter trades. If the $R^2$ is low (e.g., below 0.5), the market is in a "Random Walk" phase, and the regression lines may be less reliable. High $R^2$ values suggest a "Trending" phase where the channel boundaries act as significant support and resistance.
● Dynamic Take Profits
The median line (the Cyan/Orange vector) serves as a dynamic take-profit target. Since the line is based on a linear slope, the price target adjusts every bar to reflect the ongoing trend.
⚙️ Inputs and Settings
● Algorithmic Core
• Scan Horizon: Determines how many historical pivots the script should evaluate. A higher number increases the "search depth" but requires more processing.
• Deviation Factor: Controls the width of the channel. A value of 2.0 covers approximately 95% of price action if the distribution is normal.
• Structural Sensitivity: Controls the lookback for the Pivot High/Low detection. Smaller values find more "local" structures; higher values find "major" structures.
● Signal Processing
• Quality Threshold (R²): This is a "gatekeeper" setting. If no model reaches this minimum quality, the indicator will not display a channel, protecting the user from weak or chaotic patterns.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
● Statistical Basis (OLS)
The indicator is grounded in the Gauss-Markov theorem. By calculating the slope via the covariance of time and price divided by the variance of time, it provides the "Best Linear Unbiased Estimator" (BLUE) of the current price trajectory.
● Information Theory & Heuristics
The scoring mechanism (using the natural log of N) draws inspiration from Information Criteria (like AIC or BIC). In statistical modeling, increasing the sample size ($N$) usually improves the model's reliability but can introduce "lag." By using the log of duration, the script balances the benefit of a larger sample size against the need for current relevance.
● Standardized Residuals (Z-Scores)
The "Z-Metric" displayed in the dashboard is a calculation of:
$Z = (Price - Estimated Price) / Standard Error$
This standardizes the distance of price from the mean across different assets and timeframes, allowing for a universal interpretation of "overbought" or "oversold" conditions based on the specific volatility of the current trend.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion. Indicator

Indicator

Indicator

DDCA Composite Risk Metric v0.1Dynamic Dollar-Cost Averaging signal — a single 0–1 risk oscillator for Bitcoin cycle positioning.
This indicator combines 19 cross-domain signals into one composite score that tells you when to accumulate and when to distribute. It was built to solve one problem: removing emotion from DCA sizing decisions.
0.0 = Maximum opportunity (buy aggressively)
1.0 = Maximum risk (sell everything)
How It Works
The composite blends four tiers of market data, each answering a different question:
Macro & Liquidity (35%) — "Is the environment creating cheap prices?" Fed rate direction, global M2 growth, Fed balance sheet, real yields, unemployment trend, DXY dollar strength. When macro is painful, assets are cheap.
On-Chain (30%) — "Is capitulation happening NOW?" MVRV Z-Score, NUPL, Puell Multiple, LTH netflow, hash ribbons. Measures actual blockchain behavior — smart money accumulation vs distribution.
Technical (25%) — "Does price structure confirm the bottom?" 200-week MA ratio, bull market support band, Pi Cycle top, BTC dominance, log regression band, stablecoin supply ratio.
Sentiment (10%) — "Is everyone terrified?" Fear & Greed proxy (momentum + volatility + price strength), altcoin breadth.
When all four tiers align near 0 simultaneously — that is the real buy signal. Any single tier at 0 alone just means "conditions are favorable, wait for confirmation."
Key Features
Adaptive normalization — Six indicators use rolling 4-year percentile ranking instead of fixed ranges. This solves the critical problem of cycle compression where metrics like MVRV peak at lower absolute values each cycle (10 → 7 → 3.5). The indicator stays equally sensitive whether it is 2017 or 2030.
Sigmoid rescaling — Prevents blow-off distortion. The 2021 peak where all 19 indicators maxed simultaneously is compressed naturally, keeping the actionable 0.2–0.8 range responsive.
Tier and individual toggles — Disable any tier or any single indicator with one click. Weights automatically renormalize. Build your own blend.
Na-safe architecture — If any data source goes offline, that indicator defaults to neutral 0.5 instead of breaking the entire composite. The chart never goes blank.
DDCA Action Bands
< 0.10 — ALL-IN zone (generational bottom)
0.10 – 0.20 — Heavy buy
0.20 – 0.28 — Strong buy
0.28 – 0.35 — Normal buy (standard DCA)
0.35 – 0.75 — HOLD (no action)
0.75 – 0.82 — Start selling
0.82 – 0.90 — Accelerate selling
> 0.90 — SELL ALL (cycle top)
Settings
Composite SMA smoothing — default 7 bars. Increase for less noise, decrease for faster signals.
Sigmoid center — default 0.42. The raw score that maps to 0.50 output.
Sigmoid steepness — default 8.0. Higher = sharper transition between zones. Lower = more gradual.
Show sub-scores — toggle to see individual tier lines for debugging.
Score table — real-time breakdown of all 19 indicators with traffic-light coloring.
Data Sources
22 request.security() calls: FRED (rates, M2, balance sheet, yields, unemployment), TVC (DXY, bonds), Glassnode & CoinMetrics (market cap, realized cap), IntoTheBlock (hashrate, netflow), Quandl (miner revenue), CryptoCap (dominance, total market cap, stablecoins).
No external API dependencies. Everything runs natively in PulseWire.
Based on
Research framework derived from Benjamin Cowen's risk metric methodology and multi-factor cycle analysis. The macro inversion logic follows the principle that tight monetary conditions create cheap assets — the environment where long-term DCA yields the best results.
"Be fearful when others are greedy, and greedy when others are fearful." This indicator quantifies exactly how fearful or greedy the market is across 19 dimensions.
Alerts included for all action band crossings: ALL-IN, HEAVY BUY, STRONG BUY, NORMAL BUY, START SELL, ACCEL SELL, SELL ALL. Indicator

Dynamic Delta FVG [LuxAlgo]The Dynamic Delta FVG indicator provides a comprehensive analysis of Fair Value Gaps (FVGs) by integrating intra-bar volume delta to visualize the internal buying and selling pressure within price imbalances.
🔶 USAGE
The script identifies standard Fair Value Gaps and enhances them by splitting the visual representation into two distinct segments based on volume delta. This allows traders to see exactly where institutional aggressive orders were concentrated during the formation of the gap.
Users can utilize this tool to:
Identify high-probability FVGs where the volume delta aligns with the gap direction. Determine specific price levels within a gap that acted as the primary "point of control" for buyers or sellers. Monitor real-time sentiment through a dynamic dashboard that aggregates the delta of all active imbalances. Filter out insignificant market noise using ATR and volume-based threshold settings.
🔹 Detailed Buyer/Seller Tags
Each active FVG features a dynamic tag on the right edge displaying the specific percentage of buying (B) and selling (S) volume that occurred within that price range. The tag background color shifts based on the dominant force, providing an immediate visual cue of the gap's internal strength. These tags move dynamically as the boxes expand, ensuring they always remain at the current price action edge.
🔹 Filter Overlapping
When enabled, the script will automatically remove existing active FVGs that overlap with a new discovery. This ensures only the most recent "current" imbalance is displayed in a specific price zone, preventing visual clutter and focusing on the most relevant institutional levels.
🔹 Mitigation Modes
The script supports two mitigation modes to suit different trading styles:
**Touch:** A gap is considered mitigated as soon as price enters the range. **Full Fill:** A gap remains active until price has completely traversed the entire range of the imbalance.
🔶 DETAILS
The indicator utilizes
request.security_lower_tf()
to fetch granular volume data from lower timeframes (e.g., 1-second data). This allows for a precise calculation of "Buy Volume" versus "Sell Volume". The split in the FVG box represents the ratio of these volumes. For example, if an FVG has 70% buying volume, the green segment will occupy 70% of the vertical height of the box, while the red segment occupies the remaining 30%.
🔹 Aggregate Sentiment Dashboard
The dashboard calculates market strength across all active imbalances rather than just categorizing by gap direction. This means if multiple bullish FVGs contain significant "absorbed" selling volume, the "Seller Strength" metric will accurately reflect this bearish pressure. The Net Sentiment is derived from the net difference between aggregate buyer and seller percentages across all active gaps.
🔶 SETTINGS
🔹 Detection Filters
**Min Volume Threshold:** Multiplier for the 20-period average volume. Gaps forming on volume lower than this threshold are ignored. **Min ATR Magnitude:** Sets the minimum required size of the FVG relative to the current ATR. **Mitigation Mode:** Determines whether a touch or a full fill "closes" the gap. **Filter Overlapping:** When enabled, the script deletes older active gaps that overlap with new ones.
🔹 Volume Delta Analysis
**Delta Timeframe:** The lower timeframe used for volume calculations. Required for higher precision on 1m charts.
🔹 Visuals
**Max Active Gaps:** Limits the number of boxes displayed on the chart (Default: 10). **Buyer/Seller Color:** Customizable colors for the split segments within the FVG. **Show Mitigated Gaps:** When enabled, mitigated gaps remain on the chart with a faded appearance.
🔹 Dashboard
**Show Dashboard:** Toggles the real-time sentiment and imbalance summary table. **Position/Size:** Controls the UI placement and scale of the dashboard. Indicator

5m ORB with Dynamic Position Size and TargetThis script is based off of the 5 minute high and low (opening range) of the NY session, specifically developed for ES/MES. It marks the high and low of the first five minutes of trading, as well as marks profit targets if price breaks out high or low.
In settings you can configure the maximum capital to risk, high volatility target and regular volatility, and the ORB size in points that indicates if it is a high or normal volatility regime. I use a maximum risk of $500, normal volatility target of 1.5 RR, and a high volatility target of 1.0 RR. The maximum ORB range that I assume is normal volatility is 20 points, so below 20 points it targets 1.5 RR, above it targets 1.0 RR.
For illustrative purposes, I will outline my current strategy below. This is not financial advice, obviously.
When price breaks out of the 5 minute opening range, I enter in the direction of the move (break out of the high, I enter long; break down from low, I enter short). Stop loss is set at one tick outside of the opposite end of the range. I currently exit the full position at the target price, but will be playing around with leaving a runner for trend days.
Again, not financial advice. Be sure to paper trade before committing any real funds. Indicator

Orderflow GapThis is the **Orderflow Gap (OG)** analyzer.
It goes beyond standard price gap detection by integrating
**Market Structure (Dow/SMC)** and **Intra-Bar Orderflow**
to classify the quality and intent behind price discontinuities.
Key Features:
1. **Advanced Gap Detection & Lifecycle:**
- **Flexible Definition:** Users can define gaps based on
market psychology:
- **Body (Open-Close):** Focuses on the "True Gap" between
sessions or candles, ignoring wicks.
- **Full (High-Low):** Focuses on total price dislocation
where no trading occurred at all.
- **Lifecycle Tracking:** The indicator persistently tracks
open gaps and visually marks them as **Filled** once price
mitigates the area by a user-defined percentage.
2. **Intra-Bar Orderflow Profiling (Pre & Post Analysis):**
- **Context:** Standard tools treat a gap merely as empty price space.
This indicator analyzes the **Micro-Auction** immediately surrounding
the event to understand the mechanics of the move.
- **Reconstruction:** Using high-resolution lower timeframe data, it
builds detailed Volume Profiles for the **Pre-Gap Candle** (The Origin)
and the **Post-Gap Candle** (The Reaction).
- **Flow Validation:** This allows the user to verify **Orderflow Continuity**:
Does the aggressive buying/selling that caused the gap continue
immediately after, or is the move fading into absorption?
3. **Statistical Volume Profile Engine:** For each bar in the anchored
period, the indicator builds a complete volume profile on a lower
'Intra-Bar Timeframe'. Instead of simple tick counting, it uses
**statistical models ('PDF' allocation)** to distribute volume
across price levels and **advanced classifiers ('Dynamic' split)**
to determine the buy/sell pressure within that profile.
4. **Structural & Volumetric Context:**
- **Vacuum (Density):** Calculates the "Volume Density" per
tick. A low density indicates a **Liquidity Vacuum** (price
slipped due to lack of orders), while high density indicates
aggressive fighting.
- **Commitment:** Compares the volume surrounding the gap
to the historical average to determine if big players
are backing the move.
- **Trend Alignment:** Filters signals based on the underlying
trend using either **Dow Theory** or **Smart Money Concepts**.
5. **Gap Classification Engine:**
The indicator automatically classifies gaps into four
structural types based on the metrics above:
- **Breakaway:** A high-conviction move that breaks structure,
showing **Initiative** (breaking previous Value Area) and
**Commitment** (High Volume).
- **Runaway:** A continuation gap within an established trend,
aligned with the Orderflow Delta.
- **Exhaustion:** A gap that occurs late in a trend, often
characterized by a **Liquidity Vacuum** (low density) despite
high volume, signaling potential reversal.
- **Common:** Standard volatility gaps lacking significant structural
or volumetric backing.
**Volume Fallback:** If no volume data is provided by the
exchange (e.g., certain CFDs or Indices), the classification
logic automatically defaults to **Common** to ensure strict
signal integrity without Orderflow verification.
6. **Visual Orderflow Insight:**
- **Profile Visualization:** Plots the reconstructed volume
profile as a polyline directly adjacent to the gap, allowing
you to see the "Injection" of volume that caused the move.
- **Color Coding:** Gaps are color-coded based on their
classification (Breakaway/Runaway/Exhaustion) and direction
(Bullish/Bearish).
7. **Multi-Metric Profiling (Volume, Time, Velocity):** Unlike standard
tools, this indicator allows you to switch between three critical
dimensions of market activity:
- **VOLUME (The "Where"):** Shows standard acceptance levels.
- **TIME (The "How Long"):** Measures duration at price (similar to TPO),
indicating fair value (High Time) or rejection (Low Time).
- **VELOCITY (The "How Fast"):** Measures the speed of trading (Contracts
per Second) to reveal intent. **High Velocity** suggests aggression
(initiative buying/selling), while **Low Velocity** despite volume
indicates absorption (passive limit orders).
8. **Integrated Alerts:** Includes granular alerts for:
- Detection of specific gap types (e.g., "Bullish Breakaway Gap").
- General gap formation.
**Caution: Real-Time Data Behavior (Intra-Bar Repainting)**
This indicator uses high-resolution intra-bar data. As a result, the
values on the **current, unclosed bar** (the real-time bar) will
update dynamically as new intra-bar data arrives. This includes
the values used for real-time alerts in 'Structure' and
'Delta' modes.
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration. Indicator

Dynamic ATR-based Renko Overlay - Non repaintingDaily ATR-Based Renko Overlay
Overview
This Pine Script v5 indicator creates a dynamic Renko overlay on your time-based charts (optimized for 1-minute timeframes), using the previous period's ATR from a user-specified higher timeframe (default: 1-hour) to determine brick sizes. Unlike traditional Renko charts, this is an overlay that draws Renko bricks directly on top of your existing candles, allowing you to combine the noise-filtering power of Renko with the full features of time-based charts.
It's designed for traders who want Renko's trend-clarity benefits without switching chart types, especially useful for intraday trading in volatile markets like forex, stocks, or crypto.
Key Features
- Adaptive Brick Sizing: Brick size is calculated as a percentage (default 40%) of the previous period's ATR (Average True Range, default length 14) from the selected higher timeframe (default: 1-hour). This makes bricks volatility-adjusted—larger in high-vol periods to reduce noise, smaller in low-vol for more detail.
- Periodic Recalculation: Resets brick size at the start of each new period based on the user-specified reset timeframe (default: daily), using the prior period's ATR from the chosen timeframe. This ensures relevance without unwanted disruptions.
- Traditional Renko Logic: Uses 1-box reversal (a full brick against the trend to reverse). Bricks form based on closing prices, ignoring time and minor fluctuations.
- Visual Style: Stepped lines with green (up) and red (down) fills for a box-like appearance. Semi-transparent for easy overlay on candles.
- Customizable Inputs:
- ATR Length: Adjust the ATR period (default: 14).
- Percentage of ATR: Fine-tune brick sensitivity (default: 0.4 or 40%; range 0-1).
- ATR Timeframe: Specify the timeframe for ATR calculation (default: "60" for 1-hour; enter as a string like "240" for 4-hour, "D" for daily, etc.).
- Reset Timeframe: Specify the period for recalculating the brick size (default: "D" for daily; enter as a string like "W" for weekly, "M" for monthly, etc.).
How It Works
1. Fetches ATR from the user-specified timeframe via `request.security` for higher-timeframe volatility data.
2. On new periods based on the reset timeframe (or first load), sets brick size to `percent * ATR_HTF`.
3. Tracks Renko "close" and "previous close" to calculate bricks:
- Upward moves add green bricks in multiples of the size.
- Downward moves add red bricks.
- Reversals require a full brick against the direction.
4. Plots and fills create the overlay, updating on each 1-min bar close.
Add it to a 1-minute chart for best results—bricks will adapt periodically while you retain full candle visibility.
Why This Indicator is Helpful
PulseWire's native Renko charts are powerful but come with limitations that can frustrate serious traders:
- No Bar Replay: Native Renko doesn't support PulseWire's bar replay feature, making it hard to simulate historical trading sessions.
- Inaccurate/Repainting Strategy Testing: Strategies on native Renko can repaint or lack precision due to the non-time-based nature, leading to unreliable backtests.
- Limited Data History: Fast Renko timeframes (e.g., small bricks) often load very little historical data, restricting long-term analysis.
This overlay solves these by building Renko on a time-based chart:
- Full Bar Replay Support: Replay sessions as usual on your 1-min chart—the Renko follows along.
- Accurate, Non-Repainting Testing: Test strategies on the underlying time chart without repainting issues, as Renko is derived from closes.
- Unlimited Data Depth: Access PulseWire's full historical data for 1-min charts (up to years of bars), not limited by Renko's data constraints.
- Hybrid Analysis: Overlay Renko on candles to spot trends while using volume, indicators (e.g., RSI, MAs), or drawing tools that don't work well on native Renko.
It's a game-changer for trend-following, breakout strategies, or filtering noise in short-term trades. No more switching charts—get the best of both worlds!
Usage Tips
- Best on 1-min charts for intraday precision, but experiment with others.
- Tune the percentage lower (e.g., 0.3) for more bricks/sensitivity, higher (e.g., 0.5) for fewer/false-signal reduction.
- Adjust the ATR timeframe to match your strategy—e.g., "240" for longer-term volatility or "15" for shorter.
- Customize the reset timeframe for different recalculation frequencies—e.g., "W" for weekly resets to capture broader market shifts, or "240" for every 4 hours.
- Combine with alerts: right now I am experimenting with 90 period EMA and the Renko brick pullbacks to find some EDGE
If you find this useful, give it a thumbs up or share your tweaks in the comments. Feedback welcome—happy trading! 🚀 Indicator

Indicator

Market Structure Volume Time Velocity ProfileThis is the Market Structure Volume Time Velocity Profile (MSVTVP). It combines event-based profiling with advanced metrics like Time and Velocity (Flow Rate). Instead of fixed time periods, profiles are anchored to critical market events (Swings, Structure Breaks, Delta Breaks), giving you a precise view of value development during specific market phases.
## The 3 Dimensions of the Market
Unlike standard tools that only show Volume, MSVTVP allows you
to switch between three critical metrics:
1. **VOLUME Profile (The "Where"):**
* Shows standard acceptance. High volume nodes (HVN)
are magnets for price.
2. **TIME Profile (The "How Long"):**
* Similar to TPO, it measures how long price spent at each
level.
* **High Time:** True acceptance and fair value.
* **Low Time:** Rejection or rapid movement.
3. **VELOCITY Profile (The "How Fast"):**
* Measures the **speed of trading** (Contracts per Second).
This reveals the hidden intent of market participants.
* **High Velocity (Fast Flow):** Aggression. Initiative
buyers/sellers are hitting market orders rapidly. Often
seen at breakouts or in liquidity vacu.
* **Low Velocity (Slow Flow):** Absorption. Massive passive
limit orders are slowing price down despite high volume.
Often seen at major reversals ("hitting a brick wall").
Key Features:
1. **Event-Based Profile Anchoring:** The indicator starts a new
profile based on one of three user-selected events
('Profile Anchor'):
- **Swing:** A new profile begins when the 'impulse baseline'
(derived from intra-bar delta) changes. This baseline
adjusts when a new **price pivot** is confirmed: When a
price **high** forms, the baseline moves to the **lower**
of its previous level or the peak delta (max of
delta O/C) at the pivot. When a price **low** forms, it
moves to the **higher** of its previous level or the
trough delta (min of delta O/C) at the pivot.
- **Structure:** A new profile begins immediately on the bar
that *confirms* a market structure break (e.g., a new HH
or LL, based on a sequence of price pivots).
- **Delta:** A new profile begins immediately on the bar
that *confirms* a break in the *cumulative delta's*
market structure (e.g., a new HH or LL in the delta).
Both 'Swing' and 'Delta' anchors are derived from the same
**continuous (non-resetting) Cumulative Volume Profile Delta (CVPD)**,
which is built from the intra-bar statistical analysis.
2. **Statistical Profile Engine:** For each bar in the anchored
period, the indicator builds a volume profile on a lower
'Intra-Bar Timeframe'. Instead of simple tick counting, it
uses advanced statistical models:
- **Allocation ('Allot model'):** 'PDF' (Probability Density
Function) distributes volume proportionally across the
bar's range based on an assumed statistical model
(e.g., T4-Skew). 'Classic' assigns all volume to
the close.
- **Buy/Sell Split ('Volume Estimator'):** 'Dynamic'
applies a model that analyzes candle wicks and
recent trend to estimate buy/sell pressure. 'Classic'
classifies all volume based on the candle color.
3. **Visualization & Lag:** The indicator plots the final
profile (as a polygon) and the developing statistical
lines (POC, VA, VWAP, StdDev).
- **Note on Lag:** All anchor events require `Pivot Right Bars`
for confirmation.
- In 'Structure' and 'Delta' mode, the developing lines
(POC, VA, etc.) are plotted using a **non-repainting**
method (showing the value from `pivRi` bars ago).
- In 'Swing' mode, the profile is plotted **retroactively**,
starting *from the bar where the pivot occurred*. The
developing lines are also plotted with this full
`pivRi` lag to align with the past data.
4. **Flexible Display Modes:** The finalized profile can be displayed
in three ways: 'Up/Down' (buy vs. sell), 'Total' (combined
volume), and 'Delta' (net difference).
5. **Dynamic Row Sizing:** Includes an option ('Rows per Percent')
to automatically adjust the number of profile rows (buckets)
based on the profile's price range.
6. **Integrated Alerts:** Includes 13 alerts that trigger for:
- A new profile reset ('Profile was resetted').
- Price crossing any of the 6 developing levels (POC,
VA High/Low, VWAP, StdDev High/Low).
- **Alert Lag Assumption:** In 'Swing' mode, alerts are
delayed to match the retroactively plotted lines.
In 'Structure' and 'Delta' modes, alerts fire in
**real-time** based on the *current price* crossing
the *current (repainting)* value of the metric, which
may **differ from the non-repainting plotted line.**
**Caution: Real-Time Data Behavior (Intra-Bar Repainting)**
This indicator uses high-resolution intra-bar data. As a result, the
values on the **current, unclosed bar** (the real-time bar) will
update dynamically as new intra-bar data arrives. This includes
the values used for real-time alerts in 'Structure' and
'Delta' modes.
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration. Indicator

Periodic Volume Time Velocity ProfileThis is the Periodic Volume Time Velocity Profile (PVTVP). It is an advanced professional profiling tool that goes beyond standard volume analysis by introducing Time and Velocity (Flow Rate) as profile dimensions.
By analyzing high-resolution intra-bar data, it builds
precise profiles for any custom period (Session, Day, Week, etc.),
helping you understand not just *where* the market traded,
but *how* it traded there.
## The 3 Dimensions of the Market
Unlike standard tools that only show Volume, PVTVP allows you
to switch between three critical metrics:
1. **VOLUME Profile (The "Where"):**
* Shows standard acceptance. High volume nodes (HVN)
are magnets for price.
2. **TIME Profile (The "How Long"):**
* Similar to TPO, it measures how long price spent at each
level.
* **High Time:** True acceptance and fair value.
* **Low Time:** Rejection or rapid movement.
3. **VELOCITY Profile (The "How Fast"):**
* Measures the **speed of trading** (Contracts per Second).
This reveals the hidden intent of market participants.
* **High Velocity (Fast Flow):** Aggression. Initiative
buyers/sellers are hitting market orders rapidly. Often
seen at breakouts or in liquidity vacuums.
* **Low Velocity (Slow Flow):** Absorption. Massive passive
limit orders are slowing price down despite high volume.
Often seen at major reversals ("hitting a brick wall").
## Key Features
1. **Statistical Volume Profile Engine:** For each bar in the selected
period, the indicator builds a complete volume profile on a lower
'Intra-Bar Timeframe'. Instead of simple tick counting, it uses
**statistical models ('PDF' allocation)** to distribute volume
across price levels and **advanced classifiers ('Dynamic' split)**
to determine the buy/sell pressure within that profile.
2. **Flexible Profile Display:** The **finalized profile** (plotted at
the end of each period) can be visualized in three distinct
ways: 'Up/Down' (buy vs. sell), 'Total' (combined volume),
and 'Delta' (net difference).
3. **Developing Key Levels:** The indicator also plots the developing
Point of Control (POC), Value Area (VA), VWAP, and Standard
Deviation bands in real-time as the period unfolds, providing
live insights into the emerging market structure.
4. **Dynamic Row Sizing:** Includes an option ('Rows per Percent')
to automatically adjust the number of profile rows (buckets)
based on the profile's price range, maintaining a consistent
visual density.
5. **Integrated Alerts:** Includes 12 alerts that trigger when the
main price crosses over or under the key developing levels:
POC, VWAP, Value Area High/Low, and the +/- Standard
Deviation bands.
**Caution: Real-Time Data Behavior (Intra-Bar Repainting)**
This indicator uses high-resolution intra-bar data. As a result, the
values on the **current, unclosed bar** (the real-time bar) will
update dynamically as new intra-bar data arrives. This behavior is
normal and necessary for this type of analysis. Signals should only
be considered final **after the main chart bar has closed.**
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration. Indicator

Volatility-Targeted Momentum Portfolio [BackQuant]Volatility-Targeted Momentum Portfolio
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
What the script does at a glance
Momentum, what it is, how to know if it is present
Volatility targeting, why and how it is done here
Portfolio construction modes: Long Only, Short Only, Delta Neutral
Regime filter and when the strategy goes to cash
Transaction cost modelling in this script
Backtest metrics and definitions
Performance attribution chart
Monte Carlo simulation
Scatter plot analysis modes
Asset allocation pie chart
Inputs, presets, and deployment checklist
Suggested workflow
1) What the script does at a glance
Pulls a list of up to 15 tickers, computes a simple momentum score on each over a configurable lookback, then volatility-scales their bar-to-bar return stream to a target annualized volatility.
Ranks assets by raw momentum, selects the top 3 and bottom 3, builds positions according to the chosen mode, and gates exposure with a fast regime filter.
Accumulates a portfolio equity curve with risk and performance metrics, optional benchmark buy-and-hold for comparison, and a full alert suite.
Adds visual diagnostics: performance attribution bars, Monte Carlo forward paths, an allocation pie, and scatter plots for risk-return and factor views.
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices . Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present .
Leaders and laggards persist across adjacent windows rather than flipping every bar.
Spread between average momentum of leaders and laggards is materially positive in sample.
Cross-sectional dispersion is non-trivial. If everything is flat or highly correlated with no separation, momentum selection will be weak.
Your validation should include a diagnostic that measures whether returns are explained by a momentum regression on the timeseries.
Recommended diagnostic tool . Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check: It fits a regression to price, exposes slope and goodness-of-fit style context, and helps confirm if there is usable momentum before you force a ranking into a flat regime.
3) Volatility targeting: purpose and implementation here
Purpose . Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
Return series ret = log(price/price ).
Annualized volatility estimate vol = stdev(ret, lookback) * sqrt(tradingdays).
Leverage multiplier volMult = clamp(targetVol / vol, 0.1, 5.0).
This caps sizing so extremely low-vol assets don’t explode weight and extremely high-vol assets don’t go to zero.
Scaled return stream sr = ret * volMult. This is the per-bar, risk-adjusted building block used in the portfolio combinations.
Interpretation . You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking . Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
Long Only . Averages the volatility-scaled returns of the top 3 assets: avgRet = mean(sr_top1, sr_top2, sr_top3). Position table shows per-asset leverages and weights proportional to their current volMult.
Short Only . Averages the negative of the volatility-scaled returns of the bottom 3: avgRet = mean(-sr_bot1, -sr_bot2, -sr_bot3). Position table shows short legs.
Delta Neutral . Long the top 3 and short the bottom 3 in equal book sizes. Each side is sized to 50 percent notional internally, with weights within each side proportional to volMult. The return stream mixes the two sides: avgRet = mean(sr_top1,sr_top2,sr_top3, -sr_bot1,-sr_bot2,-sr_bot3).
Notes .
The selection metric is raw momentum, the execution stream is volatility-scaled returns. This separation is deliberate. It avoids letting volatility dominate ranking while still enforcing risk parity at the return contribution stage.
If everything rallies together and dispersion collapses, Long Only may behave like a single beta. Delta Neutral is designed to extract cross-sectional momentum with low net beta.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
Long Only active when EMA12 > EMA21. Otherwise the book is set to cash.
Short Only active when EMA12 < EMA21. Otherwise cash.
Delta Neutral is always active.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
Per-bar drag . When the regime filter is active, the per-bar return is reduced by fee_rate * avgRet inside netRet = avgRet - (fee_rate * avgRet). This models proportional friction relative to traded impact on that bar.
Turnover-linked fee . The script tracks changes in membership of the top and bottom baskets (top1..top3, bot1..bot3). The intent is to charge fees when composition changes. The template counts changes and scales a fee by change count divided by 6 for the six slots.
Use case: increase fee_rate to reflect taker fees and slippage if you rebalance every bar or trade illiquid assets. Reduce it if you rebalance less often or use maker orders.
Practical advice .
If you rebalance daily, start with 5–20 bps round-trip per switch on liquid futures and adjust per venue.
For crypto perp microcaps, stress higher cost assumptions and add slippage buffers.
If you only rotate on lookback boundaries or at signals, use alert-driven rebalances and lower per-bar drag.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
Net Profit percent over the full test.
Max Drawdown percent, tracked from running peaks.
Annualized Mean and Stdev using the chosen trading day count.
Variance is the square of annualized stdev.
Sharpe uses daily mean adjusted by risk-free rate and annualized.
Sortino uses downside stdev only.
Omega ratio of sum of gains to sum of losses.
Gain-to-Pain total gains divided by total losses absolute.
CAGR compounded annual growth from start date to now.
Alpha, Beta versus a user-selected benchmark. Beta from covariance of daily returns, Alpha from CAPM.
Skewness of daily returns.
VaR 95 linear-interpolated 5th percentile of daily returns.
CVaR average of the worst 5 percent of daily returns.
Benchmark Buy-and-Hold equity path for comparison.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.
9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.
Normal uses Box-Muller with your seed. Good for quick, smooth envelopes.
Bootstrap resamples realized returns, preserving fat tails and volatility clustering better than a Gaussian assumption.
Bands show 10th, 25th, 75th, 90th percentiles and the path mean.
10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.
Risk-Return Efficiency . X is risk proxy from leverage, Y is expected return from annualized momentum. The star shows the current book’s composite.
Momentum vs Volatility . Visualizes whether leaders are also high vol, a cue for turnover and cost expectations.
Beta vs Alpha . X is a beta proxy, Y is risk-adjusted excess return proxy. Useful to see if leaders are just beta.
Leverage vs Momentum . X is volMult, Y is momentum. Shows how volatility targeting is redistributing risk.
11) Asset allocation pie chart
Builds a wheel of current allocations.
Long Only, weights are proportional to each long asset’s current volMult and sum to 100 percent.
Short Only, weights show the short book as positive slices that sum to 100 percent.
Delta Neutral, 50 percent long and 50 percent short books, each side leverage-proportional.
Labels can show asset, percent, and current leverage.
12) Inputs and quick presets
Core
Portfolio Strategy . Long Only, Short Only, Delta Neutral.
Initial Capital . For equity scaling in the panel.
Trading Days/Year . 252 for stocks, 365 for crypto.
Target Volatility . Annualized, drives volMult.
Transaction Fees . Per-bar drag and composition change penalty, see the modelling notes above.
Momentum Lookback . Ranking horizon. Shorter is more reactive, longer is steadier.
Start Date . Ensure every symbol has data back to this date to avoid bias.
Benchmark . Used for alpha, beta, and B&H line.
Diagnostics
Metrics, Equity, B&H, Curve labels, Daily return line, Rolling drawdown fill.
Attribution panel. Toggle winners only to focus on what matters.
Monte Carlo mode with Normal or Bootstrap and confidence bands.
Scatter plot type and styling, labels, and portfolio star.
Pie chart and labels for current allocation.
Presets
Crypto Daily, Long Only . Lookback 25, Target Vol 50 percent, Fees 10 bps, Regime filter on, Metrics and Drawdown on. Monte Carlo Bootstrap with Recent 200 bars for bands.
Crypto Daily, Delta Neutral . Lookback 25, Target Vol 50 percent, Fees 15–25 bps, Regime filter always active for this mode. Use Scatter Risk-Return to monitor efficiency and keep the star near upper left quadrants without drifting rightward.
Equities Daily, Long Only . Lookback 60–120, Target Vol 15–20 percent, Fees 5–10 bps, Regime filter on. Use Benchmark SPX and watch Alpha and Beta to keep the book from becoming index beta.
13) Suggested workflow
Universe sanity check . Pick liquid tickers with stable data. Thin assets distort vol estimates and fees.
Check momentum existence . Run on your timeframe. If slope and fit are weak, widen lookback or avoid that asset or timeframe.
Set risk budget . Choose a target volatility that matches your drawdown tolerance. Higher target increases turnover and cost sensitivity.
Pick mode . Long Only for bull regimes, Short Only for sustained downtrends, Delta Neutral for cross-sectional harvesting when index direction is unclear.
Tune lookback . If leaders rotate too often, lengthen it. If entries lag, shorten it.
Validate cost assumptions . Increase fee_rate and stress Monte Carlo. If the edge vanishes with modest friction, refine selection or lengthen rebalance cadence.
Run attribution . Confirm the strategy’s winners align with intuition and not one unstable outlier.
Use alerts . Enable position change, drawdown, volatility breach, regime, momentum shift, and crash alerts to supervise live runs.
Important implementation details mapped to code
Momentum measure . cr = price / price - 1 per symbol for ranking. Simplicity helps avoid overfitting.
Volatility targeting . vol = stdev(log returns, lookback) * sqrt(tradingdays), volMult = clamp(targetVol / vol, 0.1, 5), sr = ret * volMult.
Selection . Extract indices for top1..top3 and bot1..bot3. The arrays rets, scRets, lev_vals, and ticks_arr track momentum, scaled returns, leverage multipliers, and display tickers respectively.
Regime filter . EMA12 vs EMA21 switch determines if the strategy takes risk for Long or Short modes. Delta Neutral ignores the gate.
Equity update . Equity multiplies by 1 + netRet only when the regime was active in the prior bar. Buy-and-hold benchmark is computed separately for comparison.
Tables . Position tables show current top or bottom assets with leverage and weights. Metric table prints all risk and performance figures.
Visualization panels . Attribution, Monte Carlo, scatter, and pie use the last bars to draw overlays that update as the backtest proceeds.
Final notes
Momentum is a portfolio effect. The edge comes from cross-sectional dispersion, adequate risk normalization, and disciplined turnover control, not from a single best asset call.
Volatility targeting stabilizes path but does not fix selection. Use the momentum regression link above to confirm structure exists before you size into it.
Always test higher lag costs and slippage, then recheck metrics, attribution, and Monte Carlo envelopes. If the edge persists under stress, you have something robust.
Indicator

Intra Bar Volume ProfileThis indicator provides a high-resolution volume profile analysis for every single bar on the chart. It builds this profile by sampling data from a lower intra-bar timeframe, allowing for a granular view of price distribution and buying/selling pressure within the bar.
Key Features:
Intra-Bar Profile Engine: For each bar on the main chart, the indicator builds a complete volume profile on a lower 'Intra-Bar Timeframe'. It uses:
Statistical Models ('Allot model'): Distributes volume across price levels using 'PDF' (Probability Density Function) or 'Classic' (close) methods.
Buy/Sell Classifiers ('Volume Estimator'): Splits volume using a 'Dynamic' (trend/wick-based) or 'Classic' (candle color) model.
On-Chart Visualization (Overlay): The analysis is rendered directly onto the price bars:
Point of Control (POC): A line showing the price level with the most volume for that bar.
Value Area (VA): A colored box representing the price range where the specified percentage (e..g., 50%) of volume was traded.
VWAP: Displays the volume-weighted average price (VWAP) for the bar as a separate line.
Integrated Alerts: Includes 8 alerts that trigger when the main price crosses over or under the key intra-bar levels: POC, VWAP, and the Value Area High/Low.
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This behavior is normal and necessary for this type of analysis. Signals should only be considered final after the main chart bar has closed.
DISCLAIMM
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration. Indicator

Market Structure Volume ProfileThis indicator visualizes volume profiles that are dynamically anchored to market structure events, rather than fixed time intervals. It builds these profiles using high-resolution intra-bar data to provide a precise view of where value is established during critical market phases.
Key Features:
Event-Based Profile Anchoring: The indicator starts a new profile based on one of three user-selected events ('Profile Anchor'):
Swing: A new profile begins when the 'impulse baseline' (derived from intra-bar delta) changes. This baseline adjusts when a new price pivot is confirmed: When a price high forms, the baseline moves to the lower of its previous level or the peak delta (max of delta O/C) at the pivot. When a price low forms, it moves to the higher of its previous level or the trough delta (min of delta O/C) at the pivot.
Structure: A new profile begins immediately on the bar that confirms a market structure break (e.g., a new HH or LL, based on a sequence of price pivots).
Delta: A new profile begins immediately on the bar that confirms a break in the cumulative delta's market structure (e.g., a new HH or LL in the delta). Both 'Swing' and 'Delta' anchors are derived from the same continuous (non-resetting) Cumulative Volume Profile Delta (CVPD), which is built from the intra-bar statistical analysis.
Statistical Profile Engine: For each bar in the anchored period, the indicator builds a volume profile on a lower 'Intra-Bar Timeframe'. Instead of simple tick counting, it uses advanced statistical models:
Allocation ('Allot model'): 'PDF' (Probability Density Function) distributes volume proportionally across the bar's range based on an assumed statistical model (e.g., T4-Skew). 'Classic' assigns all volume to the close.
Buy/Sell Split ('Volume Estimator'): 'Dynamic' applies a model that analyzes candle wicks and recent trend to estimate buy/sell pressure. 'Classic' classifies all volume based on the candle color.
Visualization & Lag: The indicator plots the final profile (as a polygon) and the developing statistical lines (POC, VA, VWAP, StdDev).
Note on Lag: All anchor events require Pivot Right Bars for confirmation.
In 'Structure' and 'Delta' mode, the developing lines (POC, VA, etc.) are plotted using a non-repainting method (showing the value from pivRi bars ago).
In 'Swing' mode, the profile is plotted retroactively, starting from the bar where the pivot occurred. The developing lines are also plotted with this full pivRi lag to align with the past data.
Flexible Display Modes: The finalized profile can be displayed in three ways: 'Up/Down' (buy vs. sell), 'Total' (combined volume), and 'Delta' (net difference).
Dynamic Row Sizing: Includes an option ('Rows per Percent') to automatically adjust the number of profile rows (buckets) based on the profile's price range.
Integrated Alerts: Includes 13 alerts that trigger for:
A new profile reset ('Profile was resetted').
Price crossing any of the 6 developing levels (POC, VA High/Low, VWAP, StdDev High/Low).
Alert Lag Assumption: In 'Swing' mode, alerts are delayed to match the retroactively plotted lines. In 'Structure' and 'Delta' modes, alerts fire in real-time based on the current price crossing the current (repainting) value of the metric, which may differ from the non-repainting plotted line.
Caution: Real-Time Data Behavior (Intra-Bar Repainting) This indicator uses high-resolution intra-bar data. As a result, the values on the current, unclosed bar (the real-time bar) will update dynamically as new intra-bar data arrives. This includes the values used for real-time alerts in 'Structure' and 'Delta' modes.
DISCLAIMER
For Informational/Educational Use Only: This indicator is provided for informational and educational purposes only. It does not constitute financial, investment, or trading advice, nor is it a recommendation to buy or sell any asset.
Use at Your Own Risk: All trading decisions you make based on the information or signals generated by this indicator are made solely at your own risk.
No Guarantee of Performance: Past performance is not an indicator of future results. The author makes no guarantee regarding the accuracy of the signals or future profitability.
No Liability: The author shall not be held liable for any financial losses or damages incurred directly or indirectly from the use of this indicator.
Signals Are Not Recommendations: The alerts and visual signals (e.g., crossovers) generated by this tool are not direct recommendations to buy or sell. They are technical observations for your own analysis and consideration. Indicator
