Indicator · Pine Script v5 · On the chart

Bollinger Bands Signals

by techteam92· code credited to capissimo

This indicator calculates custom Bollinger Bands using one of four selectable moving averages, defaulting to VIDYA.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code96
Settings6inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago20 Nov 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

96 lines of Pine Script v5 from scripts/132-Bollinger-Bands-Signals.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

132-Bollinger-Bands-Signals.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=5
indicator("Bollinger Bands Signals", 'BBS', true, timeframe="", timeframe_gaps=true)   // UPDATED!!!

// Description:
// This indicator works well in trending markets on long runs and in mean-reverting markets, at almost any timeframe. 
// That said, higher timeframes are much preferred for their intrinsic ability to cut out noise.
// Be mindful, the script shows somewhat erratic jigsaw-like behaviour during consolidation periods when the price
// jupms up and down in indecision which way to go. Fortunately, there are scripts out there that detect such periods.
// You can choose between 4 Moving Averages, Vidya being the default. Period, Deviation and Bands Width parameters
// all all of them affect the signal generation.

// For the Pine Script coder this script is pretty obvious. 
// It uses a standard technical analysis indicator - Bollinger Bands - and appends it with a 'width' parameter and
// a signal generation procedure.
// The signal generation procedure is the heart of this script that keeps the script pumping signals.
// The BB width is used as a filter.
// You can use this procedure in your own scripts and it will continue generate signals according to your rules.


//-- Inputs

Data   = input.source(close,   'Dataset')
Ma     = input.string('Vidya', 'Base Moving Average', ['EMA','SMA','WMA','Vidya'])
Period = input.int   (42,      'Period [1..n]', 1)
Mult   = input.float (2.0,     'Deviation [0.01..50]', minval=0.01, maxval=50, step=0.01)
Width  = input.float (0.019,   'Bands Width [0.0001..0.1]',  minval=0.0001, maxval=0.1, step=0.0001)
Offset = input.int   (0,       'Offset [-500..+500]', -500, 500)

//-- Constants

var string up = 'Δ' 
var string dn = '∇'

type SignalType    // enum
    int BUY   = 1
    int SELL  =-1
    int CLEAR = 0

//-- Variables

var SignalType stype  = SignalType.new()
var int        signal = stype.CLEAR

//-- Functions

vidya(float x, int p) =>
    float mom = ta.change(x)
    float upSum = math.sum(math.max(mom, 0), p)
    float downSum = math.sum(-math.min(mom, 0), p)
    float cmo = math.abs((upSum - downSum) / (upSum + downSum))
    float alpha = 2 / (p + 1)
    float vidya = 0.0
    vidya := x * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)

//-- Logic

float basis = switch Ma
    'EMA'  => ta.ema(Data, Period)
    'SMA'  => ta.sma(Data, Period)
    'WMA'  => ta.wma(Data, Period)
    => vidya(Data, Period)
float dev   = Mult * ta.stdev(Data, Period)
float upper = basis + dev
float lower = basis - dev
float width = (upper-lower)/basis

// signal generation procedure
bool long  = (ta.crossunder(close, lower) or close>basis or close>lower) and width>Width    
bool short = (ta.crossover (close, upper) or close<basis or close<upper) and width>Width    

// assemble a signal
signal := long  ? stype.BUY  : 
          short ? stype.SELL : 
          nz(signal[1])

int  changed         = ta.change(signal) 
bool long_condition  = changed and signal==stype.BUY  
bool short_condition = changed and signal==stype.SELL

//-- Visuals

plot(basis,      "Basis", color=#FF6D00, offset=Offset)
p1 = plot(upper, "Upper", color=#2962FF, offset=Offset)
p2 = plot(lower, "Lower", color=#2962FF, offset=Offset)
fill(p1, p2, color.rgb(33, 150, 243, 95), "Background")
plotshape(long_condition,  '', shape.labelup,   location.belowbar, color.green, 0, up, color.white, size=size.tiny)
plotshape(short_condition, '', shape.labeldown, location.abovebar, color.red,   0, dn, color.white, size=size.tiny)

//-- Notification

alertcondition(long_condition,  'Go long',  'Upturn!')
alertcondition(short_condition, 'Go short', 'Downturn!')
alertcondition(long_condition or short_condition, 'Reversal', 'Time to ACT!')

Overview

Bollinger Bands Signals plots the upper band, lower band, and basis line directly on the price chart, with a filled background between the outer bands. Buy and sell shape signals are generated using price crosses relative to the bands and basis line, filtered by a minimum band width threshold to reduce noise during consolidation.

Details

Published by

techteam92 on GitHub

Code credit

capissimo, as written in the script's header

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
DatasetsourcecloseData
Base Moving AveragestringVidyaMa
Period [1..n]int42Period
Deviation [0.01..50]float2.0Mult
Bands Width [0.0001..0.1]float0.019Width
Offset [-500..+500]int0Offset
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This indicator plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [Alorse]

Acceleration Bands

by capissimo
114 stars

Acceleration Bands is an overlay indicator that plots a volatility envelope around a central simple moving average. It calculates upper and lower boundary bands scaled by the high-to-low bar range relative to the midpoint price, smoothed by an SMA over a user-

Indicator v4 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Acceleration Bands

Kalman Percentile Bands

by NQ-stats-MX
15 stars

Kalman Percentile Bands plots a volatility-adaptive Kalman mean along with three empirical percentile bands on each side of the price chart. It calculates a local-level Kalman filter as the fair value mean, normalizes price deviations by an EWMA of volatility,

Indicator v6 Mean reversionVolatility & bands
Updated 2 weeks ago · MIT GitHub repository of Kalman Percentile Bands

This indicator detects compressed corrective coils inside a higher-timeframe trend and signals when they resolve into clean directional breaks. It plots compression bands, fractal boxes, efficiency scores, and a light dashboard on the price chart. Signals clas

Indicator v6 Volatility & bandsSMC / ICT / price action
Updated 3 days ago · MIT GitHub repository of Compression Fractal Release [WavesUnchained]
6 stars

This indicator classifies price action into four distinct market regimes: Trend, Expansion, Compression, or Mean Reversion. It determines states using a simplified Hurst exponent estimate, ADX slope thresholds, and realized volatility measurements. Based on th

Indicator v6 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of Capital41 Regime Matrix v3

More Volatility & bands scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers