Strategy · Pine Script v5 · Own pane

Breakout Bollinger Band and Keltner Channel Strategy

by hayashi19· code credited to HayashiHitsuji

This strategy builds a normalised band reading from Bollinger Bands, Keltner Channels or the average of both, using Heikin Ashi closes over a 200-bar window by default, with an optional EMA smoothing.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code101
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago10 Jan 2022

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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

101 lines of Pine Script v5 from strategy/STRATEGY Breakout Bollinger Band & Keltner Channel (林19).pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

STRATEGY Breakout Bollinger Band & Keltner Channel (林19).pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HayashiHitsuji

//@version=5
strategy("STRATEGY: Breakout Bollinger Band & Keltner Channel (林19)", shorttitle = "S BBKC (林19)", overlay = false, format = format.price, pyramiding = 0, commission_type = strategy.commission.percent, commission_value = 0.1, default_qty_type = strategy.cash, default_qty_value = 100, currency = currency.USD, slippage = 1, process_orders_on_close = true, initial_capital = 100)

////////////////////////////////////////////////////////////////////////////////
// INDICATOR INPUT /////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Input: indicator type value =================================================

band_type   = input.session('BB%B', "Band Type", options = ['BBKC', 'BB%B', 'KC%K'])

src = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
band_period = input.int(200, "Band Value")
band_mult   = input.float(1.0, "Band Mult")

smooth      = input.bool(false, "Use smooth band?")
band_smooth = input.int(9, "Smooth Value")

upper_break = input.float(1.0, "Bullish Breakout")
lower_break = input.float(0.0, "Bearish Breakout")

// ========================================================================== //

////////////////////////////////////////////////////////////////////////////////
// INDICATOR CALCULATION & ALGORITHM ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Algo: set the bollinger band & keltner channel ==============================

[bb_mid, bb_upper, bb_lower] = ta.bb(src, band_period, band_mult)
[kc_mid, kc_upper, kc_lower] = ta.kc(src, band_period, band_mult)

// ========================================================================== //

// Calc: bb & kc calculation ===================================================

bbpb = smooth ? ta.ema((src - bb_lower) / (bb_upper - bb_lower), band_smooth) : 
         (src - bb_lower) / (bb_upper - bb_lower)
         
kcpk = smooth ? ta.ema((src - kc_lower) / (kc_upper - kc_lower), band_smooth) : 
         (src - kc_lower) / (kc_upper - kc_lower)
         
bbkc = smooth ? ta.ema((src - math.avg(bb_lower, kc_lower)) / (math.avg(bb_upper, kc_upper) - math.avg(bb_lower, kc_lower)), band_smooth) : 
         (src - math.avg(bb_lower, kc_lower)) / (math.avg(bb_upper, kc_upper) - math.avg(bb_lower, kc_lower))
         
band =  band_type == 'BBKC' ? bbkc : 
             band_type == 'BB%B' ? bbpb :
                 kcpk
// ========================================================================== //

// Algo: set color for inticator ===============================================

band_color  = band > upper_break ? color.lime : band < lower_break ? color.red : color.white
long        = ta.crossover(band, 0) ? color.lime : ta.crossover(band, 1) ? color.green : na
short       = ta.crossunder(band, 1) ? color.red : ta.crossunder(band, 0) ? color.maroon : na

// ========================================================================== //

////////////////////////////////////////////////////////////////////////////////
// PLOT INDICATOR //////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Plot: indicator and breakout line ===========================================

hline(upper_break, color = color.lime, linestyle = hline.style_solid, title = "Upper Breakout")
hline(lower_break, color = color.red, linestyle = hline.style_solid, title = "Lower Breakout")

hline(0.5, title = "Mid Breakout")

plot(band, color = band_color, linewidth = 2, title = "Band")
plot(1, color = long, style = plot.style_columns)
plot(1, color = short, style = plot.style_columns)

// ========================================================================== //

////////////////////////////////////////////////////////////////////////////////
// INDICATOR STRATEGY //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

// Strategy: algorithm for entry and exit ======================================

long_entry  = ta.crossover(band, 0)
short_entry = ta.crossunder(band, 1)

long_tp     = ta.crossover(band, 1)
short_tp    = ta.crossunder(band, 0)

// ========================================================================== //

// Strategy: the execution for long or short ===================================

strategy.entry("enter long", strategy.long, when = long_entry)
strategy.entry("enter short", strategy.short, when = short_entry)

strategy.close("enter long", when = long_tp, qty_percent = 100, comment = "take profit slong")
strategy.close("enter short", when = short_tp, qty_percent = 100, comment = "take profit short")

// ========================================================================== //

Overview

Bullish and bearish breakout levels at one and zero define when the reading is considered a breakout. Orders use a fixed cash amount with a small percentage commission and slippage. The entry and exit statements were not in the supplied part of the code, so how trades are managed is not confirmed.

Details

Published by

hayashi19 on GitHub

Code credit

HayashiHitsuji, as written in the script's header

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Band TypesessionBB%Bband_type
Band Valueint200band_period
Band Multfloat1.0band_mult
Use smooth band?boolfalsesmooth
Smooth Valueint9band_smooth
Bullish Breakoutfloat1.0upper_break
Bearish Breakoutfloat0.0lower_break
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

6 stars

This strategy identifies high-volatility expansion bars by comparing the high-low range to a moving average plus standard deviation threshold. When range expansion occurs, it checks momentum over a specified lookback period. It opens a long position if the cur

Strategy v5 Volatility & bandsOscillators & momentum
Updated 1 year ago · None stated GitHub repository of TradersPost High-Low Range Strategy
257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint
228 stars

This strategy detects price breakouts above rolling highest highs or below lowest lows over a customizable lookback period. It includes optional volume spike and ATR volatility threshold filters, along with bar confirmation rules. Positions are taken upon conf

Strategy v6 BreakoutVolatility & bands
Updated 3 months ago · None stated GitHub repository of Breakout Strategy Template

Bollinger Breakout

by hackingthemarkets
189 stars

This price-chart strategy plots a simple moving average and upper and lower bands built from the standard deviation of close, scaled by separate offset inputs. It enters a fixed quantity long when close crosses above the upper band and a fixed quantity short w

Strategy v4 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of Bollinger Breakout

2 Candles Inside ATR

by hasnocool
106 stars

2 Candles Inside ATR is an overlay script that measures volatility compression across two consecutive candles. It calculates a smoothed Average True Range (ATR) and compares it against the combined high and low range of the current and previous bars. When the

Strategy v4 Volatility & bandsBreakout
Updated 2 years ago · GPL-3.0 GitHub repository of 2 Candles Inside ATR

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