Build Bollinger Bands and inspect what the signals mean
An SMA, two deviation bands, and explicit closed-bar observations.
Add the built-in Bollinger Bands study or copy the example below. Compare the same source, length and multiplier before interpreting a band touch or a narrow channel. Neither identifies a profitable trade by itself.
Add the study and match its calculation
In TradingView Indicators, search for Bollinger Bands. Match Length 20, Source Close, SMA basis and multiplier 2 for this example. The three lines describe price relative to a moving window; they do not forecast a future price interval.
TradingView documents the band construction. John Bollinger explains that tags alone are not buy or sell signals and that 20 and 2 are defaults rather than universal optimum settings. Two deviations do not guarantee 95% future coverage.
Why Traders Use This Indicator
- Compare the selected source with its recent average and dispersion.
- Measure width relative to a positive price basis.
- Write a reproducible band-cross or width condition to test within a separate strategy.
| Parameter | Default | Description |
|---|---|---|
| Length | 20 | Window for both the SMA and standard deviation; chart bars, not necessarily days. |
| Source | Close | The same selected series feeds the average, deviation and cross events. |
| Multiplier | 2.0 | Scales dispersion. This example does not establish a best multiplier. |
| Width comparison | 100 prior bars | Compares percentage width with the preceding window, excluding the current bar. |
Calculate the bands and define the event
Basis = SMA(source, n); upper = basis + k × standard deviation; lower = basis − k × standard deviation. The example uses ta.sma and the default biased ta.stdev calculation over the same source and length.
For a hypothetical basis of 100, standard deviation of 3 and multiplier of 2, the bands are 106 and 94. Width is 100 × (106 − 94) / 100 = 12%. This is invented arithmetic, not market data. Percentage width is unavailable when the basis is not positive.
The orange marker requires width at or below the lowest width of the preceding comparison window. The purple marker requires width above that window’s maximum. The script waits for a current value and a value a full comparison window ago. A new width high can recur on successive bars; it is not a one-time squeeze-release detector.
Signal Interpretation
A cross means the selected source moved from at or below the upper band to above it, or from at or above the lower band to below it. Both the source and the bands move. Lines update on an open bar, but alert conditions and width markers wait for bar close.
A band tag does not require reversal. A narrow channel does not specify breakout timing or direction. The example has no plot offset, higher-timeframe request or backdated marker. Width appears in the Data Window, not in a separate pane.
Create a TradingView alert for a named condition. Recreate it after changing the script or inputs because alerts keep a script snapshot. Revised market data can still change historical calculations.
Combining with Other Indicators
Use a separate, explicit rule for direction, entries, exits and position size. If adding RSI, volume or MACD, compare results with and without that extra condition using the same dates and costs. More conditions do not establish better performance.
Writing Pine Script Manually
Challenges of Manual Coding
Place fill and plot calls in global scope; use a conditional color to toggle a fill.
Exclude the current bar from a prior-window breakout threshold.
Keep an overlay metric out of the price scale by using the Data Window.
Calculate cross functions every bar and confirm events at bar close.
//@version=6
indicator("Bollinger Bands and closed-bar events", shorttitle="BB events", overlay=true)
length = input.int(20, "Length", minval=2)
src = input.source(close, "Source")
mult = input.float(2.0, "Standard deviation multiplier", minval=0.1)
widthLookback = input.int(100, "Width comparison bars", minval=2)
showFill = input.bool(true, "Show band fill")
basis = ta.sma(src, length)
deviation = mult * ta.stdev(src, length)
upper = basis + deviation
lower = basis - deviation
// A percentage width needs a positive basis.
widthPercent = basis > 0 ? 100.0 * (upper - lower) / basis : na
priorLow = ta.lowest(widthPercent[1], widthLookback)
priorHigh = ta.highest(widthPercent[1], widthLookback)
ready = not na(widthPercent) and not na(widthPercent[widthLookback])
compressed = barstate.isconfirmed and ready and widthPercent <= priorLow
expanded = barstate.isconfirmed and ready and widthPercent > priorHigh
crossUp = ta.crossover(src, upper)
crossDown = ta.crossunder(src, lower)
upperEvent = barstate.isconfirmed and crossUp
lowerEvent = barstate.isconfirmed and crossDown
plot(basis, "SMA basis", color=color.blue)
upperPlot = plot(upper, "Upper", color=color.red)
lowerPlot = plot(lower, "Lower", color=color.teal)
fill(upperPlot, lowerPlot, color=showFill ? color.new(color.blue, 90) : na, title="Band fill")
plot(widthPercent, "Width (%) - Data Window", display=display.data_window)
plotshape(compressed, "Closed-bar width low", shape.circle, location.belowbar, color.orange, size=size.tiny)
plotshape(expanded, "Closed-bar width high", shape.diamond, location.abovebar, color.purple, size=size.tiny)
alertcondition(upperEvent, "Source crossed upper band", "Selected source crossed above the upper band at bar close on {{ticker}}.")
alertcondition(lowerEvent, "Source crossed lower band", "Selected source crossed below the lower band at bar close on {{ticker}}.")
alertcondition(expanded, "Width exceeds prior window", "Bollinger width exceeded the preceding comparison window at bar close on {{ticker}}.")Maintenance Note: This indicator draws bands and observations. It places no orders and reports no backtest performance. Width is a percentage for a positive basis only. The open-bar lines can change; markers and alerts wait for chart-bar close. Syntax checks do not establish profitability.
Build with Pineify Visual Editor
Pineify lets you configure supported indicators and export Pine Script. Available settings and plan requirements vary by indicator. Compare the generated rules with the example before using its signals.
| Feature | Manual Pine Script | Pineify Visual Editor |
|---|---|---|
| Band inputs | Write source, length and multiplier inputs. | Configure Source, Length, MA Type and StdDev in the BB module. |
| Plots | Plot the basis and bands; choose a fill color. | Configure the three line styles and band color. |
| Custom width event | Implement the prior-window and bar-close conditions. | Ask the AI Coding Agent for the exact rule, then review the source and chart behavior. |
Configure the existing BB module and inspect its generated source.
Combine supported indicator outputs in explicit conditions.
Request custom event logic from the AI Coding Agent and validate the result.
Step-by-Step Tutorial
Create an indicator
Open the Visual Pine Script Editor and add Bollinger Bands.
Match the inputs
Set Length 20, MA Type SMA, Source Close and StdDev 2 for comparison.
Review the plots and rules
Set the three line styles and band color. Custom width markers require their own explicit condition.
Export and compare
Compile in TradingView and compare closed-bar bands against the built-in study with matching inputs.
Trading Strategies & Pro Tips
Band-cross experiment
Count closed-bar crosses and inspect subsequent behavior before defining an order rule. For a strategy test, state exits, costs, sizing and sample dates.
Pro Tip: A signal count is not a return, and a band touch is not a guaranteed reversal.
Width comparison experiment
Hold the band inputs fixed and vary only the comparison window. Count width-high and width-low events on the same history.
Pro Tip: These are proposed tests, not reported profitable results.
Trend versus range samples
Choose samples before tuning and retain later untouched data. Evaluate any mean-reversion and trend-following rules separately.
Common Mistakes to Avoid
- Treating two deviations as a guaranteed 95% forecast interval.
- Comparing width with a maximum that includes the current value and expecting it to exceed that maximum.
- Confusing a plotted width observation with an order-executing strategy.
- Assuming a visual editor removes the need to inspect generated logic.
Frequently Asked Questions
Create bands with rules you can inspect
- Configure the BB inputs and line styles.
- Describe custom event conditions precisely.
- Review generated source and compare chart values.
Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.