Indicator · Pine Script v6 · Own pane

Directional EMA For Loop

by vedkanani123· code credited to LyroRS

A separate-pane oscillator that smooths price with a selectable moving average, then scores its direction by looping over a range of lookbacks from a start to an end value.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code320
Settings20inputs
LicenceNone statedfile: MPL-2.0
Last update2 months ago23 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 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

320 lines of Pine Script v6 from indicator/olg_7_6_26/LyroRS/15.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

15.txt
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LyroRS

//@version=6
indicator("Directional EMA - For Loop | Lyro RS", overlay = false)


//─────────────────────────────────────────────────────────────────────────────────────────────────────────────
//─██████─────────████████──████████─████████████████───██████████████───────████████████████───██████████████─
//─██░░██─────────██░░░░██──██░░░░██─██░░░░░░░░░░░░██───██░░░░░░░░░░██───────██░░░░░░░░░░░░██───██░░░░░░░░░░██─
//─██░░██─────────████░░██──██░░████─██░░████████░░██───██░░██████░░██───────██░░████████░░██───██░░██████████─
//─██░░██───────────██░░░░██░░░░██───██░░██────██░░██───██░░██──██░░██───────██░░██────██░░██───██░░██─────────
//─██░░██───────────████░░░░░░████───██░░████████░░██───██░░██──██░░██───────██░░████████░░██───██░░██████████─
//─██░░██─────────────████░░████─────██░░░░░░░░░░░░██───██░░██──██░░██───────██░░░░░░░░░░░░██───██░░░░░░░░░░██─
//─██░░██───────────────██░░██───────██░░██████░░████───██░░██──██░░██───────██░░██████░░████───██████████░░██─
//─██░░██───────────────██░░██───────██░░██──██░░██─────██░░██──██░░██───────██░░██──██░░██─────────────██░░██─
//─██░░██████████───────██░░██───────██░░██──██░░██████─██░░██████░░██───────██░░██──██░░██████─██████████░░██─
//─██░░░░░░░░░░██───────██░░██───────██░░██──██░░░░░░██─██░░░░░░░░░░██───────██░░██──██░░░░░░██─██░░░░░░░░░░██─
//─██████████████───────██████───────██████──██████████─██████████████───────██████──██████████─██████████████─
//─────────────────────────────────────────────────────────────────────────────────────────────────────────────
//                                                 LyroRS v1.0



// Library
import TradingView/ta/9 as ta
import LyroRS/LMAs/1 as DynamicMA

// Groups
table_g = "TABLE"
colors_g = "COLORS"
indi_settings_g = "INDICATOR SETTINGS"
div_g = "DIVERGENCE SETTINGS"

// Inputs
bench = input.string("ALMA", "Select Moving Average BB", options=["SMA", "EMA", "WMA", "VWMA", "DEMA", "TEMA", "RMA", "HMA", "LSMA", "SMMA", "ALMA", "ZLSMA", "FRAMA", "KAMA", "JMA", "T3"],  group = indi_settings_g)
length = input.int(35, title = "MA - Length", group = indi_settings_g)
source = input.source(close, title = "Source 1", group = indi_settings_g)
calculateDivergence = input.bool(true, title="Calculate Divergence", group = indi_settings_g, display = display.data_window, tooltip = "Calculating divergences is needed in order for divergence alerts to fire.")


// Moving Average Switch
ma_switch(src, length, avg_type) =>
    avg = switch avg_type
        "SMA" =>    DynamicMA.SMA(src, length)
        "EMA" =>    DynamicMA.EMA(src, length)
        "WMA" =>    DynamicMA.WMA(src, length)
        "VWMA" =>   DynamicMA.VWMA(src, volume, length)
        "DEMA" =>   DynamicMA.DEMA(src, length)
        "TEMA" =>   DynamicMA.TEMA(src, length)
        "RMA" =>   DynamicMA.RMA(src, length)
        "HMA" =>    DynamicMA.HMA(src, length)
        "LSMA" =>   DynamicMA.LSMA(src, length, 0)
        "SMMA" =>   DynamicMA.SMMA(src, length)
        "ALMA" =>   DynamicMA.ALMA(src, length, 0, 20)
        "ZLSMA" =>  DynamicMA.ZLSMA(src, length)
        "FRAMA" =>  DynamicMA.FRAMA(src, length)
        "KAMA" =>   DynamicMA.KAMA(src, length)
        "JMA" =>   DynamicMA.JMA(src, length, 0.5)
        "T3" =>   DynamicMA.T3(src, length, 0.5)

Threshold_L_Fl = input.int(23, "Threshold Long", step=1, group = indi_settings_g)
Threshold_S_Fl = input.int(2, "Threshold Short", step=1, group = indi_settings_g)
a_ = input.int(54, "From", tooltip="Sets the starting index for the loop iteration.", group = indi_settings_g)
b_ = input.int(100, "To", tooltip="Sets the ending index for the loop iteration.", group = indi_settings_g)

// -- Tables
fo = input.bool(false, 'Force Table Overlay', display = display.none, group =table_g, tooltip = 'Allows forcing the overlay of the table on the chart.')
enable_table = input.bool(true, '', display = display.none, group =table_g, inline= "T")
pos_table = input.string('Middle Right', 'For Loop Table', options = ['Top Left', 'Middle Left', 'Bottom Left', 'Top Right', 'Middle Right', 'Bottom Right', 'Top Center', "Middle Center", 'Bottom Center'], group = table_g, display = display.none, inline= "T")
table_size_input = input.string("Normal", '', options= ["Huge", "Large", "Normal", "Small", "Tiny"], group= table_g, tooltip= "Settings for the  For Loop table.", display = display.none, inline= "T")

// Color Inputs
ColMode = input.string("Mystic", "Custom Color Palette", inline="drop", options=["Classic", "Mystic", "Accented", "Royal"], display=display.none, group=colors_g,  tooltip="Choose a predefined color scheme for indicator visualization.")

cpyn = input.bool(false, "Use Custom Palette", tooltip= "Enable manual selection of custom colors for trend signals.", group=colors_g, display=display.none)
cp_UpC = input.color(#00ff00, "Custom Up", inline= "Custom Palette", tooltip= "Set a custom color for bullish signals.", group=colors_g, display=display.none)
cp_DnC = input.color(#ff0000, "Custom Down", inline= "Custom Palette", tooltip= "Set a custom color for bearish signals.", group=colors_g, display=display.none)



// Colors
color UpC = na
color DnC = na

switch ColMode
    "Classic" =>
        UpC := #00E676
        DnC := #880E4F
    "Mystic" =>
        UpC := #30FDCF
        DnC := #E117B7
    "Accented" =>
        UpC := #9618F7
        DnC := #FF0078
    "Royal" =>
        UpC := #FFC107
        DnC := #673AB7


if cpyn
    UpC := cp_UpC
    DnC := cp_DnC




// Table

// -- Defining Table Size
var string table_size = na


// -- Switching Table Size
switch table_size_input
    "Huge" =>
        table_size := size.huge
    "Large" =>
        table_size :=  size.large
    "Normal" =>
        table_size :=  size.normal
    "Small" =>
        table_size :=  size.small
    "Tiny" =>
        table_size :=  size.tiny


// -- Position Switching
pot(position) =>
    var pos = switch position
        'Top Left' => position.top_left
        'Middle Left' => position.middle_left
        'Bottom Left' => position.bottom_left
        'Top Right' => position.top_right
        'Middle Right' => position.middle_right
        'Bottom Right' => position.bottom_right
        'Top Center' => position.top_center
        "Middle Center" => position.middle_center
        'Bottom Center' => position.bottom_center
    pos


// For Loop
system(src, a, b) =>
    total  = 0.0
    for i  = a to b by 1
        total += (src > src[i] ? 1 : -1)
        total
    total


all(src, benchmark, length) =>
    var float[] src_buf = array.new_float(length)
    var float[] bench_buf = array.new_float(length)
    
    // Update buffers
    array.push(src_buf, src)
    array.push(bench_buf, benchmark)
    if array.size(src_buf) > length
        array.shift(src_buf)
        array.shift(bench_buf)
    

    sum_diff = 0.0
    sum_squares = 0.0
    for i = 0 to array.size(src_buf) - 1
        src_val = array.get(src_buf, i)
        bench_val = array.get(bench_buf, i)
        diff = src_val - bench_val
        sum_diff := sum_diff + diff
        sum_squares := sum_squares + diff * diff
    
    array_size = array.size(src_buf)
    mean_diff = sum_diff / array_size
    volatility = math.sqrt(sum_squares / array_size)
    

    directional_signal = mean_diff * (volatility / (math.avg(src, benchmark) + 0.0001))
    directional_signal




avg_fl = ma_switch(source, length, bench)
aaaa = all(source,avg_fl, length)
fffff = ma_switch(source*aaaa,length,bench)
gggg = system(fffff, a_, b_)



// PLOT
plot(gggg, color = color.white)

var int fl_score = 0

// -- FL
if ta.crossover(gggg, Threshold_L_Fl)
    fl_score := 1

if ta.crossunder(gggg, Threshold_S_Fl)
    fl_score := -1

pc_fl = fl_score == 1 ? UpC : fl_score == -1 ? DnC : color.gray

plotcandle(open, high, low, close, "Candle Color", pc_fl, pc_fl, true, bordercolor = pc_fl, display = display.pane, force_overlay = true)

// Tables
var table mode_stat_table = na
if fo // 'fo' is an input, but used in an if block, not directly in table.new
    mode_stat_table := table.new(pot(pos_table), 100, 100, frame_width = 1, frame_color = color.gray, force_overlay = true, border_color = color.gray, border_width = 1)

else
    mode_stat_table := table.new(pot(pos_table), 100, 100, frame_width = 1, frame_color = color.gray, force_overlay = false, border_color = color.gray, border_width = 1)


// -- Table Cells
if enable_table
    table.cell(mode_stat_table, 0, 0, 'Directional EMA - For Loop | 𝓛𝓎𝓻𝓸 𝓡𝓢', text_color = color.white, bgcolor = #000000, text_size=table_size)
    table.cell(mode_stat_table, 1, 0, '', text_color = color.white, bgcolor = #000000, text_size=table_size)


    table.cell(mode_stat_table, 0, 1, 'Mode:', text_color = color.white, bgcolor = #000000, text_size=table_size)
    table.cell(mode_stat_table, 0, 2, 'For Loop', text_color = color.gray, bgcolor = #000000, text_size=table_size)

    table.cell(mode_stat_table, 1, 1, 'Signal:', text_color = color.white, bgcolor = #000000, text_size=table_size)
    table.cell(mode_stat_table, 1, 2, fl_score == 1 ? "⬆️Long ⬆️" : fl_score == -1 ? "⬇️Short ⬇️" : na, text_color = pc_fl, bgcolor = #000000, text_size=table_size)

    table.merge_cells(mode_stat_table, 0, 0, 1, 0)


// -- For Loop Plot
pg = plot(gggg, color = pc_fl, title= "For Loop")
plot(gggg, color = color.new(pc_fl, 75), title= "For Loop Glow Effect", linewidth = 10, display= display.pane)

plottlfl = plot(Threshold_L_Fl, color= color.new(UpC,30), editable = false)
plottsfl = plot(Threshold_S_Fl, color= color.new(DnC,30), editable = false)

fill(plottlfl, pg, gggg, Threshold_L_Fl,    fl_score == 1 ?color.new(UpC, 30):na, color.new(chart.bg_color, 50),  display = display.all, title="Shading")
fill(plottsfl, pg, gggg, Threshold_S_Fl,     fl_score == -1 ? color.new(DnC, 30) : na, color.new(chart.bg_color, 50),  display = display.all, title="Shading")


// Divergence
lookbackRight = input.int(5, title = "Lookback Right", group = div_g)
lookbackLeft = input.int(5, title = "Lookback Left", group = div_g)
rangeUpper = input.int(60, title = "Range Upper", group = div_g)
rangeLower = input.int(5, title = "Range Lower", group = div_g)
bearColor = color.red
bullColor = color.green
textColor = color.white
noneColor = color.new(color.white, 100)

_inRange(bool cond) =>
    bars = ta.barssince(cond)
    rangeLower <= bars and bars <= rangeUpper

plFound = false
phFound = false

bullCond = false
bearCond = false

rsiLBR = gggg[lookbackRight]

if calculateDivergence
    //------------------------------------------------------------------------------
    // Regular Bullish
    // rsi: Higher Low
    plFound := not na(ta.pivotlow(gggg, lookbackLeft, lookbackRight))    
    rsiHL = rsiLBR > ta.valuewhen(plFound, rsiLBR, 1) and _inRange(plFound[1])
    // Price: Lower Low
    lowLBR = low[lookbackRight]
    priceLL = lowLBR < ta.valuewhen(plFound, lowLBR, 1)
    bullCond := priceLL and rsiHL and plFound

    //------------------------------------------------------------------------------
    // Regular Bearish
    // rsi: Lower High
    phFound := not na(ta.pivothigh(gggg, lookbackLeft, lookbackRight))
    rsiLH = rsiLBR < ta.valuewhen(phFound, rsiLBR, 1) and _inRange(phFound[1])
    // Price: Higher High
    highLBR = high[lookbackRight]
    priceHH = highLBR > ta.valuewhen(phFound, highLBR, 1)
    bearCond := priceHH and rsiLH and phFound


// Divergence 
plotshape(
     bullCond  ? rsiLBR : na,
     offset    = -lookbackRight,
     title     = "Regular Bullish Label",
     text      = "⬆",
     style     = shape.labelup,
     location  = location.belowbar,
     color     = bullColor,
     textcolor = textColor,
     display   = display.pane,
     editable  = calculateDivergence,
     force_overlay = true)


plotshape(
     bearCond  ? rsiLBR : na,
     offset    = -lookbackRight,
     title     = "Regular Bearish Label",
     text      = "⬇",
     style     = shape.labeldown,
     location  = location.abovebar,
     color     = bearColor,
     textcolor = textColor,
     display   = display.pane,
     editable  = calculateDivergence,
     force_overlay = true)


// Alerts
alertcondition(fl_score == 1, "Directional EMA For Loop Trend - Long", "Root Mean Squared Error Trend is Long {{exchange}}:{{ticker}}")
alertcondition(fl_score == -1, "Directional EMA For Loop Trend - Short", "Root Mean Squared Error Trend is Short {{exchange}}:{{ticker}}")

alertcondition(bullCond, title='Regular Bullish Divergence', message="Found a new Regular Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar.")
alertcondition(bearCond, title='Regular Bearish Divergence', message='Found a new Regular Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar.')

Overview

The score is compared with long and short thresholds to mark uptrend and downtrend states. It can also detect divergences between price and the oscillator using adjustable pivot lookbacks and a bar range. A state table and color palettes are available.

Details

Published by

vedkanani123 on GitHub

Code credit

LyroRS, as written in the script's header

Draws

Separate pane below the chart

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
Select Moving Average BBstringALMAbench
MA - Lengthint35length
Source 1sourceclosesource
Calculate DivergencebooltruecalculateDivergence
Threshold Longint23Threshold_L_Fl
Threshold Shortint2Threshold_S_Fl
Fromint54a_
Toint100b_
Force Table Overlayboolfalsefo
enable_tablebooltrueenable_table
For Loop TablestringMiddle Rightpos_table
table_size_inputstringNormaltable_size_input
Show all 20 settings
SettingTypeDefaultVariable
Custom Color PalettestringMysticColMode
Use Custom Paletteboolfalsecpyn
Custom Upcolor#00ff00cp_UpC
Custom Downcolor#ff0000cp_DnC
Lookback Rightint5lookbackRight
Lookback Leftint5lookbackLeft
Range Upperint60rangeUpper
Range Lowerint5rangeLower
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

This separate-pane indicator plots a MACD line, a signal line, and a histogram whose colors show whether the histogram is rising or falling above or below zero. The oscillator and signal can each use an SMA or an EMA, and an optional marker highlights MACD and

Indicator v5 Oscillators & momentumDivergence
Updated 2 months ago · None stated GitHub repository of MTF + MACD [Alorse]

Benso RSI + PMARP

by benso87
24 stars

This indicator plots an RSI and a PMARP line in a separate pane. It calculates RSI from a chosen source and length, then overlays an SMA or EMA signal. Horizontal bull and bear control and critical levels scale the oscillator. Optional arrows mark regular and

Indicator v5 Oscillators & momentumDivergence
Updated 4 years ago · MPL-2.0 GitHub repository of Benso RSI + PMARP

Relative Strength Index

by deepentropy
13 stars

The Relative Strength Index indicator calculates momentum based on price changes over a specified length and plots the curve in a separate pane. It includes adjustable upper and lower bands, background color fills, and an optional smoothing moving average or B

Indicator v6 Oscillators & momentumMoving averages
Updated 6 months ago · MIT GitHub repository of Relative Strength Index

This indicator evaluates how price relates to one selected moving-average family rather than treating a crossover as a signal. It scores trend quality, historical respect of the average, extension, compression, acceleration, and exhaustion, then plots a relati

Indicator v6 TrendMoving averages
Updated 2 days ago · MIT GitHub repository of Market–Average Relationship Engine [WavesUnchained]

This indicator combines RSI and MFI into a hybrid oscillator scaled to 0-1. It detects divergences by comparing price and MFI slopes from linear regression. The MFI receives extra weight during divergence to amplify the effect. A TMA smooths the hybrid result

Indicator v6 Oscillators & momentumDivergence
Updated 5 months ago · None stated GitHub repository of Hybrid RSI+MFI - Gold Divergence

More Oscillators & momentum 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