Indicator · Pine Script v6 · On the chart

EMD Trend [InvestorUnknown]

by regalouisei· code credited to InvestorUnknown

EMD Trend calculates trend direction by combining moving averages with an exponential moving deviation filter.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code226
Settings13inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago25 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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

226 lines of Pine Script v6 from pinescript/editors_picks/emd-trend-investorunknown.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

emd-trend-investorunknown.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © InvestorUnknown
//                                                                                  {||}                   
//                                                       ,                          {||}          
//                                                  ,,,,,                           {||}
//                                                ,,,,,       ,       ,,            {||}       
//                                    ,         ,,,, ,       ,,     ,,,             {||}       
//             .                   , ,         ,,,,  ,     ,,,,   .,,               {||}            ╔╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╗
//             ,,                 ,       ,,   ,,,,,,,  ,  ,      ,                 {||}            ╠╬╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╬╣  
//             ,,                 ,,   ,  ,,  ,,,,,, ,,,,    , ,                    {||}            ╠╣  /$$$$$$                                           /$$                         ╠╣
//              .,         ,      ,,,  ,,,,,,,,,,,,,, ,,  ,,  , ,         ,,        {||}            ╠╣ |_  $$_/                                          | $$                         ╠╣
//                           ,  .  ,, ,,,,,,,,,,,,, ,    ,,, , ,,    ,   ,          {||}            ╠╣   | $$   /$$$$$$$  /$$    /$$ /$$$$$$   /$$$$$$$ /$$$$$$    /$$$$$$   /$$$$$$  ╠╣
//                   ,,           ,,, ,,,,,,,,,,,,,,,,,,,,,,  ,,,   ,,              {||}            ╠╣   | $$  | $$__  $$|  $$  /$$//$$__  $$ /$$_____/|_  $$_/   /$$__  $$ /$$__  $$ ╠╣
//               , ,   ,,,     .,,,,,,,,,,,, ,,,  ,,,,,,,,   ,,,    ,,              {||}            ╠╣   | $$  | $$  \ $$ \  $$/$$/| $$$$$$$$|  $$$$$$   | $$    | $$  \ $$| $$  \__/ ╠╣      
//         .,     , ,,  ,,    ,,, ,,,,,,, ,,  ,,, ,,,,, ,,, ,  ,,   ,,              {||}            ╠╣   | $$  | $$  | $$  \  $$$/ | $$_____/ \____  $$  | $$ /$$| $$  | $$| $$       ╠╣     
//            ,   ,,,,,  ,    ,,,, ,, , ,,,,,,,,,,,,,,,,,,,,,, ,,  ,,               {||}            ╠╣  /$$$$$$| $$  | $$   \  $/  |  $$$$$$$ /$$$$$$$/  |  $$$$/|  $$$$$$/| $$       ╠╣   
//               .    //./ /// ,,,,,,,,,,,,,,,. ,,,,,,,,,,,,,,,,,,                  {||}            ╠╣ |______/|__/  |__/    \_/    \_______/|_______/    \___/   \______/ |__/       ╠╣
//                ,  /         ,., ,,,,,,,,,,, ,,,,,,,   ,,,,,,,                    {||}            ╠╣                                                                                ╠╣
//            .  ,,,  ,/ ///./   ,,,.,,,,,,,,,,,,,,,      ,, , ,                    {||}            ╠╣                                                                                ╠╣
//             ,,,,,,  //./ , /    .,,.,,, ,,,,,, ,.     ,,,,,,,                    {||}            ╠╣                                                                                ╠╣
//              ,,,,   //  *, / / ,,,,,,,,,,,,          ,, ,,,,,                    {||}            ╠╣    /$$   /$$           /$$                                                     ╠╣
//               ,,  // ////.*/// / ,.,,,,,.,, ,,  ,,,, ,,,,,,                      {||}            ╠╣   | $$  | $$          | $$                                                     ╠╣
//                   ,  /////    //  , ,,,,,, ,,,, ,,,,,  ,,, / /.                  {||}            ╠╣   | $$  | $$ /$$$$$$$ | $$   /$$ /$$$$$$$   /$$$$$$  /$$  /$$  /$$ /$$$$$$$    ╠╣
//              ,,   ,         ////// ,,,,,,,,,  ,,,,,,,,/ ///  / //                {||}            ╠╣   | $$  | $$| $$__  $$| $$  /$$/| $$__  $$ /$$__  $$| $$ | $$ | $$| $$__  $$   ╠╣
//                         ///// .// ,,,,,,  ,, ,,,, ,,, ///*  //*///               {||}            ╠╣   | $$  | $$| $$  \ $$| $$$$$$/ | $$  \ $$| $$  \ $$| $$ | $$ | $$| $$  \ $$   ╠╣
//                           //  .           ,, .// ,,      ///, ///                {||}            ╠╣   | $$  | $$| $$  | $$| $$_  $$ | $$  | $$| $$  | $$| $$ | $$ | $$| $$  | $$   ╠╣
//                        //////        ,,,,    ///// ,.        ,                   {||}            ╠╣   |  $$$$$$/| $$  | $$| $$ \  $$| $$  | $$|  $$$$$$/|  $$$$$/$$$$/| $$  | $$   ╠╣
//                   *///////. //              /  */////*                           {||}            ╠╣    \______/ |__/  |__/|__/  \__/|__/  |__/ \______/  \_____/\___/ |__/  |__/   ╠╣ 
//                         .,,  // ,,,,,,,,,, //* ,,,  //////                       {||}            ╠╬╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╬╣
//                           ,,,,,   ,,,,,, ,.,,,,,,,                               {||}            ╚╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╝
//                               ,,,,,,,,,,,, ,,                                    {||}          
//                                  ,,,,,,,,,                                       {||}                                                                                                                                  
//                                                                                  {||} 
//                                                                                  {||} 

//@version=6
indicator("EMD Trend [InvestorUnknown]", "EMD Trend", overlay=true, max_bars_back = 4999)

import InvestorUnknown/BacktestLibrary/2 as backtestlib
import TradingView/ta/9 as ta

// - - - - - FUNCTIONS - - - - - //{
type bar
    float o             = open
    float h             = high
    float l             = low
    float c             = close

method calc_src(bar b, simple string src) =>
    float x = switch src
        "open"          => b.o
        "high"          => b.h
        "low"           => b.l
        "close"         => b.c
        "oc2"           => math.avg(b.o, b.c          )
        "hl2"           => math.avg(b.h, b.l          )
        "occ3"          => math.avg(b.o, b.c, b.c     )
        "hlc3"          => math.avg(b.h, b.l, b.c     )
        "ohlc4"         => math.avg(b.o, b.h, b.l, b.c)
        "hlcc4"         => math.avg(b.h, b.l, b.c, b.c)
    x

// Exponential Moving Deviation
emd(source, benchmark, length) =>
    abs_dev = math.abs(source - benchmark)
    exp_dev = ta.ema(abs_dev, length)

EMD_Trend(series float src, simple int length, simple float mult, simple string avg_type) =>
    avg = switch avg_type
        "SMA" =>    ta.sma(src, length) 
        "EMA" =>    ta.ema(src, length)
        "HMA" =>    ta.hma(src, length)
        "DEMA" =>   ta.dema(src, length)
        "TEMA" =>   ta.tema(src, length)
        "RMA" =>    ta.rma(src, length)
        "FRAMA" =>  ta.frama(src, length)

    emd = emd(src, avg, length)
    avg_p = avg + (emd * mult)
    avg_m = avg - (emd * mult)

    var direction = 0
    if ta.crossover(src, avg_p)
        direction := 1
    else if ta.crossunder(src, avg_m)
        direction := -1

    [direction, avg, avg_p, avg_m]
//}


// - - - - - STRINGS - - - - - //{
var string G1                       = "General Settings"
var string G2                       = "Indicator Settings"
var string G3                       = "Backtest Mode"

var string intrabar_tooltip         = "Updates the Long/Short signal within the bar, but may cause intra-bar signal repainting. This setting also affects alerts."

var string use_endDate_tooltip      = "If turned-off, the backtest will run until the current day."
var string bah_tooltip              = "Plots Buy and Hold Equity for the Backtest Period"
//}


// - - - - - INPUTS - - - - - //{

// General
simple string disp_mode             = input.string("Overlay", "Display Mode", options = ["Overlay", "Backtest Mode"], group = G1, display = display.none)
simple bool   intrabar              = input.bool(true, "Allow Intra-bar Updating", tooltip = intrabar_tooltip, group = G1)
simple bool   color_bars            = input.bool(true, "Color Bars?", group = G1)

