Indicator · Pine Script v5 · On the chart

Nadaraya-Watson: Envelope (Non-Repainting)

by nersent· code credited to jdehorty

This overlay indicator estimates price with a Nadaraya-Watson rational quadratic kernel and draws an envelope around that estimate.

View on GitHub

GitHub stars29on the repository
Pine versionv5runs as is
Lines of code84
Settings6inputs
LicenceCustom licencefile: MPL-2.0
Last update11 months ago24 Nov 2025

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

84 lines of Pine Script v5 from suite/jdehorty/nadaraya_watson_envelope.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

nadaraya_watson_envelope.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jdehorty
// @version=5

indicator(title="Nadaraya-Watson: Envelope (Non-Repainting)", overlay=true, timeframe='')

// In technical analysis, an "envelope" typically refers to a pair of upper and lower bounds that surrounds price action to help characterize extreme overbought and oversold conditions. Envelopes are often derived from a simple moving average (SMA) and are placed at a predefined distance above and below the SMA from which they were generated.
// However, envelopes do not necessarily need to be derived from a moving average. In fact, they can be derived from any estimator, including a kernel density estimator (KDE) such as Nadaraya-Watson (NW). Nadaraya-Watson Estimation is a non-parametric regression technique that uses a kernel function to estimate the value of a function at a given point. 
// In this indicator, the Rational Quadratic (RQ) Kernel is used to estimate the value of the price at each bar. From this estimation, the upper and lower bounds of the envelope are calculated based on ATR and a user-defined multiplier.

// Libraries
import jdehorty/KernelFunctions/2 as kernels 

// Helper Functions
getBounds(_atr, _nearFactor, _farFactor, _yhat) => 
    _upper_far = _yhat + _farFactor*_atr
    _upper_near = _yhat + _nearFactor*_atr
    _lower_near = _yhat - _nearFactor*_atr
    _lower_far = _yhat - _farFactor*_atr
    _upper_avg = (_upper_far + _upper_near) / 2
    _lower_avg = (_lower_far + _lower_near) / 2 
    [_upper_near, _upper_far, _upper_avg, _lower_near, _lower_far, _lower_avg]

kernel_atr(length, _high, _low, _close) =>
    trueRange = na(_high[1])? _high-_low : math.max(math.max(_high - _low, math.abs(_high - _close[1])), math.abs(_low - _close[1]))
    ta.rma(trueRange, length)

