Deviation Lens [JOAT]Deviation Lens
Introduction
Deviation Lens is an open-source multi-dimensional statistical displacement tool that applies Z-Score analysis simultaneously to three market dimensions: price level, close-to-close price change, and volume. Rather than using arbitrary overbought/oversold thresholds derived from historical maxima and minima, Deviation Lens computes exactly how many standard deviations each dimension is from its recent rolling mean. This provides a precise, adaptive, distribution-aware measure of how statistically extreme current market conditions are.
The core insight is that markets are mean-reverting systems over short time horizons. Statistical extremes — conditions where price, momentum, or volume are far from their recent averages — represent transient states. The further from the mean, the greater the statistical probability that conditions will normalize. Deviation Lens quantifies this probability directly, from 0% (at the mean) to 99.7% (at three standard deviations), and displays it as a live reversal probability for every bar.
Core Concepts
1. Three-Dimensional Z-Score Calculation
Three independent Z-Scores are computed on every bar:
The Price Z-Score measures how far the current close is from the rolling mean close in standard deviation units. This captures whether the current price level is statistically cheap or expensive relative to recent history.
The Change Z-Score measures how far the current bar's close-to-close price change is from the rolling mean change — quantifying momentum extremity rather than price level extremity.
The Volume Z-Score measures how far the current volume is from the rolling mean volume. High-volume Z-Score values identify bars where unusual institutional participation is statistically evident:
priceZ = priceStd > 0 ? (close - priceMean) / priceStd : 0.0
changeZ = changeStd > 0 ? (chg - changeMean) / changeStd : 0.0
volumeZ = volStd > 0 ? (volume - volMean) / volStd : 0.0
2. Reversal Probability Mapping
The absolute Z-Score is mapped to a reversal probability percentage based on the properties of the normal distribution. A Z-Score of 1.0 corresponds to 68.3% of values lying within one standard deviation — meaning only 31.7% of readings exceed this level, implying a 68.3% probability of mean reversion. A Z-Score of 2.0 corresponds to 95.4%, and 3.0 to 99.7%:
calcRevProb(float z) =>
float absZ = math.abs(z)
absZ >= 3.0 ? 99.7 : absZ >= 2.5 ? 98.8 : absZ >= 2.0 ? 95.4 : absZ >= 1.5 ? 86.6 : absZ >= 1.0 ? 68.3 : absZ >= 0.5 ? 38.3 : 0.0
This probability is displayed in the dashboard alongside the live Z-Score value, giving the trader both the raw statistical reading and its corresponding reversal likelihood.
3. Composite Z-Score and Zone Classification
The three individual Z-Scores are combined into a composite score using configurable weights for each dimension. The composite is then classified into a zone: EXTREME (above the configurable extreme threshold), ELEVATED, NEUTRAL, or the opposing directional equivalents. Zone classification determines the dashboard color coding and alert triggers:
composite = (priceZ * wPrice + changeZ * wChange + volumeZ * wVolume) / totalWeight
4. Divergence and Hidden Divergence Detection
Deviation Lens monitors for two divergence conditions. Standard divergence occurs when the Z-Score direction disagrees with the price direction — price makes a higher high but the Z-Score makes a lower high (bearish divergence), or price makes a lower low but the Z-Score makes a higher low (bullish divergence). Hidden divergence occurs when the Z-Score makes an extreme move while price action is relatively contained — a potential continuation pattern. Divergence events are labeled directly on the chart with bold, clearly sized labels:
bullDiv = close > close and priceZ < priceZ // Price up, Z down = bull div
bearDiv = close < close and priceZ > priceZ // Price down, Z up = bear div
Labels: BULL DIV, BEAR DIV (size.small), H.BULL, H.BEAR (size.tiny for hidden divergence).
5. Multi-Dimensional Dashboard
The institutional dashboard presents all three Z-Scores, the composite Z-Score, current zone classification, reversal probability, and divergence status simultaneously. The layout is designed so the most actionable information — Zone and Rev. Probability — is displayed at the largest text size, with supporting metrics at smaller sizes.
Features
Three independent Z-Scores: Price level, price change (momentum), and volume — each computed on its own rolling mean and standard deviation
Configurable Z-Score weights: The composite score uses adjustable per-dimension weights allowing emphasis on price, momentum, or volume depending on trading context
Live reversal probability: Probability percentage mapped directly from the Z-Score using normal distribution properties (68.3% at 1σ through 99.7% at 3σ)
Zone classification: Composite Z-Score classified as Extreme, Elevated, or Neutral in both directions with color-coded dashboard display
Divergence labels (BULL DIV / BEAR DIV): Z-Score vs price direction disagreement labeled on-chart at size.small
Hidden divergence labels (H.BULL / H.BEAR): Z-Score extreme with contained price action labeled at size.tiny
Configurable extreme and elevated thresholds: Both Z-Score thresholds independently adjustable
Institutional dashboard (top right): 14-row table with Price Z, Change Z, Volume Z, Composite Z, Zone, Reversal Probability, and divergence status
Adaptive thresholds: All calculations normalize to the rolling lookback period, adapting to current instrument and timeframe volatility
Alerts: Separate alertconditions for extreme bull and extreme bear composite Z-Score readings
Input Parameters
Z-Score Settings:
Z-Score Length: Rolling window for all three Z-Score calculations (default: 20)
Extreme Threshold: Z-Score magnitude classified as Extreme zone (default: 2.0)
Elevated Threshold: Z-Score magnitude classified as Elevated zone (default: 1.0)
Dimension Weights:
Price Weight: Relative weight of the price Z-Score in composite (default: 1.0)
Change Weight: Relative weight of the momentum Z-Score in composite (default: 1.0)
Volume Weight: Relative weight of the volume Z-Score in composite (default: 0.5)
Divergence:
Divergence Lookback: Bars back for divergence comparison (default: 5)
Show Divergence Labels toggle
Display:
Show Dashboard toggle
Bull and Bear color inputs
How to Use This Indicator
Step 1: Read the Composite Zone
The Zone row in the dashboard shows the current composite Z-Score classification. EXTREME readings at the top of the scale indicate the highest statistical probability of mean reversion. NEUTRAL readings indicate current conditions are close to the mean and have low statistical directional edge from this tool alone.
Step 2: Check Reversal Probability
The Rev. Probability row translates the Z-Score magnitude directly into a percentage. A reading above 95% means the current composite Z-Score is in the outer 5% of its historical distribution — a statistical extreme that has preceded mean reversion 95% of the time in the measured period.
Step 3: Assess Each Dimension Independently
The three individual Z-Score rows reveal which dimension is driving the composite. A high composite driven entirely by volume Z-Score is a different setup than one driven by price Z-Score. Understanding which dimension is extreme helps filter entries: a price Z-Score extreme without supporting momentum or volume Z-Score extremes may be a lower-conviction reading.
Step 4: React to Divergence Labels
BULL DIV and BEAR DIV labels appear when Z-Score momentum diverges from price direction. These signal that the statistical driver of a move is weakening even as price continues. H.BULL and H.BEAR hidden divergence labels flag potential continuation setups where Z-Score is extreme but price is not.
Step 5: Combine with Structural Context
Deviation Lens produces the highest value when its extreme readings coincide with a structural confluence point — an order block, session low, or structure level. A 99.7% reversal probability at a tested support zone is a higher-conviction setup than the same reading in open air.
Indicator Limitations
All Z-Scores are computed relative to the rolling lookback window. The lookback defines what "normal" means. A very short lookback will produce extreme readings frequently; a very long lookback will rarely reach the extreme threshold. Calibration to the instrument and timeframe is required
The reversal probability percentages are derived from the normal distribution assumption. Price change and volume distributions are not perfectly normal — they exhibit fat tails and skew. The probabilities are approximations, not precise statistical guarantees
The composite Z-Score uses equal weights by default. Changing dimension weights significantly alters which market conditions produce extreme readings. Weight adjustments should be based on the specific instrument's characteristics
Divergence detection uses a simple lookback comparison, not a peak-detection algorithm. In choppy markets, divergence labels may appear frequently without providing actionable signals
Originality Statement
Deviation Lens is original in its simultaneous, weighted multi-dimensional Z-Score framework that maps composite statistical extremity directly to a reversal probability percentage. This indicator is published because:
Applying Z-Score analysis to three independent market dimensions simultaneously — price level, momentum (close-to-close change), and volume — rather than a single oscillator provides a richer statistical picture of current market extremity than any single-dimension Z-Score tool
The direct mapping of Z-Score magnitude to reversal probability percentages using normal distribution properties gives traders an immediately interpretable statistic rather than a raw number requiring subjective interpretation
The composite weighted Z-Score system, where each dimension's contribution to the overall reading is configurable, allows the indicator to be tuned toward price-mean-reversion strategies, momentum exhaustion strategies, or volume anomaly detection depending on the trader's methodology
The combined detection of standard divergence and hidden divergence between the Z-Score and price direction provides trend continuation and reversal signals from the same framework
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Z-Score readings and reversal probability percentages are statistical tools based on historical distributions and do not guarantee any future price behavior. The normal distribution assumption applied to price and volume data is an approximation. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Premium & Discount Zones with Bias═══════════════════════════════════════════════
PREMIUM & DISCOUNT ZONES WITH BIAS
═══════════════════════════════════════════════
A statistical mean-reversion framework that identifies premium (sell) and discount (buy) zones on your entry timeframe, derived from higher-timeframe structure. Built for intraday traders who want meaningful, stable reference levels without the noise of lower-timeframe volatility.
WHAT IT DOES
─────────────────────────────────────────────
This indicator projects five statistical zones from higher-timeframe candle distributions:
• Upper Sell Zone (95th percentile) — extreme premium, mean reversion likely
• Sell Zone (75th percentile) — standard premium zone
• EQ / Equilibrium (50th percentile) — the statistical midpoint, natural target
• Buy Zone (25th percentile) — standard discount zone
• Lower Buy Zone (5th percentile) — extreme discount, mean reversion likely
The zones are calculated from the distribution of recent higher-timeframe candles (default: 18 × 4H candles = 3 days of structure) using Monte Carlo projection. A Naive Bayes classifier runs on the current chart timeframe to produce a directional bias based on relative volume and momentum.
The key advantage: zones update only when a new HTF candle closes, giving you stable reference levels that stay fixed for hours at a time. No more chasing shifting lines on a 1m chart.
INSPIRATION & CREDIT
─────────────────────────────────────────────
This indicator is inspired by and builds on "Monte Carlo CT " by © Steversteves, published on PulseWire under Mozilla Public License 2.0 at mozilla.org
The original script provided the mathematical foundation of Monte Carlo price projection combined with a Naive Bayes directional classifier. This version reimagines that concept as a premium/discount zone framework: instead of projecting bands forward across the chart, zones are derived from higher-timeframe structure and displayed as stable horizontal reference levels on the entry timeframe. Session awareness, bias table, and full visual customisation have been added for intraday traders.
Full credit and thanks to Steversteves for the original work.
HOW TO USE IT
─────────────────────────────────────────────
RECOMMENDED SETUP
Apply to your entry timeframe (1m, 3m, or 5m recommended). The zones will reflect your chosen higher timeframe (default 4H), giving you structural context without cluttering the entry chart.
CORE CONCEPT
The indicator identifies where price is statistically extended relative to recent structure. When price enters a buy or sell zone, it has a statistical tendency to revert toward the EQ (equilibrium). This is NOT a signal to blindly buy or sell — it is a confluence tool that tells you whether your chosen entry is at a statistically favourable location.
EXAMPLE SETUPS
─────────────────────────────────────────────
BULLISH SETUP (long from discount)
Wait for London or NY kill zone — the Session cell in the table will turn active
Price trades down into the Buy Zone (25th percentile) or Lower Buy Zone (5th percentile)
Check the Bias table — is it showing LONG with elevated probability?
Confirm with your own entry trigger (sweep + reclaim, break of structure, CISD, order block, etc.)
Enter long, targeting EQ as first target or the opposing Sell Zone as runner target
Why this works: you are entering long at a statistically discounted price with directional bias confirmation, targeting the statistical mean or opposing extreme.
BEARISH SETUP (short from premium)
Wait for an active kill zone
Price trades up into the Sell Zone (75th percentile) or Upper Sell Zone (95th percentile)
Check the Bias table — is it showing SHORT with elevated probability?
Confirm with your own entry trigger (failure to break, rejection candle, bearish CISD, etc.)
Enter short, targeting EQ as first target or the opposing Buy Zone as runner target
Why this works: you are selling at a statistically premium price against the likely mean reversion move.
WHAT NOT TO DO
─────────────────────────────────────────────
• Do not trade against the Bias signal. If price is in the Buy Zone but Bias shows SHORT, the setup lacks confluence — skip it
• Do not trade outside active kill zones unless you have another strong edge — the zones are most reliable during high-volume sessions
• Do not treat this indicator as a standalone entry signal. It is a confluence filter that works best combined with your existing framework
• Do not expect zones to hold every time. These are statistical probabilities, not guarantees
SETTINGS EXPLAINED
─────────────────────────────────────────────
ZONE CALCULATION
• Higher Timeframe — Controls which timeframe the zones are derived from. Default 240 (4H) balances structure and responsiveness. For longer-term reference, try Daily. For faster updates, try 60 or 120.
• HTF Candles Lookback — How many HTF candles feed the distribution. Default 18 = 3 days of 4H data. Minimum 10-12 for statistical significance. Higher values give smoother zones; lower values adapt faster to regime changes.
• Use Monte Carlo Projection — ON uses Monte Carlo simulation for distribution projection (more robust, slightly slower). OFF uses direct percentile calculation of historical returns (faster, tighter zones).
• Monte Carlo Simulations — Number of simulation runs when MC is enabled. 200 is the sweet spot. More sims give smoother bands but slower calculation.
• MC Forecast Horizon — How many HTF candles ahead to project. Default 6 × 4H = 24 hours. Increase for longer-term projection, decrease for closer zones.
• Line Offset — How far right the horizontal zone lines extend on your chart. Adjust for visual preference.
BIAS CLASSIFIER SETTINGS
• NB Train Lookback — Training window in current chart bars for the Naive Bayes classifier. Default 240.
• NB Momentum Period — ROC period for the momentum feature. Higher = smoother and less noisy on low timeframes. Default 30.
KILL ZONES
• London and NY kill zone windows in NY time. Adjust if you trade different sessions or different time zones.
COLOURS
• Fully customisable for both the zone lines and the bias table. Separate controls for background, borders, header text, label text, value text, and all highlight colours. Works on both light and dark chart themes.
TABLE DISPLAY
• Toggle table on/off
• Six position options (top/middle/bottom × left/right)
• Three size options: Normal, Small, Tiny
ALERTS
─────────────────────────────────────────────
Two alert conditions are available:
• Price entered BUY ZONE — when close drops below the 25th percentile line
• Price entered SELL ZONE — when close rises above the 75th percentile line
Set these as audio alerts if you want to focus on other charts and be notified only when price reaches a zone.
INSTRUMENTS & TIMEFRAMES
─────────────────────────────────────────────
This indicator is designed for:
• Futures (Gold, Silver, Indices, Oil, etc.)
• Forex majors
• Major crypto pairs
Best performance on liquid instruments with consistent volume. Recommended entry timeframes: 1m, 3m, 5m. Recommended higher timeframe for zones: 4H (default), 2H for faster updates, Daily for swing trading.
FINAL NOTES
─────────────────────────────────────────────
This is a confluence indicator, not a signal generator. Use it in combination with your own entry methodology — order flow reading, structure analysis, liquidity concepts, or any systematic entry framework.
The zones tell you WHERE. Your framework tells you WHEN.
Feedback and suggestions welcome. Trade safe. Indicator

Luminous Mean Reversion Channels [Pineify]Luminous Mean Reversion Channels
Luminous Mean Reversion Channels is a volatility-adaptive mean reversion overlay built around an ATR-stepped central level. Rather than following every candle like a moving average, the center line only recalibrates after price moves far enough to clear a volatility threshold. The upper and lower bands then mark stretched areas where price may begin rotating back toward the mean.
Key Features
ATR-based range logic that adapts to changing volatility
Stepped mean reversion level that filters small price noise
Upper overbought band and lower oversold band with soft visual fills
BUY and SELL labels when price crosses back through an outer band
Alert conditions for bullish and bearish mean reversion events
How It Works
The script measures Average True Range over the selected Volatility Length, then multiplies it by the Channel Width Factor. This creates the displacement threshold.
If the source price rises more than that threshold above the current center line, the center line steps upward by one threshold. If price falls more than that threshold below the current center line, it steps downward. If price stays inside the threshold, the center line does not move.
When the center line changes, the script stores half of the active threshold as the channel width. The overbought band is plotted above the center line, and the oversold band is plotted below it. A BUY label appears when price crosses upward through the lower band. A SELL label appears when price crosses downward through the upper band.
How the Components Work Together
ATR defines how large a move must be before the range is considered meaningful. The stepped center line defines the current mean reversion reference. The band-crossing logic then looks for price moving back inside a stretched area. This combination helps separate ordinary candle noise from larger volatility-adjusted displacement.
Trading Ideas and Insights
A BUY label near the lower band may indicate that downside extension is starting to mean revert
A SELL label near the upper band may indicate that upside extension is starting to cool
Repeated center-line steps in one direction suggest trend pressure; countertrend signals may need stronger confirmation
Sideways rotation between the two bands can be useful context for range-trading analysis
Signals are context markers, not guaranteed entries. Trend, structure, liquidity, and higher-timeframe conditions should still guide risk decisions.
Unique Aspects
This is not a standard Bollinger Band, Keltner Channel, or fixed moving average envelope. The central value moves in discrete ATR-based steps instead of updating on every bar
The active band width is captured when the mean level recalibrates, tying the channel to the volatility regime that caused the shift
The visual output focuses on two practical reversal zones rather than a dense stack of intermediate levels
How to Use
Apply the indicator to a clean chart and choose the source price
Use the gray center line as the current mean reversion reference
Watch the red upper band for stretched upside conditions and the green lower band for stretched downside conditions
Use BUY and SELL labels as prompts for further confirmation, not as standalone trade instructions
Create alerts from the bullish or bearish mean reversion conditions if you want notifications
Customization
Volatility Length (default: 200) - ATR lookback. Higher values smooth the channel; lower values react faster
Channel Width Factor (default: 6.0) - ATR multiplier. Higher values create wider bands and fewer signals
Source - Price series used for the channel and signal crosses
Open-Source Reference and Limitations
This script uses the public volatility-stepped range concept associated with Predictive Ranges as a foundation, then presents it as a simplified two-band mean reversion channel with Pineify styling, focused labels, and alerts. Mean reversion labels can appear early during strong trends, and past chart examples do not guarantee future results. Avoid using BUY/SELL signals on non-standard chart types when evaluating realistic trading behavior.
Conclusion
Luminous Mean Reversion Channels is designed for traders who want a clean, volatility-aware view of price extension. Its main value is showing when price is stretched relative to an ATR-stepped mean and when it begins crossing back toward the active range. Indicator

Indicator

Adaptive Fourier Transform CCI [QuantAlgo]🟢 Overview
The Adaptive Fourier Transform CCI reimagines the classic Commodity Channel Index by replacing its fixed lookback period with one that continuously adjusts to the market's own rhythm. Rather than measuring price deviation against an arbitrary static length, it first isolates the cyclical component of price action through a Discrete Fourier Transform, identifies which cycle period currently holds the most spectral energy, and then tunes the CCI calculation to that dominant period. The result is a momentum oscillator calibrated to the frequency structure of the instrument being traded, naturally tightening during fast, high-frequency regimes and widening during slower, drawn-out cycles without requiring manual timeframe adjustments.
🟢 How It Works
Before any cycle detection occurs, raw price is conditioned through two sequential filters. A high-pass filter strips the slow-moving trend component from the close, leaving only the oscillating portion of price action:
hp := 0.5 * (1 + a1) * (close - close ) + a1 * hp
That residual is then passed through a Super Smoother filter, which removes short-term noise from the cycle signal without introducing the lag that standard moving averages add at this stage:
filt := c1 * (hp + hp ) / 2 + c2 * filt + c3 * filt
This cleaned signal is what the Discrete Fourier Transform (DFT) operates on. The DFT scans across a range of candidate cycle periods and measures how much price energy is concentrated at each one. The period where that energy is strongest is selected as the dominant cycle. An EMA smooths the period output to prevent erratic length switching between bars, and the result is scaled by the Length Multiplier to derive the final adaptive CCI lookback:
adaptiveLen = clamp(round(dominantPeriod × lengthMult), 5, 60)
The CCI is then calculated using the standard Lambert formula over that adaptive length, measuring how far typical price has deviated from its mean relative to its average absolute deviation. An optional output smoothing MA reduces bar-to-bar noise before the final value is plotted.
🟢 Signal Interpretation
▶ Overbought (Above Upper Level, Red): When the Adaptive Fourier Transform CCI (AFT-CCI) rises above the upper threshold, price has deviated significantly above its cycle-adaptive mean. The reading reflects momentum extended relative to the market's current detected rhythm rather than a fixed arbitrary baseline. The signal carries more weight when the dominant cycle is stable and the DFT is locked onto a consistent frequency rather than switching between periods.
▶ Oversold (Below Lower Level, Green): When the AFT-CCI falls below the lower threshold, price has moved an equivalent distance below its cycle-adaptive mean. In strongly trending conditions the AFT-CCI can remain in either zone for extended periods, so the threshold levels should be read as zones of extension rather than automatic reversal points.
▶ Neutral Zone (Between Levels, Grey): When the AFT-CCI sits between the upper and lower thresholds, price deviation relative to the detected cycle is within normal range. Zero-line crosses within this zone indicate the adaptive mean is being reclaimed, which can serve as early directional context before a full threshold break develops.
▶ Zero Line: The zero line represents the adaptive mean itself. A cross above zero indicates typical price has moved above the cycle-adaptive mean; a cross below indicates the opposite. These crosses are lower-conviction reads on their own but become more meaningful when followed by a threshold break in the same direction.
🟢 Features
▶ Preconfigured Presets: Two parameter sets sit alongside the default configuration. "Fast Response" compresses the DFT window and cycle search range while raising the length multiplier, producing faster adaptation suited to intraday charts from 5-minute to 1-hour. "Smooth Trend" expands the window and search range while lowering the multiplier, establishing a more stable cycle read suited to daily and weekly position trading.
▶ Built-in Alerts: Six alert conditions cover the full range of meaningful oscillator events. Separate alerts fire on entering and exiting both overbought and oversold territory, capturing threshold breaks in both directions. Two additional alerts trigger on bullish and bearish zero-line crosses, enabling directional monitoring without requiring constant chart observation.
▶ Visual Customisation: Six colour presets, Classic, Aqua, Cosmic, Cyber, Neon, and Custom, apply consistently across the signal line, glow layers, and threshold level lines so the overbought and oversold colours remain coherent regardless of which preset is active. The optional neon glow effect uses three layered plots at increasing transparency to give the signal line visual depth and make threshold breaks immediately readable at a glance.
Indicator

