Strategy · Pine Script v6 · On the chart

MACD Strategy [trugurpala]

by trugurpala

This strategy combines a standard Moving Average Convergence Divergence (MACD) crossover signal with an exponential moving average (EMA) trend filter.

View on GitHub

GitHub stars4on the repository
Pine versionv6current
Lines of code37
Settings8inputs
LicenceMIT
Last update2 months ago3 Aug 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

37 lines of Pine Script v6 from examples/strategies/05_macd_strategy.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

05_macd_strategy.pine
//@version=6
// MACD Signal Cross + EMA Trend Filter — github.com/trugurpala/pinescriptv6
// Author: Ugur Pala · mail@ugurpala.com
strategy("MACD Strategy [trugurpala]",
    overlay=true, initial_capital=10000,
    default_qty_type=strategy.percent_of_equity, default_qty_value=10,
    commission_type=strategy.commission.percent, commission_value=0.1)

// ── Inputs ───────────────────────────────────────────────────────────────────
int   fastLen  = input.int(12, "MACD Fast",   minval=1)
int   slowLen  = input.int(26, "MACD Slow",   minval=1)
int   sigLen   = input.int(9,  "Signal",      minval=1)
int   trendLen = input.int(200,"Trend EMA",   minval=1)
int   atrLen   = input.int(14, "ATR Length",  minval=1)
float slMult   = input.float(2.0, "SL Mult",  step=0.1)
float tpMult   = input.float(2.5, "TP Mult",  step=0.1)
bool  useTrend = input.bool(true, "Use Trend Filter")

// ── Calculations ─────────────────────────────────────────────────────────────
[macdLine, signalLine, _] = ta.macd(close, fastLen, slowLen, sigLen)
float trendEma = ta.ema(close, trendLen)
float atrVal   = ta.atr(atrLen)
bool  bullCross = ta.crossover(macdLine,  signalLine) and (not useTrend or close > trendEma)
bool  bearCross = ta.crossunder(macdLine, signalLine) and (not useTrend or close < trendEma)

// ── Entries ──────────────────────────────────────────────────────────────────
if bullCross
    strategy.entry("Long", strategy.long)
    strategy.exit("Long Exit", "Long", stop=close - slMult * atrVal, limit=close + tpMult * atrVal)
if bearCross
    strategy.entry("Short", strategy.short)
    strategy.exit("Short Exit", "Short", stop=close + slMult * atrVal, limit=close - tpMult * atrVal)

// ── Visuals ──────────────────────────────────────────────────────────────────
plot(trendEma, "Trend EMA", color.new(color.orange, 20), linewidth=2)
plotshape(bullCross, "Long",  shape.triangleup,   location.belowbar, color.green, size=size.small)
plotshape(bearCross, "Short", shape.triangledown, location.abovebar, color.red,   size=size.small)

Overview

Long positions are entered when the MACD crosses above its signal line while price is above the trend EMA. Short positions trigger when the MACD crosses below its signal line while price is below the trend EMA. Risk management is handled using Average True Range (ATR) multipliers for stop loss and take profit targets. The strategy overlays the trend EMA and entry markers directly on the price chart.

Details

Published by

trugurpala on GitHub

Type

Strategy, Pine Script v6

Draws

On the price 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.

Topics

aialgorithmic-tradingclaude-codecodexcoding-agentsgithub-copilotopen-sourcepine-scriptpine-script-v6technical-analysis

Settings

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

SettingTypeDefaultVariable
MACD Fastint12fastLen
MACD Slowint26slowLen
Signalint9sigLen
Trend EMAint200trendLen
ATR Lengthint14atrLen
SL Multfloat2.0slMult
TP Multfloat2.5tpMult
Use Trend FilterbooltrueuseTrend
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

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

This strategy combines Arnaud Legoux Moving Average percentage price change calculations with an adaptive Gaussian Moving Average to generate trend-following signals. Long and short entries are triggered when the ALMA change calculation crosses above or below

Strategy v5 Moving averagesOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of ESM2024 - ALMA Smoothed Gaussian Moving Average
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

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA Strategy

SMA RSI Strategy

by PythonForForex
64 stars

This strategy evaluates simple moving averages and the Relative Strength Index to generate trading signals. It calculates a 10-period SMA, a 30-period SMA, and a 14-period RSI. Long positions are entered when the fast SMA crosses above the slow SMA while RSI i

Strategy v5 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of SMA RSI 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