OPEN-SOURCE SCRIPT
Z-Score Mean Reversion Strategy

Based on Indicator "Rolling Z- Score trend" by QuantAlgo
The Z-Score Mean Reversion Strategy is a statistical trading approach that exploits price extremes and their tendency to return to average levels. It uses the Z-Score indicator to identify when an asset has deviated significantly from its statistical mean, creating high-probability reversal opportunities.
Core Concept:
Z-Score measures how many standard deviations price is from its moving average
When Z-Score reaches extreme levels (±1.5 or more), price is statistically "stretched"
The strategy trades the expected "snap back" to the mean
Works best in ranging or mean-reverting markets
How It Works:
LONG Entry: When price becomes oversold (Z-Score < -1.5), expect upward reversion
SHORT Entry: When price becomes overbought (Z-Score > +1.5), expect downward reversion
Exit: When price returns closer to the mean or reaches opposite extreme
Risk Management: Stop loss at -3% and take profit at +5% by default
🎯 Best Settings by Market & Timeframe
Cryptocurrency (High Volatility)
Preset: Scalping
Timeframe: 15m - 1H
Lookback: 10-15 periods
Entry Threshold: 1.0 - 1.5
Stop Loss: 2-3%
Take Profit: 3-5%
Notes: Crypto moves fast; use tighter parameters for quicker signals
Forex (Medium Volatility)
Preset: Default or Swing Trading
Timeframe: 1H - 4H
Lookback: 20-25 periods
Entry Threshold: 1.5 - 2.0
Stop Loss: 1-2%
Take Profit: 2-4%
Notes: Works well on major pairs during normal market conditions
Stocks (Lower Volatility)
Preset: Swing Trading
Timeframe: 4H - Daily
Lookback: 25-30 periods
Entry Threshold: 1.5 - 1.8
Stop Loss: 2-4%
Take Profit: 4-8%
Notes: Best on liquid stocks; avoid during earnings or major news
Indices (Trend + Ranging)
Preset: Trend Following
Timeframe: Daily - Weekly
Lookback: 35-50 periods
Entry Threshold: 2.0 - 2.5
Stop Loss: 3-5%
Take Profit: 5-10%
Notes: Higher threshold reduces false signals; captures major reversals
⚙️ Optimal Configuration Guide
Conservative (Lower Risk, Fewer Trades)
Lookback Period: 30-40
Entry Threshold: 2.0-2.5
Exit Threshold: 0.8-1.0
Stop Loss: 3-4%
Take Profit: 6-10%
Momentum Filter: ON
Balanced (Recommended Starting Point)
Lookback Period: 20-25
Entry Threshold: 1.5-1.8
Exit Threshold: 0.5-0.6
Stop Loss: 2-3%
Take Profit: 4-6%
Momentum Filter: OFF
Aggressive (Higher Risk, More Trades)
Lookback Period: 10-15
Entry Threshold: 1.0-1.2
Exit Threshold: 0.3-0.4
Stop Loss: 1-2%
Take Profit: 2-4%
Momentum Filter: OFF
💡 Pro Tips for Best Results
When the Strategy Works Best:
✅ Ranging markets with clear support/resistance
✅ High liquidity assets (major pairs, large-cap stocks)
✅ Normal market conditions (avoid during crashes or parabolic runs)
✅ Mean-reverting assets (avoid strong trending stocks)
When to Avoid:
❌ Strong trending markets (price won't revert)
❌ Low liquidity / low volume periods
❌ Major news events (earnings, FOMC, NFP)
❌ Market crashes or euphoria phases
Optimization Process:
Start with "Default" preset on your chosen timeframe
Backtest 6-12 months to see performance
Adjust Entry Threshold first (lower = more trades, higher = fewer but stronger signals)
Fine-tune Stop Loss/Take Profit based on average trade duration
Consider Momentum Filter if getting too many false signals
Key Metrics to Monitor:
Win Rate: Target 50-60% (mean reversion typically has moderate win rate)
Profit Factor: Aim for >1.5
Average Trade Duration: Should match your timeframe (scalping: minutes/hours, swing: days)
Max Drawdown: Keep under 20% of capital
📈 Quick Start Recommendation
For most traders, start here:
Timeframe: 1H or 4H
Preset: Default (Lookback 20, Threshold 1.5)
Stop Loss: 3%
Take Profit: 5%
Momentum Filter: OFF (turn ON if too many false entries)
Test on BTCUSD, EURUSD, or SPY first, then adapt to your preferred instruments!
The Z-Score Mean Reversion Strategy is a statistical trading approach that exploits price extremes and their tendency to return to average levels. It uses the Z-Score indicator to identify when an asset has deviated significantly from its statistical mean, creating high-probability reversal opportunities.
Core Concept:
Z-Score measures how many standard deviations price is from its moving average
When Z-Score reaches extreme levels (±1.5 or more), price is statistically "stretched"
The strategy trades the expected "snap back" to the mean
Works best in ranging or mean-reverting markets
How It Works:
LONG Entry: When price becomes oversold (Z-Score < -1.5), expect upward reversion
SHORT Entry: When price becomes overbought (Z-Score > +1.5), expect downward reversion
Exit: When price returns closer to the mean or reaches opposite extreme
Risk Management: Stop loss at -3% and take profit at +5% by default
🎯 Best Settings by Market & Timeframe
Cryptocurrency (High Volatility)
Preset: Scalping
Timeframe: 15m - 1H
Lookback: 10-15 periods
Entry Threshold: 1.0 - 1.5
Stop Loss: 2-3%
Take Profit: 3-5%
Notes: Crypto moves fast; use tighter parameters for quicker signals
Forex (Medium Volatility)
Preset: Default or Swing Trading
Timeframe: 1H - 4H
Lookback: 20-25 periods
Entry Threshold: 1.5 - 2.0
Stop Loss: 1-2%
Take Profit: 2-4%
Notes: Works well on major pairs during normal market conditions
Stocks (Lower Volatility)
Preset: Swing Trading
Timeframe: 4H - Daily
Lookback: 25-30 periods
Entry Threshold: 1.5 - 1.8
Stop Loss: 2-4%
Take Profit: 4-8%
Notes: Best on liquid stocks; avoid during earnings or major news
Indices (Trend + Ranging)
Preset: Trend Following
Timeframe: Daily - Weekly
Lookback: 35-50 periods
Entry Threshold: 2.0 - 2.5
Stop Loss: 3-5%
Take Profit: 5-10%
Notes: Higher threshold reduces false signals; captures major reversals
⚙️ Optimal Configuration Guide
Conservative (Lower Risk, Fewer Trades)
Lookback Period: 30-40
Entry Threshold: 2.0-2.5
Exit Threshold: 0.8-1.0
Stop Loss: 3-4%
Take Profit: 6-10%
Momentum Filter: ON
Balanced (Recommended Starting Point)
Lookback Period: 20-25
Entry Threshold: 1.5-1.8
Exit Threshold: 0.5-0.6
Stop Loss: 2-3%
Take Profit: 4-6%
Momentum Filter: OFF
Aggressive (Higher Risk, More Trades)
Lookback Period: 10-15
Entry Threshold: 1.0-1.2
Exit Threshold: 0.3-0.4
Stop Loss: 1-2%
Take Profit: 2-4%
Momentum Filter: OFF
💡 Pro Tips for Best Results
When the Strategy Works Best:
✅ Ranging markets with clear support/resistance
✅ High liquidity assets (major pairs, large-cap stocks)
✅ Normal market conditions (avoid during crashes or parabolic runs)
✅ Mean-reverting assets (avoid strong trending stocks)
When to Avoid:
❌ Strong trending markets (price won't revert)
❌ Low liquidity / low volume periods
❌ Major news events (earnings, FOMC, NFP)
❌ Market crashes or euphoria phases
Optimization Process:
Start with "Default" preset on your chosen timeframe
Backtest 6-12 months to see performance
Adjust Entry Threshold first (lower = more trades, higher = fewer but stronger signals)
Fine-tune Stop Loss/Take Profit based on average trade duration
Consider Momentum Filter if getting too many false signals
Key Metrics to Monitor:
Win Rate: Target 50-60% (mean reversion typically has moderate win rate)
Profit Factor: Aim for >1.5
Average Trade Duration: Should match your timeframe (scalping: minutes/hours, swing: days)
Max Drawdown: Keep under 20% of capital
📈 Quick Start Recommendation
For most traders, start here:
Timeframe: 1H or 4H
Preset: Default (Lookback 20, Threshold 1.5)
Stop Loss: 3%
Take Profit: 5%
Momentum Filter: OFF (turn ON if too many false entries)
Test on BTCUSD, EURUSD, or SPY first, then adapt to your preferred instruments!
Script de código abierto
Siguiendo fielmente el espíritu de TradingView, el creador de este script lo ha publicado en código abierto, permitiendo que otros traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Puede utilizarlo de forma gratuita, pero tenga en cuenta que la publicación de este código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones que ofrecemos, no implican ni constituyen un asesoramiento financiero, ni de inversión, trading o cualquier otro tipo de consejo o recomendación emitida o respaldada por TradingView. Puede obtener información adicional en las Condiciones de uso.
Script de código abierto
Siguiendo fielmente el espíritu de TradingView, el creador de este script lo ha publicado en código abierto, permitiendo que otros traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Puede utilizarlo de forma gratuita, pero tenga en cuenta que la publicación de este código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones que ofrecemos, no implican ni constituyen un asesoramiento financiero, ni de inversión, trading o cualquier otro tipo de consejo o recomendación emitida o respaldada por TradingView. Puede obtener información adicional en las Condiciones de uso.