Strategy · Pine Script v4 · On the chart

MACD + Support / Resistance Long Strategy

by krosenfeld7

This strategy combines MACD momentum signals with support and resistance levels from pivot points and an EMA100 trend filter for long positions.

View on GitHub

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

174 lines of Pine Script v4 from MACD+Support_Resistance/MACD+Support_Resistance_Long_Strategy.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

MACD+Support_Resistance_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("MACD + Support / Resistance 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
lookback = input(title = "Pivot Lookback", type = input.integer, defval = 10, minval = 1)
epsilon  = input(title = "Price Epsilon (%)", type = input.float, defval = 0.5, minval = 0.1)
emaRes = input(title = "EMA Resolution", type = input.resolution, defval = "D")
emaSrc = input(title = "EMA Source", type = input.source, defval = close)
emaLength = input(title = "EMA Length", type = input.integer, defval = 100, minval = 1)

ema100 = ema(emaSrc, emaLength)

ema100Daily = security(syminfo.tickerid, emaRes, ema100[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off)

emaLong = close > ema100Daily
emaShort = close < ema100Daily

plot(ema100Daily, "EMA", color = color.white, linewidth = 2)

epsilon /= 100

// 100 EMA, MACD, previous high or low

prevHigh = pivothigh(close, lookback, lookback)
prevLow  = pivotlow(close,  lookback, lookback)

// MACD
// Getting inputs
macdRes = input(title = "MACD Resolution", type = input.resolution, defval = "30")
fast_length = input(title="MACD Fast Length", type=input.integer, defval=12)
slow_length = input(title="MACD Slow Length", type=input.integer, defval=26)
src = input(title="MACD Source", type=input.source, defval=close)
signal_length = input(title="MACD Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="MACD Simple MA (Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="MACD Simple MA (Signal Line)", type=input.bool, defval=false)
displayPivots = input(title = "Display Pivot Labels", type = input.bool, defval = false)

// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal

macdSec   = security(syminfo.tickerid, macdRes, macd[barstate.isrealtime ? 1 : 0],   barmerge.gaps_off, barmerge.lookahead_off)
signalSec = security(syminfo.tickerid, macdRes, signal[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off)

macdCrossDown = crossunder(macdSec, signalSec)
macdCrossUp   = crossover(macdSec,  signalSec)

var bool highPointReached = na
var bool lowPointReached  = na

if (high + (epsilon * high)) >= prevHigh
    if displayPivots
        label.new(bar_index, y = na, yloc = yloc.abovebar, color = color.green, style = label.style_triangledown)
    highPointReached := true
else
    highPointReached := na
if (low - (epsilon * low)) <= prevLow
    if displayPivots
        label.new(bar_index, y = na, yloc = yloc.belowbar, color = color.red, style = label.style_triangleup)
    lowPointReached := true
else
    lowPointReached := na

macdPriceLong = false
macdPriceShort = false

if macdCrossDown and barssince(not na(highPointReached)) < lookback
    macdPriceShort := true

if macdCrossUp and barssince(not na(lowPointReached)) < lookback
    macdPriceLong := true

if not na(prevHigh) and displayPivots
    label.new(bar_index - lookback, y = na, yloc = yloc.abovebar, style = label.style_triangledown)
if not na(prevLow) and displayPivots
    label.new(bar_index - lookback, y = na, yloc = yloc.belowbar, style = label.style_triangleup)

long  = macdPriceLong and emaLong
short = macdPriceShort and emaShort

// 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

MACD + Support / Resistance Long Strategy plots the 100-period EMA on the price chart and signals when price breaks above the EMA or forms bullish pivot patterns aligned with MACD crossovers. Long entries occur automatically, with exits using customizable take-profit percentages, stop-loss percentages, ATR-based stops, trailing stop options, or maximum order duration. The strategy draws indicators directly on the price chart and supports any market or timeframe.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Trend, Oscillators & momentum, Moving averages, Support & resistance

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.

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
Pivot Lookbackint10lookback
Price Epsilon (%)float0.5epsilon
EMA ResolutiontimeframeDemaRes
Show all 22 settings
SettingTypeDefaultVariable
EMA SourcesourcecloseemaSrc
EMA Lengthint100emaLength
MACD Resolutiontimeframe30macdRes
MACD Fast Lengthint12fast_length
MACD Slow Lengthint26slow_length
MACD Sourcesourceclosesrc
MACD Signal Smoothingint9signal_length
MACD Simple MA (Oscillator)boolfalsesma_source
MACD Simple MA (Signal Line)boolfalsesma_signal
Display Pivot LabelsboolfalsedisplayPivots
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 strategy overlays the price chart and looks for VWAP pullbacks. It goes long when a short SMA crosses above VWAP after RSI has been oversold within ten bars, and short on the opposite cross after RSI has been overbought. Optional Minervini-style moving-av

Strategy v5 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of Advanced VWAP-Momentum Pullback Trend Qualifier

This strategy trades 1-minute futures contracts on Binance. It plots pivot high and low resistance and support levels on the price chart, along with an EMA and a custom Cto indicator. Long and short entries trigger on EMA and Cto crossovers combined with price

Strategy v5 TrendMoving averages Repaints
Updated 2 years ago · None stated GitHub repository of Binancash Futures Strategy 1M Candles
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar
218 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

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