Strategy · Pine Script v4 · On the chart

3Commas Bollinger Strategy

by hasnocool· code credited to tedwardd

This strategy backtests a long Bollinger Band deal on the price chart for 3Commas-style bots.

View on GitHub

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code84
Settings22inputs
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

84 lines of Pine Script v4 from 3Commas Bollinger Strategy.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

3Commas Bollinger Strategy.pine
//@version=4
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tedwardd
// This strategy is intended to help users of the 3commas.io platform backtest bot performance based on a Bollinger Strategy.
// It can also be used to signal a bot to open a deal by providing the Bot ID, email token and trading pair in the strategy settings screen.
// As currently written, this strategy uses a basic Bollinger Band strategy, recommening a deal start when the closing price crosses under the lower band.
// The thick red line plotted on the chart shows the average entry price of the current deal.
strategy("3Commas Bollinger Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=1000, initial_capital=5000, currency="USD", commission_value=0.1)
// 3Commas Bot settinsg
bot_type                = input(title="Simple bot", defval="composite", options=["simple", "composite"])
bot_id                  = input(title="3Commas Bot ID", defval="")
email_token             = input(title="Bot Email Token", defval="")
base_order_size         = input(title="Base order size",minval=10, step=1, defval=500)
safety_order_size       = input(title="Safety order size", minval=15, step=1, defval=1000)
volume_scale            = input(title="Safety Order Vol Scale (%)", minval=0.00, step=0.01, defval=1.83)
safety_step             = input(title="Safety Order Step Scale (%)", minval=0.00, step=0.1, defval=1.55)
safety_max              = input(title="Max Number of Safety Orders", minval=0, step=1, defval=4)
initial_deviation_input = input(title="Initial SO Deviation (%)", minval=0, step=0.01, defval=0.8) * 0.01
stoploss_input          = input(title="Long Stop Loss (%)", minval=0, step=1, defval=15) * 0.01
takeprofit_input        = input(title="Long Take Profit (%)", minval=0, step=1, defval=1.4) * 0.01
// USER INPUTS
sma_short_val           = input(title="Short MA Window", defval=20)
sma_long_val            = input(title="Long MA Window", defval=100)
ubOffset                = input(title="Upper Band Offset", defval=2.5, step=0.5)
lbOffset                = input(title="Lower Band Offset", defval=2.5, step=0.5)
cross                   = input(title="Entrry at Cross Over/Under Lower", defval="over", options=["over", "under"])
// Backtesting Date Ranges
startDate  = input(title="Start Date", defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", defval=1, minval=1, maxval=12)
startYear  = input(title="Start Year", defval=2016, minval=1800, maxval=2100)
endDate    = input(title="End Date", defval=31, minval=1, maxval=31)
endMonth   = input(title="End Month", defval=12, minval=1, maxval=12)
endYear    = input(title="End Year", defval=2022, minval=1800, maxval=2100)
// VARS
short_sma        = sma(close, sma_short_val)
long_sma         = sma(close, sma_long_val)
stdDev           = stdev(close, sma_short_val)
upperBand        = short_sma + (stdDev * ubOffset)
lowerBand        = short_sma - (stdDev * lbOffset)
stoploss_value   = strategy.position_avg_price * (1 - stoploss_input)
takeprofit_value = strategy.position_avg_price * (1 + takeprofit_input)
initial_dev_val  = strategy.position_avg_price * (1 - initial_deviation_input)
inDateRange      = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
initial_deviation = close < initial_dev_val
// Market Conditions
goodBuy    = cross=="over"?crossover(close, lowerBand):crossunder(close, lowerBand) // Buy when close crossing lower band
safety     = initial_deviation and (1-(close/strategy.position_avg_price))/.01 > strategy.opentrades-1 * safety_step and strategy.opentrades <= safety_max // SO when price deviates below SO threshold %
stoploss   = close <= stoploss_value // Stoploss condition - true if closing price for current bar drops below stoploss %
takeprofit = close >= takeprofit_value // Take profit condition - true if closing price for current bar is >= take profit percentage
// goodSell is currently unused for any practical purpose. If you wish to try it, switch these two values. 
// Doing so will make sell suggestions at high crossover upper bollinger but it does not trigger the bot to sell as written but may affect backtest results
//goodSell = crossover(high, upperBand)
goodSell   = false
// Plot some lines
plot(short_sma, color=color.green)
plot(upperBand)
plot(lowerBand, color=color.yellow)
plot(strategy.position_avg_price, color=color.red, linewidth=3)
// Webhook message. Defaults to string. To signal 3c bot, fill in bot_id and email_token in user settings
var enter_msg = "Enter Position"
var exit_msg  = "Exit Position"
var close_all = "Exit Position"
if bot_id != "" and email_token != ""
    if bot_type == "composite"
        enter_msg := '{"message_type": "bot",  "bot_id": ' + bot_id + ',  "email_token": "' + email_token + '", "delay_seconds": 0, "pair": "' + syminfo.currency + "_" + syminfo.basecurrency + '"}'
    else
        enter_msg := '{"message_type": "bot",  "bot_id": ' + bot_id + ',  "email_token": "' + email_token + '", "delay_seconds": 0}'
    exit_msg  := '{  "message_type": "bot",  "bot_id": ' + bot_id + ',  "email_token": ' + email_token + ',  "delay_seconds": 0,  "action": "close_at_market_price"}'
    close_all := '{ "message_type": "bot", "bot_id": ' + bot_id + ', "email_token": ' + email_token + ', "delay_seconds": 0, "action": "close_at_market_price_all"}'
actual_safety_size = float(safety_order_size) // Set safety order size to starting safety
if strategy.opentrades > 2 // If we have more than two open trades we need to start scaling the safety size by the volume_scale
    actual_safety_size := (strategy.position_size - base_order_size) * volume_scale // Remove base order from total position size and scale it for next safety order
// Strategy Actions
if inDateRange and goodBuy
    strategy.entry("Good Buy", strategy.long, base_order_size, when = strategy.opentrades <= 0, alert_message=enter_msg)
if inDateRange and safety
    strategy.order("Good Buy", strategy.long, actual_safety_size, when = strategy.opentrades > 0, comment = "safety order")
if inDateRange and goodSell
    strategy.close_all(comment="Good sell point")
if inDateRange and stoploss
    strategy.close_all(comment="Stoploss")
if inDateRange and takeprofit
    strategy.close_all(comment="TP Target")
Expand (102 lines)

Overview

3Commas Bollinger Strategy plots short and long simple moving averages, offset bands, and the average entry price of the open deal. A long starts when price crosses the lower band inside a chosen date range. Base and safety order sizes, volume and step scales, and a maximum safety-order count shape the position. Percent stop-loss and take-profit inputs are available, though the supplied excerpt does not show an exit being placed.

Details

Published by

hasnocool on GitHub

Code credit

tedwardd, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Volatility & bands, Moving averages, Mean reversion

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Simple botstringcompositebot_type
3Commas Bot IDstringbot_id
Bot Email Tokenstringemail_token
Base order sizeint500base_order_size
Safety order sizeint1000safety_order_size
Safety Order Vol Scale (%)float1.83volume_scale
Safety Order Step Scale (%)float1.55safety_step
Max Number of Safety Ordersint4safety_max
Initial SO Deviation (%)float0.8initial_deviation_input
Long Stop Loss (%)int15stoploss_input
Long Take Profit (%)float1.4takeprofit_input
Short MA Windowint20sma_short_val
Show all 22 settings
SettingTypeDefaultVariable
Long MA Windowint100sma_long_val
Upper Band Offsetfloat2.5ubOffset
Lower Band Offsetfloat2.5lbOffset
Entrry at Cross Over/Under Lowerstringovercross
Start Dateint1startDate
Start Monthint1startMonth
Start Yearint2016startYear
End Dateint31endDate
End Monthint12endMonth
End Yearint2022endYear
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

218 stars

The Mean Reversion Strategy Template calculates a baseline mean using SMA, EMA, or VWAP alongside upper and lower deviation bands based on standard deviation, ATR, or percentage offsets. It generates long and short entries when price touches, bounces from, or

Strategy v6 Mean reversionMoving averages
Updated 3 months ago · None stated GitHub repository of Mean Reversion Strategy Template

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy

Bollinger Bands Strategy

by TWODS-CAPITAL
37 stars

This strategy executes trades based on price interactions with standard Bollinger Bands plotted on the price chart. It calculates a simple moving average basis line along with upper and lower standard deviation bands. Long entries are triggered when price cros

Strategy v5 Volatility & bandsMean reversion
Updated 3 years ago · MIT GitHub repository of Bollinger Bands Strategy
9 stars

This strategy scaffold calculates a standard Volume Weighted Average Price (VWAP) alongside upper and lower volatility bands set 1.5 ATRs away. It generates long entry signals when a confirmed bar closes below the lower band and short entry signals when a conf

Strategy v5 Mean reversionMoving averages
Updated 12 days ago · Custom licence GitHub repository of Nexural VWAP Reversion Scaffold
7 stars

This strategy plots a simple moving average basis and upper and lower Bollinger bands on the price chart, with a fill between the bands. It also calculates RSI. It opens one long trade when RSI is above 25, price is at or below the lower band, and no position

Strategy v5 Volatility & bandsOscillators & momentum
Updated 4 years ago · GPL-3.0 GitHub repository of Bollinger Bands Strategy

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