Indicator · Pine Script v4 · On the chart

Nadaraya-Watson Estimator + Moving Average Colored EMA/SMA

by DaniilOkrug· code credited to LuxAlgo

This indicator combines a Nadaraya-Watson kernel regression estimator with moving average trend overlays.

View on GitHub

Repaints

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code198
Settings11inputs
LicenceMIT
Last update4 years ago15 Dec 2021

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

198 lines of Pine Script v4 from [Order] Nadaraya-Watson Estimator + Moving Average Colored EMASMA.txt, published under MIT. Keep the author's credit and licence lines when you reuse it.

[Order] Nadaraya-Watson Estimator + Moving Average Colored EMASMA.txt
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=4

study("[Order] Nadaraya-Watson Estimator + Moving Average Colored EMA/SMA",overlay=true,max_lines_count=500,max_bars_back=500)
h = input(8.,'Bandwidth')
src_e = input(close,'Source')

emaplot = input (true, title="Show EMA on chart")
len_ema = input(8, minval=1, title="ema Length")

smaplot = input (false, title="Show SMA on chart")
len_sma = input(8, minval=1, title="sma Length")

//----
n = bar_index
var ln = array.new_line(0) 
if barstate.isfirst
    for i = 0 to 499
        array.push(ln,line.new(na,na,na,na))
