Strategy · Pine Script v5 · On the chart

Bollinger Band Strategy with Split, Limit, Stop

by hasnocool

A strategy based on Bollinger Bands that enters long positions when price crosses above the lower band and short positions when price crosses below the upper band.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code74
Settings4inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 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 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

74 lines of Pine Script v5 from Bollinger Band strategy with split, limit, stop.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Bollinger Band strategy with split, limit, stop.pine
//@version=5
strategy(title='Bollinger Band strategy with split, limit, stop', shorttitle='bb strategy', overlay=true,commission_type = strategy.commission.percent, commission_value = 0.01, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, pyramiding = 4)
//Summary: Going Long or Short when Entering after Breaking the Bollinger Bands\
//At this time, the stop-loss, profit-taking price, and pyramiding standard\
// are determined from the difference between the position average price and the band price.
//After entering the position, if the price crosses the mid-band line, the stop loss is adjusted to the mid-band line.
//each trade, entry position size = 10% of total cash
//max pyramiding is 4
//commission = 0.01%
start_time = input.time(timestamp("20 Jul 2020 00:00 +0300"), "Strstegy Start Date")
exit_time = input.time(timestamp("20 Jul 2023 00:00 +0300"), "Strategy Exit Date")
bgcolor(time[1]<start_time and time>=start_time?color.red:na)
bgcolor(time[1]<exit_time and time>=exit_time?color.blue:na)
in_period = time>=start_time and time<=exit_time
bb_length = input.int(20)
bb_mult = input.int(2)
[middle, upper, lower] = ta.bb(close,bb_length, bb_mult)
plot(middle, color=color.aqua)
plot(upper, color=color.orange)
plot(lower, color=color.orange)
long_cond = ta.crossover(close,lower)
short_cond = ta.crossunder(close,upper)
var saved_ph = 0.0
if strategy.opentrades>0 and strategy.opentrades[1]==0 and strategy.position_size > 0
    saved_ph := upper[1]
var saved_pl = 0.0
if strategy.opentrades>0 and strategy.opentrades[1]==0 and strategy.position_size < 0
    saved_pl := lower[1]
avg = strategy.position_avg_price
long_diff = saved_ph-avg
short_diff = saved_pl-avg
long_stoploss = avg - 1*long_diff
short_stoploss = avg - 1*short_diff
long_avgdown = avg - 0.5*long_diff
short_avgup = avg - 0.5*short_diff
long_profit_price = avg + 0.5*long_diff
short_profit_price = avg + 0.5*short_diff
var label _label = na
if in_period
    if long_cond and strategy.opentrades==0
        strategy.entry("Long",strategy.long)
    if long_cond and strategy.opentrades >0 and (close[1]<long_avgdown or close[2]<long_avgdown)
        strategy.entry("Long",strategy.long)
    if short_cond and strategy.opentrades==0
        strategy.entry("Short", strategy.short)
    if short_cond and strategy.opentrades>0 and (close[1]>short_avgup or close[2]>short_avgup)
        strategy.entry("Short",strategy.short)
plot(avg, style=plot.style_linebr)
plot(strategy.position_size > 0? long_profit_price: na,color=color.green, style=plot.style_linebr)
plot(strategy.position_size > 0? long_avgdown: na,color=color.yellow, style=plot.style_linebr)
plot(strategy.position_size > 0? long_stoploss: na,color=color.red, style=plot.style_linebr)
plot(strategy.position_size < 0? short_profit_price: na,color=color.green, style=plot.style_linebr)
plot(strategy.position_size < 0? short_avgup: na,color=color.yellow, style=plot.style_linebr)
plot(strategy.position_size < 0? short_stoploss: na,color=color.red, style=plot.style_linebr)
var co = false
if strategy.position_size > 0 and ta.crossover(close, middle)
    co := true
var cu = false
if strategy.position_size < 0 and ta.crossunder(close, middle)
    cu := true
if strategy.opentrades == 0
    co := false
    cu := false
if strategy.position_size > 0
    if co
        strategy.exit("Long Exit", "Long", limit=long_profit_price, stop=middle)
    else
        strategy.exit("Long Exit", "Long", limit=long_profit_price, stop=long_stoploss)
if strategy.position_size < 0
    if cu
        strategy.exit("Short Exit", "Short", limit=short_profit_price, stop=middle)
    else
        strategy.exit("Short Exit", "Short", limit=short_profit_price, stop=short_stoploss)
Expand (104 lines)

Overview

Take-profit, stop-loss, and scale-in price levels are dynamically calculated from the position average price relative to the opposite band. Up to four pyramiding entries are supported when price moves beyond scale-in thresholds. If price crosses the middle band during a trade, the stop loss is adjusted to the middle band.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Mean reversion, Breakout

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Strstegy Start Datetimetimestamp("20 Jul 2020 00:00 +0300")start_time
Strategy Exit Datetimetimestamp("20 Jul 2023 00:00 +0300")exit_time
bb_lengthint20bb_length
bb_multint2bb_mult
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

3 stars

This strategy plots Bollinger Bands on the price chart and enters long only when flat. It buys on a strong bullish close above the middle band or on a small-body pullback that tags the middle band with a long lower wick. The stop sits below the signal bar by a

Strategy v5 Volatility & bandsBreakout
Updated yesterday · None stated GitHub repository of H4 布林ATR型態多單策略

KC Integration

by Sikako
1 stars

KC Integration is a trading strategy that calculates multiple sets of Keltner Channels tailored for both trend-following and counter-trend conditions. It plots upper, middle, and lower channel bands directly on the main price chart to identify potential breako

Strategy v5 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of KC Integration
1 stars

The strategy detects range expansion by comparing the previous bar's range to its ATR multiple. It places pending stop entries above highs of up bars or below lows of down bars. On trigger it enters positions with take profit and stop loss in ticks using OCA g

Strategy v6 Volatility & bandsSupport & resistance
Updated 5 days ago · Apache-2.0 GitHub repository of PF probe 97 - tp/sl gap reversal oca

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers