Auction Regime Router Entropy Gate & Hurst MemoryAuction Regime Router — Entropy Gate & Hurst Memory
What it is
Every structure playbook fails in the wrong regime. Fading the value-area edge works when price is anti-persistent (stretches snap back); riding a breakout works when price is persistent (moves feed on themselves); and nothing structural works when the tape is noise. This tool measures two things — how much structure exists, and what kind it is — and routes to a plain-language answer: FADES VIABLE / BREAKOUTS VIABLE / STAND ASIDE. It decides which of your tools to trust, never buy or sell.
The two measurements (and how they work together)
Permutation entropy (Bandt–Pompe 2002) — the gate. It measures how disordered the recent price sequence is from the frequencies of ordinal patterns (which of the 6 orderings each price triplet takes). High entropy = all patterns equally likely = noise = no structural edge. The gate is self-calibrated: entropy is ranked against its own recent history, so "noisy" means noisy for this symbol and timeframe.
Hurst exponent (Hurst 1951; Mandelbrot) — the router. Memory via diffusion scaling: how the dispersion of K-bar returns grows with K. H > 0.5 = persistent → continuation regime; H < 0.5 = anti-persistent → reversion regime. Research supports the routing: mean reversion is empirically more probable and faster during anti-persistent periods.
The mashup logic is a hierarchy, not a mixture: the entropy gate overrides the Hurst read. If the tape is noise, the router says STAND ASIDE regardless of what H says — because a memory estimate on noise is meaningless.
The honesty steps
A dead zone around H = 0.5 (default 0.45–0.55): near a random walk the memory read is unreliable, so the router says MIXED rather than pretending. Practitioners commonly require a margin before activating a playbook; both thresholds are inputs.
A minimum-dwell filter (the standard anti-chattering design from switched-systems control): a new regime is announced only after it survives a set number of confirmed bars, so the read doesn't flip-flop bar to bar. The cost is that many bars of lag — stated, and adjustable.
Estimates are proxies from bar data with overlapping windows — descriptive of the recent past, not a prediction. The dashboard shows the state, how long it has persisted (regime age), how dominant it has been recently (stability %), and any pending regime with a countdown — nothing more.
How to use it
Add to any liquid symbol/timeframe; defaults suit intraday index futures. The script requests no external data of any kind, so it runs on every plan and every symbol.
Glance at the regime lane — the thin colored strip at the bottom of the pane: blue = continuation, violet = reversion, amber = noise, gray = mixed. The palette is deliberately direction-neutral — no green or red anywhere in regime coding, so nothing can be misread as a buy or sell.
The HTF STACK row shows the raw regime on three higher timeframes derived as multiples of the chart (defaults 3×, 5×, 15× — so a 5m chart reads 15m/25m/75m automatically, adapting to any chart). A ✓ in green = every timeframe agrees on the same actionable regime (strongest context). A ⚠ in amber = a higher timeframe reads NOISE or the opposite regime while the chart claims a playbook (weakest — reduce or wait).
Read the dashboard for detail: REVERSION → your value-area fade / band-reversion tools are in their element; CONTINUATION → your breakout / drive tools are; NOISE → the gate is closed, stand aside; MIXED → no clear routing, reduce. STABILITY shows how settled the read is; PENDING shows a forming regime with a countdown.
Regime-change tags print only on announced (dwell-confirmed) changes; alerts fire on entering each state.
Best used as the selector above your structure toolkit rather than as a standalone display.
What makes it original
Hurst and entropy oscillators exist. What this adds: (1) the hierarchy — a self-calibrated entropy gate that can veto the memory read, instead of two numbers side by side; (2) routing to auction playbooks in plain language (fade vs breakout viability), not a raw statistic; (3) honest dead zones, a minimum-dwell announcement filter, and stability/pending context instead of a binary flip at H = 0.500. It is a decision-hygiene tool for structure traders.
Concept credits
Ordinal-pattern (permutation) entropy — C. Bandt & B. Pompe (2002). Long-memory / rescaled-range analysis — H. E. Hurst (1951); fractal market framing — B. Mandelbrot. Regime-gated strategy selection — standard quantitative practice. Implementation and charting design are the author's own.
Important disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. Regime labels are descriptive statistics of recent bars; regimes change without warning and estimates are proxies. Validate independently and manage your own risk. Indicator

Adaptive Predictability Engine Entropy Gate, Regime RouterAdaptive Predictability Engine — Entropy Gate, Regime Router & Expert Committee
What it is
The Adaptive Predictability Engine is a governed decision framework, not another confluence average. It refuses to treat all market conditions as tradable. It applies a strict hierarchy: first it asks whether price is forecastable at all right now; if it is, it decides whether trend-style or reversion-style logic is appropriate; and only then does a small committee of transparent experts vote — with the committee continuously re-weighting itself toward whichever experts have been correct recently. When the market is unpredictable, the whole engine stands aside and shows nothing to trade.
It plots directly on price: long/short signals, the live entry/target/stop of the active trade, a plain-language dashboard, and an optional self-calibration panel that scores past signals in R-multiple expectancy (not just win rate).
Why these components are combined (mashup justification)
This is a deliberate, dependent stack — each layer conditions the next, so removing any one changes the layer below it. That is the difference between a governed engine and a bag of averaged indicators.
Predictability gate (permutation entropy + structure). Permutation entropy (Bandt–Pompe) measures the ordinal randomness of recent price across three time scales; this is blended with |Hurst − 0.5|, the distance of the market from a random walk, which is high for strong trends and strong mean-reversion. The blended predictability is percentile-ranked so the gate self-tunes per symbol and timeframe. If the tape is unpredictable, nothing downstream may fire. This is the master switch, and it is why the engine spends much of its time deliberately doing nothing.
Regime router (Hurst exponent). When structure exists, the Hurst exponent (generalized, via a structure-function slope) decides whether it is persistent (trend) or anti-persistent (mean-revert), and routes weight toward the appropriate family of experts rather than averaging trend and reversion logic together.
Expert committee (Hedge / multiplicative weights). Six deliberately diverse experts — price trend, volume-weighted price, order-flow delta, momentum exhaustion, volatility extreme, and range extreme — each cast a directional vote. Their weights update every bar by exponential regret (right experts gain influence, wrong ones lose it), with fixed-share regularization so no single expert can dominate and make the vote fragile.
Distribution-shift guard. If the recent return distribution moves materially versus a reference window, the engine freezes learning and cuts conviction until conditions settle, so stale weights don't drive trades through a regime change.
The output is a single decision = the regret-weighted vote of only the currently-appropriate experts, gated to zero whenever the tape is unpredictable.
How to use it
Add it to any liquid symbol and timeframe. Defaults are tuned for index futures (e.g. NIFTY) but every input is adjustable, and the Data source group lets you repoint price and volume for any market.
Watch the dashboard headline: LONG / SHORT / WAIT / STAND ASIDE. When a signal fires, the engine draws the entry, ATR target, and ATR stop so the action is concrete.
Treat the shaded background as a hard "do not trade" — the engine has judged the tape unpredictable.
Open the Edge calibration (advanced) panel to see, per market memory, the past R-expectancy of the engine's own signals versus a direction-matched baseline. Positive expectancy means the sample was profitable before costs; this is descriptive of the past, not a forward guarantee.
Use the Ablation (research) toggles to switch each layer off and see, on your own data, whether it earns its place.
What makes it original
Most published tools average indicators and hope. This one inverts the approach by asking whether to act at all before what to do, using information-theoretic predictability (permutation entropy) as a master gate, a memory estimate (Hurst) as a router, and online regret-minimization (Hedge) to arbitrate a diverse expert set — with built-in R-expectancy self-calibration so users can judge it honestly rather than on a cherry-picked screenshot. The order-flow expert reads finest-available lower-timeframe signed volume with automatic fallback. The coupling and governance order are the contribution; the individual estimators are classical and credited below.
Concept credits
Permutation entropy — Bandt & Pompe. Hurst exponent / long-range dependence — H. E. Hurst; Mandelbrot. Hedge / multiplicative-weights online learning — Freund & Schapire; Littlestone & Warmuth; Vovk. Efficiency/structure framing — Kaufman. Triple-barrier labelling and R-multiple expectancy — M. López de Prado. Wilson score interval — E. B. Wilson. Synthesis, governance design, and implementation are the author's own.
Important disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. No indicator has an inherent edge. The calibration panel is a descriptive summary of past behaviour on the current chart — not a backtest and not a forward prediction. Always validate independently, apply realistic costs and slippage, and manage risk. You are solely responsible for your trading decisions. Indicator

AI SuperTrend [PickMyTrade]THE PROBLEM WITH A FIXED MULTIPLIER
Every standard SuperTrend applies the same ATR multiplier across all market conditions — the same constant during a strong trending breakout, a narrow choppy range, and a volatility spike. A value calibrated for one regime is miscalibrated for the others. Most traders compensate by manually switching timeframes or parameters. This script automates that decision.
The question it asks: what if the ATR multiplier were selected from historical bars that most resembled the current market regime — matched by Hurst state and volatility rank — rather than set by the user as a fixed constant?
────────────────────────────────────────
THREE AI LAYERS
Layer 1 — Hurst Exponent (Regime Gate)
The Hurst Exponent is computed via Rescaled Range (R/S) Analysis. It measures the degree of long-range dependence (memory) in the price series:
H ≥ 0.55 → Persistent (trending) — SuperTrend active, signals enabled
H ≈ 0.50 → Random walk — candles turn gray, no signal generated
H ≤ 0.45 → Anti-persistent (mean-reverting) — signals suppressed
The Hurst gate is the first filter. Signals only fire when market structure is historically associated with persistence — not randomness or mean-reversion.
Layer 2 — Garman-Klass Volatility Rank
Garman-Klass (1980) estimates realized volatility from OHLC prices rather than close-to-close returns, capturing intrabar price range and making it more sensitive to volatility changes. The current reading is percentile-ranked against recent history (0–100%) and used as the second feature dimension for the KNN search.
Layer 3 — KNN Multiplier Optimizer
K-Nearest Neighbors searches a rolling memory bank of feature pairs from previous bars. For each current bar it finds the K most similar historical bars by Euclidean distance in that 2D feature space. From those neighbors it retrieves the ATR multipliers that were in effect — weighted by the profitability of the bar that followed. The result is the AI Multiplier: a context-aware value drawn from the most similar past conditions, not a fixed constant.
────────────────────────────────────────
WHAT YOU SEE ON THE CHART
Candle color — the defining visual. Orange = bull trend regime, blue = bear trend regime, gray = random walk or mean-reverting. The regime state is readable on every bar without checking the table.
Signals — ● (circle) marks trend flips with Hurst ≥ 0.65, the high-conviction threshold. ▲▼ (triangle) marks standard threshold crossings. No signal fires in gray (random or mean-reverting) regimes.
SL / TP lines — dashed lines drawn automatically at each signal bar, sized from current ATR × the AI Multiplier active at that bar.
Info table (top right) — live display of Hurst value, Regime label, Direction, AI Multiplier, Vol Rank, and KNN memory bar count. Shows WARMUP until KNN has stored enough bars to begin optimizing.
────────────────────────────────────────
HOW TO USE
A signal requires all three conditions to be true simultaneously:
KNN is warmed up (table shows ● LIVE)
Hurst confirms a trending regime (H ≥ Trend Threshold input)
Price is on the correct side of the EMA filter
Circle signals (●) indicate Hurst has exceeded 0.65 — stronger persistence than the standard threshold. Triangle signals (▲▼) are at the user-defined threshold. Gray candles indicate the market is not in a trending regime; reducing exposure or standing aside is appropriate during those periods.
The regime background shading (faint orange or blue fill) shows when the SuperTrend is in an active directional state.
────────────────────────────────────────
INPUTS
AI Engine — Hurst Lookback, KNN Neighbors (K), KNN Memory (bars), Trend Threshold, Mean-Revert Threshold
SuperTrend — ATR Length, Base Multiplier, Volatility Window, EMA Period
Visual — Bull/Bear colors, SL/TP lines toggle, SL ATR Multiplier, Risk:Reward ratio, Regime Background
Display — Zen Mode (hides labels and table), Show Info Table
ALERTS
Three alert conditions: Long Signal, Short Signal, Any Signal.
────────────────────────────────────────
NOTES
KNN requires warmup equal to the KNN Memory setting before the AI Multiplier activates. During warmup the base multiplier scaled by Hurst and volatility rank is used instead.
No repainting. All signals are confirmed on bar close. KNN stores lagged values only.
Garman-Klass citation: Garman, M. & Klass, M. (1980). On the Estimation of Security Price Volatilities from Historical Data. Journal of Business , 53(1), 67–78.
Indicator

Trend Persistence OscillatorTrend Persistence Oscillator
OVERVIEW
Most oscillators answer "is price stretched?" This one answers the prior question almost everyone skips: "is the market even in a state where a stretch should snap back?" It plots a rolling persistence exponent of price around the 0.5 line. ~0.5 is a random walk; above 0.5 the series is persistent (moves tend to continue → trending); below 0.5 it is anti-persistent (moves tend to reverse → mean-reverting). It is an analytical study of market state — not a directional signal and not a strategy.
WHY THESE COMPONENTS BELONG IN ONE SCRIPT (mashup rationale)
Three parts that chain into one testable idea — is a reversion likely here, and has that held before?
The persistence exponent classifies the regime (trending / random / reverting). Research finds price reverts to its mean significantly faster when the local exponent is anti-persistent, so a low reading is a green light for fades and a high reading is a warning that a reversion will likely fail.
A stretch z-score measures how far price sits from its rolling mean — the "is it extended?" half a regime read alone can't supply.
A fade flag arms only when both agree (anti-persistent regime and stretched), turning the research claim into a concrete, located event.
The calibration harness proves or disproves the claim on your instrument: it logs each fade and checks, a fixed horizon later, whether price actually reverted — reporting Edge versus the unconditional base rate.
A regime read without a stretch is just a state label; a stretch without the regime is a naive fade; either without calibration is an untested assertion. Chained, they answer one question end to end. Remove a part and the chain breaks.
HOW IT WORKS
The exponent is estimated by the structure-function (generalized-Hurst) method: for several lags, the windowed mean of |log-price(t) − log-price(t−lag)| scales like lag^H, so the exponent is the slope of log(mean|Δ|) against log(lag). The first-moment (absolute) form is used deliberately because it is the variant most robust to the heavy tails of financial returns — Monte-Carlo studies find the generalized-Hurst approach gives the lowest bias and variance of the common estimators on heavy-tailed data.
A short optional smoothing tames the noise inherent to short-window local estimates (very short windows are known to produce volatile readings and false alarms).
A stretch z-score and the regime thresholds combine into the fade flag.
The harness logs each fade and, a fixed horizon later, checks a ≥ k × ATR reversion.
HOW TO USE
Read the line for regime: in the green (reverting) zone, mean-reversion / fade setups have the wind behind them; in the gold (trending) zone, expect continuation and treat reversion setups with suspicion; near 0.5 the tape is effectively random. The fade dots mark reverting-and-stretched moments. Then read the Edge row — a regime filter only earns its keep if fades taken inside it beat the unconditional base rate. Context, never a standalone trigger.
Three visual styles are provided (Gradient area + glow / Histogram / Line).
UNIVERSAL ACROSS MARKETS
The price source is an input, so the engine runs on any instrument and timeframe. Defaults target intraday index futures (e.g. NSE NIFTY); change the source for any other market. The reading is self-normalising around 0.5, so the same regime bands work everywhere.
ORIGINALITY
The exponent itself is a standard public statistic, credited below. The original work is the assembly: a structure-function persistence estimator chosen for heavy-tail robustness and smoothed against short-window noise, gated against a stretch z-score into a located fade event, and tied to a forward base-rate calibration so the regime claim is tested on each instrument rather than asserted. It is a regime and validation tool, not a plain exponent plot. No third-party Pine code is reused.
CONCEPT CREDIT
The scaling exponent and rescaled-range analysis — Harold E. Hurst (1951). Fractional / self-similar processes and the generalized exponent — Benoit Mandelbrot. The structure-function (generalized-Hurst) estimator is the variant most robust to heavy-tailed financial data. The anti-persistence-anticipates-reversion application follows recent local-exponent mean-reversion research (2024). Not affiliated with, nor endorsed by, any third party.
HONESTY / LIMITATIONS
The exponent is an estimate from a finite window — it is noisy and lags, and short windows can raise false alarms (which is why a smoothing control is provided, on by default). A low reading is context, not a trigger. The Edge figures are in-sample, close-to-close, with overlapping forward windows and no costs — descriptive context, not a verified backtest. An Edge near zero or negative is the harness honestly reporting that the regime read isn't helping here; do not tune until it turns green — that is curve-fitting. Nothing here predicts direction.
DISCLAIMER
Research and educational tool only. NOT financial advice and NO guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script. Indicator

Lead-Lag Information FlowLead-Lag Information Flow
OVERVIEW
Correlation tells you two instruments move together. It cannot tell you who moves first. This indicator answers that question directly: it measures the net directional information flow between a reference symbol and the chart using transfer entropy — how much knowing the reference's last move reduces uncertainty about the chart's next move, beyond what the chart's own history already says, minus the same quantity in the other direction.
The result plots around zero. Positive = the reference leads the chart; negative = the chart leads the reference. A regime read (is the follower trending or chopping?) sits alongside it, because a lead is only worth acting on when the follower is in a state that lets the move pay off.
WHY THESE COMPONENTS BELONG IN ONE SCRIPT (mashup rationale)
Three parts, one question — is there exploitable lead-lag right now, and which way? Each closes a gap the others leave open:
Transfer entropy (net, in bits) answers the DIRECTION of information — who leads. It is model-free and captures nonlinear lead-lag that a correlation or linear regression misses, and netting the two directions cancels much of the small-sample bias that distorts raw entropy estimates.
The Hurst regime read answers whether a lead is tradeable: information flowing into a persistent (trending) follower is far more actionable than into a mean-reverting chop. The same lead means different things in different regimes.
The calibration harness answers whether it has actually worked here: it logs each lead-and-follow setup and, a fixed horizon later, checks whether the chart moved with the leader by at least k × ATR, reporting Hit %, Base %, and Edge.
Direction without a regime filter fires into noise; a regime read without direction is just a Hurst line; either without calibration is an untested assertion. Together they form one decision — lead exists (entropy) and the follower can run (regime) and it has paid before (Edge). Remove any one and the question is answered less completely.
HOW IT WORKS
Each series' bar-to-bar move is reduced to an up/down state.
Over a rolling window, state-transition frequencies estimate the transfer entropy in each direction (Schreiber's estimator); the plotted line is the net (reference→chart minus chart→reference), in bits. An optional Miller-Madow finite-sample correction subtracts the small-sample bias raw entropy estimates carry on short windows — a streaming-feasible step toward effective transfer entropy.
A Hurst exponent (a structure-function estimate around the 0.5 line) classifies the follower's regime as trending or reverting.
A follow setup arms when net flow says the reference leads and the reference has just moved; the calibration harness then measures whether the chart followed.
HOW TO USE
Read the line for direction — above the upper threshold, the reference leads; below the lower threshold, the chart leads — and read the dashboard for regime and the Edge row. A lead into a trending follower with a positive, matured Edge is the context this tool is built to surface. A lead into a reverting follower, or one where Edge sits near zero, is the engine telling you the lead-lag is not exploitable on this pair and timeframe. The background tints faintly green when the reference leads decisively and red when the chart leads. Treat all of this as context, never a standalone trigger.
Three visual styles are provided (Gradient area + glow / Histogram / Line); the gradient area's intensity scales with how strong the net flow is.
UNIVERSAL ACROSS MARKETS
The chart is the follower; the Reference symbol is the candidate leader — both are inputs, so the engine runs on any related pair in any market: cash index vs its futures, an index vs a lead constituent, an asset vs its dominant driver. Defaults pair NSE:NIFTY (cash) as the candidate leader against a NIFTY-futures chart; change the reference for any other pair. Use it on the timeframe at which you expect the lead-lag to operate.
ORIGINALITY
The techniques are public and credited below. The original work is the integration: a streaming two-state transfer-entropy estimator that nets the two directions and applies a Miller-Madow finite-sample correction to approximate effective transfer entropy (the documented fix for small-sample bias) without the shuffle step that a streaming script can't perform, gated by a Hurst regime classifier so a lead is only surfaced where the follower can act on it, and tied to a forward base-rate calibration so every follow setup reports its own realized Edge rather than an asserted one. No third-party Pine code is reused.
CONCEPT CREDIT
Transfer entropy — Thomas Schreiber (2000); effective transfer entropy and small-sample bias correction — Marschinski & Kantz (2002). Finite-sample entropy correction — Miller (1955) / Madow. Information entropy — Claude E. Shannon (1948). Hurst exponent — Harold E. Hurst (1951); long-memory framing — Benoit Mandelbrot. Not affiliated with, nor endorsed by, any third party.
HONESTY / LIMITATIONS
This is a coarse, two-state, windowed estimator. The finite-sample (Miller-Madow) correction and the netting of the two directions together approximate effective transfer entropy — they reduce the small-sample bias raw TE carries — but they are not a full surrogate-shuffle effective TE with significance testing (which requires reshuffling that isn't possible in a streaming script). The Edge figures are in-sample, close-to-close, with overlapping forward windows and no costs — descriptive context, not a verified backtest. An Edge near zero or negative is the harness honestly reporting that the lead-lag is not exploitable here; do not tune until it turns green — that is curve-fitting. The reference must be a genuinely related instrument for the read to mean anything. Nothing here predicts price.
DISCLAIMER
Research and educational tool only. NOT financial advice and NO guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script. Indicator

Strong Hurst Cycles | ProjectSyndicateHurst Cycles Pro decomposes the chart into a nest of harmonic cycles and projects when the next low of each one is due — so instead of guessing where a turn might land, you can see the cycle structure, read which cycles are lining up, and frame your analysis around the moments several of them are set to bottom together. It builds 4–8 nested cycles each one double the length of the cycle below it, following Hurst's harmonic principle, auto-sizes them to your timeframe, confirms every cycle low on a centred non-repainting window, and renders the whole structure as smooth scalloped arcs in a dedicated pane with a ranked turning-point strip beneath. A dashboard then translates every cycle into plain language — its period, how long since its last low, when its next low is projected, and whether it is currently rising or falling.
IMPORTANT NOTE: Run system on H1 H4 D1 timeframes.
🌀 NESTED HARMONIC CYCLES
4–8 cycles, each exactly double the length of the one below it (Hurst's harmonic doubling), drawn as smooth scalloped polylines. Longer cycles are given taller arcs, so amplitude scales with period the way real cyclic structure does. The base cycle either auto-scales to your timeframe — shorter on intraday, expanding on H4 / D1 — or you set it manually.
🔮 NEXT-LOW PROJECTION
Each cycle's next arc is projected forward as a dashed scallop, and the dashboard reports the projected time of every cycle's next low. The longest cycle anchors the structure; the shorter ones nest inside it.
💎 TURNING-POINT DIAMONDS
Two synchronised views of the same lows. A full-history diamond strip lives in the cycle pane — drawn with plotshape, so it covers ALL history with no 500-object limit, one row per cycle. Matching diamond stacks are pinned to the actual cycle-low candles on the price chart, stacked by cycle order. Independent size controls for each.
🥇 MAJOR SYNCHRONISED LOWS
When a chosen number of cycles bottom within tolerance of one another, the level is flagged as a MAJOR low and marked with a triangle in the pane — Hurst's synchronicity principle, where cycles tend to trough together. The alignment threshold and the confluence tolerance are both adjustable (tolerance can auto-size from the base cycle).
📊 CYCLE DASHBOARD
A pinned table grades the whole structure at a glance: for every cycle it shows the period, the last low (how long ago, in time), the next low (projected, in time), and the live phase (▲ up / ▼ down). A footer line projects the next major turn as a calendar date and time, with how many cycles are converging on it. Four corner positions.
🎯 DOMINANT-CYCLE TOOLS — VTL & FLD
Nominate a dominant cycle and the indicator overlays its classic Hurst tools onto the price chart: the VTL (Valid Trend Line) drawn through its last two lows and extended forward, and the FLD (Future Line of Demarcation), the price midline displaced forward by half the dominant cycle. Both are optional and force-overlaid onto price.
🔒 NON-REPAINTING BY CONSTRUCTION
Every trough is confirmed on a centred window — only after P/2 bars have closed on each side. A printed cycle low is locked in and never shifts as new bars arrive; only the still-forming right edge can update.
🎨 OWN PANE, LOCKED SCALE
The cycles and the diamond strip share their own pane on a single flat baseline, perfectly aligned, with the vertical scale locked so the arcs and rows don't jump around as detections land. Eight fully configurable cycle colours run short → long.
🔔 NATIVE ALERTS
Dedicated alerts for a major synchronised low forming and for the dominant cycle confirming a trough.
🔧 FULLY ADJUSTABLE
Number of cycles, auto vs manual base, arc heights and smoothness, history span and next-arc projection; diamond visibility, size and history span, plus pane row spacing and price stack spacing; confluence tolerance and the major-low alignment threshold; dominant-cycle selection and VTL / FLD toggles; dashboard position; and the full eight-colour cycle theme.
🚀 Works on gold (XAUUSD), silver, forex, crypto, stocks and indices, H1/H4/D1 TF.
────────────────────────
HOW TO USE IT — TWO WORKFLOWS
The cycles give you timing and context, not orders. Use them to decide WHEN and in WHICH direction to apply your own method.
TIME THE TURN — synchronised cycle lows
Use when several cycles are projected to bottom together.
Watch the dashboard's "Next low" column and the "Next major turn" footer for a date where multiple cycles converge.
The strongest windows are the MAJOR synchronised lows (triangle in the pane) — more aligned cycles, more weight.
Treat the projected date/time as a window to focus your analysis, not as an automatic entry.
Wait for your own price-action confirmation at the level before acting, and define risk beyond the structure that would invalidate the low.
READ THE TREND — dominant cycle, VTL & FLD
Use to judge whether a projected low is likely trend-resuming or just a counter-trend bounce.
Set the dominant cycle to the one that best fits the swings you trade.
The VTL frames the prevailing trend off the last two dominant lows; how price holds relative to it describes trend health.
The FLD acts as the dominant cycle's demarcation line; interactions with it describe momentum shifts of that cycle.
Combine the dashboard phase (▲ / ▼) with VTL / FLD context to weight the conviction of the next projected low.
Rule of thumb: many cycles bottoming together, with a fresh dominant-cycle phase, is the highest-conviction timing window. A lone short-cycle low against a falling dominant cycle is weaker context.
────────────────────────
⚠️ THIS IS NOT A SIGNAL SYSTEM. Hurst Cycles is an analytical timing-and-context tool built for advanced traders who already have a method. It projects cycle structure and probable turning windows — it does NOT generate buy / sell signals, and it makes no promise that a projected low will actually occur. Cycles drift, skip and occasionally invert in live markets, and the projection is only as good as the recent cyclic rhythm. Always combine it with your own strategy, price-action analysis and risk management to confirm setups. Past cyclic behaviour does not guarantee future results. Indicator

Hurst Exponent Strategy [Fast + Weekly]## Overview
The **Hurst Exponent Strategy ** is an advanced quantitative tool that calculates the Hurst Exponent ($H$) using the Rescaled Range ($R/S$) analysis. Instead of tracking directional momentum or price overlays, this indicator measures the **statistical memory** and fractal dimension of financial time series to detect market regimes.
It helps traders identify whether an asset is trending, mean-reverting, or trapped in a state of pure noise (chaos).
---
## The Mathematics of Market Regimes
The indicator evaluates the price action and plots values between 0 and 1, anchored to a theoretical center line of **0.5 (Random Walk)**:
- **$H > 0.60$ (Trend / Persistent):** The market possesses long-term memory. Price movements tend to be followed by movements in the same direction. Ideal for trend-following strategies.
- **$H < 0.45$ (Elastic / Anti-Persistent):** The market behaves like a rubber band (Mean Reversion). Price movements are consistently followed by reversals. Ideal for grid, mean-reversion, or range-bound strategies.
- **$0.45 \le H \le 0.60$ (Chaos / Random Walk):** The price action mimics a Brownian motion. Movements are random, noise is high, and directional edge is minimal.
---
## Dual Timeframe Framework
To avoid fighting macro market structures, this script calculates two separate Hurst metrics simultaneously:
1. **Fast Hurst (Cyan Line):** Calculated on the current chart timeframe. It responds quickly to micro-regime shifts, pinpointing when a consolidation is breaking into a trend or expanding into chaos.
2. **Macro Hurst (Orange Line):** Multi-timeframe execution locked exclusively to the **Weekly ("W") chart**. It acts as a structural filter, keeping you aligned with the true macro nature of the asset.
Both exponents feature an optional built-in **Smoothing filter (SMA)** to remove high-frequency mathematical noise without heavily lagging the structural reading.
---
## Real-Time Informative Legend
The top-right dashboard monitors the live mathematical output of both exponents:
- Displays exact numerical values down to 4 decimal places.
- Dynamically classifies the market state into **TREND** (Green), **ELASTICO** (Red), or **CAOS** (Gray) for instant visual confirmation.
---
Disclaimer: This tool calculates mathematical probabilities based on historical fractal dimensions. It does not provide entry/exit arrows or guarantee profits. Use it as a regime filter alongside your preferred execution strategy. Indicator

Hurst Fractal Regime Atlas [JOAT]Hurst Fractal Regime Atlas
Introduction
Hurst Fractal Regime Atlas estimates persistence and mean-reversion regimes using Hurst approximation, fractal dimension, variance ratio, phase coherence, and tension.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Hurst Approximation
Rescaled-range behavior estimates whether price is persistent, random-like, or mean-reverting.
2. Fractal Dimension
The Hurst estimate is converted into a roughness measure using dimension logic.
3. Multi-Horizon Coherence
Micro, meso, and macro Hurst readings are compared for agreement.
4. Adaptive Rails
ATR, volatility cluster, and Hurst distance expand or contract the fractal field.
fractalDimension = 2.0 - hurstBlend
Features
Hurst and fractal dimension estimates
Persistence, reversion, and mixed regimes
Coherence and tension scoring
Adaptive fractal rails
Breakout, mean, fade, and unstable events
Input Parameters
Fractal and short horizon windows
ATR length
Persistence and mean-reversion gates
Cooldown
Rails, candles, and HUD toggles
How to Use This Script
Use the HUD regime first. Persistence supports continuation interpretation; reversion supports fading extremes; high tension warns of disagreement.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
HFA is original in combining Hurst approximation, variance ratio, coherence, tension, and adaptive rails.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades Indicator

Statistical Mean-Reversion Engine [SMRE]## Statistical Mean-Reversion Engine (SMRE)
SMRE is an open-source mean-reversion indicator that combines a rigorous statistical core with up to eight optional confirmation layers, designed primarily for index-futures trading on intraday timeframes (1-minute through 1-hour).
### What it does
For every bar, SMRE fits an Ornstein-Uhlenbeck (OU) process to the recent price series via linear regression on lag-1 prices, yielding four outputs:
- **μ (the mean)** — the equilibrium price the series is reverting to
- **θ (mean-reversion speed)** — how strongly the series pulls back to μ
- **HL (half-life)** — how many bars it takes to revert halfway
- **σ_eq (stationary residual variance)** — used to z-score the current price
The current price's z-score against μ (the "OU Z") is the primary signal. When |OU Z| exceeds a configurable threshold, a mean-reversion entry is considered — but only after the script also confirms that the recent price series is genuinely stationary using three orthogonal statistical tests:
- **Hurst exponent** must be below 0.55 (i.e., the series is not persistently trending)
- **Augmented Dickey-Fuller** t-statistic must be below -2.86 (rejects unit root)
- **Variance Ratio** test at q=4 must be below 1.0 (variance grows sub-linearly with horizon)
If all four conditions pass, the L1 (statistical core) signal fires.
### Why the multi-layer structure (mashup justification)
A single OU-based mean-reversion signal works well in stationary regimes but degrades in trending or volatile conditions. SMRE addresses this by validating each potential entry through up to eight orthogonal confirmation channels, each measuring something the others do not:
- **L2 — Volatility Regime (6-state):** Classifies market state via VIX, ADX, and realized volatility. Suppresses signals during high-trend conditions (regime 6, "Spike") where mean-reversion historically fails.
- **L3 — Spot-Futures Basis (Kalman filter):** Tracks the deviation between actual and theoretical futures pricing. Statistically significant basis dislocations often resolve via mean-reversion.
- **L4 — Options Surface:** Computes ATM implied volatility from straddle pricing and a skew z-score from OTM put/call ratio. Optional; requires user to provide option symbols.
- **L5 — Microstructure:** Blends rolling VWAP and session-anchored VWAP z-scores with VPIN (a volume-clock toxicity proxy) and order-flow imbalance. Captures flow-based exhaustion.
- **L6 — Gamma Walls (GEX) OR Put-Call Ratio:** Two mutually exclusive options. GEX requires OI symbols at five strikes; PCR requires a single broker-published PCR feed. Both detect option-driven price magnets.
- **L7 — Dispersion:** Rolling correlation of index returns with its top 5 constituent stocks' returns. High dispersion (low correlation) penalizes signals; high cohesion boosts them.
- **L7b — Residual Dispersion:** Idiosyncratic residual z-scores (β-adjusted) per constituent. If 3 of 5 stocks show same-sign extreme residuals, the index is detached from constituents — strong mean-reversion candidate.
- **L9 — Cross-Asset Stress:** Sigma-normalized stress across USD/INR, DXY, and crude oil. Penalizes signals during cross-asset hedging cascades.
Each layer outputs a {direction, strength} pair. The Layer 8 fusion engine combines these via a weighted composite score (default weights: L1=0.28, L5=0.22, L3=0.18, L4=0.12, L6/L7b=0.10), then applies a regime multiplier (L2 × L7 × VRP × cross-asset × expiry), clamped to to prevent extreme compounding.
If the absolute composite score crosses one of three thresholds (0.25 / 0.40 / 0.45 by default), a signal is fired at Scalp / Swing / Session horizon respectively. A TCA cost filter then validates that the expected move (distance to μ) exceeds estimated round-trip transaction cost; otherwise the signal is suppressed.
### Originality
The author is not aware of any other public Pine script that implements the full OU-fit chain (mean, mean-reversion speed, half-life, stationary variance) together with all three stationarity tests (Hurst, ADF, Variance Ratio) directly in Pine v6 — every step is computed natively, no external library calls. Additionally, the session-anchored VWAP with running volume-weighted sigma bands, the rolling-beta residual dispersion across multiple constituents, and the Kalman-filtered futures-basis residual are original Pine implementations. The signal telemetry module (a 200-signal FIFO ring buffer with horizon × composite-magnitude bucket attribution) is also an original diagnostic tool.
### How to use
1. **Apply to an index futures chart.** Defaults are pre-configured for NSE NIFTY1! futures, but inputs allow any index — change the VIX symbol, spot/futures symbols, constituent symbols, and currency pairs.
2. **Read the compact dashboard.** It's a single 9-row table (default position: middle-right) showing only what you need to evaluate a setup:
| Row | What it shows | What it means |
|---|---|---|
| Title | Profile + OU window in use | Confirms which calibration is active |
| OU Z-Score | Z-score with half-life (HL) | How extended price is + how long mean-reversion typically takes |
| Stat Validity | H / ADF / VR pass-fail | Whether the recent series is actually stationary (all 3 must pass) |
| Regime | Volatility state + VIX value | Whether market conditions favor mean-reversion |
| Composite | Fused score × regime multiplier | The unified signal strength |
| Confluence | Layers agreeing (out of 6) | How many orthogonal signals support the direction |
| TCA Edge | Expected move in bps + PASS/FAIL | Whether the trade clears transaction costs |
| E / SL / TP | Entry, Stop, Target + Risk:Reward | The trade levels if a signal fires |
| **DECISION** | Direction · Horizon · Side | The actionable output (green=long, red=short, gray=neutral) |
3. **Trade levels and markers.** When a signal fires, entry/stop/target lines auto-plot on the chart. Stop is ATR-based (default 1.2× ATR); target is min(OU mean μ, entry + 2× ATR). Triangle markers plot below (long) or above (short) the bar — small for Scalp, medium for Swing, large for Session.
4. **Optional diagnostic.** A separate Signal Telemetry table (disabled by default; enable via the "Show Telemetry Dashboard" input) tracks the last 200 signals' outcomes (win = price touched μ, loss = stop hit, expired = timeout) and reports hit rate by horizon × composite-magnitude bucket. This is a backward-looking diagnostic, not a backtest.
### Recommended chart and timeframe
This indicator was developed and parameter-tested primarily on NIFTY1! futures. The OU window auto-mapping (1m→32, 2m→20, 5m→12, 15m→32, 30m→20, 1h→24) was selected empirically through parameter sweeps. Users on other instruments should expect to tune the OU window manually or accept the auto-mapped default as a starting point.
The indicator works on any timeframe between 1 minute and daily, though intraday timeframes (1m through 1h) are where the multi-layer confluence adds the most value.
### Important notes
- This is an **indicator**, not a strategy — no backtest equity curve is produced. The telemetry table is a descriptive measure of recent signal outcomes only.
- Many layers are **optional**. If you don't have symbols for options OI, just leave those inputs blank; the script will redistribute composite weight naturally across the active layers.
- Signals can fluctuate intra-bar before bar close, especially in real-time mode. For consistent behavior, evaluate signals on closed bars only.
- The default constituents (top-5 NIFTY weights) need to be changed in the L7 inputs to use this on a different index.
### Disclaimer
This indicator is published for educational and research purposes only. It is not financial advice, not an investment recommendation, and not a solicitation to trade. Past behavior of signals does not guarantee future results. Trading futures, options, and equities carries substantial risk of loss. You are solely responsible for your trading decisions. The author makes no representations about the accuracy, completeness, or suitability of this indicator for any particular purpose. Use at your own risk, and always consult a qualified financial professional before trading.
Indicator

Z-Score Probability Pro KAMA
Z-Score Probability Pro KAMA, v1.0 by Erika Barker
Hey guys, this is the successor to my original Z-Score Probability HMA Indicator, which you can still use if you prefer that one.
This is version 1.0 of the new rebuild, and it is a pretty big upgrade. The goal was to keep the statistical foundation that made the original useful, but make it more adaptive, cleaner, and better at understanding different market conditions.
What is new
1. Timeframe auto-adaptation
No more constantly re-tuning the indicator when you switch charts.
The lookback now automatically adjusts based on the chart timeframe, using a calendar-style window, defaulting to about 5 trading days. The dashboard also shows the effective lookback being used, so you always know what the script is calculating from.
It works from 1 minute charts all the way up to weekly charts.
2. Better smoothing logic
The original HMA was doing a lot of work at once. In this version, the baseline and the Z-score smoothing are separated so each one can do its own job better.
By default:
* Baseline: KAMA, great for adapting to noisy markets
* Z-score smoothing: ALMA, smoother and cleaner on the oscillator
HMA is still available if you prefer the original feel.
3. Modified Z-Score option
There is now an optional Modified Z-Score mode using MAD, median absolute deviation.
This is useful for markets with big outliers, fat tails, sudden spikes, crypto moves, small caps, and anything that tends to behave a little wild.
When this mode is turned on, the threshold bands automatically adjust.
4. Regime filter using Hurst logic (been needing out on this a lot lately on personal stuff)
This version attempts to classify the market as:
* Trending
* Mean-reverting
* Random
That matters because an extreme Z-score does not always mean the same thing.
In a mean-reverting market, an extreme Z-score can suggest exhaustion.
In a trending market, that same extreme can sometimes mean continuation or breakout strength.
This was one of the biggest things I wanted to improve from the original.
5. Divergence engine
The indicator now includes both regular and hidden divergence.
It can detect:
* Regular bullish divergence
* Regular bearish divergence
* Hidden bullish divergence
* Hidden bearish divergence
Divergences are confirmed using pivots, so they are non-repainting, but they will appear a few bars after the actual pivot. That is the tradeoff for confirmation.
6. Higher-timeframe confirmation
The script can pull Z-score confirmation from a higher timeframe.
You can use the automatic HTF mode or set it manually. HTF values only update after the higher-timeframe candle closes, so this is designed to avoid repainting.
7. Strong Buy and Strong Sell signals
Signals are based on a confluence score instead of just one condition.
The score looks at things like:
* Z-score reversal
* Divergence
* Baseline slope
* Market regime
* Higher-timeframe agreement
* Volume confirmation, when volume is available
You can choose the conviction level:
* Low
* Medium
* High
Medium is the default and should give fewer, cleaner signals.
8. Live dashboard
The dashboard shows:
* Detected timeframe
* Effective lookback
* Current Z-score
* Market regime
* Hurst value
* Higher-timeframe status
* Bull and bear scores
* Conviction threshold
* Last signal
You can move it to any corner of the chart.
9. More stable defaults
The defaults were chosen to be centered in stable performance zones, not over-optimized for one market.
Basically, I did not want this to be something that only looks good on one ticker, one timeframe, during one perfect backtest window.
10. Built in Pine v6
This version uses Pine v6 features, including dynamic higher-timeframe requests and confirmed-bar alert logic.
Repaint disclosure
This indicator is designed to avoid repainting, but there are a few things to know:
* Divergence and Strong Buy/Sell labels appear after pivot confirmation, default is 3 bars later
* Higher-timeframe confirmation only updates after the higher-timeframe candle closes
* Alerts fire on confirmed bars, not intrabar ticks
So, signals are delayed slightly by design, but that is what makes them confirmed.
How to use it
Beginner
Leave everything on default.
Watch the dashboard and look for:
* Strong Buy
* Strong Sell
Medium conviction is probably the best starting point.
Intermediate
Try the Modified Z-Score mode on crypto, small caps, or anything with sharp moves and big outliers.
Turn on Hidden Divergence if you like trading trend continuation setups.
Advanced
You can tune the component weights to match your own strategy.
The indicator is flexible, so you can make it more reversal-focused, more trend-following, or more confirmation-heavy depending on your trading style. Indicator

AlphaQuant Statistical Intelligence█ ALPHAQUANT STATISTICAL INTELLIGENCE (QSI)
Quantitative Market Quality Analysis
A quantitative market analysis tool that measures the statistical "quality" of market conditions using three core modules: Hurst Regime Engine , Shannon Entropy Flow , and Price Efficiency Ratio . These combine into a single QSI Composite Score (0-100) that rates whether current conditions are favorable for trading or not.
Free and Open Source.
█ THE CONCEPT: WHY STATISTICAL MARKET QUALITY MATTERS
Most indicators answer "which direction?" — QSI answers a different question: "Should I be trading right now?"
Markets alternate between regimes: trending, mean-reverting, chaotic, and efficient. QSI identifies these regimes in real-time so you can adapt your strategy accordingly. A trending Hurst regime favors breakout strategies. A mean-reverting regime favors fading. High entropy means the market is chaotic — reduce size. High efficiency means clean directional moves — increase conviction.
█ CORE MODULES
1. Hurst Regime Engine
Calculates the Hurst Exponent via Rescaled Range (R/S) analysis — a robust statistical method from hydrology adapted for financial markets.
H > 0.55 — Trending regime. Price has "memory" — breakout/trend-following strategies work well.
H = 0.50 — Random Walk. No statistical edge — the market is coin-flipping. Reduce size.
H < 0.45 — Mean-Reverting regime. Price has "anti-memory" — fade strategies work well.
2. Shannon Entropy Flow
Measures the information entropy of the return distribution using the Shannon Entropy formula from information theory.
High Entropy (>70) — Returns spread across many bins = chaotic, unpredictable. Reduce exposure.
Low Entropy (<30) — Returns cluster in few bins = ordered, predictable. Good for systematic strategies.
3. Price Efficiency Ratio
Measures directional efficiency by comparing net price movement to gross price movement over N bars.
High Efficiency (>30%) — Price moving cleanly in one direction. Trend-following conditions.
Low Efficiency (<10%) — Price chopping with no net progress. Avoid or use range strategies.
█ QSI COMPOSITE SCORE
The three modules combine into a single 0-100 score with fixed weights:
Hurst Edge: 40% — How strong is the regime signal?
Inverse Entropy: 35% — How ordered is the market?
Efficiency: 25% — How clean are the price moves?
Score interpretation:
> 70 — PRIME — Optimal conditions, full conviction
55-70 — FAVORABLE — Good conditions, normal sizing
40-55 — NEUTRAL — Mixed signals, proceed with caution
25-40 — CAUTION — Poor conditions, reduce size
< 25 — AVOID — Worst conditions, stay out
█ DASHBOARD
A compact, dark-themed info panel displaying:
QSI INDEX — Current composite value with regime label
HURST — Current Hurst exponent with regime classification
ENTROPY — Current entropy score with regime classification
EFFICIENCY — Current efficiency ratio with regime classification
WEIGHTS — Module weight distribution (H:40 E:35 F:25)
█ ALERTS (8 CONDITIONS)
QSI: PRIME Conditions — Composite entered prime zone (>70)
QSI: AVOID Conditions — Composite dropped to avoid zone (<25)
QSI: Conditions Improving — Composite crossed above 55
QSI: Conditions Deteriorating — Composite dropped below 40
QSI: Hurst → Trending — Hurst crossed above 0.55
QSI: Hurst → Mean-Reversion — Hurst crossed below 0.45
QSI: Entropy → Chaos — Entropy spiked above 70
QSI: Entropy → Order — Entropy dropped below 30
█ PRO VERSION
The PRO version adds:
Markov Transition Probabilities — Statistical prediction of next-bar direction
Correlation Intelligence — Auto-benchmark correlation with breakdown detection
Fractal Dimension — Higuchi fractal complexity analysis
Absorption Detection — High volume + low range = institutional activity
Trading Style Presets — Auto/Scalping/Daytrading/Swing/Position
Asset Auto-Optimization — Automatic parameter tuning per asset class
Profile-Adaptive Weighting — Dynamic composite weights based on style + asset
█ NON-REPAINTING
All calculations use confirmed bar data only. The Hurst Exponent is calculated from historical log-returns. Shannon Entropy uses a rolling window of past data. Price Efficiency uses closed bars only. No future data leakage. No repainting.
█ WORKS ON
Crypto, Forex, Stocks, Futures, Indices — any timeframe from 1 minute to Monthly.
█ DISCLAIMER
This indicator is for educational and informational purposes only. It does not constitute financial advice. Always do your own research and manage your risk. Past performance does not guarantee future results. Trading involves substantial risk of loss.
Indicator

Hurst Exponent Adaptive Supertrend [QuantAlgo]🟢 Overview
The Hurst Exponent Adaptive Supertrend identifies trending and mean-reverting market conditions by dynamically adjusting its sensitivity and band width based on the real-time persistence of price movement. It estimates the Hurst exponent through variance scaling to classify the current market regime, applies a Kalman smoother with a Hurst-scaled tracking gain to follow price with regime-appropriate responsiveness, and constructs a supertrend band whose width expands in choppy conditions and contracts in strongly trending ones. This allows traders to stay positioned through genuine trends while filtering out noise-driven whipsaws across any timeframe or instrument.
🟢 How It Works
The indicator's core methodology centres on a three-layer pipeline: regime classification via the Hurst exponent, adaptive price smoothing via a Kalman filter, and dynamic band construction that responds to the estimated market state.
First, the Hurst exponent is estimated by comparing short-run and long-run return variance over the configured lookback window. A lag-q variance is scaled against a lag-1 variance, and the ratio is log-transformed to produce a raw H value that is then clamped between 0 and 1:
var1 = ta.variance(close - close , active_h_period)
varq = ta.variance(close - close , active_h_period)
H_raw = math.log(varq / math.max(var1, 1e-10)) / (2.0 * math.log(active_h_lag))
H = math.max(0.0, math.min(H_raw, 1.0))
H values above 0.5 indicate persistent, trending behaviour. Values below 0.5 indicate mean-reversion or choppiness. This reading then drives every downstream calculation.
Next, a Kalman smoother tracks price using a gain that is amplified in trending regimes and suppressed in choppy ones, keeping the smoothed price line tight to momentum when it matters and sluggish when it does not:
adaptive_gain = math.max(math.min(active_kf_gain * (0.5 + safeH), 0.99), 0.01)
kf := na(kf ) ? close : kf + adaptive_gain * (close - kf )
Finally, the ATR-based band width is computed using a Hurst-scaled multiplier. When H is low (choppy market), the multiplier is large, widening the band to avoid false flips. When H is high (strong trend), the multiplier approaches the base value, keeping the band tight to price:
h_mult = active_atr_base + active_atr_hscale * (1.0 - safeH)
band = ta.atr(active_atr_len) * h_mult
The supertrend logic then ratchets the upper and lower bands in the direction of the prevailing trend, flipping state only when the Kalman-smoothed price crosses the opposing band. This prevents band drift from causing premature reversals during normal consolidation:
upBand := prevT == 1 ? math.max(kf - band, prevUp) : kf - band
dnBand := prevT == -1 ? math.min(kf + band, prevDn) : kf + band
trend := kf > prevDn ? 1 : kf < prevUp ? -1 : prevT
🟢 Signal Interpretation
▶ Bullish Trend (Supertrend Line Below Price with Bullish Color): When the Kalman-smoothed price crosses above the upper band, the indicator flips to a bullish state and the trailing line plots below price as a dynamic support level - the floor that price must decisively break before the uptrend is considered invalidated. The support level ratchets higher with each new bar, never pulling back, locking in the floor as the trend develops. In choppy regimes the band width is deliberately wide, meaning price can pull back significantly without breaching support, keeping traders positioned through noise-driven corrections that lack genuine bearish conviction.
▶ Bearish Trend (Supertrend Line Above Price with Bearish Color): When the Kalman-smoothed price crosses below the lower band, the indicator flips to a bearish state and the trailing line plots above price as a dynamic resistance level - the ceiling price must reclaim before a bullish reversal is confirmed. The resistance level ratchets lower with each new bar, tightening the ceiling as the downtrend develops. As with the bullish state, a wide band in low-H environments requires a substantial recovery move before the indicator reverses, allowing traders to hold directional bias through corrective bounces that stay within the noise threshold.
🟢 Features
▶ Preconfigured Presets: Three optimised parameter sets tailored to different trading styles and timeframes. "Default" delivers balanced trend detection for swing trading on 4-hour and daily charts, with moderate Kalman gain and band scaling suited to typical momentum cycles. "Fast Response" uses a higher tracking gain, shorter ATR window, and tighter base multiplier for intraday trading on 5-minute to 1-hour charts, producing earlier trend flips better suited to active traders. "Smooth Trend" applies a lower Kalman gain, longer ATR period, and wider band scaling for position trading on daily and weekly charts, confirming only major directional shifts with minimal false positives.
▶ Built-in Alerts: Two alert conditions enable automated monitoring of trend transitions without constant chart observation. "Bullish Trend Signal" triggers on the bar the indicator first flips to a bullish state, alerting for potential long entries. "Bearish Trend Signal" fires on the bar the indicator first confirms a bearish state, signalling potential short entries or long exits. Both alerts include the exchange, ticker, and timeframe in the alert message for immediate context.
▶ Visual Customisation: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) accommodate different chart themes and personal preferences, with coordinated bullish and bearish color schemes applied consistently to the trend line. When the Custom preset is selected, independent color pickers for bullish and bearish states allow full manual control over the indicator's appearance.
Indicator

SemiCircle Cycle Notation PivotsFor decades, traders have sought to decode the rhythm of the markets through cycle theory. From the groundbreaking work of HM Gartley in the 1930s to modern-day cycle trading tools on PulseWire, the concept remains the same: markets move in repeating waves with larger cycles influencing smaller ones in a fractal-like structure, and understanding their timing gives traders an edge to better anticipate future price movements🔮.
Traditional cycle analysis has always been manual, requiring traders to painstakingly plot semicircles, diamonds, or sine waves to estimate pivot points and time reversals. Drawing tools like semicircle & sine wave projections exist on PulseWire, but they lack automation—forcing traders to adjust cycle lengths by eye, often leading to inconsistencies.
This is where SemiCircle Cycle Notation Pivots indicator comes in. Semicircle cycle chart notation appears to have evolved as a practical visualization tool among cycle theorists rather than being pioneered by a single individual; some key influences include HM Gartley, WD Gann, JM Hurst, Walter Bressert, and RayTomes. Built upon LonesomeTheBlue's foundational ZigZag Waves indicator , this indicator takes cycle visualization to the next level by dynamically detecting price pivots and then automatically plotting semicircles based on real-time cycle length calculations & expected rhythm of price action over time.
Key Features:
Automated Cycle Detection: The indicator identifies pivot points based on your preference—highs, lows, or both—and plots semicircle waves that correspond to Hurst's cycle notation.
Customizable Cycle Lengths: Tailor the analysis to your trading strategy with adjustable cycle lengths, defaulting to 10, 20, and 40 bars, allowing for flexibility across various timeframes and assets.
Dynamic Wave Scaling: The semicircle waves adapt to different price structures, ensuring that the visualization remains proportional to the detected cycle lengths and aiding in the identification of potential reversal points.
Automated Cycle Detection: Dynamically identifies price pivot points and automatically adjusts offsets based on real-time cycle length calculations, ensuring precise semicircle wave alignment with market structure.
Color-Coded Cycle Tiers: Each cycle tier is distinctly color-coded, enabling quick differentiation and a clearer understanding of nested market cycles.
Indicator

Hurst Future Lines of Demarcation StrategyJ. M. Hurst introduced a concept in technical analysis known as the Future Line of Demarcation (FLD), which serves as a forward-looking tool by incorporating a simple yet profound line into future projections on a financial chart. Specifically, the FLD is constructed by offsetting the price half a cycle ahead into the future on the time axis, relative to the Hurst Cycle of interest. For instance, in the context of a 40 Day Cycle, the FLD would be represented by shifting the current price data 20 days forward on the chart, offering an idea of future price movement anticipations.
The utility of FLDs extends into three critical areas of insight, which form the backbone of the FLD Trading Strategy:
A price crossing the FLD signifies the confirmation of either a peak or trough formation, indicating pivotal moments in price action.
Such crossings also help determine precise price targets for the upcoming peak or trough, aligned with the cycle of examination.
Additionally, the occurrence of a peak in the FLD itself signals a probable zone where the price might experience a trough, helping to anticipate of future price movements.
These insights by Hurst in his "Cycles Trading Course" during the 1970s, are instrumental for traders aiming to determine entry and exit points, and to forecast potential price movements within the market.
To use the FLD Trading Strategy, for example when focusing on the 40 Day Cycle, a trader should primarily concentrate on the interplay between three Hurst Cycles:
The 20 Day FLD (Signal) - Half the length of the Trade Cycle
The 40 Day FLD (Trade) - The Cycle you want to trade
The 80 Day FLD (Trend) - Twice the length of the Trade Cycle
Traders can gauge trend or consolidation by watching for two critical patterns:
Cascading patterns, characterized by several FLDs running parallel with a consistent separation, typically emerge during pronounced market trends, indicating strong directional momentum.
Consolidation patterns, on the other hand, occur when multiple FLDs intersect and navigate within the same price bandwidth, often reversing direction to traverse this range multiple times. This tangled scenario results in the formation of Pause Zones, areas where price momentum is likely to temporarily stall or where the emergence of a significant trend might be delayed.
This simple FLD indicator provides 3 FLDs with optional source input and smoothing, A-through-H FLD interaction background, adjustable “Close the Trade” triggers, and a simple strategy for backtesting it all.
The A-through-H FLD interactions are a framework designed to classify the different types of price movements as they intersect with or diverge from the Future Line of Demarcation (FLD). Each interaction (designated A through H by color) represents a specific phase or characteristic within the cycle, and understanding these can help traders anticipate future price movements and make informed decisions.
The adjustable “Close the Trade” triggers are for setting the crossover/under that determines the trade exits. The options include: Price, Signal FLD, Trade FLD, or Trend FLD. For example, a trader may want to exit trades only when price finally crosses the Trade FLD line.
Shoutouts & Credits for all the raw code, helpful information, ideas & collaboration, conversations together, introductions, indicator feedback, and genuine/selfless help:
🏆 @TerryPascoe
🏅 @Hpotter
👏 @parisboy
Strategy

Indicator

Dominant Cycle Detection OscillatorThis is a Dominant Cycle Detection Oscillator that searches multiple ranges of wavelengths within a spectrum. Choose one of 4 different dominant cycle detection methods (MESA MAMA cycle, Pearson Autocorrelation, Discreet Fourier Transform, and Phase Accumulation) to determine the most dominant cycles and see the historical results. Straight lines can indicate a steady dominant cycle; while Wavy lines might indicate a varying dominant cycle length. The steadier the cycle, the easier it may be to predict future events in that cycle (keep the log scale in mind when considering steadiness). The presence of evenly divisible (or harmonic) cycle lengths may also indicate stronger cycles; for example, 19, 38, and 76 dominant lengths for the 2x, 4x, and 8x cycles. Practically, a trader can use these cycle outputs as the default settings for other Hurst/cycle indicators. For example, if you see dominant cycle oscillator outputs of 38 & 76 for the 4x and 8x cycle respectively, you might want to test/use defaults of 38 & 76 for the 4x & 8x lengths in the bandpass, diamond/semi-circle notation, moving average & envelope, and FLD instead of the defaults 40 & 80 for a more fine-tuned analysis.
Muting the oscillator's historical lines and overlaying the indicator on the chart can visually cue a trader to the cycle lengths without taking up extra panes. The DFT Cycle lengths with muted historical lines have been overlayed on the chart in the photo.
The y-axis scale for this indicator's pane (just the oscillator pane, not the chart) most likely needs to be changed to logarithmic to look normal, but it depends on the search ranges in your settings. There are instructions in the settings. In the photo, the MESA MAMA scale is set to regular (not logarithmic) which demonstrates how difficult it can be to read if not changed.
In the Spectral Analysis chapter of Hurst's book Profit Magic, he recommended doing a Fourier analysis across a spectrum of frequencies. Hurst acknowledged there were many ways to do this analysis but recommended the method described by Lanczos. Currently in this indicator, the closest thing to the method described by Lanczos is the DFT Discreet Fourier Transform method.
Shoutout to @lastguru for the dominant cycle library referenced in this code. He mentioned that he may add more methods in the future.
Indicator

Hurst Spectral Analysis Oscillator"It is a true fact that any given time history of any event (including the price history of a stock) can always be considered as reproducible to any desired degree of accuracy by the process of algebraically summing a particular series of sine waves. This is intuitively evident if you start with a number of sine waves of differing frequencies, amplitudes, and phases, and then sum them up to get a new and more complex waveform." (Spectral Analysis chapter of J M Hurst's book, Profit Magic )
Background: A band-pass filter or bandpass filter is a device that passes frequencies within a certain range and rejects (attenuates) frequencies outside that range. Bandpass filters are widely used in wireless transmitters and receivers. Well-designed bandpass filters (having the optimum bandwidth) maximize the number of signal transmitters that can exist in a system while minimizing the interference or competition among signals. Outside of electronics and signal processing, other examples of the use of bandpass filters include atmospheric sciences, neuroscience, astronomy, economics, and finance.
About the indicator: This indicator will accept float/decimal length inputs to display a spectrum of 11 bandpass filters. The trader can select a single bandpass for analysis that includes future high/low predictions. The trader can also select which bandpasses contribute to a composite model of expected price action.
10 Statements to describe the 5 elements of Hurst's price-motion model:
Random events account for only 2% of the price change of the overall market and of individual issues.
National and world historical events influence the market to a negligible degree.
Foreseeable fundamental events account for about 75% of all price motion. The effect is smooth and slow changing.
Unforeseeable fundamental events influence price motion. They occur relatively seldom, but the effect can be large and must be guarded against.
Approximately 23% of all price motion is cyclic in nature and semi-predictable (basis of the "cyclic model").
Cyclicality in price motion consists of the sum of a number of (non-ideal) periodic cyclic "waves" or "fluctuations" (summation principle).
Summed cyclicality is a common factor among all stocks (commonality principle).
Cyclic component magnitude and duration fluctuate slowly with the passage of time. In the course of such fluctuations, the greater the magnitude, the longer the duration and vice-versa (variation principle).
Principle of nominality: an element of commonality from which variation is expected.
The greater the nominal duration of a cyclic component, the larger the nominal magnitude (principle of proportionality).
Shoutouts & Credits for all the raw code, helpful information, ideas & collaboration, conversations together, introductions, indicator feedback, and genuine/selfless help:
🏆 @TerryPascoe
🏅 DavidF at Sigma-L, and @HPotter
👏 @Saviolis, parisboy, and @upslidedown Indicator

Indicator

Hurst Exponent (Dubuc's variation method)Library "Hurst"
hurst(length, samples, hi, lo)
Estimate the Hurst Exponent using Dubuc's variation method
Parameters:
length : The length of the history window to use. Large values do not cause lag.
samples : The number of scale samples to take within the window. These samples are then used for regression. The minimum value is 2 but 3+ is recommended. Large values give more accurate results but suffer from a performance penalty.
hi : The high value of the series to analyze.
lo : The low value of the series to analyze.
The Hurst Exponent is a measure of fractal dimension, and in the context of time series it may be interpreted as indicating a mean-reverting market if the value is below 0.5 or a trending market if the value is above 0.5. A value of exactly 0.5 corresponds to a random walk.
There are many definitions of fractal dimension and many methods for its estimation. Approaches relying on calculation of an area, such as the Box Counting Method, are inappropriate for time series data, because the units of the x-axis (time) do match the units of the y-axis (price). Other approaches such as Detrended Fluctuation Analysis are useful for nonstationary time series but are not exactly equivalent to the Hurst Exponent.
This library implements Dubuc's variation method for estimating the Hurst Exponent. The technique is insensitive to x-axis units and is therefore useful for time series. It will give slightly different results to DFA, and the two methods should be compared to see which estimator fits your trading objectives best.
Original Paper:
Dubuc B, Quiniou JF, Roques-Carmes C, Tricot C. Evaluating the fractal dimension of profiles. Physical Review A. 1989;39(3):1500-1512. DOI: 10.1103/PhysRevA.39.1500
Review of various Hurst Exponent estimators for time-series data, including Dubuc's method:
www.intechopen.com
Library

HurstExponentLibrary "HurstExponent"
Library to calculate Hurst Exponent refactored from Hurst Exponent - Detrended Fluctuation Analysis
demean(src) Calculates a series subtracted from the series mean.
Parameters:
src : The series used to calculate the difference from the mean (e.g. log returns).
Returns: The series subtracted from the series mean
cumsum(src, length) Calculates a cumulated sum from the series.
Parameters:
src : The series used to calculate the cumulative sum (e.g. demeaned log returns).
length : The length used to calculate the cumulative sum (e.g. 100).
Returns: The cumulative sum of the series as an array
aproximateLogScale(scale, length) Calculates an aproximated log scale. Used to save sample size
Parameters:
scale : The scale to aproximate.
length : The length used to aproximate the expected scale.
Returns: The aproximated log scale of the value
rootMeanSum(cumulativeSum, barId, numberOfSegments) Calculates linear trend to determine error between linear trend and cumulative sum
Parameters:
cumulativeSum : The cumulative sum array to regress.
barId : The barId for the slice
numberOfSegments : The total number of segments used for the regression calculation
Returns: The error between linear trend and cumulative sum
averageRootMeanSum(cumulativeSum, barId, length) Calculates the Root Mean Sum Measured for each block (e.g the aproximated log scale)
Parameters:
cumulativeSum : The cumulative sum array to regress and determine the average of.
barId : The barId for the slice
length : The length used for finding the average
Returns: The average root mean sum error of the cumulativeSum
criticalValues(length) Calculates the critical values for a hurst exponent for a given length
Parameters:
length : The length used for finding the average
Returns: The critical value, upper critical value and lower critical value for a hurst exponent
slope(cumulativeSum, length) Calculates the hurst exponent slope measured from root mean sum, scaled to log log plot using linear regression
Parameters:
cumulativeSum : The cumulative sum array to regress and determine the average of.
length : The length used for the hurst exponent sample size
Returns: The slope of the hurst exponent
smooth(src, length) Smooths input using advanced linear regression
Parameters:
src : The series to smooth (e.g. hurst exponent slope)
length : The length used to smooth
Returns: The src smoothed according to the given length
exponent(src, hurstLength) Wrapper function to calculate the hurst exponent slope
Parameters:
src : The series used for returns calculation (e.g. close)
hurstLength : The length used to calculate the hurst exponent (should be greater than 50)
Returns: The src smoothed according to the given length Library

Indicator

Indicator

[blackcat] L2 Ehlers Hurst Coefficient IndicatorLevel: 2
Background
John F. Ehlers introuced Hurst Coefficient Indicator in his "Cycle Analytics for Traders" chapter 6 on 2013.
Function
The Hurst coefficient is one way to attempt to get a handle on the slope of the power density of market data. The Hurst coefficient varies between 0 and 1, and is related to the α power coefficient as H = 1 − α/2. The Hurst coefficient is more estimated than computed. Dr. Ehlers found the estimate using the fractal dimension was the most practical for shorter-term market data. The Hurst coefficient is related to the fractal dimension as H = 2 − D. Dr. Ehlers would like to make it perfectly clear that the Hurst coefficient or the fractal dimension has no direct practical application to trading not only because it is an estimate, but also because it has no predictive value. These computations only reflect the general structure of the market, and the answer you get is dependent on your assumptions. For example, the Hurst coefficient changes dramatically with the length of data used in making the estimate.
The only user input is the length of data to be used. The number can be arbitrarily large if you have sufficient data. The results are critically dependent on the input data length selected. After declaring variables, the coefficients of a 20-bar SuperSmoother filter are computed. The computations of N1, N2, and N3 are as described in the previous section. The fractal dimension is then converted to the Hurst coefficient, which is subsequently smoothed in the SuperSmoother filter.
Key Signal
SmoothHurst --> Hurst Coefficient Indicator fast line
Trigger --> Hurst Coefficient Indicator slow line
Pros and Cons
100% John F. Ehlers definition translation of original work, even variable names are the same. This help readers who would like to use pine to read his book. If you had read his works, then you will be quite familiar with my code style.
Remarks
The 40th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy. Indicator