//----
float y2 = na
float y1 = na
float y1_d = na
//----
line l = na
label lb = na
if barstate.islast
    for i = 0 to min(499,n-1)
        sum = 0.
        sumw = 0.
        for j = 0 to min(499,n-1)
            w = exp(-(pow(i-j,2)/(h*h*2)))
            sum += src_e[j]*w
            sumw += w
        y2 := sum/sumw
        d = y2 - y1

        l := array.get(ln,i)
        line.set_xy1(l,n-i+1,y1)
        line.set_xy2(l,n-i,y2)
        line.set_color(l,y2 > y1 ? #ff1100 : #39ff14)
        line.set_width(l,2)
        
        if d > 0 and y1_d < 0
            label.new(n-i+1,src_e[i],'▲',color=#00000000,style=label.style_label_up,textcolor=#39ff14,textalign=text.align_center) 
        if d < 0 and y1_d > 0
            label.new(n-i+1,src_e[i],'▼',color=#00000000,style=label.style_label_down,textcolor=#ff1100,textalign=text.align_center) 

        y1 := y2
        y1_d := d

//EMA
src_ema = close
out_ema = ema(src_ema, len_ema)
up = out_ema > out_ema[1]
down = out_ema < out_ema[1]
mycolor = up ? color.green : down ? color.red : color.blue
plot(out_ema and emaplot ? out_ema :na, title="EMA", color=mycolor, linewidth=3)

//SMA
src_sma = close
out2 = sma(src_sma, len_sma)
up2 = out2 > out2[1]
down2 = out2 < out2[1]
mycolor2 = up2 ? color.green : down2 ? color.red : color.blue
plot(out2 and smaplot ? out2 :na , title="SMA", color=mycolor2, linewidth=1)

/////////

source = close
hilow = ((high - low)*100)
openclose = ((close - open)*100)
vol = (volume / hilow)
spreadvol = (openclose * vol)
VPT = spreadvol + cum(spreadvol)
window_len = 28

v_len = 14
price_spread = stdev(high-low, window_len)

v =  spreadvol + cum(spreadvol)
smooth = sma(v, v_len)
v_spread = stdev(v - smooth, window_len)
shadow = (v - smooth) / v_spread * price_spread

out = shadow > 0 ? high + shadow : low + shadow
//
src = out
src1=open
src2=low
src3=high
tf =input(720)
len = timeframe.isintraday and timeframe.multiplier >= 1 ? 
   tf / timeframe.multiplier * 7 : 
   timeframe.isintraday and timeframe.multiplier < 60 ? 
   60 / timeframe.multiplier * 24 * 7 : 7

c = ema(src, len)
plot(c,color=color.red)
o = ema(src1,len)
plot(o,color=color.blue)
//h = ema(src3,len)
//l=ema(src2,len)
//
col=c > o? color.lime : color.orange
vis = true
vl = c
ll = o
m1 = plot(vl, color=col, linewidth=1, transp=60)
m2 = plot(vis ? ll : na,  color=col, linewidth=2, transp=80)

fill(m1, m2,  color=col, transp=70)
//

vpt=ema(out,len)

// INPUTS //
st_mult   = input(1,   title = 'SuperTrend Multiplier', minval = 0, maxval = 100, step = 0.01)
st_period = input(10, title = 'SuperTrend Period',     minval = 1)

// CALCULATIONS //
up_lev = vpt - (st_mult * atr(st_period))
dn_lev = vpt + (st_mult * atr(st_period))

up_trend   = 0.0
up_trend   := close[1] > up_trend[1]   ? max(up_lev, up_trend[1])   : up_lev

down_trend = 0.0
down_trend := close[1] < down_trend[1] ? min(dn_lev, down_trend[1]) : dn_lev

// Calculate trend var
trend = 0
trend := close > down_trend[1] ? 1: close < up_trend[1] ? -1 : nz(trend[1], 1)

// Calculate SuperTrend Line
st_line = trend ==1 ? up_trend : down_trend

// Plotting
plot(st_line[1], color = trend == 1 ? color.green : color.red , style = plot.style_cross, linewidth = 2, title = "SuperTrend")
buy=crossover( close, st_line) and close>o
sell=crossunder(close, st_line) and close<o
//plotshape(crossover( close, st_line), location = location.belowbar, color = color.green,size=size.tiny)
//plotshape(crossunder(close, st_line), location = location.abovebar, color = color.red,size=size.tiny)
plotshape(buy, title="buy", text="Buy", color=color.green, style=shape.labelup, location=location.belowbar, size=size.small, textcolor=color.white, transp=0)  //plot for buy icon
plotshape(sell, title="sell", text="Sell", color=color.red, style=shape.labeldown, location=location.abovebar, size=size.small, textcolor=color.white, transp=0)  //plot for sell icon


//
multiplier = input(title="TP", type=input.float, defval=2, minval=1)
src5 = close
len5 = input(title="TP length", defval=150, minval=1)
offset = 0

calcSlope(src5, len5) =>
    sumX = 0.0
    sumY = 0.0
    sumXSqr = 0.0
    sumXY = 0.0
    for i = 1 to len5
        val = src5[len5-i]
        per = i + 1.0
        sumX := sumX + per
        sumY := sumY + val
        sumXSqr := sumXSqr + per * per
        sumXY := sumXY + val * per
        
        
    slope = (len5 * sumXY - sumX * sumY) / (len5 * sumXSqr - sumX * sumX)
    average = sumY / len5
    intercept = average - slope * sumX / len5 + slope
    [slope, average, intercept]

var float tmp = na
[s, a, i] = calcSlope(src5, len5)

vwap1=(i + s * (len5 - offset))
sdev = stdev(close, len5)
dev = multiplier * sdev
top=vwap1+dev
bott=vwap1-dev

//
z1 = vwap1 + dev
x1 = vwap1 - dev

low1 = crossover(close, x1)  
high1 = crossunder(close, z1) 

plotshape(low1, title="low", text="TP", color=color.red, style=shape.labelup, location=location.belowbar, size=size.small, textcolor=color.white, transp=0)  //plot for buy icon
plotshape(high1, title="high", text="TP", color=color.green, style=shape.labeldown, location=location.abovebar, size=size.small, textcolor=color.white, transp=0)  //plot for sell icon


/////// Alerts /////
alertcondition(buy,title="buy")
alertcondition(sell,title="sell")
alertcondition(low1,title="sell tp")
alertcondition(high1,title="buy tp")

Overview

Nadaraya-Watson Estimator + Moving Average Colored EMA/SMA recalculates kernel-weighted lines across historical bars on the latest candle, plotting reversal arrows when the curve direction shifts. Additionally, it plots color-coded EMAs and SMAs that change hue based on slope, alongside a volume-adjusted spread ribbon. All elements draw directly on the price chart. The Nadaraya-Watson estimator inherently repaints historical lines and signals as new bars form.

Details

Published by

DaniilOkrug on GitHub

Code credit

LuxAlgo, as written in the script's header

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Moving averages, Trend, Volume

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Bandwidthinput8.h
Sourcesourceclosesrc_e
Show EMA on chartbooltrueemaplot
ema Lengthint8len_ema
Show SMA on chartboolfalsesmaplot
sma Lengthint8len_sma
tfint720tf
SuperTrend Multiplierint1st_mult
SuperTrend Periodint10st_period
TPfloat2multiplier
TP lengthint150len5
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

Adaptive MA Slope

by capissimo
114 stars

This indicator calculates Kaufman's Adaptive Moving Average (KAMA) on a chosen price source and determines trend direction based on the slope across a configurable lookback window. Signals can be filtered by short-term volatility expansion using ATR comparison

Indicator v4 Moving averagesTrend
Updated 1 year ago · None stated GitHub repository of Adaptive MA Slope

Signal Strategy 15m

by tripolskypetr
72 stars

This indicator generates trend-following trade signals on the price chart by combining moving average crossovers with multi-factor filters. It triggers entry alerts when fast and slow EMAs cross in the direction of a baseline trend EMA, confirmed by non-extrem

Indicator v5 TrendMoving averages
Updated 3 days ago · MIT GitHub repository of Signal Strategy 15m
46 stars

This overlay indicator plots a SuperTrend using a 10-period ATR with a multiplier of 3, drawing up and down stop lines and a faint trend fill on the price chart. It compares a 9-period EMA with an 18-period EMA and a 12/26/9 MACD against its signal, and it req

Indicator v5 TrendOscillators & momentum
Updated 3 years ago · None stated GitHub repository of SuperTrend + MACD + EMA

Bte Acc

by f-cksociety
11 stars

Bte Acc is a chart indicator form of the PineCoders Backtesting and Trading Engine. It seeks an entry trigger from a main or alternate entry method, then checks trade direction, filters, date range, ATR readiness, and remaining capital before filling on the ne

Indicator v5 TrendOscillators & momentum Repaints
Updated 4 years ago · MPL-2.0 GitHub repository of Bte Acc
9 stars

This indicator plots a volume-weighted moving average as a central trend baseline and surrounds it with ATR-based volatility bands. It colors the trend and optional price bars according to whether price is on the bullish or bearish side of those bands. Users c

Indicator v6 TrendMoving averages
Updated 4 months ago · MIT GitHub repository of Volume Weighted Trend [QuantAlgo]
7 stars

ACCVOL 1j (SMA5 + SMA10) - AD/B is a price chart overlay indicator designed to identify volume accumulation and bullish swing trading setups. It evaluates current bar price gains, volume expansion, and volume relative to a moving average against historical pri

Indicator v6 VolumeMoving averages
Updated 3 months ago · None stated GitHub repository of ACCVOL 1j (SMA5 + SMA10) - AD/B

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