Indicator

Fibonacci MA Trend Gap V1Overview
The Smart Fibonacci Trend Gap is a comprehensive momentum and mean-reversion oscillator designed to identify when price action has overextended relative to its Fibonacci-weighted trend. By calculating the squared variance between the current price and a composite average of 17 Fibonacci lengths, this tool highlights high-probability reversal zones and trend exhaustion points.
Key Features
📐 Multi-Fibonacci Core: Calculates an aggregate mean from up to 17 different Fibonacci moving average lengths (2 to 4181), providing a much "smoother" and more reliable trend baseline than a single MA.
🔍 Auto-Divergence Detection: Automatically identifies and draws Regular and Hidden bullish/bearish divergences directly on the oscillator. Solid lines indicate Regular divergence; dashed lines indicate Hidden.
⚡ Dual Signal Lines: Includes a Fast (Red) and Slow (Green) signal crossover system for confirming momentum shifts and trend changes.
🌈 Visual Sentiment: The background dynamically shifts color based on the Signal Line crossover, providing an instant "at-a-glance" read on the current trend bias.
🛠 Fully Customizable: Choose from 7 different MA types (SMA, EMA, WMA, HMA, VWMA, SMMA, DEMA) and toggle exactly how many Fibonacci lengths to include in the calculation.
How to Use
Mean Reversion: When the cyan oscillator line reaches extreme peaks or valleys away from the zero line, look for Regular Divergence (Triangles) to signal a potential snap-back to the mean.
Trend Following: Use the background color and Signal Line crossovers (Red/Green) to stay on the right side of the macro trend.
Hidden Divergence: Use dashed-line signals to identify trend continuation opportunities during pullbacks.
Settings
MA Type: Change the underlying math of the trend (HMA for speed, EMA for standard trend following).
Number of MAs: Scale the sensitivity by including more or fewer Fibonacci lengths.
Divergence Lookback: Fine-tune how sensitive the pivot detection is to fit your specific timeframe. Indicator

Daily Deviation Range and Gap Stats - NikaQuant
## What It Does
This indicator projects six pairs of deviation levels above and below a defined session range, draws a daily gap line at a configurable time, and shows a live stats panel with historical hit rates, mean-revert rates, gap fill statistics, and trade-decision suggestions.
The range itself is captured as the high and low of 5-minute closes during a configurable New York time window (default 19:30 to 20:30 NY). Once the window closes, the range is locked and six fibonacci-style deviation levels at multiples 1, 2.5, 5, 8, 13, and 19 of the range size are projected forward both upward and downward across the next trading day until a configurable cutoff (default 16:00 NY next day).
A separate gap line is captured at a configurable time (default 15:55 NY) using the close of that 5-minute bar. The gap line extends visually across the overnight session and is monitored for fill during the next session's open-to-close window (default 09:30 to 16:00 NY). When price crosses the gap level inside that window, the line is locked at the fill bar.
A live statistics table aggregates historical performance per day for the lookback period, showing per-level touch frequencies, mean-revert frequencies, close-inside-level frequencies, and gap fill statistics, then turns these into actionable trade-setup suggestions.
## Why It Is Original
Unlike a standard pivots or fibonacci-retracement indicator, this script is not a static price-level projection. It is a session-range deviation framework combined with an integrated gap tracker and a per-level historical statistics engine.
This script combines three distinct functional modules because each one addresses a different question about session structure:
(1) The range-multiple deviation levels answer "how far has price moved from session balance, in units of session range?" — analogous to standard-deviation channels but anchored to a user-defined range window rather than a rolling average.
(2) The daily gap line answers "is there an unfilled overnight reference price and what is the historical edge of trading toward it?" — different from standard gap detectors that only flag open-to-close gaps because it captures a specific price (the close at gap-time) and tracks fill behaviour inside a defined session window.
(3) The historical statistics engine answers "given today's structure, what has actually happened on past days when price reached the same levels or when a gap was open at this distance?" — turning the visual levels into probability-weighted decision inputs rather than just lines on a chart.
Together, the three modules produce something none of them would alone: a session-relative deviation map with quantified historical edge per level, plus a context-aware trade decision suggestion that combines current position, time remaining in the session, and historical revert behaviour.
The script also enforces a strict 5-minute internal data resolution regardless of chart timeframe (1-minute through 1-hour), so the levels and gap stay consistent whether the user is on a 5m chart or a 1H chart. This is accomplished via a dual-path data fetch that adapts to the chart's timeframe — pulling individual 5-minute samples on lower-timeframe charts and aggregating 5-minute closes per chart bar on higher-timeframe charts.
## How It Works
On each chart bar the script collects the 5-minute bars that have closed since the last update. For each 5-minute bar it checks whether the bar falls inside the range window, the extension window, the gap trigger time, or the gap fill window, and updates the relevant state.
When a 5-minute bar marks the end of the range window, the script locks in the highest and lowest 5-minute closes of the window, computes the range size and midline, and draws the deviation levels at multiples of the range above the high and below the low, projected forward to the configured extension-end time. A range-outline box is drawn over the range window for visual reference.
When a 5-minute bar matches the gap-trigger time, the script captures that bar's close as the gap price and starts drawing a horizontal line. On every subsequent 5-minute bar inside the next session's gap-fill window, the script checks whether the bar's high-low straddles the gap price. If so, the line is locked and the gap is recorded as filled.
Every time a deviation level is touched intraday — the 5-minute high reaches an upper level or the 5-minute low reaches a lower level — the script records that touch for the day. If price subsequently revisits the midline before the extension window ends, all touched levels for that day are also recorded as having reverted. When the extension window ends, the day's data is appended to a rolling history.
Each day's gap statistics (occurred, filled, minutes from fill-window open to fill) are appended at the next gap trigger, which ensures the gap is paired with its complete fill outcome before the next gap overwrites the live tracking state.
The stats table reads the history and renders per-level touch frequency, per-level revert frequency, close-inside-level frequency, gap fill rate, gap fill-time distribution (average, median, percent filled within 1 hour, percent filled within 4 hours), daily directional bias, range expansion vs contraction regime, day-type classification, time-elapsed in the active extension, and a context-aware trade-setup suggestion with stop and target prices for active fade setups.
The setup engine includes a time-remaining guard: when fewer minutes remain in the extension than the configured threshold, time-sensitive setups (fades and gap targets) are suppressed and the panel shows a "late session" status instead.
## How To Use It
- A range outline box appears over the range window once the window closes — this is the visual reference for the session range.
- Six pairs of lines extend forward from range-end to extension-end at multiples 1, 2.5, 5, 8, 13, and 19 of the range above and below the range high and low.
- Numerical labels at each level show the multiple — labels can be placed at the left or right end of the line via the "Level Label Side" setting.
- The gap line appears horizontally at the gap price after the configured gap time and extends until either price crosses through it during the fill window or the next day's gap is set.
- The live stats panel shows current price location vs midline (in range-multiples), today's range vs historical average, the current zone between two adjacent levels, the furthest level tagged today, per-level historical touch and revert rates, gap fill statistics, and a live setup suggestion.
Recommended timeframes: 1-minute through 1-hour. The script always uses 5-minute data internally, so behavior is consistent across chart timeframes.
Recommended markets: 24-hour markets such as index futures (ES, NQ), major FX pairs, and crypto majors, where overnight session structure matters and the configured NY-time windows align with meaningful session boundaries.
Avoid using when: less than 30 sessions of chart history are loaded (statistics will be unreliable) or on instruments that close before the configured range window (the range simply will not populate).
## Settings
- Max Deviation Days (default 11): how many past days to keep deviation levels visible. Older days are removed automatically.
- Show Deviation Levels: toggle the level lines.
- Normalize Range Size: when on, the range box and level distances use the average range over N past days instead of today's actual range.
- Normalize over N Days (default 500): number of past days to average for the normalization.
- Range Start and End Hour and Minute (default 19:30 to 20:30 NY): the window during which the range is captured.
- Extension Start and End Hour and Minute (default 20:30 to 16:00 NY next day): the window during which the deviation levels are drawn forward.
- Show Gap Level: toggle the gap line.
- Max Gap Days (default 11): number of past gap lines to keep visible.
- Gap Time Hour and Minute (default 15:55 NY): the 5-minute bar whose close becomes the gap price.
- Gap Close Start and End Hour and Minute (default 09:30 to 16:00 NY next day): the window during which gap fill is detected.
- Show Range Outline (default on): toggle the range outline box.
- Range Outline Color, Width, Style, Fill Transparency: visual settings for the box.
- Gap Width, Style, Color: visual settings for the gap line.
- Levels Width, Style: visual settings for the deviation lines.
- Level 1 through Level 6 (defaults 1, 2.5, 5, 8, 13, 19): numeric multiples of the range used for each level pair.
- Level 1 to 6 Color: per-level color.
- Level Label Side (default Left): place the level number labels at the left or right end of each line.
- Font Size (default 9): label font size.
- Show Stats Table (default on): toggle the live statistics panel.
- Stats Lookback in Days (default 5000): number of past completed days to include in historical statistics. Higher means more reliable percentages but requires more chart history loaded.
- Min Revert Percent for Fade Setup (default 55): a FADE setup is suggested only if the historical mean-revert rate at the touched level is at or above this threshold and the level was tagged at least 3 times in the lookback.
- Min Remaining Minutes for Setup (default 60): suppresses time-sensitive setups when fewer than this many minutes remain in the extension. Set to 0 to disable.
- Table Position (default Top Right): where the stats table is anchored.
- Table Size (default Normal): text size inside the stats table.
- Bull / Setup Color, Bear / Warning Color, Table Background, Table Text, Table Border: color settings for the panel.
## Alerts
Five alert conditions are exposed and can be selected from PulseWire's "Add Alert" dialog:
- Range Locked: fires when the range window closes and the levels are projected.
- Level Tagged: fires the first time price reaches any deviation level on either side.
- Gap Set: fires when the daily gap level is captured.
- Gap Filled: fires when price crosses through an open gap during the fill window.
- Session End: fires when the extension window ends and stats are finalized.
## Notes
The script does not repaint after a 5-minute bar closes. The range, deviation levels, and gap line are drawn from confirmed data only. The live distance-from-midline and live setup suggestions update intrabar based on current price.
Future bar-index positions for projected lines and labels are estimated based on the chart timeframe's bar duration. On charts with weekend gaps the projected end positions may visually diverge from the configured extension-end time by a small amount, but the underlying logical end time is correct.
Indicator

Indicator