// Kernel Settings
h = input.int(8, 'Lookback Window', tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50', group='Kernel Settings')
alpha = input.float(8., 'Relative Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group='Kernel Settings')
x_0 = input.int(25, "Start Regression at Bar", tooltip='Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit. Recommended range: 5-25', group='Kernel Settings')

// Envelope Calculations
var float yhat_close = na
var float yhat_high = na
var float yhat_low = na
var float yhat = na
var float ktr = na

yhat_close := kernels.rationalQuadratic(close, h, alpha, x_0)
yhat_high := kernels.rationalQuadratic(high, h, alpha, x_0)
yhat_low := kernels.rationalQuadratic(low, h, alpha, x_0)
yhat := yhat_close
atr_length = input.int(60, 'ATR Length', minval=1, tooltip='The number of bars associated with the Average True Range (ATR).')
ktr := kernel_atr(atr_length, yhat_high, yhat_low, yhat_close)
nearFactor = input.float(1.5, 'Near ATR Factor', minval=0.5, step=0.25, tooltip='The factor by which to multiply the ATR to calculate the near bound of the envelope. Recommended range: 0.5-2.0')
farFactor = input.float(8.0, 'Far ATR Factor', minval=1.0, step=0.25, tooltip='The factor by which to multiply the ATR to calculate the far bound of the envelope. Recommended range: 6.0-8.0')
[_upper_near, _upper_far, _upper_avg, _lower_near, _lower_far, _lower_avg] = getBounds(ktr, nearFactor, farFactor, yhat_close)

var float upper_near = na
upper_near := _upper_near
var float upper_far = na
upper_far := _upper_far
var float upper_avg = na
upper_avg := _upper_avg
var float lower_near = na
lower_near := _lower_near
var float lower_far = na
lower_far := _lower_far
var float lower_avg = na
lower_avg := _lower_avg

// Colors
// red_far = input.color(color.new(color.red, 60), title='Upper Boundary Color: Far', tooltip='The color of the farmost upper boundary of the envelope.', group='Color Settings')
// red_near = input.color(color.new(color.red, 80), title='Upper Boundary Color: Near', tooltip='The color of the nearmost upper boundary of the envelope.', group='Color Settings')
// yhat_green = input.color(color.new(color.green, 50), title='Bullish Estimator Color', tooltip='The Bullish color of the Nadaraya-Watson estimator.', group='Color Settings')
// yhat_red = input.color(color.new(color.red, 50), title='Bearish Estimator Color', tooltip='The Bearish color of the Nadaraya-Watson estimator.', group='Color Settings')
// green_near = input.color(color.new(color.green, 80), title='Lower Boundary Color: Near', tooltip='The color of the nearmost lower boundary of the envelope.', group='Color Settings')
// green_far = input.color(color.new(color.green, 60), title='Lower Boundary Color: Far', tooltip='The color of the farmost lower boundary of the envelope.', group='Color Settings')

// // Plots
// p_upper_far = plot(upper_far, color=red_far, title='Upper Boundary: Far')
// p_upper_avg = plot(upper_avg, color=red_near,title='Upper Boundary: Average')
// p_upper_near = plot(upper_near, color=red_near, title='Upper Boundary: Near') 
// p_yhat = plot(yhat_close, color=yhat > yhat[1] ? yhat_green : yhat_red, linewidth=2, title='Nadaraya-Watson Estimation')
// p_lower_near = plot(lower_near, color=green_near, title='Lower Boundary: Near')
// p_lower_avg = plot(lower_avg, color=green_near, title='Lower Boundary: Average') 
// p_lower_far = plot(lower_far, color=green_far, title='Lower Boundary: Far')

// // Fills
// fill(p_upper_far, p_upper_avg, color=red_far, title='Upper Boundary: Farmost Region')
// fill(p_upper_near, p_upper_avg, color=red_near, title='Upper Boundary: Nearmost Region')
// fill(p_lower_near, p_lower_avg, color=green_near, title='Lower Boundary: Nearmost Region')
// fill(p_lower_far, p_lower_avg, color=green_far, title='Lower Boundary: Farmost Region')

Overview

Nadaraya-Watson: Envelope (Non-Repainting) regresses close, high, and low, then builds a kernel ATR from those estimates. Near and far upper and lower bounds, plus their midpoints, are placed using user ATR multipliers. Lookback window, relative weighting, regression start bar, and ATR length change the fit and band width. It plots on the price chart and does not generate entries or exits. The title marks it as non-repainting.

Details

Published by

nersent on GitHub

Code credit

jdehorty, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Volatility & bands

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.

Topics

backtestindicatorjavascriptpandas-tapinescriptpythontata-libtradingviewvectorized

Settings

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

SettingTypeDefaultVariable
Lookback Windowint8h
Relative Weightingfloat8.alpha
Start Regression at Barint25x_0
ATR Lengthint60atr_length
Near ATR Factorfloat1.5nearFactor
Far ATR Factorfloat8.0farFactor
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

Chandelier Exit

by everget
948 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 10 days ago · GPL-3.0 GitHub repository of Chandelier Exit

ICT Liquidity Void Fill

by ArunKBhaskar
575 stars

This overlay indicator marks ICT liquidity void fills on the price chart and can show long and short signals. It places a Fibonacci level inside a displacement candle, defaulting to the midpoint, and draws lines in a chosen style. Optional filters limit the fi

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Liquidity Void Fill

This indicator plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

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

Algo AVT

by ricardosantos79
261 stars

This indicator calculates an outlier-filtered moving average based on statistical filtering concepts. It stores close prices in a rolling array over a user-defined length, calculates the mean and standard deviation, and excludes values falling within a specifi

Indicator v4 Moving averagesVolatility & bands
Updated 4 years ago · None stated GitHub repository of Algo AVT

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