Strategy library

Bollinger Bands Trend Following strategy in Pine Script

A close outside the Bollinger Bands, in the direction of two EMAs, opens a trend trade with an ATR stop.

Bollinger Bands · EMA · ATR · long and short · by Robrecht99 · Mozilla Public License 2.0

What is its backtest worth?

A parameter sweep finds the best setting of the Bollinger Bands Trend Following strategy. PineTester tells you if it holds up: whether the best result was only picked after the fact, what it makes with fees, what you could have known at the time (a walk-forward on data the pick did not see) and how deep it fell along the way. On the free start, your first own backtest gets the full evaluation; its trade list and result file come with the full report or a plan.

Creates a draft on Binance BTC/USDT 4h over about six and a half years with 0.1% commission per order and 2 ticks slippage; you start it yourself. A backtest uses credits; new accounts receive free credits.

The rules

  • Enters long when the close is above the upper band and the fast EMA is above the slow one; short when the close is below the lower band and the fast EMA is below.
  • Places a stop an ATR multiple from the entry; closes the long when the EMAs cross down, the short when they cross up.
  • Sizes each trade from a fixed risk per trade and the ATR.

What to watch for

  • Bands used for breakouts react late at turns; the EMA exit decides how much of a trend is kept.
  • Five varied inputs give many similar settings – the typical setting tells more than the top one.

How PineTester judges a backtest, with its sources: how we judge results.

The Pine Script code

The author's code with its licence notice (Mozilla Public License 2.0), with one change marked in the code: the same test conditions for every library strategy in its strategy() line – the whole account per trade (split over the entries where it adds to a position), 0.1% commission per order and 2 ticks slippage; the trading rules are unchanged. Pine Script v5; PineTester converts it to v6 automatically, so results can differ slightly from TradingView.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Robrecht99
// Modified by PineTester (2026-11-14): the same test conditions for every library strategy in strategy(): 100% of equity per entry,
// 0.1% commission per order, 2 ticks slippage, initial capital 10,000. The trading rules are unchanged.
//@version=5
strategy("Trend Following with Bollinger Bands", overlay=true, margin_long=0, margin_short=0, pyramiding=1, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, slippage=2)
// Bollinger Bands //
length = input.int(20, minval=1, group="Bollinger Bands Inputs")
src = input(close, title="Source", group="Bollinger Bands Inputs")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500, group="Bollinger Bands Inputs")
plot(basis, "Basis", color=color.orange, offset = offset)
p1 = plot(upper, "Upper", color=color.orange, offset = offset)
p2 = plot(lower, "Lower", color=color.orange, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(255, 0, 255, 95))
// Moving Averages //
len1 = input.int(40, minval=1, title="Length Fast MA", group="Moving Average Inputs")
len2 = input.int(120, minval=1, title="Length Slow MA", group="Moving Average Inputs")
src1 = input(close, title="Source Fast MA")
src2 = input(close, title="Source Slow MA")
maColorFast = input.color(color.new(color.red, 0), title = "Color Fast MA", group = "Moving Average Inputs", inline = "maFast")
maColorSlow = input.color(color.new(color.purple, 0), title = "Color Slow MA", group = "Moving Average Inputs", inline = "maSlow")
fast = ta.ema(src1, len1) 
slow = ta.ema(src2, len2)
plot(fast, color=maColorFast, title="Fast EMA")
plot(slow, color=maColorSlow, title="Slow EMA")
// ATR and Position Size //
leverage = input.int(title = "Leverage Used", defval = 1, minval = 1, group = "ATR Position Size Inputs")
pointvalue = input.int(title = "Point Value/ATR Multipliers from Entry", defval = 4, minval = 1, group = "ATR Position Size Inputs")
length1 = input.int(title = "ATR Period", defval = 14, minval = 1, group ="ATR Position Size Inputs")
risk = input(title = "Risk Per Trade", defval = 0.01, group = "ATR Position Size Inputs")
atr = ta.atr(length1)
amount = (risk * strategy.initial_capital / (pointvalue * atr * leverage))
// ATR Trailing Stops //
xATRPeriod = input.int(14, "ATR Period", group = "ATR Trailing Stop Inputs")
xATRMultiplier = input.float(4, "ATR Multiplier", step = .1, group = "ATR Trailing Stop Inputs")
xATR = ta.atr(xATRPeriod)
Stop = xATRMultiplier * xATR
var xATRTrailingStop = 0.0
xATRTrailingStop := if close>xATRTrailingStop[1] and close[1] > xATRTrailingStop[1]
    math.max(xATRTrailingStop[1], close - Stop)
else if close < xATRTrailingStop[1] and close[1] < xATRTrailingStop[1]
    math.min(xATRTrailingStop[1], close + Stop)
else if close > xATRTrailingStop[1]
    close - Stop 
else 
    close + Stop
var Position = 0.0
Position := if close[1] < xATRTrailingStop[1] and close > xATRTrailingStop[1]
    1
else if close[1] > xATRTrailingStop[1] and close < xATRTrailingStop[1]
    -1
else
    Position[1]
PlotColor = Position == -1 ? color.orange : Position == 1 ? color.orange : color.orange
plot(xATRTrailingStop, color=PlotColor, linewidth = input(2, "Line Width", group = "ATR Trailing Stop Inputs"), style = plot.style_circles, title = "ATR Trailing Stop")
// Buy and Sell Conditions //
entrycondition1 = ta.crossover(fast, slow)
entrycondition2 = fast > slow
sellcondition1 = ta.crossunder(fast, slow)
sellcondition2 = slow > fast
// Buy and Sell Signals //
if (close > upper and entrycondition2)
    strategy.entry("long", strategy.long, qty=amount)
    stoploss = close - atr * xATRMultiplier
    strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (sellcondition1 and sellcondition2)
    strategy.close(id="long")
if (close < lower and sellcondition2)
    strategy.entry("short", strategy.short, qty=amount)
    stoploss = close + atr * xATRMultiplier
    strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (entrycondition1 and entrycondition2)
    strategy.close(id="short")
  • RSI + EMA – Buys an oversold RSI while a faster moving average is above a slower one.
  • Tendency EMA + RSI – Buys a crossover of two short EMAs above a long EMA and takes profit after a set number of bars.
  • Omar MMR – A MACD crossover in an uptrend of three EMAs, with a fixed take profit and stop loss.
  • Crunchster's Turtle and Trend System – A Turtle-style channel breakout with a trailing channel exit and a position size set by recent volatility.
  • Ultimate Ichimoku Cloud – An Ichimoku entry that needs the conversion/base cross, the cloud, the lagging span and the price to agree.

Open-source script by Robrecht99, shown under the Mozilla Public License 2.0. Not a recommendation; neither the author nor TradingView endorses PineTester. Backtests are hypothetical results on past data, not a forecast.