Strategy · Pine Script v6 · Own pane

MACD Pullback Sniper | Trend + ADX Filtered Strategy

by ZhijuCen· code credited to blitz_locked

This strategy identifies trend pullback entries using MACD signal line crossovers plotted in a separate indicator pane.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code119
Settings18inputs
LicenceMIT
Last update2 weeks ago12 Oct 2026

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

119 lines of Pine Script v6 from skills/mql5-from-pinescript/assets/pine-scripts/macd-pullback-sniper.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

macd-pullback-sniper.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © blitz_locked

//@version=6
strategy('MACD Pullback Sniper | Trend + ADX Filtered Strategy', overlay = false,
     initial_capital = 10000,
     commission_type = strategy.commission.percent, commission_value = 0.05,
     slippage = 2, pyramiding = 0,
     margin_long = 100, margin_short = 100)

// MACD signal-line cross, filtered by trend, zero line and ADX.
// Exits use an ATR stop and a fixed reward:risk target.

// --- Inputs ---
grpM = 'MACD'
fastLen   = input.int(12, 'Fast EMA', minval = 1, group = grpM)
slowLen   = input.int(26, 'Slow EMA', minval = 1, group = grpM)
signalLen = input.int(9, 'Signal EMA', minval = 1, group = grpM)

grpF = 'Filters'
useTrend = input.bool(true, 'Trend filter (price vs EMA)', group = grpF)
trendLen = input.int(200, 'Trend EMA length', minval = 2, group = grpF)
useZero  = input.bool(true, 'Zero-line filter', group = grpF, tooltip = 'Longs only when the cross happens below zero, shorts only above zero.')
useAdx   = input.bool(true, 'ADX filter', group = grpF)
adxLen   = input.int(14, 'ADX length', minval = 1, group = grpF)
adxMin   = input.float(20.0, 'ADX minimum', minval = 1, group = grpF)

grpR = 'Risk'
atrLen    = input.int(14, 'ATR length', minval = 1, group = grpR)
slMult    = input.float(2.0, 'Stop distance (x ATR)', minval = 0.1, step = 0.1, group = grpR)
rrRatio   = input.float(2.0, 'Reward : Risk', minval = 0.5, step = 0.1, group = grpR)
riskPct   = input.float(1.0, 'Risk per trade (% of equity)', minval = 0.1, maxval = 10, step = 0.1, group = grpR)
maxLev    = input.float(1.0, 'Max position size (x equity)', minval = 0.1, step = 0.1, group = grpR, tooltip = 'Caps position value so a tight stop cannot create an oversized trade.')
exitCross = input.bool(true, 'Exit on opposite MACD cross', group = grpR)

grpG = 'General'
allowShort = input.bool(true, 'Allow shorts', group = grpG)
startDate  = input.time(timestamp('01 Jan 2018 00:00 +0000'), 'Start date', group = grpG)
endDate    = input.time(timestamp('31 Dec 2069 23:59 +0000'), 'End date', group = grpG)

// --- Calculations ---
[macdLine, signalLine, hist] = ta.macd(close, fastLen, slowLen, signalLen)
trendEma = ta.ema(close, trendLen)
[_, _, adx] = ta.dmi(adxLen, adxLen)
atr = ta.atr(atrLen)

inRange   = time >= startDate and time <= endDate
bullCross = ta.crossover(macdLine, signalLine)
bearCross = ta.crossunder(macdLine, signalLine)

// --- Signals ---
trendLongOk  = not useTrend or close > trendEma
trendShortOk = not useTrend or close < trendEma
zeroLongOk   = not useZero or macdLine < 0
zeroShortOk  = not useZero or macdLine > 0
adxOk        = not useAdx or adx > adxMin

longSignal  = bullCross and trendLongOk and zeroLongOk and adxOk and inRange
shortSignal = bearCross and trendShortOk and zeroShortOk and adxOk and inRange and allowShort

// --- Position sizing (fixed % risk per trade) ---
f_qty(float stopDist) =>
    float riskAmt = strategy.equity * riskPct / 100
    float q = stopDist > 0 ? riskAmt / stopDist : 0.0
    q := math.min(q, strategy.equity * maxLev / close)
    float step = syminfo.mincontract > 0 ? syminfo.mincontract : 1.0
    math.floor(q / step) * step

// --- Trade management ---
var float entryAtr = na
var float slLvl = na
var float tpLvl = na

// Open position: anchor stop and target to the actual fill price
if strategy.position_size > 0
    slLvl := strategy.position_avg_price - entryAtr * slMult
    tpLvl := strategy.position_avg_price + entryAtr * slMult * rrRatio
    strategy.exit('Long Exit', 'Long', stop = slLvl, limit = tpLvl)
else if strategy.position_size < 0
    slLvl := strategy.position_avg_price + entryAtr * slMult
    tpLvl := strategy.position_avg_price - entryAtr * slMult * rrRatio
    strategy.exit('Short Exit', 'Short', stop = slLvl, limit = tpLvl)
else
    slLvl := na
    tpLvl := na

// Exit on opposite cross (unless it is also a valid reversal entry)
if exitCross and bearCross and strategy.position_size > 0 and not shortSignal
    strategy.close('Long', comment = 'MACD cross')
if exitCross and bullCross and strategy.position_size < 0 and not longSignal
    strategy.close('Short', comment = 'MACD cross')

// Entries (provisional stop/target protect the fill bar)
if longSignal and strategy.position_size <= 0
    float q = f_qty(atr * slMult)
    if q > 0
        entryAtr := atr
        strategy.entry('Long', strategy.long, qty = q)
        strategy.exit('Long Exit', 'Long', stop = close - atr * slMult, limit = close + atr * slMult * rrRatio)

if shortSignal and strategy.position_size >= 0
    float q = f_qty(atr * slMult)
    if q > 0
        entryAtr := atr
        strategy.entry('Short', strategy.short, qty = q)
        strategy.exit('Short Exit', 'Short', stop = close + atr * slMult, limit = close - atr * slMult * rrRatio)

// --- Visuals ---
hColor = hist >= 0 ? (hist > hist[1] ? color.new(color.teal, 0) : color.new(color.teal, 60)) : (hist < hist[1] ? color.new(color.red, 0) : color.new(color.red, 60))
plot(hist, 'Histogram', style = plot.style_columns, color = hColor)
plot(macdLine, 'MACD', color = color.blue, linewidth = 2)
plot(signalLine, 'Signal', color = color.orange, linewidth = 1)
hline(0, 'Zero', color = color.gray, linestyle = hline.style_dashed)

plot(trendEma, 'Trend EMA', color = color.new(color.gray, 20), linewidth = 2, force_overlay = true)
plot(slLvl, 'Stop', color = color.red, style = plot.style_linebr, force_overlay = true)
plot(tpLvl, 'Target', color = color.green, style = plot.style_linebr, force_overlay = true)
plotshape(longSignal, 'Long', style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small, force_overlay = true)
plotshape(shortSignal, 'Short', style = shape.triangledown, location = location.abovebar, color = color.red, size = size.small, force_overlay = true)

Overview

Long trades enter on bullish MACD crossovers below the zero line when price is above a trend EMA and ADX exceeds a minimum threshold, with reverse conditions for short trades. Position sizing is calculated from equity risk and ATR stop distance, bounded by a maximum leverage cap. Exits occur at ATR-based stop loss levels, a fixed reward-to-risk profit target, or an optional opposite MACD crossover.

Details

Published by

ZhijuCen on GitHub

Code credit

blitz_locked, as written in the script's header

Type

Strategy, Pine Script v6

Draws

Separate pane below the chart

Category

Trend, Oscillators & momentum, Moving averages

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
Fast EMAint12fastLen
Slow EMAint26slowLen
Signal EMAint9signalLen
Trend filter (price vs EMA)booltrueuseTrend
Trend EMA lengthint200trendLen
Zero-line filterbooltrueuseZero
ADX filterbooltrueuseAdx
ADX lengthint14adxLen
ADX minimumfloat20.0adxMin
ATR lengthint14atrLen
Stop distance (x ATR)float2.0slMult
Reward : Riskfloat2.0rrRatio
Show all 18 settings
SettingTypeDefaultVariable
Risk per trade (% of equity)float1.0riskPct
Max position size (x equity)float1.0maxLev
Exit on opposite MACD crossbooltrueexitCross
Allow shortsbooltrueallowShort
Start datetimetimestamp('01 Jan 2018 00:00 +0000')startDate
End datetimetimestamp('31 Dec 2069 23:59 +0000')endDate
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

MACD + Divergences [Alorse] is a momentum strategy that calculates the MACD oscillator and identifies regular and hidden divergences using pivot high and low points. It filters trade signals with dual Exponential Moving Averages (EMA 150 and 600) to ensure tra

Strategy v4 Oscillators & momentumDivergence Repaints
Updated 2 months ago · None stated GitHub repository of MACD + Divergences [Alorse]

MACD Crossover (tutorial)

by pineforge-4pass
193 stars

This strategy calculates the Moving Average Convergence Divergence indicator and plots the MACD line, signal line, and histogram in a separate pane. It enters long positions when the MACD line crosses above the signal line and enters short positions when it cr

Strategy v6 Oscillators & momentumMoving averages
Updated today · Apache-2.0 GitHub repository of MACD Crossover (tutorial)

ADX Strategy

by hasnocool
106 stars

An ADX-based trend-following strategy that enters long positions when the positive directional indicator (DI+) crosses above the Average Directional Index (ADX) while ADX remains below a preset threshold and a fast EMA is above a slow EMA. It allows adding to

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of ADX Strategy

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

This strategy evaluates the dynamic relationship between price and a chosen moving average across six diagnostic dimensions: trend, respect, extension, compression, acceleration, and exhaustion. It plots a normalized relationship oscillator bounded between -10

Strategy v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of Market–Average Relationship Engine [WavesUnchained]
7 stars

This strategy combines the Moving Average Convergence Divergence oscillator with an Exponential Moving Average trend filter. It enters long positions when the MACD histogram crosses above zero while price stays above the long-term EMA filter. Long trades close

Strategy v5 TrendOscillators & momentum
Updated 1 year ago · MPL-2.0 GitHub repository of MACD EMA Filter 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