Strategy · Pine Script v4 · On the chart

ZEGUELA DEMALONG

by danielvm-git· code credited to zeguela

This strategy executes long trades based on Double Exponential Moving Average (DEMA) crossover signals.

View on GitHub

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code136
Settings10inputs
LicenceMIT
Last update2 months ago2 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

136 lines of Pine Script v4 from demalong_indicator.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

demalong_indicator.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// This code is based on the study you can find here: https://kodify.net/tradingview/indicators/dema/
// © zeguela
//@version=4
strategy(title="ZEGUELA DEMALONG", commission_value=0.070, commission_type=strategy.commission.percent, initial_capital=100, default_qty_value=90, default_qty_type=strategy.percent_of_equity, overlay=true, process_orders_on_close=true)

// Step 1. Script settings

// Input options
_srcData = input(title="Source Data", type=input.source, defval=close)

// Length settings
len1 = input(title="Length DEMA #1", type=input.integer, defval=8, minval=1)
len2 = input(title="Length DEMA #2", type=input.integer, defval=24, minval=0)
len3 = input(title="Length DEMA #3", type=input.integer, defval=0, minval=0)

// Step 2. Calculate indicator values
// Function that calculates the DEMA
DEMA(series, length) =>
    if (length > 0)
        emaValue = ema(series, length)
        2 * emaValue - ema(emaValue, length)
    else
        na

// Calculate the DEMA values
demaVal1 = DEMA(_srcData, len1)
demaVal2 = DEMA(_srcData, len2)
demaVal3 = DEMA(_srcData, len3)

// Step 3. Determine indicator signals
// See if there's a DEMA crossover
demaCrossover = if (len2 > 0) and (len3 > 0)
    crossover(demaVal1, demaVal2) and (demaVal3 > demaVal3[1])
else
    if (len2 > 0) and (len3 == 0)
        crossover(demaVal1, demaVal2)
    else
        if (len3 > 0) and (len2 == 0)
            crossover(demaVal1, demaVal3)
        else
            crossover(close, demaVal1)

// Check if there's a DEMA crossunder
demaCrossunder = if (len2 > 0) and (len3 > 0)
    crossunder(demaVal1, demaVal2) and (demaVal3 < demaVal3[1])
else
    if (len2 > 0) and (len3 == 0)
        crossunder(demaVal1, demaVal2)
    else
        if (len3 > 0) and (len2 == 0)
            crossunder(demaVal1, demaVal3)
        else
            crossunder(close, demaVal1)

// Step 4. Output indicator data
// Plot DEMAs on the chart
plot(series=demaVal1, color=color.green, linewidth=2, title="DEMA #1")
plot(series=demaVal2, color=color.red, linewidth=2, title="DEMA #2")
plot(series=demaVal3, color=color.fuchsia, linewidth=2, title="DEMA #3")


//Plot the box with position and P&L
posColor = color.new(color.green, 50)
negColor = color.new(color.red, 50)
dftColor = color.new(color.blue, 75)
posProfit= (strategy.position_size > 0) ? (close * 100 / strategy.position_avg_price - 100) : strategy.position_size < 0 ? (strategy.position_avg_price * 100 / close - 100) : 0.0
posDir   = (strategy.position_size  > 0) ? "long" : strategy.position_size < 0 ? "short" : "flat"
posCol   = (posProfit > 0) ? posColor : (posProfit < 0) ? negColor : dftColor

//Open trade Box
var label lb = na
label.delete(lb)
lb := label.new(bar_index, max(high, highest(4)[1]), textcolor=color.white,
   color=posCol,
   text="Pos: "+ posDir +
      "\nPnL: "+tostring(posProfit, "#.##")+"%" +
      "\nAvg Price: "+tostring(strategy.position_avg_price, "#.####") +
      "\nClose: "+tostring(close, "#.####"))

//Closed trades boxes
if demaCrossunder
    var label lL = na
    lL := label.new(bar_index, max(high, highest(4)[1]), textcolor=color.white, yloc=yloc.belowbar, style=label.style_label_up,
       color=posCol,
       text="Pos: "+ posDir +
          "\nPnL: "+tostring(posProfit, "#.##")+"%" +
          "\nAvg Price: "+tostring(strategy.position_avg_price, "#.####") +
          "\nClose: "+tostring(close, "#.####"))

//Plot PnL area
p1=plot(strategy.position_avg_price, color=color.blue, style=plot.style_linebr, linewidth=2, title="Entry Price")
p2=plot(series=strategy.position_size > 0 ? close : na, color=posCol, style=plot.style_linebr, linewidth=1, title="Long TP")
fill(p1, p2, color=posCol)

//Plot entru long circle sign
plotshape(demaCrossover, color=color.blue, style=shape.circle, size=size.small, textcolor=color.white)

// Step 5. Strategy setup
// Make input options that configure backtest date range
_startDate = input(title="Start Date", type=input.integer,
     defval=1, minval=1, maxval=31, group="BackTest Period")
_startMonth = input(title="Start Month", type=input.integer,
     defval=4, minval=1, maxval=12, group="BackTest Period")
_startYear = input(title="Start Year", type=input.integer,
     defval=2021, minval=1800, maxval=2100, group="BackTest Period")

_endDate = input(title="End Date", type=input.integer,
     defval=31, minval=1, maxval=31, group="BackTest Period")
_endMonth = input(title="End Month", type=input.integer,
     defval=12, minval=1, maxval=12, group="BackTest Period")
_endYear = input(title="End Year", type=input.integer,
     defval=2031, minval=1800, maxval=2100, group="BackTest Period")

// Look if the close time of the current bar
// falls inside the date range
_inDateRange = (time >= timestamp(syminfo.timezone, _startYear,
         _startMonth, _startDate, 0, 0)) and
     (time < timestamp(syminfo.timezone, _endYear, _endMonth, _endDate, 0, 0))
  
//Alert configuration     
_alertMessageOpenLong="put your message here"
_alertMessageCloseLong="put your message here"
_alertmessageExitLong="put your message here"
_alertmessageTPLong="put your message here"

// Step 6. Strategy Execution
if (_inDateRange)
    if (demaCrossover)
        strategy.entry("LONG", strategy.long, comment = "ENTER LONG", alert_message=_alertMessageOpenLong)
    if (demaCrossunder)
        strategy.close(id="LONG", when=strategy.position_size != 0, comment = "EXIT LONG", alert_message=_alertmessageExitLong)

// Exit open market position when date range ends
if (not _inDateRange)
    strategy.close_all()

Overview

ZEGUELA DEMALONG calculates up to three DEMAs, triggering entries when the faster DEMA crosses above the slower DEMA (optionally filtered by a third DEMA's direction) or when price crosses above a single DEMA. Exits occur on corresponding crossunders. Position status, average entry price, and current percentage profit or loss are displayed via on-chart labels. There is no predefined stop loss or take profit.

Details

Published by

danielvm-git on GitHub

Code credit

zeguela, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Markets

Any symbol

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
Source Datasourceclose_srcData
Length DEMA #1int8len1
Length DEMA #2int24len2
Length DEMA #3int0len3
Start Dateint1_startDate
Start Monthint4_startMonth
Start Yearint2021_startYear
End Dateint31_endDate
End Monthint12_endMonth
End Yearint2031_endYear
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated 2 days ago · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
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
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 7 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

EMA Crossover Strategy

by TradersPost
228 stars

EMA Crossover Strategy plots a fast and a slow exponential moving average on the price chart. It treats a confirmed fast-over-slow cross as a long condition and a confirmed cross under as a short condition. Position size is a percentage of equity. Optional per

Strategy v6 TrendMoving averages
Updated 3 months ago · None stated GitHub repository of EMA Crossover Strategy

More Moving averages 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