Iridescent Helix [JOAT]Iridescent Helix
Iridescent Helix is a composite momentum oscillator that lives in a sub-pane and projects cross-pane visuals onto the price chart. The composite blends three orthogonal momentum legs into a single normalized score in the range -100 to +100. Above the math, it adds a layered iridescent ribbon, a breath-opacity histogram, gradient overbought / oversold zones, cross-pane iridescent candle recoloring, and an in-pane pivot divergence engine.
What makes it different
The composite blends three independent momentum lenses: a volume-weighted-median price distance, a Connors-style triple RSI, and a clamped volume Z-score. Smoothed with a Hull Moving Average to reduce phase lag while preserving sensitivity.
The visual stack uses seven plot layers per direction, hue-rotated through the bull or bear accent gradient, each layer at a different transparency and linewidth, producing a depth effect that single-color ribbons cannot match.
A breath-opacity histogram fades columns when momentum is decelerating and brightens them when momentum is accelerating, giving an at-a-glance read of momentum derivative.
An in-pane pivot divergence engine detects regular and hidden divergences and projects both as in-pane markers and as price-to-price connector lines on the price chart.
How it works
Volume-weighted median over a rolling window. Sort close prices ascending, accumulate volumes in that order. The price at which cumulative volume crosses half of total volume is the weighted median.
Composite equals 0.50 times the normalized distance from the volume-weighted median, plus 0.35 times the normalized Connors RSI, plus 0.15 times the clamped volume Z.
Hull-smoothed and scaled to centi-percent, clamped to the range -100 to +100. EMA(21) signal line drawn alongside.
Pivot divergence detection compares price pivots against composite pivots, gated to a 5-to-60-bar window between successive pivots.
Right-edge labels in the pane (composite, signal, volume Z) and on the price chart (cross-pane regime status).
Reading the chart
In-pane : seven-layer iridescent ribbon, breath-opacity histogram, volume-modulated zero line, overbought / oversold guide lines with gradient fills when the composite breaches them, composite-to-signal ribbon fill.
Cross-pane : iridescent candle recolor on price, divergence connector lines between price pivots, subtle reversal dots at extreme reversal closes, soft regime tint background when the composite is clearly above or below zero.
Right-edge label cluster : the pane shows current composite (with percentile rank), signal line, and volume Z. The price chart shows a single IRH summary label with composite value, percentile, and regime tag.
A right-edge state block lists current regime, zone (overbought, oversold, neutral), and bars since the last zero cross.
Signals
Bull / bear zero cross (composite re-crosses zero)
Overbought / oversold reversal (composite crosses back from an extreme)
Volume surge (volume Z above two)
Momentum acceleration / deceleration above a user-tunable threshold
Regular and hidden divergence detection (bull / bear pairs)
All gated on barstate.isconfirmed or barstate.ishistory. No future references. No lookahead_on.
Inputs
Composite : VW median length, volume Z length, overbought / oversold levels, divergence lookback, percentile envelope length.
Visual : bullish / bearish / accent / magenta colors, toggles for ribbon, histogram, iridescent candles, cross-pane reversal dots, divergence dots, percentile envelope, cross-pane regime tint.
Labels : pane right-edge cluster, pane state block, cross-pane IRH label, divergence lines, divergence labels, OB/OS event labels, zero-cross events, acceleration events.
Dashboard : position, size.
Alerts : acceleration magnitude threshold.
How traders use this
Trend continuation : open positions in the direction of the composite when it crosses zero from the appropriate side and the volume Z confirms.
Reversion plays : take fades when the composite reaches an extreme zone and momentum begins decelerating (histogram fades), particularly when supported by a regular divergence connector on the price chart.
Hidden divergence : in a clear trend, a hidden divergence is a continuation signal and can be used to add to existing positions on a pullback.
Cross-system confirmation : feed the composite into other JOAT scripts (for example Position Architect) as a signal source by connecting plots in the chart UI.
Limitations
The composite is a normalized smoothed reading, not a leading indicator. It quantifies present momentum strength and direction rather than predicting future direction.
Connors RSI and volume Z need warm-up bars before they stabilize.
Pivot divergence detection inherits the right-bar delay of pivot identification (the pivot is only confirmed several bars after the actual extreme).
HMA smoothing introduces a few bars of warm-up where the composite is unavailable.
Compatibility
Pine Script v6 open-source indicator (pane). Any symbol, any timeframe. Cross-pane elements use force_overlay=true. No request.security calls. Non-repainting (divergence pivots are confirmed-bar gated).
Defaults
Mint and red defaults, plus cyan (bull accent) and magenta (bear accent) hue-rotation targets. Top-right medium dashboard. All visualizations on. For fast intraday work, shorten the VW median length and the divergence lookback.
Indicator

RSI Multi-Timeframe DashboardRSI Multi-Timeframe Dashboard
═══════════════════════════════════════════
WHAT IT DOES
═══════════════════════════════════════════
This tool displays the Relative Strength Index (RSI) of up to six timeframes
at once in a compact on-chart table, so you can judge momentum across the
whole timeframe stack without switching charts. Instead of reading RSI on a
single timeframe, you see how short-, medium- and higher-timeframe momentum
line up — and a consensus row summarises the overall picture.
It is designed as a CONFLUENCE tool: a way to see whether the broader market
agrees with what you're seeing on your trading timeframe.
═══════════════════════════════════════════
HOW IT WORKS
═══════════════════════════════════════════
RSI is calculated with the standard Wilder method (default length 14) on each
selected timeframe using request.security(). Each row is classified into a zone:
- Overbought — RSI at or above the overbought level (default 70)
- Oversold — RSI at or below the oversold level (default 30)
- Bullish — RSI above the midline (default 50)
- Bearish — RSI below the midline (default 50)
The "ALL" row aggregates only the enabled timeframes:
- If every enabled timeframe is oversold → "STRONG BUY ZONE"
- If every enabled timeframe is overbought → "STRONG SELL ZONE"
- Otherwise it shows the majority bias and a score, e.g. "BULLISH (4/5)"
These are descriptions of momentum conditions — not instructions to buy or sell.
═══════════════════════════════════════════
HOW TO USE IT IN A TRADE
═══════════════════════════════════════════
The core idea is alignment. Higher-timeframe RSI defines the bias; lower-timeframe
RSI helps with timing inside that bias.
Example long workflow:
1. Bias — Confirm the higher timeframes (e.g. 4H, Daily) are Bullish (above the
midline). This says the dominant momentum favours longs.
2. Timing — Wait for a lower timeframe (e.g. 5m/15m) to dip toward Oversold and
turn back up, offering a pullback entry in the direction of the higher-TF bias.
3. Confluence — A "BULLISH (5/5)" or rising consensus score adds conviction;
a "MIXED" reading is a reason to wait.
4. Management — Define your stop from price structure (recent swing), not from
RSI alone, and size the position to your own risk rules.
The short workflow is the mirror image (higher TFs Bearish, lower TF rallies into
Overbought and rolls over).
Things to respect:
- RSI can remain Overbought in a strong uptrend (and Oversold in a strong
downtrend) for a long time. "Overbought" is not automatically "sell."
- Counter-trend signals (e.g. Oversold while higher TFs are Bearish) are
lower-probability and best avoided or treated as scalps only.
- This indicator does not place trades, set stops, or manage risk for you.
═══════════════════════════════════════════
SETTINGS
═══════════════════════════════════════════
- RSI — length, source, and the overbought / oversold / midline levels.
- Timeframes to monitor — up to 6 slots, each with an on/off toggle and its own
timeframe. Set them equal to or higher than your chart timeframe.
- Style — table position, text size, and your own bullish / bearish colours.
═══════════════════════════════════════════
ALERTS
═══════════════════════════════════════════
- All timeframes oversold
- All timeframes overbought
- Consensus turned bullish (majority crossed above the midline)
- Consensus turned bearish (majority crossed below the midline)
═══════════════════════════════════════════
NOTES, REPAINTING & LIMITATIONS
═══════════════════════════════════════════
- Monitored timeframes should be greater than or equal to your chart timeframe;
requesting a lower timeframe is not meaningful.
- Repainting: values use lookahead_off, so a higher-timeframe RSI updates live
until that bar closes — this is intended for real-time reading. The reading on
a closed higher-TF bar is final.
- RSI is a momentum oscillator, not a forecast. This dashboard organises that
information across timeframes; it does not predict price.
This script is published open-source. Study it, learn from it, and adapt it to
your own process. It is provided for educational purposes only and is not
financial advice. Past behaviour of any indicator does not guarantee future
results — always do your own analysis and manage your risk. Indicator

Artemis Wave Oscillator🟦 Artemis Wave Oscillator is a Pine v6 reimagination of the classical WaveTrend family, built on a Welford running-stdev channel and EMA-smoothed normalization. Unlike fixed-band WaveTrend variants that ship with hard-coded levels, the engine continuously rescales itself against its own dispersion — producing a momentum curve that stays perfectly bounded between visually consistent reversion bands on every asset and every timeframe, with no manual recalibration.
The indicator integrates six analytical layers — WaveTrend core, dynamic reversion bands, histogram momentum gauge, extremity reversion dots, regular + hidden divergence detection with a Smart AI Filter, and a theme-adaptive PRO dashboard — each operating independently and rendered on a single, clean oscillator panel.
🟦 HOW THE CORE ENGINE WORKS
**WaveTrend Channel**
Each bar, the engine builds an EMA-smoothed midline from the selected price aggregate over the Channel Length window. In parallel, a Welford single-pass running standard deviation measures the channel width — a numerically stable O(N) algorithm that updates the running mean and squared deviation simultaneously, preserving precision on long histories where naive sum-of-squares accumulators drift.
The raw wave is then computed as:
wave_raw = (src − chanMid) / chanDev × 100
This produces a z-score-like signal scaled to the ±100 range. Dividing by the running standard deviation normalizes the output regardless of asset volatility — BTC, EURUSD, SPY, and a small-cap stock all swing through the same band structure without parameter changes.
**EMA Smoothing**
The raw wave is then passed through an EMA of length Average Length to produce the visible `wave` line. This is the dominant responsiveness control — larger values produce a calmer curve with fewer reversion-zone touches.
**Signal Line**
An SMA of the wave (Signal Length) builds the trigger line. Crossovers between the wave and signal line mark momentum regime changes — the same convention used by classical MACD and Stochastic.
**Histogram**
The wave − signal delta is rendered as a filled area. Two opacity tiers distinguish rising momentum (brighter) from fading momentum (dimmer), so the eye picks up acceleration vs. deceleration at a glance.
**Source Selector**
Nine price aggregates are available:
| Source | Formula | Use case |
|---|---|---|
| Open | open | Open-of-bar bias |
| High | high | Top-of-range tracking |
| Low | low | Bottom-of-range tracking |
| Close | close | Standard, fastest reaction |
| OC2 | (open + close) / 2 | Body midpoint |
| HL2 | (high + low) / 2 | Body-independent midpoint |
| HLC3 | (high + low + close) / 3 | Typical mean — default |
| OHLC4 | (open + high + low + close) / 4 | Smoothest |
| HLCC4 | (high + low + 2×close) / 4 | Close-weighted |
🟦 REVERSION BANDS
The user picks a single Reversion Threshold (T) — the distance from zero (in normalized wave units) beyond which the wave is considered overbought (positive side) or oversold (negative side). Three proportional tiers render automatically:
| Tier | Level | Visual |
|---|---|---|
| Inner | ±T | Outer ring of the gradient fill |
| Middle | ±T × 1.25 | Boundary between outer ring and inner extreme |
| Outer | ±T × 1.5 | Hard outer boundary of the gradient fill |
Because the bands are derived from T, they always wrap the threshold no matter how the user tunes it. A trader scaling T from 80 (volatile assets) to 150 (trending assets) keeps the visual context intact without retuning the band levels.
The Reversion Threshold itself drives three downstream features:
- Extremity Dot triggers
- The "Extremities" bar-coloring mode
- The Dashboard Zone tag (OB / MID / OS)
🟦 EXTREMITY DOTS
OB / OS reversion markers — small dual-layer dots that fire when the wave crosses the signal line beyond the Reversion Threshold:
- **OS dot** (bull theme color) → wave crossed UP past −T
- **OB dot** (bear theme color) → wave crossed DOWN past +T
These are the highest-conviction mean-reversion triggers in the script. The dots use a two-track rendering — a pixel-perfect glow + core visual via `plot.style_circles`, paired with an invisible `label.style_circle` carrying a rich tooltip. Hovering on a dot surfaces:
- Direction (Crossed UP / DOWN through Signal)
- Active zone (Below −T / Above +T)
- Current wave value
- Current signal value
- Trading interpretation (mean-reversion long / short opportunity)
🟦 DIVERGENCE DETECTION
Pivots are calculated using `ta.pivothigh` and `ta.pivotlow` with an arm of `Channel Length / 2`. All divergence results appear `Channel Length / 2` bars late — this is standard Pine Script pivot behavior, not a bug.
**Four divergence types:**
| Type | Price | Wave | Signal |
|---|---|---|---|
| Regular Bull (D▲) | Lower Low | Higher Low | Potential reversal up |
| Regular Bear (D▼) | Higher High | Lower High | Potential reversal down |
| Hidden Bull (H▲) | Higher Low | Lower Low | Uptrend continuation |
| Hidden Bear (H▼) | Lower High | Higher High | Downtrend continuation |
Regular divergence uses solid lines (width 2). Hidden divergence uses dashed lines (width 1) — the thinner, dashed style makes the continuation signal visually quieter than the reversal signal, matching their respective conviction tiers. Labels use bracketed symbols (D▲ / D▼ / H▲ / H▼) and each carries a tooltip-rich hover with price + wave context.
**Smart Divergence Filter (AI)**
An optional pre-filter that rejects low-quality divergences before they render. Three independent gates:
1. **Min Wave Swing** — minimum oscillator swing between the two pivots (default: 5 units). Drops noise-level differences where the wave barely moved between pivots.
2. **Min Price Swing (%)** — minimum price swing between pivots as a percentage of the recent `Channel Length × 4` high-low range (default: 0.3%). Drops divergences where price barely moved relative to recent volatility.
3. **Zone Confirmation** — the wave at the current pivot must sit in the matching reversion half:
- Bullish divergence → wave at LL pivot ≤ −T × 0.5 (oversold half)
- Bearish divergence → wave at HH pivot ≥ +T × 0.5 (overbought half)
This encodes the classical "best divergences form at extremes" rule using the wave value itself as the gate — no MFI or volume input required.
When the master toggle is OFF (default), all detected divergences render. When ON, only divergences that clear all three gates survive. The filter applies identically to both chart rendering and alert conditions — no mismatch between visual and alert signals.
🟦 HISTOGRAM
The wave − signal histogram is rendered as a filled area between the histogram value and the zero line. Two opacity tiers per side:
| State | Color | Opacity |
|---|---|---|
| Bull, rising | thBull | Rising Opacity (default 60) |
| Bull, fading | thBull | Fading Opacity (default 40) |
| Bear, rising | thBear | Rising Opacity (default 60) |
| Bear, fading | thBear | Fading Opacity (default 40) |
Rising bars are the most actionable visual cue — they mark momentum that is accelerating in the active direction. Fading bars indicate momentum stalling.
🟦 BAR COLORING
Five mutually exclusive modes apply a wave-driven color to every price bar on the chart:
| Mode | Behavior |
|---|---|
| None | Leave bars untouched (default) |
| Midline Cross | Bull above zero, bear below zero |
| Extremities | Bull beyond +T, bear beyond −T, neutral elsewhere |
| Reversions | Bull on OS dot trigger, bear on OB dot trigger |
| Slope | Bull when wave > signal, bear when wave < signal |
Colors are pulled from the active theme — no per-mode color picker needed.
🟦 DASHBOARD
A compact 2-column, 7-row data panel renders on the last bar when enabled. Every value derives from variables already computed upstream, so the dashboard adds zero overhead until the final bar.
| Row | Left | Right |
|---|---|---|
| Header | Artemis Wave | ▲ BULL / ▼ BEAR / ■ NEUTRAL |
| Wave | Wave | Current value + trend arrow (▲ ▼ ■) |
| Signal | Signal | Current SMA trigger value |
| Strength | Strength | 10-block monospace bar gauge |
| Zone | Zone | OB / MID / OS tag |
| Div | Div | Most recent divergence within last 50 bars (▲ REG / ▼ REG / ▲ HID / ▼ HID / —) |
| Slope | Slope | ▲ UP / ▼ DOWN / ■ FLAT |
The strength gauge normalizes `|wave − signal|` against 50 (typical mid-amplitude swing) and buckets the result into 10 monospace blocks (`█` filled, `░` empty), giving an at-a-glance read of crossover conviction.
**Theme-Adaptive Chrome**
The dashboard auto-inverts its layout based on the active theme:
- **Dark themes** (Tropic, Amber, Pastel, Cyber, Helios, Electric, Candy, Bloomberg, Solar, Royal): header and footer use a faint `thBull` tint, middle rows stay solid dark, text uses full-saturation `thBull`. Border uses `thBull` at 20% transparency for strong theme presence.
- **Light themes** (Midnight, Graphite): backgrounds flip to white, text stays `thBull` (which is itself dark on these themes), border uses `thBull` at 40% transparency.
This guarantees text legibility against every palette without per-theme manual tuning.
**Position & Size**
Six anchor slots (Top/Middle/Bottom × Left/Right) and four text sizes (Tiny / Small / Normal / Large).
🟦 COLOR THEMES
Twelve cohesive palettes, each resolving to four axis colors:
| Theme | Character | Bull | Bear |
|---|---|---|---|
| Tropic | Cyan steel + deep orange | #00bcd4 | #ff6d00 |
| Amber | Warm amber + indigo blue | #ff9800 | #e53935 |
| Pastel | Sky blue + soft lavender | #4fc3f7 | #9575cd |
| Cyber | Neon lime + hot crimson | #00e676 | #ff1744 |
| Helios | Bright gold + scarlet | #ffd600 | #ef5350 |
| Electric | Electric aqua + magenta | #00e5ff | #e040fb |
| Candy | Neon green + hot pink | #69F0AE | #FF4081 |
| Bloomberg | Terminal orange + cyan | #ff8c00 | #00b0ff |
| Solar | Solarized olive + crimson | #859900 | #dc322f |
| Royal | Imperial gold + deep purple | #ffd700 | #6a0dad |
| Midnight | Deep navy + dark crimson | #0d47a1 | #b71c1c |
| Graphite | Near-black + silver grey | #1a1a1a | #757575 |
All four color roles (bull / bear / neutral / signal) change simultaneously when the theme changes. The whole script reads through these four variables — nothing below the resolver references a raw hex literal, so a single dropdown selection drives every plot, fill, dot, divergence line, dashboard cell and border.
🟦 ALERT SYSTEM
Ten alert conditions, all using `alert.freq_once_per_bar_close`:
| Alert | Condition |
|---|---|
| OS Reversion | Wave crossed UP through signal while wave < −T |
| OB Reversion | Wave crossed DOWN through signal while wave > +T |
| Regular Divergence | D▲ or D▼ detected (respects Smart Filter) |
| Hidden Divergence | H▲ or H▼ detected (respects Smart Filter) |
| Bullish Trend | Wave crossed above the midline (zero) |
| Bearish Trend | Wave crossed below the midline (zero) |
| Bullish Swing | Wave × signal upward cross, regardless of zone |
| Bearish Swing | Wave × signal downward cross, regardless of zone |
Each alert fires through `alert()` so the message body carries live context — direction, current wave value, and the threshold that triggered. Divergence alerts respect the Smart Divergence Filter — if the filter is ON and a divergence is rejected visually, the alert will also not fire.
🟦 SETTINGS REFERENCE
**WaveTrend Core**
- Source — 9 price aggregates. Default: HLC3
- Channel Length — EMA midline + Welford stdev lookback. Default: 10
- Average Length — EMA smoothing of the normalized wave. Default: 21
- Signal Length — SMA smoothing of the wave to build the trigger. Default: 4
**Reversion Bands**
- Reversion Threshold — 50–200, step 5. Default: 100
- Show Band Fills — Toggle. Default: ON
- Band Opacity — 0–100. Default: 30
**Histogram**
- Show Histogram — Toggle. Default: ON
- Rising Opacity — Default: 60
- Fading Opacity — Default: 40
**Extremity Dots**
- Show Extremity Dots — Toggle. Default: ON
**Divergence**
- Regular Divergence — Toggle. Default: ON
- Regular Opacity — Default: 80
- Hidden Divergence — Toggle. Default: ON
- Hidden Opacity — Default: 80
- Label Size — Tiny / Small / Normal / Large. Default: Tiny
- Smart Divergence Filter (AI) — Master toggle. Default: OFF
- Min Wave Swing — Default: 5.0
- Min Price Swing (%) — Default: 0.3%
- Require Zone Confirmation — Default: ON
**Bar Coloring**
- Bar Color Mode — None / Midline Cross / Extremities / Reversions / Slope. Default: None
**Dashboard**
- Show Dashboard — Toggle. Default: ON
- Panel Position — 6 anchor slots. Default: Middle Right
- Panel Text Size — Tiny / Small / Normal / Large. Default: Small
**Alerts**
- OS Reversion — Default: ON
- OB Reversion — Default: ON
- Regular Divergence — Default: ON
- Hidden Divergence — Default: OFF
- Bullish Trend — Default: ON
- Bearish Trend — Default: ON
- Bullish Swing — Default: OFF
- Bearish Swing — Default: OFF
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in PulseWire Pine Script v6.
- Crypto: Spot, futures, perpetual contracts
- Forex: All pairs
- Equities: Stocks, ETFs, indices
- Commodities: Metals, energy, agriculture
- Timeframes: 1m through Monthly
The Welford running standard deviation normalizes the wave against its own dispersion, making the engine fully volatility-agnostic. The same default settings work on a 5-second BTC chart and a weekly index chart without retuning.
🟦 TECHNICAL NOTES
- Pine Script v6
- `max_lines_count = 500`, `max_labels_count = 500` (divergence drawings + extremity dot hover labels)
- No repainting — all values calculated on bar close. Pivot-based divergence results appear `Channel Length / 2` bars late by design
- WaveTrend engine intentionally mirrors EliCobra's original Enhanced WaveTrend formulation — the value added by Artemis Wave is in the Pine v6 idioms, the dynamic band scaling, the divergence engine, the Smart Filter, the theme system, and the dashboard, not in altering the well-tested core curve
- UDT fields declared without defaults to comply with Pine v6's compile-time-literal requirement; objects constructed via `Bar.new(...)` and `WaveReading.new(...)`
- `var int x = int(na)` pattern used for safe persistent integer state (pivot bar indices)
- Reversion-band anchors rendered as hidden `plot()`s rather than `hline()`s — `hline()` only accepts compile-time constants, but the band levels are series values driven by the user-tunable Reversion Threshold
- Extremity Dots use a dual-track rendering: `plot.style_circles` for the pixel-perfect visual, plus a parallel invisible `label.style_circle` carrying the hover tooltip (since `plot()` does not support the `tooltip` argument)
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. Always conduct your own analysis and apply proper risk management. Indicator

