Strategy · Pine Script v4 · On the chart

BB + ADX Strategy

by hasnocool· code credited to tweakerID

The BB + ADX Strategy triggers entries when price crosses Bollinger Bands during low-trend market conditions as filtered by the Average Directional Index (ADX).

View on GitHub

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

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

Bollinger Bands + ADX Strategy.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tweakerID
// This strategy uses Bollinger Bands to buy when the price 
// crosses over the lower band and sell when it crosses down
// the upper band. It only takes trades when the ADX is 
// below a certain level, and exits all trades when it's above it.
//@version=4
strategy("BB + ADX Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_value = 0.04, initial_capital=10000)
//Inputs
i_reverse=input(false, title="Reverse Trades")
i_ADXClose=input(true, title="ADX Close")
i_SL=input(false, title="Use Swing Lo/Hi Stop Loss & Take Profit")
i_SwingLookback=input(20, title="Swing Lo/Hi Lookback")
i_SLExpander=input(defval=0, step=.5, title="SL Expander")
i_TPExpander=input(defval=0, step=.5, title="TP Expander")
//ADX Calculations
adxlen = input(14, title="ADX Smoothing")
dilen = input(20, title="DI Length")
dirmov(len) =>
    up = change(high)
    down = -change(low)
    plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
    minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
    truerange = rma(tr, len)
    plus = fixnan(100 * rma(plusDM, len) / truerange)
    minus = fixnan(100 * rma(minusDM, len) / truerange)
    [plus, minus]
adx(dilen, adxlen) =>
    [plus, minus] = dirmov(dilen)
    sum = plus + minus
    adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
adxlevel=input(20, step=5)
//BB Calculations
BBCALC=input(false, title="-----------BB Inputs-----------")
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)
MAlen=input(defval=9)
source = close
basis = sma(source, length)
dev = mult * stdev(source, length)
upper = basis + dev
lower = basis - dev
//Entry Logic
BUY = crossover(source, lower) and sig < adxlevel
SELL = crossunder(source, upper) and sig < adxlevel
//SL & TP Calculations
SwingLow=lowest(i_SwingLookback)
SwingHigh=highest(i_SwingLookback)
bought=strategy.position_size != strategy.position_size[1]
LSL=valuewhen(bought, SwingLow, 0)-((valuewhen(bought, atr(14), 0))*i_SLExpander)
SSL=valuewhen(bought, SwingHigh, 0)+((valuewhen(bought, atr(14), 0))*i_SLExpander)
lTP=strategy.position_avg_price + (strategy.position_avg_price-(valuewhen(bought, SwingLow, 0))+((valuewhen(bought, atr(14), 0))*i_TPExpander))
sTP=strategy.position_avg_price - (valuewhen(bought, SwingHigh, 0)-strategy.position_avg_price)-((valuewhen(bought, atr(14), 0))*i_TPExpander)
islong=strategy.position_size > 0
isshort=strategy.position_size < 0
SL= islong ? LSL : isshort ? SSL : na
TP= islong ? lTP : isshort ? sTP : na
//Entries
strategy.entry("long", long=i_reverse?false:true, when=BUY)
strategy.entry("short", long=i_reverse?true:false, when=SELL)
//EXITS
if i_ADXClose
    strategy.close_all(when=sig > adxlevel)
if i_SL
    strategy.exit("longexit", "long", stop=SL, limit=TP)
    strategy.exit("shortexit", "short", stop=SL, limit=TP)
//Plots 
plot(i_SL ? SL : na, color=color.red, style=plot.style_cross, title="SL")
plot(i_SL ? TP : na, color=color.green, style=plot.style_cross, title="TP")
plot(upper)
plot(lower)
Expand (86 lines)

Overview

BB + ADX Strategy enters long when price crosses above the lower band and short when price crosses below the upper band, provided ADX remains below the set threshold. Positions are automatically closed when ADX rises above the threshold if enabled. Optional risk controls include swing high and low stop loss and take profit levels with ATR expanders. It plots Bollinger Bands and exit targets on the price chart.

Details

Published by

hasnocool on GitHub

Code credit

tweakerID, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Volatility & bands, Oscillators & momentum, 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
Reverse Tradesboolfalsei_reverse
ADX Closebooltruei_ADXClose
Use Swing Lo/Hi Stop Loss & Take Profitboolfalsei_SL
Swing Lo/Hi Lookbackint20i_SwingLookback
SL Expanderint0i_SLExpander
TP Expanderint0i_TPExpander
ADX Smoothingint14adxlen
DI Lengthint20dilen
adxlevelint20adxlevel
-----------BB Inputs-----------boolfalseBBCALC
lengthint20length
multfloat2.0mult
Show all 13 settings
SettingTypeDefaultVariable
MAlenint9MAlen
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

330 stars

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]
104 stars

This strategy combines Bollinger Bands with a short RSI to fade moves that leave the bands and then return. A long requires the prior bar below the lower band and oversold, then a close back inside the band while RSI is between 30 and 50. Shorts mirror that at

Strategy v5 Oscillators & momentumVolatility & bands
Updated 3 years ago · MIT GitHub repository of Bollinger Bands and RSI Strategy

Greeffer RSI Strategy

by SammyEnigma
18 stars

Greeffer RSI Strategy is a trading strategy that generates buy and sell entries based on Bollinger Bands and RSI levels. It places stop orders at upper and lower Bollinger Bands on band crossovers, and adds positions when RSI reaches extreme levels. Users can

Strategy v4 Oscillators & momentumVolatility & bands
Updated 6 years ago · None stated GitHub repository of Greeffer RSI Strategy
13 stars

This strategy overlays the price chart to trade DAX futures during European market hours. It calculates exponential and simple moving averages, RSI, MACD, Bollinger Bands, ATR, and realized volatility to simulate VIX levels. Trades execute when session time fi

Strategy v5 Sessions & timeOscillators & momentum
Updated 8 months ago · Custom licence GitHub repository of ClaudeHedge - DAX Session Strategy

Calculates a combination of the Relative Strength Index, MACD histogram, and Bollinger Bands contraction to identify long trade entries. The strategy signals a long position on a bullish bar when the MACD histogram turns upward while negative, RSI remains belo

Strategy v4 Oscillators & momentumVolatility & bands
Updated 3 years ago · Apache-2.0 GitHub repository of RSI + MACD + BB Long Strategy (Not Good)

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