OPEN-SOURCE SCRIPT
BB SPY Mean Reversion Investment Strategy

Summary
Mean reversion first, continuation second. This strategy targets equities and ETFs on daily timeframes. It waits for price to revert from a Bollinger location with candle and EMA agreement, then manages risk with ATR based exits. Uniqueness comes from two elements working together. One, an adaptive band multiplier driven by volatility of volatility that expands or contracts the envelope as conditions change. Two, a bias memory that re arms the same direction after any stop, target, or time exit until a true opposite signal appears. Add it to a clean chart, use the markers and levels, and select on bar close for conservative alerts. Shapes can move while the bar is open and settle on close.
Scope and intent
• Markets. Currently adapted for SPY, needs to be optimized for other assets
• Timeframes. Daily primary. Other frames are possible but not the default
• Default demo. SPY on daily
• Purpose. Trade mean reversion entries that can chain into a longer swing by splitting holds into ATR or time segments
Originality and usefulness
• Novelty. Adaptive band width from volatility of volatility plus a persistent bias array that keeps the original direction alive across sequential entries until an opposite setup is confirmed
• Failure modes mitigated. False starts in chop are reduced by candle color and EMA location. Missed continuation after a take profit or stop is addressed by the re arm engine. Oversized envelopes during quiet regimes are avoided by the adaptive multiplier
• Testability. Every module has Inputs and visible levels so users can see why a suggestion appears
• Portable yardstick. All risk and targets are expressed in ATR units
Method overview in plain language
The engine measures where price sits relative to Bollinger bands, confirms with candle color and EMA location, requires ADX for shorts(in our case long close since we use it currently as long only), and optionally requires a trend or mean reversion regime using band width percent rank and basis slope. Risk uses ATR for stop, target, and optional breakeven. A small array stores the last confirmed direction. While flat, the engine keeps a pending order in that direction. The array flips only when a true opposite setup appears.
Base measures
• Range basis. True Range smoothed over a user defined ATR Length
• Return basis. Not required
Components
• Bollinger envelope. SMA length and standard deviation multiplier. Entry is based on cross of close through the band with location bias
• Candle and EMA filter. Close relative to open and close relative to EMA align direction
• ADX gate for shorts. Requires minimum trend strength for short trades
• Adaptive multiplier. Band width scales using volatility of volatility so envelopes breathe with conditions
• Regime gate optional. Band width percent rank and basis slope identify trend or mean reversion regimes
• Risk manager. ATR stop, ATR target, optional breakeven, optional time exit
• Bias memory. Array stores last confirmed direction and re arms entries while flat
Fusion rule
Minimum satisfied gates count style. All required gates must be true. Optional gates are controlled in Inputs. Bias memory never overrides an opposite confirmed setup.
Signal rule
• Long setup when close crosses up through the lower band, the bar closes green, and close is above the long EMA
• Short setup when close crosses down through the upper band, the bar closes red, close is below the short EMA, and ADX is above the minimum
• While flat the model keeps a pending order in the stored direction until a true opposite setup appears
• IN LONG or IN SHORT describes states between entry and exit
What you will see on the chart
• Markers for Long and Short setups
• Exit markers from ATR or time rules
• Reference levels for entry, stop, and target
• Bollinger bands and optional adaptive bands
Inputs with guidance
Setup
• Signal timeframe. Uses the chart timeframe
• Invert direction optional. Flips long and short
Logic
• BB Length. Typical 10 to 50. Higher smooths more
• BB Mult. Typical 1.0 to 2.5. Higher widens entries
• EMA Length long. Typical 10 to 50
• EMA Length short. Typical 5 to 30
• ADX Minimum for short. Typical 15 to 35
Filters
• Regime Type. none or trend or mean reversion
• Rank Lookback. Typical 100 to 300
• Basis Slope Length and Threshold. Larger values reduce false trends
Risk
• ATR Length. Typical 10 to 21
• ATR Stop Mult. Typical 1.0 to 3.0
• ATR Take Profit Mult. Typical 2.0 to 5.0
• Breakeven Trigger R. Move stop to entry after the chosen multiple
• Time Exit. Minimum bars and extension when profit exceeds a fraction of ATR
Bias and rearm
• Bias flips kept. Array depth
• Keep rearm when flat. Maintain a pending order while flat
UI
• Show markers and levels. Clean defaults
Usage recipes
Alerts update in real time and can change while the bar forms. Select on bar close for conservative workflows.
Properties visible in this publication
• Initial capital 25000
• Base currency USD
• If any higher timeframe calls are enabled, request.security uses lookahead off
• Commission 0.03 percent
• Slippage 3 ticks
• Default order size method Percent of equity with value 5
• Pyramiding 0
• Process orders on close On
• Bar magnifier Off
• Recalculate after order is filled Off
• Calc on every tick Off
Realism and responsible publication
No performance claims. Costs and fills vary by venue. Shapes can move intrabar and settle on close. Strategies use standard candles only.
Honest limitations and failure modes
High impact releases and thin liquidity can break assumptions. Gap heavy symbols may require larger ATR. Very quiet regimes can reduce contrast in the mean reversion signal. If stop and target can both be touched inside one bar, outcome follows the TradingView order model for that bar path.
Regimes with extreme one sided trend and very low volatility can reduce mean reversion edges. Results vary by symbol and venue. Past results never guarantee future outcomes.
Open source reuse and credits
None.
Backtest realism
Costs are realistic for liquid equities. Sizing does not exceed five percent per trade by default. Any departure should be justified by the user.
If you got any questions please le me know
Mean reversion first, continuation second. This strategy targets equities and ETFs on daily timeframes. It waits for price to revert from a Bollinger location with candle and EMA agreement, then manages risk with ATR based exits. Uniqueness comes from two elements working together. One, an adaptive band multiplier driven by volatility of volatility that expands or contracts the envelope as conditions change. Two, a bias memory that re arms the same direction after any stop, target, or time exit until a true opposite signal appears. Add it to a clean chart, use the markers and levels, and select on bar close for conservative alerts. Shapes can move while the bar is open and settle on close.
Scope and intent
• Markets. Currently adapted for SPY, needs to be optimized for other assets
• Timeframes. Daily primary. Other frames are possible but not the default
• Default demo. SPY on daily
• Purpose. Trade mean reversion entries that can chain into a longer swing by splitting holds into ATR or time segments
Originality and usefulness
• Novelty. Adaptive band width from volatility of volatility plus a persistent bias array that keeps the original direction alive across sequential entries until an opposite setup is confirmed
• Failure modes mitigated. False starts in chop are reduced by candle color and EMA location. Missed continuation after a take profit or stop is addressed by the re arm engine. Oversized envelopes during quiet regimes are avoided by the adaptive multiplier
• Testability. Every module has Inputs and visible levels so users can see why a suggestion appears
• Portable yardstick. All risk and targets are expressed in ATR units
Method overview in plain language
The engine measures where price sits relative to Bollinger bands, confirms with candle color and EMA location, requires ADX for shorts(in our case long close since we use it currently as long only), and optionally requires a trend or mean reversion regime using band width percent rank and basis slope. Risk uses ATR for stop, target, and optional breakeven. A small array stores the last confirmed direction. While flat, the engine keeps a pending order in that direction. The array flips only when a true opposite setup appears.
Base measures
• Range basis. True Range smoothed over a user defined ATR Length
• Return basis. Not required
Components
• Bollinger envelope. SMA length and standard deviation multiplier. Entry is based on cross of close through the band with location bias
• Candle and EMA filter. Close relative to open and close relative to EMA align direction
• ADX gate for shorts. Requires minimum trend strength for short trades
• Adaptive multiplier. Band width scales using volatility of volatility so envelopes breathe with conditions
• Regime gate optional. Band width percent rank and basis slope identify trend or mean reversion regimes
• Risk manager. ATR stop, ATR target, optional breakeven, optional time exit
• Bias memory. Array stores last confirmed direction and re arms entries while flat
Fusion rule
Minimum satisfied gates count style. All required gates must be true. Optional gates are controlled in Inputs. Bias memory never overrides an opposite confirmed setup.
Signal rule
• Long setup when close crosses up through the lower band, the bar closes green, and close is above the long EMA
• Short setup when close crosses down through the upper band, the bar closes red, close is below the short EMA, and ADX is above the minimum
• While flat the model keeps a pending order in the stored direction until a true opposite setup appears
• IN LONG or IN SHORT describes states between entry and exit
What you will see on the chart
• Markers for Long and Short setups
• Exit markers from ATR or time rules
• Reference levels for entry, stop, and target
• Bollinger bands and optional adaptive bands
Inputs with guidance
Setup
• Signal timeframe. Uses the chart timeframe
• Invert direction optional. Flips long and short
Logic
• BB Length. Typical 10 to 50. Higher smooths more
• BB Mult. Typical 1.0 to 2.5. Higher widens entries
• EMA Length long. Typical 10 to 50
• EMA Length short. Typical 5 to 30
• ADX Minimum for short. Typical 15 to 35
Filters
• Regime Type. none or trend or mean reversion
• Rank Lookback. Typical 100 to 300
• Basis Slope Length and Threshold. Larger values reduce false trends
Risk
• ATR Length. Typical 10 to 21
• ATR Stop Mult. Typical 1.0 to 3.0
• ATR Take Profit Mult. Typical 2.0 to 5.0
• Breakeven Trigger R. Move stop to entry after the chosen multiple
• Time Exit. Minimum bars and extension when profit exceeds a fraction of ATR
Bias and rearm
• Bias flips kept. Array depth
• Keep rearm when flat. Maintain a pending order while flat
UI
• Show markers and levels. Clean defaults
Usage recipes
Alerts update in real time and can change while the bar forms. Select on bar close for conservative workflows.
Properties visible in this publication
• Initial capital 25000
• Base currency USD
• If any higher timeframe calls are enabled, request.security uses lookahead off
• Commission 0.03 percent
• Slippage 3 ticks
• Default order size method Percent of equity with value 5
• Pyramiding 0
• Process orders on close On
• Bar magnifier Off
• Recalculate after order is filled Off
• Calc on every tick Off
Realism and responsible publication
No performance claims. Costs and fills vary by venue. Shapes can move intrabar and settle on close. Strategies use standard candles only.
Honest limitations and failure modes
High impact releases and thin liquidity can break assumptions. Gap heavy symbols may require larger ATR. Very quiet regimes can reduce contrast in the mean reversion signal. If stop and target can both be touched inside one bar, outcome follows the TradingView order model for that bar path.
Regimes with extreme one sided trend and very low volatility can reduce mean reversion edges. Results vary by symbol and venue. Past results never guarantee future outcomes.
Open source reuse and credits
None.
Backtest realism
Costs are realistic for liquid equities. Sizing does not exceed five percent per trade by default. Any departure should be justified by the user.
If you got any questions please le me know
Skrypt open-source
W duchu TradingView twórca tego skryptu udostępnił go jako open-source, aby traderzy mogli analizować i weryfikować jego funkcjonalność. Brawo dla autora! Możesz korzystać z niego za darmo, ale pamiętaj, że ponowna publikacja kodu podlega naszym Zasadom Społeczności.
🔻Website: finaur.com/
🔻Strategies: finaur.com/lab/
🔻Blog: finaur.com/blog/
🔻Telegram : t.me/finaur_com/
🔻Trader Psychology Profile – thelumenism.com/
🔻Strategies: finaur.com/lab/
🔻Blog: finaur.com/blog/
🔻Telegram : t.me/finaur_com/
🔻Trader Psychology Profile – thelumenism.com/
Wyłączenie odpowiedzialności
Informacje i publikacje przygotowane przez TradingView lub jego użytkowników, prezentowane na tej stronie, nie stanowią rekomendacji ani porad handlowych, inwestycyjnych i finansowych i nie powinny być w ten sposób traktowane ani wykorzystywane. Więcej informacji na ten temat znajdziesz w naszym Regulaminie.
Skrypt open-source
W duchu TradingView twórca tego skryptu udostępnił go jako open-source, aby traderzy mogli analizować i weryfikować jego funkcjonalność. Brawo dla autora! Możesz korzystać z niego za darmo, ale pamiętaj, że ponowna publikacja kodu podlega naszym Zasadom Społeczności.
🔻Website: finaur.com/
🔻Strategies: finaur.com/lab/
🔻Blog: finaur.com/blog/
🔻Telegram : t.me/finaur_com/
🔻Trader Psychology Profile – thelumenism.com/
🔻Strategies: finaur.com/lab/
🔻Blog: finaur.com/blog/
🔻Telegram : t.me/finaur_com/
🔻Trader Psychology Profile – thelumenism.com/
Wyłączenie odpowiedzialności
Informacje i publikacje przygotowane przez TradingView lub jego użytkowników, prezentowane na tej stronie, nie stanowią rekomendacji ani porad handlowych, inwestycyjnych i finansowych i nie powinny być w ten sposób traktowane ani wykorzystywane. Więcej informacji na ten temat znajdziesz w naszym Regulaminie.