Adaptive Anomaly Beast [MarketFragments]Adaptive Anomaly Mk II — Adaptive Cycle
A composite anomaly detector that combines an autoencoder reconstruction
error, true k-nearest-neighbor distance, and an Ehlers adaptive cycle
with self-tuning alpha. The indicator flags bars where the market's
structure differs from its recent self in a way that survives three
independent mathematical tests, and only inside a market regime that
supports it.
The main plot is a ratio. Values near zero mean normal market
structure. Values above 1.0 mean the reconstruction error has exceeded
its dynamic threshold. When that condition persists and the other
confirmations agree, the plot turns red and a composite anomaly
signal fires.
─────────────────────────────────────────────────────────────
HOW IT WORKS
─────────────────────────────────────────────────────────────
STEP 1 -- AUTOENCODER RECONSTRUCTION ERROR
Three features -- VWAP, activity density (volume per unit price
range), and true range -- are each independently z-score normalized
over a rolling window, smoothed through a Hull Moving Average,
compressed via a short-period average (encoder), and expanded back
through a mirror average (decoder). The absolute difference between
the normalized input and its reconstructed output is the per-feature
reconstruction error. The final error is the arithmetic mean of
the three, ensuring no single feature dominates by scale.
Large reconstruction error means the market's recent structure no
longer matches its own short-term pattern -- a compression failure.
STEP 2 -- TRUE K-NEAREST-NEIGHBOR DISTANCE
For each bar, absolute differences |close - close | are computed
across a lookback window. Five sequential passes extract the five
smallest distances without requiring sortable arrays -- each pass
finds the smallest distance strictly greater than the previous
pass's winner. The kNN score is the mean of those five.
High kNN score means the current bar is far from its nearest
neighbors in recent price history -- a local outlier.
STEP 3 -- EHLERS ADAPTIVE CYCLE WITH WIN-RATE HILL CLIMBING
A two-pole Ehlers cycle filter runs with a self-tuning alpha
coefficient. Each direction change of the cycle simulates a trade;
realized PnL is tracked across all simulated trades. When the
rolling win rate falls below 55% and the cycle's speed is
visibly mismatched to price -- defined as cycle delta greater
than 2x price delta (too fast) or less than 0.3x (too slow) --
alpha is nudged by one step in the corrective direction.
Alpha is bounded to and only adapts after
a minimum number of simulated trades (default 5) to avoid
chasing early noise.
Recent cycle direction changes within the lookback window count
as a confirmation signal.
STEP 4 -- REGIME FILTERS
Two independent regime gates must agree for an anomaly to fire:
Volume Break Hull Moving Average of Volume RSI > 49
Volatility Break RMA(TR, 5) > RMA(TR, 20) * 1.2
Without active regime expansion, anomaly signals are suppressed.
This prevents flagging during flat tape.
STEP 5 -- COMPOSITE ANOMALY SIGNAL
A signal fires when all of the following are true:
-- Autoencoder reconstruction error exceeds the dynamic threshold
-- EMA-smoothed error is above its rolling mean
-- Either kNN distance exceeds its threshold OR cycle has recently turned
-- Either volume break OR volatility break is active
-- All of the above persist for at least N consecutive bars (default 2)
When the signal becomes active, the main plot turns red, red
markers appear on the ratio line, and an alert fires on the
fresh signal bar.
─────────────────────────────────────────────────────────────
DYNAMIC THRESHOLD
─────────────────────────────────────────────────────────────
The anomaly threshold is computed as:
thresholdMean + thresholdAdjust * thresholdStd
where thresholdMean and thresholdStd are computed from the
reconstruction error series over a rolling lookback window.
During the configured active session (default 0930-1600 New
York), thresholdAdjust is raised by a configurable amount
to reflect that active hours produce more signal noise and
require a higher bar. Outside the session, thresholdAdjust is
reduced by the same amount.
The main plot divides reconstruction error by the adjusted
threshold, so crossings of 1.0 always mean "above threshold"
regardless of current market volatility.
─────────────────────────────────────────────────────────────
WHAT YOU SEE
─────────────────────────────────────────────────────────────
Ratio line Green below threshold, orange above, red when signal fires
Yellow dashed Threshold at 1.0
Cyan line EMA of ratio for slower confirmation
Red dots Marker circles on ratio line at each signal bar
Info table Anomaly state, regime, persistence, ratio, cycle direction,
adapted alpha, cycle win rate, session status
─────────────────────────────────────────────────────────────
SETTINGS
─────────────────────────────────────────────────────────────
Encoding Size 5 Autoencoder compression window
Decoding Size 5 Autoencoder decompression window
Threshold Lookback 20 Window for dynamic threshold stats
Threshold Multiplier 1.5 Standard deviations above mean
EMA Length for Error 15 EMA smoothing on error
Persistence (bars) 2 Bars signal must persist to fire
kNN Lookback 20 Bars searched for nearest neighbors
Cycle Smoothing Length 4 EMA length feeding the cycle
Alpha Min 0.05 Lower bound on adapted alpha
Alpha Max 0.45 Upper bound on adapted alpha
Alpha Adaptation Step 0.01 Per-bar nudge size
Fallback Alpha 0.20 Initial alpha and pre-adaptation value
Min Trades Before Adapt 5 Trades required before adapter activates
Cycle Turn Lookback 3 Bars within which a turn counts
Active Session 0930-1600 Session for threshold boost
Session Timezone America/New_York Configurable for non-US markets
Active Hours Threshold Bump 0.2 Threshold multiplier delta during session
Intended for 5-minute charts. A warning label appears on other timeframes.
─────────────────────────────────────────────────────────────
IMPORTANT NOTES
─────────────────────────────────────────────────────────────
-- This indicator has not been backtested or forward tested
-- No performance claims are made
-- The cycle's alpha adaptation is hill-climbing, not full grid
search; it converges slowly and may not converge in whipsaw
markets
-- The cycle's win rate is measured on its own direction changes
and can be statistically noisy at low trade counts
-- The active session default is US equity regular hours; non-US
markets require the session and timezone inputs to be updated
-- k is fixed at 5 in the implementation regardless of input
settings related to k
-- Shared as a research tool for community review
-- Results will vary by instrument, timeframe, and market conditions
-- This is not financial advice
-- Trading involves substantial risk of loss
-- Past results do not guarantee future performance
-- Use for educational and research purposes only
─────────────────────────────────────────────────────────────
LINEAGE
─────────────────────────────────────────────────────────────
Derived from "Beast Autoencoder-RNN for Anomaly Detection" by
marketframents/mcdon030 (originally for ThinkOrSwim). This
version rewrites the autoencoder normalization to be scale-
consistent across features, replaces a mean-absolute-deviation
score that was labeled kNN with a real k-nearest-neighbor
implementation, removes a regularization penalty that was
subtracted from activations (regularization belongs in a loss
function, not the output), removes injected random noise from
the encoder (denoising autoencoders need noise during training,
not during streaming inference), and adds the Ehlers adaptive
cycle layer with win-rate-driven alpha adaptation.
─────────────────────────────────────────────────────────────
Free for public use
Indicator

Indicator

Indicator

Liquidity Surge Forecast with Markov Chains [TechnicalZen]Clear direction from Markov Chains confirmed projections.
Publishing this v3 with all the enhancements users desired and more. Thank you for your feedback.
What This Is
A 3D liquidity-and-momentum visualization that tells you where the market is heading right now, how long the current state is likely to hold, and when the next regime change is expected — all backed by a 2nd-order Markov chain that learns from your chart's own history.
Two independent systems — Money Flow (MFI-driven) and Price Current (Hull-VWMA or signed-ADX) — render as layered dotted carpets inside a bounded 3D box. When both systems agree on direction AND the Markov chain confirms, a whale surfaces — 🐳 bullish, 🐋 bearish. Chop gets a shark 🦈. Sideways drift gets a crab 🦀. And when the Markov chain predicts an imminent regime transition, a small hatchling whale appears before confluence forms.
The Current State row tells you, in one line, exactly what to expect next.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built On
Money Flow Dynamics Forecaster 3D — the original 3D layered-terrain architecture, MFI/RSI momentum carpet, Hull-VWMA price current carpet, slope-extrapolated forecast, rider + whale system.
Same 3D engine. Same dual-system confluence as the foundation. Then: regime classification, Markov statistical learning, current-state intelligence, and a live win-rate scoreboard on top.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Clear Direction — At A Glance
Most indicators show you lines and ask you to interpret. This one tells you plainly, in a single dashboard row:
What regime you're in right now — 🐳 Bull, 🐋 Bear, 🦈 Chop-zone, or 🦀 Sideways
How long it's been held — in bars
Whether the regime is BALANCED or IMBALANCED — based on the Markov chain's next-bar probabilities
When the next regime change is expected — in bars, computed from the stay-probability
Which direction the market leans next — the highest-probability non-current state
Example readouts:
"Current State: 🐳 Bull held 5b · IMBALANCED — stay 68%, change expected in ~3b · next lean: 🦀 Sideways"
"Current State: 🦀 Sideways held 12b · BALANCED — change imminent · next lean: 🐳 Bull"
"Current State: 🐋 Bear held 2b · IMBALANCED — stay 82%, change expected in ~5b · next lean: 🦀 Sideways"
No interpretation required. You read the line, you know where you are, you know what to expect.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
New Features — And Why Each Exists
1. Current State intelligence row
Why: Confluence indicators tell you WHEN a signal fires. They don't tell you "how solid is the current regime," "is a change coming," or "how long do I have before conditions flip." The Current State row answers all three in one glance.
The balanced / imbalanced distinction matters most:
BALANCED — the three next-bar probabilities are close to 1/3 each. No clear direction. A regime change is imminent (could go anywhere). Trade lighter, wait for resolution.
IMBALANCED — one direction dominates. Regime has a preferred path. The stay-probability tells you how long it's likely to persist; the next-lean tells you which direction it will tilt when it does flip.
The expected-bars-to-change is a geometric distribution mean: 1 / (1 − P(stay)). If a regime has 80% stay probability, it's expected to persist ~5 more bars. If 33%, it's expected to flip in ~1.5 bars.
2. 2nd-order Markov chain regime predictor
Why: the original whale logic was reactive — it fires after confluence forms. Markov is predictive — it learns your instrument's transition habits and uses them to gate and anticipate whale signals.
Pure statistics, no black box:
2nd-order — predicts the next regime from the pair of previous regimes, not just one. Captures patterns like "Chop → Sideways → 68% Bull next" that a 1st-order chain would miss.
Laplace smoothing (α=1) — every transition count gets a +1 pseudocount before normalization. Prevents "never observed → 0% forever" failure. Standard in real statistics.
Exponential recency decay — newer transitions count more than old ones (default 0.995/bar). Markets drift; stale history shouldn't dominate current prediction.
Duration conditioning — separate transition matrices for "current state held <5 bars" vs "held ≥5 bars." Regimes behave differently after they've been running. Real statistical sub-populations.
Confidence gating — if the current context has fewer than 10 observations, predictions are flagged low-n . No fabricated probabilities.
Maximum useful substance without gimmick. 3rd-order Markov would need thousands of regime transitions per cell to converge — doesn't happen on typical charts. 2nd-order is the ceiling before diminishing returns.
3. Dual-layer regime classification — Chop-zone 🦈 vs Sideways 🦀
Why: prior versions treated "not trending" as a single category. But there are two fundamentally different kinds of non-trending market:
🦈 Chop-zone — violent range-bound circling. Detected via classic Choppiness Index . Often precedes a sharp breakout.
🦀 Sideways — slow drift, flat angles across close/high/low at both short and long periods. Detected via angle consensus . Often indicates accumulation or distribution.
Showing them separately lets you read which kind of non-trending you're in. Different implications, different decisions.
4. Hatchling whales — pre-signal pre-whales
Why: the Markov chain lets us anticipate confluence before it forms. When the current state is Sideways AND Markov predicts Bull (or Bear) with confidence above the hatchling threshold, a small whale appears at the mid-forecast position — a heads-up that confluence is probabilistically coming.
Full whale (size.huge at forecast edge) = confluence is here now.
Hatchling whale (size.small at forecast mid) = confluence is probably coming soon.
Better entries on regime changes.
5. Markov-gated whale confirmation
Why: sometimes projected-confluence fires, but the instrument's historical pattern says "from this context, the opposite is more likely." That's exactly the setup a trader wants the indicator to filter out .
The gate is permissive — Markov blocks a whale only if it's confident AND its argmax points the opposite direction. Uncertainty or agreement = pass through. Reduces false confluence without over-filtering.
6. Regime-aware 4-column win-rate dashboard
Why: knowing how much time the instrument actually spends in each regime is as actionable as the signals themselves.
Four parallel columns:
🐳 Bull — confluence signals and win rate
🐋 Bear — same, opposite direction
🦈 Chop-zone — CI chop events and % of bars
🦀 Sideways — angle-sideways events and % of bars
If your instrument spends 80% of bars in Chop/Sideways, confluence will be rare — adjust timeframe or instrument. If Markov shows low-n on most bars, the matrix isn't populated yet — wait for more history before trusting predictions.
7. Session-aware for futures
Why: NQ, ES, CL and other overnight-session futures stamp their daily bar at session start , which is the previous calendar evening. Naive `dayofweek(time)` reads NQ's "Friday session" as Thursday. The indicator uses `time_close("D")` — the close of the daily bar, always on the trading date — so regime classification is correct for both cash equities (TSLA, SPY) and overnight futures (NQ, ES). Same indicator, any asset class.
8. Honest evaluation — next-signal MFE or directional close
Why: "close-at-N-bars" is dishonest. Price can move 2×ATR favorably then retrace — close-at-N logs that as a loss. MFE logs it as what it actually was.
Each signal is held pending until the next signal fires. It's a win if either:
The close at next-signal bar was directionally favorable vs entry, OR
The Maximum Favorable Excursion between the two signals reached the ATR-scaled threshold (default 0.5×ATR at entry bar)
Either qualifies. Transparent. Computed live. Disclaimer embedded in the dashboard footer.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How to Read the Dashboard
┌────────────────────────────────────────────────┐
│ Liquidity Surge + Markov · Win Rate │
├────────┬────────┬─────────────┬───────────────┤
│🐳 Bull │🐋 Bear │🦈 Chop-zone │🦀 Sideways │
│42 sigs │38 sigs │7 events │12 events │
│31 wins │24 wins │120 bars │45 bars │
│73.8% │63.2% │23% │8.6% │
├────────────────────────────────────────────────┤
│Markov Forecast Next: 🐳 52% · 🦀 31% · 🐋 17% │
├────────────────────────────────────────────────┤
│Current State: 🐳 Bull held 5b · IMBALANCED │
│ stay 68%, change expected in ~3b · next: 🦀 │
├────────────────────────────────────────────────┤
│⚠ Not financial advice · Learned on chart hist │
└────────────────────────────────────────────────┘
Reading order:
Column data — how Bull/Bear signals have performed, how much time is spent in each regime
Markov Forecast Next — next-bar regime probabilities (with sample-size confidence)
Current State — the single-line answer to "where am I and what's next"
Footer — disclaimer + config
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How to Use
Load with defaults.
Wait for ~100-200 bars of history. The Markov matrix needs observations to learn.
Read Current State first. It tells you what to expect.
If BALANCED → expect a regime change, trade light.
If IMBALANCED + change in ~N bars → plan around that window.
Watch for 🐳 / 🐋 full whales at the forecast edge — confluence + Markov confirmed.
Watch for small hatchling whales at forecast mid-point — Markov's early prediction of confluence coming.
Respect 🦈 (chop-zone) and 🦀 (sideways). Don't fight the regime.
Tune Hatchling Threshold and Win Threshold (×ATR) to your instrument and style.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best Paired With Smart Candle Structures
This indicator answers whether and when to trust the flow. Smart Candle Structures answers where to act. Together: right place, right moment, measurable conviction, regime-aware.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
Time Span — past bars rendered + forecast horizon (default 15)
Momentum Source — MFI (default) or RSI
Oscillator Type — Hull-VWMA (default) or signed-ADX
Slope Lookback — bars for slope that fires whales (default 4)
Evaluation Window — bars after a signal to measure MFE (default 5)
Win Threshold (× ATR) — minimum favorable excursion as a multiple of ATR (default 0.5)
Gate Whale by Choppiness — master toggle for 🦈 / 🦀 filter
CI Length / CI Threshold — classic Choppiness Index tuning
Angle Short / Long Period — angle-based sideways lookbacks
Angle Trend / Sideways Threshold — angle degrees defining trending vs sideways
Use Markov Predictor — master toggle for the 2nd-order chain
Count Decay per Bar — recency weighting for Markov counts (default 0.995)
Hatchling Threshold — minimum Markov probability to fire pre-whale (default 55%)
Dashboard Text Size — Tiny / Small / Normal / Large / Huge
Camera — yaw / pitch / scales for the 3D view
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This is a visualization and analytical tool, not financial advice or a signal service. The Markov chain is trained on your chart's history — it describes what has happened on this instrument at this timeframe, not what will happen. Regime transition probabilities are learned estimates; past frequencies do not guarantee future outcomes. Markets are reflexive and can transition in ways the chain has never observed. Hatchlings, whales, sharks and crabs are visualizations of mathematical predictions — they do not constitute buy or sell recommendations. Trade with your own risk management. Every trade can lose.
The indicator echoes this disclaimer in its dashboard footer so you see it every time you read the chart. It's always there because it's always true.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Clear direction from learned regimes.
— TechnicalZen
Indicator

Indicator

ATR Daily Time Frame Display BoxATR Display Box
A clean, minimal ATR display that sits in the corner of your chart without getting in the way.
The indicator pulls ATR from the daily timeframe regardless of what chart you're on — so whether you're on a 1 minute, 5 minute, or any intraday timeframe, you're always seeing the true daily ATR value. No more manually switching timeframes or calculating inflated period numbers to approximate a daily ATR on lower timeframes.
Features:
Always references the daily timeframe for accurate ATR readings
Adjustable ATR period (7, 9, 14 or any value you choose)
Compact table display — stays out of the way of your chart
Fully customisable: position, background colour, text colour, border colour
Adjustable decimal places to suit any instrument
Best used for:
Gauging daily range on futures (ES, NQ, CL, GC etc.)
Setting realistic profit targets and stop distances based on true daily range
Quick reference during intraday trading without cluttering your chart
Works on any instrument and any timeframe. Indicator

