Strategy · Pine Script v5 · On the chart

Bollinger Bands + EMA 9

by hasnocool· code credited to D499

This strategy plots a 20-period Bollinger Band and a 9-period EMA on the price chart.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code63
Settings2inputs
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

63 lines of Pine Script v5 from Bollinger Bands + EMA 9.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Bollinger Bands + EMA 9.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © D499
// -D4-
//@version=5
strategy("Bollinger Bands + EMA 9", overlay = true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.fixed)
// Risk management inputs
max_risk_percentage = input.float(1, "Max Risk (%)", 0.01, 99, 0.01, group = "Risk Management")
riskType = input.string("%", title="Risk Type", options = ["%", "$"], group = "Risk Management")
// Calculate Indicators
bb_upper = ta.sma(close, 20) + 2 * ta.stdev(close, 20)
bb_lower = ta.sma(close, 20) - 2 * ta.stdev(close, 20)
ema = ta.ema(close, 9)
// Define bull_candle and bear_candle candles
bull_candle = close > open
bear_candle = close < open
// Check if entry signal is flashed and calculate order size
barsSinceLastEntry() =>
    strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na
percent2money(price, percent) =>
    price * percent / 100 * syminfo.pointvalue
calcPositionSize(entry, stop_size) =>
    risk = if riskType == "% from equity"
        strategy.equity * max_risk_percentage / 100
    else
        max_risk_percentage
    risk / percent2money(entry, stop_size)
stop = 0.0
entry = 0.0
tp = 0.0
if close[1] < bb_lower and bull_candle and strategy.position_size == 0 
    stop := low[1]
    entry := close
    tp := ema
    stop_size = (entry - stop) / stop
    order_size = calcPositionSize(close, stop_size)
    strategy.entry("LONG", strategy.long, math.abs(order_size))
if close[1] > bb_upper and bear_candle and strategy.position_size == 0
    stop := high[1]
    entry := close
    tp := ema
    stop_size = (stop - entry) / stop
    order_size = calcPositionSize(close, stop_size)
    strategy.entry("SHORT", strategy.short, math.abs(order_size))
if strategy.position_size > 0
    strategy.exit("LONG", limit = ema[barsSinceLastEntry()], stop = low[barsSinceLastEntry()+1], comment_profit = "✅", comment_loss = "❌")
if strategy.position_size < 0 
    strategy.exit("SHORT", limit = ema[barsSinceLastEntry()], stop = high[barsSinceLastEntry()+1], comment_profit = "✅", comment_loss = "❌")
// Plot Indicators
plot(bb_upper, color=color.red)
plot(bb_lower, color=color.green)
plot(ema, color = color.white)
// Plot trade visualization
longEntryPlot = plot(strategy.position_size > 0  ? strategy.position_avg_price : na, color=color.new(color.white, 85), style=plot.style_linebr)
longTargetPlot = plot(strategy.position_size > 0  ? ema[barsSinceLastEntry()] : na, color=color.new(color.green, 85), style=plot.style_linebr)
longStopPlot = plot(strategy.position_size > 0  ? low[barsSinceLastEntry()+1] : na, color=color.new(color.red, 85), style=plot.style_linebr)
fill(longEntryPlot, longTargetPlot, color=color.new(color.green, 85), editable=true)
fill(longEntryPlot, longStopPlot, color=color.new(color.red, 85), editable=true)
shortEntryPlot = plot(strategy.position_size < 0  ? strategy.position_avg_price : na, color=color.new(color.white, 85), style=plot.style_linebr)
shortTargetPlot = plot(strategy.position_size < 0  ? ema[barsSinceLastEntry()] : na, color=color.new(color.green, 85), style=plot.style_linebr)
shortStopPlot = plot(strategy.position_size < 0  ? high[barsSinceLastEntry()+1] : na, color=color.new(color.red, 85), style=plot.style_linebr)
fill(shortEntryPlot, shortTargetPlot, color=color.new(color.green, 85), editable=true)
fill(shortEntryPlot, shortStopPlot, color=color.new(color.red, 85), editable=true)
Expand (76 lines)

Overview

Bollinger Bands + EMA 9 opens a long when the prior close is below the lower band and the current candle is bullish, and a short when the prior close is above the upper band and the current candle is bearish. It sizes the order from a max risk setting, places a stop at the prior candle extreme, and exits at the EMA or that stop. It does not add to an open position. The risk-type option does not match the percent branch in the code.

Details

Published by

hasnocool on GitHub

Code credit

D499, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Moving averages, Mean reversion

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Max Risk (%)float1max_risk_percentage
Risk Typestring%riskType
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
5 stars

Greeffer's Scalping Strategy combines multi-timeframe Exponential Moving Averages, Bollinger Bands, and Donchian Channels to execute dip-buying trades directly on the price chart. It triggers long entries when price dips below both the lower Donchian Channel a

Strategy v5 Moving averagesVolatility & bands
Updated 4 years ago · None stated GitHub repository of Greeffer's Scalping 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