Vortex Signals [Gabremoku]Vortex Signals is a reworked version of the classic Vortex Indicator designed to make directional shifts easier to read and less reactive than raw crossover-based interpretations.
Instead of treating every VI+ / VI- crossover as a direct trading signal, this script uses the Vortex lines as a regime detector first, then looks for signal quality through spread expansion and re-activation after a pullback. The goal is to reduce the noisy sequence of repeated entries and exits that often appears when the standard Vortex is used on its own.
What the script does:
Plots the classic Vortex components, VI+ and VI-.
Fills the space between the two lines with a dynamic gradient that reflects which side is dominant and how strong the current spread is.
Detects bullish and bearish dominance regimes.
Uses a signal engine based on regime change, spread expansion, and first valid continuation after weakening.
Prints compact chart markers for LONG, SHORT, and CLOSE events.
Includes a dashboard to show current state, sequence status, setup condition, spread, slope, and directional bias.
How it works:
Regime: the script first determines whether VI+ is above VI- or VI- is above VI+.
Spread: it measures the distance between the two Vortex lines to evaluate whether dominance is meaningful or weak.
Expansion: a regime becomes more relevant when the spread rises above its short baseline and continues widening.
Trigger logic: instead of firing on every crossover, the script waits for either an early valid impulse after regime change or the first useful re-expansion after a pullback inside the same regime.
Why this is different from the classic Vortex:
The built-in Vortex is often read through raw line crossovers.
This script reframes the indicator as a dominance and continuation tool rather than a pure crossover trigger.
The signal engine is designed to capture cleaner transitions and continuation phases while avoiding part of the back-and-forth noise that often occurs in choppy conditions.
How to use it:
In Long mode, focus on bullish dominance and the appearance of a LONG marker after spread expansion or re-expansion.
In Short mode, focus on bearish dominance and the appearance of a SHORT marker after the same logic on the opposite side.
CLOSE markers appear when the opposite Vortex condition breaks the active sequence.
Suggested use:
This script is generally better suited to trending or directional environments than to highly compressed sideways markets.
In my testing and chart observation, the signals can appear cleaner on the 1H timeframe, where short-term noise is often reduced compared with very low timeframes, but users should still adapt settings to the instrument and market structure they trade.
Notes:
This indicator is not predictive and does not guarantee profitable signals.
It should be used as a decision-support tool together with price structure, risk management, and broader market context.
As with any directional model, false signals can still occur during whipsaw or transition phases. Indicateur

Path Signature Regime Engine# Path Signature Regime Engine (PSRE)
**What it does**
Path Signature Regime Engine reads the *geometry* of recent price action and
labels the current market state as **Trending up**, **Trending down**,
**Range / chop**, or **Turning (reversion)**. Instead of smoothing price with a
moving average, it measures the shape of the path itself using the low-order
**path signature** — a description of a curve by its iterated integrals from
rough-path theory.
Two terms do the work:
- **Level 1 — drift:** the net displacement of the path over a lookback window.
- **Level 2 — Lévy area:** the signed area the path sweeps relative to its own
chord. A path that keeps curling the same way (a trend) accumulates area; a
path that oscillates back and forth (a range) cancels it out. The sign and
size of this area is the core regime signal.
Both terms are turned into 0–100 percentiles over a rolling window, so the read
adapts to each symbol and timeframe automatically.
**How it works (one method, three views — not a mashup)**
This is deliberately **not** a bundle of independent indicators stitched
together. Every component calls the same internal routine that computes the
drift + Lévy-area read. The "extra" layers are that single computation pointed
at different data:
- **Chart timeframe** — the primary regime read.
- **Multi-timeframe confluence** — the *identical* read evaluated on two higher
timeframes (default 1H and 4H). It is reported as **agreement** ("aligned
2/3"), explicitly *not* as independent confirmation, because nested
timeframes share information. "Aligned" requires at least two of the three
views to agree with the chart.
- **Cross-asset comparison** — the same iterated-integral area computed between
*two return streams* (your symbol and a benchmark) instead of price-vs-time.
This yields a geometric lead/lag read plus a relative-strength sign.
Because the higher-timeframe and cross-asset views are projections of one
geometric primitive rather than separate tools, they reinforce a single
conclusion: what is the path doing, and does that hold up when seen from a
slower clock or against a related instrument.
**The honesty layer (why this differs from a typical regime indicator)**
Markets are noisy, so the engine carries its own reality checks rather than
asking you to take the colours on faith:
- **In-sample base rates** — for each regime it tracks, on the history loaded
on your chart, how often price actually continued over a chosen horizon, with
sample counts shown.
- **"Aligned vs not"** — a side-by-side that can reveal the multi-timeframe
layer adding *nothing* on a given instrument (if the two numbers are equal,
alignment isn't helping — and the panel will tell you so).
- **Transition log** — a table of recent regime flips with their realised
forward return (in ATR units) and a ✓/✗ result. With one toggle it also
emits `log:*` series so you can right-click → *Export chart data* and study
the full transition history offline.
These are descriptive statistics on past data, not predictions.
**How to use it**
1. Add it to any chart. It reads the chart's own symbol, so it works on any
market — equities, futures, FX, crypto, indices.
2. Defaults are tuned for **NIFTY** (benchmark `NSE:BANKNIFTY`, same trading
session). For any other asset, open settings group **4 · Cross-asset
comparison** and set a benchmark that trades in the *same hours* as your
instrument, and adjust the two higher timeframes in group **3** relative to
your working timeframe.
3. Read the panel top-down: regime → strength → bias → path quality →
timeframe agreement → relative strength → flow tilt → base rates.
4. Treat the output as **context**, not a trade trigger. The base-rate rows are
there so you can judge, per instrument and timeframe, whether the read has
any historical edge before relying on it.
5. Optional alerts fire on a new reversion setup and on any regime change.
**Inputs are organised in workflow order:** Data & source, Signature engine,
Multi-timeframe confluence, Cross-asset comparison, Regime base-rate study,
Transition log, Appearance. The panel theme adapts to your chart background
luminance for readability on light or dark themes.
**Concept credits**
The mathematics is not mine; the implementation and the regime/honesty
framework are. Path signatures and the Lévy-area interpretation come from the
rough-path and signature-method literature:
- K.-T. Chen — iterated integrals (1957).
- T. Lyons — rough-path theory and the path signature (1998).
- I. Chevyrev & A. Kormilitzin — *A Primer on the Signature Method in Machine
Learning*.
- J. Morrill, A. Fermanian, P. Kidger & T. Lyons — *A Generalised Signature
Method for Time Series* (the basepoint + time augmentation used here).
Only the interpretable Levels 1–2 are computed directly from cumulative sums.
This is a descriptive geometric read, not a full signature and not a machine-
learning model.
---
## Disclaimer (include at the end of the description)
This script is an educational and analytical tool. It is **not financial
advice**, not a recommendation to buy or sell, and not a signal service. All
statistics it shows (base rates, transition forward returns) are **in-sample**,
computed close-to-close on the history loaded on your chart, with no execution
costs or slippage, and are **not** a backtest and **not** a forecast. Past
behaviour does not guarantee future results. Test thoroughly and trade your own
plan and risk.
Indicateur

Adaptive Divergence Core [JOAT]Adaptive Divergence Core is an open-source Pine Script v6 oscillator that combines HMA-smoothed RSI behavior, adaptive percentile bands, confirmed divergence lines, and regime fills. It is designed to make oscillator extremes relative to the current chart sample instead of relying only on fixed overbought and oversold levels.
The script is useful when standard oscillator thresholds are too rigid. A market can stay strong or weak for long periods. Adaptive Divergence Core recalculates upper and lower fields from recent oscillator distribution, then plots confirmed divergence only after both price and oscillator pivots are confirmed.
Core Concepts
1. HMA-RSI Core
The oscillator blends RSI on raw price, RSI on HMA-smoothed price, and an HMA-smoothed RSI value. It is centered around zero for easier bullish and bearish reading.
hmaSource = ta.hma(src, hmaLen)
rawRsi = ta.rsi(src, rsiLen)
rsiOnHma = ta.rsi(hmaSource, rsiLen)
smoothedRsi = ta.hma(rawRsi, smoothLen)
core = (rsiOnHma * 0.58 + smoothedRsi * 0.42) - 50.0
2. Adaptive Percentile Bands
The upper and lower bands are calculated from rolling percentiles of the oscillator. This lets the bands adapt to the recent distribution of momentum.
upperRaw = ta.percentile_nearest_rank(core, percentileLength, upperPercentile)
lowerRaw = ta.percentile_nearest_rank(core, percentileLength, lowerPercentile)
3. Extreme Fields
Additional 95th and 5th percentile fields help show deeper oscillator stretch zones beyond the primary adaptive bands.
4. Confirmed Divergence Detection
Bearish divergence requires price to form a higher confirmed pivot high while the oscillator forms a lower confirmed pivot high. Bullish divergence requires price to form a lower confirmed pivot low while the oscillator forms a higher confirmed pivot low.
5. Regime Fill
The script fills the oscillator against zero and against its guide line, making positive and negative regimes easy to read without large markers.
Features
HMA-RSI oscillator: Blends raw RSI, RSI on HMA, and smoothed RSI
Adaptive percentile bands: Upper and lower thresholds adjust to recent oscillator behavior
Extreme bands: Additional outer fields for deeper stretch readings
Confirmed divergence lines: Divergences plot only after price and oscillator pivots confirm
Divergence labels: Small S Div and B Div labels are placed near confirmed divergence lines
Divergence line cap: Old lines are deleted to respect object limits
Optional candle tint: Can color chart candles from the oscillator pane setting
Dashboard: Shows core value, bands, divergence counts, and current field
Alerts: Divergence, band entry, and band release conditions
Input Parameters
Core:
Source: Price source
RSI Length: Base RSI period
HMA Price Length: HMA source smoothing
HMA RSI Smooth: Smoothing for the raw RSI component
Adaptive Bands:
Percentile Length: Lookback used for adaptive thresholds
Upper Percentile: Upper adaptive threshold percentile
Lower Percentile: Lower adaptive threshold percentile
Divergence:
Divergence Left Bars / Right Bars: Pivot confirmation settings
Maximum Divergence Lines: Object cap for plotted divergence lines
Divergence Labels: Shows or hides compact divergence labels
Visuals:
Tint Candles: Optional candle tint from the oscillator state
Show Dashboard: Shows or hides the compact top-right pane dashboard
Palette: Selects the local JOAT color preset
How to Use This Indicator
Step 1: Read the Core Relative to Zero
Values above zero show positive oscillator regime. Values below zero show negative oscillator regime.
Step 2: Use Adaptive Bands
When core enters the upper or lower adaptive band, momentum is stretched relative to its recent sample.
Step 3: Evaluate Divergence After Confirmation
Divergence lines are delayed by pivot confirmation. This is intentional and avoids projecting unconfirmed pivots into the past.
Indicator Limitations
Divergences confirm late because pivots need right-side bars
Adaptive bands depend on the selected lookback and can shift over time
Divergence is context, not a complete trade plan
During strong trends, oscillator stretch can persist for many bars
Originality Statement
Adaptive Divergence Core is original in its HMA-RSI blend, rolling percentile threshold system, confirmed pivot divergence logic, and compact dashboard. It uses public Pine v6 functions to build a distinct oscillator workflow.
Disclaimer
This script is provided for educational and informational use only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Oscillator divergences can fail or remain early for extended periods. Always use independent analysis and proper risk management.
-Made with passion by jackofalltrades
Indicateur

Tectonic Regime Protocol [JOAT]Tectonic Regime Protocol
Introduction
Tectonic Regime Protocol is an open-source Pine Script v6 strategy that combines four analytical modules into a single rule-based trading system: a four-state regime classifier, a three-layer trend filter, a six-pillar confluence entry engine, and an adaptive exit module using ATR-based partial take-profit and a regime-adaptive trailing stop.
The strategy is designed for traders who want a fully automated systematic framework to study how regime-gating affects signal quality. Its primary hypothesis is that directional entries made when (1) the market is classified as a trending regime, (2) trend filters across multiple timeframes align, and (3) multiple structural, volume, and momentum inputs agree, produce statistically better outcomes than entries based on any single condition alone.
Strategy Default Properties
Initial capital: $100,000
Order size: 2% of equity per trade
Commission: 0.04% per side
Slippage: 2 ticks
Maximum open positions: 1
These settings represent realistic conditions for a funded discretionary trader using a liquid futures or equity instrument. The 2% equity sizing limits maximum theoretical drawdown from any single trade while providing meaningful position exposure. Commission and slippage values reflect typical institutional-grade execution costs for electronically traded instruments.
Core Concepts
1. Four-State Regime Classifier
The regime module classifies each bar into one of four states using ADX relative to a threshold and the ATR-to-SMA(ATR) ratio: Trend Bull, Trend Bear, Range High-Vol, Range Low-Vol. Only Trend states are eligible for entry. Range classifications suppress all entries regardless of how strong the confluence score is. This is the primary market context filter.
2. Three-Layer Trend Filter
Three independently computed trend conditions must all agree before a long or short entry is considered: close versus VWMA(200) determines whether price is above or below long-term value; the relationship between fast and slow HMA lines determines medium-term momentum direction; and the close versus a 50-period EMA on a higher timeframe provides multi-timeframe context.
3. Six-Pillar Confluence Score
The entry engine scores six market dimensions and requires the composite bull or bear score to exceed 50 of 100 (default, configurable) with a directional lead of at least 8 points above the opposing score. The six pillars are: market structure, OBV slope direction, KAMA position + RSI + WPR composite, swing-low liquidity sweep detection, ATR ratio in productive range, and Fractal Efficiency Ratio above 0.30.
bool longSetup = validRegime and regime == 1 and trendBull
and bull >= confThreshold and (bull - bear) >= confGap
and barstate.isconfirmed
4. Adaptive Exit Module
The exit logic uses partial exits at two take-profit levels. TP1 closes 50% of the position at 1.0× risk distance. TP2 closes the remaining position at 2.0× risk distance. After TP1 is reached, the stop is moved to the entry price (breakeven). The stop before TP1 uses a regime-adaptive ATR trail — the stop multiplier is lower in low-volatility regimes (tighter) and higher in high-volatility regimes (looser). A 30-bar time-based exit closes any remaining position if neither TP nor stop is reached.
5. Non-Repainting Architecture
All entry conditions are evaluated only when barstate.isconfirmed is true. The HTF EMA is requested with lookahead=barmerge.lookahead_off. Pivot-based conditions use confirmed pivot detection with symmetric lookback. No future bar references are used.
Default Settings and Performance Notes
The strategy is published with the default Properties values listed above. Results shown on the publication chart are generated using these exact settings. Commission of 0.04% per side is representative of typical electronic execution on liquid instruments.
Win rate alone does not characterize strategy performance. The strategy is designed around a two-tier partial exit structure targeting positive expectancy (wins × average win greater than losses × average loss) rather than high win rate. The profit factor and average R-multiple are the more relevant metrics for this type of system.
Input Parameters
Regime Module:
ADX Trend Threshold (default: 20)
ATR Ratio High-Vol Threshold (default: 1.2)
Trend Filter:
VWMA Length (default: 200)
Ribbon Fast HMA and Slow HMA lengths
HTF Timeframe for EMA(50) filter (default: 240)
Enable HTF Filter toggle
Confluence Engine:
Min Score (default: 50, range 50–95)
Min Direction Lead (default: 8)
Min FER (default: 0.30)
FER Lookback (default: 14)
Individual pillar weights (Structure, Volume, Momentum, Liquidity, Volatility, FER)
Exit Module:
TP1 RR Multiple (default: 1.0)
TP2 RR Multiple (default: 2.0)
Stop Multiplier for Low / Med / High Volatility Regimes
Max Bars Hold (default: 30)
How to Evaluate This Strategy
Apply it to a liquid instrument with sufficient historical data to generate more than 100 trades. Compare profit factor, Sharpe ratio, average R-multiple, and maximum drawdown — not win rate in isolation. Test it across at least two different instruments or timeframes to assess whether the results reflect genuine structural edge or data-fitting to one specific market.
The strategy is not optimized for any single market. Default parameters are deliberately conservative to avoid overfitting. Users who adjust parameters to improve backtested results should recognize that improvement on historical data does not guarantee improvement on future data.
Strategy Limitations
On lower-timeframe charts with short histories, fewer than 100 trades may result, reducing the statistical reliability of the backtest
The HTF filter uses request.security() with a higher timeframe EMA. In live trading, the HTF value updates when the higher timeframe bar closes, which may differ slightly from live server-side execution
ATR-based stops and targets mean position sizes and outcomes scale with volatility. In abnormally low-volatility environments, commission costs represent a larger proportion of expected gain
The time-based exit at 30 bars may close profitable positions before TP2 is reached in slow-moving markets
Backtested performance on any instrument does not predict future performance. Markets change, and parameters that produced edge historically may not do so in future regimes
Originality Statement
Combining a four-state regime classifier, a three-layer multi-timeframe trend filter, a six-pillar confluence score including Fractal Efficiency Ratio, and a partial-exit adaptive trailing stop system in a single non-repainting open-source strategy is an original integration of methods
The Fractal Efficiency Ratio as a pillar in a multi-factor entry score, and as a required gate condition for entry, is not present in existing open-source Pine Script v6 strategy publications as of this writing
The regime-adaptive stop multiplier — loosening in high-volatility regimes and tightening in low-volatility regimes — is an original stop calibration approach within this strategic framework
The dual entry mode (edge transition OR re-entry when flat with elevated score) increases signal frequency without compromising the fundamental regime and trend filter requirements
Disclaimer
This strategy is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Backtested results are simulated and do not represent real trading. Simulated results have inherent limitations and may not reflect actual trading outcomes due to market impact, execution differences, and changing market conditions. Past backtested performance does not guarantee future results. Trading involves substantial risk of loss. Always conduct independent due diligence and apply proper risk management before using any strategy with real capital. The author accepts no responsibility for trading losses resulting from use of this strategy.
Made with passion by jackofalltrades
Stratégie

Market Regime LT Direction (Long-Term Objective Filter)Overview
The Market Regime LT Direction indicator is a heavy-duty, multi-factor scoring engine designed to identify the macro market regime. Unlike conventional indicators that rely on a single moving average, this script utilizes a sophisticated matrix of several distinct technical factors across different lookback periods to classify the long-term market environment.
To ensure absolute objectivity and eliminate the pitfalls of over-optimization, this indicator features a zero-input design — there are no parameters to tweak, giving you a robust, curve-fitting-immune view of institutional trend direction.
Why You Should Use This Indicator (The Value Proposition)
Traders often fail because they misjudge the macro environment. A system designed for a secular bull market will fail miserably when the macro regime shifts to a structural bear market or an extended sideways distribution.
Immunity to Curve-Fitting: By fixing the core mathematical constants, this indicator provides an unbiased, baseline truth of the market structure across any asset class (Equities, Crypto, Forex, or Commodities).
Multi-Factor Confluence: Instead of guessing based on a single line, it dynamically calculates a mathematical "Total Score" using trend persistence, moving average geometry, linear regression slope, and momentum.
Macro Filter for Portfolio Allocation: It is an excellent tool for swing traders and long-term investors to manage risk, determine position sizing, or implement an overall portfolio "Risk-On / Risk-Off" switch.
How It Works & Underlying Logic
The indicator separates its engine into two primary layers: a Visual Layer and a Scoring Layer .
1. The Visual Layer
The underlying histogram is a slow-moving, high-period MACD calculated on the typical price (hlc3). This smooths out micro-volatility and visualizes structural macro-momentum.
2. The Scoring Layer (Weighted Confluence Matrix)
The color of the histogram bars is dictated by a strict mathematical matrix. Factors are split into two categories and weighted based on macro relevance:
Low Relevance Score (Short-Term Confluence) like 20 EMA slope direction, fast MACD momentum slope changes and price location relative to the 50 EMA.
High Relevance Score (Long-Term Structure) like price location relative to the 200 SMA, 50 EMA location relative to the 200 SMA, recent swing high/low persistence over a 30-bar window and 100-candle Linear Regression slope.
The script combines these metrics into a standardized Total Score ranging between -3.0 and +3.0 .
How to Interpret It for Your Trading
🟩 Lime (Macro Bullish Regime — Score > 1): Complete structural alignment to the upside. Long-term institutional buying is in control. Aggressive Long bias / Risk-On.
🟥 Red (Macro Bearish Regime — Score < -1): Complete structural alignment to the downside. Macro distribution or a structural markdown is underway. Aggressive Short bias / Defensive capital preservation.
🟨 Yellow (Transitional / Sideways Regime): The factors are in conflict, or the macro trend is losing momentum. The market is consolidating or preparing for a regime shift. Neutral stance / Reduce position sizes / Expect choppy price action.
Pro-Tip: Pair this with the Market Regime ST Direction indicator. When the Short-Term indicator aligns with this Long-Term macro engine (e.g., both turning Green), you have a mathematically high-probability environment for trend-following expansions. Indicateur

Market Regime ST Direction (Short-Term Filter)Overview
The Market Regime ST Direction indicator is a streamlined tool designed to identify the short-term market environment, specifically optimized for the Daily Chart . It serves as an über-clean trend and phase filter built to protect your trading strategy from taking unnecessary losses during difficult, choppy market conditions.
The indicator focuses exclusively on market direction , intentionally filtering out volatility noise and secondary market factors.
Why You Should Use This Indicator (The Value Proposition)
It is a fundamental truth in trading: no single strategy works in all market environments . Trend-following systems bleed capital in sideways ranges, while mean-reversion setups get destroyed in strong, runaway trends.
Smart Loss Filtering : This indicator helps you decide when not to trade. It identifies unprofitable market phases before your account takes a hit.
The Market Traffic Light : Use it as a higher-timeframe filter. Only allow long trades in the bullish (green) regime, short trades in the bearish (red) regime, and pause your strategy during the choppy (gray) regime.
Clarity Over Overtrading : With its clear, color-coded separation, you can instantly see whether the market has a clean directional bias or is caught in the "chop."
How It Works & Underlying Logic
The script intelligently decouples visual momentum from the actual trend regime logic:
The Visual Foundation (MACD Histogram) : The baseline visual consists of a classic MACD histogram calculated on the typical price (hlc3). This displays the current momentum of the market.
The Regime Filter (EMA Slope) : Crucially, the color of the bars is not determined by the MACD. Instead, it is driven entirely by the slope (steepness) of the fast 20 EMA.
The Noise Filter (Threshold) : To prevent the indicator from constantly flickering back and forth with minor price ticks, a percentage-based threshold (Sideways Threshold, default: 0.15%) is implemented. The market is only classified as trending when the EMA slope cleanly exceeds this threshold.
How to Interpret It for Your Trading
🟩 Lime (Bullish Regime) : The 20 EMA slope is strongly positive. The short-term trend is firmly up. Focus on Long setups.
🟥 Red (Bearish Regime) : The 20 EMA slope is strongly negative. The short-term trend is firmly down. Focus on Short setups.
⬜ Gray (Sideways/Chop) : The slope is too flat and remains within the threshold boundaries. Caution: This is where trend strategies usually experience their heaviest drawdowns. This is an excellent time to sit on your hands and wait on the sidelines.
Pro-Tip : Apply this indicator to the Daily chart of your favorite asset. If you trade a trend-following strategy on lower timeframes (e.g., 1H or 15M), strictly filter your entries based on the color of the Daily regime. Indicateur

Intermarket Flow OscillatorAdvanced Macro Regime Tracking & Apex Reversal Detection
What is the Intermarket Flow Oscillator (IFO)?
The Intermarket Flow Oscillator (IFO) is a quantitative momentum tool designed to track capital rotation between risk-on assets (growth, equities) and risk-off assets (defensives, bonds, safe havens). By utilizing advanced statistical normalization and John Ehlers' digital signal processing, the IFO visualizes structural market regimes and pinpoints high-probability exhaustion reversals.
Whether you are trading swing setups on the daily chart or monitoring intraday capital flows, the IFO acts as a macro compass to keep you on the right side of institutional money.
The Mathematical Engine
Traditional spread indicators suffer from noise and asymmetric scaling. The IFO solves this using a two-step quantitative process:
Z-Score Normalization: The script calculates the natural log ratio of a Risk Asset versus a Safe Haven asset, then applies a rolling Z-Score. This transforms the intermarket spread into a stationary stochastic process, making standard deviation thresholds mathematically reliable.
John Ehlers' 2-Pole SuperSmoother: To eliminate high-frequency market noise without introducing the severe phase lag typical of moving averages, the Z-Score is passed through an advanced DSP filter.
How to Read the Signals
Trend Shifts & Structural Regimes (The Zero-Line)
The smoothed oscillator crossing the zero equilibrium line indicates a macro shift in capital allocation.
Green Cloud (IFO > 0): Structural Risk-On Regime. Institutions are accumulating risk/growth. Traders should look for long momentum setups and favor high-beta assets.
Red Cloud (IFO < 0): Structural Risk-Off Regime. Capital is fleeing to safety. Traders should focus on cash preservation, defensive value, or short setups.
Apex Mean-Reversion Turns (▲ and ▼)
The script calculates the first derivative (Velocity) of the smoothed capital flow. When the oscillator reaches extreme statistical exhaustion thresholds (default ±1.5 standard deviations) and the velocity flips, the IFO prints a high-contrast triangle.
Bullish Apex (▲): Occurs deep in negative territory (panic/capitulation). Represents a mathematically optimal exhaustion point where selling pressure is dying. Excellent for buying the bottom in growth stocks.
Bearish Apex (▼): Occurs high in positive territory (euphoria). Represents exhaustion in risk-taking and serves as an early warning to take profits or look for short entries.
Practical Trading Application: Sector Rotation (XLK vs. XLP)
While the default script pairs S&P 500 Futures (ES) against 10-Year Treasuries (ZN), the true power of the IFO shines in sector rotation.
The Setup: Set the Risk Asset to XLK (Technology) and the Safe Haven to XLP (Consumer Staples).
The Logic: XLK represents high-beta, duration-sensitive growth (Apple, Microsoft, Nvidia). XLP represents inelastic consumer demand (Procter & Gamble, Walmart). This spread is the ultimate risk-on/risk-off gauge.
Key Features & Customization
Customizable Pairs: Fully adjustable inputs to test different macro pairs (e.g., BTC vs. Gold, BTCUSDT.P vs. USDT, Discretionary vs. Utilities, High Yield Bonds vs. Treasuries).
Dynamic Coloring: The oscillator line shifts between bright/faded colors based on momentum velocity, giving you a visual cue before a crossover even happens.
Indicateur

Bibliothèque

Parallax Covenant Strategy [JOAT]Parallax Covenant Strategy
Introduction
Parallax Covenant Strategy is an open-source, non-repainting TradingView strategy that integrates multiple analytical engines into one realistic execution framework. It combines regime detection, pressure confirmation, mapped bias, structure context, wave release logic, and ATR-based risk management to produce entries and exits only when several independent conditions agree.
The problem this strategy solves is weak single-factor trading. A crossover alone is rarely enough. A structure break alone is often early. A momentum spike alone can be noisy. Parallax Covenant requires alignment between regime, internal pressure, mapped bias, structural context, and release behavior before taking a trade. This creates a more selective, context-aware model than a one-indicator strategy.
Core Concepts
1. Composite Regime Engine
The strategy builds a directional regime from a structural baseline, tolerance corridors, and expansion/compression state. This acts as the primary directional context.
2. Pressure Confirmation
An internal pressure model blends weighted candle force and channel position to avoid taking trades simply because price is above or below a baseline.
3. Mapping and Higher-Timeframe Bias
The strategy uses a mapped momentum framework and an optional confirmed higher-timeframe bias filter so lower-timeframe entries can align with broader conditions.
4. Structure and Release Filters
Demand and supply context, swing structure, and release-from-compression logic help prevent entries from firing in the middle of low-quality noise.
5. Realistic Risk Management
The strategy uses ATR-based stops, reward-to-risk targets, optional trailing logic after a minimum multiple of risk, and regime-failure exits. This makes the model more realistic than fixed-tick toy strategies.
Features
Multi-engine entry stack: Regime, pressure, mapping, structure, and release alignment
Confirmed-bar logic: Entry conditions are evaluated on confirmed bars
Optional higher-timeframe bias filter: Uses confirmed higher-timeframe values
Demand and supply context: Trade logic includes structural location awareness
ATR stop and target model: Risk adjusts to symbol volatility
Trailing stop activation: Trail can engage after a defined reward threshold
Regime-failure exit: Closes trades when core directional conditions break down
Maximum time-in-trade control: Avoids stale positions
Institutional dashboard: Top-right strategy state summary
Alertconditions: Regime shifts, releases, and setup confirmations
How to Use This Strategy
Step 1: Study the Dashboard
The dashboard shows whether the system currently sees bullish, bearish, or balanced conditions and how the internal engines align.
Step 2: Understand the Entry Stack
Trades only trigger when multiple conditions confirm together. If you see a setup fail to trigger, that is often intentional filtering rather than a bug.
Step 3: Respect the Risk Model
Stops and targets are volatility-based. Results will vary materially across symbols and timeframes because the strategy adapts to local ATR conditions.
Step 4: Evaluate by Regime, Not by Individual Trade
This strategy is meant to be judged over a broad sample. It is a context-and-confirmation model, not a scalping script trying to predict every turn.
Strategy Limitations
The strategy is intentionally selective and may skip many charts or periods
Higher-timeframe confirmation uses confirmed data and can therefore feel slower than live-developing bias models
ATR-based exits adapt to volatility, which means trade statistics can shift significantly across markets
No strategy can remove all adverse conditions, especially during sudden event-driven repricing
Originality Statement
Parallax Covenant Strategy is original in the way it integrates multiple distinct analytical engines into one non-repainting framework. It is not a basic moving average crossover, not a single-oscillator strategy, and not a toy example of ATR stops. Its value comes from requiring alignment between market regime, internal pressure, mapped bias, structure, and release conditions before entering risk.
Disclaimer
This strategy is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any instrument. Historical backtest results do not guarantee future performance. Always use realistic expectations, proper risk management, and independent judgment.
- Made with passion by jackofalltrades
Stratégie

Cartograph Bands [JOAT]Cartograph Bands
Introduction
Cartograph Bands is an open-source price-space mapping overlay that translates internal momentum and regime pressure into adaptive bands around price. Instead of displaying momentum in a separate pane and forcing the user to mentally translate it back into price context, the script projects a composite regime score directly into layered price envelopes.
The problem Cartograph Bands solves is disconnected interpretation. Oscillators can show strength or weakness, but they often fail to communicate where that state matters on the chart. Cartograph Bands closes that gap by converting internal regime intensity into inner, outer, and far price-space bands, then combining that with multi-timeframe confirmation and volatility-state transitions.
Core Concepts
1. Composite Momentum Engine
The script blends several internal measurements including RSI, CMO, ROC normalization, and slope behavior to create a bounded momentum/regime score. This reduces reliance on any single oscillator.
2. Price-Space Mapping
That composite score is mapped into adaptive offsets around price using ATR and standard deviation inputs. The result is a set of bands that express regime intensity as chart structure rather than as a separate panel line.
3. Layered Band Geometry
Three band families are used:
Inner bands for local equilibrium
Outer bands for state extension
Far bands for exceptional displacement
4. Non-Repainting Higher Timeframe Confirmation
Confirmed higher-timeframe values are requested using offset expressions and lookahead handling intended to avoid future leakage on historical bars.
5. Compression and Expansion State Tracking
Cartograph Bands also classifies whether the current market state is compressing or expanding, which gives context to outer-band tests and re-entry events.
Features
Composite momentum model: Multiple internal regime factors instead of one oscillator
Mapped price-space bands: Regime intensity projected directly onto chart structure
Inner, outer, and far layers: Different depths of price displacement
MTF confirmation dashboard: Top-right summary with higher-timeframe agreement context
Compression and expansion tracking: Identifies volatility-state transitions
Outer-band re-entry events: Useful for exhaustion or reacquisition studies
State candle tinting: Visual context without heavy marker clutter
Gradient cloud system: Layered institutional-style fills
Confirmed-signal mode: Optional bar-close confirmation behavior
Alertconditions: Regime flips, re-entry, expansion, compression, and MTF conflict
How to Use This Indicator
Step 1: Read the Band State
Price inside the inner structure implies local balance. Sustained travel into outer and far layers implies stronger directional pressure.
Step 2: Check the Dashboard
Use the dashboard to confirm whether the chart-timeframe state aligns with higher-timeframe conditions.
Step 3: Watch Re-entry Behavior
Re-entry from outside the outer band can highlight exhaustion or failed extension, especially when expansion begins to fade.
Step 4: Use Compression and Expansion as Context
A compression state reduces the importance of directional interpretation. Expansion after compression matters more than random outer-band wandering.
Indicator Limitations
The mapping is adaptive, so band distance changes with symbol volatility
Higher-timeframe context is intentionally confirmed and may feel slower than live-developing HTF tools
Band interaction alone should not be treated as a complete trade system
The script maps internal regime state into price context, but it does not forecast exact reversal points
Originality Statement
Cartograph Bands is original in the way it blends multiple internal regime measurements and projects them into layered price-space geometry. Its value is not just an oscillator or just bands, but the interaction between regime scoring, mapped offsets, MTF confirmation, and state transitions.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. All mapped bands are analytical references derived from historical price behavior and should be used with sound judgment and risk management.
- Made with passion by jackofalltrades
Indicateur

Arbiter Channel [JOAT]Arbiter Channel
Introduction
Arbiter Channel is an open-source market state overlay built to classify directional control, compression, and expansion using a layered baseline-and-channel framework. The script blends an Ichimoku-inspired composite baseline, body-aware tolerance channels, and a confirmed-bar trend-state engine to identify whether price is operating in directional acceptance, compression, or expansion. Rather than acting like a generic moving average channel, Arbiter Channel is designed to map the relationship between equilibrium and displacement.
The problem Arbiter Channel solves is false trend interpretation. Price can trade above a moving average without truly being in an efficient trend, and it can look weak during healthy pullbacks inside a broader expansion. Arbiter Channel separates baseline equilibrium, tolerance acceptance, and directional displacement so that the user can tell whether price is simply oscillating around fair value, compressing inside equilibrium, or expanding away from it with intent.
Core Concepts
1. Composite Baseline Construction
The baseline is built from an Ichimoku-style blend of Conversion, Base, Span A, and Span B components, with user-controlled inclusion and weighting. This creates a smoother and more structurally aware equilibrium anchor than a single moving average:
tenkan = donchianMid(convLen)
kijun = donchianMid(baseLen)
spanA = math.avg(tenkan, kijun)
spanB = donchianMid(spanBLen)
2. ATR and Body Tolerance Channel
Instead of plotting a fixed-width envelope, the channel adapts to both ATR behavior and candle-body pressure. This helps the band respond differently during active displacement than during passive drift. The result is a tolerance corridor where trend acceptance and loss of acceptance become visually obvious.
3. Confirmed-Bar Trend State Machine
Trend transitions are only registered on confirmed bars. This avoids intrabar flipping and helps keep trend-state changes non-repainting for practical signal use. The script distinguishes directional trend shifts from regime changes, so compression and expansion can evolve without necessarily forcing a full directional flip.
4. Compression and Expansion Regimes
Arbiter Channel tracks whether price is contracting around equilibrium or extending away from it. This is important because directional trend and volatility regime are not the same thing. A bullish trend can be compressing before expansion, and expansion can fail back into balance.
5. Institutional Visualization Layer
The overlay uses nested clouds, baseline shadows, state candle tinting, controlled event labels, and a medium top-right dashboard to summarize regime and trend without clutter.
Features
Composite baseline engine: Uses multiple Ichimoku-derived components instead of a single average
Adaptive tolerance channels: Envelope width responds to volatility and body behavior
Compression and expansion classification: Distinguishes rotational balance from directional release
Confirmed-bar trend state engine: Trend shifts only confirm after bar close
Outer reclaim events: Detects price returning inside channel boundaries after extension
Cloud-based regime visualization: Multi-layer fills show equilibrium and displacement zones
State candle tinting: Candles inherit directional context without overwhelming price
Top-right dashboard: Displays current trend, regime, channel state, and internal diagnostics
Fully configurable palette: Built for dark charts with adjustable institutional tones
Confirmed alertconditions: Trend shifts, regime changes, reclaim events, and expansion bursts
How to Use This Indicator
Step 1: Read the Trend State
Start with the dashboard and baseline color. This tells you whether the script currently classifies the market as bullish, bearish, or neutral from a confirmed-bar perspective.
Step 2: Check the Regime
Compression means price is accepting around equilibrium. Expansion means price is actively displacing. Combining trend with regime helps determine whether to expect continuation or wait for release.
Step 3: Use the Channel Structure
The inner and outer bands act as context zones. Price holding outside the inner corridor during expansion is stronger than price simply crossing the baseline.
Step 4: Watch Reclaim Events
When price extends beyond the outer channel and then reclaims back inside it, that event can signal exhaustion, acceptance failure, or a return to balance.
Indicator Limitations
The baseline is a structural equilibrium model, not a predictive model
Compression and expansion are relative to the current symbol and timeframe inputs
Strong news events can create abrupt regime transitions that temporarily distort channel interpretation
The script is best used as a context overlay, not as a standalone trade trigger
Originality Statement
Arbiter Channel is original in the way it separates directional trend, equilibrium tolerance, and volatility regime into one coordinated overlay. It is not a simple moving average channel and not a direct copy of Ichimoku. The value comes from combining a composite baseline, adaptive tolerance geometry, and confirmed-bar regime logic into a single context engine.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice and does not guarantee future market behavior. Always use proper risk management.
- Made with passion by jackofalltrades
Indicateur

Covenant Regime Atlas [JOAT]Covenant Regime Atlas
Introduction
Covenant Regime Atlas is an open-source Pine Script v6 market-regime indicator built to classify directional state through trend, expansion, persistence, and retest quality. Its purpose is not to predict the next trade by itself, but to create a durable bias layer that tells the trader whether the market is developing a bullish regime, a bearish regime, or a maturing directional environment worth respecting.
The problem this script solves is context instability. Many traders can spot a moving-average crossover or a burst in ATR, but that alone does not answer whether the regime is actually mature, whether momentum has real separation, or whether recent retests are behaving consistently with the dominant trend. Covenant Regime Atlas addresses this by blending multiple regime components into one overlay and dashboard.
The script uses a dual-mid framework derived from EMA and HMA references, ATR-scaled cloud and envelope bands, persistence measurement, heat normalization, slope impulse, and retest memory. This lets it move beyond a simple bullish-versus-bearish cross and instead describe whether the regime is developing, mature, expanding efficiently, or internally cooling.
The result is an indicator for traders who want a cleaner read of bias before interpreting any trigger tool. It is especially useful as a regime filter for execution indicators and strategies that should behave differently in mature directional flow versus unstable transition periods.
Core Concepts
1. Directional Mid Versus Structural Mid
The script creates a fast directional midpoint and a slower structural midpoint using blended EMA and HMA references. The spread between those two curves forms the backbone of regime direction.
float directionalMid = math.avg(emaFast, hmaFast)
float structuralMid = math.avg(emaSlow, hmaSlow)
bool trendBull = directionalMid > structuralMid
This gives the regime engine more shape than a single moving average crossover. The directional mid measures active flow. The structural mid measures slower context.
2. Regime Strength Through Separation And Heat
Regime strength is calculated from ATR-normalized spread plus the distance of normalized heat from its midpoint. In other words, the regime is strongest when the fast and slow structures are well separated and price is also positioned decisively within its recent range.
This helps avoid overvaluing tiny directional crosses that occur with little actual separation or energy.
3. Persistence And Maturity
Every regime needs time to prove itself. The script counts how long the current directional condition has been intact and compares that against a user-defined persistence floor. Once the threshold is met, the regime is treated as mature rather than merely developing.
This matters because a fresh directional flip is different from a directional condition that has held for many bars and survived multiple retest opportunities.
4. Retest Memory
After a mature regime forms, the indicator watches for controlled retests of the directional midpoint. Bull retests occur when price revisits the midline from above and closes back above it. Bear retests use the opposite condition. The last retest is stored as a dotted line and extended forward until it becomes irrelevant.
This gives the trader a simple memory of where the market most recently confirmed trend participation.
5. Pulse, Expansion, And Efficiency
The script also measures volatility expansion, slope impulse, heat drift, trend separation percentage, and directional travel efficiency. These metrics allow the dashboard to distinguish between a mature regime that is expanding forcefully and one that is mature but internally cooling or grinding.
Features
Bull and bear regime classification: Uses fast-versus-slow blended midpoints to define directional control
Maturity logic: Distinguishes developing regimes from mature ones using persistence counting
ATR-scaled cloud and envelope: Frames the current directional corridor directly on the chart
Retest memory engine: Stores the latest mature-regime retest level for forward reference
Initiation band: Preserves the regime start envelope so traders can judge distance from the original launch zone
Pulse ribbon: Adds a compact visual band around price to reflect internal heat conditions
Regime backdrop shading: Tints the chart according to the active directional state
Detailed dashboard: Displays strength, heat, persistence, expansion, slope pulse, retest distance, maturity, efficiency, and more
Confirmed-bar alerts: Includes mature bias, retest, expansion, continuation, efficient trend, and heat-reset conditions
Data-window outputs: Exposes regime internals for systematic reading or comparison
Visual Elements
Directional cloud: The gap between the fast and slow regime mids shows whether the market is operating with clean separation
Envelope bands: ATR-based boundaries help frame the active directional corridor around price
Initiation band: The regime launch area stays visible so users can measure how far the trend has traveled from origin
Retest line memory: The latest confirmed retest is preserved as a direct chart reference
Backdrop and pulse ribbon: Context shading and the pulse band make regime character readable without overloading the chart
Best Practices
Treat mature regimes differently from developing ones because the same trigger can behave very differently in each state
Watch heat drift when a regime remains mature but starts losing internal energy
Use retest memory to frame participation zones rather than chasing every extension away from the midline
Give more weight to regimes that show both persistence and expansion instead of one without the other
Use the atlas as a context engine first and an alert source second
Input Parameters
Trend Engine:
Fast Length: Sets the faster directional reference
Slow Length: Sets the slower structural reference
Heat Window: Defines the range-normalization window for heat calculations
ATR Length: Controls volatility normalization
Cloud Width Factor: Sets the width of the directional cloud and envelope
Retest Engine:
Show Retest Memory: Toggles retest storage and line rendering
Retest Cooldown Bars: Prevents retests from firing too frequently
Persistence Floor: Sets how many bars are required before a regime is considered mature
Show Initiation Band: Displays the preserved start range of the current regime
Maturity Window: Controls maturity scaling and travel-efficiency measurements
Display:
Show Dashboard toggle
Show Regime Backdrop toggle
Show Pulse Ribbon toggle
Independent bull, bear, neutral, and panel colors
How to Use This Indicator
Step 1: Read Regime Tag And Strength
Begin with the dashboard’s regime tag. It tells you whether the market is bullish or bearish and whether that state is still developing or already mature. Pair that with the strength reading to avoid confusing a weak directional bias with a strong one.
Step 2: Check Persistence And Expansion
Persistence tells you how long the regime has survived. Expansion tells you whether volatility is supporting the move. A mature regime with positive expansion usually deserves more respect than a new regime with weak expansion.
Step 3: Use Retest Memory As A Structural Anchor
When the retest line is present, it marks the last meaningful participation check inside the trend. That line can help frame whether the current move is still building from a healthy base or drifting too far away from supportive structure.
Step 4: Watch Heat Drift And Efficiency
Heat drift helps show whether the regime is internally warming or cooling. Efficiency tells you whether directional travel has been orderly. These readings are helpful when deciding whether the trend still looks clean or is becoming unstable.
Step 5: Use It As The Bias Layer For Other Tools
Covenant Regime Atlas is best used as a bias filter. It helps define whether you should be thinking continuation, pullback participation, or caution. Pair it with your own trigger logic rather than using the regime alone as a full trading plan.
Indicator Limitations
A developing regime can fail before reaching maturity, especially in choppy markets
Retest memory is useful for context, but the stored retest level is not guaranteed to hold on future tests
Efficiency and heat drift are descriptive metrics, not predictive guarantees of continuation
The indicator can still classify a directional state during periods where execution conditions are poor for actual trading
Originality Statement
Covenant Regime Atlas is original in the way it blends trend separation, maturity, retest memory, expansion, and efficiency into a unified regime overlay. It is not just a moving-average cloud with added cosmetics:
It separates directional identity from maturity, allowing the user to distinguish developing and established regimes
It stores retest memory as a living structural feature instead of relying only on static crossover logic
It combines heat, slope, expansion, and efficiency into one dashboard so regime quality can be judged from multiple dimensions
It preserves the initiation band of the current regime, which gives context that typical trend overlays do not maintain
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. Regime readings describe current market structure and internal state based on historical prices. They do not guarantee future movement or profitable trading decisions. Always use independent judgment and proper risk management.
-Made with passion by jackofalltrades
Indicateur

[ A L P H A X ] Slope Spectrum ProAlphaX Slope Spectrum Pro — Multi-Period Regression Oscillator, Adaptive Signal Line, Momentum Acceleration, Statistical Regime Detection, Classic & Hidden Divergence & Conviction Dashboard
AlphaX Slope Spectrum Pro is a professional-grade trend momentum oscillator built on a proprietary multi-period linear regression engine that scans across an entire range of lookback periods simultaneously and synthesizes them into a single adaptive oscillator value per bar. Rather than relying on a fixed-period momentum calculation, Slope Spectrum Pro measures the statistical slope of price across every period in the scan range and combines them using inverse-variance weighting — giving more influence to periods whose regression fits are more consistent, and less to those where price has been noisy. The result is a momentum oscillator that is simultaneously responsive and robust. On top of this engine sits a complete analytical layer: an adaptive signal line that changes speed with market conditions, a momentum acceleration histogram, statistical regime detection bands, classic and hidden divergence detection, regime-filtered entry signals with main chart overlay, and a live 10-row conviction dashboard.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📸 Visual Overview
AlphaX Slope Spectrum Pro in the oscillator pane — gradient-colored slope line with gradient fill, acceleration histogram in the background, adaptive signal line, regime threshold bands, divergence markers, bull/bear signal dots, main chart triangles, and the conviction dashboard
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔬 The Slope Engine — Multi-Period Regression Core
At the foundation of Slope Spectrum Pro is a multi-period linear regression scanner . On every bar, the engine runs a complete set of linear regressions across every period from your configured minimum to maximum, stepping at your chosen interval. With default settings of Min Period 10, Max Period 100, and Step Size 5, this means 19 independent regressions are computed and synthesized per bar.
Each regression fits a straight line to the logarithm of price over the lookback window and extracts the slope of that fit — a dimensionless measure of directional momentum at that timescale. Positive slope means upward momentum. Negative slope means downward momentum. Steeper slope means stronger momentum.
Inverse-Variance Weighting:
When Inverse-Variance Weighting is enabled, each regression period's slope is weighted by the inverse of its residual variance — how consistently price tracked the regression line over that lookback. A period where price followed its regression cleanly gets high weight. A period where price bounced erratically around the fitted line gets low weight. The result is that cleaner, more consistent trend periods contribute more to the final oscillator value than noisy, choppy periods — the oscillator becomes naturally less sensitive to random price fluctuations and more responsive to genuine directional momentum.
What the oscillator value means:
A value above zero means the weighted regression slope is net positive — more periods are trending upward than downward across the scanned range.
A value below zero means the weighted slope is net negative — dominant downward trend momentum.
The magnitude reflects how steep the consensus slope is. A large positive value means strong, consistent upward momentum. A value near zero means flat or contested momentum.
The oscillator is plotted as a gradient-colored line that transitions dynamically from bear red to bull green based on its rolling 200-bar min/max range — the stronger the current momentum relative to recent history, the brighter the color. A gradient fill between the oscillator line and the zero line reinforces the directional bias visually.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
〰 Adaptive Signal Line
The signal line tracks the slope oscillator — but instead of a fixed-period EMA, Slope Spectrum Pro uses an adaptive alpha-based EMA that changes its effective length based on current market conditions.
How it adapts:
The adaptation measures trend strength as how many standard deviations the current oscillator value is from its recent mean. When the oscillator is far from its mean — a clear, developing trend — the signal line shortens and reacts faster, following the oscillator closely. When the oscillator is near its mean — a ranging or choppy condition — the signal line lengthens, smoothing out minor oscillations and reducing false crossovers.
In a strong trend: the signal is tight. Crossovers happen quickly and reflect real momentum shifts.
In chop or range: the signal is loose. It takes a more significant oscillator move to produce a crossover, filtering out noise automatically.
The current effective signal length is shown live on the dashboard as EMA~N — you can see exactly how tight or loose the signal is at any moment. Adaptive speed can be toggled off for a consistent fixed-length signal.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Momentum Acceleration Histogram
Behind the oscillator line, a background acceleration histogram plots the rate of change of the slope oscillator — how fast momentum is building or fading right now.
Green columns — acceleration is positive. The slope oscillator is increasing. Momentum is building in the bullish direction.
Red columns — acceleration is negative. The slope oscillator is decreasing. Momentum is fading or building in the bearish direction.
Reading the acceleration alongside the main oscillator gives you a two-layer picture:
Oscillator above zero + green acceleration = strengthening bull momentum . The best time to enter or hold long.
Oscillator above zero + red acceleration = bull momentum peaking and fading . Consider reducing exposure or preparing to exit.
Oscillator below zero + red acceleration = strengthening bear momentum . Best time to hold or enter short.
Oscillator below zero + green acceleration = bear momentum fading . Watch for a potential reversal or crossover signal.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Statistical Regime Detection
Slope Spectrum Pro automatically classifies the current market environment into one of three regimes using a rolling statistical framework built from the oscillator's own mean and standard deviation:
Bull Regime — the oscillator is above the upper band (mean + N standard deviations). Background tints subtly green. Only bullish signals fire when regime filtering is enabled.
Bear Regime — the oscillator is below the lower band (mean − N standard deviations). Background tints subtly red. Only bearish signals fire when regime filtering is enabled.
Range Regime — the oscillator sits between the two bands. Background is a very faint neutral gray. No directional regime is confirmed. Regime-filtered signals are suppressed entirely.
Thresholds are calculated as oscillator mean ± (standard deviation × sensitivity multiplier) over the configured lookback. Increasing the sensitivity multiplier raises the bar required to enter Bull or Bear regime — only the strongest trend episodes qualify. Lowering it makes transitions more frequent.
This system directly controls signal quality when Regime-Filtered Signals is enabled — crossovers opposing the active regime direction are silently blocked before they ever reach the chart.
Regime bands on the oscillator — Bull threshold above, Bear threshold below, background tint reflecting the current zone
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
◆ Divergence Engine — Classic and Hidden
Slope Spectrum Pro detects four divergence types by comparing confirmed oscillator pivot highs and lows against confirmed price pivot highs and lows. All detections are confirmed on bar close only — no repainting.
Classic Divergences — Reversal Signals:
Classic Bull Divergence (DIV ▲) — price makes a lower low while the slope oscillator makes a higher low. Selling pressure is weakening even though price is still falling. A reversal upward may be building.
Classic Bear Divergence (DIV ▼) — price makes a higher high while the slope oscillator makes a lower high. Buying pressure is weakening even though price is still rising. A reversal downward may be building.
Hidden Divergences — Trend Continuation Signals:
Hidden Bull Divergence (H ▲) — price makes a higher low while the oscillator makes a lower low. Price held higher ground during the pullback — the uptrend is intact and continuation upward is probable.
Hidden Bear Divergence (H ▼) — price makes a lower high while the oscillator makes a higher high. Price failed to rally as high as before even as the oscillator rebounded — the downtrend is intact and continuation downward is probable.
Classic divergences warn of potential reversals. Hidden divergences confirm that pullbacks within a trend are likely to resume. Both are marked on the oscillator at the pivot bar with compact DIV or H labels. The divergence pivot lookback is configurable. Hidden divergence can be toggled independently from classic divergence.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 Entry Signals — Oscillator and Main Chart Overlay
Crossover signals fire when the slope oscillator crosses above or below the adaptive signal line, confirmed on bar close:
Bull Signal (●) — oscillator crossed above signal line. A small green dot appears on the oscillator.
Bear Signal (●) — oscillator crossed below signal line. A small red dot appears on the oscillator.
Regime filtering: When enabled, bull crossovers during a Bear Regime are blocked. Bear crossovers during a Bull Regime are blocked. Only signals aligned with the current statistical regime are displayed — this single filter eliminates a significant category of false signals.
Main chart overlay: When Overlay Candle Color is enabled:
A ▲ green triangle appears below the bar on the main chart at every bull signal.
A ▼ red triangle appears above the bar on the main chart at every bear signal.
Candles on the main chart are colored using the same gradient as the oscillator — chart candles reflect the current slope momentum state at a glance.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 Live Conviction Dashboard
A real-time 10-row readout of the oscillator's full internal state, updating on every bar close:
SAMPLES — number of regression periods computed per bar based on Min, Max, and Step settings.
MODE — INV-VAR WEIGHTED or SIMPLE AVERAGE aggregation.
OSC VALUE — live slope oscillator value to six decimal places, green above zero, red below.
REGIME — ▲ BULL ZONE, ▼ BEAR ZONE, or — RANGING. Row highlighted in the corresponding color.
MOMENTUM — ▲ BUILDING (acceleration positive) or ▼ FADING (acceleration negative). Row highlighted accordingly.
SIGNAL — ▲ BULL CROSS / ▼ BEAR CROSS when a crossover fired this bar, or ▲ ABOVE SIG / ▼ BELOW SIG for ongoing position.
SIG SPEED — current effective signal length as EMA~N, showing how tight or loose the adaptive signal is in real time.
DIVERGENCE — highest-priority active divergence: ▲ BULL DIV, ▼ BEAR DIV, ▲ HIDDEN BULL, ▼ HIDDEN BEAR, or — NONE. Row highlighted when active.
CONVICTION — a 0–4 confluence score. Each of the following adds 1 point: regime and oscillator sign agree; regime and acceleration agree; regime and signal side agree; any divergence is active. Score labels — LOW / MIXED (0–1), MODERATE (2), HIGH CONVICTION (3), MAX — ALL ALIGNED (4).
OSC (sigma) — the oscillator value expressed as standard deviations from its recent mean. Shows statistically how far momentum has moved from neutral — +2.5s means 2.5 standard deviations into bull territory.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡ Key Features
🔬 Multi-period regression engine — 19 independent regressions per bar (default) synthesized into one adaptive oscillator value
⚖ Inverse-variance weighting — consistent regression periods carry more weight; noisy periods are automatically discounted
〰 Adaptive signal line — effective EMA length speeds up in trends, slows in chop; current length shown live as EMA~N
⚡ Momentum acceleration histogram — rate-of-change of the oscillator, showing whether momentum is building or fading right now
📊 Statistical regime detection — three-zone classification (Bull / Bear / Range) using rolling mean ± standard deviation bands
🔒 Regime-filtered signals — crossovers opposing the current statistical regime are automatically suppressed
◆ Classic divergence — bull and bear reversal divergence between price pivots and oscillator pivots, bar-close confirmed
◆ Hidden divergence — trend continuation signals when price and oscillator diverge in the trend direction
🎯 Main chart overlay — bull/bear triangles on price chart and gradient candle coloring reflecting live slope momentum
🎨 Dynamic gradient oscillator color — live transition from bear to bull based on rolling 200-bar normalization
📋 Live 10-row conviction dashboard — samples, mode, osc value, regime, momentum, signal, signal speed, divergence, conviction score, sigma reading
🏆 4-point conviction scoring — real-time confluence count across regime, acceleration, signal, and divergence alignment
🔔 10 alert conditions — crossovers, classic and hidden divergences, confluence long/short, zero line crosses
🎨 14 user-configurable color inputs — every visual element independently themeable with AlphaX brand defaults
✅ Confirmed on bar close — no repainting on any signal, divergence, or regime transition
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙ Settings Reference
Slope Engine
Max Period — upper bound of the regression scan range (default: 100)
Min Period — lower bound of the scan range (default: 10)
Step Size — increment between scanned periods (default: 5). Smaller = more samples, smoother oscillator.
Inverse-Variance Weighting — weight each period by its regression consistency (default: on)
Source — price input for all regressions (default: close)
Adaptive Signal Line
Base Signal Length — signal EMA length in neutral conditions (default: 7)
Adaptive Speed — toggle adaptive EMA alpha on or off
Momentum Acceleration
Show Acceleration Histogram — toggle the background column histogram
Acceleration Smoothing — EMA smoothing period for acceleration (default: 3)
Regime Detection
Show Regime Bands — toggle threshold lines and background tinting
Regime Lookback — rolling window for mean and standard deviation (default: 200)
Regime Sensitivity (σ×) — standard deviation multiplier for thresholds (default: 0.5)
Divergence Engine
Show Divergences — toggle all divergence detection
Divergence Pivot Length — bars on each side to confirm a divergence pivot (default: 5)
Show Hidden Divergences — toggle hidden divergence independently
Entry Signals
Show Crossover Signals — toggle oscillator signal dots
Regime-Filtered Signals — suppress signals opposing the current regime
Overlay Candle Color — toggle main chart triangles and gradient candle coloring
Dashboard
Show Dashboard — toggle the dashboard panel
Position — Top Right, Top Left, Bottom Right, Bottom Left
Theme
Bull Primary / Bright / Dim — three shades of the bullish color family
Bear Primary / Bright / Dim — three shades of the bearish color family
Neutral / Neutral Light — neutral and secondary text colors
Accel Bull / Accel Bear — acceleration histogram column colors
Divergence Bull / Divergence Bear — classic divergence marker colors
Hidden Div Bull / Hidden Div Bear — hidden divergence marker colors
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 How to Trade with AlphaX Slope Spectrum Pro — Step by Step
Step 1 — Establish the regime and directional bias
Check the REGIME row. ▲ BULL ZONE = the market is in a statistically confirmed trend upward. ▼ BEAR ZONE = confirmed trend downward. — RANGING = no directional edge. Only trade in the direction of the active regime.
Check OSC (sigma). A reading above +2s means deep bull territory. Below −2s means deep bear territory. Near zero = flat momentum, no edge.
Step 2 — Read acceleration for entry timing
In a Bull Regime, wait for the acceleration histogram to turn green (▲ BUILDING on the dashboard). This means the slope oscillator is accelerating — momentum is growing, not just present.
The ideal entry timing: Bull Regime + oscillator above zero + acceleration building + oscillator above signal line.
Entering while acceleration is red (▼ FADING) in a bull regime risks entering as the current wave is losing steam.
Step 3 — Enter on a signal crossover
A bull signal dot (oscillator crosses above signal line) with regime filtering enabled is your entry trigger — counter-trend crossovers are already blocked automatically.
If Overlay is enabled, the ▲ triangle on the main chart confirms the exact entry bar.
The faster the adaptive signal (lower EMA~N), the tighter the crossover timing. In strong trends the signal shortens and reacts more quickly.
Step 4 — Upgrade conviction with divergence
A bull signal crossover occurring simultaneously with or just after a Classic Bull Divergence (DIV ▲) = high-probability reversal setup.
A bull signal crossover during an uptrend following a Hidden Bull Divergence (H ▲) = high-probability trend continuation setup.
Check CONVICTION. Score of HIGH CONVICTION (3) or MAX — ALL ALIGNED (4) means multiple independent factors agree. These are the setups to prioritize.
Step 5 — Exit when momentum confirms the move is ending
Acceleration histogram turning red (▼ FADING) while you are long = first sign the current wave is losing force. Begin monitoring for exit.
A bear signal crossover (oscillator crosses below signal line) = exit trigger.
A regime shift from Bull Zone to Ranging or Bear Zone = structural move is over. Exit and reset.
A Classic Bear Divergence appearing while you are in a long position = warning. Price is printing new highs the oscillator is not confirming. Reduce size or prepare to close.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔔 Alert Conditions
SSP — Bull Crossover — oscillator crossed above the adaptive signal line
SSP — Bear Crossover — oscillator crossed below the adaptive signal line
SSP — Classic Bull Divergence — price lower low, oscillator higher low confirmed
SSP — Classic Bear Divergence — price higher high, oscillator lower high confirmed
SSP — Hidden Bull Divergence — price higher low, oscillator lower low (trend continuation)
SSP — Hidden Bear Divergence — price lower high, oscillator higher high (trend continuation)
SSP — CONFLUENCE LONG — bull crossover occurring with bull or hidden bull divergence simultaneously
SSP — CONFLUENCE SHORT — bear crossover occurring with bear or hidden bear divergence simultaneously
SSP — Zero Line Cross Up — oscillator crossed above zero (macro bull momentum shift)
SSP — Zero Line Cross Down — oscillator crossed below zero (macro bear momentum shift)
All alert messages include {{ticker}} and {{interval}} for webhook integration.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
👥 Who This Is For
🧠 Systematic and quantitative traders — the regression engine, inverse-variance weighting, and statistical regime framework provide a mathematically grounded, objective momentum reading with no arbitrary indicator parameters to tune
📈 Trend traders on any instrument and timeframe — the multi-period scan adapts naturally to any market's momentum characteristics without manual recalibration
🔍 Divergence traders — four divergence types covering both reversals and trend continuations, all confirmed on bar close
⚡ Momentum traders — the acceleration histogram adds a layer no standard oscillator provides: not just where momentum is, but whether it is growing or shrinking right now
🎯 Precision entry traders — regime filtering, adaptive signal speed, and the conviction score ensure signals are only shown when multiple independent conditions agree simultaneously
🎨 Traders who customize their charts — 14 fully user-configurable color inputs, compatible with any chart theme
🔔 Alert-driven traders and bot operators — 10 alert conditions including a dedicated confluence alert for maximum-conviction setups
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📝 Notes
All signals are confirmed on bar close only. Slope Spectrum Pro does not repaint.
The oscillator value is in units of log-price per bar. The absolute value is very small (typically 0.000001 to 0.001 range) — what matters is the sign, the direction of change, and where it sits relative to regime thresholds and zero.
Wider Min–Max scan ranges produce a smoother oscillator capturing broader trend consensus. Narrower ranges are more reactive to short-term changes. Smaller Step Size = more periods sampled per bar = smoother result.
Regime Sensitivity is the most impactful setting after the scan range. At 0.5σ (default) the regime bands trigger relatively frequently. At 1.0–1.5σ, only very strong trend episodes qualify — signals become rarer but higher quality.
On very low timeframes the nested regression loop may be computationally intensive. Default settings are optimized for timeframes from 1 minute upward on standard instruments.
All theme color defaults are designed for dark chart backgrounds. Adjust Theme inputs if using a light background.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ Disclaimer
This indicator is a technical analysis and visualization tool intended for educational and informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any financial instrument. All signals are generated from historical and real-time price data using mathematical calculations — their accuracy or profitability is not guaranteed. Past performance does not guarantee future results. Always conduct your own analysis, use proper risk management, and consult a licensed financial advisor before making any trading decisions. The author accepts no responsibility for any losses incurred from the use of this indicator.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built for traders who want to know not just where momentum is — but how it got there, how strong it is, and whether it is still building. Indicateur

Structural Momentum Gauge [JOAT]Structural Momentum Gauge
Introduction
Structural Momentum Gauge is an open-source overlay indicator that fuses an adaptive Kalman filter with a Supertrend ratchet trail and a WMA-based volatility envelope to produce three clearly defined regime states: Bull Trend, Bear Trend, and Range-Bound. Rather than relying on a fixed moving average, the Kalman filter continuously self-calibrates its noise estimate each bar, delivering a smoothed price proxy that adapts to changing market conditions without introducing unnecessary lag. The Supertrend ratchet applied directly to the Kalman value — rather than to a raw price midpoint — generates directional bias changes that are markedly more stable than those produced by conventional price-based systems.
The core problem this indicator addresses is that most trend-following tools either repaint (flipping signals on the same bar as price reverses) or commit to a direction far too slowly. The Kalman filter's gain calculation absorbs noise on low-momentum bars while remaining sensitive during genuine impulses. Layering an envelope breach condition on top means both the Kalman direction and price location relative to the volatility band must agree before a trend regime is confirmed — a dual-gate that substantially reduces false readings on choppy, sideways charts.
Core Concepts
1. Adaptive Kalman Filter
The Kalman filter maintains two persistent state variables: the current estimate (k_est) and the error variance (k_err). Each bar the Kalman gain is computed as k_err / (k_err + noise), where noise equals kAlpha * kPeriod. The gain controls how much the estimate shifts toward the current close. After updating the estimate, the error variance is revised: (1 - gain) * k_err + kBeta / kPeriod. This means a large prediction error pushes the variance higher, increasing the gain on the next bar and making the filter more responsive. When price action settles, the gain contracts and the filter smooths out. The result is a price proxy that is neither the fixed-lag of a simple moving average nor the noise sensitivity of a raw close.
2. Supertrend Ratchet on Kalman
ATR-scaled upper and lower bands are applied around the Kalman value rather than the raw hl2. The ratchet rule then applies: the upper band can only move down (or reset when the Kalman value crosses above it), and the lower band can only move up (or reset when the Kalman value crosses below it). Direction flips when the Kalman value closes through the active band. Applying the ratchet to a pre-filtered price removes the micro-fluctuations that cause excessive direction changes when using hl2 directly.
3. WMA Volatility Envelope
A WMA of the high-low range, multiplied by the deviation parameter, defines half the envelope width. The envelope upper and lower levels are placed symmetrically around the Kalman value. An extended outer cloud — 1.35x the inner envelope — is plotted for spatial context. A price close above the upper envelope sets the range state to 1; a close below the lower sets it to -1. Regime confirmation requires both the Kalman Supertrend direction and the envelope range state to agree in sign:
4. Regime Classification
combined = kBias * rState, where kBias is +1 when the Kalman Supertrend is bullish and rState is +1 when close is above the upper envelope. combined == 1 with kBias == 1 is a confirmed bull trend. combined == 1 with kBias == -1 is a confirmed bear trend. All other states are range or opposing. A rolling 50-bar history computes what percentage of recent bars were in a trending state, producing a Trend Strength percentage.
5. K-Velocity
The rate of change of the Kalman value over three bars, normalized by the current ATR, yields a K-Velocity score from 0 to 1. Velocity dots appear on the Kalman line when the score exceeds 0.5, with their transparency inversely proportional to the velocity — faster moves produce more saturated dots. This creates a visual intensity signal on the trail itself, communicating acceleration and deceleration without a separate panel.
Features
Adaptive Kalman Filter: Self-calibrating price proxy with alpha and beta gain controls — responds faster during impulses, smooths more during consolidation
Supertrend Ratchet on Kalman: Direction-persistent trail applied to the Kalman value, eliminating noise-driven flips on raw price crossovers
Outer Envelope Cloud: Wide ATR envelope filled directionally, providing spatial context at a glance
Inner Envelope Fill: Standard WMA envelope bands with conditional fills that activate in range regime
Triple-Layer Kalman Glow: Three stacked plots at widths 9, 5, and 2 with decreasing transparency create a neon glow shadow effect on the Kalman line
Gradient Core Fills: 6-argument fill() between Kalman and candle mid-body, transparent at the Kalman line and saturated at the body — colored by confirmed regime
K-Velocity Dots: Pulsing circles on the trail during high-velocity trend bars, intensity scales with normalized velocity score
Regime Transition Circles: Circle marker fires at every confirmed regime change — immediate visual alert to state transitions
Bull/Bear Trend Start Arrows: Triangle up/down plotshape fires at the exact bar where both Kalman direction and envelope breach first agree
Trend End Marker: X marker fires when the trending regime ends, helping traders tighten stops or close positions
Kalman Flip Labels: K▲ / K▼ labels placed below/above the Supertrend level when the Kalman bias flips direction
Envelope Squeeze Marker: Golden diamond when envelope width drops below 80% of its recent SMA — flags compression before potential breakout
Gradient Bar Coloring: Bars saturate based on distance from Kalman within envelope range, fading to neutral in range-bound conditions
10-Row Dashboard: Regime state, K-Trend direction, Kalman price, upper/lower band levels, trend bar count, T-Strength %, K-Velocity %, volatility state
Input Parameters
Kalman Filter:
Alpha (Smoothing): Controls base noise level — lower values produce a smoother, higher-lag filter (default 0.01)
Beta (Adapt Rate): Controls how quickly error variance recovers after a large miss — higher values make the filter adapt faster (default 0.10)
Period: Normalises the gain magnitude — acts as a scaling factor on both noise and beta (default 77)
Supertrend:
ST Factor: ATR multiplier for the ratchet bands around the Kalman value (default 0.7)
ST ATR Length: ATR lookback for the Supertrend band calculation (default 7)
Volatility Envelope:
Envelope WMA Length: Lookback for the WMA of high-low range (default 200)
Envelope Deviation: Multiplier on the WMA to set envelope half-width (default 1.2)
Visuals:
Toggles for Supertrend line, envelope bands, gradient fills, Kalman glow, envelope cloud, and dashboard
Bull Color (default cyan #22d3ee), Bear Color (default rose #f43f5e), Range Color (default slate #94a3b8)
How to Use This Indicator
Primary Setup — Trend Confirmation Entry:
Wait for a trend start arrow (triangle up or down) to fire. This marks the bar where the Kalman Supertrend direction and the envelope breach state first agree. Enter in the arrow direction. Trail your stop below the Kalman line for longs or above it for shorts. Exit on a Trend End X marker or when the K▲/K▼ flip label fires against your position.
Using K-Velocity for Sizing:
When velocity dots are dense and bright, momentum is expanding — the trending move is accelerating. When dots thin out or disappear, momentum is fading even if the regime has not changed yet. Reduce size on fade or tighten stops before the trend end marker appears.
Squeeze Setup:
When the golden diamond squeeze marker fires, the envelope is compressing. Wait for price to break the envelope band in either direction. If a trend start arrow follows within the next few bars, this is a high-probability breakout entry aligned with both volatility expansion and regime confirmation.
Reading the Dashboard:
T-Strength above 60% indicates a mature, sustained trend. Values below 30% indicate the regime state is new or unstable — the trend is young and position sizing should reflect that uncertainty.
Indicator Limitations
The Kalman filter's gain is bounded by the alpha and beta parameters. Very low alpha values may make the filter too sluggish to capture short, sharp reversal moves before the ratchet trail catches them
The envelope breach condition for regime confirmation means the indicator will not register a trend until price has already moved far enough from the Kalman center to exit the band — entries will not be at the very start of a move
On instruments with consistently narrow true range (low-liquidity futures, off-hours sessions), the WMA envelope may be so tight that price is rarely inside the band, causing permanent range state classification
The Kalman filter uses close-to-close data and has no concept of intrabar price action; on daily charts, a spike high that closes near the open may produce a different Kalman trajectory than on a lower timeframe
Trend Strength is a rolling 50-bar measure. On very fast timeframes, 50 bars may represent only minutes, making the percentage less meaningful as a maturity gauge
Originality Statement
This indicator is original in its application of a Kalman filter as the supertrend base, the dual-gate regime confirmation system, and the K-velocity visual intensity layer. The publication is justified because:
Applying the Supertrend ratchet to a Kalman-filtered price rather than raw hl2 produces direction changes that are measurably more stable — the Kalman pre-filters noise that would otherwise cause excessive band crossings
The dual-gate regime system (Kalman direction AND envelope breach must agree) produces a stricter trending classification than any single-condition approach, reducing false trend readings in sideways conditions
The K-velocity normalization layer embeds a momentum acceleration measure directly into the trail visualization without requiring a separate panel, communicating both direction and rate-of-change simultaneously
The envelope squeeze detection integrated with trend start arrows identifies the specific condition where compressed volatility resolves into a confirmed regime shift — a novel combination for a Kalman-based system
The Trend Strength rolling percentage provides a trend maturity measure that distinguishes freshly flipped regimes from mature, sustained trends, enabling differentiated position sizing without a separate indicator
Disclaimer
This indicator is provided for educational and informational purposes only and does not constitute financial advice or a recommendation to buy or sell any financial instrument. Past performance of any pattern or signal does not guarantee future results. All trading involves substantial risk. Always use proper risk management and conduct your own independent analysis.
— Made with passion by officialjackofalltrades
Indicateur

Vantage Protocol [JOAT]Vantage Protocol
Introduction
Vantage Protocol is an advanced open-source execution strategy that integrates regime classification, adaptive momentum filtering, volume confirmation, session timing, and ATR-based risk management into a unified NNFX-aligned trading engine. Rather than relying on a single entry signal, the strategy requires alignment across five independent subsystems — regime state, momentum direction, cumulative volume delta, volume presence, and session timing — before entering a trade. This multi-gate architecture is designed to filter out low-probability setups and only execute when multiple independent factors converge.
This strategy exists because most retail strategies fail for a predictable reason: they use one or two conditions for entry and ignore the broader market context. A moving average crossover in a choppy market produces losses. A momentum signal during a low-volume session lacks follow-through. An entry outside the active institutional window misses the liquidity needed for clean execution. Vantage Protocol addresses each of these failure modes with a dedicated subsystem, and only enters when all subsystems agree.
Important Note on Strategy Results
Backtesting results shown with this strategy are historical simulations and do not guarantee future performance. Markets change, and strategies that performed well historically may not perform well in the future. The default settings use realistic parameters: 2% of equity per trade, $100,000 initial capital, no pyramiding, and zero margin. Users should add commission and slippage appropriate for their broker and instrument in the strategy Properties dialog before evaluating results. The strategy is published with these defaults to provide a transparent starting point — users are expected to adjust parameters for their specific trading conditions.
Strategy Architecture
The strategy follows an NNFX (No Nonsense Forex) inspired architecture where each subsystem acts as an independent gate. A trade is only entered when all gates are open simultaneously.
Gate 1: Regime Engine
The regime engine determines whether the market is trending or ranging. It combines three independent measures:
H-Infinity Filter: An adaptive filter from control theory that tracks price under worst-case noise assumptions. The filter's slope determines directional bias — positive slope = bullish, negative slope = bearish
R-Squared Efficiency Gate: Measures how well price fits a linear regression. When R-squared exceeds an auto-calibrating threshold (rolling mean plus k standard deviations), the efficiency gate opens, indicating a trending market. A hysteresis band prevents flickering
Chop Score: Measures path efficiency — the ratio of net movement to total path length. High chop scores indicate choppy, non-directional markets where trend-following strategies fail
The regime is classified as trending (bullish or bearish) only when R-squared confirms efficiency AND chop score confirms directional movement. If either condition fails, the regime is classified as ranging and no entries are allowed.
bool regimeTrend = effOK and not isChoppy
int regimeBias = regimeTrend ? (hinfSlope >= 0 ? 1 : -1) : 0
Gate 2: Momentum Core
The momentum subsystem uses a Laguerre RSI processed through JMA adaptive smoothing. The Laguerre filter provides a smoother, less laggy momentum reading than standard RSI, and the JMA smoothing further reduces noise while preserving responsiveness to genuine momentum shifts.
Momentum must confirm the regime direction:
For long entries: JMA-smoothed Laguerre RSI must be above the bull threshold (default: 62)
For short entries: JMA-smoothed Laguerre RSI must be below the bear threshold (default: 38)
This prevents entries when momentum is neutral or contradicts the regime bias.
Gate 3: Volume Filter (CVD)
Cumulative Volume Delta tracks net buying versus selling pressure. The strategy requires the CVD slope (smoothed with an EMA) to confirm the trade direction:
For long entries: CVD slope must be positive (net buying pressure increasing)
For short entries: CVD slope must be negative (net selling pressure increasing)
Additionally, the current bar's volume must exceed a minimum ratio relative to the 50-bar average (default: 0.7x). This filters out entries during thin-liquidity periods where price moves lack conviction and slippage risk is elevated.
Gate 4: Session Filter
An optional session window filter restricts entries to a configurable time window (default: 0200-1200 New York time). This aligns trading with the London and New York sessions where institutional liquidity is deepest. Entries outside this window are blocked because low-liquidity sessions produce unreliable price action and wider spreads.
Gate 5: Cooldown
After any exit (whether by stop loss, take profit, or regime exit), a configurable cooldown period (default: 5 bars) must pass before a new entry is allowed. This prevents revenge trading and allows the market to establish a new setup after a position closes.
Entry and Exit Logic
Entry Conditions:
All five gates must be open simultaneously, and the strategy must be flat (no existing position):
bool longSetup = regimeBias == 1 and momBull and cvdBull and volOK and sessOK and cooldownOK
bool shortSetup = regimeBias == -1 and momBear and cvdBear and volOK and sessOK and cooldownOK
Stop Loss and Take Profit:
SL and TP levels are calculated using ZEMA-smoothed ATR multiplied by configurable factors:
Stop Loss: Entry price minus (ZEMA-ATR x SL Multiplier) for longs, plus for shorts (default SL multiplier: 1.8)
Take Profit: Entry price plus (ZEMA-ATR x TP Multiplier) for longs, minus for shorts (default TP multiplier: 2.8)
The default risk-reward ratio is approximately 1:1.56 (1.8 SL to 2.8 TP). ZEMA smoothing on the ATR removes noise from the volatility measure, producing more stable SL/TP levels than raw ATR.
Regime Exit:
If the regime flips to ranging or the opposite direction while a position is open, the strategy closes the position immediately with a "Regime Exit" comment. Additionally, if momentum deteriorates significantly (Laguerre RSI crossing back toward neutral), the position is closed. This prevents holding positions through regime changes where the original thesis is no longer valid.
Band Structure Visualization
The strategy plots a JMA baseline with regime-colored glow, and SL/TP bands around it:
SL bands (inner) shown in muted scarlet with fill zones
TP bands (outer) shown in muted jade with cross-style plotting
The baseline color shifts based on regime: green for bullish trend, red for bearish trend, purple for ranging
Bar coloring reflects the current position state: green when long, red when short, purple when ranging (no position allowed), and grey when flat in a trending regime.
Default Strategy Properties
These are the default values used in the strategy's Properties dialog:
Initial Capital: $100,000
Order Size: 2% of equity per trade
Pyramiding: 0 (no adding to positions)
Margin: Long 0%, Short 0% (cash account simulation)
Commission: Not set by default — users should configure this for their broker (typical values: 0.01-0.1% for crypto, $1-5 per contract for futures, 1-3 pips for forex)
Slippage: Not set by default — users should configure this for their instrument (typical values: 1-3 ticks for liquid instruments, more for illiquid ones)
Users are strongly encouraged to set realistic commission and slippage values before evaluating backtesting results. Results without commission and slippage will overstate performance.
Input Parameters
Regime Engine:
R-Squared Length (default: 30), R-Squared Threshold k (default: 0.8), Chop Length (default: 20), Chop Threshold (default: 0.55)
H-Infinity Order (default: 3), Noise (default: 0.5), Disturbance (default: 1.0)
Momentum Core:
Laguerre Alpha (default: 0.07), JMA Smooth Period (default: 8), Bull Threshold (default: 62), Bear Threshold (default: 38)
Volume Filter:
CVD Smoothing (default: 14), Min Volume Ratio (default: 0.7)
Band Structure:
JMA Period (default: 21), ATR Length (default: 14), SL Multiplier (default: 1.8), TP Multiplier (default: 2.8)
Session Filter:
Session Filter toggle (default: on), Active Window (default: 0200-1200), Timezone (default: America/New_York)
Risk Management:
Risk % (default: 1.5), Re-entry Cooldown (default: 5 bars)
How to Use This Strategy
Step 1: Configure for Your Instrument
Open the strategy Properties dialog and set commission and slippage values appropriate for your broker and instrument. Adjust the session window if you trade instruments with different liquidity patterns than the default London/NY window.
Step 2: Evaluate on Sufficient Data
Run the strategy on a dataset that produces at least 100 trades for statistical significance. Short datasets with few trades produce unreliable performance metrics. Use the strategy tester's detailed trade list to review individual trades.
Step 3: Monitor the Dashboard
The 9-row dashboard shows the state of every subsystem in real-time: regime classification, momentum reading, CVD direction, volume ratio, session status, current position, ATR value, and cooldown status. This transparency lets you understand exactly why the strategy is or is not entering trades.
Step 4: Understand the Regime Exit
The strategy will close positions when the regime changes, even if the SL/TP has not been hit. This is by design — holding a trend-following position through a regime change to ranging is a common source of losses. Regime exits may result in small wins or small losses, but they prevent the larger losses that come from ignoring changing conditions.
Step 5: Adjust Parameters Thoughtfully
If the strategy produces too few trades, consider lowering the momentum thresholds (bull from 62 to 58, bear from 38 to 42) or reducing the minimum volume ratio. If it produces too many losing trades, consider increasing the R-squared threshold k or the chop threshold. Each parameter change affects the trade-off between signal frequency and signal quality.
Strategy Limitations and Compromises
Trade Frequency: The five-gate architecture is deliberately selective. On many instruments and timeframes, the strategy may only produce a handful of trades per month. This is by design — fewer, higher-quality trades — but it means the strategy is not suitable for traders who need frequent activity
Regime Detection Lag: The regime engine uses lookback-based measures (R-squared, chop score) and persistence requirements. Regime changes are identified with a delay, which means the strategy may miss the first portion of a new trend or hold slightly into a regime change
CVD Approximation: The volume delta calculation (close > open = buying) is an approximation. True order flow requires Level 2 data not available in Pine Script. On instruments with unreliable volume data (forex with tick volume), the CVD gate may be less effective
Fixed SL/TP: Stop loss and take profit are set at entry and do not trail. In strong trends, the strategy may exit at the TP while the trend continues. A trailing stop modification could capture more of extended moves but would also increase the risk of giving back profits during pullbacks
Session Dependency: The default session filter is optimized for forex and futures with distinct London/NY sessions. Crypto and other 24/7 markets may benefit from disabling the session filter or adjusting the window
No Pyramiding: The strategy does not add to winning positions. This limits profit potential in strong trends but also limits risk exposure
Backtesting vs Live: Backtesting assumes fills at the close of the signal bar. In live trading, slippage, requotes, and execution delays may produce different results. Always paper trade before committing real capital
Originality Statement
This strategy is original in its multi-gate architecture that synthesizes five independent subsystems into a unified execution engine. While individual components (regime detection, Laguerre RSI, CVD, session filtering, ATR-based risk management) are established concepts, this strategy is justified because:
The five-gate entry architecture (regime + momentum + CVD + volume + session) provides a systematic approach to filtering low-probability setups that is not available in single-indicator strategies
The H-Infinity filter for regime detection applies control theory to market classification, providing a theoretically grounded alternative to simple moving average crossover regime detection
The triple-measure regime engine (R-squared + chop + H-Infinity slope) provides more robust regime classification than any single measure
The regime exit mechanism actively manages positions based on changing market conditions rather than relying solely on fixed SL/TP levels
The NNFX-inspired architecture with clearly separated subsystems (baseline, confirmation, volume, exit, session) provides a modular framework that traders can understand, evaluate, and modify
The cooldown mechanism prevents revenge trading after exits, addressing a common behavioral trading error
All subsystem states are displayed transparently in the dashboard, allowing traders to understand exactly why trades are or are not being taken
Disclaimer
This strategy is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss and is not suitable for all investors.
Backtesting results are historical simulations based on past data. Past performance does not guarantee future results. The strategy's historical performance was generated under specific market conditions that may not repeat. Markets are dynamic, and strategies that worked historically may fail in the future.
The default strategy properties do not include commission or slippage. Users must configure these values for their specific broker and instrument to obtain realistic performance estimates. Results without commission and slippage will overstate actual trading performance.
Always use proper risk management, including position sizing appropriate for your account and risk tolerance. Never risk more than you can afford to lose. Consider paper trading this strategy extensively before using real capital. The author is not responsible for any losses incurred from using this strategy.
-Made with passion by officialjackofalltrades
Stratégie

Adaptive Regime Filter + Divergence (AER-VN) [KEYALGOS]Adaptive Regime Filter + Divergence (AER-VN)
Professional Grade Market Regime Classification with Advanced Divergence Detection
Precision trend identification using Adaptive Efficiency Ratio methodology
Volatility-normalized thresholds that adjust to real-time market conditions
Automatic divergence detection (Regular and Hidden) with visual confirmation lines
Four distinct market regimes with color-coded clarity
Zero-lag signal generation with confirmation logic
OVERVIEW
The Adaptive Regime Filter with Volatility Normalization (AER-VN) represents a sophisticated evolution of traditional trend filtering methodologies. This proprietary indicator combines Kaufman's Efficiency Ratio principles with dynamic volatility adaptation to classify market conditions into four actionable regimes: Uptrend, Downtrend, Choppiness, and Consolidation.
The integrated Divergence Detection System operates as a secondary analytical layer, identifying momentum exhaustion and trend continuation patterns through comparative analysis of price action versus efficiency metrics. Unlike standard oscillators that measure raw momentum, this system evaluates the quality of price movement, providing earlier and more reliable reversal signals.
METHODOLOGY AND TECHNIQUE
1. Adaptive Efficiency Ratio (AER) Core
Traditional efficiency ratios utilize static thresholds that fail across varying volatility environments. The AER-VN methodology introduces dynamic threshold calculation that self-adjusts based on current volatility relative to historical norms.
Displacement Measurement: Calculates net price movement over the lookback period
Path Distance Analysis: Sums absolute bar-to-bar movements to determine movement quality
Efficiency Calculation: Ratio of displacement to path distance (0.0 to 1.0 scale)
Threshold Adaptation: Baseline efficiency requirements scale proportionally with the ATR ratio
When volatility expands (ATR above mean), the system automatically raises the efficiency threshold required to qualify as "trending." This prevents false trend signals during volatile chop. Conversely, during low volatility periods, the threshold contracts to capture subtle trending behavior.
2. Volatility Normalization Engine
The Volatility Normalization component creates a relative volatility index by comparing current ATR readings against a rolling historical average. This produces an ATR Ratio that serves as the scaling factor for dynamic threshold calculation.
Current ATR: Short-term volatility measurement (default 14 periods)
Mean ATR: Long-term volatility baseline (default 50 periods)
Adaptive Scaling: Raw threshold = Base Threshold x ATR Ratio
Ceiling Protection: Maximum threshold cap prevents mathematically impossible requirements during extreme volatility events
3. Four Regime Classification System
Uptrend (Teal): Efficiency exceeds dynamic threshold with positive price displacement. Indicates high-quality upward movement with minimal retracement.
Downtrend (Maroon): Efficiency exceeds dynamic threshold with negative price displacement. Indicates sustained selling pressure with directional clarity.
Choppiness (Orange): Efficiency below threshold during above-average volatility. Characterized by noisy, directionless movement with large wicks and whipsaws.
Consolidation (Gray): Efficiency below threshold during below-average volatility. Represents quiet, range-bound markets with compressed price action.
4. Zero-Lag Divergence Detection
The divergence system employs confirmed swing detection to identify pivotal highs and lows without repainting. Once a swing point is confirmed (price violates the extreme), the system evaluates four divergence classifications:
Regular Bearish Divergence: Price records higher highs while Efficiency Ratio records lower highs. Indicates trend exhaustion and potential reversal to the downside.
Regular Bullish Divergence: Price records lower lows while Efficiency Ratio records higher lows. Indicates selling exhaustion and potential reversal to the upside.
Hidden Bearish Divergence: Price records lower highs while Efficiency Ratio records higher highs. Suggests continuation of the current downtrend after a pullback.
Hidden Bullish Divergence: Price records higher lows while Efficiency Ratio records lower lows. Suggests continuation of the current uptrend after a retracement.
Visual confirmation lines connect the relevant swing points on the indicator panel, allowing traders to verify divergence validity visually.
INPUT PARAMETERS AND CONFIGURATION
Efficiency Ratio Settings
ER Lookback (N)
Default: 10 | Range: 2+
The calculation period for efficiency measurement. Shorter values increase sensitivity to recent price action, suitable for scalping lower timeframes. Longer values smooth the oscillator, better for swing trading higher timeframes.
Base ER Threshold
Default: 0.25 | Range: 0.05 to 0.80 | Step: 0.05
The foundational efficiency level required in normalized volatility conditions. Higher values demand cleaner, more directional movement to trigger trending regime classification. Lower values allow noisier price action to qualify as trending.
Max Threshold Cap
Default: 0.65 | Range: 0.10 to 0.99 | Step: 0.05
The absolute ceiling for the dynamic threshold. This safety mechanism prevents the threshold from rising to levels mathematically impossible to achieve during extreme volatility expansion.
Volatility Normalization Settings
ATR Length
Default: 14 | Range: 1+
The lookback period for Average True Range calculation. Determines how quickly the system responds to changing volatility conditions.
ATR Mean Lookback
Default: 50 | Range: 5+
The historical window for establishing the volatility baseline. Longer periods create a smoother volatility reference, while shorter periods adapt more quickly to regime changes in volatility.
Divergence Detection Settings
Swing Definition Length
Default: 10 | Range: 3+
The lookback window for identifying swing highs and lows. Determines the minimum number of bars required to establish a pivot point. Lower values detect micro-swings (more signals, more noise). Higher values detect major swings (fewer signals, higher quality).
Visual Display Toggles
Show Regular Div Markers: Display circle markers for Regular Bearish and Regular Bullish divergences
Show Hidden Div Markers: Display circle markers for Hidden Bearish and Hidden Bullish divergences
Line: Regular Bearish: Draw connecting lines between swing highs for Regular Bearish divergences (Red)
Line: Regular Bullish: Draw connecting lines between swing lows for Regular Bullish divergences (Lime)
Line: Hidden Bearish: Draw connecting lines for Hidden Bearish divergences (Orange)
Line: Hidden Bullish: Draw connecting lines for Hidden Bullish divergences (Aqua)
Visual Settings
Color Price Bars
Toggle to apply regime colors directly to price candles/bars on the main chart. Uptrend (Teal), Downtrend (Maroon), Choppiness (Orange), Consolidation (Gray).
INTERPRETATION GUIDE
Reading the Oscillator
The main panel displays three critical elements:
Efficiency Ratio Line: The primary oscillator colored by current regime. Values near 1.0 indicate perfect efficiency (strong trend). Values near 0.0 indicate complete inefficiency (chop).
Dynamic Threshold: The white crossed line representing the current volatility-adjusted efficiency requirement. When the ER line crosses above this threshold, the regime shifts to trending.
Base Threshold Reference: The gray dotted line showing the static baseline (0.25 default) for reference.
Divergence Signal Interpretation
Red Circle (Regular Bearish): Momentum divergence at highs. Consider reducing long exposure or preparing short entries. Highest probability when appearing near resistance or after extended uptrends.
Lime Circle (Regular Bullish): Momentum divergence at lows. Consider reducing short exposure or preparing long entries. Highest probability when appearing near support or after extended downtrends.
Orange Circle (Hidden Bearish): Trend continuation signal in downtrends. Pullback likely ending, downtrend resumption probable.
Aqua Circle (Hidden Bullish): Trend continuation signal in uptrends. Retracement likely ending, uptrend resumption probable.
TRADING APPLICATIONS
Strategy 1: Regime-Based Trend Following
Enter long positions only when the indicator displays Teal coloring (Uptrend regime) and short positions only during Maroon coloring (Downtrend regime). Exit positions when the regime shifts to Orange or Gray, indicating the trending condition has ended.
Best for: Directional traders and trend followers
Timeframe: M15 and higher recommended for stability
Confluence: Combine with moving average alignment or breakout patterns
Strategy 2: Divergence Reversal Trading
Monitor for Regular Divergences (Red or Lime circles) as early warning systems. Wait for price confirmation (engulfing candles, pin bars) at the divergence point before entering. Use the connecting lines to visualize the divergence strength.
Best for: Counter-trend scalpers and swing traders
Timeframe: M5 to H1 depending on swing length settings
Confluence: Combine with support/resistance levels and volume analysis
Strategy 3: Chop Avoidance and Consolidation Breakout
Use the Orange (Choppiness) and Gray (Consolidation) regimes as "No Trade" zones or reduction zones. Wait for a divergence to form within these regimes, then enter when the regime shifts back to trending (Teal or Maroon), capturing the breakout momentum.
Best for: Patience-based traders seeking high-probability setups
Timeframe: Effective across all timeframes
Confluence: Combine with volume expansion on regime change
Strategy 4: Hidden Divergence Continuation
In established trends (Teal lasting 5+ bars), look for Hidden Bullish Divergences (Aqua) on pullbacks to enter additional long positions. In established downtrends (Maroon), look for Hidden Bearish Divergences (Orange) on rallies to add to shorts.
Best for: Position traders adding to winners
Timeframe: H1 to Daily for best results
Confluence: Combine with Fibonacci retracement levels
OPTIMIZATION GUIDELINES
For Lower Timeframes (M1 to M5)
Reduce ER Lookback to 6-8 for faster response
Lower Base ER Threshold to 0.15-0.20 to account for noise
Reduce Max Threshold Cap to 0.50-0.55
Shorten ATR Mean Lookback to 20-30
Reduce Swing Definition Length to 6-8 for micro-structure
For Higher Timeframes (H1 to Daily)
Increase ER Lookback to 14-21 for smoother readings
Maintain or increase Base ER Threshold to 0.30+ for quality control
Increase ATR Mean Lookback to 50-100 for stable volatility baselines
Increase Swing Definition Length to 10-20 for major pivots only
ALERTS AND NOTIFICATIONS
The indicator includes built-in alert conditions for:
Regular Bearish Divergence Detection
Regular Bullish Divergence Detection
Configure TradingView alerts to trigger on these conditions to monitor markets without constant chart watching.
BEST PRACTICES AND RISK MANAGEMENT
Always confirm divergence signals with price action patterns (engulfing candles, pin bars, break of structure) rather than entering immediately on marker appearance.
Avoid trading divergence signals that occur deep within the Choppiness (Orange) regime without waiting for a regime shift confirmation.
Use the regime colors as a position sizing guide: Full size in Teal/Maroon, half size in Gray, flat or minimal in Orange.
The indicator excels when combined with support/resistance analysis. Divergences forming at key S/R levels carry significantly higher probability.
In ranging markets, decrease the Base ER Threshold to reduce whipsaws. In strongly trending markets, consider increasing it to filter out minor retracements.
TECHNICAL NOTES
The indicator does not repaint. Swing points require confirmation on the subsequent bar to print, ensuring signals remain fixed after formation.
All calculations utilize Pine Script v6 native functions for optimal performance and minimal resource usage.
The Volatility Normalization component prevents the common failure mode of static efficiency indicators during periods of expanding volatility.
Connecting lines for divergences are managed with automatic cleanup protocols to prevent chart clutter on extended runs.
SUPPORT AND UPDATES
This indicator is maintained by KeyAlgos. All users receive automatic updates as methodology improvements are implemented. For questions regarding parameter optimization or implementation strategies, utilize the TradingView comments section on this publication.
Disclaimer: This indicator is a technical analysis tool designed to assist with market analysis, not a guaranteed profit system. Always practice proper risk management and use stop losses. Past performance of indicator signals does not guarantee future results. Indicateur

Indicateur

Regime Classifier [JOAT]Regime Classifier
Introduction
The Regime Classifier is a sophisticated market state detection system designed to identify and classify market conditions into distinct operational regimes. Understanding the current market regime is perhaps the most critical factor in successful trading - a strategy that works beautifully in a trending market will fail miserably in a ranging market, and vice versa. This indicator solves that fundamental problem by providing clear, actionable classification of market states, allowing traders to adapt their approach to current conditions.
This tool is built for traders who understand that markets are not random but move through distinct phases, each requiring different strategies and risk management approaches. Whether you're a systematic trader needing regime filters, a discretionary trader seeking market context, or a portfolio manager adjusting exposure, this classifier provides the institutional-grade market intelligence needed to navigate any market environment successfully.
Why This Indicator Exists
Most traders apply the same strategy regardless of market conditions, then wonder why their performance is inconsistent. This indicator addresses that critical flaw by:
Regime Classification: Identifies four distinct market states with clear characteristics
Regime Strength: Measures how strongly the market exhibits regime characteristics
Regime Persistence: Tracks how long the current regime has been in place
Regime Quality: Evaluates the reliability of the current regime classification
Session Awareness: Considers session context for regime analysis
Regime Transitions: Detects and signals regime changes for strategy adaptation
The classifier transforms the complex, often subjective process of market analysis into an objective, systematic framework that can be consistently applied across all instruments and timeframes.
Core Components Explained
1. ADX-Based Trend Detection
The Average Directional Index (ADX) is the primary tool for trend detection:
// ADX calculation
float atr_val = ta.rma(ta.tr(true), i_adx_period)
float up_move = high - high
float down_move = low - low
float plus_dm = up_move > down_move and up_move > 0 ? up_move : 0
float minus_dm = down_move > up_move and down_move > 0 ? down_move : 0
float plus_di = 100 * ta.rma(plus_dm, i_adx_period) / atr_val
float minus_di = 100 * ta.rma(minus_dm, i_adx_period) / atr_val
float adx = 100 * ta.rma(math.abs(plus_di - minus_di) / (plus_di + minus_di), i_adx_period)
ADX components:
ADX Value: Trend strength (0-100), regardless of direction
+DI: Bullish directional movement
-DI: Bearish directional movement
Trend Threshold: Minimum ADX for trend classification (default 25)
Directional Bias: +DI vs -DI for trend direction
ADX above 25 indicates a trending market, while below 25 suggests ranging or volatile conditions.
2. ATR-Based Volatility Analysis
The Average True Range (ATR) measures volatility and helps distinguish between different non-trending states:
// ATR analysis
float atr_current = ta.atr(i_atr_period)
float atr_average = ta.sma(atr_current, i_atr_period * 3)
float atr_ratio = atr_average > 0 ? atr_current / atr_average : 1.0
// Volatility thresholds
float expansion_threshold = i_atr_expansion_mult
float contraction_threshold = i_atr_contraction_mult
ATR components:
Current ATR: Recent volatility measurement
Average ATR: Long-term volatility baseline
ATR Ratio: Current volatility relative to average
Expansion Threshold: Ratio indicating high volatility (default 1.4)
Contraction Threshold: Ratio indicating low volatility (default 0.6)
ATR analysis helps distinguish between ranging (low volatility) and volatile (high volatility) markets when ADX is below the trend threshold.
3. Regime Classification Logic
The indicator classifies markets into four distinct regimes:
// Regime classification
int market_regime = 0
if adx >= i_adx_trend
market_regime := 1 // Trending
else if atr_ratio >= expansion_threshold and adx < i_adx_trend
market_regime := 3 // Volatile
else if atr_ratio <= contraction_threshold and adx < i_adx_trend
market_regime := 2 // Ranging
else
market_regime := 0 // Neutral
Regime types:
Trending (ADX ≥ 25): Strong directional movement with clear trend
Ranging (ADX < 25, ATR ratio ≤ 0.6): Low volatility, sideways movement
Volatile (ADX < 25, ATR ratio ≥ 1.4): High volatility, erratic movement
Neutral (ADX < 25, 0.6 < ATR ratio < 1.4): Transition between defined states
Each regime has distinct characteristics that require different trading approaches.
4. Regime Strength Measurement
Not all regimes are created equal - some are stronger and more reliable than others:
// Regime strength calculation
float regime_strength = 0.0
switch market_regime
1 => regime_strength := math.min(adx / 50.0 * 100, 100) // Trending strength
2 => regime_strength := math.min((1 - atr_ratio) / (1 - contraction_threshold) * 100, 100) // Ranging strength
3 => regime_strength := math.min((atr_ratio - 1) / (expansion_threshold - 1) * 100, 100) // Volatile strength
0 => regime_strength := 50.0 // Neutral default
Strength interpretation:
Trending Strength: Based on ADX value (higher ADX = stronger trend)
Ranging Strength: Based on how low volatility is (lower ATR = stronger range)
Volatile Strength: Based on how high volatility is (higher ATR = stronger volatility)
Neutral Strength: Fixed at 50% as baseline
Strength Range: 0-100% indicating regime confidence
Higher strength values indicate more reliable regime classification.
5. Regime Persistence Analysis
The duration of a regime provides additional context about its reliability:
// Regime persistence tracking
var int regime_bars = 0
var int regime_start_bar = 0
if market_regime == market_regime
regime_bars := regime_bars + 1
else
regime_bars := 1
regime_start_bar := bar_index
// Persistence score
float persistence_score = math.min(float(regime_bars) / i_persistence_lookback * 100, 100)
Persistence features:
Regime Bars: Number of consecutive bars in current regime
Regime Start: When the current regime began
Persistence Score: Normalized duration (0-100%)
Lookback Period: Reference period for normalization (default 50)
Mature Regimes: Higher persistence indicates established conditions
Long-lasting regimes are more reliable than newly formed ones.
6. Regime Quality Assessment
Quality evaluates how well the current market fits the regime characteristics:
// Quality assessment
float quality_score = 0.0
float adx_quality = adx / 50.0 * 50 // 50% weight
float atr_quality = market_regime == 2 ? (1 - atr_ratio) / (1 - contraction_threshold) * 50 :
market_regime == 3 ? (atr_ratio - 1) / (expansion_threshold - 1) * 50 : 25
quality_score := adx_quality + atr_quality
Quality components:
ADX Quality: How well trend strength matches regime expectations
ATR Quality: How well volatility matches regime expectations
Quality Score: Combined assessment (0-100%)
High Quality: Clear regime characteristics
Low Quality: Ambiguous or transitioning conditions
High quality scores indicate clear, unambiguous market conditions.
7. Session Context Integration
Market behavior varies significantly across trading sessions:
// Session analysis
bool asian_session = time(timeframe.period, "0000-0800")
bool london_session = time(timeframe.period, "0700-1600")
bool ny_session = time(timeframe.period, "1200-2100")
// Session-specific adjustments
float session_multiplier = 1.0
if london_session
session_multiplier := 1.2 // Higher volatility expected
else if asian_session
session_multiplier := 0.8 // Lower volatility expected
Session features:
Session Detection: Identifies major trading sessions
Session Multipliers: Adjusts expectations based on session characteristics
Session Persistence: Tracks regime duration within current session
Session Quality: Evaluates regime quality within session context
Session Transitions: Identifies regime changes at session opens/closes
Session context helps interpret regime changes and anticipate behavior.
Visual Elements
Regime Histogram: Color-coded bars showing current regime
Strength Meter: Visual representation of regime strength
Persistence Line: Shows regime duration over time
Quality Gauge: Quality score visualization
Background Colors: Regime-based background shading
Session Markers: Visual session boundaries
Dashboard: Real-time regime metrics
Transition Alerts: Visual regime change notifications
The dashboard displays:
1. Current market regime and confidence
2. Regime strength and persistence
3. Quality score and trend direction
4. Session context and behavior
5. Regime history and transitions
6. Recommended strategies for current regime
7. Risk management adjustments
8. Regime forecast based on patterns
Input Parameters
ADX Settings:
ADX Period: Trend strength calculation (default: 14)
Trend Threshold: Minimum ADX for trend regime (default: 25)
ADX Smoothing: Additional smoothing for ADX (default: 3)
ATR Settings:
ATR Period: Volatility calculation (default: 14)
Expansion Multiplier: High volatility threshold (default: 1.4)
Contraction Multiplier: Low volatility threshold (default: 0.6)
Analysis Settings:
Persistence Lookback: Reference for persistence score (default: 50)
Quality Smoothing: Smoothing for quality calculation (default: 5)
Session Awareness: Enable session analysis (default: true)
Visual Settings:
Color Scheme: Customizable regime colors
Background Shading: Enable regime backgrounds
Dashboard Display: Show metrics panel
Alert Settings: Configure regime change alerts
How to Use This Indicator
Step 1: Identify Current Regime
Check the dashboard for the current market regime. Each regime requires a different approach:
Trending: Use trend-following strategies, let winners run
Ranging: Use mean-reversion strategies, take profits at levels
Volatile: Reduce position size, use wider stops, or avoid trading
Neutral: Wait for clarity, reduce trading activity
Step 2: Assess Regime Strength
Higher strength indicates more reliable conditions. In strong regimes (80%+), you can be more aggressive with position sizing. In weak regimes (<50%), reduce exposure and wait for confirmation.
Step 3: Monitor Persistence
Newly formed regimes (<10 bars) may be false signals. Mature regimes (>20 bars) are more established and reliable. Consider regime persistence in your strategy selection.
Step 4: Evaluate Quality
High quality scores (>75%) indicate clear market conditions. Low quality scores (<50%) suggest ambiguity - reduce trading or wait for clarity.
Step 5: Consider Session Context
Regimes that persist across multiple sessions are more significant. Regime changes at session opens often set the tone for the session.
Step 6: Watch for Transitions
Regime transitions signal strategy changes. A shift from trending to ranging requires switching from trend-following to range-bound strategies.
Best Practices
Always adapt your strategy to the current regime - don't use a trending strategy in ranging markets
High strength + high quality = maximum confidence in regime classification
Low persistence regimes (<10 bars) may be false - wait for confirmation
Session transitions often trigger regime changes - be alert at session opens
Volatile regimes are dangerous for most traders - consider reducing activity
Regime persistence is key - the longer a regime persists, the more reliable it is
Quality scores below 50% suggest waiting for clarity
Combine regime analysis with your existing strategy for better results
Keep a regime journal to track how each instrument behaves in different regimes
Use regime transitions as signals to adjust your entire trading approach
Strategy Applications by Regime
Trending Regime:
Trend-following strategies (moving averages, ADX, momentum)
Let winners run to maximum targets
Use trailing stops to capture extended moves
Add to positions on pullbacks in trend direction
Higher position sizing due to clear direction
Ranging Regime:
Mean-reversion strategies (RSI, Stochastic, Bollinger Bands)
Take profits at support/resistance levels
Use fixed targets - don't let winners turn into losers
Fade extreme moves toward the range middle
Smaller position sizing due to limited moves
Volatile Regime:
Reduce position size significantly (50% or less)
Use wider stops to avoid premature exits
Consider sitting out until conditions improve
Focus on volatility breakout patterns if trading
Quick profit taking - volatile conditions reverse quickly
Neutral Regime:
Wait for clarity before taking new positions
Manage existing positions more actively
Reduce trading frequency
Look for regime transition signals
Focus on longer timeframe analysis for direction
Technical Implementation
Built with Pine Script v6 featuring:
Advanced ADX calculation with directional movement analysis
Multi-timeframe ATR analysis for volatility assessment
Regime classification with confirmation logic
Strength, persistence, and quality scoring systems
Session awareness with timezone handling
Comprehensive visualization with multiple display modes
Real-time dashboard with 10 key metrics
Alert conditions for regime changes and thresholds
Export functions for strategy integration
Historical regime tracking and pattern recognition
The code uses confirmed bars for all calculations to prevent repainting and ensure reliable regime classification.
Originality Statement
This indicator is original in its comprehensive approach to regime classification and market state analysis. While ADX and ATR are established tools, this indicator is justified because:
It synthesizes trend and volatility analysis into a unified regime classification system
The strength, persistence, and quality scoring provides multi-dimensional regime assessment
Session awareness adds critical context often missing from regime analysis
Regime transition detection helps traders adapt strategy changes proactively
The four-regime classification (Trending, Ranging, Volatile, Neutral) covers all market states
Quality assessment helps distinguish between clear and ambiguous market conditions
Persistence analysis identifies mature, reliable regimes versus new, potentially false ones
Comprehensive visualization makes complex regime analysis accessible and actionable
Export functions enable regime-based strategy filtering and adaptation
Each component provides unique insights: ADX shows trend, ATR shows volatility, strength shows conviction, persistence shows duration, and quality shows clarity
The indicator's value lies in transforming the abstract concept of "market conditions" into concrete, actionable classifications that traders can use to adapt their strategies systematically and consistently.
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. Regime classification is a tool for understanding market conditions, not a prediction system.
Market regimes can change suddenly due to news events, economic data, or changes in market structure. Past regime behavior does not guarantee future patterns. The indicator's classifications are mathematical calculations based on historical patterns and should be used in conjunction with other forms of analysis.
Always use proper risk management, including stop losses and position sizing appropriate for current market conditions. Different regimes require different risk approaches - volatile regimes may require smaller positions and wider stops.
The author is not responsible for any losses incurred from using this indicator. Users assume full responsibility for all trading decisions made using this system.
-Made with passion by officialjackofalltrades
Indicateur

VIX-VIXEQ Regime DetectorThe VIX-VIXEQ Regime Detector is an market structure indicator that compares the CBOE Volatility Index (VIX) with the CBOE S&P 500 Equal Weight Volatility Index (VIXEQ) to identify distinct market volatility regimes.
It analyses the relationship between index-level and constituent-level volatility, and helps investors to detect regime changes that often precede major market moves.
Credits: Idea suggested by @m_chromatic Thanks a lot!
What It Measures
VIX measures implied volatility of S&P 500 index options (cap-weighted, dominated by mega-cap stocks)
VIXEQ measures implied volatility of equal-weighted S&P 500 constituents (reflects broader market volatility)
The ratio between these two metrics reveals whether volatility is concentrated in mega-caps or dispersed across the broader market.
When VIXEQ rises faster than VIX (ratio > 1.0), it indicates that constituent stocks are experiencing higher volatility than the index itself. This divergence often signals:
Increased market stress
Breakdown in correlation
Potential regime transitions
Mean reversion opportunities
Five Market Regimes in the Indicator
The indicator uses adaptive thresholds based on rolling statistics to classify markets into five distinct regimes:
🔵 CONCENTRATION (Ratio < threshold): Mega-cap dominance, Low dispersion, Healthy market structure
🟢 NORMAL (Ratio near mean): Balanced volatility, Healthy market conditions, Standard risk environment
🟡 ELEVATED (Ratio moderately above mean), Early warning signal, Rising constituent stress, Watch for deterioration
🟠 DISPERSION (Ratio significantly above mean), Broad market stress, Elevated constituent volatility, Defensive positioning warranted
🔴 SYSTEMIC (Ratio > 1.5σ above mean), Crisis conditions, Extreme constituent stress, High mean reversion potential
The indicator includes z-score calculations to measure how extreme the current spread is relative to historical norms.
Recommended Timeframe
Daily (1D): Optimal for most use cases - balances signal quality with responsiveness
Weekly (1W): For macro positioning and long-term regime context
4-Hour: Not recommended - too noisy for structural regime analysis
Technical Notes
Uses request.security() to fetch VIX and VIXEQ data
Ratio is scaled by (ratio - 1) × 10 for chart visibility alongside spread
Actual ratio values are displayed in the table and labels
Adaptive thresholds recalculate on every bar based on rolling statistics
All regime classifications update in real-time
Indicateur

Indicateur

HMM Enhanced: Regime ProbabilityHMM Enhanced: Regime Probability
Most technical indicators tell you what price has already done. This one asks a different question entirely: what kind of market are we probably in right now?
The HMM Enhanced: Regime Probability indicator applies a Bayesian Hidden Markov Model to three independently constructed market features, producing a real-time probability estimate for three market regimes — Bullish, Bearish, and Chop. It runs directly on the price chart as an overlay, colours your bars by the dominant regime and its confidence, and plots the adaptive trend engine's basis and trailing level so you can see the model's inputs on the chart. A compact dashboard shows the live probability split at all times.
1. What Is a Hidden Markov Model?
A Hidden Markov Model is a statistical framework for reasoning about systems that switch between a small number of underlying states — states that can't be observed directly, but leave traces in the data we can observe.
The "hidden" part is the key insight. In financial markets, the true regime — whether the market is in a trending, ranging, or volatile state — is never directly visible. We can't look at a price bar and read off "this is a bull regime bar" the way we'd read a closing price. What we can observe are things like price's distance from a trend reference, the slope of a moving average, and the strength of directional movement. An HMM uses these observable signals to continuously estimate the probability that the hidden state is X versus Y versus Z.
The model has three core components:
States — the hidden regimes (here: Bull, Bear, Chop).
Emission distributions — for each state, a probability distribution over what the observable signals tend to look like when that state is active. In this indicator, those are Gaussian (normal) distributions parameterised by a mean and standard deviation for each of the three features.
Transition matrix — the probability of moving from one regime to another between bars. This encodes the "stickiness" of regimes: a trending market doesn't instantly flip to choppy on a single bad bar.
Each bar, the forward algorithm combines the previous regime probabilities (propagated through the transition matrix) with the likelihood of today's observations under each regime's emission model, and normalises to produce a fresh posterior probability for each state. This is sequential Bayesian inference: every bar is an update step.
Baum-Welch and Why This Indicator Takes a Different Approach
In a fully trained HMM, the emission parameters (the means and variances that define what each regime "looks like") would be estimated from historical data using the Baum-Welch algorithm — an Expectation-Maximisation procedure that iterates forward and backward passes over the full training set until the parameters converge to a locally optimal fit. Baum-Welch is the textbook solution, but it has a practical limitation in a live trading context: it requires a fixed training window, it's computationally heavy to run on every new bar, and it can produce a model that's well-fitted to its training period but struggles on new market conditions.
This indicator uses a different approach: online dominant-state EM. The emission parameters start from carefully designed prior values (described below) and then update incrementally each bar — but only for whichever state currently has a posterior probability above 50%. This means the model adapts continuously to the instrument and timeframe you're trading, without the need for a training phase, without look-ahead, and without the risk of a single regime's parameters drifting toward another's.
HMMs in Trading — What They Show and Why They're Useful
Markets don't behave the same way all the time. A momentum strategy that performs brilliantly in a trending regime will bleed in chop; a mean-reversion strategy that thrives in ranging markets gets destroyed in a sustained trend. Regime detection is the discipline of figuring out which kind of market you're in before committing to a strategy.
HMMs are particularly well-suited to this problem because:
They're probabilistic, not binary. Instead of telling you "it's a bull market," they tell you "there's a 72% probability this is a bull regime." That distinction matters enormously for position sizing, risk management, and knowing when to wait.
They have memory. The transition matrix means the model can't flip on a single bar. If it called Bull last bar with 80% confidence, it takes sustained evidence to shift that.
The states are inferred, not defined by rules. There's no arbitrary threshold like "above the 200MA = bull." The model learns what each regime looks like in terms of the underlying feature distribution.
2. What This Indicator Does
At its core, this indicator runs a three-state Gaussian HMM using three z-scored features derived from an adaptive trend engine. Each bar it outputs a probability for Bull, Bear, and Chop. The dominant state colours the bars, the probabilities populate the dashboard, and the trend engine's basis and trailing level are plotted directly on the price chart so the model is fully transparent.
The Three Features
All three features are z-scored against a rolling window before entering the model, so they sit on a common scale regardless of instrument or timeframe.
Feature 1 — Trend Position: (close − trailing_level) / ATR14, then z-scored. The trailing level is a ratcheting ATR band around a dual-MA midline — it only moves in the trend's favour, which filters out noise. Price well above the level is strong bull evidence; well below is bear evidence; near the level suggests indecision or chop.
Feature 2 — Basis Slope: The rate of change of the dual-MA midline, ATR-normalised and z-scored. This measures whether the trend reference itself is rising or falling, and how fast. A slow grind higher reads differently from a sharp spike, and both read differently from a flat midline.
Feature 3 — ADX Strength: Z-scored ADX. ADX rises when the market is trending in either direction and falls when it's ranging. The bull and bear emission priors for this feature are identical (+0.5) because ADX is directionless — it only distinguishes trending from ranging. Chop gets a negative ADX prior (−0.5) to reflect that ranging markets have below-average directional strength.
The Adaptive Trend Engine
The trend basis is a dual-MA midline: the average of a fast MA and a slow MA (at 2× the fast length), smoothed using your choice of MA type.
The trailing level sits at an ATR band below the basis during uptrends and above it during downtrends. With the Min/Max Ratchet enabled, the level can only move in the trend's favour — it won't retreat on a retracement bar, which significantly reduces whipsaw flips. The basis and trailing level are plotted on your price chart, coloured by the current dominant regime.
Emission Parameter Design
The prior means are set symmetrically so neither bull nor bear is favoured at initialisation:
FeatureBullBearChopTrend Position+1.0−1.00.0Basis Slope+0.7−0.70.0ADX Strength+0.5+0.5−0.5
The standard deviations start at 1.0 and adapt via learning. Bull and Bear are exact mirrors — there is no directional bias baked into the model.
Transition Matrix Structure
The off-diagonal transition probabilities are asymmetric by design. When the model exits a Bull or Bear regime, 80% of the exit probability routes through Chop — not directly to the opposite regime. This reflects the realistic observation that markets rarely flip directly from trending up to trending down without a period of consolidation first. Exits from Chop are split 50/50 to Bull and Bear.
3. How This Differs From Other HMM Indicators on TradingView
Several HMM indicators exist on TradingView. Here's how this one is different:
vs. Static emission parameters: Most HMM indicators on TradingView use fixed emission parameters — the model's definition of what each regime "looks like" is set at publication and never changes. This indicator adapts its emission parameters online via dominant-state EM learning, so the model continuously calibrates to what Bull, Bear, and Chop actually look like on your specific instrument and timeframe.
vs. Separate pane oscillators: The majority of HMM indicators on TradingView run as subplot oscillators showing regime probabilities in a separate pane. This indicator runs as a price chart overlay — the trend engine that generates the model's primary features is plotted directly on your bars, so the model's inputs are always visible alongside its outputs.
vs. Momentum and volatility features: Several published HMM indicators use raw price returns, rate-of-change, or historical volatility as their observation features. This indicator uses a purpose-built adaptive trend engine instead — specifically the distance from a ratcheting trailing level and the slope of a dual-MA basis. These are more directly connected to trend structure than raw returns or volatility measures, and the ratcheting mechanism filters out pullback noise before the feature ever reaches the model.
vs. Full Baum-Welch training: Some implementations use full Baum-Welch EM on a fixed lookback window, which requires a defined training period and can introduce look-ahead bias if not implemented carefully. This indicator uses only causal bar-by-bar forward updates — it never looks ahead and has no training window.
vs. Volume-based features: Some indicators incorporate volume ratio as an observation feature. This indicator deliberately avoids volume — volume data is unreliable, inconsistent, or entirely absent on many instruments and timeframes (particularly forex and synthetic indices). All three features are built purely from price structure.
The key differentiators in summary:
Adaptive online learning — emission parameters update every bar on the dominant state, no training window required
Purpose-built trend engine features — trend position and basis slope capture trend structure more precisely than raw returns
Overlay on price chart — the trend engine is visible alongside the probability output
Asymmetric transition matrix — regime exits route through chop before flipping, reducing false direct reversals
Emission temperature control — softens the model's decisiveness to avoid overconfident calls on noisy data
Adaptive MA basis combined with ADX to identify trend
4. Configuration & Inputs
1. Adaptive Trend Engine (big thanks to @Crak_Trading for his excellent Adaptive Trend indicator
Source — Price input for the trend engine. Default is HLC3 (a noise-reduced proxy for the bar's "true price"). You can change this to Close, HL2, or any other source.
Adaptive Length — The period for the fast MA. The slow MA is automatically set to 2× this value. The basis is the midpoint of the two. Shorter = more responsive, more noise. Longer = smoother, more lag. 20 is a balanced default for most timeframes.
Smoothing — Period for the ATR band smoothing. Controls how quickly the band width responds to changes in volatility. Higher = slower, smoother bands.
Band Multiplier — Width of the ATR band around the basis. Higher values require price to move further from the basis before a trend flip occurs, reducing whipsaw at the cost of more lag on genuine reversals.
Band Type — How the band width is calculated. True Range (default) uses the average of the bar's true range, which is sensitive to gaps. ATR uses the standard 14-period ATR. StDev uses the rolling standard deviation of price, which responds faster to volatility spikes.
MA Type — The moving average used for the basis calculation. Various options (EMA, SMA, WMA, HMA, RMA) are available for comparison.
Use Min/Max Ratchet — When enabled, the trailing level can only move in the direction of the current trend. In an uptrend it can only rise; in a downtrend it can only fall. This prevents the level from retreating on retracement bars and significantly reduces false trend flips.
2. ADX Settings
DMI Length — The lookback for the DI+ and DI− directional movement calculations. 14 is the standard Wilder setting.
ADX Smoothing — Smoothing period for the ADX line itself. 14 is standard. Higher values produce a smoother, slower-reacting ADX.
Z-Score Lookback — The rolling window used to z-score all three features. A longer window produces a more stable baseline and makes the z-scores less sensitive to recent volatility changes. 50 bars is a reasonable default; increase to 100+ for higher timeframes.
3. Transition Matrix
P(Bull | Bull) — The probability that the market stays in a Bull regime from one bar to the next. Higher values make bull regimes stickier and slower to exit. 0.80 is the default, meaning an 80% chance of remaining bull each bar. The remaining 20% is split: 80% routes to Chop, 20% routes directly to Bear.
P(Bear | Bear) — Same as above for the Bear regime.
P(Chop | Chop) — The probability of remaining in Chop. Set lower by default (0.60) because choppy periods tend to resolve faster than trends persist. When Chop exits, the probability is split 50/50 to Bull or Bear.
Note: Higher persistence values increase regime stability but slow the model's response to genuine regime changes. Lower values make it more reactive but noisier.
4. Adaptive Learning
Enable Adaptive Learning — When on, the emission means and standard deviations update incrementally each bar for whichever regime currently has >50% posterior probability. Over time, the model calibrates to what Bull, Bear, and Chop actually look like on your instrument. When off, the parameters stay fixed at their initial prior values.
Learning Rate — Controls the speed of adaptation. 0.05 (default) is slow and stable — good for most use cases. Values around 0.10–0.15 adapt faster but produce noisier parameter estimates. Values above 0.20 should be used with caution as they can cause the emission distributions to drift away from their priors quickly on anomalous bars.
Min Emission Std Dev — A floor on the emission standard deviation. Prevents the Gaussian distributions from collapsing to near-zero width, which would make the model pathologically confident and brittle. 0.3 is a safe default.
5. HMM Settings
Emission Temperature — A softening parameter applied to the raw emission likelihoods before the HMM update. At temperature 1.0, the likelihoods are used as-is, which can produce very sharp, confident regime calls. Higher values (default 2.0) flatten the differences between regimes' likelihoods, keeping probabilities in a more realistic 50–70% range for clear signals rather than snapping to 90%+. Think of it as a confidence dampener — useful on noisy instruments or timeframes where overconfident calls are common.
6. Visuals
Show Basis / Show Trailing Level — Toggle the dual-MA midline and ratcheting trailing level plots on the price chart.
Basis / Trail Line Width — Line thickness for each plot.
Color Transition Speed — Controls the smoothing of bar colour transitions between regime changes. Lower values (closer to 0) produce very gradual colour transitions; higher values (closer to 1.0) make colour changes near-instant. 0.4 is the default for a natural-looking blend.
Bull / Bear / Chop Weak & Strong colours — Each regime has a gradient from a "weak" colour (lower confidence) to a "strong" colour (high confidence). Bars are coloured by the dominant regime's probability within that gradient. The same colours are used for the basis line.
Table Position — Where the dashboard appears on the chart. All eight TradingView anchor positions are available.
Table Text Size — Four sizes: Tiny, Small (default), Normal, Large. The regime label row (BULLISH / BEARISH / CHOP) automatically renders one step larger than the body text for visual hierarchy.
5. The Dashboard — How to Read It
The dashboard table shows the model's current state in real time. All values update on the close of each bar.
Row: What It Shows
REGIME: The dominant state: BULLISH, BEARISH, or CHOP. Coloured by the current bar colour.CONFIDENCEThe probability of the dominant state, followed by HIGH (>65%), MED (>50%), or LOW (≤50%).
P(BULL): Probability the market is currently in a Bull regime, as a percentage.
P(BEAR): Probability of Bear regime.
P(CHOP): Probability of Chop regime.sig B/Br/CThe current emission standard deviations for Bull, Bear, and Chop respectively, followed by LRN (learning enabled) or FIX (fixed).
How to Use the Confidence Tiers
HIGH confidence (>65%) — The model has a strong view. The dominant regime's probability is well above the other two. This is when the signal is most actionable as a strategy filter.
MED confidence (50–65%) — The model has a lean but not a strong conviction. One regime is leading but the others are not far behind. Use as context rather than a hard filter.
LOW confidence (≤50%) — The three probabilities are close together. The model is genuinely uncertain. This is not a failure state — it's an honest reflection of ambiguous market conditions. Avoid relying on it as a filter until confidence improves.
The sig B/Br/C Row
This row shows the adaptive emission standard deviations for each regime. At startup, all three are 1.0. As the model learns:
Values shrinking toward the floor (default 0.3) mean the model is seeing consistent, tight feature values in that regime — it has a precise picture of what it looks like.
Values staying near 1.0 or above mean the regime is observing noisy, inconsistent feature values — the model has a broad, uncertain picture of it.
If Bull and Bear sigmas drift far apart, it may indicate one regime has been much more prevalent than the other, and you may want to reset the indicator or consider whether your instrument is structurally one-sided on your chosen timeframe.
As a Strategy Filter
This indicator is not designed to generate buy and sell signals on its own. It is designed to tell you what kind of strategy is appropriate right now:
BULL dominant (HIGH/MED): Favour trend-following long setups. Momentum indicators and breakout strategies are in their element. Ignore oversold signals from oscillators.
BEAR dominant (HIGH/MED): Favour trend-following short setups or defensive positioning. Overbought oscillator signals can be ignored.
CHOP dominant or LOW confidence: Trend-following strategies are likely to churn. Consider mean-reversion approaches, tighter stops, reduced position sizes, or standing aside entirely.
Alerts
Three alert conditions are included, all non-repainting (they trigger on confirmed bar closes only):
HMM: Regime → BULLISH — The dominant regime has shifted to Bull.
HMM: Regime → BEARISH — The dominant regime has shifted to Bear.
HMM: Regime → CHOP — The dominant regime has shifted to Chop.
This indicator is open-source. The code is fully commented and structured to be readable, developed and aid learning for all users Indicateur

Ultimate RegimeUltimate Regime | MisinkoMaster
Ultimate Regime is an advanced market environment classification tool designed to identify whether an asset is currently operating in a trending or mean-reverting regime. Instead of focusing on entry signals, the indicator concentrates on answering a more fundamental question: what type of market are we trading right now?
By continuously evaluating market structure, volatility behavior, and directional persistence, the script provides a unified regime view that helps traders adapt strategy selection, risk management, and trade expectations to current conditions.
This makes Ultimate Regime particularly valuable for traders using multiple systems, algorithmic frameworks, or discretionary approaches that perform differently depending on market state.
Core Concept
Markets alternate between expansion phases where directional movement dominates and contraction phases where price oscillates around equilibrium. Strategies built for one condition often underperform in the other.
Ultimate Regime solves this by aggregating several environment measurements into a single regime score that expresses whether the market currently favors:
• Trend continuation strategies
• Breakout participation
• Momentum trading
or instead
• Range trading
• Mean reversion strategies
• Oscillation-based setups
The indicator therefore acts as a decision filter rather than a trade trigger.
Key Features
Unified regime classification combining multiple market characteristics
Automatic detection of trending vs mean-reverting environments
Smooth regime transitions to reduce noise and false flips
Visual histogram representing regime strength
Automatic chart candle coloring based on environment
On-chart regime change labeling for clarity
Configurable lookback and smoothing controls
Works across all timeframes and asset classes
Suitable for discretionary and systematic traders
Designed for integration into multi-indicator workflows
How It Works (Conceptual)
Instead of relying on a single measurement, Ultimate Regime evaluates several dimensions of market behavior simultaneously, such as:
• Price expansion versus contraction
• Volatility shifts
• Directional persistence
• Structural movement characteristics
These components are normalized and combined into a composite regime value. The result is then smoothed to ensure regime changes reflect genuine environment shifts rather than short-term fluctuations.
When the combined regime value turns positive, the market is considered to favor directional movement. When it turns negative, price behavior favors oscillation and mean reversion.
The internal weighting and transformation methods remain proprietary in the invite-only version.
Regime States Explained
Trending Regime
Indicates directional dominance where price tends to move persistently in one direction. Momentum and breakout systems typically perform better under these conditions.
Mean Reverting Regime
Indicates oscillatory behavior where price frequently returns toward equilibrium zones. Range strategies and reversal setups often become more effective.
Neutral Transitions
Short transition periods may occur during regime changes as the environment reorganizes before committing to a dominant state.
Visual Components
Regime Histogram
A histogram displays regime strength and direction, making it easy to gauge whether trending or reverting behavior dominates.
Colored Candles
Price candles automatically change color according to regime classification, allowing instant environment recognition directly on the chart.
Regime Change Labels
Labels appear when regime shifts occur, helping traders visually track transitions between trending and mean-reverting phases.
Reference Thresholds
Visual guide levels help users understand regime extremes and neutral zones.
Inputs Overview
Source
Selects the price data used for regime analysis.
High-Low Difference Lookback
Controls how far back structural price expansion is evaluated.
ATR Lookback
Adjusts how volatility expansion or contraction is measured.
Standard Deviation Lookback
Defines the evaluation window for statistical price dispersion.
ADX Lookback
Controls directional persistence measurement sensitivity.
Smoothing Period
Applies smoothing to regime calculations, balancing responsiveness and stability.
Higher smoothing reduces noise but delays regime changes. Lower smoothing reacts faster but may increase regime flipping.
Usage Guidelines
Use Ultimate Regime as a strategy filter rather than a direct entry signal.
Trending regime environments generally favor:
• Breakout systems
• Momentum entries
• Trend-following approaches
• Pullback continuation trades
Mean-reverting environments generally favor:
• Range trading
• Support and resistance reversals
• Oscillation strategies
• Counter-trend setups
Regime analysis works best when combined with entry and risk tools rather than used standalone.
Practical Applications
Strategy selection switching between trend and range systems
Position sizing adjustments based on environment strength
Filtering trades that conflict with prevailing market behavior
Algorithmic system optimization
Portfolio regime monitoring
Timeframe alignment analysis
Parameter Tuning Notes
Lower lookback values increase responsiveness but may produce faster regime changes.
Higher lookback values stabilize regime detection for swing or position trading.
Short smoothing periods work better for intraday trading.
Longer smoothing periods help long-term traders avoid noise.
Optimal settings vary by asset volatility and timeframe.
Best Practices
Combine regime detection with price structure and confirmation tools.
Avoid forcing trend systems in reverting environments and vice versa.
Use regime awareness to improve trade selection discipline.
Backtest strategies separately for trending and mean-reverting periods.
Summary
Ultimate Regime provides a structured and adaptive view of market conditions by classifying whether the environment favors trend continuation or mean reversion. By separating environment analysis from trade signals, traders gain clarity in strategy selection and improve consistency across changing market conditions.
The invite-only version preserves proprietary calculation methods while delivering a robust regime detection framework suitable for discretionary traders, system developers, and algorithmic strategies alike. Indicateur

Hidden Markov Model Market Regimes [LuxAlgo]The Hidden Markov Model Market Regimes tool provides a probabilistic framework for identifying the current state of the market by applying a Hidden Markov Model (HMM) to price action and volatility data.
🔶 USAGE
The indicator identifies four distinct market regimes. Each regime is represented by a unique color, and the oscillator values (0-100%) represent the probability of the market being in that specific state.
🔹 Regime Breakdown & Trading Implications
Low Volatility Trend (Gray): Characterized by steady, consistent returns with minimal price swings. Ideal for trend-following strategies and "buy-and-hold" positions.
High Volatility Chop (Orange): Large price swings without a clear directional trend. Suggests a "risk-off" environment or mean-reversion strategies.
Crash Regime (Red): Extreme negative returns coupled with a spike in volatility. Indicates high panic; traders may look for hedging opportunities.
Accumulation (Blue): Low volatility with neutral-to-rounding price action. Often occurs at the end of a bear cycle, signaling a potential "bottom-fishing" zone.
🔹 Visual Cues
The indicator features background highlighting that changes based on the "Dominant State" (the state with the highest current probability).
When a specific probability line crosses above the 50% "Neutral" line, the model is gaining conviction. Crosses above 80% indicate "High Confidence" in that regime. Users should watch for "probability flips," where one regime's dominance is rapidly overtaken by another, signaling a structural shift in the market.
🔶 DETAILS
The script implements a specialized version of the Forward Algorithm to estimate the likelihood of hidden states.
🔹 Heuristic vs. Trained ML
It is important to note that this indicator is accurately described as a "Heuristic" or "Static" HMM rather than a traditional Machine Learning model. Unlike modern ML models that require extensive training on historical datasets (using algorithms like Baum-Welch or Expectation-Maximization), this model uses fixed mathematical parameters and predefined heuristic-based emission profiles.
This approach ensures deterministic behavior—the model will always react to the same price patterns in the same way—and eliminates the "black box" nature of traditional ML while still providing the probabilistic benefits of a Markov chain.
🔹 Mathematical Logic
Log Returns: The model utilizes log returns ( TSX:LN (Close_{t} / Close_{t-1})$) rather than simple percentage changes to ensure time-additivity and a more symmetric distribution of data.
Emission Likelihoods: The model uses Gaussian-style probability density functions to compare normalized returns and volatility against "ideal" profiles for each state. For example, the Crash Regime likelihood increases when returns are significantly below the mean and volatility is significantly above the mean.
Transition Matrix (Markov Property): This defines the "memory" of the system. The matrix is weighted toward "persistence" (diagonal values), meaning the market is statistically more likely to stay in its current regime than to jump to a different one every bar.
🔶 SETTINGS
🔹 HMM Settings
Lookback Period: The window used to calculate the mean and standard deviation for normalizing returns and volatility.
Learning Rate: Controls how quickly the model updates its internal probabilities. Range: 0.01 (very slow/stable) to 1.0 (instant/reactive).
🔹 Dashboard
Enable Dashboard: Toggles the visibility of the on-screen information table.
Position: Determines where the dashboard is anchored (Top Right, Bottom Right, or Bottom Left).
Size: Adjusts the scale of the dashboard text and cells.
Indicateur
