Strategy · Pine Script v4 · Own pane

SM and MACD

by jerryinyang· code credited to Cerebr

This strategy combines Squeeze Momentum and MACD indicators to generate trading signals.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code95
Settings11inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago12 May 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

95 lines of Pine Script v4 from SuperTrend Strategy/Pine Script/Squeeze and MACD.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Squeeze and MACD.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Cerebr

//@version=4
strategy("SM and MACD", overlay=0, pyramiding = 1)

//Squeeze Momentum { 
length = input(20, title="BB Length", group = "Squeeze Momentum")
mult = input(2.0,title="BB MultFactor", group = "Squeeze Momentum")
lengthKC=input(20, title="KC Length", group = "Squeeze Momentum")
multKC = input(1.5, title="KC MultFactor", group = "Squeeze Momentum")

useTrueRange = input(true, title="Use TrueRange (KC)", type=input.bool)

// Calculate BB
source = close
basis = sma(source, length)
dev = mult * stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev

// Calculate KC
ma = sma(source, lengthKC)
range = useTrueRange ? tr : (high - low)
rangema = sma(range, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC

sqzOn  = (lowerBB > lowerKC) and (upperBB < upperKC)
sqzOff = (lowerBB < lowerKC) and (upperBB > upperKC)
noSqz  = (sqzOn == false) and (sqzOff == false)

val = linreg(source  -  avg(avg(highest(high, lengthKC), lowest(low, lengthKC)),sma(close,lengthKC)), lengthKC,0)

bcolor = iff( val > 0, iff( val > nz(val[1]), #00FF00, #008000),iff( val < nz(val[1]), #FF0000, #800000))
  
scolor = noSqz ? #0000FF : sqzOn ? #0000FF : color.blue 

plot(val, color=bcolor, style=plot.style_histogram, linewidth=4)
plot(0, color=scolor, style=plot.style_circles, linewidth=2)

//SIGNALS
sqzEnt = scolor[2] == #0000FF and scolor[1] == color.blue
sqzDir = bcolor == #00FF00 ? "Buy" : bcolor == #FF0000 ? "Sell" : na
sqzBE = bcolor == #008000 ? "BE Buy" : bcolor == #800000 ? "BE Sell" : na

//}----- End of Squeeze Momentum
//Signals ==> sqzEnt (True or False), sqzDir ("Buy" or "Sell"), and sqzBE ("BE Buy" and "BE Sell")

//MACD {

macdsrc = input(close, "Source", group = "MACD")
macdflen = input(12, "Fask MA", group = "MACD")
macdslen = input(26, "Slow MA", group = "MACD")
siglen = input(13, "Signal Line", input.integer, group = "MACD")
showHist = input(false, "Show MACD Histogram", group = "MACD")
Filt = input(false, "Use MACD Advanced Filter", group = "MACD")

[macd, signal, hist] = macd(macdsrc, macdflen, macdslen, siglen)

//PLOTS
plot(macd, "MACD Line", color.lime)
plot(signal, "Signal Line", color.maroon)
plot(showHist ? hist : na, "MACD Histogram", color.white)

//SIGNALS
macdBuy = 
  Filt == true ? crossover(macd, signal) and macd < 0 :
  macd > signal
  
macdSell = 
  Filt == true ? crossunder(macd, signal) and macd > 0 :
  macd < signal
//}----- End of MACD
//Signals ==> macdBuy and macdSell

//Strategy Executions {
longCondition = sqzEnt and sqzDir == "Buy" and macdBuy
if (longCondition)
    strategy.entry("Long", strategy.long)

shortCondition = sqzEnt and sqzDir == "Sell" and macdSell
if (shortCondition)
    strategy.entry("Short", strategy.short)

atr = atr(20)

tp = 
  sqzDir == "Buy" ? strategy.position_avg_price + (3 * atr) :
  sqzDir == "Sell" ? strategy.position_avg_price - (1.5 * atr) :
  na

strategy.exit("Trade Exit", sqzDir == "Buy" ? "Long" : "Short", limit = tp)

//}

Overview

SM and MACD plots the Squeeze Momentum histogram and MACD in a separate pane. The strategy enters long positions when squeeze enters and MACD is bullish, and short when squeeze enters and MACD is bearish. It uses a custom take profit based on ATR multiplier and allows pyramiding of one position. There is no stop loss by default. Main settings adjust Bollinger Bands, Keltner Channels for squeeze detection, and MACD parameters for signal confirmation.

Details

Published by

jerryinyang on GitHub

Code credit

Cerebr, as written in the script's header

Type

Strategy, Pine Script v4

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction
  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
BB Lengthint20length
BB MultFactorfloat2.0mult
KC Lengthint20lengthKC
KC MultFactorfloat1.5multKC
Use TrueRange (KC)booltrueuseTrueRange
Sourcesourceclosemacdsrc
Fask MAint12macdflen
Slow MAint26macdslen
Signal Lineint13siglen
Show MACD HistogramboolfalseshowHist
Use MACD Advanced FilterboolfalseFilt
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

A momentum strategy combining the TTM Squeeze oscillator with an RSI filter. It calculates linear regression momentum relative to Bollinger Bands and Keltner Channels alongside an RSI oscillator. Long signals trigger when momentum rises from below zero while R

Strategy v5 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of TTM Squeeze [Alorse]

2xTP, SL to Entry

by hasnocool
106 stars

This strategy executes mean-reversion trades based on Bollinger Bands and the Stochastic Oscillator. Long orders trigger when price dips below the lower band alongside a bullish Stochastic crossover, with an optional oversold threshold. Short orders execute on

Strategy v5 Mean reversionOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 2xTP, SL to Entry

EMA Ribbon MACD

by iamrichardD
57 stars

This strategy combines an EMA ribbon with MACD confirmation and plots in a separate pane. It enters when ribbon alignment, optional MACD zero or signal crosses, volume, smart-money, and multi-timeframe filters agree, then exits with percentage stop loss and ta

Strategy v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon MACD
25 stars

This Pine Script strategy calculates Bayesian probabilities of price breaking up or down relative to Bollinger Bands and a Simple Moving Average. It plots these breakout and breakdown probability lines as oscillators in a separate pane. Long entries trigger wh

Strategy v4 Oscillators & momentumVolatility & bands
Updated 6 years ago · None stated GitHub repository of Bayesian BBSMA Oscillator Strategy

Greeffer BB Strategy

by SammyEnigma
18 stars

This strategy fades Bollinger Band extremes using the close. It enters short when price crosses above the upper band and the 14-period RSI is above 70, and enters long when price crosses below the lower band and RSI is below 30. It closes half of an open short

Strategy v4 Volatility & bandsOscillators & momentum
Updated 6 years ago · None stated GitHub repository of Greeffer BB Strategy

AwesomeADX

by koradiyakaushal
12 stars

AwesomeADX is a Pine Script v4 strategy that combines an Awesome Oscillator, ADX directional movement, and Bollinger percent B with an optional four-length moving-average trend filter. It sizes each position as a percentage of equity and can limit trades to a

Strategy v4 Oscillators & momentumMoving averages
Updated 5 years ago · MIT GitHub repository of AwesomeADX

More Oscillators & momentum scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers