OPEN-SOURCE SCRIPT
Atualizado

BBands + Overbought/Oversold Markers

1 304
Advanced Bollinger Bands indicator with overbought/oversold signals, automatic squeeze detection, and multi-timeframe (MTF) capabilities.

Retains all functions of the original Bollinger Bands indicator from TradingView with a few added features:
  • Overbought/Oversold Markers: Visual signals when price opens and closes outside the bands
    🔴 Red Highlight & Arrow → Price opens & closes above the upper BB (potential overbought/excess momentum).
    🟢 Green Highlight & Arrow → Price opens & closes below the lower BB (potential oversold/reversal).
  • Squeeze Detection: Automatically highlights when bandwidth reaches its lowest point (narrowest BB width) in the lookback period, signalling potential breakout zones
  • Multi-Timeframe Bands: Display Bollinger Bands from any timeframe on your current chart (e.g., weekly bands on a daily chart), including markers and squeeze zones snapshot
  • Dual Rendering MTF Modes: Choose between traditional plots (unlimited history) or smooth line drawing (~125-165 MTF bars of history)
  • Built-in Alerts: Set alerts for overbought conditions, oversold conditions, squeeze detection, or any combination

Fully Customizable: Adjust MA type (SMA/EMA/RMA/WMA/VWMA), standard deviation multiplier, colors, and marker styles

Perfect for: Swing traders, MTF analysis, volatility-based entries, and identifying consolidation/expansion cycles.
Notas de Lançamento
Fixed Alert Timing & Added Timeframe Info:

Fixed issue where alerts were firing prematurely on intrabar price action instead of waiting for confirmed candle closes. Alerts now only trigger when a candle opens AND closes entirely above the upper band (overbought) or below the lower band (oversold), ensuring more reliable signals with no false positives.

Added chart timeframe to all alert messages (e.g., "Overbought signal on (2D)") for better context when managing multiple alerts across different symbols and timeframes.
Notas de Lançamento
This update adds a historical performance table that automatically tracks and evaluates all Bollinger Band overbought and oversold signals in real time.

snapshot

Each signal is monitored until it reaches a user-defined reversion target (basis, opposite band, retracement level, or opposite signal). Once resolved, the table calculates:
  • Total signals and active (unresolved) signals
  • Win rate with win/loss breakdown
  • Average winning and losing percentage moves
  • Average time required for mean reversion

Statistics are calculated separately for overbought and oversold conditions, providing a clear view of how each side performs under different market conditions and timeframes.

This allows traders to objectively measure the historical reliability, speed, and profitability of Bollinger Band mean-reversion behavior directly on the chart.
Notas de Lançamento
This update transforms the indicator from a simple signal generator into a complete backtesting and live trading tool. The addition of stop loss management, multiple exit detection methods, and advanced metrics (EV, MFE, DD) gives traders realistic performance data. The enhanced visualization with active trade tracking makes it practical for actual trading use, not just historical analysis.
snapshot
1. Advanced Trade Detection Options
Target Detection Modes: Three methods for determining when trades are closed to match your trading style:
  • Close: Target must be reached by candle close price
  • Wick: Target can be reached by high/low wick for faster exits
  • Cross: Trade closes as soon as price crosses the target intrabar

2. Stop Loss Management
  • Configurable Stop Loss: Set maximum loss percentage (-1% to -500%)
  • Automatically closes trades when loss threshold is exceeded
  • Stop Loss Tracking: Statistics now track stop loss hit rate separately
  • Visual indicators show which trades were stopped out

snapshot
3. Enhanced Trade Visualization
Active/Pending Trade Lines
  • Separate controls for past trades vs. active trades
  • Active Shorts/Longs: Show current open positions with live target projections
  • Past Shorts/Longs: Historical completed trades with exit points
  • Line Style Options: Choose Diagonal or L-Shape for different visual preferences
  • Smart Spacing: Automatically offsets overlapping lines for clarity

Win/Loss Labels Improvements - Three Display Modes:
  • Past: Show only completed trades
  • Active: Show only open positions with live P&L
  • Both: Show all trades

Label Limit Control: Set max labels per type (1-250) to prevent clutter
Real-time P&L: Active trades show current unrealized profit/loss percentage
snapshot
4. Advanced Performance Metrics
Maximum Favorable Excursion (MFE)
  • Tracks the best price move in your favor before trade closes
  • Shows average MFE for winning trades
  • Helps identify if you're exiting too early

Maximum Drawdown (DD)
  • Tracks worst adverse price movement during winning trades
  • Shows how much pain you had to endure before profit

Expected Value (EV)
  • New primary metric showing mathematical edge
  • Formula: (Win Rate × Avg Win) - (Loss Rate × Avg Loss)
  • Color-coded: Green (positive EV), Orange (breakeven), Red (negative EV)
  • Tells you if the strategy is statistically profitable

5. Improved Statistics Table
  • Better Organization
  • Visual Grouping: Background shading groups related metrics
  • Timeframe Display: Shows which display timeframe settings are active
  • Target Method Display: Shows both target type and detection method

6. Performance Optimizations
Memory Management
  • Buffer limits: Separate limits for drawable vs. trackable history
  • Automatic cleanup: Old pending signals beyond drawable range are removed
  • FIFO System: When max signals reached, oldest is automatically removed

Code Efficiency
  • Combined loops: Single-pass calculation of all statistics
  • Cached values: Stores frequently accessed data to reduce redundant calculations
  • Pre-calculated globals: Price ranges and TA functions computed once per bar
  • Significantly reduced execution time and memory usage

Technical Improvements
Signal Detection Enhancements
  • More accurate historical position tracking
  • Better handling of MTF (Multi-Timeframe) data
  • Safety checks prevent drawing beyond available history
  • Better handling of replay mode and data reloading
  • Improved overlap detection for cleaner visuals
Notas de Lançamento
✅ Enhanced Cross Detection Mode via Gap Detection
- Now properly handles price gaps through targets
- More accurate P&L calculations for gap scenarios

✅ Bug Fix: Active Trade Labels
- Fixed issue where active labels required line visualization
- Labels now work independently from lines
Notas de Lançamento
Key Improvements

1. Enhanced Signal Detection
  • Real-time signal generation: Signals now trigger on the current bar close, eliminating the previous offsets which delayed alerts from firing until the following candle open. Trades now open on candle close for more accurate reversion targets.

snapshot
2. Stats Table Customization
  • Separate toggles for Shorts/Longs: Users can now independently show/hide stats for short trades and long trades
  • Theme support: Added selectableLight/Dark mode for better table visibility across different chart backgrounds
  • Streamlined inputs: Reorganized settings into clearer groups (Closed Trades, Open Trades) with unified styling controls

snapshot
3. Visual Enhancements
  • Win/Loss color coding: Closed trade lines now display in green (wins) or red (losses) instead of uniform colors, making performance instantly recognizable
  • Dynamic open trade colors: Active trade lines change color based on current PnL (green when profitable, red when losing)
  • Label filtering: New option to display only wins, only losses, or both for cleaner charts

Warning: TradingView automatically resets all alerts whenever a script is updated (this applies to all indicators). After updating, you'll need to set up your alerts again from scratch.

Aviso legal

As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.