Anchored Regression Oracle [JOAT]Anchored Regression Oracle
Introduction
Linear regression is one of the most powerful tools in statistical analysis, yet its application in most trading indicators is limited to a fixed rolling window applied to closing prices — a single-dimensional view of a multi-dimensional problem. The Anchored Regression Oracle extends classical Ordinary Least Squares regression in four distinct ways: it supports both logarithmic and linear price scaling, it offers multiple anchor modes (fixed bar count or calendar-period anchoring), it computes a full set of deviation, Fibonacci, and extreme projection levels above and below the regression line, and it incorporates the Pearson R correlation coefficient and theta angle as real-time quality metrics that control signal eligibility.
The fundamental insight motivating the log/linear duality is that financial prices grow multiplicatively, not additively. A $10 move from $100 is a 10% change; a $10 move from $1000 is a 1% change. Fitting a straight line through raw prices on a linear scale treats these as equivalent. Fitting through log-transformed prices treats them as proportionally equivalent — and for equities, cryptocurrencies, and other compounding instruments, the log-space regression is often the more meaningful representation of trend. The indicator handles both cases transparently, transforming all calculation into log space when selected and back-transforming all output levels to price space for display.
The calendar anchoring system adds a dimension that pure bar-count indicators cannot provide: the ability to reset and recalculate the regression window at the start of each new trading day, week, month, or other period — automatically. This makes the regression channel contextually anchored to the current period's price action rather than an arbitrary historical bar count, without any manual intervention.
Core Concepts
1. Manual OLS Linear Regression
The indicator implements the full Ordinary Least Squares regression formula manually rather than using Pine Script's built-in ta.linreg(). This is a deliberate choice: the manual implementation supports both logarithmic transformation and expanding anchor windows, neither of which the built-in function accommodates. The calculation accumulates bar-level sums across the current window to derive the exact OLS slope and intercept.
slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)
intercept = (sumY - slope * sumX) / n
lrValue = intercept + slope * n
Where n is the current window size, sumXY is the sum of bar-index times price products, sumXX is the sum of squared bar indices, and sumX and sumY are the simple sums of indices and prices respectively. In log mode, all price values entering the sums are first transformed via math.log(), and all output levels are back-transformed via math.exp() before rendering on the chart.
2. Pearson R Correlation Coefficient
After computing slope and intercept, the Pearson R coefficient is derived from the same accumulated sums. R measures the linearity of the relationship between bar index and price — essentially, how well the regression line fits the actual price path. Values near 1.0 or -1.0 indicate strong linear trends where the regression line is a reliable representation. Values near 0 indicate that price is moving chaotically relative to a linear model.
dxt = sumXX - sumX * sumX / n
dyt = sumYY - sumY * sumY / n
pearsonR = (sumXY - sumX * sumY / n) / math.sqrt(dxt * dyt)
The dashboard displays Pearson R with color coding: teal for |R| ≥ 0.8 (strong fit), orange for |R| ≥ 0.5 (moderate fit), red for |R| below 0.5 (weak fit). When the Pearson filter is enabled, only readings with |R| above the user threshold are eligible for signal generation — preventing trades on regression lines that do not actually describe the price behavior.
3. Theta Angle
The slope of the regression line is an abstract mathematical quantity that is not intuitively interpretable. Converting it to a theta angle using the arctangent function produces a human-readable degree value: a steeply rising trend shows a large positive angle, a flat trend shows near-zero degrees, and a declining trend shows a negative angle. The minimum theta filter allows users to exclude signals from very shallow trends — requiring a minimum degree of directional conviction before entries are considered.
theta = math.atan(-slope) * 180 / math.pi
Note that the negative sign before slope accounts for the inversion between mathematical y-axis convention (upward) and screen y-axis convention (downward in most chart implementations), ensuring the displayed angle intuitively matches the visual slope direction on the chart.
4. Window Modes: Rolling vs. Anchored
The "Bar" mode uses a fixed rolling window of N bars — the regression line covers exactly the last N candles regardless of calendar position. All period-based modes ("Minute", "Hour", "Day", "Week", "Month") use an expanding anchor: a bar counter resets to zero each time a new period begins (detected via timeframe.change()), and the regression window expands from that anchor point through the current bar. This means on day anchoring, the regression always describes the current day's price action from the first bar to now — expanding as the day progresses and resetting at the start of each new day.
var int windowBars = 0
periodChanged = timeframe.change(targetTF)
windowBars := periodChanged ? 1 : windowBars + 1
effectiveLen = windowMode == "Bar" ? barLen : windowBars
5. Deviation and Fibonacci Projection Levels
Six lines are drawn on the chart, all updated on barstate.islast to avoid performance overhead. The center line is the regression line itself. The upper and lower deviation lines are offset by user-configurable standard deviation multiples. A Fibonacci level is plotted at 1.618 standard deviations. Historical high and low lines track the maximum deviation point actually reached by price above and below the regression line over the window — providing empirical rather than statistical bounds.
f_lvl(base, std, mult) =>
logMode ? math.exp(math.log(base) + std * mult) : base + std * mult
upperDev = f_lvl(lrValue, stdDev, upperMult)
lowerDev = f_lvl(lrValue, stdDev, lowerMult)
fibLevel = f_lvl(lrValue, stdDev, 1.618)
In log mode, the offset is applied additively in log space (equivalent to multiplicative scaling in price space), ensuring the deviation levels remain proportionally consistent with the log-scale price representation.
6. Five Signal Modes
The signal system offers five distinct behavioral modes. "None" disables signals entirely. "Deviation|Breakout" fires when price crosses above the upper deviation (long) or below the lower deviation (short). "Deviation|MeanReversion" fires when price crosses back inside the deviation bands after an excursion outside. "Extreme|Breakout" uses the historical high and low deviation lines as the reference. "Extreme|MeanReversion" fires when price returns inside the historical extremes. "Theta-Only" generates signals based solely on the theta angle crossing the minimum threshold, regardless of price position relative to deviation levels.
Features
Full Manual OLS Regression: Complete Ordinary Least Squares implementation supporting both log and linear price scaling without any ta.linreg() dependency.
Log/Linear Scale Toggle: Log mode transforms all prices via math.log before regression and back-transforms all output levels, producing proportionally correct channels for compounding instruments.
Multiple Window Modes: Fixed bar count or calendar-anchored expanding windows (Minute, Hour, Day, Week, Month) that reset automatically on period transitions.
Pearson R Coefficient: Real-time correlation quality metric with color-coded dashboard display and optional signal eligibility filter.
Theta Angle: Human-readable trend angle from arctangent of slope with optional minimum threshold signal filter.
Six Regression Lines: Center regression line, upper and lower user-configured deviation bands, 1.618 Fibonacci level, and historical high/low deviation extremes.
Five Signal Modes: Deviation breakout, deviation mean-reversion, extreme breakout, extreme mean-reversion, and theta-only — covering different trading philosophies.
Historical Ghost Plots: Non-repainting semi-transparent historical regression and deviation plots for visual context of prior channel positions.
Efficient Line Updates: All six lines are updated on barstate.islast only, maintaining performance even on long chart histories.
Seven-Row Dashboard: Pearson R (color-coded), theta with sign, direction, signal mode, window type, standard deviation, and window size.
Four Alert Conditions: Long entry, short entry, long exit, short exit — all gated by optional Pearson and theta filters.
Input Parameters
Regression Settings:
Window Mode: Bar, Minute, Hour, Day, Week, or Month (default: Day)
Bar Length: Fixed window size when mode is "Bar" (default: 100)
Target Timeframe: Calendar period string used in timeframe.change() for anchored modes (default: "D")
Log Mode: Enable logarithmic price transformation (default: false)
Deviation Settings:
Upper Deviation Multiplier: Standard deviation multiple for upper channel boundary (default: 2.0)
Lower Deviation Multiplier: Standard deviation multiple for lower channel boundary (default: 2.0)
Show Fibonacci Level: Toggle the 1.618 StdDev Fibonacci projection line (default: true)
Show Historical Extremes: Toggle the historical high/low deviation lines (default: true)
Signal Settings:
Signal Mode: None, Deviation|Breakout, Deviation|MeanReversion, Extreme|Breakout, Extreme|MeanReversion, Theta-Only (default: Deviation|Breakout)
Minimum Theta: Minimum absolute angle in degrees required for signal eligibility (default: 5)
Pearson Filter: Enable Pearson R minimum threshold (default: false)
Min Pearson R: Minimum |R| required when filter is active (default: 0.7)
Display Settings:
Show Historical Plots: Toggle ghost regression and deviation plots (default: true)
Historical Alpha: Transparency level for historical plots (default: 75)
Show Dashboard: Toggle the seven-row information table (default: true)
How to Use This Indicator
Step 1: Select the Appropriate Window Mode
Start by choosing the window mode that matches your analytical context. For intraday trading, Day anchoring is most natural — it resets the regression at the start of each session, showing how the current day's price action trends from the open. For swing trading, Week or Month anchoring provides a broader structural perspective. Bar mode is appropriate when you want consistent lookback regardless of calendar, for example in crypto markets that trade continuously without session boundaries.
Step 2: Evaluate Regression Quality Before Trusting Signals
Check the Pearson R value in the dashboard before interpreting any signal. A strong R (teal, ≥ 0.8) means price has been moving in a well-defined linear trend — the regression line is descriptively accurate and signals from it carry more weight. A weak R (red, < 0.5) means price has been choppy and non-linear; the regression line is fitting noise, and deviation-based signals will be unreliable. If the Pearson filter is enabled, signals will simply not fire when R is below threshold, automating this quality check.
Step 3: Choose a Signal Mode Matching Your Strategy
Breakout modes are suited for momentum strategies — they enter when price is moving away from the regression mean with statistical force. Mean-reversion modes are suited for range-expansion strategies — they enter when price returns inside the channel after an excursion, betting on a return to mean. The Extreme modes use the actual historical high/low deviations rather than the fixed multiplier, making them adaptive to the specific price behavior observed in the current window.
Step 4: Apply Theta and Pearson Filters for Quality Control
Enable the minimum theta filter to avoid trading very shallow trends. A trend angled at 3 degrees has minimal directional conviction — the regression line is nearly horizontal, and any deviation signals from it may be as much noise as signal. Setting a minimum of 10-15 degrees for active entries ensures you are trading genuine directional moves rather than sideways grinding. Combine this with the Pearson filter for the highest-quality signal subset.
Indicator Limitations
Linear regression assumes the relationship between time and price is fundamentally linear during the window. In strongly trending markets this is approximately true; in markets with curves, accelerating trends, or parabolic moves, the linear model will systematically underfit the actual trajectory.
The OLS calculation accumulates sums over the entire window on every bar. On very long bar counts or in expanding anchor modes late in a long session, this can affect script execution time, particularly when combined with other indicators on the same chart.
Calendar anchoring uses timeframe.change() which is resolution-dependent. If the chart timeframe is coarser than the anchor period (e.g., viewing a weekly chart with day anchoring), the anchor period may not transition as expected.
Pearson R measures linear correlation specifically. A price series that follows a consistent curve will produce a lower R than one that follows a straight line, even if the curve describes a very orderly trend. In log mode, this issue is partially mitigated for exponentially trending instruments.
Historical ghost plots are informational only and represent completed regression windows. They do not update after their respective periods close.
In log mode, the volatility measure used for deviation computation is the standard deviation of log-transformed prices, which is equivalent to a percentage standard deviation. For very short windows, this measure can be highly sensitive to individual bar outliers.
Signals on the current (incomplete) bar are not displayed, as all signal conditions require barstate.isconfirmed to prevent look-ahead.
Originality Statement
The Anchored Regression Oracle is a substantially original analytical tool that addresses specific limitations of existing regression-based indicators on PulseWire.
The manual OLS implementation (computing slope, intercept, and Pearson R from accumulated sums without ta.linreg()) enables the log-space calculation that built-in functions do not support — allowing mathematically correct regression channels for compounding assets.
The calendar-anchored expanding window system (using timeframe.change() to reset a bar counter and grow the regression window from a fixed calendar point) is an original approach to making regression contextually meaningful for session-based or period-based analysis.
Computing and displaying the theta angle (arctangent of slope in degrees) as a real-time trend steepness metric, with a configurable minimum threshold that gates signal eligibility, is an original signal quality framework not found in standard regression channel indicators.
The five-mode signal system — providing breakout and mean-reversion variants for both statistical deviation levels and empirical historical extremes, plus a theta-only mode — covers a range of trading philosophies from a single indicator, rather than requiring separate indicators for each approach.
The combination of log/linear duality, calendar anchoring, Pearson quality gating, theta filtering, Fibonacci projection at 1.618 StdDev, and historical ghost plots in a single indicator represents an integration of features not available in any single existing PulseWire regression tool.
Disclaimer
The Anchored Regression Oracle is provided for educational and informational purposes only. It is a technical analysis tool and does not constitute financial advice. Statistical measures such as Pearson R and regression slope describe historical relationships and do not predict future price behavior. All trading involves risk of loss. Users are solely responsible for their own trading decisions. Please consider your individual risk tolerance and consult a licensed financial professional before engaging in any trading activity.
-Made with passion by officialjackofalltrades
Indicator

Cadence Veil [JOAT]Cadence Veil /b]
Introduction
Cadence Veil is an advanced open-source regime classification indicator that fuses an H-Infinity adaptive filter, R-squared efficiency gating, dual-window chop scoring, and Kaufman adaptive efficiency into a unified five-state regime engine. The indicator classifies every bar into one of five market states — Expansion Bull, Expansion Bear, Compression, Whipsaw, or Dormant — using a hysteresis state machine that prevents rapid flip-flopping between regimes. It then overlays volatility envelope bands, a ZEMA bias ribbon, structural pivot tracking, regime shift boxes, and gradient visualization to create a complete market phase recognition system.
The core problem this indicator solves is regime misidentification. Most traders apply the same strategy regardless of market conditions — trend-following in chop, mean-reversion in trends, or trading during dormant periods when nothing meaningful is happening. Each of these mismatches leads to losses. Cadence Veil explicitly classifies the current regime so traders can select the appropriate strategy for the conditions. A compression regime calls for breakout preparation. An expansion regime calls for trend-following. A whipsaw regime calls for caution or sitting out entirely. A dormant regime means the market lacks the energy for any strategy to work reliably.
Core Concepts
1. H-Infinity Adaptive Filter
The centerline of the indicator uses an H-Infinity filter rather than a conventional moving average. H-Infinity filtering is a control theory technique designed to produce optimal estimates under worst-case noise conditions. Unlike a Kalman filter (which assumes Gaussian noise), the H-Infinity filter makes no assumptions about noise distribution, making it more robust in financial markets where price noise is decidedly non-Gaussian:
for i = 0 to hinfOrder - 1
float s = array.get(hinfState, i)
float e = array.get(hinfError, i) + hinfNoise
float g = e / (e + hinfDist)
array.set(hinfState, i, s + g * (close - s))
array.set(hinfError, i, (1.0 - g) * e)
The filter maintains internal state and error estimates that adapt each bar. The gain parameter (error divided by error plus disturbance) determines how much the filter trusts new data versus its existing estimate. Higher disturbance values make the filter more conservative (smoother); lower values make it more responsive. The filter order parameter controls how many state dimensions are tracked, with higher orders providing more sophisticated noise modeling.
2. R-Squared Efficiency Gate
R-squared measures how well price movement fits a linear regression line. A high R-squared (close to 1.0) means price is moving in a straight, efficient line — a strong trend. A low R-squared (close to 0) means price is moving randomly with no directional efficiency:
float r2Raw = math.pow(ta.correlation(close, bar_index, effLen), 2)
float r2Smooth = ta.sma(r2Raw, effSmooth)
The indicator uses an auto-calibrating threshold: the rolling mean of R-squared plus k standard deviations. This means the threshold adapts to the instrument's typical trending behavior. A hysteresis band prevents the gate from flickering — once open, R-squared must drop further to close the gate than it needed to rise to open it.
3. Dual-Window Chop Scoring
Chop is measured using the efficiency ratio concept: the net price movement divided by the total path length over a window. A perfectly straight move scores 0 (no chop); a move that goes nowhere despite lots of bar-to-bar movement scores 1 (maximum chop). The indicator uses two windows — a fast window (default 14 bars) for recent chop and a slow window (default 50 bars) for structural chop — and blends them:
f_chop(int len) =>
float netMove = math.abs(close - close )
float pathLen = math.sum(math.abs(close - close ), len)
pathLen == 0.0 ? 1.0 : 1.0 - (netMove / pathLen)
float chopBlend = (chopFastVal + chopSlowVal) / 2.0
The dual-window approach catches both short-term whipsaws and longer-term structural chop that a single window might miss.
4. Kaufman Efficiency Ratio
The Kaufman ER provides a third independent measure of trend quality. It compares the absolute net price change over N bars to the sum of all bar-to-bar changes over the same period. Values near 1.0 indicate efficient, directional movement; values near 0 indicate noisy, non-directional movement. This complements R-squared (which measures linearity) and chop score (which measures path efficiency) by measuring absolute directional efficiency.
5. Composite Trend Score and State Machine
The three measures are blended into a single composite trend score:
float trendScore = (kaufER * 0.35) + ((1.0 - chopBlend) * 0.35) + (r2Smooth * 0.30)
This score, combined with the H-Infinity filter slope and volatility ratio, feeds into a five-state machine with persistence requirements. A candidate state must hold for a configurable number of consecutive bars (default 3) before the regime officially transitions. This prevents single-bar noise from triggering false regime changes.
The five states are:
Expansion Bull: R-squared gate open, trend score above threshold, H-Infinity slope positive
Expansion Bear: R-squared gate open, trend score above threshold, H-Infinity slope negative
Compression: High chop score, low volatility ratio — market is coiling
Whipsaw: High volatility but also high chop — dangerous conditions with large moves in both directions
Dormant: None of the above conditions met — market lacks energy or direction
6. Volatility Envelope Bands
Adaptive bands are constructed around the H-Infinity line using ZEMA-smoothed ATR. The bands scale their width based on the current regime: narrower during compression (0.7x), wider during expansion (1.2x), and standard during normal conditions. This regime-adaptive scaling means the bands contract when the market is coiling (tightening the range for breakout detection) and expand when the market is trending (giving the trend room to breathe).
Features
Five-State Regime Classification: Clear categorical identification of the current market phase with color-coded rendering throughout the indicator
H-Infinity Core Line with Glow: The adaptive filter line renders with a gradient glow whose color and intensity reflect the current regime and trend score
Regime Shift Boxes: When the regime changes, a colored box is drawn that expands to encompass the price range of the new regime, providing a visual record of regime transitions
Regime Shift Labels: Labels at regime transitions show the new regime abbreviation and the trend score at the time of transition
ZEMA Bias Ribbon: A filled ribbon between the H-Infinity line and its ZEMA shows directional bias with bull/bear coloring
Structural Pivot Detection: Swing highs and lows are identified and labeled with regime context — pivots formed during expansion regimes are colored differently than those formed during compression
Structure Lines: Dashed horizontal lines at the most recent swing high and low provide support/resistance reference
Envelope Breach Detection: The dashboard reports whether price is inside the bands, above/below the inner band, or above/below the outer band
Composite Signal Strength: A 0-100 score measuring how aligned all subsystems are (R-squared gate, Kaufman ER, chop score, and ZEMA bias)
Regime History Tracking: The dashboard shows the last three regime states in sequence, revealing the pattern of market phase transitions
Gradient Background Zones: Background coloring shifts on a gradient from compression tones to the current regime color based on the trend score
Regime-Aware Bar Coloring: Candle colors reflect the current regime with momentum-based gradient intensity
14-Row Dashboard: Displays regime state, duration, trend score, signal strength, R-squared gate status, chop blend, Kaufman ER, volatility ratio, H-Infinity gain, ZEMA bias, swing levels, envelope position, and regime history
Input Parameters
H-Infinity Filter:
Filter Order: Number of state-space dimensions (default: 3, range: 1-8)
Process Noise: Expected noise level (default: 0.5)
Disturbance: External disruption parameter (default: 1.0)
Efficiency Gate:
R-Squared Length: Correlation calculation period (default: 30)
Smoothing: R-squared smoothing period (default: 10)
Threshold k: Standard deviations above mean for auto-threshold (default: 1.0)
Chop Detector:
Fast Window: Short-term chop measurement (default: 14)
Slow Window: Long-term chop measurement (default: 50)
State Engine:
Entry Persistence: Consecutive bars required for regime transition (default: 3)
Hysteresis Band: Width of the hysteresis zone to prevent flickering (default: 0.15)
Volatility Envelope:
Inner/Outer ATR Multipliers: Band distance from the core line (default: 1.2/2.4)
ATR Length: Period for ATR calculation (default: 14)
Visuals:
Toggles for envelope bands, ZEMA bias ribbon, structural pivots, structure lines, regime shift boxes, regime shift signals, background zones, bar coloring, and dashboard
How to Use This Indicator
Step 1: Identify the Current Regime
The dashboard's regime field and the background coloring immediately tell you the market phase. This is the most important piece of information — it determines which strategy to apply.
Step 2: Match Strategy to Regime
Expansion Bull/Bear: Use trend-following strategies. Enter pullbacks to the H-Infinity line or inner band in the direction of the expansion
Compression: Prepare for a breakout. Tighten stops, reduce position sizes, and watch for the regime to shift to expansion. The ZEMA bias may hint at the breakout direction
Whipsaw: Reduce exposure or sit out. This regime produces large moves in both directions that stop out trend-followers and mean-reversion traders alike
Dormant: No edge exists. Wait for the market to wake up
Step 3: Use Signal Strength for Conviction
The composite signal strength (0-100) tells you how aligned all subsystems are. A 75+ score during an expansion regime is high-conviction. A 25 score during expansion suggests the regime may be weakening.
Step 4: Monitor Regime Transitions
Regime shift boxes and labels mark exactly where transitions occurred. The most profitable trades often come at the transition from compression to expansion — the breakout from a coiled market.
Step 5: Read the Regime History
The history chain (e.g., "COMP > EXP+ > DORM") reveals the market's recent phase pattern. A sequence like "COMP > EXP+ > COMP > EXP+" suggests a market that trends in bursts between consolidation periods.
Cadence Veil showing a regime transition sequence: compression (purple box) resolving into expansion bull (green box), with the H-Infinity line glow intensifying, envelope bands widening, and the trend score rising in the dashboard
Indicator Limitations
The H-Infinity filter, while theoretically robust, has three parameters (order, noise, disturbance) that significantly affect behavior. Optimal settings vary across instruments and timeframes and may require experimentation
The persistence requirement for regime transitions (default 3 bars) creates a delay. Fast regime changes may be identified several bars after they begin. This is a deliberate trade-off for stability
The five-state classification is a simplification of continuous market behavior. Markets can exist in states that don't cleanly fit any category, and the boundaries between states are inherently fuzzy
R-squared, chop score, and Kaufman ER all use lookback windows. They describe what the market has been doing, not what it will do. A regime can change immediately after being classified
The whipsaw state is identified but no strategy is recommended for it because whipsaw conditions are inherently difficult to trade profitably. The indicator's value here is in warning you to reduce exposure
Volatility envelope bands adapt to the regime but still use ATR, which is backward-looking. Sudden volatility shifts (news events, gaps) may not be reflected in the bands for several bars
Originality Statement
This indicator is original in its application of control theory (H-Infinity filtering) to market regime classification and its synthesis of multiple independent efficiency measures into a unified state machine. While regime detection and adaptive filtering are established concepts, this indicator is justified because:
The H-Infinity filter is rarely used in technical analysis. Its worst-case noise optimization makes it theoretically more appropriate for financial markets than the more common Kalman filter, which assumes Gaussian noise
The triple-measure efficiency assessment (R-squared linearity + dual-window chop + Kaufman efficiency) provides more robust regime detection than any single measure. Each captures a different aspect of market behavior
The five-state classification with hysteresis persistence requirements produces stable, actionable regime labels rather than the flickering binary (trending/ranging) classifications common in simpler indicators
Regime-adaptive volatility envelope scaling automatically adjusts band behavior to the detected market phase, providing context-appropriate support/resistance levels
The composite signal strength score synthesizes all subsystems into a single conviction measure
Regime shift boxes provide a visual record of market phase transitions that aids in pattern recognition across longer timeframes
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Regime classifications are based on historical data analysis and do not predict future market phases. A market classified as "Expansion Bull" can reverse at any time. Compression does not guarantee a subsequent breakout, and the direction of any breakout is not predicted by the compression classification. Always use proper risk management and conduct your own analysis. The author is not responsible for any losses incurred from using this indicator.
-Made with passion by officialjackofalltrades
Indicator

Possible Reversal Zone DetectorThis indicator is a comprehensive tool designed to identify potential market reversal zones and mean-reversion opportunities. It utilizes a dynamic volatility channel to detect when the price becomes overextended and is likely to reverse its short-term direction.
To eliminate false signals during strong trends, it comes packed with multiple highly customizable technical filters, including RSI, Volume Spikes, and Price Action patterns. Furthermore, it visually assists traders by drawing automated Risk/Reward boxes directly on the chart upon signal generation.
Key Features & Mechanics:
Dynamic Volatility Channel: The core of the indicator relies on an EMA baseline and a Standard Deviation multiplier. It creates an envelope around the price action. Signals are generated when the price pierces these outer boundaries and shows rejection.
Volume Spike Filter (Default: ON): A reversal is much stronger when backed by heavy volume. This filter ensures that a signal is only valid if the current volume exceeds the moving average of the volume by a specified multiplier.
Automated Risk/Reward Boxes (Default: ON): Once a valid reversal signal is confirmed, the indicator instantly plots a customizable Risk/Reward box (Default 1:2 RR, 1% Stop Loss) on your chart. This allows you to visually plan your trade, target, and invalidation level effortlessly.
RSI Filter (Default: OFF): When enabled, it checks if the asset is mathematically overbought or oversold before confirming a reversal from the channel boundaries.
Price Action Filters (Default: OFF): For the ultimate "sniper" entry, you can require the indicator to look for specific candlestick patterns—such as a Pinbar (Wick Rejection) or an Engulfing pattern—at the exact moment the price tests the channel boundary.
How to Use:
Wait for the visual arrows (Yellow for Bullish, Red for Bearish) to appear. These indicate that the price has breached the volatility band and satisfied your selected filters (like volume spikes). Evaluate the automatically drawn Risk/Reward box to see if the setup matches your risk management strategy.
Customization:
Every aspect of this indicator is adjustable. You can tweak the channel sensitivity, volume requirements, RSI levels, and the exact dimensions of the Risk/Reward boxes to fit any timeframe or asset class.
Disclaimer: This script is for educational purposes only and does not constitute financial advice. Always use proper risk management. Indicator

Strategy

Volatility Z-Score [NovaLens]Volatility Z-Score is a statistical volatility indicator that measures how far the current ATR deviates from its historical average, expressed in standard deviations. Built on the Z-Score method used by quantitative desks to detect anomalies, it self-normalizes across any asset and timeframe - no parameter guessing needed.
◉ HOW IT WORKS
Most traders watch ATR to measure volatility - but raw ATR numbers are meaningless without context. ATR = 50 tells you nothing unless you know the asset's history. Is that high? Low? Normal?
The Z-Score solves this by standardizing ATR against its own rolling distribution:
Z = (ATR_current - ATR_mean) / ATR_stddev
A Z-Score of +2 means current ATR is two standard deviations above the historical mean - statistically extreme. A score of 0 means volatility is exactly average. This is the same standardization method used across quantitative finance to detect regime changes and anomalies.
◈ HOW TO READ IT
• Z > +2 : Statistically extreme volatility. Breakout in progress or capitulation event. Consider tightening stops or waiting for mean reversion.
• Z between −1 and +1 : Normal volatility range. Trade your usual setups with standard risk parameters.
• Z < −2 : Unusually quiet market. Compression before expansion. Watch for pre-breakout positioning opportunities.
✦ USE CASES
• Filter entries - only take trades when volatility is in your preferred regime (e.g., avoid extreme Z for trend-following)
• Time exits - extreme Z-Scores often precede reversals or consolidation phases
• Risk management - scale position size inversely with Z-Score: smaller in high-vol, larger in low-vol
• Regime detection - sustained high or low Z indicates a volatility regime shift, not just noise
• Combine with trend tools - high Efficiency Ratio + low Z-Score = quiet strong trend about to expand
⚙ SETTINGS
• ATR Period - Period for Average True Range calculation. Higher values smooth the ATR, lower values make it more responsive to recent price action.
• Z-Score Lookback - Number of bars for computing mean and standard deviation of ATR. Longer lookback = more stable reference, shorter = faster regime detection.
△ LIMITATIONS
Z-Score assumes a roughly normal distribution of ATR values. In assets with structural volatility shifts (e.g., post-halving crypto), the lookback window may not capture the new regime quickly. Works best on liquid instruments with sufficient history. Not a directional signal - tells you about volatility magnitude, not trend direction.
⌁ NOTES
• Based on standard Z-Score normalization - a foundational technique in quantitative finance
• Validated against Python implementation (1.000 correlation via PyneCore)
• Open-source - read the code and verify the math
• Built for traders who want volatility context in standardized units, not raw ATR values Indicator

IBS Internal Bar Strength (Intraday)# IBS — Internal Bar Strength (Intraday)
### PulseWire Publication Description
*by imhurtin | theTRADINGDECK*
---
## What Is IBS?
**Internal Bar Strength (IBS)** measures where price closed *within* the current bar's range.
**Formula:** `IBS = (Close - Low) / (High - Low)`
The result is a value between 0 and 1:
- **IBS = 0** → Price closed exactly at the low (maximum weakness)
- **IBS = 1** → Price closed exactly at the high (maximum strength)
- **IBS = 0.5** → Price closed at the midpoint (neutral)
---
## How To Read It
| IBS Value | Meaning | Bias |
|-----------|---------|------|
| Below 0.3 | Closed in bottom 30% of range | Potential bounce / long setup |
| 0.3 – 0.7 | Closed near midrange | Neutral — no edge |
| Above 0.7 | Closed in top 70% of range | Potential fade / short setup |
**Green bar / background** = IBS in oversold territory (below 0.3)
**Red bar / background** = IBS in overbought territory (above 0.7)
**Triangle up** = IBS crossing back above 0.3 (bounce signal)
**Triangle down** = IBS crossing back below 0.7 (fade signal)
---
## When To Use It
IBS works best as a **confirmation tool** — not a standalone signal. Here's when it adds real value:
### ✅ LONG SETUP (Bounce)
Use IBS < 0.3 to confirm a long when:
- Price has sold off and is at or near a key support level (VWAP, PDL, ORB low, EMA)
- Market internals are neutral or turning bullish ( USI:TICK recovering, USI:ADD > -200)
- Price action shows a hammer, pin bar, or inside bar at support
- IBS crosses back above 0.3 = signal that sellers are losing grip
**Entry:** IBS crosses above 0.3 + candle body closes back above support
**Stop:** Below the low of the signal candle
**Target:** VWAP or next resistance level
---
### ✅ SHORT SETUP (Fade)
Use IBS > 0.7 to confirm a short when:
- Price has pushed into resistance (PDH, VWAP from below, ORB high, EMA)
- Market internals are neutral or turning bearish ( USI:TICK fading, USI:ADD < +200)
- Price action shows a shooting star, bearish engulfing, or doji at resistance
- IBS crosses back below 0.7 = signal that buyers are exhausted
**Entry:** IBS crosses below 0.7 + candle body closes back below resistance
**Stop:** Above the high of the signal candle
**Target:** VWAP or next support level
---
## What It Does NOT Do
- ❌ IBS alone is NOT a buy or sell signal — always confirm with price action + internals
- ❌ Do not trade IBS signals against the trend — if the trend is strongly down, IBS < 0.3 bounces fail
- ❌ Do not use in the first 5–10 minutes of market open — too much noise, IBS whipsaws
- ❌ Do not use on low-volume tickers — IBS requires meaningful price action within the bar
---
## Best Timeframes
| Timeframe | Use Case |
|-----------|----------|
| **2-minute** | Precise entry timing after signal forms on 5m |
| **5-minute** | Primary signal timeframe — best balance of signal vs noise |
| **15-minute** | Swing trade confirmation or higher timeframe context |
| **Daily** | Original IBS application — mean reversion swing trades |
---
## Recommended Workflow (Intraday / 0DTE)
1. **Mark your levels** — VWAP, PDH, PDL, ORB High/Low before the trade
2. **Check market internals** — USI:TICK , USI:ADD , USI:VOLD must support direction
3. **Watch for IBS extreme** — below 0.3 at support OR above 0.7 at resistance
4. **Wait for the cross** — IBS must cross BACK through the threshold (not just touch it)
5. **Confirm with price action** — candle body closing beyond the level seals it
6. **Enter with defined stop** — stop beyond the signal candle, minimum 1:1.5 R:R
---
## Settings
| Setting | Default | Description |
|---------|---------|-------------|
| IBS Length | 1 | Number of bars for IBS calculation (1 = current bar) |
| Smoothing (EMA) | 3 | Light smoothing to reduce noise — increase for smoother line |
| Overbought Level | 0.7 | IBS fade/short threshold |
| Oversold Level | 0.3 | IBS bounce/long threshold |
| Show Entry Signals | On | Show triangle markers on threshold crosses |
| Color Background | On | Highlight bars in extreme zones |
---
## Alerts
Two built-in alerts:
- **IBS Bounce Setup** — fires when IBS crosses above the oversold level
- **IBS Fade Setup** — fires when IBS crosses below the overbought level
Set alerts on your preferred ticker and timeframe. Recommended: SPY or QQQ on the 5-minute chart.
---
## Important Notes
This indicator is a **tool, not a strategy**. The edge comes from combining IBS with:
- Strong key levels (support/resistance)
- Market internals confirmation
- Clean price action setup
- Proper risk management
**No indicator replaces discipline.** Always define your stop before entry. If the setup doesn't meet all criteria — no trade is a good trade.
---
*Built for intraday traders. Stack the deck in your favor.*
*— theTRADINGDECK* Indicator

Flag Breakout Forecasts [AlgoAlpha]🟠 OVERVIEW
This indicator detects converging price channels — commonly called flags or wedges — directly on the chart using a zigzag-based pivot detection algorithm. It identifies three collinear pivot points on both the highs and the lows to confirm a valid channel, then monitors the channel in real time for a breakout.
Beyond just drawing the channel, the script assigns probabilistic forecasts to each active pattern. It uses the historical distribution of past breakout durations and directions to estimate the likelihood of an imminent breakout, whether that breakout will be bullish or bearish, and adjusts those estimates using live volume data accumulated inside the pattern.
A supplemental volume table and a net-volume gauge render alongside each detected pattern, giving traders a second lens into the supply-and-demand balance before a move resolves.
🟠 CONCEPTS
Zigzag — A filtered sequence of alternating swing highs and swing lows. Pivots are confirmed only after a user defined bars on each side, so shorter user defined values capture minor swings and larger values require more significant price moves.
Collinearity check — Given three pivot points, the script projects a straight line from the first to the third and measures how far the middle pivot deviates from it, expressed as a percentage of price. If the deviation falls below the tolerance threshold, the three pivots are treated as lying on the same trendline.
Converging channel — A pair of trendlines (one through swing highs, one through swing lows) where the gap between them narrows from left to right. This geometry distinguishes flags and symmetric wedges from parallel channels.
Early detection — When one trendline is confirmed but the other lacks a third pivot, the script uses the current running extreme (an unconfirmed potential pivot) as a temporary third point. The resulting line is drawn dashed and upgrades to solid when the pivot is confirmed.
Breakout confirmation — A break is logged after the close exits the projected channel boundary for two consecutive bars, or immediately when the breakout candle body extends well beyond the boundary and its body size is at least 3 standard deviations above the 20-bar mean body length.
Normal CDF approximation — Breakout duration probabilities are derived using the Abramowitz and Stegun rational approximation to the standard normal cumulative distribution function, applied to z-scores computed from the historical distribution of past breakout durations.
Net volume ratio — Bullish volume (up-close bars) minus bearish volume (down-close bars), divided by total volume, mapped to a −100 to +100 scale. Used to tilt the directional probability estimate away from the purely historical base rate.
🟠 FEATURES
Automatic channel detection — Channels are drawn the moment three collinear pivots are confirmed on each side with matching alignment and convergence.
• Solid lines for fully confirmed channels.
• Dashed lines for the side that is still waiting on a third confirmed pivot.
Probabilistic overlay label — Displayed above each active channel.
• P(break): probability that a breakout will occur soon, based on how the current pattern duration compares to historical durations.
• P(bull) / P(bear): directional probabilities derived from historical breakout directions and blended with live net volume.
Net volume gauge — A color-gradient vertical bar drawn to the right of the last candle, with a pointer showing whether up-close or down-close volume dominates the current pattern.
Volume statistics table — Shows bullish volume, bearish volume, net volume, total volume, ATR, and pattern duration for the most recent active pattern. Cell background intensity scales with volume magnitude.
Breakout signals — Arrow labels mark the breakout bar with the direction, total volume absorbed, and the number of bars the pattern lasted.
Background highlight — A subtle background color appears on the bar when a new pattern is first detected. To help users know the exact time the pattern was detected
🟠 HOW TO USE
Adjust len to match the swings you trade — lower values (3–5) for intraday patterns, higher values (10–20) for swing or position setups.
Tighten collinearity tolerance to 0.1–0.2% if you want only very clean trendline alignments; loosen it toward 1% if you want the indicator to catch more approximate formations.
Watch the dashed channel side — it signals an early, unconfirmed pattern. Treat it as a warning rather than a confirmed setup, and wait for it to turn solid before acting.
Check P(break) in the label — a reading above 70% means the current pattern has already lasted longer than most historical patterns, suggesting a resolution is statistically overdue.
Use P(bull) and P(bear) alongside the volume gauge — when P(bull) is elevated and the gauge leans bullish, the two signals agree on direction. Disagreement between them calls for extra caution.
Reference the volume table's net row — persistently positive net volume during a bearish-looking wedge can indicate absorption of selling pressure and a possible upside resolution.
Set alerts for "Pattern formed," "Bullish breakout," "Bearish breakout," and the strong-break variants to monitor multiple instruments without watching the chart continuously.
🟠 CONCLUSION
Flag Breakout Forecasts detects converging price channels using zigzag pivot collinearity and geometric validation, then layers on probabilistic duration and direction estimates derived from each instrument's own historical breakout data. The result is a self-calibrating pattern tool that combines structural chart analysis, volume profiling, and statistical inference in a single overlay. Indicator

A1 Value Turn Triple Mode v2.3 (Swing + Crypto)# A1 Value Turn Triple Mode v2.3 — Swing + Crypto
## Overview
The A1 Value Turn is a multi-layer confluence indicator designed to identify high-probability mean reversion entries on quality stocks and crypto assets that have pulled back significantly from their 52-week highs. It combines value band detection, moving average proximity, RSI momentum, volume confirmation, sector rotation, and IV rank filtering into a single signal system with a built-in 3-leg exit ladder.
Built for swing traders and options traders targeting 60–90 DTE calls or verticals on A-grade companies trading at a discount.
---
## How It Works
### 4-Layer Signal Gate
A full signal only fires when ALL four conditions align:
1. **Value Band** — Price is 40–60% (or 60–80% in Deep mode) below its 52-week high
2. **MA Proximity** — Price is within a configurable % of the 200-period SMA
3. **RSI Turn** — RSI is within the mode-specific range AND curling upward from the prior bar
4. **Volume Surge** — Current volume is at least 1.3x the 20-day average
Plus two optional confirmation layers:
- **Sector ETF confirmation** — The selected sector ETF RSI is also curling up and price is above its 50 MA
- **IV Rank filter** — Historical volatility rank is below your threshold, ensuring you are not overpaying for options premium
---
## Three Modes
| Mode | Value Band | RSI Range | Vol Mult | Target 1 |
|---|---|---|---|---|
| 40–60% off High (Swing) | 40–60% below 52W high | 40–70 | 1.3x | +20% |
| 60–80% off High (Deep) | 60–80% below 52W high | 35–70 | 1.3x | +35% |
| Crypto-Linked | Any | 25–75 | 1.1x | +50% |
---
## 3-Leg Exit Ladder
Every signal automatically calculates three exit targets with live R:R ratios:
- **Target 1** — Mode-specific % gain from entry (scale out 1/3)
- **Target 2** — 2x Target 1 (scale out 1/3)
- **Target 3** — The actual 52-week high (full recovery, scale out final 1/3)
Each target plots as a dashed horizontal line anchored to the signal bar. The ATR-based stop loss plots simultaneously so you know your risk before you enter.
---
## Signal States on the Chart
| Shape | Color | Meaning |
|---|---|---|
| Large triangle below bar | Mode color (aqua/orange/purple) | All layers confirmed — entry signal |
| Small triangle below bar | Faded orange | Stock + sector ready, IV rank too high — wait |
| Small triangle below bar | Faded gray | Stock + IV ready, sector not confirmed — wait |
| Gold circle above bar | Yellow | Bullish RSI divergence confluence bonus |
| Bar background tint | Mode color | Full signal bar highlight |
---
## Signal Label
Each confirmed signal prints a label showing:
- Entry price
- Target 1, 2, and 3 with % gain and R:R ratio per leg
- ATR stop loss price
- HV Rank % and current VIX reading
- Sector ETF RSI
- % off 52-week high, RSI, and volume ratio
---
## IV Rank Filter (New in v2.3)
Since PulseWire does not provide live options IV data in Pine Script, this indicator uses Historical Volatility Rank — the annualized standard deviation of daily log returns measured against its own 52-week high and low range. HV Rank and IV move together closely enough that HV Rank is the standard professional proxy used in Pine-based systems.
A separate VIX macro threshold adds a second layer — if the market fear index is above your set level, signals are suppressed regardless of individual stock HV.
When IV is too high, a pending orange triangle fires with a label showing exactly what threshold to wait for.
---
## Inputs
### Core Settings
- Lookback for 52W High (bars)
- Long MA Length
- RSI Length
- Max % Distance from MA
- Mode selection
### Display
- Show/hide table, labels, stop line, Target 2, Target 3
- ATR Length and Multiplier for stop calculation
### IV Rank Filter
- Enable/disable IV filter
- Max HV Rank % (default 50)
- Enable/disable VIX threshold
- Max VIX level (default 25)
### Sector Rotation
- Enable/disable sector confirmation
- Sector ETF ticker (XLK, XLV, XLF, XLY, etc.)
- Sector ETF MA length
---
## Alerts
Four alert conditions built in:
1. **Full Signal** — All layers confirmed, ready to enter
2. **Pending IV** — Stock and sector ready, waiting for IV to cool
3. **Pending Sector** — Stock and IV ready, waiting for sector confirmation
4. **Max Confluence** — Full signal AND bullish RSI divergence
---
## Recommended Use
1. Run a Finviz scan each morning filtering for large caps 40–80% off their 52-week high with above-average volume
2. Open each candidate in PulseWire with this indicator applied
3. Set your sector ETF to match the stock's sector
4. Wait for a full signal (large colored triangle)
5. Use the label to size your 60–90 DTE options position using the printed R:R ratios
6. Scale out 1/3 at each target
Best results on daily timeframe. Works on weekly for longer-horizon setups.
---
## Notes
- This indicator is for educational and informational purposes
- Past signals do not guarantee future results
- Always use proper position sizing and risk management
- HV Rank is a proxy for IV, not actual options implied volatility
---
*Built by MOR Trading Systems* Indicator

Indicator

Gravity Reactor [by Oberlunar]Gravity Reactor is a structural trading engine built around one central idea: price does not move only in trend or only in reversion, but continuously oscillates around a dynamic gravity center. This center is computed from the fast/mid/slow moving-average stack, and the script measures the gravity gap as the ATR-normalized distance between price and that centroid. From there, the model evaluates whether the market is in compression, directed expansion, or overstretched displacement.
The rationale is to distinguish between two very different situations that are often confused by conventional indicators. A move away from gravity can be the start of a real expansion, or it can be an exhaustion event ready to mean-revert. For that reason, Gravity Reactor does not rely on simple MA crosses or isolated momentum spikes. It combines gravity distance, stack alignment, distance velocity, volume pressure, and multi-timeframe agreement into a single structural score. This score is then interpreted through two operative regimes: Thrust, when compression releases into a confirmed directional move, and Snapback, when price reaches an extreme displacement and shows signs of absorption or rebalancing.
Visually, the script puts gravity in the foreground through lane heatmaps that display local gravity and higher-timeframe gravity states side by side, so the trader can immediately see whether the chart is aligned, fragmented, or overstretched across scales. The goal is to detect where the price stands relative to its internal market geometry and whether that displacement is being reinforced or rejected.
Oberlunar ◉✦ Indicator

Harmonic Resonance Field [JOAT]Harmonic Resonance Field
Introduction
The Harmonic Resonance Field is an open-source overlay indicator that combines dynamic range detection, Renko-style trend tracking, harmonic frequency analysis, and magnetic field visualization into a unified system for identifying consolidation zones, trend direction, and potential reversal points. It is designed for traders who want to understand where price is within its current range, how strong the prevailing trend is, and when conditions are ripe for a breakout or mean reversion.
Built with Pine Script v6, the indicator uses custom user-defined types for Renko state management, range detection, reversal signals, harmonic bands, magnetic fields, and resonance points.
Why This Indicator Exists
Range-bound markets account for a significant portion of trading time, yet most indicators are optimized for trending conditions. This indicator fills that gap by providing:
ADX-based range detection: Automatically identifies when the market is ranging versus trending using ADX with a configurable threshold, so traders know which strategy framework to apply
Multi-style band calculation: Offers four band calculation methods (ATR, Percentage, Standard Deviation, Harmonic) so traders can choose the volatility measure that best fits their instrument
Renko trend overlay: A smoothed Renko-style trend line that filters noise and shows the dominant direction without requiring a separate Renko chart
Harmonic frequency analysis: Uses sine-wave modulation to create bands that expand and contract with market rhythm, capturing cyclical behavior that static bands miss
Magnetic field visualization: Plots dynamic attraction/repulsion levels around the mean, helping traders visualize where price is likely to gravitate
Core Components Explained
1. Range Detection Engine
The indicator uses ADX to classify market conditions. When ADX falls below the configurable threshold (default 25), the market is classified as ranging, and the indicator highlights the range boundaries. When ADX rises above the threshold, the market is trending, and the indicator shifts focus to the Renko trend line and harmonic bands.
adxSmoothed = ta.rma(dx, adxLength)
isRanging = adxSmoothed < adxThreshold
During ranging conditions, the indicator calculates the highest high and lowest low over the range lookback period and draws a dynamic range box with upper, lower, and midline levels. This gives traders clear boundaries for mean reversion strategies.
2. Harmonic Band System
The band system supports four calculation styles:
ATR: Bands based on Average True Range multiplied by a configurable factor
Percentage: Bands at a fixed percentage distance from the mean
Standard Deviation: Bollinger-style bands using standard deviation
Harmonic: Bands modulated by a sine wave that creates rhythmic expansion and contraction
The harmonic mode is unique to this indicator. It calculates a phase and amplitude based on bar position and ATR, then modulates the band width with a sine function:
harmonicPhase = math.sin(bar_index * 2 * math.pi / bandLength) * 0.5 + 0.5
harmonicAmplitude = atrVal * bandMultiplier
bandWidth = harmonicAmplitude * (0.5 + harmonicPhase * 0.5)
This creates bands that breathe with the market's natural rhythm rather than remaining static or purely reactive.
Chart showing the Harmonic Resonance Field with harmonic bands expanding and contracting around price, Renko trend line, and range detection box during a consolidation period
3. Renko Trend Engine
Rather than requiring traders to switch to a Renko chart, this indicator calculates a Renko-style trend directly on the standard candlestick chart. The brick size can be set using ATR, a fixed percentage, or a static value. The Renko state is managed as a custom type that tracks the current level, direction, and brick boundaries.
When price moves by one brick size in the trend direction, the Renko level advances. When price reverses by the configurable reversal multiplier (default 2 bricks), the trend flips. The result is a stepped trend line overlaid on the chart that filters minor fluctuations and shows only significant directional changes.
4. Magnetic Field Visualization
The magnetic field creates a set of attraction levels around the mean price. These levels represent zones where price tends to gravitate based on the configurable field strength parameter. The field is calculated using the distance from the mean and the current ATR:
Strong attraction zone: Within 0.5x ATR of the mean — price tends to consolidate here
Moderate zone: 0.5x to 1.0x ATR from the mean — normal trading range
Weak zone: Beyond 1.0x ATR — price is extended and may revert
The magnetic field lines are drawn with gradient transparency, becoming more transparent as they move away from the mean, visually communicating the decreasing "pull" of the mean at greater distances.
5. Reversal and Resonance Detection
The indicator generates two types of signals:
Reversal signals: Triggered when price reaches the outer bands with momentum showing signs of exhaustion (RSI-based or rate-of-change based). These are plotted as directional markers on the chart.
Resonance signals: Triggered when multiple conditions align — price at a band extreme, ranging market detected, and volume above average. Resonance points represent higher-conviction mean reversion opportunities.
Visual Elements
Harmonic Bands: Upper and lower bands with gradient fill between them
Renko Trend Line: Stepped line showing the dominant trend direction
Range Box: Dynamic box highlighting the current consolidation range
Magnetic Field Lines: Gradient-colored attraction levels around the mean
Reversal Markers: Directional signals at potential turning points
Resonance Points: High-confluence mean reversion signals
Candle Coloring: Optional trend-based candle coloring
Dashboard: Displays trend direction, range status, band width, Renko state, and resonance count
Input Parameters
Range Detection:
Range Lookback (default 50)
ADX Length (default 14) and ADX Threshold (default 25)
Band Settings:
Band Style: ATR, Percentage, Standard Dev, or Harmonic
Band Length (default 20) and Band Multiplier (default 2.0)
Renko Settings:
Brick Size Style: ATR, Percentage, or Static
Brick Size (default 1.0) and Reversal Multiplier (default 2)
Magnetic Field:
Field Strength (0.1-2.0, default 1.0)
Visual Settings:
Show Candle Coloring, Gradient Fill, Dashboard, Glow Effects, Pulse Effects
How to Use This Indicator
Step 1: Check the dashboard for the current market regime. If the market is ranging, focus on the range box boundaries and magnetic field levels for mean reversion setups.
Step 2: In trending conditions, follow the Renko trend line. Stay with the trend as long as the Renko direction holds. A Renko reversal (direction flip) is a significant event that suggests the trend may be changing.
Step 3: Watch for price reaching the outer harmonic bands. In ranging markets, these represent potential reversal zones. In trending markets, they may indicate overextension.
Step 4: Look for resonance signals. These combine multiple conditions (band extreme + ranging + volume) and represent the highest-conviction mean reversion setups.
Step 5: Use the magnetic field levels as dynamic support and resistance. Price tends to gravitate toward the strong attraction zone near the mean.
Close-up showing reversal markers at band extremes with resonance signals highlighted during a ranging market, with the magnetic field gradient visible around the mean
Indicator Limitations
ADX-based range detection has an inherent lag. The transition from trending to ranging (and vice versa) is identified after it has already begun.
Harmonic bands use a fixed-frequency sine wave. Real market cycles are not perfectly periodic, so the harmonic modulation is an approximation.
Renko trend calculations on a candlestick chart are a simulation. They will not match a true Renko chart exactly due to differences in bar construction.
Reversal signals at band extremes do not guarantee reversals. In strong trends, price can ride the outer band for extended periods.
The magnetic field visualization is a conceptual tool for understanding mean reversion tendency, not a precise prediction of where price will go.
Performance may be affected on very low timeframes with many visual elements enabled. Consider reducing visual effects on sub-minute charts.
Originality Statement
This indicator is original in its synthesis of range detection, harmonic frequency analysis, and magnetic field visualization. While individual components (ADX range detection, Renko trends, Bollinger-style bands) are established concepts, this indicator is justified because:
The harmonic band mode introduces sine-wave modulation to create bands that rhythmically expand and contract, a method not found in standard band indicators
The magnetic field visualization provides a novel way to represent mean reversion tendency using gradient-based attraction zones
Combining Renko trend tracking with ADX range detection on a standard chart gives traders both trend-following and mean-reversion frameworks simultaneously
Resonance detection creates a multi-factor confluence signal by combining band position, range status, and volume conditions
The four-style band system (ATR, Percentage, StdDev, Harmonic) allows traders to adapt the indicator to different instruments and market conditions
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Range detection and band analysis are tools for understanding market structure, not guarantees of future price movement. Always use proper risk management. The author is not responsible for any losses incurred from using this indicator.
-Made with passion by officialjackofalltrades
Indicator

Indicator

Dynamic Median Momentum Oscillator [AlgoAlpha]🟠 OVERVIEW
This script provides a momentum oscillator that uses a median-based approach rather than traditional averages to find the center of price action. By calculating the distance between the current price and a rolling median (HLC3), it identifies how far the market has stretched from its historical equilibrium. The indicator is designed to filter out the noise typical of standard momentum tools, using a standardized range calculation to provide fixed overbought and oversold zones. It helps traders identify trend strength, potential exhaustion, and mean reversion opportunities across different market conditions.
🟠 CONCEPTS
The core of this tool is the Dynamic Median basis, which uses a rolling median of the HLC3 price to establish a "fair value" line. Unlike a simple moving average, the median is less sensitive to extreme price spikes, making the resulting oscillator more robust against outliers. To ensure the oscillator remains readable across different assets, the raw difference between price and median is standardized by the average candle range (EMA of High-Low). This normalization allows for the use of fixed thresholds (e.g., +/- 200, 250, 300) regardless of the asset's price. The median sets the context for the baseline, while the smoothed MCD and its signal line provide the timing for entries and exits.
🟠 FEATURES
Standardization feature to enable fixed overbought/oversold levels across any asset
Multi-component display: Fast (histogram), Slow (lines), and Super Slow (filled zones)
Reversion markers (triangles) indicating price returning from extreme levels
🟠 USAGE
Setup : Add the script to your chart and choose your preferred Display Mode. Use "All" to see the full picture or "Slow" for a cleaner view of trend direction. Ensure "Standardize" is checked if you want to use the built-in overbought/oversold bands effectively.
Read the chart : Look for the Smooth MCD (white line) crossing the Signal (orange line) for momentum shifts. Values above 0 indicate bullish momentum, while values below 0 indicate bearish momentum. Triangles appear at the top or bottom of the oscillator when price reaches extreme levels (300/-300) and begins to revert to the mean.
Settings that matter : The Basis Length determines how much historical data defines the "center" of the market; longer lengths are better for higher timeframes. Smoothing Length controls the reactivity of the main white line—increase this if you find the oscillator is giving too many false signals in choppy markets.
Indicator

DKJ H/L Levels 2.0Previous High & Low Levels — 4H | Daily | Weekly | Monthly
Price action trading, Support & resistance, Mean reversal.
Updated version of DKJ H/L Levels
A clean, minimal indicator that plots the previous high and low for four key timeframes — 4H, Daily, Weekly, and Monthly — directly on your chart.
Levels are displayed as horizontal lines extending left from the current bar, with price labels neatly aligned at the right edge. Designed to give you an immediate read on the most relevant institutional reference points without cluttering the chart.
Features:
Previous 4H, Daily, Weekly and Monthly highs and lows
Fully adjustable line width, style, and length
Customisable colours per timeframe
Label size and vertical position (above/below) controls
Built-in alerts for price crossing any level
Best used on: 4H charts and below — 30m and 1H being the sweet spot.
Setting alerts:
Right-click the indicator name on your chart and select Add alert, or open the Alerts panel and create a new alert
In the Condition dropdown, select DKJ H/L Levels
Choose Any alert() function call — this covers all timeframes and directions in one alert
Set your notification method and click Create
Each alert will fire once per bar and tell you exactly which level was crossed and in which direction.
Indicator
