Strategy · Pine Script v6 · Own pane

Stella's MACD Crossover

by stella-entry· code credited to Stella

This strategy calculates the standard Moving Average Convergence Divergence oscillator and generates trade entries based on signal line crossovers.

View on GitHub

GitHub stars3on the repository
Pine versionv6current
Lines of code101
Settings7inputs
LicenceMIT
Last update8 months ago22 Feb 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

101 lines of Pine Script v6 from strategies/macd-crossover.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

macd-crossover.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Stella

//@version=6
strategy("Stella's MACD Crossover", 
         overlay=false, 
         default_qty_type=strategy.percent_of_equity, 
         default_qty_value=10,
         initial_capital=1000,
         commission_type=strategy.commission.percent,
         commission_value=0.1)

// ============================================
// MACD Crossover Strategy / MACDクロスオーバー戦略
// ============================================
// 
// 【English】
// Classic momentum strategy using MACD signal line crossovers.
// - Long: MACD crosses above signal line
// - Short: MACD crosses below signal line
// - Optional: Add EMA filter to trade only with trend
//
// 【日本語】
// MACDシグナルラインのクロスオーバーを使った古典的なモメンタム戦略。
// - ロング: MACDがシグナルラインを上抜け
// - ショート: MACDがシグナルラインを下抜け
// - オプション: EMAフィルターでトレンド方向のみ取引

// ----------------------------------------
// Inputs / 入力パラメータ
// ----------------------------------------
fastLength = input.int(12, "Fast EMA Period / 短期EMA期間", minval=1)
slowLength = input.int(26, "Slow EMA Period / 長期EMA期間", minval=1)
signalLength = input.int(9, "Signal Period / シグナル期間", minval=1)

useTrendFilter = input.bool(false, "Use EMA Trend Filter / EMAトレンドフィルター使用")
emaPeriod = input.int(200, "Trend EMA Period / トレンドEMA期間", minval=1)

// Stop Loss / 損切り
useStopLoss = input.bool(true, "Use Stop Loss / 損切り使用")
stopLossPercent = input.float(8.0, "Stop Loss % / 損切り%", minval=0.1, maxval=50)

// ----------------------------------------
// Calculations / 計算
// ----------------------------------------

// MACD calculation / MACD計算
[macdLine, signalLine, histLine] = ta.macd(close, fastLength, slowLength, signalLength)

// Trend filter / トレンドフィルター
trendEma = ta.ema(close, emaPeriod)
isUptrend = close > trendEma
isDowntrend = close < trendEma

// ----------------------------------------
// Entry Conditions / エントリー条件
// ----------------------------------------

// MACD crossover / MACDクロスオーバー
macdBullishCross = ta.crossover(macdLine, signalLine)
macdBearishCross = ta.crossunder(macdLine, signalLine)

// With trend filter / トレンドフィルター付き
longCondition = useTrendFilter ? (macdBullishCross and isUptrend) : macdBullishCross
shortCondition = useTrendFilter ? (macdBearishCross and isDowntrend) : macdBearishCross

// ----------------------------------------
// Execute Trades / 取引実行
// ----------------------------------------

if longCondition
    strategy.entry("Long", strategy.long)

if shortCondition
    strategy.entry("Short", strategy.short)

// Stop Loss / 損切り
if useStopLoss
    if strategy.position_size > 0
        strategy.exit("SL Long", "Long", stop=strategy.position_avg_price * (1 - stopLossPercent / 100))
    if strategy.position_size < 0
        strategy.exit("SL Short", "Short", stop=strategy.position_avg_price * (1 + stopLossPercent / 100))

// ----------------------------------------
// Plotting / プロット
// ----------------------------------------

plot(macdLine, "MACD", color=color.blue, linewidth=2)
plot(signalLine, "Signal", color=color.orange, linewidth=2)
plot(histLine, "Histogram", style=plot.style_columns, 
     color=histLine >= 0 ? color.green : color.red)

// Zero line / ゼロライン
hline(0, "Zero", color=color.gray, linestyle=hline.style_dashed)

// Trend EMA (if enabled) / トレンドEMA(有効時)
plot(useTrendFilter ? trendEma : na, "Trend EMA", color=color.purple, linewidth=2)

// Entry markers / エントリーマーカー
plotshape(longCondition, "Long Signal", shape.triangleup, location.bottom, color.green, size=size.small)
plotshape(shortCondition, "Short Signal", shape.triangledown, location.top, color.red, size=size.small)

Overview

Stella's MACD Crossover opens long positions on bullish crossovers and short positions on bearish crossunders. An optional exponential moving average filter allows entries only aligned with the broader trend. Risk is managed with an optional fixed percentage stop loss, while opposite crossover signals naturally reverse trades. The script plots the MACD and signal line in an oscillator pane below the price chart.

Details

Published by

stella-entry on GitHub

Code credit

Stella, as written in the script's header

Draws

Separate pane below the chart

Markets

Crypto

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 EMA Period / 短期EMA期間int12fastLength
Slow EMA Period / 長期EMA期間int26slowLength
Signal Period / シグナル期間int9signalLength
Use EMA Trend Filter / EMAトレンドフィルター使用boolfalseuseTrendFilter
Trend EMA Period / トレンドEMA期間int200emaPeriod
Use Stop Loss / 損切り使用booltrueuseStopLoss
Stop Loss % / 損切り%float8.0stopLossPercent
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 2 days ago · 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 3 days ago · 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 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