Runs Test Z-Score# Runs Test Z-Score
## What It Is
The Runs Test Z-Score is a statistical time-series indicator that applies the Wald-Wolfowitz Runs Test to directional price change sequences to measure departures from randomness.
Advantages: The Runs Test is non-parametric, simple to compute, and does not require assumptions about the distribution of returns.
Limitations: It considers only the direction of price changes, ignoring their magnitude, and may have limited power to detect more complex forms of dependence.
Runs are uninterrupted sequences of the same directional state. For example, the sequence (+, +, +, −, −, +, +) forms three runs: (+++), (--), and (++). The Runs Test compares the observed number of runs to the number expected under pure randomness to determine whether price changes exhibit persistence, anti-persistence (alternation), or random sequencing.
The indicator evaluates the **sequential randomness of price changes** to determine whether directional movements occur in a manner consistent with a random walk, or whether they exhibit persistent or alternating structural behavior.
The indicator produces a standardized Z-score:
**Negative values** indicate persistence (fewer directional state changes than expected under randomness).
**Values near zero** indicate random-like sequencing.
**Positive values** indicate anti-persistence (more directional state changes than expected under randomness).
Three independent price sequences can be analyzed:
### 1. Close-to-Close
Measures the sequential pattern of where price closed on the current bar relative to the previous bar's close. It captures the net directional outcome between consecutive intervals, incorporating all activity—including overnight or weekend gaps—while ignoring the path taken within the bar itself. This is typically the broadest, most aggregated mode.
### 2. Open-to-Close
Measures the sequential pattern of directional movement strictly *within* each bar by comparing the close to the open. Positive states indicate an upward drive during the session; negative states indicate a downward drive. This sequence reveals whether intraday or intra-bar directional drive tends to persist or alternate through time.
### 3. Midpoint Position
Measures where price closes relative to the high-low midpoint of each bar. A close above the midpoint indicates that buyers controlled the final portion of the bar's range, while a close below indicates seller control. This pattern captures whether range-control dominance tends to persist or alternate across consecutive bars, regardless of the net change between closes.
---
## What Divergence Means in Practice
Divergence is not a failure of the indicator. It is the indicator revealing something more precise than any single sequence could.
The three sequences measure distinct aspects of price behavior. When they diverge, they reveal structural differences in how directional progression, intra-bar drive, and range control are expressed through sequential price changes.
**All Three Agree:** Sequential structure is highly coherent across inter-bar direction, intra-bar drive, and range control. Price changes are expressing a consistent behavioral pattern across all three dimensions of price action.
**Close-to-Close Persists | Open-to-Close is Random:** The broader trend is being carried primarily by net bar-to-bar advances — including gap contributions — rather than persistent intra-bar directional drive.
**Open-to-Close Persists | Close-to-Close is Random:** Bars exhibit consistent internal directional drive, but that drive does not translate into sequential progress across bars. Strong movement occurs within sessions, but net inter-session direction remains inconsistent.
**Midpoint Position Diverges From Both:** Intra-bar auction control is decoupled from directional movement. Buyers or sellers may be consistently dominating the close of the bar's range even while net trend progression and intra-bar drive remain mixed or random.
**Close-to-Close & Open-to-Close Agree | Midpoint Disagrees:** Directional movement is consistent both within and between bars, but closing location within the range suggests underlying auction dynamics are less consistent with the prevailing directional movement. Trend progression and range control are actively diverging.
**Open-to-Close & Midpoint Agree | Close-to-Close Disagrees:** Intra-bar directional drive and range control are aligned, but that internal behavior fails to translate into persistent directional progression across consecutive bars.
**Close-to-Close & Midpoint Agree | Open-to-Close Disagrees:** Directional progression and range control are aligned, but movement occurring within individual bars lacks persistence. Price changes are making net progress despite inconsistent intra-bar drive.
**All Three Disagree:** Structural signals are mixed across all three dimensions, indicating low agreement regarding the prevailing sequential regime.
---
## Why It Was Built
Most technical indicators focus on trend strength, momentum, volatility, or price efficiency. Far fewer attempt to quantify the underlying sequencing structure of consecutive price changes.
Sequential price changes can produce identical net price movements while exhibiting entirely different internal structures:
**Persistent sequences** contain fewer directional state changes than expected under a random process.
**Random sequences** exhibit no detectable departure from random ordering.
**Alternating sequences** contain more directional state changes than expected under a random process.
Understanding which structural environment currently dominates provides objective, statistical context for trend-following systems, mean-reversion approaches, pattern analysis, and price structure assessment.
---
## Core Concepts
### Persistence
Persistence occurs when directional moves tend to continue. In a persistent environment, state changes occur less frequently than expected under randomness. This produces fewer overall runs and yields a negative Z-score.
### Randomness
Randomness refers to the *ordering* of directional outcomes, not the overall trend vector. Prices can trend strongly while still exhibiting random directional sequencing. Trend direction and sequential randomness are separate price properties. Price may trend upward while directional changes remain statistically random. Z-scores near zero indicate no detectable departure from random sequencing.
### Anti-Persistence
Anti-persistence occurs when directional states alternate more frequently than expected under randomness. This produces more runs than predicted by a random process and results in a positive Z-score.
### Partition Methods
The indicator offers two distinct classification models:
**Zero-Split:** Partitions observations around zero. This mode preserves directional bias and trend influence, measuring randomness while retaining directional drift. Useful when directional bias is core to the analysis.
**Median-Split:** Partitions observations around the rolling median. This removes directional imbalance from the classification process, isolating sequencing behavior from the overarching trend direction.
Comparing both modes helps distinguish persistence arising from directional drift from persistence arising from the sequencing structure itself.
---
## Z-Score Interpretation
| Zone | Z-Score | Structural Interpretation |
🟦 **Strong Persistence** | Z ≤ −1.96 | Sequential changes tend to persist (+/+ or −/−) rather than alternate.
🔵 **Mild Persistence** | −1.96 < Z ≤ −1.0 | Increasing evidence of continuations in sequential price changes.
⬜ **Random-Like** | −1.0 < Z ≤ 1.0 | No detectable sequential structure; outcomes occur with similar frequency.
🟨 **Mild Anti-Persistence** | 1.0 < Z < 1.96 | Increasing evidence of alternations (+/− or −/+) in price changes.
🟧 **Strong Anti-Persistence** | Z ≥ 1.96 | Sequential changes alternate (+/− or −/+) rather than persist.
Color Legend: Dark Blue = Strong Persistence, Light Blue = Mild Persistence, Gray = Random-Like, Light Orange = Mild Anti-Persistence, Dark Orange = Strong Anti-Persistence.
**Statistical Note:** The ±1.96 thresholds correspond to the conventional 5% two-tailed significance level. Values beyond these thresholds indicate statistically significant departures from randomness under the assumptions of the Runs Test. Intermediate zones represent varying degrees of structural evidence but should be interpreted as descriptive rather than formally significant.
---
## Empirical Validation
Validation was conducted using approximately 150,000 daily observations across 50 liquid U.S. equities, ETFs, and sector funds spanning roughly ten years of market history. Lookback periods of 20, 30, and 40 bars were evaluated. Results confirmed that runs-based measurements reliably isolate structural shifts in sequential price behavior.
The study demonstrated:
* Correct regime ordering across all 50 tested securities.
* Stable structural readings that persist beyond short-term noise.
* Consistent behavior across multiple lookback settings.
* Strong correspondence with serial dependence metrics.
*Essentially no correlation with Efficiency Ratio (Kaufman) measurements.**
This final finding strongly suggests that sequential randomness and trend efficiency measure distinct price sequence properties. Price changes can exhibit highly efficient directional travel while still displaying random sequencing, or vice versa. This makes the Runs Test Z-Score a valuable complementary tool rather than a duplicate of existing efficiency or momentum indicators.
---
## How To Use It
**Contextualizing Chart Patterns:** Continuation patterns (flags, channels) implicitly assume a persistent environment. Reversal patterns (double tops and exhaustion structures) are often associated with a breakdown in persistent directional movement, making alternating price changes more likely than continued runs in the same direction. Use the Z-score to determine if the price sequence structure statistically supports the pattern type forming on your chart. When the Runs Test indicates randomness, apparent technical patterns should be interpreted with caution, since their formation may be attributable to chance rather than persistent price behavior.
**Selecting Lookback Periods:** Shorter lookbacks increase responsiveness to structural change but are more sensitive to sampling variability. Longer lookbacks improve stability by filtering short-term noise and highlighting broader regime behavior.
**Applying Partitions:** Monitor the gap between Zero-Split and Median-Split. If Zero-Split shows strong persistence but Median-Split looks random, the non-randomness is entirely driven by directional drift (the trend), not the underlying sequencing mechanics.
**EMA Smoothing:** The optional EMA smoothing layer serves as a visual aid, improving interpretability and helping users track the indicator's underlying trend. Statistical interpretation should always remain anchored to the raw Z-score levels.
---
## Disclaimers & Limitations
This indicator is a descriptive statistical measurement tool, not a predictive trading system. The Runs Test Z-Score evaluates historical directional sequencing and does not forecast future price behavior. Persistent, random, or alternating conditions observed in the past do not guarantee the continuation of those regimes. It should be utilized as contextual analysis alongside proper risk management protocols. Indicatore

Multi-Strategy Portfolio Optimizer [LuxAlgo]The Multi-Strategy Portfolio Optimizer indicator is a comprehensive quantitative tool that evaluates 9 distinct trading setups across trend-following, momentum, and mean-reversion categories to construct an optimized, equally-weighted portfolio.
🔶 USAGE
This script aims to help users identify which trading methodologies are currently performing best on a specific ticker and timeframe, while simultaneously monitoring how well those strategies diversify each other to create a smoother equity curve.
🔹 Strategy Selection & Evaluation
The optimizer evaluates three unique parameter variations for each of the following 9 strategy types:
Supertrend & EMA Crossovers: Captures sustained directional trends.
MACD & CCI: Focuses on momentum shifts and overextended breakouts.
Donchian Channels: Classic breakout logic based on price extremes.
RSI Trend: Uses RSI levels to confirm momentum direction.
RSI Rev, Bollinger Bands & Stochastic: Targets mean-reversion and overbought/oversold exhaustion.
The tool automatically selects the "Best Setting" for each category by comparing the cumulative performance of all three variations across the available chart history. Only the top-performing variation from each category is included in the final portfolio calculation.
🔹 Equity Dashboards
The indicator features two primary visual interfaces to monitor performance and risk:
Floating Curves Box: Displays a real-time equity curve of the total portfolio (thick white line) against the individual active strategies (faded colored lines). This allows users to see the recent performance stability over a user-defined lookback.
Correlation Heatmap: Analyzes the statistical relationship between active strategies. This table uses color-coding to show how similar or different strategy returns are, providing a "Diversification Grade" (e.g., Excellent, Good, Poor) to help users avoid over-exposure to a single market regime.
🔹 Trade Visualization
Users can enable "Show Past & Open Trades" to audit the simulated performance directly on the price action. The script plots entry lines and shaded ATR-based Stop Loss (red) and Take Profit (green) zones for both currently active and historical trades.
🔶 DETAILS
🔹 Best Setting Logic
For every strategy category, the script runs three parallel simulations with different sensitivity settings. The "Best Setting" displayed in the dashboard is the variation that has achieved the highest cumulative percentage return since the beginning of the chart.
🔹 Portfolio Calculation (Equal Weight)
The Portfolio Equity Curve is calculated by averaging the cumulative returns of all active "best" setups on a bar-by-bar basis. This simulates an equally weighted allocation where the capital is distributed evenly across all chosen trading methodologies, aiming to reduce the drawdown typically associated with a single-strategy approach.
🔹 Diversification & Correlation
The Heatmap calculates a Pearson correlation coefficient over a rolling 100-bar window for every pair of active strategies.
Correlation > 0.7 (Red): Strategies are moving in lockstep, offering little diversification.
Correlation near 0 (Yellow): Strategies are independent, providing healthy diversification.
Correlation < -0.2 (Green): Strategies are inversely correlated, which can significantly hedge portfolio volatility.
🔹 Auto-Scaling Polylines
The floating curves dashboard uses a dynamic normalization algorithm. It captures the highest and lowest equity values within the user-defined lookback (Curves Length) and scales them to fit within the box height. This ensures the curves remain visible and proportional regardless of whether the returns are 1% or 100%.
🔶 SETTINGS
🔹 Strategies
Enable : Toggles whether a specific strategy category is evaluated and included in the portfolio math.
🔹 Risk Management
Enable Stop Loss & Take Profit: Toggles the ATR-based exit engine.
ATR Length: The period used for calculating volatility-based exits.
Stop Loss / Take Profit Mult: The multipliers that define the distance of exit targets from the entry price.
Show Past & Open Trades: Visualizes the execution zones on the chart.
🔹 Dashboard
Main Dashboard / Correlation Heatmap: Toggles the visibility of the tables.
Position: Moves the UI elements to different corners of the chart.
Curves Length: Determines the lookback for the floating equity chart.
Curves Vertical Position: Allows you to pin the curves box to the Top, Middle, or Bottom of the price range.
Curves Box Height (%): Adjusts the vertical scale of the equity chart relative to the price action.
Size: Controls the scale of the text and tables (Tiny to Huge). Indicatore

Indicatore

Markov Regime 2.0 - Bull / Bear / SidewaysHere's a publish-ready description for the indicator — written to be honest about what it does and doesn't do (in the spirit of the method):
---
**Markov Regime 2.0 — Bull / Bear / Sideways**
A market-regime model that labels price history into Bull / Bear / Sideways states, builds the Markov transition matrix between them, and turns the regime's persistence into a directional signal. This is a corrected rebuild of the classic Markov regime indicator, with three statistical flaws fixed — so the numbers it shows are honest rather than flattering.
**How it works**
- Each bar is labelled by its rolling N-day return: ≥ +5% = Bull, ≤ −5% = Bear, otherwise Sideways (all configurable).
- It counts how often each state transitions to each other state and normalises into a 3×3 probability matrix. The diagonal is the regime "stickiness" — how likely a state is to persist.
- The signal is `P(bull next) − P(bear next)` from today's regime row: sign = direction, magnitude = conviction.
**The three corrections (what makes it 2.0)**
1. **Stride sampling (the autocorrelation fix).** The original counted a transition on *every* bar — but consecutive rolling windows share all but one bar, which manufactures fake persistence on the diagonal. 2.0 also counts transitions between *non-overlapping* windows (stride = lookback). Each matrix cell shows `honest stride % (legacy overlapping % in brackets)` so you can see the inflation directly.
2. **Label self-check.** Before displaying, it verifies that mean return of Bear < Sideways < Bull and flags a `✓`/`✗` next to the sample size — so a mislabelled state can't ship silently.
3. **Explicit signal + modes.** A real signal with a no-edge deadband (Standalone mode sizes a position by conviction; Filter mode just gates longs/shorts), instead of pure visualisation.
**On the chart**
- A compact dashboard: the transition matrix, current regime (TODAY), the live signal with a verdict (`stay flat` / `LONG x%` / `SHORT x%`), sample size and label-check.
- Optional regime ribbon and state-transition labels.
- **Edge markers:** ▲ LONG / ▼ SHORT print on the candle where the *walk-forward* signal first crosses the deadband. The per-bar signal uses only data available up to that bar (no look-ahead), so markers on closed bars don't repaint. Matching alerts are built in.
**How to read it**
Use it on a daily chart — the default is a ~20-*day* regime concept. Treat the honest (stride) column as the real one; if it sits near 33% (a 3-state coin flip) and the signal stays inside the deadband, the model is telling you there's **no edge — stay flat**, and that's a valid answer. The bracketed legacy values are shown only to expose how much the old overlapping method exaggerates persistence. Small-history assets will have a low transition count (`n=`) — the smaller that number, the less you should trust the matrix.
**Disclaimer**
This is a research and visualisation tool, not financial advice and not a strategy with a guaranteed edge. It reads regimes and reports what your own rules imply; it does not place trades. Past regime behaviour does not predict future returns. Always size and manage risk yourself.
Original framework: Roan (@RohOnChain). 2.0 corrections per the Markov 2.0 method.
---
Want a **short version** (2–3 lines for the script's one-liner subtitle), or should I drop this straight into the code as the top comment block / an `//@description` line? Indicatore

Indicatore

AetherEdge - Smart Money Flow🖊️ Overview
AE-SMF focuses on what smart-money price action is really about — liquidity. It maps the stop pools resting above swing highs (buyside) and below swing lows (sellside) and learns which liquidity price reaches for next (draw on liquidity). The liquidity, sweep, displacement/FVG and premium/discount concepts are re-implemented from public material, with a genuine learning core on top.
🔶 Key Features
Liquidity pool map — buyside/sellside pools, auto-removed once taken
Sweep detection — a grab of one side's liquidity followed by reclaim
ML: draw on liquidity — learns P(the buyside pool is reached before the sellside pool), turning the pull of price into a probability
RL: self-tuning bias threshold — a UCB bandit auto-tunes the firing threshold per structure regime
Sweep-origin signals — TP set to the targeted liquidity pool, SL beyond the swept extreme
Displacement/FVG and premium/discount included
Structure uses confirmed pivots; training and signals gate on bar close — no repaint
🧠 Technical Architecture
Liquidity engine: buyside/sellside pools from confirmed pivots are held in arrays; pools price trades through (taken liquidity) are removed; the nearest pools are drawn as lines.
Sweeps: piercing sellside then reclaiming up = bullish sweep; piercing buyside then closing down = bearish sweep.
ML (online logistic regression): eight features (trend, displacement tendency, premium/discount position, recent bullish/bearish sweep, distance to the buyside/sellside pools, structure direction) feed a model of the draw = P(buyside pool reached before sellside, within N bars). Each confirmed bar labels a pool-to-pool barrier — which of the nearest buyside target (above) and sellside target (below) is touched first — so the prediction uses no future data. If neither is reached in time, the sample is discarded (only clean draws train it).
RL (UCB contextual bandit): auto-tunes the bias firing threshold per structure regime (trend-strength terciles). Its reward is tied to the same draw resolution (a confident bias that proves correct = +1, wrong = −penalty, abstaining when neutral = a small reward) — so the ML training and the RL reward share one judgment loop.
Signals: long = bullish sweep + buyside draw ≥ threshold + discount; short = the mirror. TP is the targeted liquidity pool; SL is beyond the swept extreme.
Honest scope: a linear classifier + a UCB bandit over standard liquidity/structure features. Not deep learning, not a guarantee.
⚙️ Recommended Settings & Tuning Guide
Key parameters: swing lookback (pivots), pools per side, displacement multiple, barrier horizon N, learning rate, threshold search range, stop buffer.
Larger swing lookback → focus on major-structure pools; smaller → more detections
N is the window for deciding which liquidity is reached first (smaller for short-term, larger for swing)
Crypto starting points (tune on your chart):
BTC / ETH (15m–4H): defaults are the baseline (pivLen 10, N 20)
SOL / XRP and high-vol alts: a slightly longer swing lookback and a wider stop buffer to avoid wick-hunts
Scalping (1–15m): smaller pivot length and N
Swing (4H–daily): larger pivot length, N, and warmup
Bias, accuracy, and threshold are coarse until warmup plus enough draws accumulate
💡 How to Use in Practice
Read the draw bias for the liquidity price is likely to target next (buyside = up, sellside = down)
Enter on a sweep + agreeing-draw signal and use the drawn SL/TP (TP = the targeted pool)
Use premium/discount to favor advantageous pullbacks/rallies (buy discount, sell premium)
Leave the auto threshold to the learner by default
Combine with a higher-timeframe liquidity view or a precision-entry tool (AE-ACE)
⚠️ Important Notes
Needs a learning period (warmup); weights and the Q-table re-learn on input/symbol/timeframe change
Pools come from confirmed pivots, so the latest extreme confirms a few bars late (the trade-off for avoiding repaint)
A sweep does not guarantee a reversal (it can continue)
Probability, not a guarantee — always use stops and position sizing
🚨 Disclaimer
This indicator is for educational and informational purposes only and is not financial advice or a recommendation to buy or sell. No method guarantees future profits; past performance does not indicate future results, and trading carries the risk of loss. All trading decisions are your own — use proper backtesting and disciplined risk management. Indicatore

Indicatore

AmendLogic Performance - Dynamic Matrix and Heatmap EngineOverview
AmendLogic_perf is a high-performance analytics utility library designed for Pine Script v6 strategy scripts. It automates the calculation, compounding, and visual rendering of closed and rolling equity structures into a clean, institutional-grade monthly and yearly return matrix.By separating performance rendering from your core entry/exit logic, your scripts remain lean, scannable, and modular.
Key Features
Real-Time Compounding Engine: Continuously tracks equity variations bar-by-bar, automatically computing exact monthly and yearly percentage returns ($P\&L$) alongside raw monetary value gains.
Smart History Reconstruction: Uses dynamic accumulators and arrays to handle historical lookback state tracking. It dynamically pushes and corrects current-period metrics on the final live bar (barstate.islast) without missing real-time fractional ticks.
Proportional Heatmap Scaling (f_getAlpha): Evaluates overall strategic history to locate relative historical maximums and minimums. The library automatically calibrates color transparency to match performance weight: highly profitable months or deep drawdowns receive intense color depth, while neutral periods gracefully fade into a subtle tint.
Native Ecosystem Visual Integration: Deeply integrated with the AmendLogic_css_SEC layout library. The matrix auto-adjusts its borders, cell text, and deep-space canvas framing to remain readable across both light and dark chart layouts.
How to Use (Quick Start)
To append this performance reporting dashboard directly to your strategy, reference the library at the top of your script and pass your live equity array at the final execution layer:
//@version=6
strategy("My Custom Quant Strategy", overlay=true, initial_capital=10000)
// 1. Import the performance matrix library
import Kevinroku/AmendLogic_perf_SEC/1 as perf
// ── ──
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 50))
if (longCondition)
strategy.entry("Long", strategy.long)
// 2. Pass the strategy equity into the engine at the very end
perf.ProfitTable(strategy.equity)
Interface Layout & Output MetricsPosition: Fixed to the bottom_right quadrant of your workstation screen to maintain unobstructed viewing of historical price bars.
Row Headers: Dynamically maps out historical years discovered within your dataset profile.
Column Tracks: Standardized 12-month sequence (Jan – Dec) completed by a bolded cumulative "Year" metrics tracking column.
Color Schemes: Standardizes emerald-green zones for expansion sequences and crimson-red highlights for contraction drawdowns.
Libreria

Z-Score Statistical BandsZ-Score Statistical Bands
1. Overview
Z-Score Statistical Bands is a statistical mean-reversion indicator designed to help traders study how far a selected price series, or a pairs spread, has moved away from its rolling mean.
The script calculates and displays a Z-score oscillator with statistical bands, optional mean-reversion entry markers, exit markers, blocked setup markers, half-life filtering, and an information table.
This is an indicator, not a strategy. It does not place orders, does not execute trades, and does not produce TradingView Strategy Tester backtest results. All markers are visual statistical events only and should not be treated as guaranteed trading signals or financial advice.
2. Core Idea
The indicator measures how far the selected series is from its rolling average in standard deviation units.
A positive Z-score means the selected series is above its rolling mean.
A negative Z-score means the selected series is below its rolling mean.
The general mean-reversion idea is that extreme deviations may sometimes revert back toward the mean, but this is not guaranteed. Markets can remain extended, trend further, or fail to mean-revert.
3. Z-score Calculation
The script calculates:
* Rolling mean
* Rolling standard deviation
* Current Z-score
The Z-score is calculated from the selected series using the chosen lookback length.
The indicator plots:
* Z-score line
* Mean line at 0
* Entry bands
* Normal exit bands
* Extreme bands
4. Information Table
The indicator includes an information table designed to summarize the current statistical state of the Z-score setup.
The table helps users understand the current condition without relying only on the plotted markers.
The table can show:
Z now
The current Z-score value.
This shows how far the selected series is from its rolling mean in standard deviation units.
Half-life
Shows the estimated mean-reversion half-life in bars.
If a valid half-life is not detected, the table can show that there is no current reversion condition.
Edge?
This row shows whether the half-life gate supports mean reversion.
FADE OK
This means the half-life filter currently supports a mean-reversion condition.
DO NOT FADE
This means the half-life filter does not currently support a mean-reversion condition.
This is important because the Z-score may be extreme, but the script may still block the setup if the statistical mean-reversion gate is not valid.
Position
Shows the script’s internal visual position state:
FLAT
No visual position state is active.
LONG ACTIVE
A long-side visual state is active.
SHORT ACTIVE
A short-side visual state is active.
This is only internal marker tracking. It is not a real broker position and not a TradingView strategy position.
Entry
Shows the selected entry behavior.
Possible table examples include:
safer
Conservative entry mode.
early
Aggressive entry mode.
safer + near
Conservative entry mode with near-zone rebound entries enabled.
early + near
Aggressive entry mode with near-zone rebound entries enabled.
Risk exit
Shows whether the early Z-failure exit is enabled.
Guide
Shows a compact explanation of marker colors.
Example:
gray normal / orange fail / gold blocked
Dir
Shows the selected signal direction mode.
Possible values include:
long only
Only low-Z long-side events are allowed.
long + short
Both low-Z long events and high-Z short events are allowed.
Beta / Pair
In pairs mode, this row shows the selected beta mode and the second symbol used as leg B.
Examples:
auto beta / MSFT
manual beta / MSFT
ratio mode / MSFT
In single mode, beta is not applicable.
Why the information table matters
The information table is designed to make the indicator easier to read.
A Z-score extreme alone is not always enough. The table adds context by showing whether the selected series currently passes the half-life mean-reversion gate.
For example:
If the Z-score is extreme and the table shows FADE OK, the script is showing that the statistical gate supports mean-reversion conditions.
If the Z-score is extreme and the table shows DO NOT FADE, the script is warning that the half-life filter does not support fading that move.
This is why gold blocked markers and the information table should be reviewed together.
5. Single and Pairs Modes
The indicator includes two calculation modes:
Single mode
Single mode calculates the Z-score directly from the selected source, such as close price.
This mode is useful when the user wants to study whether one symbol is statistically extended above or below its own rolling mean.
Pairs mode
Pairs mode compares the main chart symbol against a second symbol selected by the user.
The second symbol is used as leg B.
Pairs mode supports:
* Log-spread mode
* Ratio mode
* Manual beta
* Auto rolling beta
Log-spread mode
When log-spread is enabled, the script calculates a spread using:
log(A) - beta × log(B)
This is commonly used in pairs and relative-value analysis.
Ratio mode
When log-spread is disabled, the script uses a simple ratio between symbol A and symbol B.
Auto rolling beta
When enabled in log-spread pairs mode, the script estimates a rolling beta between log(A) and log(B) using the selected lookback window.
Manual beta
Manual beta allows the user to enter a fixed hedge ratio.
Important note about pairs mode
Pairs analysis is sensitive to symbol selection, timeframe, beta stability, liquidity, and market regime. A spread that looked mean-reverting historically may stop mean-reverting. Users should validate pairs relationships independently.
6. Statistical Bands
Mean
The zero line represents the rolling mean reference.
Entry bands
The positive and negative entry bands define the main statistical extension zone.
For example:
+2 Z may represent an upper statistical extension.
-2 Z may represent a lower statistical extension.
Extreme bands
The extreme bands mark deeper statistical extensions.
For example:
+3 Z or -3 Z may indicate a stronger deviation from the rolling mean.
Normal exit bands
The normal exit bands are closer to the mean and are used for visual normal-exit conditions when the Z-score reverts toward the mean.
7. Half-life Mean-Reversion Gate
The script includes a half-life filter designed to check whether the selected series currently shows mean-reversion behavior.
The half-life estimate attempts to measure how quickly deviations may revert toward the mean.
If the half-life condition supports mean reversion, the information table shows:
FADE OK
If the half-life condition does not support mean reversion, the information table shows:
DO NOT FADE
Important note about half-life
Half-life is an estimate based on recent data. It is not a prediction and does not guarantee that price will revert. It is used as a statistical filter to reduce mean-reversion attempts when the series does not currently show a valid mean-reversion profile.
8. Signal Direction
The script supports two direction modes:
Long only
Only low-Z long-side statistical events are allowed.
Both long + short
Low-Z long-side events and high-Z short-side events are allowed.
9. Entry Styles
The script includes two entry styles:
Conservative / Safer
The conservative style waits for the Z-score to first move into an extreme zone, then start reverting back from that zone.
This is designed to avoid entering while the Z-score is still moving deeper into the extreme area.
Aggressive / Early
The aggressive style marks an entry event as soon as the Z-score reaches the selected entry band.
This can create earlier entries, but it may also increase the risk of entering before the move has finished extending.
10. Near-Zone Rebound Entries
The script includes optional near-zone rebound entries.
This feature can mark a rebound when the Z-score nearly reaches the full entry band but does not fully touch it.
Example:
If the main entry band is 2.0 Z and the near-zone band is 1.7 Z, the script can detect a rebound from the 1.7 area.
This feature is intended to catch practical rebounds that occur before the full statistical band is reached.
11. Position-State Tracking
The script tracks a simple internal visual position state:
* Flat
* Long active
* Short active
This state is used only to organize markers and avoid overlapping entry/exit logic. It is not a real broker position and not a TradingView strategy position.
12. Entry Markers
The script can display entry markers on the Z-score pane.
Long Entry
A long entry marker appears when the selected long-side statistical entry condition is met.
Short Entry
A short entry marker appears when the selected short-side statistical entry condition is met and short direction is enabled.
These markers are statistical events only. They are not guaranteed buy or sell signals.
13. Exit Logic
The script includes several visual exit event types.
Normal exit
A normal exit appears when the Z-score reverts back toward the selected normal exit band.
This represents a normal mean-reversion completion event.
Early Z-failure exit
An early failure exit appears when the Z-score fails and moves back beyond the entry band after an active visual position state exists.
This is designed to show a possible statistical failure condition.
Optional price candle failure exit
When enabled, the script can use the entry candle’s high or low as a simple price-failure reference.
For long visual states, price failure can occur if price closes below the entry candle low.
For short visual states, price failure can occur if price closes above the entry candle high.
This feature is OFF by default because it can be sensitive.
Optional emergency Z-stop
When enabled, the script can mark an emergency Z-stop if the Z-score extends further against the active visual position beyond the selected emergency Z-stop level.
This is OFF by default.
14. Marker Guide
The script uses stable markers that are placed away from the Z-score line to reduce overlap.
Long entry marker
A low-Z long-side entry event.
Short entry marker
A high-Z short-side entry event.
Gray X
Normal exit after Z-score reverts toward the mean.
Orange X
Early failure exit.
Red X
Emergency Z-stop exit.
Gold dot
Blocked setup marker.
15. Blocked Setup Markers
The gold dot appears when the Z-score reaches an extreme area, but the half-life filter does not support mean reversion.
This is not an entry marker.
It is a warning that the Z-score is extreme, but the statistical mean-reversion gate is blocking the setup.
16. Alerts
The script includes alert conditions for:
* Long entry
* Short entry
* Blocked low-Z setup
* Blocked high-Z setup
* Normal exit
* Early failure exit
* Emergency Z-stop
* Any exit
Alerts are notifications only. They do not place orders and do not confirm broker execution.
17. How to Use This Indicator
A practical workflow:
1. Choose Single mode or Pairs mode.
2. Select the source series or pair symbol.
3. Choose the lookback length for mean and standard deviation.
4. Select the entry band, normal exit band, and extreme band.
5. Review the information table.
6. Check whether the table shows FADE OK or DO NOT FADE.
7. Use conservative mode if you prefer confirmation after the Z-score starts reverting.
8. Use aggressive mode only if you understand the risk of earlier entries.
9. Review blocked setup markers to see when the half-life gate is rejecting extreme Z-score conditions.
10. Use normal exit, failure exit, and emergency exit markers to study how the Z-score reverts or fails.
11. Combine the indicator with broader market context, liquidity, trend, risk management, and independent analysis.
12. Suggested Use Cases
Z-Score Statistical Bands can be used for:
* Mean-reversion study
* Statistical deviation analysis
* Pairs spread monitoring
* Relative-value analysis
* Z-score band observation
* Half-life filtering
* Reversion timing study
* Exit event visualization
* Blocked setup review
* Statistical context review through the information table
19. Important Limitations
This indicator does not predict future price movement.
It does not guarantee mean reversion.
It does not guarantee profitable trades.
It is not a trading strategy.
It does not place orders.
It does not produce Strategy Tester results.
Z-score extremes can become more extreme.
Mean-reversion conditions can fail.
Half-life is an estimate, not a certainty.
Pairs relationships can change over time.
Rolling beta can be unstable in changing market regimes.
Ratio and log-spread methods can produce different results.
Pairs mode requires valid data for the selected second symbol.
Log calculations require positive price values.
Signal markers are statistical events, not trading instructions.
Exit markers are visual events, not broker fills.
The internal position state shown in the table is only a visual tracking state, not a real trading position.
Users are responsible for their own trading decisions, risk management, and position sizing.
20. Originality and Purpose
Z-Score Statistical Bands combines several statistical mean-reversion tools into one organized indicator:
* Single-symbol Z-score analysis
* Pairs spread Z-score analysis
* Log-spread and ratio modes
* Manual and rolling beta options
* Half-life mean-reversion gate
* Conservative and aggressive entry styles
* Near-zone rebound entries
* Internal visual position-state tracking
* Normal exit markers
* Early failure exit markers
* Optional price failure exit
* Optional emergency Z-stop
* Blocked setup markers
* Information table
* Alert conditions
The purpose of the script is to help traders study statistical extension, mean-reversion conditions, and pairs-spread behavior in a structured and visual way.
21. Educational Disclaimer
This script is for educational and chart-analysis purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. Users should perform their own analysis and manage risk independently.
Indicatore

