OPEN-SOURCE SCRIPT
Güncellendi

Regime Transition Intelligence [AGPro Series]

1 417
Regime Transition Intelligence [AGPro Series]

Most regime scripts answer a single question: "what regime are we in right now?". Regime Transition Intelligence is designed to answer a different, more actionable set of questions: how long does this regime usually last, how close to its typical end is it, how likely is it to flip within the next N bars, and where does it historically go when it does flip. Instead of treating the current regime as a standalone snapshot, it builds a living, self-calibrating statistical profile of the symbol's own regime behavior and presents it in a compact on-chart dashboard.

The engine runs on three independent axes — Trend Strength (Kaufman Efficiency Ratio + ADX), Chop Risk (Choppiness Index + inverse trend), and Volatility (ATR% normalized over a user-defined lookback). Each axis is classified as LOW / MID / HIGH, either with fixed 33/67 thresholds or with an adaptive percentile rank engine that learns the symbol's own statistical envelope over a rolling window. The three axes are then combined into a discrete regime state: TREND, MIXED, or RANGE / CHOP.


🟦 Overview / What it does

Regime Transition Intelligence is a single-pane overlay indicator that continuously classifies the market into one of three regimes and then layers a full transition intelligence stack on top of that classification:
- A per-regime dwell-time distribution learned from the chart's own completed regime blocks
- A Bayesian-style flip probability that answers "how likely is a regime change within the next N bars, given the current age"
- A 3x3 transition matrix that ranks the most likely next regime with a secondary fallback
- A fatigue score comparing the current regime's age to its historical mean (FRESH / MATURE / EXTENDED)
- A confidence decay tracker that shows whether conviction is BUILDING, STABLE, or FADING within the current regime block
- A compact history ribbon showing the last completed regime blocks with their durations
- Higher-timeframe alignment with a SYNC / DIV indicator and a live beacon at the right edge of the chart

All of this is delivered inside a single configurable dashboard, a directional transition marker layer on the chart, optional regime tint and candle coloring, and a right-edge beacon summarizing the current state.


🟣 Unique Edge / Why it is not a basic mashup

Standard regime indicators report the current state and stop there. Regime Transition Intelligence adds six distinct statistical layers that together form a transition-aware view:

1. Dwell Time Statistics — the script stores every completed regime block in a rolling array (configurable depth) and continuously updates running mean, running variance, running max, and running count per regime code. Statistics are only shown after a minimum number of blocks per regime have been collected, so the user always knows when the sample size is still too small.

2. Exponential Hazard Flip Probability — the baseline flip probability uses P(flip within H bars) = 1 - exp(-H / mean), a standard survival-analysis construction assuming constant hazard. The result is then fatigue-adjusted: if the current age is far above the historical mean, the probability is boosted; if the regime has just started, the probability is damped. The final value is capped at 95% to avoid certainty claims.

3. Transition Matrix — a 3x3 counter records every observed regime transition and is read as a conditional distribution: "given the current regime ends, which regime is it most likely to move to, and what is the runner-up". Both the top candidate and the secondary candidate are displayed with their percentages.

4. Fatigue Score — the ratio of the current age to the historical mean is bucketed into three zones (FRESH, MATURE, EXTENDED) using user-configurable thresholds. It tells the user whether the current regime is still in its early lifecycle or already past its typical end.

5. Confidence Decay Tracker — conviction in the current regime is sampled at the start of each new block and compared to the current conviction. The delta is classified as BUILDING, STABLE, or FADING, which gives an early read on whether the regime is strengthening or losing its grip.

6. History Ribbon — the last N completed regime blocks are compressed into a single compact line such as "C2·M4·C8·M1·M7*", where letters are regime codes and numbers are bar counts, with the current block marked by an asterisk. It gives immediate context on recent regime rhythm at a single glance.

None of these layers is a repackaged classic indicator. They are built on top of a trend / chop / volatility engine but deliver information that is categorically different from a simple "regime yes / no" readout.


🟢 Methodology / Conceptual data flow

1. Feature extraction. Kaufman Efficiency Ratio (net move over lookback divided by summed absolute moves) and normalized ADX are combined into a trend score. The Choppiness Index is normalized against its operating range and blended with inverse trend to produce a chop score. ATR as a percentage of price is normalized against its own lookback min/max to produce a volatility score.

2. Classification. Each score is mapped to LOW / MID / HIGH using either fixed thresholds (Static mode) or percentile rank over an adaptive lookback (Adaptive mode). The three bands are combined into a discrete regime state: TREND when trend is HIGH and chop is LOW, RANGE / CHOP when chop is HIGH, and MIXED otherwise.

3. Block tracking. Every time the regime state changes on a confirmed bar, the previous block is closed: its duration is pushed to a rolling history array and added to the running sum / sum-of-squares / count / max for its regime code. When the history array exceeds its configured depth, the oldest block is popped and its contribution is subtracted from the running totals, which keeps the statistics adaptive and non-expanding.

4. Transition matrix update. When a block closes into a new regime, the 3x3 counter is incremented at the corresponding cell, and the row total is incremented. The conditional distribution for the current regime is read from its row at display time.

5. Statistical outputs. Mean dwell, fatigue ratio, exponential-hazard flip probability, fatigue-adjusted flip probability, top and secondary next regimes, and confidence delta are all derived from the running state and rendered into the dashboard.

6. Higher-timeframe alignment. The same three-axis engine is run on a user-selected higher timeframe via request.security and compared against the current-timeframe regime; the result appears as SYNC or DIV in the header and as an optional HTF row in the dashboard.


🔔 Signals & Alerts / Interpretation

Regime Transition Intelligence is a state-mapping and statistical context tool rather than a directional buy / sell engine. The main on-chart events are:
- Regime Shift — fires when the regime state changes on a confirmed bar
- High Flip Probability — fires when the fatigue-adjusted flip probability crosses a high threshold
- Regime Fatigue Extended — fires on the transition into the EXTENDED fatigue zone
- Confidence Fading — fires on the transition into the FADING confidence zone

How to read the panel:
- Summary + Age tells the user which regime is active and how long it has been active.
- Dwell Context compares the current age to the historical mean in the form "age / mean · % of typical lifespan".
- Fatigue summarizes that comparison as FRESH, MATURE, or EXTENDED.
- Flip Probability reports the statistical odds of a regime change within the user-defined horizon.
- Next Likely names the most probable next regime with its percentage and a secondary fallback.
- Confidence and Conf Decay together tell the user whether the current read is reliable and whether conviction is rising or fading.
- History gives quick situational awareness of recent regime rhythm.

None of these rows should be interpreted as a trade instruction. They are a context layer meant to be combined with the user's own structure and entry framework.


🎛️ Key Inputs

Regime Engine Core — Trend Persistence Length, DMI/ADX Length, Chop Length, ATR Length, Volatility Normalize Lookback.
Adaptive Boundaries — Band Classification Mode (Adaptive / Static), Adaptive Lookback, Adaptive Low / High Percentile.
Transition Intelligence — Regime History Depth, Flip Probability Horizon, Min Blocks Before Stats Activate, Fatigue Fresh / Extended thresholds.
HUD — Display Mode (PRO / MINIMAL), HUD Position, Text Size, transparency controls, individual row toggles, history ribbon length.
Add-ons — Chart Regime Tint, Regime Candle Coloring (Soft / Strong), HTF Peek Timeframe, Transition Markers (location, cooldown, stagger, size, ATR offset), Live Regime Beacon (position, size, stats toggle).


🧭 How to use

1. Add the script to any chart and timeframe. The engine is tuned to work from 15m up to Daily; very low timeframes on illiquid instruments can produce unstable regime blocks and are not the intended use case.

2. Give the script time to collect blocks. Statistics stay in N/A until the configured minimum number of completed blocks per regime has accumulated. On a fresh chart or an illiquid instrument this is expected behavior, not a bug.

3. Read the dashboard top-down. Start with the three axis rows to understand the current market shape, then move to Summary and Age to see what is active and for how long, then use Dwell / Fatigue / Flip / Next Likely to place the current regime inside its historical distribution, and finally use Conf Decay and HTF to sanity-check reliability and alignment.

4. Treat EXTENDED fatigue and high flip probability as context, not as a reversal signal. Regimes can remain in the EXTENDED zone for a while before actually flipping; the statistical profile is descriptive, not deterministic.

5. Combine with structural context. The script does not know about support / resistance, order blocks, or news. It only knows about the symbol's own regime rhythm. Use it as a regime-aware filter on top of the user's existing framework.


⚠️ Limitations & Transparency

This is not a strategy and not a complete trading system. It does not predict price direction and does not generate buy or sell signals. All statistics are estimated from a rolling history of the chart's own regime blocks, so they are sensitive to the chosen engine parameters, the timeframe, and the symbol; different timeframes and different instruments will produce different statistical profiles, and that is by design.

The exponential-hazard flip probability assumes a constant hazard within the current regime, which is a simplification. Real-world regime durations are not perfectly memoryless and the fatigue multiplier is a heuristic correction, not a formal model. The probability is capped at 95% on purpose, because even a heavily aged regime cannot be considered a certainty and the script deliberately avoids certainty language.

The transition matrix is read as a conditional frequency over completed blocks; it is informative about the symbol's own past behavior and should not be interpreted as a forward-looking forecast. Very small samples produce unstable conditional probabilities, which is why stats stay in N/A until a minimum number of blocks is collected.

Regime classification itself reacts to confirmed bars and can change as new data arrives, which is expected for any regime filter. Users who prefer fully non-repainting alerts should rely on the barstate.isconfirmed-gated alert conditions provided.


📜 Risk Disclosure

Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. This indicator is provided for educational and analytical purposes only and should not be interpreted as financial advice, an investment recommendation or a solicitation to trade. Always combine multiple forms of analysis, manage position size responsibly, and never risk capital you cannot afford to lose.
Sürüm Notları
🔧 UPDATE NOTES - 1.2

This update focuses on chart readability, panel structure, visual hierarchy, and publication-grade usability.

The core purpose of the script remains unchanged.
This release improves how the existing regime-transition logic is presented, organized, and interpreted on the chart.

This script continues to function as an analytical and visualization tool.
It does not attempt to predict price direction or provide guaranteed outcomes.


------------------------
What Changed
------------------------

• Reworked the HUD into the standard AG Pro panel format.
The panel now includes show/hide control, expanded location options, theme control, and adjustable font size.

• Standardized the merged blue header row.
The first panel row now contains only the script name: AG Pro Regime Transition Intelligence.

• Moved ticker, timeframe, and HTF sync context into a dedicated panel row.
This keeps the header clean while preserving useful context.

• Refined the panel row structure.
Regime, axes, dwell context, fatigue, flip risk, next-likely regime, confidence, and history now read in a cleaner order.

• Streamlined transition markers and live regime beacon.
The chart keeps its informational value while reducing heavy visual pressure around candles.

• Adjusted default chart tint and bar coloring.
The regime background is lighter by default, and candle coloring is optional to keep the chart cleaner.

• Preserved the existing analytical engine.
Trend, chop, volatility scoring, adaptive/static bands, dwell statistics, fatigue, flip probability, transition matrix, confidence decay, HTF alignment, and alerts remain part of the script.


------------------------
Visual Improvements
------------------------

• Improved first-glance readability by separating panel header, context, and regime rows.

• Reduced visual load from the background tint and beacon while keeping the regime state visible.

• Improved transition-label discipline with controlled marker count, cooldown, and label-size control.

• Refined visual hierarchy so the active regime and transition context stand out more clearly.


------------------------
Interface & Usability
------------------------

• Added a direct Show Panel toggle.

• Added broader panel location options, including center positions.

• Added three panel themes: Elite Dark, Slate, and Clean Light.

• Kept label font size and panel font size independently adjustable.

• Kept the chart usable on both dense intraday views and wider higher-timeframe layouts.


------------------------
Behavior Notes
------------------------

This update does not change the core analytical logic of the script.

The goal is to improve clarity and usability, not to introduce new predictive behavior.

Users should interpret outputs the same way as before, but with a cleaner panel and lighter chart presentation.


------------------------
Limitations Reminder
------------------------

The script remains a rule-based analytical tool.

Regime statistics depend on the available chart history, selected timeframe, and market structure.

Volatility, liquidity, and timeframe differences may affect how regime shifts and fatigue states appear.


------------------------
Risk Reminder
------------------------

This script is for educational and analytical purposes only.

It does not provide financial advice or guaranteed trading outcomes.

Users remain responsible for their own decisions.
Sürüm Notları
🔧 UPDATE NOTES - 1.3

This update adds a clear regime stance and a transition-accuracy proof layer to
Regime Transition Intelligence. The core regime engine remains unchanged. This
script continues to function as an analytical and visualization tool. It does not
predict price direction or provide guaranteed outcomes.

------------------------
What Changed
------------------------

- Regime Stance (Action) Row
The panel now translates the active regime, fatigue and flip context into a single
stance: Follow Trend, Trend Aging, Fade Range Edges, Breakout Watch, or Reduce /
Wait.

- Transition-Accuracy Proof Layer
A new Transition Hit row tracks how often the prior bar's "Next Likely" forecast
matched the actual new regime once a shift occurred, with sample size.

- Contrast-Safe Marker & Beacon Text
Transition marker and beacon text color now adapts to the regime color, so amber
(mixed) and other light backgrounds use dark text for clean readability.

- Honest Statistics
The proof layer is confirmed-bar gated and only scores forecasts that had enough
historical transition data behind them.

------------------------
Visual Improvements
------------------------

- Improved readability of mixed-regime markers and the live beacon
- Kept transition markers staggered and non-overlapping
- Preserved the subtle regime tint and clean dashboard layout
- Maintained clear visual hierarchy across panel rows

------------------------
Interface & Usability
------------------------

- Added an Action stance row directly under the regime row
- Added a Transition Hit proof row beneath Next Likely
- Kept all existing settings and defaults backward compatible
- Enhanced overall experience without changing the core engine

------------------------
Behavior Notes
------------------------

This update does not change how regimes, axes, dwell, fatigue or flip probability
are computed. The goal is a clearer stance and added forecast-accuracy context.
Outputs should be interpreted the same way as before.

------------------------
Limitations Reminder
------------------------

The script remains a rule-based analytical tool. Volatility, liquidity and
timeframe differences can affect how regimes, transitions and statistics appear.
Always interpret outputs within broader market context.

------------------------
Risk Reminder
------------------------

This script is for educational and analytical purposes only. It does not provide
financial advice or guaranteed trading outcomes. Users remain responsible for
their own decisions.
Sürüm Notları
Version 1.4 – Duration-Aware Regime Story

This update reduced visual pressure and made each visible transition more informative while preserving the three-axis regime engine, adaptive classification, rolling dwell statistics, fatigue model, flip probability, transition matrix, HTF comparison, and Transition Hit proof.

• Raised the default regime-tint transparency to 96 so historical regime blocks remain visible without competing with candles.

• Added a minimum completed-regime duration for chart markers, filtering one- and two-bar visual noise without removing those blocks from classification or statistics.

• Added the completed block’s duration to every retained transition marker, turning short regime codes into evidence-specific historical context.

• Increased marker cooldown to 24 bars and reduced retained markers to eight for a calmer publication-ready density.

• Rebuilt the live regime beacon as a compact two-line badge and increased its default ATR offset to reduce competition with current price.

• Made the HTF display control govern panel context, initialized both panel-header cells before merging, and explicitly confirmed all four alert families on closed bars.

Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.