Strategy · Pine Script v5 · On the chart

MACD-KDJ Double Cross Strategy

by zhuzp98· code credited to rhapsodyz

This strategy enters long and short trades when MACD histogram state agrees with KDJ filters.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code109
Settings11inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago17 Jan 2025

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

109 lines of Pine Script v5 from PineScript/Stg_MACD_KDJ.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Stg_MACD_KDJ.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rhapsodyz

//@version=5

// 1. Define strategy settings
strategy(title="MACD-KDJ Double Cross Strategy", overlay=true,
     pyramiding=0, initial_capital=100000,
     commission_type=strategy.commission.cash_per_order,
     commission_value=5, slippage=2)

// Input parameters
fastLength = input.int(12, title="Fast Length")
slowLength = input.int(26, title="Slow Length")
signalLength = input.int(9, title="Signal Length")
kdjKLength = input.int(14, title="KDJ K Length")
kdjDLength = input.int(3, title="KDJ D Length")
overboughtLevel = input.int(80, title="Overbought Level")
oversoldLevel = input.int(20, title="Oversold Level")

endMonth = input.int(12, title="End Month Backtest")
endYear  = input.int(2023, title="End Year Backtest")

usePosSize = input.bool(true, title="Use Position Sizing?")
riskPerc   = input.float(0.5, title="Risk %", step=0.25)

// 2. Calculate strategy values
// Calculate MACD
[macdLine, signalLine, histLine] = ta.macd(close, fastLength, slowLength, signalLength)

// Calculate KDJ
kdjK = ta.stoch(close, high, low, kdjKLength)
kdjD = ta.sma(kdjK, kdjDLength)
kdjJ = 3 * kdjK - 2 * kdjD

// Calculate EMA20
ema20 = ta.ema(close,20)

riskEquity  = (riskPerc / 100) * strategy.equity
atrCurrency = ta.atr(20) * syminfo.pointvalue
posSize     = usePosSize ? math.floor(riskEquity / atrCurrency) : 1

tradeWindow = time <= timestamp(endYear, endMonth, 1, 0, 0)



// 3. Determine strategy conditions
// MACD Cross-over conditions
macdCrossUp = ta.crossover(macdLine, signalLine) // Long
macdCrossDown = ta.crossunder(macdLine, signalLine) // Short 

macdLong = histLine > 0 and
     macdLine < 0
macdShort = histLine < 0 and
     macdLine > 0 

// KDJ Cross-over conditions
kdjCrossUp = ta.crossover(kdjK, kdjD)
kdjCrossDown = ta.crossunder(kdjK, kdjD)

kdjBuy = kdjK > kdjD and
     kdjJ > kdjK * 1.1 and
     kdjK < 30 and
     kdjD < 30 and
     kdjJ < 30
kdjSell = kdjK < kdjD and
     kdjJ < kdjK * 0.9 and
     kdjK > 70 and
     kdjD > 70 and
     kdjJ > 70

// 4. Determine long trading conditions
enterLong = macdLong and
     kdjBuy and
     tradeWindow

exitLong = (macdCrossDown and macdLine > 0) or
     kdjCrossDown

// 5. Code short trading conditions
enterShort = macdShort and
     kdjSell and 
     tradeWindow

exitShort = (macdCrossUp and macdLine < 0) or
     kdjCrossUp

// 6. Plottings
// Plotting signals on the chart
plotshape(series=macdCrossUp and kdjCrossUp, title="Buy Signal", color=color.green, style=shape.labelup, location=location.belowbar, text="Buy")
plotshape(series=macdCrossDown and kdjCrossDown, title="Sell Signal", color=color.red, style=shape.labeldown, location=location.abovebar, text="Sell")

// Plotting overbought/oversold levels
hline(overboughtLevel, "Overbought Level", color=color.red)
hline(oversoldLevel, "Oversold Level", color=color.green)

// 7. Submit entry orders
if enterLong
    strategy.entry("EL", strategy.long, qty=posSize)

if enterShort
    strategy.entry("ES", strategy.short, qty=posSize)

// 8. Submit exit orders
if exitLong
    strategy.close("EL")

if exitShort
    strategy.close("ES")

Overview

Longs need a positive histogram, MACD below zero, and K, D, and J below 30. Shorts need a negative histogram, MACD above zero, and those values above 70. It closes longs after a bearish MACD cross or a KDJ cross down, and shorts after the opposite crosses. Optional size uses a risk percent of equity divided by ATR. An end date blocks later entries. Labels and level lines sit on the price chart. No stop loss is set.

Details

Published by

zhuzp98 on GitHub

Code credit

rhapsodyz, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum, Mean reversion

Markets

Crypto

Timeframes

Any timeframe

Risk Notes

  • 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
Fast Lengthint12fastLength
Slow Lengthint26slowLength
Signal Lengthint9signalLength
KDJ K Lengthint14kdjKLength
KDJ D Lengthint3kdjDLength
Overbought Levelint80overboughtLevel
Oversold Levelint20oversoldLevel
End Month Backtestint12endMonth
End Year Backtestint2023endYear
Use Position Sizing?booltrueusePosSize
Risk %float0.5riskPerc
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

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

This strategy draws on the price chart and combines Stochastic RSI, the Money Flow Index, and an exponential moving average to open long or short trades. Longs use the lower oscillator thresholds and shorts use the upper ones, with direction limited to longs,

Strategy v5 Oscillators & momentumMoving averages Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders
104 stars

This strategy combines Bollinger Bands with a short RSI to fade moves that leave the bands and then return. A long requires the prior bar below the lower band and oversold, then a close back inside the band while RSI is between 30 and 50. Shorts mirror that at

Strategy v5 Oscillators & momentumVolatility & bands
Updated 3 years ago · MIT GitHub repository of Bollinger Bands and RSI Strategy
53 stars

This strategy implements Larry Connors' 2-period RSI mean-reversion algorithm overlaid on the price chart. It filters trades using a long-term Simple Moving Average (SMA), entering long positions when the price trades above the SMA and the short-term RSI drops

Strategy v6 Oscillators & momentumMean reversion
Updated 2 months ago · MPL-2.0 GitHub repository of Larry Connors 2-Period 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