Tether PrinterTether Printer — Stablecoin Mint/Burn Histogram
Tether Printer tracks changes in USDT market cap and displays them as a histogram. Green bars mean Tether minted new USDT — fresh liquidity entering the crypto ecosystem. Red bars mean USDT was burned or redeemed — capital leaving. The height of each bar shows the size of the print. When the printer runs hot, crypto tends to follow.
The logic is simple. The indicator pulls the USDT market cap via CRYPTOCAP:USDT and calculates the bar-over-bar change. A positive delta means more USDT exists now than it did one bar ago — that's a mint. A negative delta means supply contracted — that's a burn. No complicated math, no lagging signals, just raw supply changes visualized as a histogram.
A gold SMA line smooths the noise to reveal the trend. When the SMA is above zero and rising, Tether is net printing over time — a tailwind for crypto prices. When the SMA dips below zero, net redemptions are underway and liquidity is draining. The SMA length is configurable (default 14 periods) so you can tune it to your preferred timeframe.
The configurable threshold lets you filter for significant prints only. Set it to 100M on a daily chart and only mints or burns above $100 million will appear at full brightness — everything below gets dimmed. Triangle markers flag significant events so they're visible at a glance even when scrolling through history. Set it to zero to see every change.
The info table in the corner shows the current state at a glance: whether the last bar was a MINT or BURN and the dollar amount, current market cap, SMA trend value, consecutive mint or burn streak count, and net flow over the last 30 bars. A 12-bar mint streak with +3.8B net 30-day flow tells a very different story than a 5-bar burn streak with negative net flow.
The indicator is not limited to USDT. Change the ticker input to CRYPTOCAP:USDC to track Circle's stablecoin, or CRYPTOCAP:FDUSD for First Digital. Any stablecoin with a market cap ticker on PulseWire works.
Four alert conditions are included: significant mint, significant burn, any mint, and any burn. Set up alerts on a daily chart and you'll get notified the moment Tether fires up the printer.
Best used on a daily or 4-hour chart overlaid below BTC. When the histogram goes green and stays green, pay attention — the money printer is telling you something the price chart hasn't shown yet. Indicator

PGS - Pareto-Gaussian Skew [Zofesu]PGS - Pareto-Gaussian Skew is a trend gravity indicator built on two mathematical principles: the Gaussian distribution for detecting statistically significant price moves, and the Pareto principle for isolating the minority of moves that drive the majority of directional displacement.
The result is a single adaptive line that acts as a gravitational center — pulling toward institutional price displacement while filtering out the noise that makes standard moving averages lag or whipsaw.
─────────────────────────────────────
01 — What is PGS?
─────────────────────────────────────
PGS plots a gravity line that tracks where price is being pulled by significant institutional moves. Unlike a standard moving average, it does not react to all price movement equally. It reacts only when price moves beyond one standard deviation from its mean — the threshold where statistically normal noise ends and directional displacement begins.
Below that threshold, the line stays anchored to the mean. Above it, the Pareto Skew Factor shifts the gravity line toward the extreme, capturing the 20% of moves that drive 80% of the trend.
─────────────────────────────────────
02 — How it works
─────────────────────────────────────
The engine runs in three steps:
Step 1 — Mean and standard deviation
SMA and standard deviation are calculated over the lookback window (default 100 bars). This defines the Gaussian baseline — the statistical center of recent price behavior.
Step 2 — Extreme detection
The distance between current close and the mean is measured. If that distance exceeds 1x standard deviation, the move is classified as extreme. Moves within 1 standard deviation are treated as noise and ignored.
Step 3 — Pareto displacement
Extreme moves are multiplied by the Pareto Skew Factor (default 0.8). This skewed value is then smoothed with an EMA over a quarter of the lookback period and added back to the mean — producing the final gravity line.
Formula:
gravity = SMA(close, n) + EMA(d × extreme × skew, n/4)
where d = close − SMA(close, n), extreme = 1 if |d| > StDev else 0
─────────────────────────────────────
03 — Visuals
─────────────────────────────────────
Blue line — Pareto-Gaussian gravity line
Tension Cloud — fill between price and the gravity line.
Green fill = price above gravity line (bullish tension).
Pink fill = price below gravity line (bearish tension).
Note: Price Reference and PGS Reference appear in the indicator's plot list but are invisible on the chart. They are internal anchors required by Pine Script's fill() function and serve no visual or analytical purpose for the user.
─────────────────────────────────────
04 — Settings
─────────────────────────────────────
Smith's Memory (Lookback) — default 100
Number of candles used for the Gaussian baseline. Higher = slower, more stable line. Lower = faster, more reactive.
Pareto Skew Factor — default 0.8
Weight applied to extreme moves. Higher = gravity line shifts more aggressively toward institutional displacement. Lower = more conservative, stays closer to the mean.
─────────────────────────────────────
05 — How To Use
─────────────────────────────────────
Step 1 — Read the Tension Cloud
Green fill = price is above the gravity line. Bullish context — look for longs or hold existing positions.
Pink fill = price is below the gravity line. Bearish context — look for shorts or avoid longs.
Step 2 — Watch for gravity line crossings
Price crossing the gravity line from below = potential bullish shift.
Price crossing from above = potential bearish shift.
Step 3 — Use as dynamic support and resistance
In trending markets the gravity line acts as a dynamic S/R level. Price pulling back to the line in a green cloud = potential long entry zone.
Step 4 — Combine with higher timeframe context
PGS works best as a trend context filter alongside entry tools. It defines the direction — your entry indicator defines the moment.
Works on all asset classes: Indices, Forex, Gold, Oil, Crypto.
Best timeframes: H1, H4, D1. Indicator

Indicator

SMC Supply and Demand Zones [Dots3Red]SMC Supply & Demand Zones
This script automatically detects and visualizes Smart Money Concept (SMC) Supply and Demand zones using a three-factor confirmation model: base consolidation, impulse breakout, and volume surge .
How zone detection works
The indicator looks for a tight consolidation base (price range below ATR threshold) followed by a strong impulsive candle breaking out of that base with above-average volume. The direction of the breakout determines the zone type — bullish breakout creates a Demand zone, bearish breakout creates a Supply zone. The base range itself becomes the zone, as that is where institutional activity occurred.
Zone scoring (max 5)
Each zone is scored at birth based on three factors:
Base tightness — how compressed the consolidation was (1pt)
Impulse strength — how strong the breakout candle body was relative to ATR (2pts)
Volume confirmation — whether breakout volume exceeded the MA threshold (2pts)
Higher scoring zones render with stronger fill intensity.
Visual features
Supply and Demand zones themselves
Inactive zones (invalidated or max touches reached) can be shown or hidden via toggle
Proximity dashboard
A live table in the top-right corner shows all active zones ranked by distance from current price. Each zone displays its type, score, distance in ATR units, and status — INSIDE (gold), NEAR (orange), or AWAY (gray).
Zone invalidation
A zone is considered broken when price closes through it (configurable to wick-based) or when it has been touched too many times — both signals that the institutional order block has been absorbed.
Settings
All key parameters are tunable — base length, ATR multipliers, volume sensitivity, touch limits, score threshold, and proximity distance — making the indicator adaptable to any instrument and timeframe.
Indicator

Indicator

Indicator

Liquidity Surge Forecast with Win Rate [TechnicalZen]Publishing this v2 with Proven performance dashboard for scalpers.
What This Is
A 3D liquidity-and-momentum visualization with a built-in, MFE-verified win-rate dashboard.
Two independent systems — Money Flow (MFI-driven) and Price Current (Hull-VWMA or signed-ADX) — render as layered terrains inside a bounded 3D box. When both systems agree on direction, a whale surfaces: 🐳 bullish, 🐋 bearish. Every whale is tracked. Every outcome is scored. The dashboard prints the running win rate on your chart, on your instrument, on your timeframe. Live.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built On Money Flow Dynamics Forecaster 3D
This is the next iteration. Same solid confluence-detection engine, rebuilt rendering, and a performance dashboard on top for visual proof of how the system is doing.
Improvements over v1:
Win-rate dashboard with ATR-scaled MFE — every 🐳 / 🐋 signal is now tracked and scored. Each signal resolves when the next one fires, judged by directional close or MFE ≥ 0.5 × ATR. No more hand-waving about "does this actually work."
Seamless carpet terrain — layered strips share color between fill and outline. No visible seams; the terrain reads as one continuous surface.
Dotted wave contours — each HMA layer traces as a dotted line along its depth, like isobars on a topographic map. Wave shape is visible at a glance.
Depth fog gradient — far Z layers tint toward atmospheric navy-violet. Real 3D depth perception without extra wireframe.
Dotted wireframe, emphasized horizon — box edges and grids are dotted (quieter), while the Y=0 tide line is kept solid and bold as the one structural anchor that should stand out.
Unified ADX-mode terrain — ADX mode now renders a proper 12-layer terrain (v1 fell back to a single-ribbon). Both oscillator modes share identical visual grammar.
Cleaner defaults — Yaw −20°, Pitch 15°, axis markers off, back-wall grid off, mesh columns removed. Less visual noise out of the box.
Bug fixes — ring-buffer wrap when Slope Lookback > Time Span ; ADX-mode second-signal for the emoji confluence check; dead inputs cleaned up.
If you're coming from v1, interpretation is identical — same riders, same whales, same color semantics. The new dashboard simply gives you a way to measure how often confluence actually pays off.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Win-Rate Dashboard — Proof, Not Claims
Most indicators claim a success rate. This one measures it.
Every 🐳 / 🐋 signal is recorded at its first bar of entry and held pending — until the next signal fires. At that moment the indicator judges the previous signal by two criteria :
Directional close — did price close favorable at the next signal's bar? (bull: close > entry. bear: close < entry.)
MFE ≥ ATR threshold — did the favorable excursion between the two signals reach 0.5 × ATR (at the entry bar)? ATR multiplier is tunable.
Either criterion qualifies as a win. Direction alone is a win. MFE alone is a win. No fixed evaluation window — signals are judged against reality when the regime actually changes.
The threshold is volatility-relative : quiet instruments need small moves, volatile ones need larger moves. Always calibrated to the instrument, never arbitrary.
The dashboard shows:
Total bull and bear signals fired (resolved ones only — the most recent signal is pending until the next)
How many won
Rolling win rate, traffic-lit — green ≥ 60%, yellow 40–60%, red < 40%
Your ATR multiplier, printed right on the table
Why next-signal evaluation? Because fixed bar counts are arbitrary. A regime lasts as long as it lasts. When the next whale flips, the previous whale's journey is over — and that's the fair moment to judge it. Entry quality and regime persistence are both captured naturally.
The result: you don't trust marketing, you trust your own data . Every number is computed from your chart, right now, with your settings. Change the ATR multiplier, change the timeframe — the dashboard updates. This is how an indicator should prove itself.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Signal
Confluence requires agreement between two fundamentally different witnesses:
Money Flow — volume-weighted momentum (MFI). 20 Hull-smoothed layers (HMA 3 → HMA 60). Detects accumulation or distribution before price has to move.
Price Current — volume-weighted directional pressure (Hull-VWMA 2-bar slope, or signed-ADX HMAs). 12 layers. Detects committed displacement of price.
Money Flow leads. Price Current confirms. When both middle-layer slopes point the same way, a whale fires. That is the signal worth trading — not a crossover, not a threshold break, but two independent systems aligning.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
What You See
Layered dotted waves — each HMA smoothing horizon, stitched into a 3D carpet. Depth fog tints far layers into atmospheric haze for real 3D perception.
Forecast terrain — each layer slope-extrapolated with exponential decay into the future half of the box.
🏄♂ Surfer — rides the Money Flow leading edge (the impulse).
⛵ Sailboat — rides the Price Current leading edge (the trend).
🐳 / 🐋 Whale — surfaces at the forecast edge when both slopes agree. Confluence confirmed.
Dashboard — running win rate, always visible.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How to Use
Load with defaults. Switch chart to Volume Candles.
Check the dashboard — what is your current win rate on this instrument / timeframe?
Tune Win Threshold (× ATR) to match how strict you want the measurement to be — 0.3×ATR = loose, 0.5×ATR = balanced (default), 1.0×ATR = strict.
Watch for 🐳 or 🐋. They are rare by design.
On a whale, align with the direction. On no whale, stand aside. Let the dashboard keep scoring.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best Paired With Smart Candle Structures
This indicator tells you whether and when to trust the flow. Smart Candle Structures tells you where to act — order blocks, fair-value gaps, liquidity sweeps, BOS / CHoCH zones.
Together: the right place, at the right moment, with a measurable win rate behind it.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
Time Span — past bars rendered and forecast horizon (default 15)
Momentum Source — MFI (default) or RSI
Oscillator Type — Hull-VWMA (default) or signed-ADX
Slope Lookback — bars used to compute the slope that fires whales (default 4)
ATR Length — lookback for volatility scaling the win threshold (default 14)
Win Threshold (× ATR) — minimum favorable excursion between signals, as a multiple of ATR at the entry bar (default 0.5 × ATR)
Depth Fog Strength — atmospheric depth gradient on far layers (default 0.55)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This is a visualization and analytical tool, not financial advice or a signal service. The dashboard measures what has happened on your chart; it does not predict what will. Markets are reflexive. Past performance does not guarantee future results. Trade with your own risk management. Every trade can lose.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Confluence you can measure.
— TechnicalZen
Indicator

Indicator

Indicator

Indicator

Prism Intelligence SPX GEX Confluence and Sniper Entry System
Prism Intelligence SPX is a professional-grade overlay indicator built specifically
for SPX intraday and swing trading. It combines dealer gamma exposure (GEX) levels,
volatility regime analysis, and a 12-component confluence scoring system to identify
high-conviction long entries and precise exits — with zero signal noise between
setups.
The indicator is designed to be updated once before the open each session using
inputs from your GEX data provider or newsletter, then left to run autonomously
throughout the day.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ DATA SUBSCRIPTION NOTICE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This indicator fetches the following external symbols via request.security(). Some
may require a paid data subscription depending on your PulseWire account tier:
• CBOE:VIX — CBOE Volatility Index
• CBOE:VIX3M — CBOE 3-Month Volatility Index
• CBOE:VVIX — CBOE Volatility of Volatility Index
• CBOE:SKEW — CBOE SKEW Index
• USI:PCCE — CBOE Equity Put/Call Ratio
• USI:ADVN.NY — NYSE Advancing Issues
• USI:DECL.NY — NYSE Declining Issues
If any of these display as N/A in the dashboard table, check your PulseWire data
permissions under Profile → Manage Plan → Data.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ DISCLAIMER
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This indicator is provided for informational and educational purposes only. It does
not constitute financial advice, a recommendation to buy or sell any security, or a
guarantee of any particular outcome. All trading involves risk, including the
possible loss of principal. Past signal performance does not guarantee future
results. You are solely responsible for your own trading decisions. Always conduct
your own research and consult a qualified financial advisor before making any
investment decisions.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW IT WORKS — THREE-LAYER ARCHITECTURE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
LAYER 1 — MACRO REGIME CONTEXT
A 12-point confluence score is calculated from a combination of session inputs and
auto-fetched market data. The score determines whether conditions favor aggressive
positioning, cautious positioning, or staying flat. A score of 9 or higher with
price above the HVL (gamma flip level) is required for any long signal to activate.
LAYER 2 — LOCAL TREND FILTER
The MA9 slope and price position relative to MA9 are evaluated on every bar. Long
signals are fully suppressed when short-term momentum is declining — this prevents
buying into intraday downtrends even when the macro score is green.
LAYER 3 — PRECISION ENTRY TRIGGER
Within the right macro and trend context, signals fire on specific price-action
events: MA20 reclaims, MA9 reclaims, opening range momentum confirmation (bars
3–8 of the session), HVL reclaims, and key level bounces. Exits fire on MA20
breaks or HVL loss.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SIGNALS ON CHART
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔺 TEAL TRIANGLE — Sniper Long (below bar)
Highest conviction long entry. Score ≥9, above HVL, local uptrend confirmed,
triggered by MA20 reclaim, HVL reclaim, opening momentum confirmation, or key
level bounce (HVL / Put Wall / Lower Band).
🔺 LIME TRIANGLE — Aggressive Long (below bar)
Faster entry off MA9 reclaim in the same high-score context. Suitable for
momentum continuation or scalp trades. Fires only when not already covered by
a Sniper Long on the same bar.
◆ YELLOW DIAMOND — Caution (below bar)
Score 6–8 with valid MA reclaim and local uptrend. Setup is valid but conviction
is lower — consider reducing size or using tighter stops.
🔻 RED TRIANGLE — Exit (above bar)
MA20 broken in a high-score regime, or HVL broken at any score, or confluence
score collapsed below 6. Get flat or tighten stops immediately.
✕ RED X — HVL Breach (above bar)
Price crossed below the gamma flip level. Regime may be shifting bearish — treat
all long exposure with caution until price reclaims HVL.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
AUTOMATIC LEVEL OVERLAY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
All levels extend right with labeled price callouts. No extra input required.
DAILY EXPECTED MOVE ±1σ (purple dashed)
Derived from VIX using the standard dealer pricing formula:
prev_close × (VIX / 100) / √252
Upper and lower bands represent the 1-standard-deviation daily range that options
dealers are pricing. Price reaching either band mid-session is a natural
mean-reversion reference and often marks an intraday exhaustion point.
OPENING RANGE HIGH / LOW (yellow dotted)
High and low of the first N bars of RTH (default 6 bars = 30 minutes on a 5-min
chart, configurable in settings). OR High breakout signals momentum continuation;
OR Low breakdown signals potential intraday reversal. Among the most reliable
intraday reference levels for SPX specifically.
PREVIOUS DAY HIGH / CLOSE / LOW (silver dashed)
Non-repainting confirmed daily OHLC. PDH and PDL define the overnight reference
frame and are key levels for gap analysis. PDC is the primary overnight positioning
level — price often gravitates here when the session lacks a directional catalyst.
MANUAL SESSION LEVELS (drawn from your inputs each session)
• Call Wall (red dashed) — Primary dealer call resistance strike
• Put Wall (green dashed) — Primary 0DTE dealer put support strike
• HVL (orange solid) — Gamma flip level / regime boundary
• Risk Trigger (teal solid) — Primary swing model upside target
• Lower Band (blue dotted) — Swing model downside support
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
BACKGROUND ZONE COLORING
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Faint teal — Score ≥9 and above HVL. Full green light environment.
Faint yellow — Score 6–8 and above HVL. Cautious but tradeable.
Faint red — Price below HVL. Danger zone — long bias suspended.
Colors apply only to confirmed closed bars and do not fill future bars.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DASHBOARD TABLE (top-right corner)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
All 20 rows update in real time. Color-coded status dot on each row.
MANUAL INPUTS (update before the open each session):
Regime CONSTRUCTIVE / TRANSITIONAL / CONTESTED / BEARISH
Q-Score MenthorQ composite score 0–12
Net GEX Net dealer gamma in billions (positive = pinning environment)
Call Wall Primary dealer call resistance strike
Put Wall Primary 0DTE put support strike
HVL Gamma flip / regime boundary
Risk Trigger Primary swing model upside target
Lower Band Swing model downside support
AUTO-CALCULATED (live, no input required):
VIX Spot implied volatility + compressing/expanding status
Term Struct CONTANGO (VIX < VIX3M) or BACKWARDATION — regime indicator
VRP Volatility Risk Premium (VIX minus 30-day HV annualized)
IV Rank VIX percentile over trailing 252 bars
VVIX Vol-of-vol — green below 100, red above 110
SKEW Tail risk — green below 130, red above 140
PCCE Equity put/call ratio — green above 0.80 (contrarian long)
CTA Proxy Price vs MA20/50/200 structure (0–4 long signals)
NYMO NYSE McClellan Oscillator (calculated from ADVN/DECL)
Entry Score Total confluence score /12 with teal/yellow/red color coding
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MANUAL INPUTS — FULL REFERENCE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Input Range Description
─────────────────────────────────────────────────────────────────
Regime 4 options CONSTRUCTIVE (+2), TRANSITIONAL (+1),
CONTESTED (0), BEARISH (0)
Q-Score 0–12 MenthorQ composite score
Net GEX (B) any Net gamma in billions. Positive = dealer
pinning, negative = dealer amplifying moves
Call Wall price Largest dealer call OI strike (resistance)
Put Wall price Largest 0DTE dealer put OI strike (support)
HVL price Gamma flip level — the most important level.
Above = dealers buy dips; Below = dealers
sell rallies
Risk Trigger price Primary swing model upside target
Lower Band price Primary swing model downside support
CTA Z-Score -3 to 3 CTA equity positioning z-score (MenthorQ)
L/S Barometer 0–0.5 Long/short vol barometer (low = less hedging)
Vol Control any Vol control fund ratio (≤1.05 = re-entry zone)
Expiry 3 options MONTHLY / WEEKLY / NONE (context only)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CONFLUENCE SCORING — HOW POINTS ARE ASSIGNED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Component Max Condition
──────────────────────────────────────────────────────────────────
Regime 2 CONSTRUCTIVE=2, TRANSITIONAL=1, else 0
Q-Score 2 ≥10=2, ≥7=1, else 0
Net GEX positive 1 GEX > 0
VIX compressing 1 VIX < MA10 < MA20
Term contango 1 VIX < VIX3M
VVIX calm 1 VVIX < 100
SKEW not extreme 1 SKEW < 135
PCCE elevated 1 PCCE > 0.80 (contrarian long)
CTA constructive 1 CTA Z-Score > 0.5
Low hedging demand 1 L/S Barometer < 0.20
Vol control entry 1 Vol ratio ≤ 1.05
Positive breadth 1 NYMO > 0
──────────────────────────────────────────────────────────────────
TOTAL 12
Score ≥9 + above HVL → Sniper Long eligible
Score 6–8 + above HVL → Caution Long eligible
Score <6 or below HVL → No long signals
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SETTINGS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Opening Range bars (default 6):
Adjust for your timeframe —
5-min chart: 6 bars = 30 min OR, 3 bars = 15 min OR
1-min chart: 30 bars = 30 min OR
15-min chart: 2 bars = 30 min OR
Individual toggles for Daily EM, Opening Range, and Prev Day levels.
All can be turned off independently if the chart becomes crowded.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
BEST TIMEFRAMES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Recommended: 5-minute and 15-minute
Compatible symbols: SPX, SPCFD, SPY, ES1!, MES1!
The 12-point scoring system is session-level — update the manual inputs once
before the open. The signal triggers (MA crossovers, level bounces) fire
automatically throughout the session.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ALERTS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Five alert conditions are built in. Set them via the Alerts panel (⏰) once the
indicator is on your chart:
• Prism Sniper Long — Highest conviction entry
• Prism Aggressive Long — Faster MA9-based entry
• Prism Caution — Score 6–8 setup
• Prism Exit — Exit or stop-tighten signal
• HVL Breach — Gamma flip level lost
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
RELATED RESOURCES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Manual inputs are designed to work directly with data from:
• MenthorQ (Q-Score, CTA Z-Score, L/S Barometer, Vol Control Ratio)
• SpotGamma, SqueezeMetrics, or similar GEX providers
(Call Wall, Put Wall, HVL, Net GEX)
The Prism Intelligence newsletter publishes these values prior to each session.
Indicator

COT Week BoxCOT Week Box — visualize weekly positioning shifts from the CFTC Commitments of Traders report directly on your price chart.
═══════════════════════════════════════
WHAT IT DOES
═══════════════════════════════════════
Every week on Friday, the CFTC publishes updated positioning data reflecting what traders did between the previous Wednesday and Tuesday. This indicator takes that weekly change in net positioning and draws a colored rectangle spanning exactly that Wed→Tue price window on your chart.
The result: you can instantly see which weeks had unusually large positioning shifts, what the price did during those weeks, and which side of the market was driving the flow.
═══════════════════════════════════════
HOW TO READ THE COLORS
═══════════════════════════════════════
GREEN — Net positioning increased. Traders added more longs than shorts on balance.
RED — Net positioning decreased. Traders added more shorts than longs on balance.
YELLOW — Net positioning increased, but the move was driven mostly by shorts covering (closing losing positions) rather than fresh buying. Often a sign of short squeeze dynamics.
BLUE — Net positioning decreased, but the move was driven mostly by longs liquidating (closing winning or losing positions) rather than fresh shorting. Often a sign of profit-taking or capitulation.
The opacity of each box scales with how extreme the week was: faint boxes are borderline, bold boxes are true outliers.
═══════════════════════════════════════
INPUTS
═══════════════════════════════════════
Group — choose which participant group to analyze: Commercials (hedgers), Non-Commercials (large speculators / funds), Non-Reportables (small traders), or All (sum of all groups).
Weekly move threshold (%) — only draw boxes for weeks where the absolute change in net positioning ranks above this percentile. Default 85 shows the top 15% of weeks. Increase to 95 or 99 to isolate only the most extreme weeks.
Reduction dominance threshold (%) — controls when BLUE/YELLOW colors trigger instead of RED/GREEN. Higher values require cleaner one-sided flow to flag a reduction-dominated week.
Lookback (weeks) — historical window for percentile calculation. Default 156 weeks (≈ 3 years).
═══════════════════════════════════════
SUPPORTED INSTRUMENTS
═══════════════════════════════════════
The indicator automatically maps the chart symbol to the correct CFTC report code. Supported markets include:
Metals: Gold, Silver, Copper, Platinum, Palladium
Energy: WTI Crude, Brent, Natural Gas, RBOB Gasoline, Heating Oil
FX: DXY, EUR, GBP, JPY, CAD, AUD, NZD, CHF, MXN
Indices: S&P 500, Nasdaq 100, Dow, Russell 2000, VIX
Softs: Coffee, Cocoa, Sugar, Cotton, Orange Juice
Grains: Corn, Wheat, Soybeans, Soybean Meal, Soybean Oil, Oats, Rough Rice
Meats: Live Cattle, Feeder Cattle, Lean Hogs
Works on the daily (D1) timeframe only.
═══════════════════════════════════════
USAGE TIPS
═══════════════════════════════════════
Settings -> pin to scale -> pin to right scale (may be needed if rectangles aren't bind to candles)
Start with Group = "Commercial" on commodity charts — commercial hedgers often signal turning points when their positioning reaches extremes.
On index futures and FX, try Group = "Non-Commercial" to follow large speculator flow.
A cluster of BLUE boxes near a price high, or YELLOW boxes near a price low, can indicate exhaustion of the dominant side.
Combine with your existing technical analysis — COT data works best as a confirmation tool, not a standalone signal.
═══════════════════════════════════════
NOTES
═══════════════════════════════════════
Data source: CFTC Legacy report, futures-only.
Boxes are drawn after the Friday release, covering the prior Wed→Tue reporting week.
The indicator requires a full week of bars (Wed through Tue) to draw a box.
If your instrument isn't in the supported list, the indicator will display "Instrument not mapped" — a premium version with manual CFTC code override is available separately. Indicator

Swing Data Pro - Intraday Trend and Relative Strength DashboardSwing Data Pro is a clean decision-support dashboard built for traders who want to combine intraday structure with higher-quality context before entering a trade.
This script is designed to help you quickly answer the most important questions:
- Is the stock acting bullish, bearish, or mixed right now?
- Is the move confirmed by volume and participation?
- Is the broader market helping or fighting the trade?
- Has the stock already used too much of its normal daily range?
- Is this ticker showing real relative strength, or is it just moving with noise?
Instead of relying on one signal, this tool organizes multiple layers of information into one compact panel so you can make faster and more structured decisions.
MAIN FEATURES
1) Setup Score
A quick snapshot score built from key quality inputs such as relative strength, volume, and range behavior.
This helps rank the overall quality of the setup at a glance.
2) ADR%, Day Range %, and ADR Used %
ADR% shows the stock’s average daily range.
Day Range % shows how much the stock has ranged today.
ADR Used % shows how much of the stock’s normal daily range has already been used.
Why this matters:
If a stock already used most of its typical daily range, the move may be getting extended and harder to chase.
3) ATR%, Day Move %, ATR Used %, and ATR ($)
ATR% helps compare daily movement across stocks with different prices.
Day Move % shows the move from today’s open to the current price.
ATR Used % helps show how much of the stock’s typical move has already been consumed.
ATR ($) helps estimate normal dollar movement for stops and targets.
4) Relative Volume (RVol)
This script uses intraday relative volume logic so participation is more relevant for active trading.
That makes RVol more useful for intraday entries instead of only relying on broad daily comparisons.
5) U/D Volume Ratio
The U/D reading is used as a pressure gauge to see whether buying or selling volume is more dominant.
This helps separate real trend participation from weak or unstable movement.
6) Relative Strength (RS)
The RS reading is designed to show whether the stock is outperforming the broader market.
In general, stronger RS names are often better candidates for long setups, while weak RS names are often lower quality for longs.
7) Trend Bias
Trend Bias simplifies price structure into:
- Bullish
- Bearish
- Mixed
This is based on how price is behaving relative to important structure such as today’s open and VWAP.
It is meant to answer one simple question:
“What is price doing right now?”
8) Trend Day
Trend Day is the confirmation layer.
This helps determine whether the current directional bias is being supported by participation conditions such as volume and U/D.
Possible outputs include:
- BULL TREND
- BEAR TREND
- BALANCED
This is useful because a stock can look bullish on price structure alone, but still not have enough participation to qualify as a stronger trend day.
9) Market Confirm
The Market Confirm row checks broader alignment using:
- SPY
- QQQ
- BTC
- Sector ETF
This helps you quickly judge whether the wider environment is supportive or conflicting.
A bullish individual stock setup is generally stronger when the broader market and sector are aligned.
10) VIX Label
The VIX row shows the actual VIX price and daily direction.
If VIX is rising, that often signals increasing market stress.
If VIX is falling, that often supports better risk appetite.
The row is color-coded for easier reading.
11) Key Levels
The script can display key reference levels such as:
- Today’s Open
- Yesterday’s High / Low
- Pre-Market High / Low
- VWAP
- This Week High / Low
- Last Week High / Low
These levels are useful for planning entries, exits, breakdowns, reclaims, and rejection areas.
12) Moving Averages
Optional EMA and SMA overlays are included for traders who want moving-average structure directly on the chart.
13) Candle Pattern Detection
The script includes optional bullish candle pattern highlights to help identify useful reversal or continuation candles.
HOW TO USE IT
A simple workflow:
Step 1:
Check Trend Bias.
This gives you the immediate structural read:
Bullish, Bearish, or Mixed.
Step 2:
Check Trend Day.
This tells you whether participation confirms the move or whether the stock is still more balanced.
Step 3:
Check Market Confirm.
Look at SPY, QQQ, BTC, and the sector ETF.
The best trades often happen when the stock and broader market are aligned.
Step 4:
Check RVol and U/D.
Strong trends usually look better when both participation and pressure support the move.
Step 5:
Check ADR Used % and ATR Used %.
These help you avoid chasing moves that may already be too extended.
Step 6:
Use the key levels.
Look for reclaims, breakouts, pullbacks, holds, or failures around important reference levels.
PRACTICAL INTERPRETATION
For long ideas:
- Trend Bias should preferably be Bullish
- Trend Day should ideally improve toward BULL TREND
- Market Confirm should lean positive
- RVol and U/D should support the move
- ADR Used % should not be overly stretched if you are entering late
For short ideas:
- Trend Bias should preferably be Bearish
- Trend Day should ideally improve toward BEAR TREND
- Market Confirm should lean negative
- Participation should support downside pressure
- Avoid forcing shorts if the broader market is strongly risk-on
WHO THIS IS FOR
This script is best suited for:
- Intraday traders
- Momentum traders
- Breakout traders
- Pullback traders
- Swing traders who want a stronger intraday timing panel
It is not meant to be a fully automated buy/sell system.
It is a structured decision-support tool designed to improve context, timing, and trade filtering.
NOTES
- No indicator should be used alone.
- Always combine signal quality with price action, levels, risk management, and your own trading plan.
- This script is for educational and decision-support purposes only and is not financial advice. Indicator

Strategy

Indicator

Machine Learning: seMLP Q-Wavelet RL Engine [Jamallo]Author Note: I always get asked: "How can I build a Machine Learning or Artificial Intelligence trading system?" I created the study "Machine Learning: seMLP Q-Wavelet RL Engine" to showcase exactly how it can be done in a beginner-friendly manner. We will break down exactly how this AI thinks in plain English, and then show you exactly how the Pine Script code executes it step-by-step.
Introduction: The Institutional Approach to Algorithmic Trading
Most retail and algorithmic traders spend years searching for the "holy grail" by combining static indicators and hard-coded `IF/THEN` rule sets. They are often unaware that institutional quant desks abandoned those basic, curve-fitted patterns decades ago. Standard algorithmic analysis fails because financial markets are inherently chaotic—a hardcoded strategy that works perfectly in a backtest will systematically break down during a live regime shift.
To acquire a true institutional edge, algorithmic strategies cannot rely on rigid, backwards-looking formulas; they require a system that adapts dynamically in real-time. This script brings that quantitative firepower directly to your chart by constructing a live Self-Teaching AI .
Dynamic Filtering : It uses advanced frequency mathematics (Wavelets) to separate random market noise from true institutional momentum footprints with near-zero lag.
Artificial Brain : It feeds that data into a neural network—a living matrix of artificial "neurons" that continuously analyze and execute decisions.
Self-Correction : Most importantly, it executes Reinforcement Learning. If a trade fails, the AI actively calculates the error and mathematically rewires its own brain, ensuring it constantly evolves to survive changing market conditions.
Ultimately, this serves as a foundational study showing you exactly how to break away from basic scripting and get started in true Quantitative Algorithmic Trading.
1. The Core Architecture Loop
Here is the high-level flow of how the AI thinks on every single candle:
The Invisible "Burn-In" Phase
Because the AI starts with a completely randomized, "empty" brain, it will make terrible decisions on the very first few candles. To prevent it from acting prematurely on live data, the script executes an aggressive Burn-In Phase (e.g., the first 300 bars of the chart). During this period, the indicator is completely invisible. It aggressively executes hundreds of "mock trades" in the background, tracking virtual PnL, taking massive risks, and rapidly rewiring its brain without showing a single signal on your screen. Once the 300 bars are up, the burn-in phase ends. The AI stops acting recklessly and officially enters "Live Trading" mode with a fully trained, highly-intelligent brain.
SECTIONS 2 & 3: Setting Up the Brain
Conceptual Overview
Imagine the brain as a massive team of financial analysts.
We have 16 junior analysts looking at chart data.
They report their findings up to 12 senior analysts.
The seniors report to 6 directors.
The 6 directors send their final opinions to 3 executives representing the 3 possible actions: `BUY, SELL, HOLD`. This is called a 16 → 12 → 6 → 3 network structure.
Before we hand the price data to the junior analysts, we Normalize it (Z-Score). This just means "leveling the playing field" so a massive $500 candle wick doesn't break the analysts' math compared to a tiny $1 movement.
The Code Breakdown
// Section 2: Brain Size Constants
int NI = 16 // 16 Inputs (Junior analysts)
int NH1 = 12 // 12 Hidden layer 1 nodes
int NH2 = 6 // 6 Hidden layer 2 nodes
int NO = 3 // 3 Outputs
// Section 3: Normalization Helper
norm(series float x, simple int win) =>
float mu = ta.sma(x, win)
float sg = ta.stdev(x, win)
float sf = nz(sg) < 1e-10 ? 1.0 : sg
float res = (x - nz(mu, x)) / sf // Levels out the price data
na(res) ? 0.0 : res
SECTIONS 4 & 5: Giving the AI "Memory"
Conceptual Overview
By default, PulseWire indicators suffer from permanent amnesia! Every time a new candle paints, PulseWire completely deletes its short-term memory and forgets what happened on the last candle. If we are building an AI for trading that needs to "learn", it must be able to remember its past mathematical mistakes.
To force PulseWire to remember, we use special variables called `var` to create "Persistent Memory Matrices" where the AI for trading stores its brain's wiring throughout the entire chart history.
The Code Breakdown
// Using 'var' locks the memory so it never resets when a new candle paints
var matrix W1 = matrix.new(NI, NH1, 0.0) // The connections between neurons
var matrix W2 = matrix.new(NH1, NH2, 0.0)
...
var int pos = 0 // The AI remembers its current position: Long (1), Short (-1), or Flat (0)
SECTION 6: Seeing the Market (Wavelets)
Conceptual Overview
If you use a Moving Average, it always "lags" behind the real price. By the time the Moving Average crosses to tell you to buy, the massive breakout has already happened.
To fix this, we teach the AI for trading to see using Haar Wavelets . A Wavelet is a piece of advanced math that splits the price candle with minimal lag into two things:
The Detail (D) : The immediate, rapid volatility chop.
The Smooth (V) : The true underlying smooth momentum. By looking at the detail and momentum completely separately, the AI for trading can react to shifts with minimal lag.
The Code Breakdown
// We take standard features like Open, Close, and Volume:
float f0 = open
float f1 = close...
// We break them into Wavelets using simple math combinations:
float v1_0 = (f0 + nz(f0 , f0)) / 2.0 // Smooth momentum
float d1_0 = (f0 - nz(f0 , f0)) / 2.0 // Instant volatility detail
...
// We pack all 16 traits into the 'feat' array to feed the AI for trading's Brain
feat.set(0, norm(d1_0, i_normWin))
feat.set(14, float(pos)) // Tells the brain its current trade position
feat.set(15, norm(portRet, i_normWin)) // Tells the brain its current open trade return
SECTION 7: How the Brain Thinks (seMLP)
Conceptual Overview
An "MLP" is just a standard Neural Network (a massive web of variables that pass data to each other). The problem is that if you give PulseWire an insanely massive web of math equations, it will crash and throw a compiler timeout error.
So, we use a Self-evolving MLP (seMLP) . The AI pushes the Wavelet data through its network dynamically. To prevent "dead zones" where a neuron just stops firing in a flat market, it uses a formula called LeakyReLU . It basically acts as a gatekeeper that tells the neuron: "If this signal is incredibly weak, shrink it down to 1%, but don't explicitly delete it."
The Code Breakdown
// The data enters Hidden Layer 1 (h1)
array h1 = array.new(NH1, 0.0)
for j = 0 to NH1 - 1
float s = B1.get(j)
// The inner brain loops through all 16 incoming inputs
for i = 0 to NI - 1
s += feat.get(i) * W1.get(i, j)
// LeakyReLU Formula: f(x) = x if x > 0 else 0.01 * x
// If the signal 's' is positive, keep it. If 's' is negative, shrink to 1%
h1.set(j, s > 0 ? s : 0.01 * s)
SECTION 8: Taking Action (Exploration vs Exploitation)
Conceptual Overview
How does the AI actually press the BUY or SELL button? It calculates a "Confidence Score" (called a Q-Value) for all three options— Buy, Sell, and Hold. The highest score wins and executes the trade.
However, during its invisible "Burn-In Period", the AI uses a variable called Epsilon . Think of Epsilon as a dice roll. Sometimes, instead of making the smartest, highest-scoring choice, the AI will randomly pick a completely stupid trade just to "experiment" and see if a hidden market pattern exists! This is conceptually how AI for trading discovers new, out-of-the-box strategies. As training goes on, Epsilon gets smaller, and the AI stops experimenting.
The Code Breakdown
// Calculate Epsilon: Start at a high 50% and slowly decay to 5% over time
float epsilon = bar_index <= i_burnIn ? math.max(0.05, i_epsStart_val * ...)
// Roll the dice. If the random number is less than epsilon, we experiment randomly!
bool explore = math.random(0.0, 1.0) < epsilon
// Find the AI for trading's highest confidence choice: Q(0) = Buy, Q(1) = Sell, Q(2) = Hold
if Q.get(1) > bestQ // If Sell confidence is higher than current best (Buy)...
bestQ := Q.get(1)
bestAct := 1
if Q.get(2) > bestQ // If Hold is even higher...
bestQ := Q.get(2)
bestAct := 2
// Execute the final action
int act = explore ? math.min(int(math.floor(math.random(0.0, 2.999))), 2) : qArg
SECTION 9: Training with Rewards (Reinforcement Learning)
Conceptual Overview
This is the heart of Machine Learning. It functions exactly like training a pet. If the AI makes a winning trade that generates cash, we give it a mathematical "treat" (a positive reward). If the AI loses money, we hit it with a brutal negative reward. Over time, the AI autonomously refines its neural weights exclusively to collect the maximum amount of "treats".
The Code Breakdown
// Calculate how much money the candle moved
float cRet = nz((close - close ) / close , 0.0)
// The Reward (R) is a combination of three factors:
// 1. PnL (rPn) - Did we make raw cash profit?
// 2. Trail (rTn) - Did we efficiently track the trend?
// 3. Lee (rLee) - A shaping bonus for correct directional positioning.
float R = i_alphaT * rTn + i_alphaP * rPn + 0.1 * rLee
SECTION 10: Learning from Mistakes (Backpropagation)
Conceptual Overview
If the AI's trade failed, how does it adjust its internal logic? It uses a process called Backpropagation . It looks at the Reward it just received, realizes it was horribly wrong, and calculates the "Error Margin" (How far off my prediction was I?). It then mathematically rewrites all of the internal connections `(W1, W2, W3)` in reverse, editing them to be slightly smarter for the next candle!
Because updating a massive brain on every single micro-tick causes chaotic glitches, we "Accumulate" the errors in a batch over several candles, and then update the brain smoothly with the batch average.
The Code Breakdown
// Compare the Target Reward vs what the Brain actually Predicted (Temporal Difference Error)
float tgt = R + i_gamma * max_qt
float td = tgt - pOut.get(prevAct)
// Accumulate the backwards gradients over multiple bars so we don't glitch
for j = 0 to NO - 1
gB3_acc.set(j, gB3_acc.get(j) + g3.get(j))
accumCount += 1
// Once 'i_accumSteps' bars have passed, we apply the compiled batch update to 'Rewire' the Brain weights!
if accumCount >= i_accumSteps
for i = 0 to NH2 - 1
for j = 0 to NO - 1
float dw = gW3_acc.get(i, j) * sc
W3.set(i, j, W3.get(i, j) + clr * dw - clr * i_l2 * W3.get(i, j))
SECTION 11: Link Pruning (Making the Brain Faster)
Conceptual Overview
Stage 1: The Initial Brain (Complex & Slow)
Stage 2: The Pruning Decision
Stage 3: The Optimized AI for trading (Sleek & Fast)
As the brain learns, some of the mathematical connections become totally useless. Having a giant Tradingview indicator calculate hundreds of useless math connections will trigger a calculation timeout. At a specific point in training length (defaulting to the end of the 300-bar burn-in period), the script literally pauses and deletes (zeroes out) the weakest neural links. PulseWire skips over calculations containing plain zeroes, making your indicator insanely fast and completely lag-proof.
The Code Breakdown
if bar_index == i_pruneBar and not pruned
// Evaluate every single connection weight...
// Find the bottom weakest percentage (i_prunePct)
float thr = absW.get(pidx)
// Explicitly set the weakest weights to Zero!
for i = 0 to NI - 1
for j = 0 to NH1 - 1
if math.abs(W1.get(i, j)) <= thr
W1.set(i, j, 0.0) // Permanent pruning: weak link removed
Important Disclaimer
This indicator is published strictly for educational and research purposes. It is a conceptual showcase proving that advanced Deep Reinforcement Learning architectures generally reserved for Python/TensorFlow can be natively executed within the PulseWire Pine Script environment. Due to Pine Script's structural time-series limitations—specifically the lack of a random-access historical buffer required for true experience replay—this is NOT intended for practical live trading. For production-grade deployment, it is highly recommended to port this mathematical framework to Python.
References
This indicator's mathematical engine was directly modeled and bridged from the following quantitative research papers:
Lee et al. (2021) — " Learning to trade in financial time series using high-frequency through wavelet transformation and deep reinforcement learning " (Used for the MODWT Wavelet integration & State architecture).
Tsantekidis et al. (2021) — " Price Trailing for Financial Trading using Deep Reinforcement Learning " (Used for the dynamic margin-trailing reward system).
Seow et al. (2021) — " seMLP: Self-evolving Multi-layer Perceptron " (Used for the 16 → 12 → 6 → 3 sparse Neural Network structure and the automatic Link Pruning logic).
Indicator

LAZARUS - Critical Transition EWSLAZARUS ⚡ Critical Transition EWS
An Early Warning System (EWS) for detecting critical regime transitions, bifurcations, and market crashes before they fully materialize. LAZARUS monitors statistical signatures of "critical slowing down" — rising autocorrelation, variance inflation, spectral reddening, and rising skew/kurtosis — to flag when a market is approaching a tipping point.
What It Does
LAZARUS synthesizes five statistical moments into a composite z-scored Early Warning Signal (EWS). It detects when a market transitions from a stable equilibrium to a critical state where small perturbations can trigger large regime shifts. The indicator operates in three distinct states with hysteresis to prevent flickering:
Normal (Cool Blue): Market operates within statistical equilibrium. No critical transition imminent.
Warning (Warm Orange): Early signatures of critical slowing down detected. Volatility rising, autocorrelation increasing, distribution tails fattening. Elevated probability of regime change.
Critical (Hot Red): Multiple statistical indicators simultaneously exceed critical thresholds. System is at or near bifurcation point. High probability of abrupt trend change, breakout, or crash.
The Five Statistical Pillars
AR(1) Autocorrelation: First-order autocorrelation of the series. Increases as systems approach critical transitions (critical slowing down causes greater memory of previous states). Detects rising persistence in price action.
Log-Variance: Rolling window variance of returns. Flickering and variance inflation are classic precursors to regime shifts. Captures sudden volatility clustering before visible price breakdowns.
Absolute Skewness: Measures distributional asymmetry. Rising |skew| indicates one-sided risk building (positive or negative tail risk accumulation). Reflects underlying order flow imbalance.
Spectral Reddening: Ratio of low-pass to high-pass variance. As critical transitions approach, low-frequency components dominate (spectral power shifts to "redder" regimes), indicating slower recovery from perturbations.
Excess Kurtosis: "Tailedness" of the return distribution. Rising kurtosis indicates increasing probability of extreme events (leptokurtosis) beyond what normal distributions predict.
Key Features
Dual-Window Architecture: Uses a short rolling window (W, default 50) to calculate current moments, and a long reference window (R, default 250) to establish baseline statistics. All components are z-scored against historical norms for genuine anomaly detection.
Hysteresis State Machine: Implements exit thresholds (thWarn - hyst, thCrit - hyst) below entry thresholds to prevent rapid state flickering. Once Critical, the system maintains that state until EWS drops significantly below the entry threshold.
Trend Bias Context: Displays directional bias (▲ uptrend / ▼ downtrend) based on price versus long-term EMA. Critical signals in the direction of the prevailing trend suggest acceleration; against the trend suggest reversal/collapse.
Flexible Pre-Processing: Choose between log returns (standard), first differences (linear trends), or HP-filtered (business cycle extraction) depending on asset characteristics.
Composite Histogram: Visual representation of EWS intensity with gradient coloring from cool (stable) to hot (critical).
Transition Resolution Alerts: Unique "↯ Transition" signal fires when exiting Critical state, indicating the bifurcation has resolved (either completed its move or reversed).
Inputs & Parameters
Core Detection
Source: Input price series (default close).
Rolling window (short): 20–500 (default 50). Window for calculating current AR(1), variance, skew, kurtosis. Shorter = more responsive but noisier.
Reference window (long): 100–2000 (default 250). Baseline for z-score normalization. Must be significantly longer than rolling window.
Pre-processing: Select data transformation — log returns (standard for finance), first difference (raw deltas), or HP-filtered (cycle extraction).
Component Weights
AR(1) weight: Contribution of autocorrelation to composite EWS.
Variance weight: Contribution of log-variance.
|Skew| weight: Contribution of absolute skewness.
Spectral-red weight: Contribution of spectral reddening (low/high freq ratio).
Kurtosis weight: Contribution of excess kurtosis.
Signal Logic
Warning threshold (z): Z-score level to trigger Warning state (default 1.5σ).
Critical threshold (z): Z-score level to trigger Critical state (default 2.5σ).
Hysteresis band: Buffer below thresholds required to exit a state (default 0.3σ). Prevents rapid Normal→Warning→Normal flickering around threshold boundaries.
Visualization
Show sub-components: Toggle visibility of individual z-scored components (z AR(1), z logVar, etc.).
Gradient background: Toggle dynamic background coloring that intensifies with EWS heat.
Diagnostic table: Toggle floating information panel showing current state, EWS value, component breakdowns, and trend bias.
Composite histogram: Toggle column histogram visualization behind the main line.
Event labels: Toggle on-chart labels for Critical entry ("⚡ CRITICAL") and Transition exit ("↯ TRANSITION").
How to Read It
EWS Composite Line: The main oscillator plotted as a thick colored line. Values are z-scores (standard deviations from long-term mean). Above 0 = elevated statistical anomalies; below 0 = subdued/stabile.
Color Gradient: Transitions from Cool Blue (EWS ≈ 0) through Warm Orange (approaching Warning) to Hot Red (Critical). The gradient uses the ratio EWS/thCrit to determine heat intensity.
State Transitions:
Enter Warning: EWS crosses above thWarn (1.5) from below.
Enter Critical: EWS crosses above thCrit (2.5) OR crosses from Warning above thCrit.
Exit Critical: EWS drops below (thCrit - hyst) = 2.2.
Exit Warning: EWS drops below (thWarn - hyst) = 1.2.
Trend Bias Indicator: Shown in diagnostic table as ▲ (uptrend) or ▼ (downtrend) based on price relative to long-term EMA. Contextualizes whether critical signals suggest trend acceleration or imminent reversal.
Sub-Component Lines: Thin semi-transparent lines showing individual z-scores. Divergences between components (e.g., variance rising while AR(1) flat) indicate specific types of regime stress.
Signal Types & Alerts
⚠ Warning (Alert): Early-warning threshold crossed. Regime instability rising. First indication that system dynamics are shifting. Consider reducing position size or tightening stops.
⚡ Critical (Alert + Label): All EWS indicators elevated simultaneously. Phase transition imminent or underway. High conviction for significant move. Label appears below bar in red.
↯ Transition (Alert + Label): Exiting Critical state. The bifurcation has resolved — either the move completed, the system settled into a new regime, or the crisis passed without materializing. Label appears above bar in ice blue.
State Persistence Counter: Internal counter tracks consecutive bars in current state. Longer duration in Critical increases probability of sustained regime change vs. temporary spike.
Practical Usage Guidelines
Regime Change Anticipation
Enter Warning state: Reduce leverage, tighten stop-losses, prepare for volatility expansion. Do not yet assume direction (could be crash or explosive breakout).
Enter Critical state: Consider directional positions in the direction of trend bias (▲ = long volatility/breakout continuation, ▼ = short/reversal). Or exit all positions if uncertainty is unacceptable.
Exit Critical state (Transition signal): Reassess the new regime. If price moved significantly during Critical phase, this may mark the end of the move (take profit). If price did not move, it may indicate a "false alarm" or aborted transition.
Risk Management
Use Critical signals as automatic trading halts for mean-reversion strategies (critical transitions destroy MR edge).
Use Warning signals to reduce Kelly criterion / position sizing by 50% or more.
Combine with trend-following systems: LAZARUS Critical + Trend Bias ▲ = high-conviction long continuation. LAZARUS Critical + Trend Bias ▼ = imminent collapse signal.
Asset-Specific Calibration
High-volatility crypto: Lower thresholds (Warn 1.2, Crit 2.0) to catch earlier signals in naturally noisy data.
Low-volatility forex/indices: Raise thresholds (Warn 1.8, Crit 3.0) to avoid false positives from normal market drift.
First-difference mode: Use for non-stationary series with strong linear trends (certain commodities).
HP-filtered mode: Use for removing business cycle effects in equity indices when looking for crashes specific to short-term dynamics.
Important Notes
Critical Slowing Down Theory: This indicator is grounded in dynamical systems theory. As systems approach bifurcation points (tipping points), they exhibit slower recovery from perturbations, causing increased autocorrelation and variance, and shifting spectral power to lower frequencies. LAZARUS detects these pre-cursor patterns statistically.
Z-Score Calculation: All components are normalized against the long reference window (R), not the short window. This means the indicator asks: "Are current statistical properties anomalous compared to the last 250 bars?" rather than "Are they high in absolute terms?"
Hysteresis Necessity: Without the hysteresis band (default 0.3σ), markets hovering near 1.5σ would flicker between Normal and Warning every tick, creating alert spam. The state machine requires EWS to drop 0.3σ below the entry threshold to exit, ensuring stable state classification.
Log Variance Guard: Variance calculations use max(variance, 1e-12) to prevent log(0) errors in flat markets. If 10+ consecutive bars have identical prices, variance floor prevents crash.
AR(1) Interpretation: In efficient markets, AR(1) ≈ 0 (no serial correlation). As AR(1) rises toward 1.0, the market "remembers" its previous moves increasingly — a mathematical signature of approaching criticality (slowing down).
Spectral Reddening Mechanics: The script separates the signal into low-pass (EMA-smoothed) and high-pass (residual) components. As critical transitions approach, the low-pass component captures increasingly more variance relative to high-pass, indicating the system is dominated by slow-moving forces rather than fast noise.
No Repainting: Uses confirmed close prices and barstate-based calculations. The "bars in state" counter tracks historical persistence accurately.
Indicator
