Code of strategy DEMA + Supertrend

Code of strategy DEMA + Supertrend

AlgoMind Lab

//@version=6

strategy("Supertrend with DEMA Strategy (Reversal Enabled)", overlay=true)


// ===== Supertrend Parameters =====

atrPeriod = input.int(10, "ATR Length", minval=1)

factor  = input.float(3.0, "Factor", minval=0.01, step=0.01)


// ===== Trade-direction Permissions =====

allowLong = input.bool(true, "Разрешить LONG")

allowShort = input.bool(true, "Разрешить SHORT")


// Supertrend calculation

[supertrend, direction] = ta.supertrend(factor, atrPeriod)

// For the first bar set value to na to avoid false signals

supertrend := barstate.isfirst ? na : supertrend


// Plot Supertrend lines

plot(direction < 0 ? supertrend : na, "Up Trend",  color=color.green, style=plot.style_linebr)

plot(direction < 0 ? na : supertrend, "Down Trend", color=color.red,  style=plot.style_linebr)


// ===== DEMA Parameters & Calculation =====

demaLength = input.int(100, "DEMA Length", minval=1)

e1 = ta.ema(close, demaLength)

e2 = ta.ema(e1, demaLength)

dema = 2 * e1 - e2


// Plot DEMA

plot(dema, "DEMA", color=#43A047)


// ===== Signal Definitions =====

// Base trend-change signals by Supertrend

trendUp  = ta.crossover(close, supertrend)

trendDown = ta.crossunder(close, supertrend)


// Entry signals with DEMA filter

longSignal = trendUp and (close > dema)

shortSignal = trendDown and (close < dema)


// ===== Entry / Position Reversal Logic =====


// LONG signal

if (longSignal)

  // If a SHORT position is open, flip to LONG if allowed

  if (strategy.position_size < 0)

    if (allowLong)

      strategy.close("Short")

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

    else

      // If flipping to LONG not allowed, just close SHORT

      strategy.close("Short")

  // If no position, open LONG if allowed

  else if (strategy.position_size == 0)

    if (allowLong)

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


// SHORT signal

if (shortSignal)

  // If a LONG position is open, flip to SHORT if allowed

  if (strategy.position_size > 0)

    if (allowShort)

      strategy.close("Long")

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

    else

      // If flipping to SHORT not allowed, just close LONG

      strategy.close("Long")

  // If no position, open SHORT if allowed

  else if (strategy.position_size == 0)

    if (allowShort)

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


// ===== Additional position close on trend change without entry =====

// If Supertrend crossover occurs (trend change) but DEMA conditions aren't met,

// then if an opposite position is open, just close it.

if (trendUp and not longSignal and strategy.position_size < 0)

  strategy.close("Short")


if (trendDown and not shortSignal and strategy.position_size > 0)

  strategy.close("Long")



Report Page