Strategy Forecast EngineThe Strategy Forecast Engine is a regime-based Monte Carlo forecasting tool that estimates the future return distribution of trend-following strategies across different market environments. The model identifies the current market regime, conditions forecasts on historical returns observed during comparable regimes, and generates thousands of potential future price paths using Monte Carlo simulation. The resulting return distribution is presented through percentile projections and a structured, color-coded table that provides a comprehensive assessment of the forecast.
First, the model identifies the current market regime using the selected trend-following strategy. Users can choose between a moving-average crossover strategy, a volatility-based trailing stop strategy, or a combined strategy that incorporates both approaches. Supported moving-average types include the Exponential Moving Average (EMA), Simple Moving Average (SMA), Wilder’s Moving Average (RMA), and Weighted Moving Average (WMA). Supported volatility types include the Average True Range (ATR), Standard Deviation (SD), and Mean Absolute Deviation (MAD). By default, the model applies an asymmetric design in which conflicting signals default to bullish unless neutral regimes are enabled in the menu. Market regimes are determined as follows:
Bullish Trend Regime = (Fast MA – Slow MA) > (ATR × Trend Margin)
Bearish Trend Regime = (Fast MA – Slow MA) < –(ATR × Trend Margin)
Bullish Volatility Regime = Price > (Highest Price – (Volatility × Stop Factor))
Bearish Volatility Regime = Price < (Lowest Price + (Volatility × Stop Factor))
Bullish Combined Regime = Bullish Trend Regime and Bullish Volatility Regime
Bearish Combined Regime = Bearish Trend Regime and Bearish Volatility Regime
Once the current regime has been identified, the model collects all historical logarithmic returns that occurred during the same regime beginning from the selected start date. Only returns from the matching regime are used to generate the forecast, allowing projections to be conditioned on historically comparable market environments rather than treating all historical observations as equally relevant. If duration-adjusted forecast is enabled in the menu, the model further restricts the sample pool to returns from regimes that were at least as mature as the current regime.
The Monte Carlo simulation engine then generates thousands of possible future price paths over the selected forecast horizon. Each simulation randomly samples historical returns from the sample pool associated with the current regime and compounds them forward to generate a potential future price path. This process is repeated for the specified number of simulations to produce a broad range of possible future outcomes. The random seed controls reproducibility, ensuring that identical settings produce identical forecasts. Once all individual simulations have been completed, the resulting return distribution is summarized using percentile projections:
95% = 5% of simulations ended above this level and 95% ended below it.
75% = 25% of simulations ended above this level and 75% ended below it.
Median = 50% of simulations ended above this level and 50% ended below it.
25% = 25% of simulations ended below this level and 75% ended above it.
5% = 5% of simulations ended below this level and 95% ended above it.
The upper quartile (75%) and lower quartile (25%) define the Interquartile Range (IQR), which contains the middle 50% of all simulated outcomes and represents the central range of the projected outcome distribution. The upper and lower tail percentiles can be set to 10% (90% / 10%), 5% (95% / 5%), or 1% (99% / 1%). The default setting is 5%, which captures the middle 90% of simulated outcomes. At 10%, the range captures 80% of simulated outcomes, while at 1%, the range captures 98% of simulated outcomes. To further evaluate the risk/reward characteristics of the forecast, the model includes a built-in table with the following metrics:
Regime = Current market regime based on the selected strategy configuration.
Duration = Percentile rank of current regime duration relative to past regimes.
Forecast = Percentile rank of current duration including the forecast horizon.
Win Rate = Percentage of profitable simulations relative to total simulations.
Profit Factor = Ratio of total simulated profits to total simulated losses.
Expectancy = Average expected percentage return across all simulations.
Reward/Risk = Ratio of upper quartile return to lower quartile return.
Asymmetry = Ratio of selected upper tail return to selected lower tail return.
Skewness = Ratio of upside potential to downside risk relative to the median.
Sample Size = Number of historical returns available for the current regime.
Frequency = Percentage of historical returns belonging to the current regime.
In summary, the Strategy Forecast Engine is a comprehensive forecasting tool designed to help investors evaluate the return distribution of trend-following strategies based on the current market regime. By combining regime detection with Monte Carlo simulation, the model conditions forecasts on historical returns observed during comparable market regimes to estimate the distribution of potential outcomes and their associated risk/reward characteristics. While the model provides valuable insight into historical return patterns, investors should remain mindful that historical market behavior may not necessarily persist under future market conditions. Indicatore

Bias Status Dashboard## Bias Status Dashboard
The Bias Status Dashboard is designed to give traders a quick visual read of the current market bias directly on the chart. It organizes market direction, projection zones, percentage references, and current symbol context into one clean dashboard.
This indicator is useful for traders who want to quickly determine whether price is leaning bullish, bearish, neutral/ranging, continuing, reversing, or becoming overextended.
## Main Features
* Displays current market bias in a simple dashboard format
* Identifies the current chart/symbol being analyzed
* Shows projection-based zones for normal, moderate, and extreme movement
* Includes percentage references to show how much of the projected move has been used
* Plots optional chart lines for upside and downside projection areas
* Helps identify when price still has room for continuation or may be stretched
* Organizes high and low projection zones in a clean, logical order
* Designed to reduce chart clutter while keeping important context visible
## Projection Zones
The dashboard separates movement into three main zones:
**Normal Zone** – Price is within a reasonable projected range.
**Moderate Zone** – Price is moving deeper into projection and should be watched more carefully.
**Extreme Zone** – Price is extended and may carry higher risk for late entries, exhaustion, or reversal behavior.
These zones can help traders avoid chasing trades after price has already moved too far.
## How to Use
Use the dashboard as a trade filter and market context tool.
A simple workflow:
1. Check the current bias.
2. Confirm whether the market is bullish, bearish, neutral, or extended.
3. Compare current price to the normal, moderate, and extreme zones.
4. Avoid late entries when price is already in an extreme area.
5. Use your own strategy for entries, stops, targets, and risk management.
This indicator is not meant to be a standalone buy or sell signal. It is designed to support analysis by showing where price currently sits within the projected movement range.
## Best For
* Intraday futures trading
* Bias confirmation
* Continuation trade filtering
* Reversal awareness
* Target planning
* Projection-based analysis
* Avoiding overextended entries
* Quick market condition review
This tool can be used across multiple futures and index markets, but users should test and adjust settings based on their preferred symbol, session, and timeframe.
## Disclaimer
This indicator does not guarantee future price direction or trade outcomes. It is intended for educational and analysis purposes only. Always use proper risk management and combine this tool with your own tested trading plan.
Indicatore

Bias Status Dashboard## Bias Status Dashboard
The **Bias Status Dashboard** is designed to help traders quickly identify the current market bias using a clean, structured dashboard directly on the chart. Instead of relying on one signal alone, this indicator organizes multiple pieces of market context into an easy-to-read status panel so you can make faster and more confident trading decisions.
This tool is especially useful for traders who want a simple visual summary of whether the market is leaning **bullish, bearish, ranging, continuation-based, or reversal-based**.
---
## What This Indicator Does
The Bias Status Dashboard evaluates current market conditions and displays the active bias in a compact table format. It helps answer questions such as:
* Is the current market leaning bullish or bearish?
* Are price conditions supporting continuation?
* Is the market showing signs of reversal?
* Are we in a normal, moderate, or extreme projected zone?
* Is the current chart aligned with the active bias?
* Are targets and projections still reasonable based on current price action?
This makes it easier to filter trades instead of taking every possible setup.
---
## Key Features
### Market Bias Status
The dashboard provides a clear bias reading so traders can quickly understand the current market environment.
Bias may display conditions such as:
* Bullish bias
* Bearish bias
* Neutral or ranging market
* Continuation condition
* Reversal condition
* Overextended or extreme condition
This gives a quick directional snapshot without needing to manually interpret every candle.
---
### Current Market Identification
The dashboard includes a row that identifies the current chart market/symbol you are viewing.
This is useful when switching between markets such as:
* MES
* ES
* MNQ
* NQ
* MGC
* GC
* M2K
* Other futures or index charts
The goal is to keep the dashboard tied to the current chart so the information stays relevant to the market being analyzed.
---
### Projection-Based Zones
The indicator includes projected market zones based on the current calculation.
These zones help classify price movement into different strength areas:
* **Normal Zone** – price is within a reasonable projected movement range.
* **Moderate Zone** – price is moving further into projection and should be watched more carefully.
* **Extreme Zone** – price is reaching an extended area where continuation may be less favorable or reversal risk may increase.
This helps traders avoid chasing price when the market is already stretched.
---
### Percentage References
The dashboard also includes percentage-based references so traders can better understand how much of the projected move has already been used.
This is helpful for determining:
* How much room may remain in the current move
* Whether price is still in a healthy continuation area
* Whether the market is becoming overextended
* Whether a trade has enough potential left before entering
Instead of only seeing lines or zones visually, the dashboard gives numerical context.
---
### Chart Zone Lines
Optional chart lines can be plotted based on the projection zones.
These lines allow traders to visually see where the normal, moderate, and extreme areas are located directly on the chart.
The zone lines are useful for:
* Target planning
* Avoiding late entries
* Understanding where price may react
* Seeing when price enters an overextended area
* Comparing current price to projected movement levels
The lines are designed to apply only to the current chart being viewed.
---
### High and Low Projection Areas
The indicator can show both upside and downside projection levels.
This helps traders understand where price may be considered extended in either direction:
* Extreme High areas appear toward the top of the projection.
* Extreme Low areas appear toward the bottom of the projection.
* Moderate and normal zones are placed between them in proper order.
This keeps the projection structure logical and visually cleaner.
---
### Cleaner Visual Layout
The dashboard and chart labels are designed to reduce clutter while still giving detailed information.
Features may include:
* Organized table rows
* Customizable text placement
* Dashed projection lines
* Zone labels
* Cleaner spacing between dashboard elements
* Improved label positioning when levels are close together
This makes the indicator easier to use during live chart analysis.
---
## How Traders Can Use It
The Bias Status Dashboard is best used as a **decision-support tool**, not as a stand-alone buy or sell signal.
It can help traders confirm whether a setup makes sense based on the current market environment.
For example:
### Bullish Continuation
If the dashboard shows bullish bias and price is still within the normal or moderate upside projection zone, a trader may look for long setups that align with their own strategy.
### Bearish Continuation
If the dashboard shows bearish bias and price has room before reaching an extreme downside projection, a trader may look for short setups that match their trading plan.
### Avoiding Late Entries
If price is already in an extreme high or extreme low zone, the dashboard can warn that the move may be stretched. This may help traders avoid chasing entries too late.
### Ranging Conditions
If the dashboard shows a neutral or ranging condition, traders may choose to wait for stronger confirmation before entering.
### Reversal Awareness
When price enters an extreme projection area, traders can use that information to watch for possible rejection, exhaustion, or reversal behavior.
---
## Best Use Cases
This indicator may be helpful for:
* Intraday futures trading
* Bias confirmation
* Continuation trade filtering
* Reversal awareness
* Target planning
* Projection-based analysis
* Avoiding overextended entries
* Comparing bullish and bearish market conditions
* Quickly reading market structure context from a dashboard
It can be used on multiple futures and index markets, but users should test the settings for their preferred symbol and timeframe.
---
## Suggested Workflow
A simple workflow could be:
1. Check the dashboard bias.
2. Confirm whether the market is bullish, bearish, neutral, or extended.
3. Look at the projection zones.
4. Avoid entries if price is already too far into an extreme zone.
5. Use your own strategy for entries, stops, and trade management.
6. Use the dashboard as a filter to support higher-quality decisions.
---
## Important Notes
This indicator does not guarantee price direction or trade outcomes. It is designed to provide market context and help traders organize bias, projection, and zone information in one place.
Traders should always use proper risk management and combine this tool with their own tested trading plan.
The dashboard is intended to support analysis, not replace it.
---
## Summary
The **Bias Status Dashboard** provides a visual and numerical summary of current market bias, projected zones, and percentage-based movement context. It helps traders quickly determine whether the market is bullish, bearish, neutral, normal, moderate, or extreme.
By combining a dashboard with optional chart projection lines, the indicator gives traders a cleaner way to understand where price currently sits within the expected movement range and whether there may still be room for continuation.
Indicatore

Indicatore

Elaris Mean Reversion ProElaris Mean Reversion Pro
Elaris Mean Reversion Pro is a multi-factor mean reversion indicator designed to help traders identify situations where price has moved significantly away from its statistical mean and may be entering a potential reversion phase.
The indicator combines adaptive deviation bands, volatility measurements, momentum filters, market regime analysis, and optional higher-timeframe confirmation to provide a structured framework for analyzing stretched market conditions.
Unlike simple overbought and oversold tools, Elaris Mean Reversion Pro allows users to customize how extremes are measured through Z-Score, ATR-based, or hybrid deviation models while incorporating optional confirmation layers such as RSI, MFI, volume, ADX, and higher-timeframe trend filters.
Key Features
• Multiple mean calculation methods including EMA, SMA, RMA, WMA, VWMA, and HMA.
• Three deviation models:
* Z-Score Bands
* ATR Bands
* Hybrid Bands
• Mean reversion signal engine with multiple confirmation styles:
* Extreme Touch
* Mean Reclaim
* Candle Rejection
• Optional RSI and MFI extreme-condition filters.
• ADX-based market regime filter to help identify environments where mean reversion conditions may be more relevant.
• Optional volume and volatility filters.
• Higher-timeframe confirmation framework.
• Signal quality scoring system.
• Dynamic mean, deviation bands, and reversion zones.
• Built-in dashboard displaying:
* Market state
* Z-Score
* Distance from mean
* Momentum readings
* Regime status
* Higher-timeframe bias
• Alert conditions for:
* Long mean reversion signals
* Short mean reversion signals
* Upper extreme zones
* Lower extreme zones
How It Works
The indicator calculates a central mean and measures how far price has deviated from that mean using statistical or volatility-based methods.
When price reaches an extreme deviation zone, the indicator evaluates additional confirmation factors such as candle behavior, momentum conditions, volatility, volume, and trend regime before generating a signal.
Signals are intended to highlight potential mean reversion conditions and should be evaluated alongside the trader's own market analysis and risk management process.
Non-Repainting
This indicator uses confirmed bar logic and higher-timeframe requests with lookahead disabled. Signals are generated using closed-bar information and do not intentionally repaint historical signals.
Notes
Mean reversion techniques may behave differently across various market conditions. Strong directional trends, high-impact news events, and volatility expansions can influence market behavior and should always be considered when interpreting indicator outputs.
This tool is designed for market analysis and educational purposes only and does not constitute financial advice.
Indicatore

