Strategy · Pine Script v4 · On the chart

EMAs + BB Squeeze + Trend Long Strategy

by krosenfeld7

EMAs + BB Squeeze + Trend Long Strategy is an overlay strategy combining multi-timeframe Exponential Moving Averages with Bollinger Bands squeeze dynamics.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code181
Settings26inputs
LicenceApache-2.0
Last update3 years ago12 May 2023

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

181 lines of Pine Script v4 from BB Squeeze + Trend + EMAs/BB_Squeeze_Trend+EMAs_Long_Strategy.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

BB_Squeeze_Trend+EMAs_Long_Strategy.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © krosenfeld7

//@version=4
strategy("EMAs + BB Squeeze + Trend Long Strategy", overlay = true, pyramiding = 0, 
         margin_long = 100, margin_short = 100, 
         default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 20, initial_capital = 2000, 
         process_orders_on_close = true)

// Set the starting point for backtesting
start = input(title = "Backtesting Start", type = input.time,
     defval = timestamp("1 Jan 2015"))
maxTimeOpen = input(title = "Order Expiration", type = input.integer,
     defval = 100, minval = 1)
tpSlStrategy = input(title = "Take Profit Strategy", type = input.string,
     defval = "Percent", options = ["Percent", "ATR"])
trailingStop = input(title = "Trailing Stop", type = input.string,
     defval = "Fixed", options = ["Fixed", "Trail"])

// ATR For Stop Loss
atrLength = input(title = "ATR SL Length", defval = 14,
     minval = 1)
atrMultiplier = input(title = "ATR Multiplier", type = input.float, 
     defval = 1, minval = 0.1)
riskLevel = input(title = "Risk Level", type = input.float, 
     defval = 1, minval = 0.1)

longProfitPercent = input(title = "Take Profit %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100
longLossPercent = input(title = "Stop Loss %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100

// Algorithm / Strategy Goes here
// Set long variables to execute positions below
trendModeStr   = input(title = "Trend or Squeeze",     type = input.string,     defval = "Trend", options = ["Trend", "Squeeze"])
ema1Length     = input(title = "EMA Short Length",     type = input.integer,    defval = 20, minval = 1)
ema1Input      = input(title = "EMA Short Source",     type = input.source,     defval = close)
ema1Resolution = input(title = "EMA Short Resolution", type = input.resolution, defval = "D")
ema2Length     = input(title = "EMA Med Length",       type = input.integer,    defval = 50, minval = 1)
ema2Input      = input(title = "EMA Med Source",       type = input.source,     defval = close)
ema2Resolution = input(title = "EMA Med Resolution",   type = input.resolution, defval = "D")
ema3Length     = input(title = "EMA Long Length",      type = input.integer,    defval = 100, minval = 1)
ema3Input      = input(title = "EMA Long Source",      type = input.source,     defval = close)
ema3Resolution = input(title = "EMA Long Resolution",  type = input.resolution, defval = "D")

ema1 = ema(ema1Input, ema1Length)
ema2 = ema(ema2Input, ema2Length)
ema3 = ema(ema3Input, ema3Length)

trendMode = trendModeStr == "Trend"

ema1Daily = security(syminfo.tickerid, ema1Resolution, ema1[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off)
ema2Daily = security(syminfo.tickerid, ema2Resolution, ema2[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off)
ema3Daily = security(syminfo.tickerid, ema3Resolution, ema3[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off)

plot(ema1Daily, "EMA Short", color = color.new(color.white, transp = trendMode ? 0 : 100), linewidth = 2)
plot(ema2Daily, "EMA Med",   color = color.new(color.blue, transp = trendMode ? 0 : 100),   linewidth = 2)
plot(ema3Daily, "EMA Long",  color = color.new(color.yellow, transp = trendMode ? 0 : 100), linewidth = 2)

emaLong  = ema1Daily > ema2Daily and ema2Daily > ema3Daily
emaShort = ema1Daily < ema2Daily and ema2Daily < ema3Daily

// Bollinger Bands
length1 = input(title = "BB MA Length", type = input.integer, defval = 20, minval = 1)
src1    = input(title = "BB MA Source", type = input.source,  defval = hlc3)
maType  = input(title = "BB MA Type",   type = input.string,  defval = "SMA", options = ["SMA", "EMA"])
mult1   = input(title = "BB 1 Std Dev Multiplier", type = input.float, defval = 2.0, minval = 0.001, maxval = 50)
mult2   = input(title = "BB 2 Std Dev Multiplier", type = input.float, defval = 1.0, minval = 0.001, maxval = 50)

bbLookback    = input(title = "BB Lookback",    type = input.integer, defval = 10, minval = 1)
displayLabels = input(title = "Display Labels", type = input.bool,    defval = true)

bbMa = sma(src1, length1)

if maType == "EMA"
    bbMa := ema(src1, length1)

plot(bbMa, "Basis", color = color.new(color.white, transp = 50), linewidth = 2)

// BB One
dev1 = mult1 * stdev(src1, length1)
upper1 = bbMa + dev1
lower1 = bbMa - dev1
p1 = plot(upper1, "Upper", color = color.new(color.green, transp = 50), linewidth = 2)
p2 = plot(lower1, "Lower", color = color.new(color.orange, transp = 50), linewidth = 2)

// BB Two
dev2 = mult2 * stdev(src1, length1)
upper2 = bbMa + dev2
lower2 = bbMa - dev2
p3 = plot(upper2, "Upper", color = color.new(color.green, transp = 50), linewidth = 2)
p4 = plot(lower2, "Lower", color = color.new(color.orange, transp = 50), linewidth = 2)

fill(p1, p3, title = "Background", color=color.new(color.green, transp = 75))
fill(p3, p4, title = "Background", color=color.new(color.white, transp = 100))
fill(p4, p2, title = "Background", color=color.new(color.orange, transp = 75))

bb1Upper = ema(upper1, bbLookback)
bb1Lower = ema(lower1, bbLookback)
bb2Upper = ema(upper2, bbLookback)
bb2Lower = ema(lower2, bbLookback)

bb1Contraction = upper1 < bb1Upper and lower1 > bb1Lower
bb2Contraction = upper2 < bb2Upper and lower2 > bb2Lower
 
bbLong  = close > upper1
bbShort = close < lower1

// Net Volume
higherVolume = volume > volume[1] and volume[1] > volume[2]

squeezeLong  = bb1Contraction and higherVolume and bbLong
squeezeShort = bb1Contraction and higherVolume and bbShort

trendLong  = emaLong  and bbLong
trendShort = emaShort and bbShort

long  = trendMode ? trendLong : squeezeLong
short = trendMode ? trendShort : squeezeShort

// End Algorithm

longExitPrice = 0.0
longStopPrice = 0.0

// Calculating exact prices for stop loss and exit prices
longExitPercentPrice = strategy.position_avg_price * (1 + 
     (longProfitPercent * riskLevel))
longStopPercentPrice = strategy.position_avg_price * (1 - 
     longLossPercent)

// Profit & Loss via ATR
atr = atr(atrLength)

atr := valuewhen(strategy.position_size == 0, atr, 0)

longExitAtrPrice = strategy.position_avg_price + (atr * 
     atrMultiplier * riskLevel)
longStopAtrPrice = strategy.position_avg_price - (atr * 
     atrMultiplier)

if tpSlStrategy == "Percent"
    longExitPrice := longExitPercentPrice
    
    if trailingStop == "Fixed"
        longStopPrice := longStopPercentPrice
    else if trailingStop == "Trail"
        stopValue      = close * (1 - longLossPercent)
        longStopPrice := (strategy.position_size > 0) ? 
             max(stopValue, longStopPrice[1]) : 0

else if tpSlStrategy == "ATR"
    if strategy.position_size > 0
        longExitPrice := longExitAtrPrice
        
    if trailingStop == "Fixed"
        longStopPrice := longStopAtrPrice
    else if trailingStop == "Trail"
        stopValue      = close - (atr * atrMultiplier)
        longStopPrice := (strategy.position_size > 0) ? 
             max(stopValue, longStopPrice[1]) : 0

// Plotting profit / loss targets
plot(series = (strategy.position_size > 0) ? longExitPrice : na, 
     color = color.green, style = plot.style_linebr, 
     linewidth = 3, title = "Long Target")
plot(series = (strategy.position_size > 0) ? longStopPrice : na, 
     color = color.red, style = plot.style_linebr, 
     linewidth = 3, title = "Long Stop Loss")

// Submit entry orders
if time >= start
    strategy.entry(id = "Long", long = strategy.long, 
         comment = "Long Open", when = long)

// Submit exit orders
strategy.exit(id = "Long", limit = longExitPrice, stop = longStopPrice, 
     comment = "Long Close", when = strategy.position_size > 0)
strategy.close(id = "Long", comment = "Expired: >" + tostring(maxTimeOpen), 
     when = (barssince(change(strategy.opentrades)) + 1) >= maxTimeOpen)

Overview

EMAs + BB Squeeze + Trend Long Strategy evaluates short, medium, and long EMAs defaulting to daily resolution alongside Bollinger Bands to identify trend or squeeze setups for long entries. Positions are managed with user-defined stop loss and take profit targets based on either fixed percentages or ATR multiples, with options for trailing stops and order expiration after a set bar duration.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Trend, Moving averages, Volatility & bands

Markets

Any symbol

Timeframes

M15-H1, H4 and above

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.

Settings

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

SettingTypeDefaultVariable
Backtesting Starttimetimestamp("1 Jan 2015")start
Order Expirationint100maxTimeOpen
Take Profit StrategystringPercenttpSlStrategy
Trailing StopstringFixedtrailingStop
ATR SL Lengthint14atrLength
ATR Multiplierfloat1atrMultiplier
Risk Levelfloat1riskLevel
Take Profit %float10longProfitPercent
Stop Loss %float10longLossPercent
Trend or SqueezestringTrendtrendModeStr
EMA Short Lengthint20ema1Length
EMA Short Sourcesourcecloseema1Input
Show all 26 settings
SettingTypeDefaultVariable
EMA Short ResolutiontimeframeDema1Resolution
EMA Med Lengthint50ema2Length
EMA Med Sourcesourcecloseema2Input
EMA Med ResolutiontimeframeDema2Resolution
EMA Long Lengthint100ema3Length
EMA Long Sourcesourcecloseema3Input
EMA Long ResolutiontimeframeDema3Resolution
BB MA Lengthint20length1
BB MA Sourcesourcehlc3src1
BB MA TypestringSMAmaType
BB 1 Std Dev Multiplierfloat2.0mult1
BB 2 Std Dev Multiplierfloat1.0mult2
BB Lookbackint10bbLookback
Display LabelsbooltruedisplayLabels
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

This mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [Alorse]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce
106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

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
104 stars

This overlay strategy combines a Chandelier Exit with a zero-lag least squares moving average. Although the header mentions Heikin Ashi candles, the calculations use ordinary closes. An ATR trailing stop sets long and short levels, and direction flips when pri

Strategy v5 TrendMoving averages
Updated 3 years ago · MIT GitHub repository of Chandelier Exit & ZLSMA 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