Markov Regime Oscillator PRO🟦 Markov Regime Oscillator PRO is a quantitative regime-classification and forward-probability forecasting engine rendered as a centred oscillator panel. Every bar is classified into one of three regimes — Bull, Bear, Sideways — using a drift-adjusted, volatility-normalised k·σ·√N threshold. The regime sequence feeds two parallel semi-Markov transition matrices (Young / Mature) with exponentially-decayed counts, producing live N-bar forward probabilities and 95 % Bayesian credible intervals on the next-bar probability vector.
The indicator integrates nine analytical layers — drift-adjusted classification, adaptive k·σ·√N threshold, EWMA-decayed transition matrix, semi-Markov duration conditioning, N-bar forecast cone via matrix iteration, Bayesian credible intervals, stationary distribution, velocity precursor with optional momentum filter, and multi-timeframe confluence — each rendered on a single oscillator panel through reference levels, a regime ribbon, gradient fill, three-layer neon glow signals, and an in-panel forecast polyline. A 30-row PRO status dashboard rendered on the main price chart (not the oscillator panel) reports every readout in real time.
Built with mathematical honesty. Every +1 forward probability carries a 95 % Dirichlet-posterior credible interval, the EWMA half-life is user-set so the model can adapt as market character evolves (2020 ≠ 2024), the semi-Markov split splits the chain on regime age so mature trends are not treated like young ones, and the documentation is explicit about what the model can and cannot predict.
🟦 HOW THE CORE ENGINE WORKS
Regime Classification
Each bar, the engine measures the rolling N-bar log return — optionally adjusted for the long-term drift of the asset:
logRet_raw = log(close / close )
meanDrift = SMA(log(close / close ), driftWin)
logRet = logRet_raw − N × meanDrift (when Drift Adjustment is ON)
The bar is labelled by comparing this return against the configured boundary:
- `logRet > +threshold` → BULL
- `logRet < −threshold` → BEAR
- otherwise → SIDEWAYS
The classification runs every bar with no look-ahead. When the optional Momentum Filter is enabled, the Bull / Bear labels additionally require the oscillator velocity to agree with the direction — killing late entries on exhausted moves.
Adaptive Threshold (k · σ · √N)
Traditional Markov regime indicators use a fixed percentage cut — e.g. "±5 % over 20 bars". This collapses on real markets: the same 5 % is trivial in a 2017 mania and never reached in 2023 chop. The fix is to scale the boundary with realised volatility:
threshold_adaptive = k × σ × √N
where σ is the per-bar log-return standard deviation over a configurable window (default 100 bars). Under a random walk, k = 1.0 cuts at the 16th / 84th percentiles; k = 2.0 at the 2.5th / 97.5th percentiles. The default k = 1.5 reproduces classic ±1.5-sigma thresholds.
Fixed-percentage mode is still available for users who want to lock the threshold deliberately.
Drift Adjustment (Alpha-Adjusted Classification)
Strong-trending markets (long BTC bull runs, persistently uptrending equity indices) carry a non-zero baseline drift. Without adjustment, the rolling log return systematically exceeds zero in such markets — producing excessive Bull-regime flips that reflect baseline drift rather than incremental kinetic energy.
The fix is to subtract the long-term mean drift before threshold comparison:
logRet_excess = log(close / close ) − N × mean(log returns, driftWin)
Log returns become EXCESS returns over the asset's own long-run drift — what quant desks call "alpha-adjusted" classification. The default 250-bar drift window approximates one trading year on the daily timeframe.
Oscillator Value
The classified log return is normalised by the active threshold and scaled to ±100 = boundary, clipped at ±300:
oscVal = clip( logRet / threshold × 100, ±300 )
The oscillator value is the central panel signal. Reference levels at ±100 (solid) mark the official regime boundaries, ±70 (dashed) mark the pending early-warning zone, and 0 (dashed) is the neutral midline.
Regime Confidence
Once classified, the move's strength is normalised relative to the active boundary:
confidence = |logRet| / threshold
| Confidence | Tier | Visual |
|---|---|---|
| < 1.0× | weak | ▱▱▱ |
| 1.0× – 2.0× | moderate | ▰▱▱ |
| 2.0× – 3.0× | strong | ▰▰▱ |
| ≥ 3.0× | stretched | ▰▰▰ |
The confidence value feeds the High Confidence alert (≥ 2.5× trigger) and is reported in the Status dashboard.
🟦 EWMA DECAY ON TRANSITION COUNTS
The Ancient-History Problem
A classic Markov chain counts every historical transition with equal weight — a Bull→Bear flip from five years ago contributes the same as one from yesterday. This breaks when market character changes: the 2020 COVID crash regime dynamics are not the same as 2024 retail mania, but a vanilla counter weighs them identically.
The Refinement (EWMA / RiskMetrics-style decay)
Markov Regime Oscillator PRO applies exponential decay to the transition counts every confirmed bar BEFORE incrementing for the new transition:
decayFactor = 0.5 ^ (1 / halfLife)
counts = counts × decayFactor (all 9 cells, every bar)
counts = counts + 1.0 (new transition)
After `halfLife` bars, an old count weighs HALF its original. This is the same math RiskMetrics uses for EWMA volatility — adapted here to regime transition memory.
| Half-life | Behaviour |
|---|---|
| 50 – 200 | highly reactive — adapts fast, probabilities noisy |
| 300 – 700 | balanced (default 500) |
| 1000+ | stable — slow adaptation, smooth probabilities |
The decay is applied to all three matrices in lockstep (full, young, mature) so the semi-Markov split below stays internally consistent.
🟦 SEMI-MARKOV DURATION CONDITIONING
The Memoryless Problem
A standard Markov chain says: "Given I'm in Bull, the probability of staying Bull tomorrow is X — regardless of whether Bull started yesterday or 200 bars ago." This is the memoryless property, and on real markets it's wrong. A 200-bar-old Bull regime carries different mean-reversion risk than a 5-bar-old one.
The Refinement
Markov Regime Oscillator PRO additionally builds two CONDITIONAL transition matrices:
- `P_young` — transitions counted when the source regime's age was below the Age Median input
- `P_mature` — transitions counted when the source regime's age was at or above the Age Median
Both matrices are constructed in parallel with the unconditional matrix, using the same per-bar bucketing logic, the same EWMA decay, and the same Dirichlet smoothing.
The active forecast then uses the matrix matching the CURRENT regime's tier — Young or Mature. A 5-bar-old Bull is statistically more likely to continue than a 50-bar-old one; semi-Markov captures this empirically without leaking into the unconditional chain.
The active matrix tier is reported live in the Status dashboard's "Matrix" cell.
🟦 N-BAR FORECAST CONE
Matrix Iteration
The 3×3 transition matrix P encodes one-bar-ahead probabilities. To project further out, the state vector is iterated through P:
s_0 = = unit vector on current regime
s_{k+1} = s_k · P (matrix multiplication)
For each step k = 1 … forecastSteps, the iteration produces the probability of each regime at that future bar.
Expected Oscillator Value
At each forecast step, the expected oscillator value is computed as:
E = 100 · ( P(Bull | k) − P(Bear | k) )
This number is +100 when the model expects pure Bull, −100 when pure Bear, and ~0 when Side.
In-Panel Polyline
The cone is rendered as a colored polyline extending PAST the last confirmed bar into the future, drawn via `line.new()` so segments are pixel-stable on any chart zoom. Each segment is colored by the dominant regime at that step (Bull / Bear / Side).
Honest Limitation
The cone is reliable up to ~5 bars; beyond that the iteration converges toward the stationary distribution and the forecast loses information. The default Forecast Horizon is 5 bars — covers the meaningful window without illusion.
The forecast is matrix-implied, not a momentum extrapolation. If the oscillator is currently at +250 (strong Bull) but the matrix says P(Bull → Side) is high, the cone will regress to the matrix-implied expected value — showing a visual "cliff" at step 1. This is mathematically honest, not a bug.
The dashboard's "HORIZON +N" cell reports the dominant regime at the terminal forecast step plus its probability — for a single-glance read of where the chain expects to be at horizon end.
🟦 BAYESIAN CREDIBLE INTERVALS
Why Ranges, Not Point Estimates
A forecast like "P(Bull) +1 = 75 %" carries hidden uncertainty. With only 30 historical Bull-source transitions, the true probability could plausibly be anywhere between 55 % and 90 %. With 2000 historical Bull-source transitions, the same 75 % is tightly bracketed at, say, 73 – 77 %.
Reporting a single number hides the difference. Hedge-fund and academic forecasts always carry uncertainty bands; this oscillator does the same.
The Derivation (Dirichlet Posterior, Gaussian Approximation)
The transition matrix posterior is Dirichlet(α + counts) with Laplace (α = 1) prior. Each marginal is Beta with parameters (α_i, Σα − α_i). The Gaussian approximation to that Beta gives:
mean = α_i / Σα
var = α_i · (Σα − α_i) / ( Σα² · (Σα + 1) )
95 % CI ≈ mean ± 1.96 · √var
The CI is computed for the +1 row (the most actionable forecast) and clipped to .
Reading the Dashboard
P(Bull) +1 75 %
| CI Width | Interpretation |
|---|---|
| Narrow (e.g. 73 – 77) | large sample, robust estimate, trust the call |
| Wide (e.g. 50 – 95) | small sample, fragile estimate, don't bet the desk |
This is the difference between a quantitative estimate and an indicator guess.
🟦 STATIONARY DISTRIBUTION π
Power-iterating the matrix to convergence yields the stationary distribution — the long-run probability of being in each regime, independent of the current state. With 50 iterations on a well-behaved stochastic matrix, the distribution is essentially converged.
π(Side) + π(Bull) + π(Bear) = 1.0
The dashboard's "STATIONARY π" section reports each component. Reading π reveals the asset's structural bias regardless of the current regime — e.g., π(Bull) = 55 % on BTC daily tells you the market spends a majority of its time in Bull regimes over the long run, which is fundamentally different from a sideways-grinding instrument with π(Side) = 60 %.
The stationary distribution also serves as the asymptote of the forecast cone: as k → ∞, the cone collapses to π.
🟦 VELOCITY PRECURSOR & MOMENTUM FILTER
Velocity Definition
The oscillator velocity is the N-bar rate-of-change of the oscillator value:
velocity = oscVal − oscVal
velocityThr = VELOCITY_BASE · √(velocityWin / 5)
The threshold auto-scales with the window so the accel / decel / flat labels stay meaningful at any setting.
Early-Warning Cue
Velocity flips direction BEFORE the official ±100 boundary is crossed — it is a leading indicator of regime change. The Status dashboard's "Velocity" cell displays:
- ↑ accelerating (velocity > +threshold) — colored bull
- ↓ decelerating (velocity < −threshold) — colored bear
- ═ flat — neutral
This partially mitigates the inherent lookback lag of threshold-based regime detection.
Optional Momentum Filter
When the Momentum Filter is enabled, regime classification additionally requires velocity sign agreement:
Bull → logRet > +threshold AND velocity > 0
Bear → logRet < −threshold AND velocity < 0
This kills late-entry signals where price has extended past the threshold but momentum is already exhausted — a classic source of false signals at trend tops/bottoms. Reduces signal count, raises signal quality. Recommended for swing trading, optional for scalping.
🟦 PENDING-REGIME EARLY WARNING
Because the regime is classified from `log(close / close )`, the official regime label inherently lags. This is structural, not a bug, but can be partially mitigated.
Inside Sideways, when the log return reaches 70 % of either boundary, the dashboard fires an early-warning cue:
distance_fraction = max(|logRet| / threshold, ...)
isPending = (regime == SIDE) AND (distance_fraction ≥ 0.70)
The Status panel's "Pending" cell displays the direction the return is leaning toward and the current fraction:
⚠ ▲ BULL 87 %
Color matches the leaning regime. The Pending Regime alert (default OFF, opt-in) fires on the first bar a pending state is entered.
This is not a regime change signal — it's a "watch this" cue, triggered roughly 30 % before the official threshold is crossed. Used alongside the official regime change, it gives the user advance notice without compromising the threshold's strictness.
🟦 SELECTABLE SIGNAL SMOOTHING
A second smoothed signal line overlays the main oscillator. Crossovers between the main and signal lines mark momentum-of-regime shifts — these often precede actual regime changes by 1-3 bars.
Four smoothing algorithms are available:
| Method | Character |
|---|---|
| EMA (default) | Exponential — classic lag/smoothness |
| HMA | Hull — near-zero lag for short windows |
| ALMA | Arnaud Legoux (0.85, 6.0) — Gaussian-weighted, smoothest |
| SMA | Simple — most stable, most lag |
The Signal Cross alert can be optionally filtered by HTF alignment — when enabled, the alert fires only when LTF and HTF regimes match. Filter is auto-bypassed when HTF Confluence is globally OFF (silent-kill protection).
🟦 MULTI-TIMEFRAME CONFLUENCE
The same regime logic runs on a user-configured higher timeframe via `request.security` with `lookahead = barmerge.lookahead_off` and `gaps = barmerge.gaps_off` (anti-repaint mandatory). The result is reported in the Status dashboard's HTF block:
| State | Display | Color |
|---|---|---|
| HTF regime matches LTF regime | ✓ ALIGNED | bull |
| HTF regime differs from LTF | ⚠ DIVERGENT | bear |
| Insufficient HTF data | — | foreground |
Divergent regimes are common at trend turns — the LTF flips before the HTF catches up. Aligned regimes carry higher conviction. A separate alert ("MTF Confluence") fires on regime entries only when the HTF agrees.
Recommended pairings:
| Chart | HTF |
|---|---|
| 15m | 1H |
| 1H | D |
| 4H | W |
| D | W |
| W | M |
Use at least 3× your chart timeframe — anything closer and the two regimes track each other with no information gain.
🟦 OSCILLATOR PANEL VISUAL LAYER
Main Oscillator Line
The oscillator value plotted as a continuous line with five color tiers reflecting regime strength:
| Range | Color |
|---|---|
| ≥ +100 | full Bull |
| +70 to +100 | dim Bull (pending up) |
| −70 to +70 | neutral Side |
| −100 to −70 | dim Bear (pending down) |
| ≤ −100 | full Bear |
Line width is configurable 1 – 5 pixels.
Signal Line
A smoothed overlay of the main oscillator, faded foreground color, single-pixel width. Drives the Signal Cross alert and the dashboard Signal cell.
Reference Levels
Three horizontal levels per panel side:
- ±100 — official regime boundaries (solid plot line)
- ±70 — pending early-warning zones (dashed `line.new`)
- 0 — neutral midline (dashed `line.new`)
The dashed lines use `line.new()` rather than `plot.style_circles` so they remain pixel-stable at any chart zoom — they will NOT rescale or fragment.
Regime Ribbon
The oscillator panel background is tinted to the current regime color at 20 % opacity. Provides instant regime context at a glance — Bull / Bear / Side periods are visually separated even when zoomed out on long history. Toggleable.
Gradient Fill
The area between the oscillator line and zero is filled in the regime color, with intensity scaling adaptively by distance from zero — stronger color = higher conviction. Empty at zero.
Three-Layer Neon Glow Signals
On every confirmed regime transition (after the Min Hold filter passes), the indicator drops a three-layer halo on the oscillator line:
| Layer | Size | Transparency | Purpose |
|---|---|---|---|
| Outer | size.large | 80 % | Soft halo |
| Middle | size.normal | 50 % | Mid-glow |
| Core | size.small | 0 % | Bright center |
Bull entries (▲ triangle up), Bear entries (▼ triangle down), and Side entries (◆ diamond). The Min Hold input (default 4 bars) requires a new regime to persist before its flip is drawn — kills label spam in choppy zones without affecting the underlying transition counts.
Forecast Cone Polyline
On the last confirmed bar, a colored polyline extends into the future for N bars, plotting the expected oscillator value at each step. Color reflects the dominant regime at that step. Drawn with `line.new()` so segments are pixel-stable; recomputed on every chart refresh.
🟦 PRO STATUS DASHBOARD
A single dashboard rendered on the MAIN PRICE CHART (not the oscillator panel) via `force_overlay = true`. This keeps the oscillator panel uncluttered so the oscillator line, signal line, gradient fill, and forecast cone get the full pane height.
The dashboard is structured in seven sections, all theme-aware:
| Section | Cells |
|---|---|
| REGIME | Regime, Age + tier, Confidence, Pending, Velocity |
| FORECAST +1 | P(Bull), P(Bear), P(Side) — each with 95 % CI |
| HORIZON +N | Dominant regime at terminal forecast step + probability |
| STATIONARY π | π(Bull), π(Bear), π(Side) — long-run equilibrium |
| OSCILLATOR | Value, Signal direction, Threshold, Drift basis points |
| HTF | Regime + Aligned / Divergent status |
| DATA | Mode, Decay half-life, Matrix tier, Sample N |
Position is configurable across 9 chart corners. Text size: Tiny / Small / Normal / Large. Default Tiny so the full 30-row layout fits on any chart without scrolling. Background and text colors flip between Dark and Light display modes.
🟦 COLOR THEMES
Ten cohesive palettes tuned to the Apex design system, each defining three regime axes (Bull, Bear, Sideways):
| Theme | Character | Bull | Bear | Sideways |
|---|---|---|---|---|
| Focus (default) | Modern | Cyan | Deep orange | Cool blue-grey |
| Prism | Classic | Forest green | Crimson | Slate grey |
| Solar | Warm | Amber | Indigo red | Lavender grey |
| Frost | Cool | Sky blue | Soft lavender | Pale steel |
| Laser | Neon | Lime green | Hot crimson | Charcoal grey |
| Aurora | Bright | Gold | Scarlet | Warm beige |
| Plasma | Electric | Aqua | Magenta | Slate teal |
| Bloom | Soft | Mint | Hot pink | Blue-grey |
| Eclipse | Deep | Navy | Dark crimson | Steel grey |
| Carbon | Minimal | Near-white | Mid-grey | Dark grey |
One theme selection drives every visual component: oscillator line, signal line, reference levels, ribbon, fill, glow signals, forecast cone, and all dashboard cells.
Dark / Light Display Mode
Dashboard chrome (background, foreground, borders, section dividers) flips between dark-on-bright and bright-on-dark. The regime axis colors remain consistent across modes — only the panel chrome changes.
🟦 ALERT SYSTEM
Seven alert conditions, each independently togglable:
| Alert | Condition |
|---|---|
| Bull Regime Entry | Regime flipped to BULL (after Min Hold confirmation) |
| Bear Regime Entry | Regime flipped to BEAR (after Min Hold confirmation) |
| Sideways Regime Entry | Regime flipped to SIDEWAYS (default OFF) |
| High Confidence | confidence ≥ 2.5× threshold, first bar of crossing |
| Pending Regime | Inside Sideways, log return ≥ 70 % of either boundary (default OFF) |
| MTF Confluence | Bull / Bear entry + HTF agrees |
| Signal Cross | Main oscillator crosses signal line (default OFF) |
All alerts fire on confirmed bar close. Entry alerts respect the Min Hold filter — a new regime must persist Min Hold bars before its entry alert fires, matching the on-chart glow markers.
The Signal Cross alert can be optionally filtered by HTF alignment (Multi-Timeframe → Filter Signal Cross by HTF). The filter is automatically bypassed when HTF Confluence is globally OFF, so enabling the filter without HTF doesn't silently kill the alert.
🟦 SETTINGS REFERENCE
Theme
- Theme — One of 10 Apex palettes. Default: Focus
- Display Mode — Dark / Light. Default: Dark
Regime Logic
- Threshold Mode — Adaptive (k·σ·√N) / Fixed (%). Default: Adaptive
- Lookback Window — Bars for the rolling log return. Default: 20
- Adaptive k — Sigma multiplier. Default: 1.5
- Fixed Bull Threshold — Used only in Fixed mode. Default: 5.0 %
- Fixed Bear Threshold — Used only in Fixed mode. Default: 5.0 %
- Volatility Window — Bars for the per-bar stdev. Default: 100
- Min Hold — Bars a new regime must persist for entry alerts and glow markers. Default: 4
- Drift-Adjusted Log Returns — Toggle the drift adjustment. Default: ON
- Drift Window — Bars for the long-term mean drift estimate. Default: 250
- Require Momentum Agreement — Velocity sign filter on regime classification. Default: OFF
Bayesian Math
- EWMA Transition Counts (Decay) — Toggle exponential decay. Default: ON
- Decay Half-Life — Bars after which an old count weighs half. Default: 500
- Semi-Markov Duration Conditioning — Toggle the Young / Mature split. Default: ON
- Age Median — Boundary between Young and Mature regimes. Default: 10
- Bayesian Credible Intervals (95 %) — Toggle CI display in the dashboard. Default: ON
Forecast
- Forecast Cone Horizon — Number of bars projected by matrix iteration. Default: 5
- Show Forecast Cone — Toggle the in-panel cone polyline. Default: ON
Oscillator
- Show Signal Line — Toggle the smoothed signal overlay. Default: ON
- Signal Smoothing Method — EMA / HMA / ALMA / SMA. Default: EMA
- Signal Smoothing Length — Window length. Default: 5
- Velocity Window — Bars for the rate-of-change measurement. Default: 5
- Oscillator Line Width — Pixels. Default: 2
Display
- Show Regime Ribbon — Toggle the panel background tint. Default: ON
- Show Gradient Fill — Toggle the oscillator-vs-zero fill. Default: ON
- Show Reference Levels — Toggle the ±100 / ±70 / 0 horizontal lines. Default: ON
- Show Regime Change Glow — Toggle the three-layer halo markers. Default: ON
Multi-Timeframe
- Enable HTF Confluence — Toggle. Default: ON
- HTF Resolution — Higher timeframe. Default: D
- Filter Signal Cross by HTF Alignment — Conditional filter on cross alert. Default: OFF
Dashboard
- Show Status Dashboard — Toggle. Default: ON
- Position — Nine chart corners. Default: Top Right
- Size — Tiny / Small / Normal / Large. Default: Tiny
Alerts
- Bull / Bear / Sideways Regime Entry — Independent toggles
- High Confidence (≥ 2.5×) — Default: ON
- Pending Regime — Default: OFF
- MTF Confluence — Default: ON
- Signal Cross — Default: OFF
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in PulseWire Pine Script v6.
- Crypto: Spot, futures, perpetual contracts
- Forex: All pairs
- Equities: Stocks, ETFs, indices
- Commodities: Metals, energy, agriculture
- Timeframes: 1m through Monthly
The adaptive threshold normalises by per-bar realised volatility, and the drift adjustment normalises by the asset's long-run mean drift — together making the regime classification volatility-and-drift-agnostic across assets without manual recalibration. The same default settings work on BTCUSDT daily, SPY weekly, and EURUSD 4H — only the HTF resolution input should be adjusted to match the chart timeframe.
🟦 TECHNICAL NOTES
- Pine Script v6
- `max_labels_count = 500`, `max_lines_count = 500`, `max_bars_back = 5000`
- No repainting — all regime classifications are computed on confirmed bar close. The HTF request uses `lookahead = barmerge.lookahead_off` and `gaps = barmerge.gaps_off`
- Transition counting uses `barstate.isconfirmed` to avoid double-counting the live bar
- Regime change debouncing uses `ta.barssince` to avoid runtime-indexed history reads (which can trip "cannot determine max_bars_back" in Pine v6)
- Heavy computation (P matrix construction, N-step iteration, Bayesian CI math, stationary distribution power iteration, dashboard rendering) is gated on `barstate.islast` to run once per chart render
- Matrix multiplication is implemented as unrolled single-line expressions over a flat 9-cell array for portability and speed
- EWMA decay multiplies all 9 cells of all 3 matrices (counts, countsYoung, countsMature) once per confirmed bar — O(27) per bar overhead
- Dirichlet smoothing prevents NaN propagation when a regime has not appeared in visible history — empty rows fall back to uniform 1/3
- Duration buckets classify by the SOURCE regime's age at the moment of transition (`regAge `), so the bucketing reflects the regime that was about to transition rather than the destination
- `ta.crossover` / `ta.crossunder` are computed at global scope every bar to satisfy Pine's stateful-series rule (the gated cross events read from the cached values)
- Dashboard is rendered with `force_overlay = true` on the main price chart — keeps the oscillator panel free of UI clutter
- Reference-level dashed lines use `line.new()` with `style = line.style_dashed` and `extend = extend.both` for pixel-stable rendering at any zoom
🟦 LIMITATIONS — READ THIS
This indicator is statistically honest about what it can and cannot do. Four known limitations:
1. The Markov assumption is partially violated. Markets are not memoryless. The semi-Markov Young / Mature split mitigates this but does not eliminate it. EWMA decay further mitigates by down-weighting ancient transitions, but a truly path-dependent process (one where the SEQUENCE of recent regimes matters, not just the last one) is not captured.
2. Forward probabilities are not predictions. They are conditional probabilities under the chain assumption with the credible intervals quantifying the SAMPLING uncertainty around them. A "Bull 58 % at +5 bars" reading does not mean "58 % chance the next 5 bars are bullish" — it means "given a long-run sample of similar starting states and the active EWMA-decayed transition matrix, 58 % were in Bull at +5 bars". Use the cone as ONE input alongside other analysis.
3. The regime label lags by N bars. This is structural — the rolling log return necessarily looks back. The Pending early warning and the optional Momentum Filter partially mitigate this but cannot eliminate the lag. Treat the official regime change as a confirmation, not a leading signal.
4. Forecast cone reliability decays with horizon. By +5 bars the cone is at the edge of usefulness; by +20 bars it collapses toward the stationary distribution and carries no additional information beyond π. The default horizon is 5 bars for this reason. Do not over-interpret the right side of the cone.
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. The forward probabilities are conditional estimates derived from historical transition counts under a (semi-)Markov model assumption — they are NOT guarantees about future market behaviour. Always conduct your own analysis and apply proper risk management. Indicator

Indicator

RSI Volume LadderA long-only pyramiding strategy that scales into corrections using RSI oversold conditions confirmed by above-average volume. Each subsequent entry requires a meaningful price drop from the previous fill, with an asymmetric exit structure: Take Profit anchored to the average entry, Stop Loss anchored to the lowest fill. Built for traders who want to systematically dollar-cost into pullbacks within an uptrend, with clearly defined risk per pyramid stack.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ORIGINALITY — WHAT MAKES THIS DIFFERENT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Five specific mechanics that, in this combination, distinguish this script from other averaging-down systems published on PulseWire:
- ASYMMETRIC EXIT ANCHORING
Take Profit is calculated from the average entry price of the pyramid — so winners run from the averaged-down cost basis. Stop Loss is calculated from the LOWEST entry price among all open positions — so the absolute worst-case loss is bounded by your deepest fill, not your average. This asymmetry is the key to making pyramiding viable: averaging works for you on the upside without inflating downside risk.
- PRICE-DROP GATE FOR EACH PYRAMID LEG
Every subsequent entry requires both a fresh RSI + volume signal AND a configurable minimum price drop from the previous fill (default 1.5%). This prevents stacking three positions within a tight range during a slow grind down — pyramiding only triggers on meaningful pullbacks, forcing real averaging instead of cosmetic averaging.
- ASYMMETRIC COOLDOWN ON EXIT
After a Stop Loss, the strategy waits N bars (default 3) before allowing new entries — blocks the "catch the falling knife" pattern where RSI stays oversold for many bars during a cascade. After a Take Profit, cooldown is configurable separately and defaults to 0, because a successful exit signals continued mean-reversion behavior worth participating in.
- ENTRY-TIMING SAFETY
Exit detection runs at the top of the bar evaluation, BEFORE the entry check. This means a Stop Loss hit on a bar cannot trigger a new entry on the same bar — even if RSI is still deeply oversold and volume is elevated. The cooldown counter is set before the entry logic ever sees the bar, eliminating a subtle but realistic execution problem in pyramiding systems.
- VISUAL EXIT CLASSIFICATION
When the position closes, the script automatically classifies the exit as TP or SL by measuring distance from actual fill price to each pre-set level, and renders a fuchsia or red cross at the exit price. No look-ahead, no estimation — the classification uses the closed trade's recorded exit price.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CREDITS & FOUNDATIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This script builds on established methodologies with original Pine v5 implementation of every layer:
- RSI — Wilder, 1978 (standard implementation via ta.rsi)
- Volume confirmation — classical technical analysis
- Pyramiding / scaling-in — standard portfolio management technique (Tharp, Elder)
- Dollar-cost averaging principles — long-standing investment methodology
ALL CODE in this script was written from scratch. No code has been copied from other public or private scripts. The five mechanics listed under ORIGINALITY above are original combinations and implementations.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW THE STRATEGY WORKS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ENTRY CONDITIONS (all must be true):
- RSI below the configurable oversold threshold (default 30)
- Volume above SMA × configurable multiplier (default 1.5× of SMA20)
- For pyramiding: price must be at least X% below the last fill (default 1.5%)
- Cooldown not active from the previous exit
- Open positions count below the pyramiding cap (default 3)
PYRAMID BUILDING:
Up to 3 long positions can be opened. Each new entry independently re-checks all conditions — the RSI + volume signal must reappear, AND the price drop gate must be satisfied. Position size per entry is fixed (default 5% of equity), so a full three-position stack uses approximately 15% of equity.
EXIT LOGIC:
Both legs run as an OCO (one-cancels-other) bracket:
Take Profit = average entry × (1 + tpPercent / 100), default +4%
Stop Loss = lowest entry × (1 − slPercent / 100), default −3%
All positions close together when either level is hit. The TP/SL levels update on every bar as the pyramid grows — average shifts on each new fill, lowest fill anchors deeper if a new low is hit.
COOLDOWN MECHANISM:
On exit, the strategy records the bar index and exit type. While bar_index − lastExitBar ≤ requiredCooldown , new entries are blocked. The required cooldown differs by exit type (default 3 bars after SL, 0 bars after TP), reflecting that an SL exit often happens during continuing weakness, while a TP exit signals healthy mean reversion.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VISUALIZATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ENTRY ARROWS — blue triangles below each fill, labeled Long_1 / Long_2 / Long_3 with the order price
AVERAGE ENTRY LINE — blue, updates as the pyramid grows (staircase pattern)
TAKE PROFIT LINE — fuchsia, updates with the average
STOP LOSS LINE — red, anchored to the lowest fill (steps down only if a deeper entry occurs)
EXIT CROSS — fuchsia at TP hit, red at SL hit, placed at the actual exit price
The line style is plot.style_linebr , which connects within an open position and breaks cleanly between positions — making each pyramid cycle visually self-contained on the chart.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW TO USE IT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This is a complete entry + exit strategy, but it is NOT a turn-it-on-and-walk-away system. Use it as a framework to test and adapt to your specific instrument:
- Load on a liquid asset with mean-reverting behavior in an uptrend. The strategy was developed on crypto majors (BTC, ETH) and major equity indices.
Start with the default parameters and run the Strategy Tester on at least 6 months of history.
- Pay attention to:
• Net Profit and Max Drawdown ratio
• Average loss vs. average win
• Whether losing streaks cluster during specific market regimes
Tune to your instrument's volatility:
• Higher-volatility assets (alt-coins, small caps) → increase dropPercent (2-3%), increase slPercent (4-6%)
• Lower-volatility assets (BTC, indices) → decrease dropPercent (1-1.5%), tighter slPercent (2-3%)
• Higher timeframes (1h, 4h) → wider TP/SL to match bar range
- Consider adding an external trend filter for your live use. The strategy will pyramid into any oversold reading regardless of higher-timeframe context. Adding an EMA200 filter (only enter if price > EMA200) materially changes the risk profile on instruments prone to extended downtrends.
- Treat the strategy output as a structured framework for your dip-buying process, not as a guaranteed system. Combine with your own market analysis, position sizing, and broader risk management.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
INPUTS WORTH KNOWING
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
RSI Length (default 14) and Oversold threshold (default 30) — standard RSI configuration. Lower threshold = fewer, deeper-oversold entries.
Volume SMA length (default 20) and Multiplier (default 1.5×) — volume confirmation strength. Higher multiplier = only enter on standout volume spikes, fewer entries.
Min drop between pyramid entries (default 1.5%) — prevents tight clustering. Higher = waits for deeper pullbacks before adding.
Max pyramid positions (default 3) — caps the stack. Note: pyramiding=3 is also set in the strategy() header.
Take Profit % from average (default 4%) — anchored to running average entry price.
Stop Loss % from lowest fill (default 3%) — anchored to the deepest entry, shared across all open positions.
Cooldown after SL (default 3 bars) — blocks the falling-knife pattern after a stop-out.
Cooldown after TP (default 0 bars) — re-enter immediately after a successful exit.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
REALISTIC EXPECTATIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Pyramiding into corrections is a well-known approach with well-known limitations. The strategy works best when:
The underlying asset has a structural uptrend
Volatility produces regular pullbacks of meaningful depth
The market is not in a sustained bear regime
What this strategy provides:
A disciplined framework for scaling into pullbacks instead of single-shot entries
Asymmetric exit anchoring that lets winners run from the averaged cost basis
Built-in protection against catching the falling knife via cooldown
Transparent visualization of each pyramid leg, exit, and risk level
What it does NOT provide:
Protection from prolonged bear trends (averaging down into a structural decline is the dominant failure mode of this entire strategy family)
A guaranteed profitable system
A signal generator for assets that don't mean-revert
A replacement for your own market analysis, position sizing, or higher-timeframe context
Treat the output as ONE structured input in your trading process. The biggest risk to your account using a pyramiding strategy is mis-applying it to a downtrending asset — always confirm regime alignment before going live.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TECHNICAL NOTES & DISCLOSURES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
NO REPAINT . Uses process_orders_on_close=true — all orders execute on confirmed bar close. No request.security() calls, no lookahead_on, no barmerge.lookahead_on.
REALISTIC EXECUTION . Default commission 0.05% per trade (typical crypto exchange taker fee). Position sizing in % of equity, not fixed contracts. Initial capital 10,000.
DATA USED : only standard Pine inputs — open, high, low, close, volume. Indicators: RSI, SMA of volume. No external feeds, no security() calls, no synthetic data.
PERFORMANCE : max_labels_count=500. Pyramiding capped at 3. No unbounded growth of internal objects.
ASSETS : developed on crypto majors and tested across 5m, 15m timeframes. Works on equities and forex but parameters were tuned on crypto and may need adjustment for assets with different intraday behavior.
EDUCATIONAL AND ANALYTICAL TOOL . Intended for traders who understand pyramiding mechanics and the inherent risk of averaging-down strategies, and who want a structured framework to test on their own instruments.
OPEN SOURCE . Read the code, learn from it, fork it. Feedback and bug reports welcome in the comments.
Check my profile for other published scripts. Strategy

Volatility Prism [JOAT]Volatility Prism
Introduction
Volatility Prism is an open-source dual Bollinger Band envelope system with percentile-based bandwidth squeeze detection and Stochastic RSI confirmation. It renders two independent envelopes — an inner band at a configurable standard deviation multiplier and an outer band at a wider multiplier — with gradient fills that color dynamically based on whether price is in a bullish or bearish position relative to the moving average basis. When the bandwidth compresses to a historically low percentile, a squeeze state is declared. When the squeeze releases, an expansion signal fires.
The problem Volatility Prism solves is that volatility states are cyclical: periods of compression (squeeze) reliably precede periods of expansion (breakout), and the direction of the breakout is where the opportunity lies. By combining a statistically-based squeeze detector — which uses percentile thresholds rather than fixed bandwidth levels — with Stochastic RSI extreme confirmation, Volatility Prism identifies both the compression state and the likely directional bias of the coming expansion simultaneously.
Core Concepts
1. Dual Bollinger Band Structure
Two separate Bollinger Band pairs share the same basis (SMA of the source) but use different standard deviation multipliers. The inner band (default 2.0x) is the primary envelope. The outer band (default 3.0x) defines the extreme extension zone. Price trading beyond the inner band but inside the outer band is in the elevated zone. Price trading beyond the outer band is in a statistical extreme:
basis = ta.sma(src, bbLen)
dev = ta.stdev(src, bbLen)
upper1 = basis + bbMult1 * dev // Inner upper
lower1 = basis - bbMult1 * dev // Inner lower
upper2 = basis + bbMult2 * dev // Outer upper
lower2 = basis - bbMult2 * dev // Outer lower
The trend bias is determined by whether the close is above or below the basis. When bullish, all envelope lines and fills render in the bullish color. When bearish, they render in the bearish color. This makes the trend state immediately visible from the envelope color alone.
2. Gradient Envelope Fills
Four gradient fills create the visual envelope structure. The inner fills gradient from a near-opaque shade at the band edge to a nearly transparent shade at the basis, creating a density effect that visually represents how far price is from the center. The outer fills extend this gradient into the extreme zone at reduced opacity, cleanly separating the normal, elevated, and extreme price zones:
fill(basisPlot, upper1Plot, upper1, basis, color.new(envCol, 85), color.new(envCol, 98), "Upper Inner Fill")
fill(upper1Plot, upper2Plot, upper2, upper1, color.new(envCol, 75), color.new(envCol, 88), "Upper Outer Fill")
3. Percentile-Based Bandwidth Squeeze Detection
The bandwidth (the width of the inner band as a percentage of the basis) is computed on each bar and added to a rolling history array of configurable length. The current bandwidth is compared to the percentile threshold of that history — if the current bandwidth is below the configured percentile (default 15th percentile), the squeeze state is active:
bandwidth = basis > 0 ? (upper1 - lower1) / basis * 100 : 0.0
// Sort history and find threshold at configured percentile
threshIdx = int(array.size(sorted) * sqzPctile / 100) - 1
sqzThreshold = array.get(sorted, threshIdx)
isSqueezing = bandwidth <= sqzThreshold
This approach adapts to the instrument and timeframe automatically — a 15th percentile squeeze on a low-volatility bond future and on a high-volatility crypto asset will both correctly identify when that specific instrument is in an unusually compressed state relative to its own history.
4. Stochastic RSI Extreme Confirmation
The Stochastic RSI (an oscillator that applies Stochastic logic to RSI values) provides momentum extreme confirmation. Overbought and oversold readings from the K and D lines confirm when band extremes coincide with momentum extremes, strengthening band rejection signals:
rsiVal = ta.rsi(src, rsiLen)
stochVal = ta.stoch(rsiVal, rsiVal, rsiVal, stochLen)
kLine = ta.sma(stochVal, smoothK)
dLine = ta.sma(kLine, smoothD)
stochOB = kLine > upperLim and dLine > upperLim // Overbought
stochOS = kLine < lowerLim and dLine < lowerLim // Oversold
5. Band Rejection Signals and Squeeze Breakout
Three signal types are generated. Bullish band rejection fires when price was below the inner lower band on the previous bar and closes back above it, with Stochastic RSI confirming oversold — a failed breakdown with momentum confirmation. Bearish band rejection fires on the symmetric condition above the inner upper band. Squeeze Breakout fires on the first bar that transitions from squeeze to non-squeeze state — the moment the bandwidth begins expanding:
bearRejection = close > upper1 and close <= upper1 and stochOB
bullRejection = close < lower1 and close >= lower1 and stochOS
sqzBreakout = isSqueezing and not isSqueezing
6. Band Price Labels at the Right Edge
All five band lines (U2, U1, MA, L1, L2) receive price labels at the right edge of the chart. These labels update every bar to show the current price of each level, eliminating the need to hover over lines or read the y-axis to determine band values:
if barstate.islast and showBandLbls
lblU2 := label.new(bar_index + 2, upper2,
"U2 " + str.tostring(upper2, format.mintick),
style=label.style_label_right, ...)
Features
Dual Bollinger Band envelopes: Inner and outer bands with independently configurable multipliers
Adaptive gradient fills: Four gradient fills (inner upper, inner lower, outer upper, outer lower) color dynamically with trend bias
Dynamic trend coloring: All envelope elements switch between bullish and bearish colors based on close vs. basis
Percentile-based squeeze detection: Bandwidth compared to a configurable percentile of its rolling history — adapts to any instrument's volatility profile
Configurable squeeze lookback: Rolling bandwidth history window from 20 to 500 bars
Squeeze background shading: Optional chart background shading during active squeeze state
Stochastic RSI confirmation: K and D line extreme zones confirm band rejection signal quality
Three signal types: Bull Rejection, Bear Rejection, and Squeeze Breakout markers with distinct shapes
Band price labels at right edge: Live price labels for all five band levels (U2, U1, MA, L1, L2) at bar_index + 2
Institutional dashboard (top right): 11-row table with Volatility state (SQUEEZE/EXPANDING), Bandwidth %, Trend, StochRSI state, K and D values, Basis price, and Envelope range
Fully configurable inputs: BB length, both multipliers, squeeze lookback and percentile, Stochastic RSI parameters, and all colors independently adjustable
Alerts: Bull Rejection, Bear Rejection, Squeeze Breakout, and Squeeze Entry alertconditions
Input Parameters
Bollinger Bands:
Source: Price source (default: close)
BB Length: MA and standard deviation period (default: 20)
Inner Mult: Standard deviation multiplier for inner bands (default: 2.0)
Outer Mult: Standard deviation multiplier for outer bands (default: 3.0)
Squeeze Detection:
Bandwidth Lookback: Rolling history window for percentile calculation (default: 120 bars)
Squeeze Percentile: Bandwidth percentile below which squeeze is active (default: 15th)
Stochastic RSI:
K Smoothing (default: 3), D Smoothing (default: 3)
RSI Length (default: 14), Stochastic Length (default: 14)
Overbought level (default: 80), Oversold level (default: 20)
Display:
Show Dashboard toggle
Squeeze Background toggle
Band Price Labels toggle
Bullish Envelope color, Bearish Envelope color, Basis Line color, Squeeze Background color
How to Use This Indicator
Step 1: Identify the Volatility State
The dashboard's Volatility row shows SQUEEZE (yellow) or EXPANDING (gray). When SQUEEZE is active, the chart background shades yellow. A squeeze state means bandwidth has compressed to a historically low percentile — the market is loading energy for a directional move.
Step 2: Watch for Squeeze Breakout Signals
The cross (x) marker appears at the first bar that exits a squeeze. This is the moment bandwidth begins expanding. The direction of the breakout bar (bullish or bearish candle) combined with the trend color of the envelope provides the directional lean for the expansion phase.
Step 3: Interpret Envelope Color for Trend Bias
When all envelope elements are teal, price is above the basis — bullish bias. When all elements are orange, price is below the basis — bearish bias. Use the envelope color as a continuous trend indicator overlaid directly on the price.
Step 4: React to Band Rejection Diamonds
Diamond markers at the band edge indicate price failed to sustain a move beyond the inner band and recovered inside, with Stochastic RSI confirming the extreme. These are mean-reversion entry signals — price rejected the statistical extreme with momentum confirmation.
Step 5: Reference Band Price Labels
The right-edge labels show the current price of each band level. Use these when planning take-profit targets (opposite band) or stop-loss placement (outer band beyond entry) without needing to manually read prices from band lines.
Indicator Limitations
The squeeze detector requires a minimum of sqzLen bars of bandwidth history to activate. On short charts or immediately after the indicator is applied, the squeeze state will not register until enough history is accumulated
The percentile-based squeeze threshold adapts to the lookback window. A longer lookback produces a more stable threshold; a shorter lookback adapts faster but may produce more frequent squeeze entries and exits
Band rejection signals require the close to recover inside the band on the bar immediately following the outside close. Multi-bar breakouts that recover more slowly are not detected as rejections
Squeeze Breakout markers fire on the first bar exiting a squeeze regardless of candle size or direction. They do not independently confirm the breakout direction — the envelope trend color and Stochastic RSI must be used to assess directional bias
Stochastic RSI is a double-transformed oscillator (RSI → Stochastic). It can reach and hold extreme levels for extended periods in strong trends, producing frequent overbought or oversold readings that reduce the specificity of band rejection confirmation
Originality Statement
Volatility Prism is original in its adaptive, percentile-based squeeze detection combined with a dual-envelope gradient structure and Stochastic RSI extreme confirmation with right-edge band price labels. This indicator is published because:
Using the rolling percentile of bandwidth history — rather than fixed bandwidth values or the classic Keltner Channel comparison method — for squeeze detection provides an instrument-adaptive and timeframe-adaptive threshold that requires no manual calibration
The dual-envelope structure (inner and outer bands) with four independent gradient fills that change color based on real-time trend bias creates a visually rich, information-dense chart overlay without adding separate indicator panes
The right-edge band price labels for all five band levels eliminate a common usability friction point in Bollinger Band analysis, where traders must hover over lines or estimate prices from the y-axis scale
The three-signal system (Bull Rejection, Bear Rejection, Squeeze Breakout) operating from two independent mechanisms (band geometry + Stochastic RSI for rejections, bandwidth percentile for breakout) provides distinct signal categories suited to different trading styles
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Bollinger Bands and Stochastic RSI readings are historical statistical tools. Squeeze states can persist for extended periods without producing a breakout, and breakouts can occur in either direction. Band rejection signals do not guarantee price will reverse from the band. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Artemis Volatility Bands PRO🟦 Artemis Volatility Bands PRO is a price-overlay volatility indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). A single kernel estimate — selectable from eight classical kernel families — anchors the Basis line. Around it, two outer bands fan outward by a fixed multiple of the residual standard deviation, creating an envelope whose width is model-consistent with the kernel. The interior is washed with a 6-layer neon halo that mirrors the statistical density of price residuals under normality. A signal engine detects basis-breaks with confirming slope direction, guarded by Confirmed (zero-repaint) or Realtime mode. Twelve cohesive color themes, a theme-aware Dark / Light dashboard, and four opt-in alert conditions complete the indicator.
🟦 HOW IT WORKS
Artemis Volatility Bands PRO fuses two mathematical operations on every bar — a single kernel regression pass and a residual standard deviation calculation:
basis = kl.estimate(type, src, ℓ, α, period, phase, filter)
sigma = kl.confidenceBand(src, basis, window)
upper = basis + k · σ
lower = basis − k · σ
where ℓ is the Primary Bandwidth, k is the Band Multiplier, and window is the Residual σ Window. The kernel regression produces the Basis line, and the residual standard deviation (σ of price − basis) produces the per-σ band half-width.
This architecture collapses classical Bollinger band duality: in Bollinger bands, the moving average and volatility estimate live in different statistical universes. In Artemis, both emerge from a single kernel pass, so the envelope is internally consistent by construction. The Basis is always non-parametric, and the band width always measures deviation relative to the Basis, never to a disconnected moving average.
The library handles all weighted-sum computation, kernel weight evaluation, NA-safe iteration, division-by-zero guards, and input validation internally. Artemis Volatility Bands PRO does not reimplement any kernel math — every bug fix or optimization in the library automatically propagates to this indicator.
🟦 KERNEL LIBRARY INTEGRATION
Artemis Volatility Bands PRO imports the published KernelLens library and uses the following exports:
| Library Export | Used For |
|---|---|
| `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on the user's Kernel Type dropdown. Called once per bar to produce the Basis line. |
| `kl.confidenceBand()` | Rolling residual standard deviation — computes σ of (source − basis) over the specified window. |
| `kl.trendState()` | Ternary trend detector — returns +1 (rising), 0 (flat), or −1 (falling) based on a 1-bar finite difference of the Basis. |
Every regression computation — kernel weight evaluation, NA-safe summation, bandwidth-aware loop termination — is delegated to the library. The indicator itself contains zero kernel math; it only orchestrates three library calls and aggregates their outputs into the band envelope and signal logic.
🟦 KERNEL REGRESSION & RESIDUAL VOLATILITY
**The Basis line** — A non-parametric kernel regression anchored to the user's choice of price source (default: close; also supports hl2, ohlc4, custom). Eight kernel families available:
| Kernel | Behavior | Best For |
|---|---|---|
| Rational Quadratic | Multi-scale mixer; α controls stretch | Default, balanced responsiveness |
| Gaussian / RBF | Canonical smoother, infinitely differentiable | Smooth trend, minimize noise |
| Periodic | Resonates with a known repetition distance p | Cyclic markets, seasonal patterns |
| Locally Periodic | Periodic × gaussian blend | Seasonal + trend drift |
| Epanechnikov | MSE-optimal, compact support | Minimal tail contamination |
| Tricube | LOWESS standard, near-Gaussian profile | Fast computation, robust |
| Triangular | Simplest compact kernel | Lightweight, real-time responsiveness |
| Cosine | Raised-cosine, smooth boundary transition | Smooth rolloff, professional appearance |
Three filter modes applied on top of the raw kernel estimate:
| Filter | Description | Use Case |
|---|---|---|
| No Filter | Single-pass Nadaraya–Watson | Rawest output, maximum responsiveness |
| Smooth | Double-pass: kernel applied to its own output | Cleaner, slightly more lag |
| Zero Lag | Ehlers de-lagging: 2·raw − smooth | Sharpens edges without increasing lag |
**Residual volatility** — Once the Basis is computed, the per-bar residual is (source − basis). The residual standard deviation is the rolling σ of this residual over a configurable window (default: 14 bars). This is the model-consistent volatility estimate — price deviations are measured relative to the kernel Basis, guaranteeing alignment between trend and volatility.
**Band levels** — upper = basis + k · σ and lower = basis − k · σ, where k is the Band Multiplier (default: 2.0, Bollinger-style). The multiplier is user-adjustable from 0.5 (tight) to 5.0 (wide).
🟦 SIGNAL ENGINE
Artemis fires Long / Short signals when price breaks the Basis with a confirming slope direction:
Long → close > basis AND basis rising
Short → close < basis AND basis falling
The signal state is persistent — once a direction flips, it remains latched until the opposite condition fires. This state machine (vii ∈ {−1, 0, +1}) ensures the Basis hue stays coherent across bars even when the raw trigger is a single-bar event.
Signal markers fire ONLY on the bar the state flips, not on every bar that satisfies the raw condition. This keeps the chart uncluttered and mirrors how discretionary traders consume trend-flip information.
**Signal Mode** — Two gating options:
| Mode | Behavior | Repaint |
|---|---|---|
| Confirmed | Signals fire ONLY after the bar closes via `barstate.isconfirmed` | Zero repaint, fully reliable for live trading |
| Realtime | Signals fire on the current (open) bar as soon as the condition is met | Fastest reaction; signal may vanish if price reverses before bar closes |
Historical repainting never occurs at any Signal Mode value. The library's `_phase` parameter shifts every kernel center into the past by that many bars, so historical bars' plotted values are final once confirmed.
🟦 6-LAYER NEON HALO VISUALIZATION
The interior between the Basis and each outer band is filled with a 6-layer gradient: 5 interior step plots plus the outer band, creating a stepped transparency schedule that mirrors the statistical density of price residuals under normality.
**Transparency schedule:**
| Layer | Transparency | Meaning |
|---|---|---|
| Outer band ↔ 1st interior | 70 % | Densest layer |
| 1st ↔ 2nd | 78 % | |
| 2nd ↔ 3rd | 85 % | |
| 3rd ↔ 4th | 90 % | |
| 4th ↔ 5th | 95 % | |
| 5th ↔ Basis | 98 % | Nearly invisible fade to centerline |
Every transparency value is scaled by the Gradient Intensity input (0–100 %), so the user can dial the visual density from invisible (0) to heavy fills (100).
**Color assignment:**
- Upper band + gradient: Bearish theme hue (short signal color)
- Lower band + gradient: Bullish theme hue (long signal color)
- Basis line: Slope-adaptive color (thBull when rising, thBear when falling, previous color on flat bars)
**Signal markers** — Two-layer neon glow plotshapes:
- Halo: size.small, 40 % opaque theme hue (glow layer)
- Core: size.tiny, 100 % opaque theme hue (bright center)
🟦 THEME SYSTEM
Twelve cohesive color palettes tuned to every trading aesthetic. One selection drives every visual component — Basis line, outer bands, gradient halos, long / short signal markers, dashboard accents — all sharing the same bull / bear / neutral color axes:
| Theme | Bull | Bear | Usage |
|---|---|---|---|
| Tropic | Cyan steel | Deep orange | Default, electric contrast |
| Amber | Warm amber | Indigo blue | Fire tones |
| Pastel | Sky blue | Soft lavender | Cool arctic glow |
| Cyber | Neon lime | Hot crimson | Cyber terminal aesthetic |
| Helios | Bright gold | Scarlet | Solar warmth |
| Electric | Electric aqua | Magenta | High-voltage neon |
| Candy | Neon green | Hot pink | Dark energy pop |
| Bloomberg | Terminal orange | Cyan | Wall Street finance heritage (PRO) |
| Solar | Solarized olive | Crimson | Developer palette, easy on eyes (PRO) |
| Royal | Imperial gold | Deep purple | Luxury signature (PRO) |
| Midnight | Deep navy | Dark crimson | Dark depth |
| Graphite | Near-black | Silver grey | Monochrome minimal |
**Dashboard display modes** — Dark (black background, bright accents) or Light (white background, darker accents), auto-adapting visual contrast regardless of chart background.
🟦 DASHBOARD
A 2-column, 9-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes, six docking positions, and four text sizes. Renders via `force_overlay = true` on the main price chart.
| Row | Label | Content |
|---|---|---|
| Header | ARTEMIS PRO | DARK / LIGHT |
| Theme | Theme | Active palette name |
| Divider | KERNEL | — |
| Type | Type | Selected kernel type |
| Bandwidth ℓ | Bandwidth ℓ | Primary bandwidth + Phase φ |
| Basis | Basis | Current Basis value in chart mintick format |
| Divider | VOLATILITY | — |
| Residual σ | Residual σ | Current residual standard deviation |
| Signal | Signal | ▲ LONG / ▼ SHORT / ━ FLAT (direction-colored) |
🟦 ALERT CONDITIONS
Four opt-in alert conditions, each gated by its own toggle:
| Alert | Fires When |
|---|---|
| Long Signal | Price breaks above the Basis with a rising slope (confirmed state flip) |
| Short Signal | Price breaks below the Basis with a falling slope (confirmed state flip) |
| Upper Band Touch | Price touches or exceeds the upper outer band (raw crossover) |
| Lower Band Touch | Price touches or falls below the lower outer band (raw crossunder) |
Band touch alerts are useful as pre-signal early warnings in trending markets. Signal alerts are gated by the Signal Mode setting, so Confirmed mode ensures zero-repaint alerts suitable for live trading.
All alerts use `alertcondition()` for maximum compatibility with PulseWire's alert system including webhooks. Messages are structured as `"Artemis Volatility Bands: "` for easy parsing in downstream automation.
🟦 RECOMMENDED PRESETS
| Trading Style | Bandwidth ℓ | Filter | Residual σ Window | Phase |
|---|---|---|---|---|
| Scalper | 10–20 | No Filter | 8–10 | 1 |
| Day Trader | 20–40 | Smooth | 14 | 2 |
| Swing | 30–60 | Smooth | 20–40 | 2 |
| Position | 60–120 | Smooth | 40–60 | 3 |
**Bandwidth tuning** — Smaller ℓ produces a tighter fit to price and faster reaction; larger ℓ produces smoother curves and more stability. Experiment with ℓ in your preferred style's range, then adjust the Residual σ Window and Filter mode for visual smoothness.
**Phase tuning** — Phase = 0 is live (flickers on the current bar); Phase = 2 is the recommended balance; Phase = 3+ adds margin against noise at the cost of lag. Historical charts are immutable at any phase value.
🟦 KERNEL-ONLY DESIGN PHILOSOPHY
Artemis Volatility Bands PRO contains zero classical technical analysis bolt-ons. No Bollinger Bands, no Keltner Channels, no linear regression, no ATR, no moving averages — only kernel regression and residual volatility. This kernel-only architecture guarantees that:
1. **Internal consistency** — The Basis and band width emerge from a single statistical model, not from mixing independent techniques.
2. **Unified parameterization** — All visual outputs (Basis, bands, gradient) are controlled by a single set of kernel-theoretic parameters.
3. **No analytical compromise** — Every choice in the indicator is mathematically motivated; no ad-hoc decorations.
The philosophy is defensive: traders who layer Artemis on top of their own edge strategies get a pure kernel-regression envelope that will not conflict with classical-TA signals already in use. Traders seeking a standalone kernel-based indicator get a complete, coherent system.
🟦 COMPATIBILITY
- Pine Script v6
- All exchanges, all asset classes (crypto, forex, equities, commodities, indices)
- All timeframes (1 minute through Monthly)
- Both Dark and Light chart themes — visual elements auto-adapt to chart background
- No exchange-specific logic — fully deterministic
Indicator renders on the main overlay chart with `force_overlay = true`. No secondary panes, no subplot logic.
🟦 TECHNICAL NOTES
- **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression math is delegated to the published library
- **Plot budget** — 2 outer bands + 10 gradient interior plots + 1 Basis + 1 transparent anchor + 4 signal shapes + 12 fills + 4 alertconditions = 34 outputs, well under Pine's 64-output hard limit (50 % margin)
- **Table** — Single `var table` created once on `barstate.islast` with `force_overlay = true`; dashboard renders on the main chart pane, zero historical overhead
- **No persistent drawing objects** — no `box.new`, `line.new`, no `array.new`; all visuals are plots and fills
- **Opacity convention** — every user-facing opacity / transparency input follows `0 = invisible, 100 = fully opaque`; conversion to Pine's native transparency is centralized in a single helper function (`f_opac`)
- **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead, no future-bar leakage at any phase value
- **Residual consistency** — The residual σ is computed as `ta.stdev(source − basis, window)`, ensuring the band width always measures deviation relative to the kernel Basis
🟦 DISCLAIMER
Artemis Volatility Bands PRO is a technical analysis indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output. The signal engine is a mechanical detector of basis breaks and slope direction — not a forecast — and should always be combined with broader context: higher-timeframe structure, volatility regime, liquidity, news, and risk management.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of Artemis Volatility Bands PRO or the underlying KernelLens library. Indicator

Overbought & Oversold Zones - MTF SignalsOverbought & Oversold Zones - MTF Signals
Overbought & Oversold Zones - MTF Signals is a visual analytical indicator that highlights extreme directional conditions directly on the price chart and across multiple timeframes. Instead of plotting an oscillator line in a separate pane, it paints gradient zones around price during periods of sustained buying or selling pressure, helping traders see exhaustion states at a glance.
The indicator combines a custom Pressure Index calculation with a volatility-adjusted envelope to shape the zones, and a compact multi-timeframe panel that scans the current timeframe plus the three higher ones.
This is a visual analytical tool intended for chart reading and context. It does not execute trades and does not provide financial advice.
Key Features
On-chart gradient zones highlighting overbought and oversold conditions
Zones follow the shape of a dynamic volatility envelope (not rectangles)
Multi-timeframe panel scanning current TF plus three higher TFs
Merged phase logic that groups close-proximity conditions into single zones
Adjustable sensitivity through ten preset levels
Fully customizable colors and optional text labels
Core Concept
The indicator uses a custom Pressure Index model to evaluate how consistently price has been pushing above or below a volatility-adjusted baseline. Unlike traditional oscillators such as RSI (which measures gain/loss ratios) or Stochastic (which measures position within a range), Pressure Index combines two complementary components:
Persistence — how consistently price has stayed above or below a volatility-adjusted baseline over the measurement window, weighted by normalized distance rather than as a binary above/below count
Displacement — how far current price is from that baseline in ATR-normalized units
The baseline adapts to volatility regime: during high-volatility periods the reference band widens to reduce false exhaustion signals, and during calm periods it tightens. Final output is bounded to a 0–100 scale and smoothed with a sensitivity-scaled EMA.
Zone Visualization
When the Pressure Index enters an extreme region, the indicator renders a three-layer gradient zone that follows the shape of the dynamic envelope:
Overbought zones fade downward from the upper envelope into the channel
Oversold zones fade upward from the lower envelope into the channel
Zone thickness scales with ATR so the visual is comparable across markets and timeframes
The gradient has three layers: a dense core band close to the envelope, a middle fade band, and an outer soft fade. This layered approach helps the zones visually surround the candles inside the extreme state rather than appearing as flat bars.
Multi-Timeframe Panel
A compact panel in the top-right corner of the chart displays the Pressure Index across the current timeframe and three higher timeframes (automatically selected from the standard ladder: 1m, 5m, 15m, 30m, 1H, 4H, 1D, 1W, 1M).
Each row shows:
Timeframe label
Horizontal gauge bar with a position marker
Numeric Pressure Index value (0–100)
State pill indicating Overbought (OB), Oversold (OS), or neutral direction
The panel adapts its higher timeframes to whichever chart timeframe is currently active. The current chart timeframe is marked with a bullet indicator.
Typical Analysis Workflow
A common analytical workflow may include:
Observing gradient zones on the main chart to identify extended conditions
Checking the MTF panel to place the current reading in higher-timeframe context
Evaluating price structure and candle behavior near zone edges
Combining zone information with other forms of analysis and risk management
Configuration
Sensitivity — Controls how quickly the Pressure Index reacts to changes in price pressure. Lower values produce faster, more frequent signals. Higher values produce slower, steadier signals.
Lower settings (1-3) — Faster reactivity, suitable for intraday charts and shorter timeframes
Middle settings (4-6) — Balanced sensitivity, default for most markets and timeframes
Higher settings (7-10) — Slower reactivity, suitable for swing and position-style chart reading
On-Chart Display — Toggles the gradient zones on or off.
Show Text Labels — Toggles "Overbought" and "Oversold" text labels that appear once per merged phase. Can be disabled for a cleaner chart.
Show MTF Panel — Toggles the multi-timeframe panel.
Appearance — Customizable colors for Overbought and Oversold zones, panel text size, and history rendering depth.
Markets and Timeframes
The indicator can be applied across multiple markets and timeframes:
Forex
Stocks and Indices
Commodities
Cryptocurrencies
Because the zone thickness and Pressure Index smoothing are both normalized by ATR and sensitivity presets, the visual behavior remains consistent across different instruments and timeframes without manual re-tuning.
Alerts
Two alert conditions are available:
Overbought Entry — triggers on the first bar a new Overbought state begins
Oversold Entry — triggers on the first bar a new Oversold state begins
Important Notes
This indicator is an analytical visualization tool. It does not execute trades and does not provide financial advice. All outputs are informational and should be interpreted within the context of independent market analysis and proper risk management.
Past behavior of any technical indicator does not guarantee future results.
If you find this indicator useful, feel free to add it to your favorites and share your feedback in the comments. Community feedback helps improve future updates. Indicator

Percentile Stretch Bands [AGPro Series]Percentile Stretch Bands
🔹 OVERVIEW
Percentile Stretch Bands is an empirical, distribution-free overextension map. Instead of plotting standard deviation envelopes that assume a normal distribution of price behavior, this indicator samples the actual historical distance between price and a chosen reference (EMA, VWAP, or Anchored VWAP) and draws context-specific Stretch and Extreme bands directly from the empirical percentile distribution. The result is a visual reference of how stretched price is relative to its own historical behavior, adapted to the asset and timeframe being viewed.
🔹 UNIQUE EDGE
Most "stretch" or "volatility band" tools on the platform rely on parametric assumptions — standard deviation multipliers, ATR multiples, or fixed percentage offsets. These approaches collapse when the underlying return distribution is skewed, fat-tailed, or regime-dependent, which is the rule rather than the exception across crypto and FX assets.
Percentile Stretch Bands takes a different path:
• Distribution-free: bands are drawn from the actual empirical percentile of price-to-reference distance, not from a Gaussian assumption.
• Side-specific sampling: upper and lower distances are collected into separate samples, so asymmetric behavior (trending markets, one-sided regimes) is preserved rather than averaged away.
• Regime-aware rendering: when Focus Active Side is enabled, each bar displays only the side relevant to price position, producing a clean single-story chart without visual competition.
• Readiness gating: bands appear only once a minimum number of observations is reached on the active side, with the status panel clearly indicating the collection stage.
🔹 METHODOLOGY
For every bar in the configured lookback window, the signed percent distance between close and the selected reference is computed and partitioned into two historical samples: positive distances (upper extensions) and negative distances in absolute terms (lower extensions).
Each sample is sorted and two percentile cut-offs are extracted independently:
• Stretch percentile (default 80) — the threshold beyond which a distance is considered materially extended.
• Extreme percentile (default 95) — the threshold beyond which a distance is statistically rare within the chosen lookback.
These cut-offs are then translated from percent-distance back into absolute price bands around the active reference, producing four levels: Upper Stretch, Upper Extreme, Lower Stretch, Lower Extreme. The current distance is also ranked against its side's sample and displayed as an ordinal percentile (for example, "Upper P87") in the status panel.
🔹 SIGNALS AND ALERTS
The indicator is a visual overextension map and does not generate directional trade signals. Four alert conditions are exposed for users who want to be notified of boundary events:
• Upper Stretch Cross — close crosses above the Upper Stretch band.
• Upper Extreme Cross — close crosses above the Upper Extreme band.
• Lower Stretch Cross — close crosses below the Lower Stretch band.
• Lower Extreme Cross — close crosses below the Lower Extreme band.
These alerts mark entries into statistically extended zones relative to the empirical sample. They are contextual flags, not trade recommendations.
🔹 KEY INPUTS
Reference
• Reference Mode — EMA, VWAP, or Anchored VWAP baseline
• EMA Length — smoothing length for the EMA reference
• AVWAP Anchor Time — starting timestamp for Anchored VWAP
Statistics
• Lookback — bars used to build the empirical distribution (default 500)
• Minimum Side Sample — observations required before bands appear
• Stretch Percentile — primary extension threshold (default 80)
• Extreme Percentile — rare-extension threshold (default 95)
Display
• Focus Active Side — regime-aware single-story rendering
• Show Active Stretch Zone Box — right-side zone anchor on the active side
• Zone Forward Projection — forward visibility of the active zone
• Band Color Profile — Soft, Premium, or Bold
• Panel Text Size and Label Text Size — Small, Normal, or Large
Level Tags
• Show Level Tags, Show Reference Tag, Tag Mode, Tag Offset Bars
🔹 HOW TO USE
1. Select a reference that fits the asset and timeframe. EMA is a robust default across all instruments. VWAP is suited to intraday equities and futures. Anchored VWAP is used when a specific event origin (earnings, news, structural low) is relevant.
2. Let the status panel reach the "Ready" state. The panel reports active samples and readiness — bands are intentionally withheld until the side-specific sample is sufficient.
3. Read the current percentile rank in the Zone cell. Values near the center indicate price trading close to the reference; values approaching P95 or above indicate the sample's rare extensions.
4. Treat Stretch and Extreme bands as context, not as triggers. A move into the Extreme zone reflects a statistically rare extension on the chosen sample, not a directional signal.
5. Combine with structural tools — trend context, market structure, higher-timeframe bias — before any discretionary decision.
🔹 LIMITATIONS AND TRANSPARENCY
• The indicator is descriptive, not predictive. Percentile bands describe past behavior within the lookback window; they do not forecast future price action.
• Regime shifts can temporarily invalidate historical bands. A sudden volatility expansion will push price beyond extreme levels while the sample re-stabilizes.
• Empirical percentiles require sufficient observations. On very new symbols or short lookbacks, the "Collecting" state is the correct and expected behavior.
• Anchored VWAP mode depends on a meaningful anchor choice. A poorly chosen anchor produces a reference line without structural relevance.
• The active stretch zone box is a visual anchor for screenshots and review, not a projection of future levels.
🔹 RISK DISCLOSURE
This script is a visual analytics tool and is not a strategy, signal service, or financial advice. It does not place orders, manage positions, or recommend directional exposure. Trading involves risk of loss. Users are responsible for their own analysis, risk management, and trading decisions. Indicator

Artemis Regression Bands🟦 Artemis Regression Bands is a kernel-driven volatility envelope indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). A single kernel estimate — selectable from eight classical kernel families — anchors the Fair Value line. Around it, three residual-standard-deviation bands (±1σ, ±2σ, ±3σ) fan outward with either Linear or Exponential spacing, producing a statistically grounded envelope far cleaner than the classical close-stdev approach used by legacy Bollinger-style indicators. A four-gate Romb signal engine overlays buy / sell diamond markers when price pokes through the outermost enabled σ boundary and reverses back inside.
🟦 HOW IT WORKS
Artemis calls the KernelLens library's unified dispatcher once per bar to build the Fair Value line, then queries three additional library exports to derive the band widths, slope direction, and residual σ:
```
fair = kl.estimate (type, src, ℓ, α, period, phase, filter)
sigma = kl.confidenceBand(src, fair, window)
slopeVal = kl.slope (fair, 1)
trendSt = kl.trendState (fair, 1)
dev = baseMult · sigma
upper1 = fair + 1·dev lower1 = fair − 1·dev
upper2 = fair + 2·dev lower2 = fair − 2·dev
upper3 = fair + k3·dev lower3 = fair − k3·dev (k3 = 3 Linear | 4 Exp)
```
The library handles all weighted-sum computation, loop-depth selection, NA-safe iteration, division-by-zero guards, and input validation internally. Artemis contains zero kernel math — every bug fix or optimization in the library automatically propagates to this indicator.
🟦 KERNEL LIBRARY INTEGRATION
Artemis imports the published KernelLens library and uses the following exports:
| Library Export | Used For |
|---|---|
| `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on the user's Kernel Type dropdown. Called once per bar to produce the Fair Value line. |
| `kl.confidenceBand()` | Rolling standard deviation of the (source − Fair Value) residual. Drives the band half-widths on every bar. |
| `kl.slope()` | Discrete first derivative of the Fair Value line. Feeds trend flip alerts. |
| `kl.trendState()` | Ternary classifier (+1 rising / −1 falling / 0 flat) of the Fair Value line. Drives the slope-adaptive color, the kernel trend confluence filter, and the dashboard Trend row. |
Every regression computation — kernel weight evaluation, NA-safe summation, bandwidth-aware loop termination, residual stdev, finite-difference slope — is delegated to the library. The indicator itself only orchestrates the four library calls and layers the visual pipeline on top.
🟦 EIGHT KERNEL FAMILIES
A single Kernel Type dropdown selects any of the eight kernels shipped with the KernelLens library. Each is a different mathematical smoother with its own statistical character:
| Kernel | Formula | Best For |
|---|---|---|
| Rational Quadratic | (1 + d² / (2·α·ℓ²))^(−α) | Multi-scale mixer; α controls stretch. Recommended default. |
| Gaussian / RBF | exp(−d² / (2·ℓ²)) | Canonical smoother; infinitely differentiable. |
| Periodic | exp(−2·sin²(π·d/p) / ℓ²) | Resonates with a known repetition distance p. |
| Locally Periodic | Periodic × Gaussian | Seasonal patterns with slow trend drift. |
| Epanechnikov | (3/4)·(1 − u²), \|u\| ≤ 1 | MSE-optimal; compact support, no tail contamination. |
| Tricube | (70/81)·(1 − \|u\|³)³, \|u\| ≤ 1 | LOWESS standard; near-Gaussian compact profile. |
| Triangular | (1 − \|u\|), \|u\| ≤ 1 | Simplest compact kernel; cheapest to compute. |
| Cosine | (π/4)·cos(π·u/2), \|u\| ≤ 1 | Raised-cosine; smooth boundary transition. |
Because the dropdown feeds the library's `kl.estimate()` dispatcher directly, every kernel inherits the same three-mode filter layer (No Filter / Smooth / Zero Lag) and the same non-repainting guarantees — there is no special case per kernel in Artemis.
🟦 FILTER LAYER
A second dropdown applies an optional post-processing layer on top of the raw Nadaraya–Watson estimate:
| Filter | Formula | Trade-off |
|---|---|---|
| No Filter | ŷ = ŷ_raw | Single-pass kernel. Rawest output, most reactive. |
| Smooth | ŷ = K(ŷ_raw) | Double-pass — kernel applied to its own output. Cleaner line, slightly more lag. |
| Zero Lag | ŷ = 2·ŷ_raw − K(ŷ_raw) | Ehlers de-lagging identity — sharpens edges without adding lag. |
The filter is resolved entirely inside `kl.estimate()`, so switching modes incurs no runtime cost beyond the extra kernel pass.
🟦 RESIDUAL-σ BAND ENGINE
Artemis bands are statistically grounded on the residual standard deviation — not on raw close stdev as in classical Bollinger indicators. The residual is computed as:
```
residual = src − fair
sigma = ta.stdev(residual, window) // via kl.confidenceBand()
```
Because Fair Value is already an unbiased local estimate of the source, the residual is a zero-mean noise series and its stdev captures **only the portion of price variance that the kernel could not explain**. This produces three benefits over the classical approach:
1. **Tighter bands in trending regimes** — close-stdev widens during strong trends because the trend itself inflates the variance; residual-σ does not, because the kernel absorbs the trend.
2. **Faster reaction to volatility regime changes** — residual-σ tightens as soon as the kernel fits well, and widens the instant the market breaks out of the kernel's neighborhood.
3. **True statistical interpretation** — under the assumption of locally Gaussian residuals, ±1σ / ±2σ / ±3σ enclose approximately 68 % / 95 % / 99.7 % of near-term price variation. The traditional close-stdev envelope carries no such interpretation.
A dedicated Residual σ Window input controls the lookback; typical values range from 50 (reactive, scalping) to 300 (stable, position trading).
🟦 BAND SPACING MODES
Two spacing presets shape the outward fan of the three σ bands:
| Mode | Multipliers | Character |
|---|---|---|
| Linear | 1·, 2·, 3· | Classical Bollinger-style uniform steps. Predictable, symmetric. |
| Exponential | 1·, 2·, 4· | Fibonacci-flavored — outer band (4σ) is reserved for genuine blow-off excursions. |
Base Multiplier scales all three bands uniformly (default 1.0). The formula is:
```
band_level = fair ± (baseMult · k · sigma) k ∈ {1, 2, k3}
```
where k3 resolves to 3 in Linear mode and 4 in Exponential mode. Every band has an independent visibility toggle, so minimalist users can run ±1σ only, swing traders ±3σ only, or any combination.
🟦 FOUR-GATE ROMB SIGNAL ENGINE
The Romb engine prints buy / sell diamond markers when price pokes through the outermost enabled σ band and reverses back inside. Four sequential gates protect against false entries:
| Gate | Logic | Purpose |
|---|---|---|
| 1 — Crossover | `ta.crossunder(high, triggerUp)` / `ta.crossover(low, triggerDn)` | Detects the reversal back through the outer band. |
| 2 — Warm-up | Residual σ computable for N consecutive bars | Blocks signals during the early kernel-settlement window. |
| 3 — Confluence | Fair Value slope aligns with the reversal direction | Optional PRO filter — Sell Romb requires falling kernel, Buy Romb requires rising kernel. |
| 4 — Cooldown | Minimum bar gap since the last same-side Romb | Prevents signal clustering on a single extended poke-and-reverse sequence. |
A Signal Mode toggle layers on top:
- **Confirmed** — signals fire only on `barstate.isconfirmed`; zero repaint on closed bars.
- **Realtime** — signals fire live on the current open bar; faster reaction, may vanish if price reverses before close.
Each confirmed signal is rendered as a two-layer neon diamond:
- **Halo** — `size.small`, 40 % transparent theme hue (glow layer).
- **Core** — `size.tiny`, fully opaque theme hue (bright center).
The halo renders first so the core sits cleanly on top, producing a sharp luminous marker that reads instantly even on dense price charts.
🟦 ADAPTIVE OUTER-BAND TRIGGER
The Romb engine does not hard-code the ±3σ band as the signal trigger. Instead, it resolves the outermost currently-enabled band on every bar:
```
triggerUp = show3 ? upper3 : show2 ? upper2 : show1 ? upper1 : na
triggerDn = show3 ? lower3 : show2 ? lower2 : show1 ? lower1 : na
```
The result is an envelope that respects the user's visibility choices:
| Visible Bands | Romb Fires At |
|---|---|
| ±1σ + ±2σ + ±3σ | ±3σ (default) |
| ±1σ + ±2σ | ±2σ |
| ±1σ only | ±1σ |
| All off | no signals |
Diamond positioning follows the same trigger, so the glyph always floats ~0.3σ outside whatever envelope is actually drawn on the chart. The behavior matches user intent: the band I can see is the band that fires signals.
🟦 NON-REPAINTING BEHAVIOR
Artemis inherits non-repainting behavior directly from the KernelLens library's `_phase` parameter. A single Phase input (default 2) shifts the kernel center into the past by that many bars:
- **Phase = 0** — live estimate, flickers on the current bar (real-time only; history is immutable).
- **Phase = 1** — 1-bar lag, non-repainting once the bar is confirmed.
- **Phase = 2** — recommended balance between freshness and stability (default).
- **Phase = 3+** — extra margin against erratic ticks, higher lag.
Historical repainting never occurs at any phase value. The library contains no `request.security` calls, no lookahead, and no array rotation that could leak future data. Every historical bar's plotted Fair Value, band, and Romb signal is final once confirmed.
🟦 VISUAL PIPELINE
**σ Band Outlines** — Three upper bands (±1σ / ±2σ / ±3σ) in progressively lighter `thBear` hues, three lower bands in progressively lighter `thBull` hues. Hidden bands collapse to na via their individual visibility toggles; the outline widths share a single Band Line Width input.
**Tapered Gradient Fills** — Six fills drawn between the Fair Value line and each σ band. Opacity scales progressively from ±1σ (densest, most opaque) to ±3σ (lightest, most transparent), creating a halo that mirrors the statistical density of price residuals under normality. Master Fill Opacity input (0 = invisible, 100 = fully opaque) scales all three fills uniformly.
**Fair Value Line** — Slope-adaptive color resolver swaps between `thBull` (rising kernel) and `thBear` (falling kernel). Flat bars retain the previous color so the line never flashes neutral on a perfectly horizontal tick. Width is user-controlled (1–5 px).
**Romb Diamonds** — Two-layer neon glow at the adaptive trigger band; halo + core rendering described above.
**Bar Coloring** — Optional theme-aware candle coloring driven by the Fair Value slope. Off by default; when enabled it paints every bar with the active theme's bull / bear hue based on the current trend state.
🟦 THEME SYSTEM
Twelve cohesive color palettes drive every visual component — Fair Value line, σ band outlines, gradient fills, Romb diamonds, bar coloring, and dashboard accents — all sharing the same four color axes (`thBull`, `thBear`, `thNeutral`, `thSignal`):
| Theme | Bull | Bear |
|---|---|---|
| Tropic | Cyan steel | Deep orange |
| Amber | Warm amber | Indigo blue |
| Pastel | Sky blue | Soft lavender |
| Cyber | Neon lime | Hot crimson |
| Helios | Bright gold | Scarlet |
| Electric | Electric aqua | Magenta |
| Candy | Neon green | Hot pink |
| Bloomberg | Terminal orange | Cyan |
| Solar | Solarized olive | Crimson |
| Royal | Imperial gold | Deep purple |
| Midnight | Deep navy | Dark crimson |
| Graphite | Near-black | Silver grey |
A separate Display Mode toggle (Dark / Light) controls the dashboard palette independently of the chart theme — so a Bloomberg chart theme with a Light dashboard is a valid configuration, as is Midnight chart + Dark dashboard.
🟦 DASHBOARD
A 2-column, 12-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes, six docking positions, and four text sizes. Renders via `force_overlay = true` on the main price chart.
| Row | Label | Content |
|---|---|---|
| Header | ARTEMIS | DARK / LIGHT |
| Theme | Theme | Active palette name |
| Kernel | Kernel | Selected kernel type |
| Divider | REGRESSION | — |
| Bandwidth | Bandwidth ℓ | Bandwidth value / Phase offset φ |
| Filter | Filter | No Filter / Smooth / Zero Lag |
| Fair Value | Fair Value | Current Fair Value in chart mintick format |
| Divider | BANDS | — |
| Spacing | Spacing | Linear 1·/2·/3· or Exp 1·/2·/4· |
| Residual σ | Band σ | Rolling residual standard deviation |
| Trend | Trend | ▲ BULL / ▼ BEAR / ━ FLAT (bull/bear colored) |
| Last Romb | Last Romb | ▲ BUY (N ago) / ▼ SELL (N ago) — bull/bear colored |
**Zebra-stripe layout** — alternating `dashBg` / `dashBgAlt` row backgrounds improve scan-ability on narrow cells. Section dividers (REGRESSION, BANDS) use a third background tone (`dashSection`) with the theme's bull accent as the header color — preserving brand identity across both Display Modes.
🟦 ALERT CONDITIONS
Six opt-in alert conditions, each gated by its own toggle:
| Alert | Fires When |
|---|---|
| Bullish Trend Flip | Fair Value slope crosses from ≤ 0 into positive territory |
| Bearish Trend Flip | Fair Value slope crosses from ≥ 0 into negative territory |
| Buy Romb | Confirmed Buy Romb fires — all four signal gates passing |
| Sell Romb | Confirmed Sell Romb fires — all four signal gates passing |
| Upper Band Touch | Price touches or exceeds the outermost enabled upper band |
| Lower Band Touch | Price touches or falls below the outermost enabled lower band |
All alerts use `alertcondition()` for maximum compatibility with PulseWire's alert system including webhooks. Messages are structured as `"Artemis Regression Bands: "` for easy parsing in downstream automation. Touch alerts are off by default (can be noisy in trending markets); the four core alerts are on by default.
🟦 RECOMMENDED PRESETS
| Style | Bandwidth ℓ | Filter | Phase | Spacing | σ Window | Chart |
|---|---|---|---|---|---|---|
| Scalper | 10–20 | No Filter | 1 | Linear | 50–80 | 1m–5m |
| Day Trader | 20–40 | Smooth | 2 | Linear | 80–120 | 15m–1h |
| Swing | 30–60 | Smooth | 2 | Linear or Exp | 100–200 | 4h–1D |
| Position | 60–120 | Smooth or Zero Lag | 3 | Exp | 200–300 | 1D–1W |
**Kernel type tuning**
- **Trending instruments** — Rational Quadratic (α = 1–3) or Gaussian. Smooth multi-scale response.
- **Mean-reverting instruments** — Epanechnikov or Tricube. Compact support keeps the band envelope tight.
- **Session-cyclic patterns** — Periodic (with p = session length in bars) or Locally Periodic. Resonates with known cycles.
**Romb filter tuning** — Keep Kernel Trend Confluence ON for high-conviction setups only. Switch OFF on range-bound instruments to capture both sides of the oscillation.
🟦 COMPATIBILITY
- Pine Script v6
- All exchanges, all asset classes (crypto, forex, equities, commodities, indices)
- All timeframes (1 minute through Monthly)
- Both Dark and Light chart themes — the Display Mode toggle controls dashboard palette independently
- No exchange-specific logic — fully deterministic
🟦 TECHNICAL NOTES
- **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression, residual σ, slope, and trend-state math is delegated to the published library.
- **Plot budget** — 6 band plots + 1 Fair Value anchor + 1 Fair Value visible + 6 gradient fills + 4 Romb plotshapes + 1 barcolor = well under Pine's plot limits.
- **Table** — Single `var table` rebuilt on `barstate.islast` with `force_overlay = true`; zero historical overhead.
- **Signal state** — Two `var int` cooldown anchors (`lastSellBar`, `lastBuyBar`) seeded at −10000 so the very first bar always passes the gap test. A `var int stabCount` warm-up counter blocks signals during early kernel settlement.
- **No persistent drawing objects** — no `box.new`, `line.new`, no array rotations; every visual is either a plot or a single-bar plotshape.
- **Adaptive trigger resolver** — Romb crossover detection, touch alerts, and diamond positioning all read from the same `triggerUp` / `triggerDn` resolver, so band visibility toggles stay semantically coherent across every layer of the indicator.
- **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead, no future-bar leakage at any phase value.
🟦 DISCLAIMER
Artemis Regression Bands is a technical analysis indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output. The residual-σ envelope describes past dispersion around the kernel estimate — not a forecast of future range — and should always be combined with broader context: higher-timeframe structure, volatility regime, liquidity, news, and risk management.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of Artemis Regression Bands or the underlying KernelLens library. Indicator

Quant Edge Ribbon PRO🟦 Quant Edge Ribbon PRO is a multi-kernel divergence ribbon indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). A primary kernel and eleven longer-bandwidth kernels form a dual-ribbon visualization driven by kernel regression mathematics, an integer trend score in , a theme-aware rendering pipeline, four user-configurable reference levels, and a PRO dashboard. All twelve kernels route through the unified library dispatcher, so the user may select any of the eight kernel families and any of the three filter modes from a single configuration panel.
🟦 HOW IT WORKS
Quant Edge Ribbon PRO calls the KernelLens library's unified dispatcher (`kl.estimate`) twelve times per bar — once for the primary kernel and once for each of the eleven outer kernels:
```
primary = kl.estimate(type, src, ℓ, α, period, phase, filter)
long00 = kl.estimate(type, src, ℓ + 1·s, α, period, phase, filter)
long01 = kl.estimate(type, src, ℓ + 2·s, α, period, phase, filter)
...
long10 = kl.estimate(type, src, ℓ + 11·s, α, period, phase, filter)
```
where ℓ is the Primary Bandwidth and s is the Bandwidth Step. All twelve kernels share the same kernel type, filter, shape α, period, and phase — only the bandwidth differs. This guarantees the ribbon behaves as a coherent spectrum of kernel scales rather than a mixture of unrelated signals.
The library handles all weighted-sum computation, loop-depth selection, NA-safe iteration, division-by-zero guards, and input validation internally. Quant Edge Ribbon PRO does not reimplement any kernel math — every bug fix or optimization in the library automatically propagates to this indicator.
🟦 KERNEL LIBRARY INTEGRATION
Quant Edge Ribbon PRO imports the published KernelLens library and uses the following export:
| Library Export | Used For |
|---|---|
| `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on the user's Kernel Type dropdown. Called twelve times per bar, once for the primary kernel and once for each of the eleven outer kernels. |
Every regression computation — kernel weight evaluation, NA-safe summation, bandwidth-aware loop termination — is delegated to the library. The indicator itself contains zero kernel math; it only orchestrates twelve library calls and aggregates their outputs into the trend score.
🟦 THE TWELVE-KERNEL RIBBON ARCHITECTURE
**Primary kernel (the shortest, the anchor)** — A single kernel at bandwidth ℓ that serves two roles: (1) it is the reference baseline for the trend score calculation, and (2) it is plotted as a dedicated highlighted anchor line when the "Highlight Primary Kernel" toggle is ON.
**Eleven outer kernels (progressively wider)** — Kernels at bandwidths ℓ+1·s, ℓ+2·s, …, ℓ+11·s, where s is the Bandwidth Step (default: 1). Each outer kernel is plotted as a line on the main chart, all eleven sharing a single score-driven gradient color — so the entire outer ribbon shifts between the theme's bull and bear hues as the trend score moves between −11 and +11.
**Eleven inner ribbon plots (lagged primary snapshots)** — The primary kernel plotted at eleven time-lag offsets (0, 1, 2, …, 10 bars). The resulting visual is a gently flowing shadow that makes expansion and contraction of the outer ribbon easier to perceive. Opacity is user-controlled (default: 40 %).
🟦 INTEGER TREND SCORE
The trend score is a signed integer in , computed on every bar by eleven pairwise comparisons between the primary kernel (at progressive lag offsets) and the eleven outer kernels:
```
score = 0
for i in 0..10:
if primary < long_i:
score += 1
else:
score -= 1
```
**Semantic interpretation** — Each comparison pairs an older snapshot of the shortest kernel against a current snapshot of a progressively wider kernel. In an uptrend, past primary values are lower while current wider-kernel values have caught up above them — the inequality resolves positive on most pairs and the score climbs toward +11. The symmetric argument drives the score toward −11 in a downtrend.
**Score parity** — Because the score is a sum of eleven ±1 terms (score = 2k − 11, k ∈ ), it is always odd. Reachable values: { −11, −9, −7, −5, −3, −1, 1, 3, 5, 7, 9, 11 }. The score is never exactly zero.
🟦 STRENGTH CATEGORIZATION
The absolute score is bucketed into four bands, each with a matched label glyph used throughout the dashboard and the last-bar signal label:
| Score Range | Strength | Label |
|---|---|---|
| \|score\| = 1 | NEUTRAL | ▰▱▱▱ NEUTRAL |
| \|score\| ∈ {3, 5} | WEAK | ▰▰▱▱ WEAK BULL / WEAK BEAR |
| \|score\| = 7 | STRONG | ▰▰▰▱ STRONG BULL / STRONG BEAR |
| \|score\| ∈ {9, 11} | TRIPLE | ▰▰▰▰ TRIPLE BULL / TRIPLE BEAR |
The bull / bear suffix is driven by the sign of the score. The progress-bar glyphs (▰▱) give an instant at-a-glance read of confluence intensity without needing to parse the numeric value.
🟦 NON-REPAINTING BEHAVIOR
Quant Edge Ribbon PRO inherits non-repainting behavior directly from the KernelLens library's `_phase` parameter. A single Phase input (default: 2) shifts every one of the twelve kernel centers into the past by that many bars.
- Phase = 0 — live estimate, flickers on the current bar (real-time only; history is immutable)
- Phase = 1 — 1-bar lag, non-repainting once the bar is confirmed
- Phase = 2 — recommended balance between freshness and stability (default)
- Phase = 3+ — extra margin against erratic ticks, higher lag
Historical repainting never occurs at any phase value. The library contains no `request.security` calls, no lookahead, and no array rotation that could leak future data. Every historical bar's plotted value is final once confirmed.
🟦 VISUAL PIPELINE
**Outer Ribbon Gradient** — All eleven outer kernels are plotted with a single shared color driven by the trend score via `color.from_gradient(score, -11, 11, thBear, thBull)`. As the score walks across its range, the entire ribbon shifts continuously between the active theme's bearish and bullish hues — producing a smooth visual feedback loop between the math and the palette.
**Inner Ribbon Shadow Trail** — Eleven lag-shifted primary snapshots (primary through primary ) drawn in the theme's accent hue with user-controlled opacity. On a trending chart the trail visually expands; on a reversing chart it contracts. Adjust opacity from 0 (invisible) to 100 (fully opaque) — default 40 balances presence and subtlety.
**Primary Kernel Anchor Line** — The primary kernel plotted as a dedicated bold line in the theme's accent color at 80 % opacity, distinct from the shadow trail. Provides a clear centerline amid the ribbon flow. Toggleable.
**Oscillator Subplot** — The smoothed trend score plotted in a dedicated subplot with a score-gradient vertical fill between the score line and the zero line. Opacity is user-controlled. An optional bold score line (up to 4 px wide) overlays the fill for sharp numeric reading.
**Last-Bar Trend Label** — A right-anchored label at the current bar in the oscillator pane. Format: `▲ TRIPLE BULL 11 / 11` (bull) or `▼ WEAK BEAR −3 / 11` (bear). The label is deleted and redrawn on every bar, so only one instance is ever present on the chart.
🟦 OSCILLATOR STYLES
The oscillator subplot ships with two visual presets, selectable from the Oscillator Style dropdown:
| Style | Plot Style | Fill | Best For |
|---|---|---|---|
| Classic Gradient | `plot.style_line` (smooth curve) | Continuous vertical gradient from score to zero | Trend flow, slope momentum |
| Stepline | `plot.style_stepline` (staircase) | Stepped gradient mirroring the discrete score plateaus | Signal / threshold trading, discrete level crossings |
**Classic Gradient** produces a smooth curve traced through the smoothed score values, with the gradient fill flowing continuously between the score line and the zero line. This is the default and suits traders who read trend direction through slope and curvature.
**Stepline** renders each bar as a horizontal plateau joined to the next bar by a vertical edge. Because the raw score is always an odd integer in { −11, −9, …, 9, 11 }, the staircase visualization honors the score's true discrete nature — making it easier to identify exact threshold crossings (e.g. the moment the score enters the ±9 extreme zone). The fill inherits the same stepline style, so the entire oscillator pane stays geometrically consistent.
Both styles share the same opacity controls, score line toggle, and line width setting — only the geometry of the score line and its fill changes between them.
🟦 THEME SYSTEM
Ten cohesive color palettes tuned to the Quant Edge Ribbon PRO optical brand. One selection drives every visual component — outer ribbon gradient, inner ribbon accent, oscillator fill, reference lines, signal label, dashboard accents — all sharing the same bull / bear / accent color axes:
| Theme | Bull | Bear |
|---|---|---|
| Prism | Forest green | Crimson red |
| Focus | Cyan steel | Deep orange |
| Solar | Warm amber | Indigo red |
| Frost | Sky blue | Soft lavender |
| Laser | Neon lime | Hot crimson |
| Aurora | Bright gold | Scarlet |
| Plasma | Electric aqua | Magenta |
| Bloom | Mint green | Hot pink |
| Eclipse | Deep navy | Dark crimson |
| Carbon | Near-black | Silver grey |
The oscillator's zero line uses Pine's `chart.fg_color` so it auto-adapts to the actual chart background (white on dark charts, black on light charts) — independent of the Dashboard's Display Mode setting.
🟦 REFERENCE LEVELS
Four user-configurable horizontal reference lines mark the score's structural thresholds inside the oscillator subplot:
| Level | Style | Meaning |
|---|---|---|
| +11 / −11 | Dotted | Ceiling / floor — the mathematical maximum (every comparison aligned) |
| +9 / −9 | Dashed | Extreme zone — nine or more of the eleven comparisons agree on direction |
Each pair (±11 and ±9) has an independent opacity input (0–100 %). A master toggle (Show Reference Levels) collapses all four lines to fully transparent in a single branch — useful for minimalist layouts. An additional `showOsc` gate hides them automatically when the oscillator itself is disabled.
🟦 PRO DASHBOARD
A 2-column, 12-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes, six docking positions, and four text sizes. Renders via `force_overlay = true` on the main price chart.
| Row | Label | Content |
|---|---|---|
| Header | Q-EDGE PRO | DARK / LIGHT |
| Theme | Theme | Active palette name |
| Kernel | Kernel | Selected kernel type |
| Divider | RIBBON | — |
| Primary ℓ | Primary ℓ | Primary bandwidth value |
| Span | Span | ℓ → ℓ + 11·s |
| Filter | Filter | No Filter / Smooth / Zero Lag |
| Divider | SCORE | — |
| Score | Score | ▲/▼ + integer score + " / 11" (bull/bear colored) |
| Bull / Bear | Bull / Bear | Bull comparison count / bear comparison count |
| Strength | Strength | ▰-bar + NEUTRAL / WEAK / STRONG / TRIPLE label |
| Primary | Primary | Primary kernel value in chart mintick format |
**Bull / Bear breakdown** — The eleven pairwise comparisons split into bulls (resolved +1) and bears (resolved −1). Always sums to 11, so this row gives a direct visual of how many kernel scales agree with the net direction.
🟦 ALERT CONDITIONS
Six opt-in alert conditions, each gated by its own toggle:
| Alert | Fires When |
|---|---|
| Bullish Flip | Score crosses from ≤ 0 into positive territory |
| Bearish Flip | Score crosses from ≥ 0 into negative territory |
| Extreme Bullish | Score reaches +9 or higher (first entry into the zone) |
| Extreme Bearish | Score reaches −9 or lower (first entry into the zone) |
| Full Confluence Up | Score hits +11 — every outer kernel aligned bullishly |
| Full Confluence Down | Score hits −11 — every outer kernel aligned bearishly |
All alerts use `alertcondition()` for maximum compatibility with PulseWire's alert system including webhooks. Messages are structured as `"Quant Edge Ribbon PRO: "` for easy parsing in downstream automation.
🟦 RECOMMENDED PRESETS
| Style | Primary ℓ | Bandwidth Step s | Phase | Filter | Chart |
|---|---|---|---|---|---|
| Scalper | 8–16 | 1 | 1 | No Filter | 1m–5m |
| Day Trader | 16–32 | 1–2 | 2 | Smooth | 15m–1h |
| Swing | 25–50 | 1–2 | 2 | Smooth | 4h–1D |
| Position | 50–120 | 2–3 | 3 | Smooth | 1D–1W |
**Bandwidth Step tuning** — Step = 1 produces a tight ribbon where adjacent outer kernels sit visually close together. Steps of 2–4 spread the eleven outer kernels across a broader spectrum of scales, making expansion / contraction easier to read at a glance. Step 5–6 is reserved for very wide ribbons where each line represents a distinctly different time scale.
🟦 COMPATIBILITY
- Pine Script v6
- All exchanges, all asset classes (crypto, forex, equities, commodities, indices)
- All timeframes (1 minute through Monthly)
- Both Dark and Light chart themes — visual elements auto-adapt via `chart.fg_color`
- No exchange-specific logic — fully deterministic
🟦 TECHNICAL NOTES
- **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression math is delegated to the published library
- **Plot budget** — 11 outer + 11 inner + 1 primary + 2 oscillator plots + 1 fill + 4 hlines = well under Pine's 64-plot limit
- **Table** — Single `var table` created once on `barstate.islast` with `force_overlay = true`; dashboard renders on the main chart pane, zero historical overhead
- **No persistent drawing objects** — no `box.new`, `line.new`, no `array.new`; the single trend label is deleted and recreated every bar so only one instance is ever present
- **Opacity convention** — every user-facing opacity input follows `0 = invisible, 100 = fully opaque`; conversion to Pine's native transparency is centralized in a single helper function (`f_opac`)
- **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead, no future-bar leakage at any phase value
- **Chart background adaptive** — the oscillator's zero line uses `chart.fg_color`, so it always renders with high contrast regardless of the user's chart color scheme
🟦 DISCLAIMER
Quant Edge Ribbon PRO is a technical analysis indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output. The integer trend score is a geometric summary of kernel alignments — not a forecast — and should always be combined with broader context: higher-timeframe structure, volatility regime, liquidity, news, and risk management.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of Quant Edge Ribbon PRO or the underlying KernelLens library. Indicator

Multi-Oscillator Consensus Engine [AGPro Series]Multi-Oscillator Consensus Engine
🔹 Overview
Multi-Oscillator Consensus Engine aggregates ten independent momentum
oscillators into a single regime classifier with overlay Consensus Zones,
flip event labels, and agreement persistence tracking. Instead of watching
ten charts separately, traders see one unified answer: are the oscillators
in agreement, and what is the consensus saying right now?
The script monitors RSI, Stochastic, CCI, MFI, Williams %R, ROC, Ultimate
Oscillator, MACD, DMI balance, and Aroon balance. Each oscillator is
normalized to a 0–100 scale and votes bullish, bearish, or neutral against
configurable thresholds. The aggregated vote determines the market regime
and drives everything else on the chart.
🔹 Unique Edge
Most multi-oscillator tools stop at a dashboard or a simple agreement
percentage. This engine goes further:
- Regime Classification — four distinct states (Consensus Bull, Consensus
Bear, Divergent, Transition) instead of a binary signal.
- Consensus Zones — a horizontal price zone is born at every regime flip
and stays alive while the regime holds. When the regime ends, the zone
becomes historical structure.
- Flip Event Labels — regime transitions are marked directly on price
with merged flip + extreme agreement tags.
- Persistence Tracking — streak bars, last flip distance, and historical
extreme rate tell you how trustworthy the current consensus is.
- Label Discipline — cooldown, horizontal stagger, and flip+extreme merge
logic keep the chart readable even in choppy regimes.
🔹 Methodology
Step 1. Ten oscillators are computed with their classic defaults and
normalized to a 0–100 range. Indicators with native 0–100 output (RSI,
Stochastic, MFI, Ultimate) pass through directly. Others (CCI, ROC, MACD
histogram) are rescaled against their own recent range. Williams %R is
flipped from its native -100..0 scale.
Step 2. Each normalized oscillator casts a vote. Values above the bullish
threshold vote +1, values below the bearish threshold vote -1, everything
else is neutral. Vote counts and agreement percentage are computed bar by bar.
Step 3. Regime is assigned from the vote distribution. Seven or more votes
in one direction triggers Consensus Bull or Consensus Bear. A tight spread
(bull-bear difference ≤ 2) triggers Divergent. Everything else is a
Transition state.
Step 4. On every bull↔bear regime entry, a new Consensus Zone is born at
the current close ± a configurable ATR multiple. The zone extends forward
while the regime is active and locks in place when the regime ends. A
maximum of five active zones keeps the chart clean.
Step 5. Labels are rendered only when cooldown and merge rules allow.
Extreme agreement events (80%+ by default) are either merged into the flip
label or drawn separately with larger offset.
🔹 Signals & Alerts
Seven alert conditions ship with the script:
- Consensus Bull Entry — regime has just entered Consensus Bull
- Consensus Bear Entry — regime has just entered Consensus Bear
- Consensus Bull Flip — direct Bear → Bull transition
- Consensus Bear Flip — direct Bull → Bear transition
- Extreme Bullish Agreement — agreement crosses the extreme threshold up
- Extreme Bearish Agreement — same, on the bearish side
- Consensus Streak 20+ — current regime has held for twenty bars
🔹 Key Inputs
- Oscillator Periods — individual length settings for all ten oscillators
- Bullish / Bearish Thresholds — the normalized levels that define a vote
- Consensus Threshold — how many oscillators must agree for a regime (default 7/10)
- Extreme Agreement — agreement percentage for extreme events (default 80%)
- Consensus Zones — show/hide, ATR length and multiplier, max active count,
closed zone trail
- Label Cooldown — minimum bars between flip labels, prevents clutter
- Merge Flip + Extreme — combine same-bar events into one label
- Panel — six location options, Dark/Light theme, font sizes
🔹 How to Use
Trend traders: wait for a Consensus Bull or Consensus Bear regime to
establish (streak > 5 bars), then use pullbacks into the active Consensus
Zone as entries in the regime direction. Exit on opposite regime flip.
Reversion traders: Extreme Agreement events mark moments where all
oscillators are stretched in the same direction. These are classic mean
reversion setups. Wait for a regime flip against the extreme, confirmed on
the next bar.
Regime filter: overlay the panel on any chart and use the Regime and
Agreement readings as a binary filter for your primary system. Only take
longs when regime is Bull, only take shorts when regime is Bear.
Works on all timeframes from 1m to 1W. Higher timeframes produce fewer
but higher-conviction signals.
🔹 Limitations & Transparency
- The oscillator votes use normalized thresholds. On extremely narrow
ranges, the normalization may produce unstable votes. Raising the
Bullish/Bearish Thresholds reduces this sensitivity.
- Consensus Zones are drawn from close price at the flip bar. Large wick
bars may place the zone slightly away from the visual pivot.
- The script is not a standalone trading system. It is a confluence and
regime tool to combine with your own structure, volume, or price action
analysis.
- All signals repaint only within the current forming bar. Once a bar
closes and barstate.isconfirmed is true, flip labels and zones are final.
🔹 Risk Disclosure
This indicator is provided for educational and analytical purposes only.
It is not financial advice. Trading involves substantial risk. Past
behavior of regime transitions does not guarantee future performance.
Always use proper risk management and never risk more than you can afford
to lose. Indicator

BTC Valuation Cycle [Alpha Extract]A sophisticated multi-metric Bitcoin valuation framework that synthesizes on-chain analytics including SOPR, MVRV, Price-to-Realized, and Mayer Multiple into a unified 0-100 cycle oscillator with six-tier zone classification for market cycle identification. Utilizing logistic transformation with configurable weighting and z-score normalization, this indicator delivers institutional-grade Bitcoin-specific valuation assessment with pivot-based extreme detection and comprehensive alert system. The system's weighted composite architecture combined with adaptive curve intensity enables precise calibration of cycle sensitivity while maintaining statistical validity across Bitcoin's multi-year market cycles.
🔶 Advanced Multi-Metric Synthesis Engine
Implements sophisticated composite calculation combining four distinct Bitcoin valuation metrics with configurable weighting and normalization framework. The system retrieves SOPR (Spent Output Profit Ratio), MVRV (Market Value to Realized Value), Price-to-Realized ratio, and Mayer Multiple from on-chain sources, applies z-score normalization to each metric over configurable periods, transforms via logistic function for 0-100 scaling, and generates weighted average creating unified cycle score.
// Component Score Calculation
SOPR_Centered = SOPR - 1.0
SOPR_Z = z_score(SOPR_Centered, Normalization_Length)
SOPR_Score = logistic_100(SOPR_Z, Curve_Intensity)
Price_to_Realized_Z = z_score(Price / Realized_Price, Normalization_Length)
PR_Score = logistic_100(Price_to_Realized_Z, Curve_Intensity)
MVRV_Z = z_score(Market_Cap / Realized_Cap, Normalization_Length)
MVRV_Score = logistic_100(MVRV_Z, Curve_Intensity)
Mayer_Z = z_score(Mayer_Multiple, Normalization_Length)
Mayer_Score = logistic_100(Mayer_Z, Curve_Intensity)
// Weighted Composite
Cycle = (SOPR_Score × W_SOPR + PR_Score × W_PR + MVRV_Score × W_MVRV + Mayer_Score × W_Mayer) / (W_SOPR + W_PR + W_MVRV + W_Mayer)
🔶 Understanding Bitcoin Valuation Metrics
SOPR (Spent Output Profit Ratio) measures the degree of profit for coins moved on-chain, calculated as value sold divided by value paid. Values above 1.0 indicate profitable selling (distribution), below 1.0 indicate loss-taking (capitulation). The system centers SOPR around 1.0 for normalization.
MVRV (Market Value to Realized Value) compares current market cap to realized cap (aggregate cost basis). High MVRV signals overvaluation as price exceeds average acquisition cost; low
MVRV suggests undervaluation. The system offers Ratio mode (raw MVRV), Z-Score mode (statistical deviation), or Blend mode (average of both).
Price-to-Realized Ratio directly compares current BTC price to realized price (realized cap divided by circulating supply), providing cleaner valuation signal than MVRV by removing market cap distortions.
Mayer Multiple measures price relative to 200-day moving average. Values above 2.4 historically mark tops; values near or below 1.0 mark bottoms. The system normalizes this classic technical indicator alongside on-chain metrics.
🔶 Logistic Transformation Framework
Features sophisticated logistic function application converting unbounded z-scores into bounded 0-100 range with configurable curve intensity controlling sensitivity. The system applies formula: 100 / (1 + exp(-z × k)) where z is z-score and k is curve intensity (default 0.90), creates S-curve transformation preserving relative relationships while preventing extreme outliers, and enables smooth gradient visualization across entire cycle range.
🔶 Six-Tier Cycle Zone Classification
Implements comprehensive market cycle framework dividing 0-100 range into six distinct zones with configurable thresholds representing Bitcoin's characteristic bubble and bust patterns. The system defines Bottom Extreme (default <10, accumulation zone), Cold Zone (10-25, early recovery), Lower Mid (25-40, neutral to bullish), Upper Mid (40-60, bullish), Hot Zone (60-75, late bull market), and Top Extreme (>75, euphoria/distribution) with dynamic color coding.
🔶 Pivot-Based Extreme Detection System
Provides intelligent local extreme identification using pivot high/low detection with zone threshold filtering and visual capsule markers. The system detects pivot highs above Hot Zone threshold and pivot lows below Cold Zone threshold using configurable left/right bars, creates horizontal capsule visualizations at exact extreme values with color-coded centers (red for tops, cyan for bottoms), and maintains rolling array limited to maximum capsule count for clean chart presentation.
🔶 MVRV Calculation Mode Selection
Offers three distinct MVRV calculation approaches optimizing for different market conditions and analytical preferences. Ratio mode uses raw Market Cap / Realized Cap for direct valuation comparison, Z-Score mode applies statistical normalization emphasizing deviations from historical mean, and Blend mode (default) averages both approaches balancing absolute valuation with statistical context for robust signal generation.
🔶 Configurable Metric Weighting System
Features flexible weight allocation enabling traders to emphasize preferred metrics or disable unreliable components during specific market regimes. The system accepts 0.0-N weight values for each metric (default 1.0 all equal), automatically handles missing data by excluding NA metrics from composite, recalculates weighted average dynamically, and enables custom cycle calibration based on trader's confidence in different on-chain signals.
🔶 Confirmed HTF Data Integration
Implements rigorous anti-repaint methodology using confirmed higher-timeframe values with offset preventing live bar distortion. The system retrieves all on-chain metrics from daily timeframe with 1-bar offset ensuring only completed daily candle data influences cycle score, applies identical offset to Mayer Multiple calculation, and maintains signal stability across real-time updates preventing false extreme alerts.
🔶 Comprehensive Alert Framework
Provides five distinct alert conditions covering critical cycle events and threshold breaches with descriptive messages. The system triggers Top Extreme alert on crossover above top threshold (default 90), Bottom Extreme alert on crossunder below bottom threshold (default 10), Hot Rejection alert when cycle falls from Hot Zone, Cold Reclaim alert when cycle rises from Cold Zone, and Mayer Threshold breach alert for traditional technical confirmation.
🔶 Gradient Zone Visualization Architecture
Creates intuitive color-coded area plot with six distinct color zones reflecting current cycle position through visual spectrum from cyan (extreme bottom) through purple/orange to red (extreme top). The system applies dynamic zone coloring to both area fill and cycle value display, implements configurable area transparency (default opaque), and maintains consistent color scheme across oscillator pane, table values, and capsule markers.
🔶 Real-Time Diagnostics System
Features comprehensive data availability monitoring with missing metric labels and detailed value table showing all component metrics. The system detects NA values in SOPR, Realized Price, MVRV, or Mayer Multiple, displays warning label listing unavailable metrics, and provides table overlay showing current values for Cycle score, all four components, MVRV-Z, Mayer MA, and threshold with color-coded formatting.
🔶 Performance Optimization Framework
Employs efficient calculation methods with null-safe division functions, optimized array management for capsule storage, and conditional plotting minimizing unnecessary rendering. The system includes streamlined weighted average calculation skipping NA metrics, smart capsule cleanup maintaining maximum limit through oldest-first deletion, and minimal recalculation overhead through var declarations and confirmed bar logic.
This indicator delivers sophisticated Bitcoin-specific valuation analysis through multi-metric on-chain synthesis unavailable in traditional technical indicators. By combining SOPR (profit/loss behavior), MVRV (cost basis valuation), Price-to-Realized (pure valuation), and Mayer Multiple (technical context) into unified cycle framework with statistical normalization, it provides comprehensive market cycle assessment grounded in blockchain fundamentals. The six-tier zone system maps directly to Bitcoin's characteristic 4-year halving cycles with Bottom Extreme zones historically marking generational buying opportunities and Top Extreme zones marking distribution phases. Perfect for long-term Bitcoin investors seeking data-driven cycle timing, position sizing based on valuation extremes (increase allocation in Cold/Bottom zones, reduce in Hot/Top zones), and objective framework for navigating Bitcoin's volatile multi-year cycles with alerts providing advance warning of major cycle transitions requiring portfolio reassessment. Indicator

Momentum Terrain 3D [LuxAlgo]The Momentum Terrain 3D tool visualizes multi-dimensional RSI momentum by mapping various lookback lengths across time into a single 3D topographical landscape.
🔶 USAGE
The script provides a comprehensive view of momentum by calculating multiple RSI lengths simultaneously. This allows users to see how short-term momentum (foreground) interacts with long-term structural momentum (background) in a single visual pane, offering a unique perspective on trend strength and exhaustion.
🔹 Understanding the Dimensions
To navigate the 3D map, it is essential to understand the three axes:
X-Axis (Width): Represents Time. The rightmost edge of the terrain represents the current bar, while moving left traverses historical data.
Y-Axis (Depth): Represents the RSI Lookback Length. The front of the terrain shows fast, reactive momentum (short lookbacks), while the back shows slow, structural momentum (long lookbacks).
Z-Axis (Height): Represents the RSI Value. A semi-transparent "Neutral Plane" is fixed at the 50 level. Peaks above this plane represent bullish momentum, while valleys below represent bearish momentum.
🔹 Interpreting the Topography
Trend Alignment: When the entire landscape from back to front rises together, it indicates a "unified" momentum where all timeframes are in bullish agreement.
Spotting Pullbacks: If the background (long-term) remains a high mountain but the foreground (short-term) drops into a valley, it identifies a pullback within a macro uptrend.
Trend Compression: If the terrain appears flat and stays near the 50 neutral plane, the market is ranging or in a period of indecision.
🔹 OB/OS Pillars
The script identifies extreme momentum through vertical color pillars. Red pillars indicate overbought conditions (RSI > 70), while cyan pillars indicate oversold conditions (RSI < 30). These help traders quickly spot exhaustion points across the entire momentum spectrum without checking multiple individual indicators.
🔶 DETAILS
The indicator utilizes an optimized 3D rendering engine built with Pine Script's polyline and matrix systems. By calculating a range of RSI lengths (e.g., from a minimum of 5 to a maximum of 60) for every historical bar within the defined window, it creates a "momentum matrix."
This matrix is then projected into 3D space using trigonometric transformations (Yaw and Pitch). The "Terrain Smoothing" feature uses an exponential smoothing calculation on the raw RSI data to transform jagged spikes into readable topographical features, making it easier to identify the flow of capital and the weight of momentum shifts.
🔶 SETTINGS
🔹 Terrain & Matrix
Time History (Width): Determines how many historical bars are rendered on the X-axis.
Lookback Layers (Depth): The number of different RSI lengths calculated. Increasing this creates a denser, more detailed surface.
Terrain Smoothing: Applies smoothing to the RSI values to create a more natural, less noisy landscape.
Minimum/Maximum Lookback: Defines the range of RSI lengths used for the front (fast) and back (slow) edges.
🔹 Camera Projection
Yaw/Pitch: Rotates the landscape horizontally or tilts it vertically to change the visual perspective.
Scale X/Y/Z: Adjusts the width, depth, and height intensity of the 3D model.
Offset X/Y: Moves the entire 3D object on the chart pane horizontally or vertically for better positioning.
🔹 Style & Colors
Show Wireframe/Surface: Toggles the visibility of the grid lines and the solid surface fill.
Show OB/OS Volume Fills: Enables the vertical pillars that highlight extreme RSI levels.
Show Current Price Marker: Highlights the most recent momentum profile and displays the current price label on the 3D grid.
Neutral Plane Color: Adjusts the color and transparency of the RSI 50 reference floor.
Indicator

Indicator

QuantEdge Momentum ML [PRO]🟦 QuantEdge Momentum ML PRO is a k-Nearest Neighbors driven momentum oscillator built on an adaptive machine-learning core. Unlike RSI, Stochastic, or MACD — which apply the same static formula to every asset — QE-ML PRO learns the dual-horizon RSI fingerprints that have historically led to bullish versus bearish outcomes on the exact instrument being traded, then scores the current bar against the N closest historical matches. The result is a non-parametric, self-calibrating oscillator whose decision boundary is shaped by the asset's own behaviour rather than a hard-coded curve.
The indicator integrates nine independent layers — feature engine, training sampler, k-NN predictor, WMA signal line, stdev-adjusted OB/OS bands, filtered signal dots, gradient channel, theme-adaptive dashboard, and a nine-theme palette — all rendered on a single, clean oscillator panel.
🟦 HOW THE CORE ENGINE WORKS
**Dual-Horizon RSI Feature Vector**
Each bar, the Feature Engine computes two RSI values at different lookback windows and smooths both through a shared trend-length WMA:
- `rsiFast = WMA(RSI(close, FastPeriod), TrendLength)` — reactive short-term momentum
- `rsiSlow = WMA(RSI(close, SlowPeriod), TrendLength)` — structural mid-term momentum
The pair `(rsiSlow, rsiFast)` is a 2-dimensional point in RSI feature space. Every training sample stores one such point along with a ±1 label that records whether price rose or fell since the previous sample. Over time the dataset accumulates a cloud of labelled points that maps which RSI states historically preceded up-moves versus down-moves on this exact asset.
**Training Sampler — Multi-Trigger Collector**
Three collection modes decide when to append a new labelled sample:
| Mode | Trigger | Use Case |
|---|---|---|
| **MA Crossover** | Fast WMA crosses Slow WMA | Clean, sparse samples — classic single-trigger behaviour |
| **Periodic** | Every N bars (user-set) | Fills dataset fast on new / low-history charts |
| **Hybrid** | MA crossover **OR** every N bars | Richest training set — recommended for fresh assets |
Sampling is gated by `barstate.isconfirmed` so the dataset never absorbs unconfirmed values from a flickering live bar.
**k-NN Predictor with Adaptive k**
On every bar, the predictor computes Euclidean distance in the 2D RSI feature space between the live `(rsiSlow, rsiFast)` point and every historical sample:
```
d = sqrt((rsiSlow_now - rsiSlow_hist)² + (rsiFast_now - rsiFast_hist)²)
```
The K closest historical points vote by summing their ±1 labels. The effective K is resolved adaptively using the classical statistical heuristic:
```
kEff = max(3, min(kMax, floor(sqrt(N))))
```
This means early bars — when only a handful of samples exist — use a small K, and the value stabilises as the dataset fills. On a fresh chart you never get a noisy prediction from an undersized neighborhood, and on a mature dataset K automatically scales up for smoother output.
**Bias Correction — Label-Mean Recentering**
Raw k-NN output is biased whenever the label distribution is skewed. On a trending asset, Periodic sampling fills the dataset with mostly +1 (or mostly −1) labels, pushing every prediction off zero. QE-ML PRO subtracts the expected value from the raw sum:
```
prediction = neighborLabelSum − (kEff × meanLabelAcrossDataset)
```
This keeps the mid-level visually centred at zero regardless of how trending the underlying asset has been. The correction is applied on every bar and is what makes the oscillator read cleanly on both sideways and strongly trending markets.
**Minimum Sample Gate**
Until the dataset has reached the user-defined Minimum Training Samples threshold, the predictor outputs exactly zero. This prevents unreliable readings during the warm-up phase on fresh charts.
**FIFO Rotation**
The dataset is hard-capped at Max Dataset Size. Once the cap is reached, the oldest sample is discarded on every new insertion — classical rolling window memory that keeps the k-NN scan bounded and the indicator fast on long histories.
🟦 PREDICTION LINE — FIVE VISUAL STYLES
All five styles are line-based. Only the visual effect differs — the underlying k-NN math is identical across styles.
| Style | Character |
|---|---|
| **Stratum** | Thick adaptive line with zone-based opacity: solid in extreme zones, semi-transparent in the mid zone. Layered intensity aesthetic — default |
| **Neon** | Bright core line with an outer glow halo. Cyberpunk luminous effect, best on dark backgrounds |
| **Resonance** | LRI-style gradient line that fades near the midline and brightens toward the rolling extremes |
| **Pulse** | Adaptive bull/bear color (above midline = bull, below = bear) plus the WMA signal line. The QE-ML PRO classic look |
| **Mono** | Single flat theme-bull line, no gradient, no adaptive coloring. Minimalist single-color silhouette |
🟦 SIGNAL LINE
A WMA of the raw prediction output, used as a crossover trigger line in the MACD convention. Crossovers between the prediction and signal line mark momentum regime changes.
**Two Visual Styles**
| Style | Rendering |
|---|---|
| **Neon** | Bright core line wrapped in a wider semi-transparent glow halo — cyberpunk aesthetic |
| **Flat** | Plain single-color line, no halo, no gradient — minimalist clean look |
🟦 SIGNAL DOTS — FILTERED CROSSOVER MARKERS
A two-layer neon cross-dot renderer fires on every Prediction × Signal crossover that survives the active filter mode. Four progressive filters decide which raw crosses reach the chart:
| Filter Mode | Behaviour | Signal Count |
|---|---|---|
| **All Crosses** | Every cross becomes a dot | Highest — noisy on choppy assets |
| **Zone Only** | Only crosses inside an OB or OS strip | Mean-reversion triggers — strongest reversal setups |
| **Mid Aligned** | Bull dots only above mid, bear dots only below | Trend-following — keeps you on regime side |
| **Strict** | Zone Only + Mid Aligned + extra strength multiplier on mid-zone crosses | Fewest signals, highest conviction — default |
Two additional gates filter out whipsaws:
- **Cooldown (bars)** — minimum spacing between consecutive dots, prevents cluster spam in ranges
- **Min Strength** — minimum `|prediction − signal|` separation at the moment of the cross, drops razor-thin crossovers that close back on themselves
Each dot is a two-layer plot: an outer glow halo with user-adjustable size and opacity, and a bright solid core on top — independently sized and opacity-controlled so users can dial in the exact visual weight they want.
The dot is placed at the actual cross point: bull dots at `min(prediction, signalLine)`, bear dots at `max(prediction, signalLine)`.
🟦 DYNAMIC BANDS — STDEV-ADJUSTED OB / OS ZONES
QE-ML PRO does not use fixed 80 / 20 overbought / oversold levels. Instead, the bands adapt to the actual historical range of the prediction output:
- **Channel Extremes** — rolling highest / lowest of the prediction over a user-configurable lookback
- **Stdev Band** — EMA of rolling standard deviation of the prediction, multiplied by the user's stdev length
- **OB Level** = `rangeHi − stdevBand` (inner boundary of the overbought strip)
- **OS Level** = `rangeLo + stdevBand` (inner boundary of the oversold strip)
The result is a pair of mean-reversion zones that tighten during quiet markets and widen during volatile ones — no manual recalibration needed across assets.
The strips are rendered as gradient fills anchored on the live prediction plot, so they only appear visually while the prediction is actually inside the zone.
🟦 CHANNEL GRADIENT
Two symmetric gradient fills bracket the mid line. The upper fill stretches from `midValue` to `rangeHi`, the lower fill from `midValue` to `rangeLo`. Opacity fades from full intensity at the extremes to fully transparent at the midline — a visual range meter showing how close the prediction is sitting to its historical boundaries.
Colors are pulled from the active Theme. A single opacity slider controls the gradient intensity.
🟦 DASHBOARD — LIVE DATA PANEL
A compact 2-column × 7-row monospace panel drawn on the last bar only (zero historical overhead). Every field updates in real time on the live bar.
| Row | Left | Right |
|---|---|---|
| Header | QE-ML PRO | Regime (▲ BULL / ▼ BEAR / ■ NEUTRAL) |
| Row 1 | Prediction | Raw value + trend arrow vs previous bar |
| Row 2 | Signal | WMA trigger line value |
| Row 3 | Strength | 10-block gauge of `|prediction − signal|` normalised against rolling channel |
| Row 4 | Zone | OB / MID / OS tag |
| Row 5 | Dataset | Sample count / effective k |
| Row 6 | Mode | Active Learning Mode (MA Cross / Periodic / Hybrid) |
**Theme-Aware Auto-Invert**
The panel background scaffolds auto-switch:
- **Tropic / Amber / Pastel / Cyber / Gold / Electric / Candy** → dark panel with bright theme accent text
- **Midnight / Graphite** → light panel with dark theme accent text
This guarantees legibility on every theme without breaking the theme's color identity — because Midnight and Graphite use deep dark bull tones that would drown against a black panel.
**Direction via Glyphs, Not Color**
Both columns share the same full-strength theme tone. Regime direction is conveyed by `▲ ▼ ■` glyphs rather than color shifts, which keeps the panel reading cleanly even on the most minimal themes.
🟦 NINE COLOR THEMES
One theme selector drives every colored component — Prediction line, Signal line, Channel fill, OB / OS strips, Mid-level line, Signal Dots, and Dashboard panel. No per-color manual inputs.
| Theme | Character | Bull | Bear |
|---|---|---|---|
| **Tropic** | Cyan steel + deep orange — electric contrast (default) | Cyan | Deep Orange |
| **Amber** | Warm amber + indigo blue — fire tones | Amber | Red |
| **Pastel** | Sky blue + soft lavender — cool arctic glow | Sky Blue | Lavender |
| **Cyber** | Neon lime + hot crimson — cyber terminal | Neon Green | Crimson |
| **Gold** | Bright gold + scarlet — solar warmth | Yellow Gold | Red |
| **Electric** | Electric aqua + magenta — high-voltage neon | Aqua | Magenta |
| **Candy** | Neon green + hot pink — dark energy pop | Mint Green | Hot Pink |
| **Midnight** | Deep navy + dark crimson — dark depth (auto light dashboard) | Navy Blue | Dark Red |
| **Graphite** | Near-black + silver grey — monochrome minimal (auto light dashboard) | Near Black | Grey |
🟦 ALERT SYSTEM — TEN CONDITIONS
Every alert is gated by its matching "Show X" visibility toggle — if a component is hidden from the chart, its alerts are automatically suppressed. This eliminates the mismatch between visual signals and alert signals that plagues many indicators.
| Alert | Condition | Gated By |
|---|---|---|
| Crossover OB | Prediction crosses above the overbought boundary | Show OB/OS Fill |
| Crossunder OB | Prediction crosses back down through OB | Show OB/OS Fill |
| Crossover OS | Prediction crosses up through oversold boundary | Show OB/OS Fill |
| Crossunder OS | Prediction crosses below the oversold boundary | Show OB/OS Fill |
| Crossover Mid | Prediction crosses above the mid line — bullish regime flip | Show Mid Level |
| Crossunder Mid | Prediction crosses below the mid line — bearish regime flip | Show Mid Level |
| Crossover Signal | Prediction crosses above its WMA signal line (MACD bullish) | Show Signal Line |
| Crossunder Signal | Prediction crosses below its WMA signal line (MACD bearish) | Show Signal Line |
| Bull Signal Dot | A filtered Bull Signal Dot is plotted (uses Filter Mode + Cooldown + Min Strength) | Show Signal Dots |
| Bear Signal Dot | A filtered Bear Signal Dot is plotted (uses Filter Mode + Cooldown + Min Strength) | Show Signal Dots |
🟦 SETTINGS REFERENCE
**Visual**
- Theme — nine cohesive palettes. Default: Tropic
**Machine Learning**
- Neighbors (k) — upper bound on neighbors used by the predictor. Default: 100
- Adaptive k — scales k with dataset size using the `floor(sqrt(N))` heuristic. Default: ON
- Learning Mode — MA Crossover / Periodic / Hybrid. Default: MA Crossover
- Sample Every (bars) — bar interval for the Periodic / Hybrid trigger. Default: 5
- Minimum Training Samples — warm-up gate, predictor outputs zero until reached. Default: 30
- Max Dataset Size — hard FIFO cap. Default: 500 (safe on all timeframes)
**Feature Engine**
- Trend Length — WMA smoothing applied to both RSI features. Default: 20
- RSI Fast Period — first feature dimension. Default: 5
- RSI Slow Period — second feature dimension. Default: 20
- MA Fast Period — fast WMA for the crossover training trigger. Default: 5
- MA Slow Period — slow WMA for the crossover training trigger. Default: 20
**Prediction Line**
- Show Prediction Line — master toggle. Default: ON
- Prediction Style — Stratum / Neon / Resonance / Pulse / Mono. Default: Stratum
- Prediction Width — 1 to 5. Default: 2
**Signal Line**
- Show Signal Line — toggle. Default: ON
- Signal Style — Neon / Flat. Default: Neon
- Signal Period — WMA length of the signal line. Default: 20
- Signal Width — 1 to 5. Default: 1
**Signal Dots**
- Show Signal Dots — toggle. Default: ON
- Filter Mode — All Crosses / Zone Only / Mid Aligned / Strict. Default: Strict
- Cooldown (bars) — minimum spacing between dots. Default: 5
- Min Strength — minimum `|prediction − signal|` at the cross. Default: 0.5
- Core Dot Size — 1 to 8. Default: 3
- Core Dot Opacity — 0 to 100. Default: 100
- Glow Dot Size — 1 to 12. Default: 8
- Glow Dot Opacity — 0 to 100. Default: 30
**Channel Fill**
- Show Channel Fill — toggle. Default: ON
- Channel Opacity — 0 to 100. Default: 25
- Channel Lookback — rolling highest / lowest window. Default: 500
**OB / OS Fill**
- Show OB/OS Fill — toggle. Default: ON
- Zone Stdev Length — stdev window that offsets the OB / OS boundaries inward. Default: 20
**Mid Level**
- Show Mid Level — toggle. Default: ON
- Mid Level Value — Y-value of the reference line. Default: 0
- Mid Level Style — Solid / Dashed / Dotted. Default: Dashed
**Dashboard**
- Show Dashboard — toggle. Default: ON
- Panel Position — six slots (Top/Middle/Bottom × Right/Left). Default: Middle Right
- Panel Text Size — Tiny / Small / Normal / Large. Default: Small
**Alerts**
- Ten opt-in toggles, one per alert condition. All default: ON
🟦 TRADER PRESETS — SETTINGS BY STYLE
QE-ML PRO is volatility-agnostic thanks to the adaptive bands and bias correction, but the reactivity of the predictor scales directly with the feature and sampler parameters. The four presets below are tested starting points you can drop straight into the settings panel — adjust by ±20% to taste.
---
** SCALPER — 1m / 3m / 5m**
High-frequency entries, tight stops, many signals per session. Priority is reaction speed — you want the predictor to flip states within a handful of bars of an actual move.
| Setting | Value |
|---|---|
| Trend Length | 10 |
| RSI Fast Period | 3 |
| RSI Slow Period | 14 |
| MA Fast Period | 3 |
| MA Slow Period | 10 |
| Signal Period | 8 |
| Neighbors (k) | 40 |
| Adaptive k | ON |
| Learning Mode | **Hybrid** |
| Sample Every | 2 |
| Minimum Training Samples | 20 |
| Max Dataset Size | **300** (keeps 1m charts fast) |
| Filter Mode | **All Crosses** or Zone Only |
| Cooldown | 2 |
| Min Strength | 0.3 |
| Channel Lookback | 200 |
| Zone Stdev Length | 10 |
| Prediction Style | Neon or Stratum |
**Why:** Low smoothing (Trend=10) + short RSI pair (3/14) keeps the features razor-sharp. Hybrid learning means you never wait for an MA crossover during quiet 1m sessions. Max Dataset capped at 300 protects you from the PulseWire per-bar calculation limit on long 1m histories.
---
** DAY TRADER — 15m / 30m / 1H**
Balanced reactivity and conviction — the default profile. You want clean crosses without noise spam, and signals that survive the open / close volatility spikes.
| Setting | Value |
|---|---|
| Trend Length | 20 (default) |
| RSI Fast Period | 5 (default) |
| RSI Slow Period | 20 (default) |
| MA Fast Period | 5 (default) |
| MA Slow Period | 20 (default) |
| Signal Period | 20 (default) |
| Neighbors (k) | 100 (default) |
| Adaptive k | ON |
| Learning Mode | **MA Crossover** (default) |
| Minimum Training Samples | 30 (default) |
| Max Dataset Size | 500 (default) |
| Filter Mode | **Strict** (default) |
| Cooldown | 5 (default) |
| Min Strength | 0.5 (default) |
| Channel Lookback | 500 (default) |
| Zone Stdev Length | 20 (default) |
| Prediction Style | Stratum (default) |
**Why:** Every default value was tuned for this range. Strict filter + 5-bar cooldown keeps the dot count honest on a 30m chart. MA Crossover sampling gives you clean sparse data since 15m+ charts already have enough crossover events.
---
** SWING TRADER — 4H / 1D**
Lower signal frequency, higher conviction per signal. You're holding for days or weeks — every dot needs to mean something.
| Setting | Value |
|---|---|
| Trend Length | 30 |
| RSI Fast Period | 7 |
| RSI Slow Period | 30 |
| MA Fast Period | 7 |
| MA Slow Period | 30 |
| Signal Period | 30 |
| Neighbors (k) | 150 |
| Adaptive k | ON |
| Learning Mode | MA Crossover |
| Minimum Training Samples | 50 |
| Max Dataset Size | 800 |
| Filter Mode | **Strict** |
| Cooldown | 10 |
| Min Strength | 0.8 |
| Channel Lookback | 800 |
| Zone Stdev Length | 30 |
| Prediction Style | Stratum or Mono |
**Why:** Longer feature periods mean the predictor only moves on genuine structural shifts. Larger k (150) + bigger dataset (800) gives the k-NN vote a wider base so outliers don't flip the sign. Cooldown of 10 bars on a 4H chart = 40 hours minimum between dots — exactly what a swing trader wants.
---
** POSITION / LONG-TERM — 1D / 1W / 1M**
Macro regime detection. You're looking for the handful of generational setups per year — noise is the enemy.
| Setting | Value |
|---|---|
| Trend Length | 50 |
| RSI Fast Period | 10 |
| RSI Slow Period | 40 |
| MA Fast Period | 10 |
| MA Slow Period | 40 |
| Signal Period | 40 |
| Neighbors (k) | 200 |
| Adaptive k | ON |
| Learning Mode | **Hybrid** |
| Sample Every | 3 |
| Minimum Training Samples | 40 |
| Max Dataset Size | 1000 |
| Filter Mode | **Strict** |
| Cooldown | 15 |
| Min Strength | 1.0 |
| Channel Lookback | 1000 |
| Zone Stdev Length | 40 |
| Prediction Style | Mono or Pulse |
**Why:** Weekly and monthly charts have few crossover events per year — without Hybrid mode the dataset starves. Sample Every = 3 on a weekly chart means one sample every 3 weeks, which is plenty of structural density. Min Strength 1.0 filters out every shallow cross — you only see dots on generational momentum inflections.
---
**Tuning Tip**
If the predictor feels **too reactive** → increase Trend Length and Signal Period by 25%, raise Cooldown.
If the predictor feels **too sluggish** → switch Learning Mode to Hybrid, decrease Min Samples, lower Trend Length.
If the dashboard shows **Dataset N is stuck low** → switch Learning Mode from MA Crossover to Hybrid — crossover events are too rare on your current settings.
If you see **runtime / timeout errors** on long histories → drop Max Dataset Size to 300 and Channel Lookback to 300.
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in PulseWire Pine Script v6.
- **Crypto** — Spot, futures, perpetual contracts
- **Forex** — All pairs
- **Equities** — Stocks, ETFs, indices
- **Commodities** — Metals, energy, agriculture
- **Timeframes** — 1m through Monthly
The k-NN engine learns each asset's own RSI fingerprint distribution, and the stdev-adjusted bands auto-scale to the volatility of that distribution, so the indicator is truly self-calibrating across assets and timeframes — no manual recalibration required.
🟦 TECHNICAL NOTES
- Pine Script v6
- No repainting — training samples are gated by `barstate.isconfirmed` so the dataset never absorbs unconfirmed live-bar values
- Dataset is hard-capped via FIFO rotation; no unbounded memory growth
- Dashboard renders only on `barstate.islast` — zero historical overhead
- All drawing objects are stateless plots (no label / box / line object pools), so `max_*_count` limits cannot be exceeded
- k-NN distance pass is O(N), sort is O(N log N), both bounded by Max Dataset Size
- Default Max Dataset Size of 500 is tuned to stay within PulseWire's per-bar calculation budget on histories up to ~50,000 bars
- Bias correction uses a single extra accumulator pass during the distance sweep — no performance penalty
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. The k-NN engine learns from historical patterns, but markets do not guarantee that historical patterns will repeat. Always conduct your own analysis and apply proper risk management. Indicator

Artemis Oscillator PROArtemis Oscillator PRO is a momentum oscillator built on a custom Directional Range Momentum (DRM) engine — an original algorithm that measures signed range impulse, not price distance. Unlike RSI or Stochastic, DRM scores the direction and force of range expansion relative to its own history, normalized to 0–100. The result is an oscillator that reacts cleanly to structural momentum shifts without the lag inherent in traditional smoothed-ratio oscillators.
The indicator integrates five analytical layers — oscillator core, volume pressure, momentum state scoring, divergence detection, and KNN machine learning bias — each operating independently and rendered on a single, clean oscillator panel.
🟦 HOW THE CORE ENGINE WORKS
**Directional Range Momentum (DRM)**
Each bar, the engine measures the current highest high and lowest low over the lookback period. It then assigns a signed range force:
- If the range is expanding to the upside → positive force (full range span)
- If the range is expanding to the downside → negative force (negative full span)
- If range is stable → raw tick delta (neutral)
This signed force is split into two smoothed components:
- `sUp` — smoothed directed force (can be positive or negative)
- `sAbs` — smoothed absolute force (always positive, represents total activity)
The oscillator value is: `(sUp / sAbs) * 50 + 50`
This produces a 0–100 scale where 50 is neutral, above 50 means upward range pressure dominates, and below 50 means downward range pressure dominates. Division by the absolute component normalizes the output regardless of asset volatility.
**Signal Line**
A second independently configurable smoothing pass over the oscillator value. Crossovers between the oscillator and signal line mark momentum regime changes.
**Smoothing Methods**
Four algorithms available for both oscillator and signal line:
- RMA — Wilder's Moving Average (default, most stable, minimal overreaction)
- EMA — Exponential, faster response
- SMA — Simple, equal weight across all bars
- TMA — Double-smoothed SMA, maximum smoothness
🟦 VOLUME PRESSURE
**Dual MFI Architecture**
Volume Pressure uses two Money Flow Index calculations simultaneously:
- Fast MFI: `Period / 1.33` (shorter window, more reactive)
- Slow MFI: `Period * 1.33` (longer window, structural bias)
These are blended 50/50, then passed through a power-curve compression function (`x^0.75`) that reduces extreme readings while preserving directional accuracy. The result is mapped to 0–100 and rendered as fill areas anchored at the midline:
- Above 50: Inflow fill (buying pressure dominates)
- Below 50: Outflow fill (selling pressure dominates)
The MFI price source is configurable: HLC3 (default), Close, HL2, or OHLC4.
🟦 MOMENTUM STATE SCORING
A composite score from 0 to 3 is calculated each bar using three independent binary conditions:
| Condition | +1 Point |
|---|---|
| Oscillator > Signal Line | Momentum direction |
| Oscillator > 50 | Oscillator position |
| Volume Pressure > 50 | Volume confirmation |
**Score interpretation:**
- Score 3 → Full overbought state fill (all three conditions bull-aligned)
- Score 2 → Partial overbought fill (two conditions)
- Score 1 → Partial oversold fill (one condition)
- Score 0 → Full oversold state fill (all three conditions bear-aligned)
Fills render inside the oscillator panel at adjustable opacity. The scoring is continuous — it updates every bar without look-ahead.
🟦 MOMENTUM EXHAUSTION
Exhaustion labels (`✦ OB` / `✦ OS`) fire when the oscillator is inside a zone but weakening consecutively. Specifically:
✦ OB — oscillator is at or above the OB threshold AND has closed lower for N consecutive bars
✦ OS — oscillator is at or below the OS threshold AND has closed higher for N consecutive bars
N (Confirmation Bars) is configurable from 1 to 4. Higher values produce fewer but more structurally confirmed signals. This is not a predictive signal — it marks the process of momentum fading, not the reversal itself.
🟦 DIVERGENCE DETECTION
Pivots are calculated using `ta.pivothigh` and `ta.pivotlow` with an arm of `Period / 2`. All divergence results appear `Period / 2` bars late — this is standard Pine Script pivot behavior, not a bug.
**Four divergence types:**
| Type | Price | Oscillator | Signal |
|---|---|---|---|
| Regular Bull (D▲) | Lower Low | Higher Low | Potential reversal up |
| Regular Bear (D▼) | Higher High | Lower High | Potential reversal down |
| Hidden Bull (H▲) | Higher Low | Lower Low | Uptrend continuation |
| Hidden Bear (H▼) | Lower High | Higher High | Downtrend continuation |
Regular divergence uses solid lines. Hidden divergence uses dashed lines. Labels use clean symbol-only style with no background box.
**Smart Divergence Filter (AI)**
An optional pre-filter that rejects low-quality divergence signals before they render. Three conditions must pass (each configurable independently):
1. Minimum oscillator swing between the two pivot points (default: 5 units)
2. Minimum price swing as a percentage of recent range (default: 0.3%)
3. Volume Pressure confirmation — VP must agree with divergence direction
When the filter is OFF, all detected divergences render. When ON, only structurally significant divergences pass. The filter applies identically to both chart rendering and alert conditions — no mismatch between visual and alert signals.
🟦 KNN BIAS PANEL
**What KNN Does**
K-Nearest Neighbors (KNN) is a non-parametric machine learning algorithm. Each bar, the indicator stores the current market state as a point in 3-dimensional feature space. When making a prediction, it finds the K historically most similar states and votes on the likely outcome.
**The Three Features**
| Feature | Calculation | Signal |
|---|---|---|
| O (Oscillator) | `oscVal / 100` | O+ = above 50 (bull zone) |
| V (Volume) | `vpMid / 100` | V+ = above 50 (inflow) |
| S (Signal gap) | `(oscVal - sigVal + 100) / 200` | S+ = oscillator above trigger |
**ATR-Normalized Output Label**
The classification target uses ATR-adjusted thresholds rather than a raw `close > close ` comparison. A bar is labeled bullish only if close moved more than `0.1 × ATR(14)` upward, bearish if it moved more than `0.1 × ATR(14)` downward, otherwise the previous label is carried forward. This eliminates noise-driven label flips caused by micro price movements.
**Distance Calculation**
Euclidean distance in 3D feature space:
```
d = sqrt((kf1_now - kf1_hist)^2 + (kf2_now - kf2_hist)^2 + (kf3_now - kf3_hist)^2)
```
The K nearest historical points vote. If majority voted bullish → BULL bias. Result thresholds: ≥60% bull vote = BULL, ≤40% = BEAR, between = NEUTRAL.
**Panel Display**
| Row | Left | Right |
|---|---|---|
| Header | KNN AI | Direction (▲ BULL / ▼ BEAR / ◈ NEUTRAL) |
| Row 1 | Confidence | Percentage (0–100%) |
| Row 2 | Progress bar (█░) | Bars in training memory |
| Row 3 | O± V± S± feature states | K= neighbor count |
Panel renders with monospace font, theme-aware backgrounds, and a single accent color derived from the active theme.
🟦 COLOR THEMES
Eight complete palettes, each defining five independently tuned colors (bull, bear, signal, VP buy, VP sell):
| Theme | Character | Bull Color | Bear Color |
|---|---|---|---|
| Aurora | Dark mode, high contrast | Cyan | Violet |
| Ember | Dark mode, warm | Amber | Steel Blue |
| Cyber | Dark mode, neon | Lime Green | Crimson |
| Arctic | Dark mode, cool | Sky Blue | Soft Purple |
| Solar | Dark mode, warm gold | Yellow Gold | Salmon |
| Obsidian | Dark mode, pro trader | Emerald | Scarlet |
| Classic | Light mode | Navy Blue | Crimson |
| Mono | Light mode, minimal | Near Black | Gray |
All five color roles (bull/bear/signal/VP buy/VP sell) change simultaneously when the theme changes. No per-color manual adjustment required.
🟦 ALERT SYSTEM
Twelve alert conditions, all using `alert.freq_once_per_bar`:
| Alert | Condition |
|---|---|
| Bullish Cross | Oscillator crosses above signal while below midline |
| Bearish Cross | Oscillator crosses below signal while above midline |
| Exit Oversold | Oscillator crosses above OS level |
| Exit Overbought | Oscillator crosses below OB level |
| Regular Bull Divergence | Price LL + oscillator HL (+ Smart Filter if enabled) |
| Regular Bear Divergence | Price HH + oscillator LH (+ Smart Filter if enabled) |
| Hidden Bull Divergence | Price HL + oscillator LL (+ Smart Filter if enabled) |
| Hidden Bear Divergence | Price LH + oscillator HH (+ Smart Filter if enabled) |
| VP Inflow | Volume Pressure crosses above 50 |
| VP Outflow | Volume Pressure crosses below 50 |
| Exhaustion OB | Oscillator weakening N bars while above OB level |
| Exhaustion OS | Oscillator strengthening N bars while below OS level |
Divergence alerts respect the Smart Divergence Filter — if the filter is ON and a divergence is rejected visually, the alert will also not fire.
🟦 SETTINGS REFERENCE
**Oscillator**
- Period — DRM lookback window. Also controls divergence pivot arm (Period / 2). Default: 14
- Smoothing — EMA / SMA / RMA / TMA. Default: RMA
- Source — Price input for the range engine. Default: Close
- Adaptive Color — Oscillator line shifts between bull/bear colors based on position. Default: ON
**Signal Line**
- Period — Signal smoothing window. Default: 7
- Smoothing — EMA / SMA / RMA / TMA. Default: EMA
- Show Cross Dots — Dot on signal line at each crossover. Default: ON
**Zones & Fills**
- Overbought level — Default: 80
- Oversold level — Default: 20
- Zone fill opacity — Configurable per zone. Default: 20
**Volume Pressure**
- Show Volume Pressure — Toggle. Default: ON
- MFI Source — HLC3 / Close / HL2 / OHLC4. Default: HLC3
- Opacity — Default: 18
**Momentum State**
- Show Momentum State — Toggle. Default: ON
- OB Opacity / OS Opacity — Default: 35 each
**Divergence**
- Regular / Hidden — Independent toggles and opacity controls
- Label Size — Tiny / Small / Normal / Large. Default: Tiny
- Smart Divergence Filter — ON/OFF. Default: OFF
- Min Oscillator Swing — Default: 5.0
- Min Price Swing % — Default: 0.3%
- Require VP Confirmation — Default: ON
**Momentum Exhaustion**
- Show Labels — Toggle. Default: ON
- Confirmation Bars — 1 to 4. Default: 4
**KNN Bias**
- Show KNN Panel — Toggle. Default: ON
- Neighbors (K) — 3 to 10. Default: 5
- Training Window — 50 to 300 bars. Default: 100
- Panel Position — Four corners. Default: Bottom Right
- Panel Text Size — Tiny / Small / Normal / Large. Default: Small
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in PulseWire Pine Script v6.
- Crypto: Spot, futures, perpetual contracts
- Forex: All pairs
- Equities: Stocks, ETFs, indices
- Commodities: Metals, energy, agriculture
- Timeframes: 1m through Monthly
The DRM engine normalizes by its own absolute smoothed component, making it volatility-agnostic across assets and timeframes without manual recalibration.
🟦 TECHNICAL NOTES
- Pine Script v6
- max_lines_count = 500`, `max_labels_count = 500` (divergence drawings)
- No repainting — all values calculated on bar close. Pivot-based divergence results appear `Period / 2` bars late by design
- KNN training updates only after `bar_index > 1` to avoid cold-start artifacts
- Volume Pressure fill anchors use `color = na` (not `display.none`) to maintain Pine v6 `fill()` compatibility
- OB/OS state fills render outside the 0–100 oscillator range (104–110 and −10 to −4) to avoid visual overlap
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. Always conduct your own analysis and apply proper risk management.
Indicator

AG Pro Williams %R Exhaustion Map [AGPro Series]AG Pro Williams %R Exhaustion Map
Overview / What it does
AG Pro Williams %R Exhaustion Map is a bounded-oscillator reaction map built to study exhaustion behavior around the extreme ends of Williams %R. Instead of treating Williams %R as a simple overbought/oversold trigger, this script maps whether an extreme reading is only being touched briefly, held with persistence, beginning to release, failing to release, or unwinding with more structure. The goal is to organize extreme-zone behavior into readable states rather than reduce the tool to a basic reversal shortcut.
The script is designed for traders who want to understand when an extreme condition is still being sustained and when that same condition may be starting to lose efficiency. In practice, that means the script focuses less on isolated crossings and more on the sequence around them: entry into an extreme zone, time spent there, the first release attempt, the possibility of a failed release, and the confirmation of an exhaustion unwind. This sequence-based framing is what gives the tool its map identity.
Within the AG Pro series, this script is intentionally separate from tools that revolve around trend confirmation, centerline balance, divergence, or generic momentum shifts. It is also intentionally separate from the series' Stochastic-based exhaustion work. Stochastic can be useful for reading swing rhythm and rotational turns, while this Williams %R version is centered more tightly on bounded extreme persistence and release behavior. In other words, this script is not presented as an alternative skin for another oscillator. It is a different framework for reading how price behaves when an oscillator remains pinned near an edge and then attempts to escape that condition.
Unique Edge
The unique edge of this script is not that it plots Williams %R, but that it classifies the life cycle of an extreme reading. The script distinguishes between stretch, locked conditions, release attempts, failed releases, and exhaustion unwinds. That structure helps separate three situations that are often mixed together in standard oscillator use:
1) an extreme reading that is still being sustained,
2) an extreme reading that has started to weaken but may still fail, and
3) an extreme reading that is releasing with enough follow-through to qualify as an exhaustion unwind.
This matters because many standard oscillator workflows treat every exit from an extreme zone as if it carried the same informational value. This script does not. It places more emphasis on persistence, release quality, and post-release follow-through, which can help users avoid treating every early reversal attempt as equivalent.
Methodology
The script begins with Williams %R and user-defined extreme thresholds. From there, it evaluates how long the oscillator remains in the upper or lower extreme zone and how deeply it is embedded in that zone. This forms the basis of the lock-strength logic. A fast touch into an extreme area and an extended embedded condition are therefore not interpreted in the same way.
Once an extreme condition has persisted long enough, the script begins monitoring for a release. A release is not defined as any random movement away from the boundary. It requires the prior extreme condition to have had sufficient persistence and then looks for a buffered move away from the threshold. This helps reduce noise from trivial fluctuations around the extreme lines.
After a release is detected, the script continues to track what happens next. If the oscillator quickly slips back into the same extreme region, the move can be classified as a failed release. If the move continues far enough away from the release anchor within the confirmation window, it can be classified as an exhaustion unwind. This post-release tracking is a central part of the script's design because it helps distinguish between temporary relief and more meaningful exhaustion release.
The panel summarizes this process using state, side, lock strength, and release quality. Lock strength is intended to reflect how established the prior extreme condition was. Release quality is intended to reflect the quality of the release sequence, not forecast what price must do next. These metrics are descriptive and contextual. They are not guarantees.
Signals & Alerts
This script provides event-style labels and alert conditions for the main transitions in the exhaustion sequence. The alerts are deterministic and tied to explicit script conditions rather than discretionary interpretation.
Main event types:
- Bullish release detected
- Bearish release detected
- Bullish release failed
- Bearish release failed
- Bull exhaustion unwind confirmed
- Bear exhaustion unwind confirmed
How to interpret them:
- A release event marks the first qualified move away from a persistent extreme condition.
- A failed release marks a release attempt that reverted back into the prior extreme condition too quickly.
- An exhaustion unwind confirmation marks a release that traveled far enough from its anchor within the configured window to qualify as a more established unwind sequence.
These events are intended to help structure chart reading. They are not standalone trade instructions, and they are not framed as guaranteed reversal signals.
Key Inputs
Williams %R Length
Controls the oscillator lookback period.
Upper Extreme / Lower Extreme
Define the zones used to classify upper and lower exhaustion behavior.
Lock Bars
Controls how much persistence is required before an extreme condition is treated as locked rather than only stretched.
Release Buffer
Adds distance beyond the raw threshold so the script does not treat every minor edge fluctuation as a release.
Confirm Distance / Confirm Window
Control how far and how quickly a release must extend to qualify as an exhaustion unwind.
Fail Window
Controls how quickly a release can revert back into the extreme zone and still be classified as a failed release.
Event Memory Bars
Controls how long the release state is remembered on the chart.
Visual Settings
Allow users to control event labels, minimum spacing between labels, background tint, and optional price-bar coloring.
Panel Settings
Allow users to control panel visibility, placement, font size, and theme.
How this differs from related AG Pro scripts
This script should not be confused with the series' other momentum or exhaustion tools.
Compared with Stochastic-based exhaustion work in the AG Pro series, this script is less about oscillator rhythm and more about the persistence and release structure of a bounded extreme condition. The emphasis here is on whether Williams %R remains pinned, whether the first escape attempt fails, and whether the unwind becomes established.
Compared with RSI-, CCI-, or MFI-oriented workflows, this script is not a centerline trend model, not a divergence engine, and not a money-flow proxy. Its purpose is narrower and more specific: to map the state transition of extreme Williams %R conditions.
Compared with broader trend or regime tools in the AG Pro series, this script is not trying to classify the full market environment by itself. It is better understood as a focused reaction map that can be used alongside a user's own structure, trend, or risk framework.
Limitations & Transparency
This is an indicator, not a strategy. It does not place orders, it does not calculate performance statistics, and it does not claim to predict future price direction. It visualizes oscillator-state transitions derived from Williams %R and user-defined thresholds.
Like all bounded oscillators, Williams %R can remain in extreme territory for extended periods during strong directional conditions. For that reason, an extreme reading should not automatically be interpreted as a reversal condition. This script attempts to improve that interpretation by separating stretch, lock, release, failed release, and unwind behavior, but it does not eliminate false positives.
Results can vary meaningfully with symbol, timeframe, volatility regime, and input configuration. Traders should expect the script to behave differently on very quiet markets, strongly trending markets, and highly reactive instruments. Label frequency and state persistence can also change materially when thresholds and confirmation settings are adjusted.
This tool is intended to support chart organization and decision framing. It should be used with the user's own market structure analysis, execution model, and risk management process.
Risk Disclosure
This script is provided for educational and analytical purposes only. It is not financial advice, not a solicitation, and not a promise of results. Trading and investing involve risk, including the risk of loss. No indicator can remove uncertainty from markets, and no exhaustion signal guarantees reversal, continuation, or trade success.
Users should validate any workflow with their own testing, judgment, and risk controls before using it in live decision-making.
Indicator

Inertial RSI [LuxAlgo]The Inertial RSI indicator introduces a novel approach to momentum smoothing by implementing "Forced Persistence," a technique that achieves stability at the mathematical source rather than through traditional lagging filters. By dynamically optimizing the RSI lookback period on every bar to minimize the variation between consecutive values, the tool effectively creates an inertial effect that resists erratic market noise and "sawtooth" fluctuations, providing a significant advantage over standard oscillators by maintaining a high degree of smoothness and trend coherence without the heavy group delay typically introduced by long-period moving averages.
🔶 USAGE
The indicator is used similarly to a standard Relative Strength Index (RSI) but with significantly reduced noise and more stable transitions. It helps traders identify momentum and overbought/oversold conditions while maintaining a more consistent trajectory, making it easier to interpret the underlying market trend without being shaken out by minor price jitters.
🔹 Forced Persistence
Traditional oscillators achieve smoothness by applying lagging filters (like moving averages) to a fixed-length calculation. The Inertial RSI introduces the concept of "Forced Persistence," where smoothing is achieved by selecting the input data dynamically. By selecting the lookback length that results in the smallest change from the previous bar, the oscillator "forces" itself to remain stable. This allows the indicator to stay at extreme levels during strong trends or transition smoothly during reversals without the typical noise found in fixed-length oscillators.
🔹 Interpretation
Inertial RSI (Solid): Represents the primary smoothed RSI value. It changes color based on whether it is above or below the 50 centerline (Bullish/Bearish).
Signal Line (Dotted): A secondary signal line calculated as a simple moving average of the RSI line, used to identify potential local crossovers or momentum shifts.
Zones: The area between the RSI line and the 50 level is filled with a gradient to highlight the strength and direction of the current momentum.
🔶 DETAILS
The core logic of the script is an optimization loop that runs on every bar. Instead of using one fixed value for N (the lookback period), the algorithm evaluates every possible integer length within the user-defined range (from Minimum Length to Maximum Length).
For each potential length, the script calculates a raw RSI value using an RMA-based approach (Wilder's Moving Average) for consistent bar-to-bar logic. It then measures the absolute difference between that candidate value and the final output from the previous bar. The algorithm "hunts" for the specific length that minimizes this difference:
Best RSI = min(|Current Candidate(N) - Previous Final RSI|)
By selecting the value that is most similar to the previous one, the indicator effectively filters out market noise by choosing a lookback window that "agrees" with the current trend's inertia. This methodology allows the oscillator to be responsive to major price shifts while ignoring minor fluctuations that do not significantly alter the internal relative strength calculation.
🔶 SETTINGS
🔹 Settings
Minimum Length: The shortest lookback period the algorithm can consider for the optimization loop.
Maximum Length: The longest lookback period the algorithm can consider. A wider range between min/max allows for more "inertia" but increases computational intensity.
RSI Smoothing: The length of the SMA used to provide a final aesthetic smoothing to the inertial RSI value.
Signal Line Length: The length of the SMA used to create the signal line from the smoothed RSI.
🔹 Visuals
Show Gradient Fill: Enables or disables the gradient fill between the RSI line and the 50 centerline.
Bullish Color: Defines the color of the RSI line and the upper gradient fill when the value is above 50.
Bearish Color: Defines the color of the RSI line and the lower gradient fill when the value is below 50.
Indicator

Volume Acceptance Zones [BigBeluga]Volume Acceptance Zones is a market structure tool designed to identify areas of price acceptance and statistically stretched extremes. By modeling market activity as a continuous distribution, the indicator highlights where price is actively accepted versus where it behaves as a statistical outlier.
The goal is not prediction, but context — separating balanced price behavior from structurally stretched conditions.
🔵 CONCEPTS
The indicator calculates a Volume-Weighted Balance Price , representing the center of gravity for participation over a selected range.
Price dispersion around this balance point is measured using volume-weighted standard deviation .
The area within ±1 standard deviation forms the Acceptance Zone , where the majority of activity is concentrated.
Prices beyond this zone are treated as outliers , where participation thins and market reactions become more likely.
These zones do NOT represent guaranteed probabilities — they describe participation density and behavioral extremes.
🔵 STANDARD DEVIATION, BELL CURVE & OUTLIERS
At the core of this indicator lies the concept of standard deviation , which describes how price activity clusters around a central value.
When activity is observed over time, it tends to form a distribution where:
Most activity concentrates near a central balance level.
Fewer observations occur as price moves further away from that balance.
This behavior can be visualized conceptually as a bell-shaped distribution — a practical way to describe market participation density.
Prices that move beyond the Acceptance Zone deviate meaningfully from the balance of participation.
These areas are treated as outliers , where price is statistically stretched relative to recent market behavior.
Outliers do not imply immediate reversals — they signal that price is operating in a low-acceptance environment.
Market responses in these zones often include rejection, consolidation, or strong continuation if acceptance builds.
🔵 NEW: INTEGRATED FREQUENCY PROFILE
While the zones are calculated using volume-weighted math, the visual profile has been updated to a Frequency-Based Distribution . This transition allows you to see "Time at Price" rather than just raw volume.
Frequency Distribution: The profile counts the number of bars (occurrences) spent at each price bin. This highlights levels of high interest where the market finds it easy to trade, effectively acting as a Time-Price Opportunity (TPO) proxy.
Time-Based Sentiment: Each bin is split into Bull/Bear frequency. This shows which side was in control during the time spent at that specific level, identifying where buyers or sellers were more persistent.
Filtering Noise: By using frequency instead of raw volume, the profile avoids being skewed by single high-volume spikes, focusing instead on where the market established a sustained presence.
🔵 FEATURES
Acceptance Zone (±1σ)
Highlights the primary balance area where price is most actively accepted and rotational behavior is common.
Extreme Zones (±2σ)
Marks statistically stretched prices where acceptance weakens and reactions or trend continuation may occur.
Volume-Weighted Balance Line
Acts as a structural fair-value reference similar to an anchored VWAP.
Outlier Detection
Price closing beyond the acceptance zone is flagged as an outlier, helping identify exhaustion or breakout conditions.
Distribution Labels
Displays how price activity is distributed between acceptance and extreme zones, reinforcing the concept visually.
Flexible Anchoring
Calculations can be based on a fixed lookback or the visible chart range.
🔵 HOW TO USE
Treat the Acceptance Zone as a balance area where price is fairly valued and mean-reversion is common.
Observe how price behaves in Extreme Zones — rejection may signal reversion, while sustained acceptance may indicate trend continuation.
Frequency Nodes: Use the Frequency Profile to identify where the market is "stalling." High frequency nodes often act as magnets for price, while low frequency gaps (low time spent) often lead to fast price movement.
Use outlier signals in combination with trend bias, liquidity levels, or momentum tools.
🔵 CONCLUSION
Volume Acceptance Zones reframes market analysis around participation density. By distinguishing accepted price behavior from statistical outliers and providing a frequency-based view of time-at-price, the indicator helps traders understand when the market is balanced—and when it is structurally stretched. Indicator

Chandelier Exit Oscillator + State MappingAt its core, this script is built on a Chandelier Exit-style ATR stop-and-flip engine. The difference is that instead of leaving that framework only in price space, this indicator converts the active side and the opposite-side extension into a normalized oscillator. In other words, this takes the same Chandelier Exit structure that can define trend state and stretch on a chart, then re-expresses that structure in a separate pane so it can be read in a different way. Rather than only asking where price is relative to a trailing stop, this script asks where price is progressing inside the current active-to-extension range and how that progression is behaving.
That is what makes this more than a standard Chandelier Exit view. It does not just plot a stop and a flip. It takes the current main multiplier structure, builds a directional channel from the active side to the opposite-side extension, and maps that channel into oscillator space. That creates a normalized way to read state, stretch, and internal zone behavior across both bullish and bearish conditions.
The script includes two mapping modes.
1) Geometry mode preserves the channel relationship more literally:
active level = -100
midpoint = 0
extension = +100
2) State-Weighted mode keeps the same Chandelier framework but biases the oscillator by active direction, so bullish regimes tend to live above 0 and bearish regimes tend to live below 0. In that mode, 0 behaves less like a simple midpoint and more like a directional boundary.
From there, the script adds three secondary Chandelier Exit multipliers, which by default are 2.5, 5.0, and 7.5. These are not separate indicators bolted onto the script for the sake of adding features. They are additional Chandelier Exit branches derived from the same underlying ATR stop-and-flip logic. Their active levels are remapped into the same oscillator space so they can act as internal zone references inside the broader main channel.
That matters because not every move waits until a full extension is reached before reacting. Sometimes price begins to stall, react, or accelerate from a smaller internal multiplier zone first. These secondary CE layers help organize that behavior into a readable internal structure instead of forcing everything to be judged only from the full outer stretch.
The script also gives multiple ways to view the same oscillator state. You can keep it simple with the main oscillator line, or display histogram columns, synthetic oscillator candles, guide rails, and extreme zones. There is also an optional price-overlay candle mode, which colors the chart candles using the same oscillator color engine so the chart view and pane view remain visually connected.
To help with context, the script also includes:
➖an HTF oscillator reference line
➖an oscillator volume-weighted average
➖adaptive fast/slow crossover lines
➖a standalone SMA 20/50 crossover engine
➖a current-state table
➖optional alerts for zero-line crosses and adaptive fast/slow crosses
These features are there to help interpret the same core Chandelier Exit structure in oscillator form. They are not separate systems with separate foundations. The main idea stays consistent throughout the script: use a CE-style ATR framework as the base, then translate it into a pane-based state and extension model that is easier to compare, normalize, and monitor over time.
A practical way to read it:
➡️ In a bullish state, the active main CE side becomes the lower anchor and the opposite-side extension becomes the upper anchor. The oscillator shows how far price is progressing through that structure.
➡️ In a bearish state, the structure flips. The active main CE side becomes the upper anchor and the opposite-side extension becomes the lower anchor.
➡️ The secondary CE multiplier zones help show where internal support/resistance-style reaction areas may begin to matter before price reaches the full outer stretch.
➡️ In Geometry mode, 0 is the midpoint of the mapped channel. In State-Weighted mode, 0 behaves more like a directional dividing line between bullish and bearish conditions.
One of the main reasons I made this was to create a true companion to my overlay script, Chandelier Exit Reaction Zones + Fib Levels. That script keeps the structure directly on price. This oscillator takes the same general Chandelier Exit framework and expresses it in normalized pane form. Used together, the overlay script helps show where the structure sits on the chart, while this oscillator helps show how price is progressing through that same structure, how internal zones are behaving, and whether the move still looks orderly inside the current channel. They work well as a package because one gives the price-space view and the other gives the pane-space view of the same broader idea.
This is not meant to predict reversals by itself, and it is not intended to be treated as a standalone signal machine. The way I use it is more practical:
➖to frame where price is stretched
➖to judge whether price is still progressing through the current CE channel or starting to stall
➖to see whether the move is only testing an internal multiplier zone or approaching a full extension
➖to compare current oscillator behavior against HTF context and crossover behavior
Bar Replay is especially useful here. Watching the script one bar at a time makes it much easier to see how the CE state flips, how the oscillator remaps around those flips, and when the internal multiplier zones begin to matter before a larger stretch is completed.
Like the companion overlay version, this works best with confluence. Volume, RSI, structure, trend context, support/resistance, and broader market conditions can all help decide whether an extended move is more likely to continue, react, or fully reverse. The value of this script is not that it replaces those tools. The value is that it gives the Chandelier Exit framework a second, more normalized expression that can make state, extension, and internal zone behavior easier to read.
A few examples showing bullish and bearish charts:
Indicator

3D Opportunity Cone [LuxAlgo]The 3D Opportunity Cone indicator is a multi-dimensional visualization tool that maps market conditions into a 3D geometric space to identify high-value, low-risk entry points. By synthesizing price action, volatility, and volume into a single spatial model, it allows traders to visualize the "distance" between current market states and optimal buying conditions.
🔶 USAGE
The indicator projects a 3D cone onto the right side of the chart, representing a theoretical "Opportunity Space." A historical trail of dots moves through this space, showing how the market's internal mechanics have evolved over time.
🔹 The 3D Coordinate System
The position of the market "point" within the cone is determined by three distinct factors:
Height (Value Factor): Derived from the Stochastic oscillator. Higher positions in the cone represent oversold (value) conditions, while lower positions represent overbought states.
Radius (Risk Factor): Derived from the Average True Range (ATR). Points closer to the center of the cone represent lower volatility risk, while points pushed toward the outer edges indicate high-volatility environments.
Angle (Conviction Factor): Derived from Normalized Volume. The rotation around the central axis indicates the level of market participation and conviction behind the current price movement.
🔹 Interpreting the Zones
The "Buy Zone" is located at the apex (top) of the cone. An ideal opportunity occurs when the market point is high (Value), centered (Low Risk), and supported by conviction. Conversely, the "Risk Zone" at the base of the cone represents overbought or high-volatility conditions where caution is required.
🔶 DETAILS
The script uses a custom projection engine to convert 3D coordinates (X, Y, Z) into 2D chart space. The "Opportunity Space" is anchored to a Simple Moving Average (SMA) to provide a localized context for the visualization.
The historical trail provides a temporal dimension, allowing users to see if the market is spiraling toward a value zone or drifting away into a high-risk state. The trail colors fade from red (High Risk/Overbought) to green (High Value/Oversold) to provide an immediate visual cue of market health.
🔶 SETTINGS
🔹 Cone Settings
Evaluation Lookback: The period used for calculating the Stochastic, ATR, and Volume normalization.
Cone Scale: Adjusts the visual size of the 3D cone on the chart.
X Offset (Bars): Determines how many bars to the right of the current price the cone is rendered.
3D Tilt: Adjusts the perspective/inclination of the 3D projection.
🔹 Trail & Colors
Highlight Color: The color of the current market point and its projection lines.
Cone Fill Color: The background color of the cone's surface.
Trail Length: The number of historical periods to display within the 3D space.
Indicator
