OPEN-SOURCE SCRIPT

Alternating KAMA-MACD Buy/Sell Triangles

65
//version=6
indicator("Alternating KAMA-MACD Buy/Sell Triangles", overlay=true)

// === Inputs ===
fastLen = input.int(10, "Fast KAMA Length", minval=2)
slowLen = input.int(30, "Slow KAMA Length", minval=2)
signalLen = input.int(9, "Signal KAMA Length", minval=1)

fastSCPeriod = input.int(2, "KAMA Fast SC period", minval=1)
slowSCPeriod = input.int(30, "KAMA Slow SC period", minval=2)

// === Helper: Kaufman's Adaptive Moving Average ===
// src = source series
// n = efficiency lookback length
// fastP, slowP = periods for smoothing constant (SC)
f_kama(src, n, fastP, slowP) =>
var float kama = na
if bar_index == 0
kama := src
else
change = math.abs(src - src[n])
vol = 0.0
for i = 0 to n - 1
vol += math.abs(src - src[i+1])
er = vol == 0.0 ? 0.0 : change / vol
fastSC = 2.0 / (fastP + 1.0)
slowSC = 2.0 / (slowP + 1.0)
sc = math.pow(er * (fastSC - slowSC) + slowSC, 2)
kama := nz(kama[1], src) + sc * (src - nz(kama[1], src))
kama

// === Compute KAMA-based MACD ===
kamaFast = f_kama(close, fastLen, fastSCPeriod, slowSCPeriod)
kamaSlow = f_kama(close, slowLen, fastSCPeriod, slowSCPeriod)
macd_line = kamaFast - kamaSlow
signalKama = f_kama(macd_line, signalLen, fastSCPeriod, slowSCPeriod)
hist = macd_line - signalKama

// === Raw Signals ===
buyRaw = ta.crossover(macd_line, signalKama) and hist > 0
sellRaw = ta.crossunder(macd_line, signalKama) and hist < 0

// === Alternating filter ===
var int lastSignal = 0 // 1 = last Buy, -1 = last Sell, 0 = none
buySignal = buyRaw and lastSignal != 1
sellSignal = sellRaw and lastSignal != -1

if buySignal
lastSignal := 1
if sellSignal
lastSignal := -1

// === Plot Triangles ===
plotshape(buySignal, title="Buy Signal", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.large, text="BUY")
plotshape(sellSignal, title="Sell Signal", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.large, text="SELL")

Clause de non-responsabilité

Les informations et les publications ne sont pas destinées à être, et ne constituent pas, des conseils ou des recommandations en matière de finance, d'investissement, de trading ou d'autres types de conseils fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.