OPEN-SOURCE SCRIPT
Z-Score Statistical Bands

Z-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.
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.
Script open-source
Dans l'esprit TradingView, le créateur de ce script l'a rendu open source afin que les traders puissent examiner et vérifier ses fonctionnalités. Bravo à l'auteur! Bien que vous puissiez l'utiliser gratuitement, n'oubliez pas que la republication du code est soumise à nos Règles.
Clause de non-responsabilité
Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.
Script open-source
Dans l'esprit TradingView, le créateur de ce script l'a rendu open source afin que les traders puissent examiner et vérifier ses fonctionnalités. Bravo à l'auteur! Bien que vous puissiez l'utiliser gratuitement, n'oubliez pas que la republication du code est soumise à nos Règles.
Clause de non-responsabilité
Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.