Kalshi BTC 15m Prob Cone v0.7.5Kalshi BTC 15m Probability Cone - Historical SMA
Overview
Kalshi BTC 15m Probability Cone - Historical SMA is a TradingView indicator designed for the Kalshi BTC 15-minute Up/Down market workflow.
It compares the current 60-period SMA to a fixed interval target, then scans historical SMA behavior over matching time windows. The result is a probability table and a forward probability cone showing how similar historical windows behaved into settlement.
The indicator is built for short-interval decision support. It does not predict the future, connect directly to Kalshi, or guarantee profitable trades. It uses the TradingView chart feed as its analysis source.
What It Does
At each 15-minute interval, the script:
1. Captures the previous 60-period SMA as the interval target.
2. Tracks the current 60-period SMA against that fixed target.
3. Calculates the time remaining in the active interval.
4. Scans historical SMA windows with the same remaining-time length.
5. Weights historical samples by recency, volume similarity, and optional settlement-phase similarity.
6. Estimates the probability of finishing above or below the target.
7. Draws a probability cone from the current SMA into the rest of the interval.
8. Displays feed, sample, and confidence diagnostics in a table.
The main question it answers is:
Based on similar historical SMA movement, how often did the SMA finish above or below the active 15-minute target?
Main Features
Historical Probability Table
The table gives a compact readout of the current interval.
It includes:
· Status – Whether enough historical data is available.
· Confidence – Quality level based on effective sample size.
· Feed – Whether recent chart bars appear regular or gapped.
· Time Window – Time remaining in the current 15-minute interval.
· Current Dist – Current SMA distance from the interval target.
· Prob Above – Weighted historical probability of finishing above the target.
· Prob Below – Weighted historical probability of finishing below the target.
· Max Up – Largest historical upward move in the analyzed windows.
· Max Down – Largest historical downward move in the analyzed windows.
· Recency λ – Current recency weighting setting.
· Volume σ – Current volume similarity setting.
· Raw Windows – Number of historical windows scanned.
· Eff. Samples – Effective sample size after weighting.
· Data Hours – Approximate stored historical data.
Probability Cone
The probability cone projects historical percentile ranges forward from the current SMA.
It includes:
· p10
· p25
· p50 median
· p75
· p90
· Max Up rail
· Max Down rail
The percentile bands use weighted linear interpolation. This makes the cone smoother, especially when the effective sample size is low.
The Max Up and Max Down rails are not percentiles. They are exact historical extremes from the analyzed sample set.
15-Minute Interval Target
At the start of each 15-minute interval, the script captures the previous 60-period SMA.
That value becomes the interval target. The target is drawn as a purple horizontal line and remains fixed until the next interval begins.
Interval Boundary Lines
Purple vertical lines mark each 15-minute boundary.
These make it easier to see where each Kalshi-style interval begins and ends.
Feed Integrity Check
The Feed row checks whether the chart feed spacing matches the active chart timeframe.
Examples:
· A 1-second chart expects about 1,000 ms between bars.
· A 5-second chart expects about 5,000 ms between bars.
The tolerance is 25% of the expected bar gap.
This allows the indicator to degrade cleanly on other timeframes instead of assuming every chart is always 1 second.
Inputs
Display Options
Show Historical Probability Table
Turns the probability table on or off.
Show Probability Cone
Turns the forward cone on or off.
Table Position
Moves the table to one of the chart corners.
Calculation Settings
Minimum Sample Size
Sets the minimum effective sample size required before the model is considered ready.
Update Frequency
Controls how often the main probability scan updates.
Store Data Every N Seconds
Controls how often SMA and volume samples are stored.
Max History Samples
Limits stored history.
Max Analysis Iterations
Limits how many historical windows are scanned during the main probability calculation.
Weighting Parameters
Recency Decay (Lambda)
Controls how much recent data matters.
· 0.0 means no recency bias.
· Small values apply mild recency bias.
· Larger values make recent data dominate faster.
Volume Similarity (Sigma %)
Controls how strongly the model prefers historical windows with volume similar to the current bar.
· Higher values are more neutral.
· Lower values are stricter.
· Very low values can sharply reduce effective sample size.
Settlement Phase Weighting
Settlement Phase Weighting Mode
Controls whether historical samples from a similar point inside the 15-minute interval get extra weight.
Available modes:
· Off
· Weighted
Settlement Phase Sigma
Controls how strict the settlement-phase matching is.
Lower values are stricter. Higher values are more forgiving.
Cone Settings
Cone Max Iterations
Controls how many historical windows are used for cone calculations.
Lower values improve performance. Higher values may improve stability, but they can increase chart load.
How to Read the Chart
Gray SMA Line
The gray line is the 60-period SMA.
This is the main value being compared against the interval target.
Purple Horizontal Line
The purple horizontal line is the active 15-minute target.
If the SMA is above this line, the interval is currently above target. If it is below this line, the interval is currently below target.
Purple Vertical Lines
The vertical lines mark 15-minute interval boundaries.
Probability Cone
The cone starts at the current SMA and extends toward the end of the interval.
A cone drifting upward means the weighted historical median is moving higher over the remaining window.
A cone drifting downward means the weighted historical median is moving lower over the remaining window.
A wide cone means historical outcomes were more spread out. A narrow cone means historical outcomes were more clustered.
Max Up and Max Down Rails
The dashed rails show the largest upside and downside moves found in the analyzed historical windows.
They are useful for context, but they are not hard limits. Market movement can exceed prior extremes.
How to Read the Table
Status
· Ready means the model has enough effective samples.
· Collecting data... means the model has not reached the minimum effective sample size.
Confidence
Confidence is based on effective sample size:
· Low – fewer than 100 effective samples
· Medium – 100 to 499 effective samples
· Good – 500 to 999 effective samples
· High – 1,000 or more effective samples
Feed
Feed status helps identify chart data problems:
· OK – Bar spacing looks normal.
· Recent Gaps – Recent irregular bars were detected.
· Gap – The current bar spacing is irregular.
· Initializing – Not enough bar history yet.
Prob Above / Prob Below
These are the main probability outputs.
They show the weighted historical percentage of comparable windows that finished above or below the active target.
Example:
Prob Above = 62%
This means 62% of the weighted historical windows finished above the target condition.
Current Dist
This shows the current percentage distance between the SMA and the active target.
Positive values mean the SMA is above target. Negative values mean the SMA is below target.
Raw Windows vs. Effective Samples
Raw Windows is the number of historical windows scanned.
Effective Samples is the usable sample size after weighting.
A high Raw Windows count with a low Effective Samples count means the weighting settings are aggressive.
Suggested Workflow for Kalshi BTC 15m Markets
1. Start with a Clean Baseline
Use neutral settings first:
· Recency λ: 0.0
· Volume σ: 100% or higher
· Settlement Phase Weighting: Off
This gives the clearest view of the raw historical distribution.
2. Check the Feed Row
Do not trust the table if the feed is showing active gaps.
Short-interval markets are sensitive to missing bars. Bad input data produces bad probability output. Shocking, yes, but machines still cannot turn garbage into edge. 🧯
3. Check Effective Sample Size
Prefer readings with a reasonable effective sample size.
A strong probability with weak sample quality is fragile. It may still be useful, but it should be treated cautiously.
4. Compare Table Bias to Cone Shape
The best readings are cleaner when the table and cone agree.
For example:
· Prob Above is clearly higher than Prob Below.
· The cone median slopes upward.
· The current SMA is not already stretched near the Max Up rail.
· Feed status is OK.
· Effective sample size is acceptable.
5. Avoid Treating Small Edges as Certainty
A 52% to 55% reading is not a magic button.
For a binary-style market, fees, spread, fill quality, and timing can easily erase a small statistical lean.
6. Use the Rails for Context
Max Up and Max Down show what happened in the most extreme historical windows.
They can help you avoid chasing when the current move is already stretched.
They should not be used as guaranteed ceilings or floors.
Practical Interpretation
The indicator is strongest as a context tool.
Useful situations include:
· Estimating whether the current interval is statistically tilted.
· Comparing the table probability against the cone median.
· Checking whether current movement is stretched versus historical windows.
· Identifying when weighting settings are too aggressive.
· Spotting feed problems before trusting a short-interval readout.
Weak situations include:
· Low effective sample size.
· Recent feed gaps.
· Sudden volatility regime changes.
· Major news or exchange disruptions.
· Thin or abnormal volume.
· Overly strict recency, volume, or phase weighting.
Recommended Chart Setup
For the intended workflow, use:
· BTC chart source that closely matches the market you are analyzing.
· 1-second chart when available.
· Enough loaded history to build a useful sample.
· Stable chart feed conditions.
· Conservative weighting settings at first.
· A separate check against Kalshi’s actual market and settlement rules.
The indicator uses TradingView chart data. It does not pull official Kalshi settlement values.
Limitations
This script is based entirely on historical SMA behavior.
It does not know:
· Future news
· Order-book changes
· Kalshi liquidity shifts
· Bid/ask spread behavior
· Fill quality
· Sudden volatility changes
· Exchange outages
· Macro events
· Official settlement-feed discrepancies
Important limits:
· Historical probability is not a forecast.
· The cone is not a predicted path.
· Max Up and Max Down are not hard boundaries.
· Low effective sample size can make results unstable.
· Aggressive weighting can create false confidence.
· Poor chart data can distort the output.
· A binary market can still be mispriced, illiquid, or difficult to enter and exit cleanly.
Use the indicator as decision support, not as an automated trading system.
Version Notes
v0.7.5
· Renamed the indicator for the Kalshi BTC 15-minute market workflow.
· Recommended title: Kalshi BTC 15m Probability Cone - Historical SMA.
· Recommended short title: Kalshi BTC 15m Prob Cone.
· Clarified that the indicator uses TradingView chart data and is not an official Kalshi settlement feed.
v0.7.4
· Feed integrity now derives expected bar spacing from the chart timeframe.
· Gap tolerance is now proportional at 25% of expected bar spacing.
· Non-time-based charts fall back to a 1-second expectation.
· Cone percentile bands now use linear interpolation between weighted ranks.
· Probability table calculations are unchanged by the cone interpolation update.
· Max Up and Max Down rails remain exact historical extremes.
v0.7.3
· Settlement countdown was aligned to the same epoch-based interval clock used by interval boundaries.
· Removed the older minute/second countdown dependency.
· Improved consistency between interval boundary detection and remaining-time calculations.
v0.7.2
· Replaced loose cache variables with typed cache structures.
· Reduced cache-management complexity.
· Preserved existing output behavior.
v0.7.1
· Unified the scan and weighting path.
· Shared one precomputed weight array between scan and cone calculations.
· Reduced duplicated weighting work.
v0.7.0
· Merged max-positive and max-negative extreme tracking into the main historical scan.
· Added cone rails for maximum historical upside and downside.
· Improved cone performance with a separate cone iteration cap.
Disclaimer
This script is for research, visualization, and educational use.
It does not provide financial advice. It does not guarantee profitable trades. It does not connect directly to Kalshi or certify settlement outcomes.
Historical probability can describe what happened before. It cannot guarantee what happens next.
Use proper risk controls.
Indicatore

F54 DividendsF54 Dividends
Overview
F54 Dividends is an informational indicator that visualises cash dividend events for the active symbol and shows event-level plus cumulative dividend context directly on the chart.
The script is designed for analysis and transparency of dividend history. It does not place orders and does not provide trade execution logic.
Why This Indicator Is Useful
Dividend income is a core component of total return for income-oriented investors, yet TradingView's default chart view gives no direct visibility into it. This indicator bridges that gap.
Yield on cost at a glance. Each label shows the dividend ratio relative to the price at the time of the ex-dividend event, so you can immediately see how yield evolved over time as the share price changed.
Cumulative income picture. The YTD, Fixed 12M, and Rolling 12M accumulation modes let you see how much income a position has generated over a meaningful period without switching to a separate data source or spreadsheet.
Pattern recognition. Seeing dividend events overlaid on price action makes it easy to spot payout consistency, growth trends, or cuts alongside the price history that accompanied them.
Monthly vs quarterly discrimination. The script automatically detects likely monthly payers and suppresses per-event noise, showing only quarter-end summaries to keep the chart readable without losing the cumulative picture.
Period boundary awareness. New accumulation periods (calendar year or 12-month anchor) are highlighted with a distinct label colour, so resets are immediately visible rather than hidden in the data.
Together these features let you assess a symbol's income quality and consistency directly on the price chart, supporting dividend-focused screening, position review, and historical context gathering.
What The Indicator Shows
- Detects ex-dividend events from TradingView dividend data.
- Displays per-event dividend amount in EUR.
- Displays per-event dividend ratio relative to a reference close.
- Displays cumulative dividend amount and cumulative dividend ratio according to the selected accumulation mode.
- Limits visible labels to the most recent N events to keep the chart readable.
Accumulation Modes
- YTD: Resets cumulative values at the start of each calendar year.
- Fixed 12M: Uses a fixed 12-month period anchored by the current month.
- Rolling 12M: Uses a continuously rolling 365-day window.
Inputs
- Show last N labels: Controls how many recent dividend labels remain visible.
- Accumulation mode: Selects how cumulative values are calculated (YTD, Fixed 12M, Rolling 12M).
How To Read Labels
Each label includes:
- Dividend amount for the current ex-day.
- Event ratio (R) for the current ex-day.
- Cumulative amount for the selected period.
- Cumulative ratio (R) for the selected period.
- In YTD and Fixed 12M modes, the start of a new accumulation period is highlighted with a teal label.
Notes And Limitations
- Output depends on TradingView dividend data availability and symbol coverage.
- Currency display is EUR in this script configuration.
- Label visibility may vary with chart scaling and timeframe.
- In Rolling 12M mode, accumulated values are window-based and may fall when older ex-dividend events leave the 12-month window, which can be confusing if a steadily increasing total is expected.
- Past data can be revised by data providers; values are informational.
Compliance And Disclaimer
This script is for educational and informational purposes only.
It is not investment advice, not a solicitation, and not a guarantee of future results.
Always perform your own research and risk assessment before making investment decisions. Indicatore

Indicatore

Path-Dependent Volatility Forecast# Path-Dependent Volatility Forecast — Publication Description
### What it is
A self-calibrating forecaster of an instrument’s own **realised volatility**, built only from its price path. It estimates how large the next bar’s volatility is likely to be, explains *why* (which part of the price path is driving it), and shows *how well* that explanation is currently working on the symbol in front of you. It is **context for risk and regime awareness — not a buy/sell signal and not a strategy.** It plots in a sub-pane: a forecast line, the realised-vol line it tracks, regime shading, and a compact dashboard.
### The idea, in one paragraph
Volatility is largely **path-dependent**: an asset’s volatility is mostly explained by its own recent price path. Falling prices tend to lift volatility (the leverage effect), recent movement tends to persist (volatility clustering), and strong rallies add their own volatility. This script turns that idea into a working, per-instrument forecaster and then proves the fit on-chart.
### Why these components are combined (mashup justification)
This is **one model expressed as a single estimate → explain → calibrate → decompose → verify loop**, not a bundle of unrelated indicators stacked together. Each stage is necessary; remove any one and the result breaks:
1. **Realised-volatility estimator** (range-based Garman-Klass, or close-to-close) measures the ground-truth volatility the model is trying to explain. Without it there is nothing to fit to.
2. **Path features** are the model’s inputs: a *trend / leverage* feature (a weighted average of recent returns) and an *activity / churn* feature (the square root of a weighted average of recent squared returns), each built as a blend of fast, medium and slow kernels so it carries short **and** long memory; plus an **upside-convexity** term (so strong rallies add volatility) and a **persistence (memory)** term (a longer-horizon average of past realised vol). Features without calibration are unscaled noise.
3. **Rolling ridge calibration** fits the weights of `realised_vol ≈ b0 + b1·trend + b2·activity + b12·upside + b3·memory` to *this* instrument by rolling regression. The predictors are correlated, so the fit is **ridge-regularised on standardised predictors** to keep the coefficients steady. Calibration without features has nothing to fit; features without calibration cannot be put in the right units.
4. **Decomposition** splits the forecast into its drivers — **Path** (leverage / upside), **Activity** (churn), and **Memory** (persistence) — which is the interpretation the model makes possible.
5. **Live fit read-out** (rolling R² of forecast vs realised) is the proof the loop is working on the asset in front of you.
So the five parts are stages of a single pipeline: measure realised vol, explain it from the path, calibrate to the instrument, decompose it, and verify the fit — one engine, not five overlays.
### How it works (more detail)
- **Inputs are lagged one bar.** The path features are built from confirmed past returns, so each bar’s forecast is known before that bar’s own return forms — a genuine one-step-ahead forecast. Historical values do not change.
- **Kernels.** Each feature blends a fast, a medium and a slow-tail kernel. The slow tail approximates the heavy, slowly-decaying weighting that long-memory volatility requires; the fast kernel keeps it responsive.
- **Positivity.** The activity feature is floored to stay strictly positive, keeping the forecast well-defined.
- **Calibration.** A 4-predictor ridge regression is solved each bar over a rolling window via standardised correlation-matrix inversion, then mapped back to raw units. Ridge (a single, adjustable penalty) is what keeps the correlated predictors from producing erratic coefficients.
### How to read it
- **Bold line** = the model’s volatility **forecast**; **faint line** = the **realised** volatility it tracks. Close agreement = the model fits here.
- **Driver** tells you *why* volatility is where it is: **Path** (a falling path lifting vol = leverage/fear, or a strong rally = upside), **Activity** (recent churn persisting), or **Memory** (volatility coasting on its own persistence). The % is that channel’s share.
- **Model fit** is the rolling R² — how much of realised-vol variance the path explains on this symbol. Trust the forecast more when it is high; treat it cautiously when it reads “weak.”
- **Regime** (Low / Normal / High / Extreme) is the forecast’s own percentile. Rising vol from a Low regime is an expansion; this is context, not a trade call.
- **Markers:** ▲ red = a fear-driven spike; ◆ amber = a volatility expansion into the High regime.
A practical note: this forecasts the **size** of moves, not their **direction**. A high forecast says “expect bigger swings,” not “go long/short.” Typical uses are risk-management context (sizing, stop width), regime filtering (compressed Low regimes precede expansions; Extreme regimes tend to mean-revert), and options-style context (is volatility likely to rise or fade) — always as context layered on your own method.
### Universal data layer (works on any asset, any market)
The script reads the chart’s own symbol by default, so it runs on equities, futures, FX, crypto and indices with no configuration. Settings let you:
- choose the **price source** (close / hl2 / hlc3 / ohlc4),
- optionally compute the forecast on a **different symbol** than the one charted,
- optionally run on a **fixed calculation timeframe** for a stable basis,
- choose the realised-vol estimator (range-based or close-to-close) for symbols with or without usable ranges.
The dashboard theme is **adaptive**: it reads the chart background and keeps text and cells legible on dark or light colour schemes (or you can force Dark/Light).
### What makes it original
A working, per-instrument path-dependent **realised-volatility forecaster** with rolling ridge self-calibration, a three-way (Path / Activity / Memory) decomposition, and an on-chart fit score — a recent institutional volatility concept made legible and measurable on a chart, rather than an ATR or a standard-deviation band. It does not merely display a volatility statistic; it fits a small volatility model to the symbol and shows you both the forecast and how much to trust it.
### Limitations (honest)
- Volatility is forecastable but never certain. The realised-volatility research this builds on explains a **minority** of realised-vol variance even at its best, so a rolling fit in the 0.3–0.6 range is doing well, not failing.
- The forecast is a **reduced, practical form** of the underlying framework; it is meant as context, not a precise volatility product.
- The fit dips through structural breaks; the dashboard shows it (“weak”), which is itself useful information.
- An optional higher calculation timeframe than the chart can update intrabar until that bar closes; the default (chart timeframe) does not.
### Credits
The path-dependent volatility framework this script operationalises is from the academic work of **J. Guyon and J. Lekeufack, “Volatility is (mostly) path-dependent” (2023)**. The persistence/memory predictor follows the heterogeneous-autoregressive (HAR) realised-volatility approach of **F. Corsi (2009)**. The range-based realised-variance estimator is **Garman & Klass (1980)**. The activity-positivity treatment follows results by **Nutz & Riveros Valdevenito** and **Andrès & Jourdain**. This implementation, the rolling ridge self-calibration, the Path/Activity/Memory decomposition, and the on-chart fit score are the author’s own work.
### Disclaimer
This script is a study/indicator for chart analysis and education only. It is **not** a strategy, **not** a recommendation, and **not** financial advice. It places no orders and guarantees no outcome. All values are estimates derived from price and can be wrong, especially through structural breaks and on illiquid or low-history symbols. Markets carry risk; do your own research and manage your own risk.
Indicatore

Options Probabilistic Bounds [InferredSignals]█ OVERVIEW
Options Probabilistic Bounds (OPB) draws a forward price corridor on the daily chart — an upper and a lower band projected over a horizon you choose (1 to 20 trading days) at a confidence level you choose (default 95%).
In plain words: given how this stock has actually been moving, where could the CLOSING price realistically land over the next few days? The corridor is calibrated so that, at each horizon, roughly your chosen percentage of closes finish inside it.
It is built for option sellers — short puts in particular. The lower band is a statistically calibrated reference for where to place a strike. And because the corridor takes no view on direction, OPB adds something most volatility tools don't: a drift readout that tells you which side currently has the wind at its back, so you can see whether puts or calls are the safer leg to sell right now.
No option-chain data is used anywhere — no implied volatility, no greeks, no implied-vol skew. "Options" describes who the tool is for, not what it reads. OPB is a pure statistical model of the underlying's own price history.
█ WHAT MAKES IT ORIGINAL
• Per-symbol MAP-style calibration, entirely in Pine.
Parameters are fitted to each ticker by minimizing a penalized negative log-posterior — Student-t likelihood, Bayesian-style priors, and residual-moment penalties combined in one objective — searched multi-start and coarse-to-fine, with the winner chosen on residual quality, not likelihood alone. The result: less in-sample curve-fitting and a steadier calibration than a plain best-fit vol model.
• Two-component, leverage-aware GJR-GARCH variance.
A slow long-run level plus a faster mean-reverting short-run component, so a volatility shock decays over a few days instead of holding the corridor wide for weeks. Negative-return days get a specific leverage response — downside risk is modeled, not averaged away.
• Filtered historical tails with EVT extension.
The residual body is empirical (Filtered Historical Simulation); each tail is extended with a Generalized Pareto fit whose shape and scale are estimated in closed form by Probability-Weighted Moments (Hosking-Wallis) — more stable than method-of-moments or MLE on the small tail samples you actually get. The shape is floored at zero so equity tails are never assumed bounded, and with too few exceedances it falls back to empirical quantiles rather than overfitting noisy extremes.
• Data-driven downside asymmetry.
The downside leverage increment is routed fully to the lower band; the upper band receives only a data-driven semivariance fraction. The corridor widens below only as far as the symbol's own history justifies.
█ THE DRIFT READOUT — WHICH SIDE TO SELL
The bands are DRIFT-NEUTRAL by design: centered on today's close, never tilted up or down. Over 1–20 days, direction is effectively unestimable from price history — and a wrong directional bet would quietly under-reserve the downside, the worst place to be short a put. So the whole band width is spent on dispersion, none of it gambled on a direction the data can't support.
OPB still measures the recent drift and reports it as a small number next to σ, in :
• ↑ : favors puts — the stock has been drifting up, so the put leg has had a cushion.
• ↓ : favors calls — drifting down, the call leg has had the cushion.
• flat — no meaningful drift.
Practical read: it is usually safer to sell the leg the drift is moving AWAY from — sell puts into an uptrend, calls into a downtrend. The wind at your back.
In the backtest this shows up cleanly: on a strongly trending stock the drift-neutral bands breach the TREND side more often than the nominal rate, while the opposite side stays close to it. This is expected, not miscalibration — the corridor is honestly direction-agnostic, so the band width itself stays unbiased and the extra breaches on the trend side are pure drift. The takeaway matches the readout: the side you should be selling — the one the trend is moving away from — is the side that stays calibrated. One caveat: the drift readout is the RECENT past, never a forecast — a strong reading is often exactly where mean-reversion becomes most likely. The fat-tailed band remains the real safety net.
MU · daily · walk-forward, monthly recals. On this uptrend the trend side (Brch+) runs well above nominal while the put-sell side (Brch−) holds at/below its 2.5% target — the drift asymmetry described above, in numbers.
█ HOW TO USE IT
• Set a horizon (e.g. 5 days) and a confidence level (e.g. 95%).
• Read the upper/lower band at your horizon as a strike-placement reference.
• Glance at the drift readout to pick the safer leg — puts vs calls.
• Turn on the walk-forward backtest and check: Close-in ≈ your confidence level; Brch+ / Brch− near the per-side rate and reasonably balanced; NT dn = how often a lower-band strike was never touched over the whole path — the number that matters for assignment.
• Optional PIT diagnostic: D ≈ 1 well-sized, D < 1 too wide, D > 1 too narrow. Read h = 1 first (least affected by overlapping windows).
• Anchor mode D-1…D-5 freezes the corridor as it looked N days ago, calibrated only on data known then — handy to inspect how past corridors held.
█ SETTINGS
Defaults are robust and research-oriented: Horizon 5d · Confidence 95% · Calibration window 252d · Two-component variance ON · Leverage-asymmetric bands ON · Earnings-gap neutralization ON.
"Long-run half-life" sets how steady the long-run volatility baseline is — a higher value keeps it stiffer after a shock, which (with the two-component model on) reduces post-shock over-widening.
Every input ships with a plain-language tooltip. Daily timeframe only. Calibration runs on the last bar for performance; walk-forward recalibration is monthly, a Pine execution-time constraint.
█ WHAT IT IS NOT
• Not a directional forecast — the corridor is drift-neutral, centered on the anchor close.
• Not a joint path bound — confidence targets the close at each horizon separately; the chance of touching a band along the path is the separate No-Touch figure (see backtest).
• Not an option-pricing model — no implied volatility, greeks, or option-chain data.
• Not a guarantee — the backtest and PIT diagnostics are historical calibration evidence, not a promise of future coverage.
Full methodology, equations, and references are documented section by section in the source code. This is a research and educational tool, not investment advice.
Indicatore

FVG Sigma [Smart Money]A Fair Value Gap is a 3-candle imbalance: the middle candle runs hard and leaves a void between candle 1 and candle 3. The problem with marking them is that gaps come in every size — most tools draw every single one, and the chart fills with noise where trivial micro-gaps sit next to the ones that actually mattered. FVG Sigma measures each gap's width and keeps only the statistically unusual ones.
HOW IT WORKS
Every gap's geometric width is fed into a rolling sample pool, with separate pools for bullish and bearish gaps. A new gap is z-scored against its own pool *before* it is added (no look-ahead into its own sample):
`z = (gap width − mean) / standard deviation`
Only gaps with `z >= threshold` (e.g. 2 sigma) are drawn — "unusually large for this symbol on this timeframe." Because a z-score is scale-free (the mean and the standard deviation share the gap's own units), there is no ATR or point normalization to tune; sigma absorbs symbol and timeframe scale on its own. The pool still collects *every* gap, so the baseline stays honest — but only the outliers reach the chart. Until a pool has gathered Min Samples gaps, nothing is drawn (warm-up).
Each surviving gap is then tracked for mitigation. The zone splits into a vivid *fresh* band and a faded *consumed* band at the deepest penetration so far (a high-water mark that never retreats), and an in-zone label reports consumption as a live percentage. When the consumed front reaches the far edge, the gap is fully mitigated and removed (or kept faded, your choice).
1) A confirmed 3-candle gap is measured and z-scored against its side's pool
2) If `z >= threshold`, the zone is drawn; otherwise it is only added to the pool
3) Price penetration splits the zone fresh/consumed and updates the live percentage
HOW TO READ
- A vivid band is the fresh, un-touched portion of a significant gap.
- The faded band behind it is the part price has already traded through.
- The in-zone label is the live consumed percentage (how much of the gap is gone).
- "Significant" means statistically large — an unusual imbalance, not a buy or sell instruction. A large gap is just a large gap; it does not predict fill, reversal, or direction. The tool marks the area; the read is yours.
INPUTS
- Sample Size N — how many recent gap widths each side's pool holds.
- Z-Score Threshold (sigma) — how extreme a gap must be to be drawn. Higher = fewer, stronger gaps.
- Min Samples — warm-up; filtering starts only once the pool has this many gaps.
- Mitigation — Wick (penetration tracked by bar high/low, live but exact) or Close (only confirmed closes count).
- Remove Mitigated / Avoid Overlap — drop fully-consumed zones; skip a new gap that overlaps a same-side one.
- Bullish FVG / Bearish FVG — enable each side independently.
- Show Last Bullish / Bearish — per-side display caps.
- Extend Right / Show Consumed % — projection length; toggle the live label.
- Style — bullish/bearish fills and text colours, fresh and mitigated transparency.
ALERTS
Two separate conditions: New significant Bullish FVG and New significant Bearish FVG. Both fire on closed bars — use "Once Per Bar Close."
NOTES & LIMITS
This is a statistical observation, not a forecast: the filter flags gaps that are unusually large for the current symbol and timeframe, nothing more. It does not say a gap will be filled, hold, or reverse. Scale-free by design — the z-score normalizes symbol and timeframe scale, so there is no ATR or point setting to calibrate. No repaint, no lookahead: gaps are created on confirmed (closed) bars only and their levels never move. Mitigation in Wick mode updates the consumed percentage live but stays exact, because a bar's high/low is a running extreme that is never revised; Close mode updates only on bar close. Open-source under CC BY-NC-SA 4.0 — non-commercial use, attribution to ElisTools required for reuse or derivatives. TradingView (Pine v6) only.
Indicatore

Multi-Divergence Strategy | GainzAlgoThe Multi-Divergence Strategy is a comprehensive, quantitative trading tool designed to identify momentum exhaustion through multi-oscillator divergence detection. By visualizing the relationship between price action and nine distinct momentum/volume metrics, this indicator provides a framework for identifying high-probability reversal setups.
Core Logic: How it Identifies Divergence
The indicator functions by monitoring pivot highs and lows across both price and nine independent oscillators (RSI, MFI, Stochastic, Z-Score, ADX, MACD, OBV, Price Action, and Swing Volume).
Logic: The script flags a Bullish Divergence when the price reaches a lower low, but the oscillator reaches a higher low. Conversely, it flags a Bearish Divergence when the price reaches a higher high, but the oscillator reaches a lower high.
Trigger: The script creates a dynamic detection system that triggers signals only when new pivot highs or lows are confirmed, ensuring signals are not repainting.
The Technical Overlay
The Technical Overlayis a visual dashboard that renders seven distinct indicator panes directly on your main chart.
Customization: The Window Width input allows you to adjust the lookback period for these panels, while the Future Offset allows you to shift the UI horizontally to avoid cluttering current price action.
Visuals: When divergence is detected, the overlay renders "neon" glowing markers at the exact pivot point where the divergence occurred, providing immediate visual feedback on which indicator is signaling the reversal.
Settings and Toggle Menus
The indicator is highly modular, allowing for granular control via the inputs menu.
General Settings:
Window Width (Bars): Defines the depth of the visual analysis panes.
Future Offset (Bars): Offsets the UI panels relative to the current bar.
Divergence Pivot Length: Adjusts sensitivity. Lower values (e.g., 2-5) detect micro-divergences, while higher values (up to 15) isolate major structural shifts.
Show Technical Overlay: A master toggle to turn the neon dashboard on or off.
Screener and Risk Management Settings:
SL/TP Multipliers: These adjust the Stop Loss (SL) and Take Profit (TP) distance based on the 14-period Average True Range (ATR).
Custom SL %: If enabled, this bypasses the ATR-based stop in favor of a fixed percentage-based stop loss.
Visuals: Show TP / SL Lines toggles the display of active trade plans on the chart, helping you visualize your risk parameters.
Risk Management and P&L Calculations
Every signal detected by the strategy is treated as a trade plan with a defined entry, stop, and target.
Stop Outs and Exits: The script performs a rolling calculation of every active trade. A trade is closed (marked as a loss) if price hits the SL level, or closed (marked as a win) if price hits the TP level.
ATR-Based P&L: The P&L is not based on arbitrary dollar amounts, but on ATR multipliers. This ensures your performance metrics are normalized against the current market volatility.
Understanding the Performance Table
The performance table provides a real-time summary of every divergence indicator's effectiveness.
Signals: The total number of trades initiated by that specific indicator.
Wins/Losses: The count of trades that reached the TP vs. the SL.
Win%: The percentage of closed trades that resulted in a win.
Avg Win/Loss: The average ATR distance captured in winning trades versus the average risk taken in losing trades.
Cumulative ATR Multi: This is the most critical metric. It represents the total P&L of the strategy expressed in ATR multiples.
A Note on Win Rate and Expectations: You may observe an average win rate of approximately 37%. Do not get discouraged by a low win rate. In quantitative trading, a "high" win rate is often irrelevant if the risk management is poor.
Instead of focusing on the strike rate, prioritize the Cumulative ATR Multi. A strategy with a 37% win rate can be highly profitable if your "Average Win" is significantly larger than your "Average Loss". Use the table to identify which specific indicators are yielding the highest cumulative ATR returns in the current market environment and lean into those signals.
How to Trade with the Strategy
Enable the Table: Keep Show Performance Table enabled to track the "Cumulative ATR Multi" for each indicator.
Monitor Signals: When a neon marker appears on your chart, verify the entry, stop-loss, and take-profit lines.
Analyze and Execute: Focus your trades on the indicators that show a positive or rising "Cumulative ATR Multi" in the performance table.
Risk Management: Always respect the stop-loss lines, as they are calculated to keep your risk consistent with current market volatility.
Disclaimer: This indicator is for analytical and educational purposes only. Past performance does not guarantee future results.
Indicatore

Indicatore

Effort vs Result [Wyckoff]Wyckoff's "effort vs result," quantified. Effort = volume (how much trading took place). Result = how far price actually travelled. When a bar shows heavy effort but little result, supply/demand is being absorbed — a battle worth marking.
HOW IT WORKS
Effort and result are turned into z-scores over a rolling window, so "high" and "low" mean high/low for this symbol on this timeframe — not a fixed number.
Absorption (high effort, low result) does not give direction — it only marks an important area where effort got absorbed. The indicator draws that area as a zone and waits. The zone develops, growing to include every following bar. The moment price closes beyond the developing range — either side, any volume — the level has given way. That break, in its own direction, is the signal.
1) Absorption seeds a zone (its high–low)
2) Each following bar expands the range
3) A close beyond the range = breakout (within N bars), otherwise the zone is discarded
HOW TO READ
- Grey dashed box: a developing absorption zone (directionless).
- Green triangle below a bar: bullish breakout (closed above the zone) — box turns green.
- Red triangle above a bar: bearish breakout (closed below the zone) — box turns red.
Zones that time out or get breached without a clean close disappear, so only meaningful areas remain.
INPUTS
- Z-Score Lookback — window for the rolling mean / standard deviation.
- Divergence Threshold (σ) — how extreme a bar must be to count as absorption. Higher = fewer, stronger zones.
- Result Source — Range (high−low), Body (|close−open|), or True Range (gap-aware).
- Detection Mode — Score (combined divergence, looser) or Strict (both legs extreme).
- Max Bars: Absorption → Breakout — how long a zone waits before being discarded.
- Visuals — show/hide zones, arrows, labels, colours.
ALERTS
Two separate conditions: Bullish Breakout and Bearish Breakout (use "Once Per Bar Close").
NOTES & LIMITS
Volume reliability depends on the symbol/feed — on spot FX it is tick volume, not real contracts; no volume = no signals. This is a statistical observation, not a forecast: a z-score flags an unusual bar, a breakout shows a level gave way — neither guarantees what price does next. No repaint, no lookahead: all calculations are on closed bars; z-scores use past bars only. Indicatore