// Indicator
simple string input_src             = input.string("close", "Source", options = ["open", "high", "low", "close", "oc2", "hl2", "occ3", "hlc3", "ohlc4", "hlcc4"], group = G2)
simple string avg_type              = input.string("SMA", "Average Type", options = ["SMA", "EMA", "HMA", "DEMA", "TEMA", "RMA", "FRAMA"], group = G2)
simple int    length                = input.int(28, "Average Length", minval = 1, group = G2)
simple float  mult                  = input.float(1.0, "Exponential Moving Deviation Multiplier", step = 0.05, minval = 0.05, group = G2)

// Backtesting Mode
simple string signals               = input.string("Long & Short", "Allowed Signals", options = ["Long & Short", "Long Only", "Short Only"], group = G3, display = display.none)
simple float  startDate             = input.time(timestamp("2023-1-1"), "Backtest Start Date", group = G3)
simple bool   plot_bah              = input.bool(true, "Plot Buy & Hold equity?", tooltip = bah_tooltip, group = G3)
simple bool   plot_metric_t         = input.bool(true, "Plot Performance Metrics Table", group = G3)

simple int    initial_capital       = input.int(1000, "Initial Capital For Trade Metrics", group = G3, display = display.none)
simple float  trade_size            = input.float(0.01, "Trade Size % (decimal)", minval = 0.001, maxval = 1.0, group = G3, display = display.none)
//}


// - - - - - CALCULATIONS - - - - - //{

b                                   = bar.new()
float src                           = b.calc_src(input_src)

[dir, avg, avg_p, avg_m]            = EMD_Trend(src, length, mult, avg_type)
//}

// - - - - - DEFINE COLORS - - - - - //{
color bcol                          =color.rgb(54, 208, 19)
color scol                          =color.rgb(227, 34, 34)
//}


// - - - - - PLOTS - - - - - //{
bool  is_backtest                   = disp_mode == "Backtest Mode"
float candle_h_l                    = src > avg_p ? high : src < avg_m ? low : math.avg(open, close)
int   i                             = intrabar ? 0 : 1 // simple index instead of writing it manually every time

C = plot(not is_backtest ? candle_h_l : na,"Candle Extreme", display = display.none)
M = plot(not is_backtest ? avg[i] : na, "Average", color = dir[i] > 0 ? bcol : scol, linewidth = 3)
U = plot(not is_backtest ? avg_p[i] : na, color = dir[i] > 0 ? color.new(bcol, 50) : color.new(scol, 50))
D = plot(not is_backtest ? avg_m[i] : na, color = dir[i] > 0 ? color.new(bcol, 50) : color.new(scol, 50))

// range fill
fill(U, D, color = dir[i] > 0 ? color.rgb(54, 208, 19, 95): na)
fill(D, U, color = dir[i] < 0 ? color.rgb(227, 34, 34, 95) : na)

// speculation area fill
fill(C, U, color = dir[i] > 0 and close > avg_p[i] ? color.rgb(54, 208, 19, 50) : na)
fill(C, D, color = dir[i] < 0 and close < avg_m[i] ? color.rgb(227, 34, 34, 50) : na)


barcolor(color_bars ? // color_bars == true ? yes -> continue : no -> na
 (is_backtest ? dir[1] > 0 ? bcol : scol : // backtest mode ? yes -> sig_col[1] : no -> continue
 (dir[i] > 0 ? bcol : scol)) : 
 na)


// Backtest Mode
float r                             = 0.0
float eq                            = 1.0
float bah                           = 1.0

series int since                    = backtestlib.since(startDate, is_backtest)

if is_backtest
    r                               := (close[0] - close[1]) / close[1]
    eq                              := backtestlib.equity(dir, 0, r, startDate, signals)
    bah                             := backtestlib.buy_and_hold(r, startDate)

plot(is_backtest ? 1 : na, "Base (1) Line", color = color.gray)
plot(is_backtest ? eq : na, "Backtest Strategy Equity",  color = dir[1] > 0 ? bcol : scol, linewidth = 3)
plot(is_backtest ? (plot_bah ? bah : na) : na, "Buy & Hold Equity", color = color.rgb(24, 42, 237), linewidth = 2)

if is_backtest and barstate.islast
    label.new(bar_index + 5, eq, "Strategy", color = dir[1] > 0 ? bcol : scol, textcolor = color.white, style = label.style_label_left)
    label.new(bar_index + 5, bah, "Buy and Hold", color = color.rgb(24, 42, 237), textcolor = color.white, style = label.style_label_left)

// Performance Metrics Table
float[] eq_array                    = na
float[] bah_array                   = na

if is_backtest
    eq_array                        := backtestlib.PerformanceMetrics(eq,  since, startDate)
    bah_array                       := backtestlib.PerformanceMetrics(bah, since, startDate)

var table t                         = table.new(position.bottom_left, 20, 20, frame_color = color.gray, frame_width = 1)

bool long_entry                     = ta.crossover(dir, 0)
bool entry_short                    = ta.crossunder(dir, 0)

[signal, closed_trades_count, closed_long, closed_short, win_trades, win_long, win_short, gross_profit, gross_losses, gross_L_profit, gross_L_losses, gross_S_profit, gross_S_losses] = backtestlib.TradeMetrics(
 startDate, initial_capital, trade_size, long_entry, entry_short, false, false)

if barstate.islast and is_backtest
    backtestlib.PerfMetricTable(bah_array, eq_array)
    backtestlib.TradeMetricsTable(initial_capital, closed_trades_count, closed_long, closed_short, win_trades, win_long, win_short, gross_profit, gross_losses, gross_L_profit, gross_L_losses, gross_S_profit, gross_S_losses)
//}

// - - - - - ALERTS - - - - - //{
alert_source                        = dir

bool long_alert                     = ta.crossover (alert_source[i], 0)
bool short_alert                    = ta.crossunder(alert_source[i], 0)

bool risk_on_long                   = ta.crossover (src, avg_p[i])
bool risk_off_long                  = ta.crossunder(src, avg_p[i])
bool risk_on_short                  = ta.crossunder(src, avg_m[i])
bool risk_off_short                 = ta.crossover (src, avg_m[i])

alertcondition(long_alert,  "LONG (EMD Trend)",  "EMD Trend flipped ⬆LONG⬆")
alertcondition(short_alert, "SHORT (EMD Trend)", "EMD Trend flipped ⬇Short⬇")

alertcondition(risk_on_long,   "RISK-ON LONG (EMD Trend)",   "RISK-ON LONG (EMD Trend)")
alertcondition(risk_off_long,  "RISK-OFF LONG (EMD Trend)",  "RISK-OFF LONG (EMD Trend)")
alertcondition(risk_on_short,  "RISK-ON SHORT (EMD Trend)",  "RISK-ON SHORT (EMD Trend)")
alertcondition(risk_off_short, "RISK-OFF SHORT (EMD Trend)", "RISK-OFF SHORT (EMD Trend)")
//}

Overview

Rendered as an overlay on the main price chart, it generates visual long and short trend signals and offers optional bar coloring. It includes an on-screen performance metrics table and buy-and-hold equity line to simulate trade results based on selected signal rules. Inputs allow customizing the baseline moving average type, calculation length, deviation multiplier, and backtest start date.

Details

Published by

regalouisei on GitHub

Code credit

InvestorUnknown, as written in the script's header

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Trend, Moving averages

Markets

Any symbol

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
Display ModestringOverlaydisp_mode
Allow Intra-bar Updatingbooltrueintrabar
Color Bars?booltruecolor_bars
Sourcestringcloseinput_src
Average TypestringSMAavg_type
Average Lengthint28length
Exponential Moving Deviation Multiplierfloat1.0mult
Allowed SignalsstringLong & Shortsignals
Backtest Start Datetimetimestamp("2023-1-1")startDate
Plot Buy & Hold equity?booltrueplot_bah
Plot Performance Metrics Tablebooltrueplot_metric_t
Initial Capital For Trade Metricsint1000initial_capital
Show all 13 settings
SettingTypeDefaultVariable
Trade Size % (decimal)float0.01trade_size
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

948 stars

The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec

Indicator v4 TrendMoving averages
Updated 10 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
330 stars

This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab

Indicator v4 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of 3 EMA/SMA + Cross [Alorse]
318 stars

This indicator plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 2 months ago · MIT GitHub repository of Multiple Moving Averages

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of NVDA Trend Ribbon
257 stars

Donald SPX - Options Trading is an overlay indicator designed for intraday SPX analysis. It plots a 200-period Weighted Moving Average (WMA) on the price chart while evaluating multi-timeframe market structure across Daily, 15-minute, 5-minute, and 2-minute ba

Indicator v5 Moving averagesTrend Repaints
Updated 6 weeks ago · None stated GitHub repository of Donald SPX - Options Trading

60K均線

by TaichiS
219 stars

This multi-timeframe indicator calculates and plots 20-period and 60-period simple moving averages from the 60-minute timeframe directly onto the price chart. The 20-period average displays as a green line, while the 60-period average appears in blue. It serve

Indicator v4 Moving averagesTrend Repaints
Updated 5 years ago · None stated GitHub repository of 60K均線

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers