Strategy · Pine Script v5 · On the chart

Nadaraya-Watson Envelope, RSI, and ATR Stop Loss Finder

by geraked

This overlay strategy combines a Nadaraya-Watson envelope, an RSI calculation, and an ATR stop-loss finder.

View on GitHub

Repaints

GitHub stars104on the repository
Pine versionv5runs as is
Lines of code148
Settings9inputs
LicenceMIT
Last update3 years ago29 Oct 2023

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

148 lines of Pine Script v5 from strategies/NWERSIASF.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

NWERSIASF.pine
// A strategy using Nadaraya-Watson Envelope, RSI, and ATR Stop Loss Finder indicators
// The strategy has been explained in this video: https://youtu.be/Olb47nBRSSo
// © 2023 Geraked, Rabist
// Licensed under MIT

// Backtesting result:
//      Symbol:             USDJPY
//      Timeframe:          15 MIN
//      Range:              2023-08-15 — 2023-10-20
//      Percent Profitable: 50.52%
//      Total Trades:       97
//      Profit Factor:      1.327

//@version=5
strategy("Nadaraya-Watson Envelope, RSI, and ATR Stop Loss Finder Strategy", "NWERSIASF", default_qty_type=strategy.percent_of_equity, overlay=true, currency=currency.USD, max_lines_count=500, max_labels_count=500, max_bars_back=500)

tpCoef = input.float(1.5, "TP Coef", group="Strategy")
reverse = input.bool(false, "Reverse Signal", group="Strategy")

// Nadaraya-Watson Envelope
h = input.float(8.0,'Bandwidth', minval = 0, group = "NWE")
mult = input.float(3.0, minval = 0, group = "NWE")
repaint = input(false, 'Repainting Smoothing', tooltip = 'Repainting is an effect where the indicators historical output is subject to change over time. Disabling repainting will cause the indicator to output the endpoints of the calculations', group = "NWE")

gauss(x, h) => math.exp(-(math.pow(x, 2)/(h * h * 2)))

// Append lines
n = bar_index
var ln = array.new_line(0)
if barstate.isfirst and repaint
    for i = 0 to 499
        array.push(ln,line.new(na,na,na,na))

// End point method
var coefs = array.new_float(0)
var den = 0.

if barstate.isfirst and not repaint
    for i = 0 to 499
        w = gauss(i, h)
        coefs.push(w)
    den := coefs.sum()

out = 0.
if not repaint
    for i = 0 to 499
        out += close[i] * coefs.get(i)
out /= den
mae = ta.sma(math.abs(close - out), 499) * mult

upper = out + mae
lower = out - mae

plot(repaint ? na : upper, 'Upper', color = color.yellow)
plot(repaint ? na : lower, 'Lower', color = color.yellow)

// Compute and display NWE
float y2 = na
float y1 = na

nwe = array.new<float>(0)
if barstate.islast and repaint
    sae = 0.

    //Compute and set NWE point
    for i = 0 to math.min(499,n - 1)
        sum = 0.
        sumw = 0.

        //Compute weighted mean
        for j = 0 to math.min(499,n - 1)
            w = gauss(i - j, h)
            sum += close[j] * w
            sumw += w

        y2 := sum / sumw
        sae += math.abs(close[i] - y2)
        nwe.push(y2)

    sae := sae / math.min(499,n - 1) * mult
    for i = 0 to math.min(499,n - 1)
        if i % 2 != 0
            line.new(n-i+1, y1 + sae, n-i, nwe.get(i) + sae, color = color.yellow)
            line.new(n-i+1, y1 - sae, n-i, nwe.get(i) - sae, color = color.yellow)
        y1 := nwe.get(i)


// RSI
rsiLength = input.int(5, "Length", minval=1, group = "RSI")
up = ta.rma(math.max(ta.change(close), 0), rsiLength)
down = ta.rma(-math.min(ta.change(close), 0), rsiLength)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))


// Average True Range Stop Loss Finder
length = input.int(title='Length', defval=14, minval=1, group = "ASF")
smoothing = input.string(title='Smoothing', defval='SMA', options=['RMA', 'SMA', 'EMA', 'WMA'], group = "ASF")
m = input(0.5, 'Multiplier', group = "ASF")

ma_function(source, length) =>
    if smoothing == 'RMA'
        ta.rma(source, length)
    else
        if smoothing == 'SMA'
            ta.sma(source, length)
        else
            if smoothing == 'EMA'
                ta.ema(source, length)
            else
                ta.wma(source, length)

shortSl = ma_function(ta.tr(true), length) * m + high
longSl = low - ma_function(ta.tr(true), length) * m

plot(shortSl, title='ATR Short Stop Loss', color=color.blue)
plot(longSl, title='ATR Long Stop Loss', color=color.blue)


// Strategy
long = low[1] < lower[1] and close > open and close < lower + 0.5 * (upper - lower) and rsi[1] < 30
short = high[1] > upper[1] and close < open and close > upper - 0.5 * (upper - lower) and rsi[1] > 70
var cnt = 1

if long
    inn = close
    longTp = inn + tpCoef * (inn - longSl)
    if not reverse
        id = "long " + str.tostring(cnt)
        strategy.entry(id, strategy.long)
        strategy.exit("exitLong " + str.tostring(cnt), id, stop=longSl, limit=longTp)
    else
        id = "short " + str.tostring(cnt)
        strategy.entry(id, strategy.short)
        strategy.exit("exitShort " + str.tostring(cnt), id, stop=longTp, limit=longSl)
    cnt += 1

if short
    inn = close
    shortTp = inn - tpCoef * (shortSl - inn)
    if not reverse
        id = "short " + str.tostring(cnt)
        strategy.entry(id, strategy.short)
        strategy.exit("exitShort " + str.tostring(cnt), id, stop=shortSl, limit=shortTp)
    else
        id = "long " + str.tostring(cnt)
        strategy.entry(id, strategy.long)
        strategy.exit("exitLong " + str.tostring(cnt), id, stop=shortTp, limit=shortSl)
    cnt += 1

Overview

With repainting off, it plots yellow upper and lower bands from a Gaussian endpoint estimate; with repainting on, it redraws the envelope on the last bar. Bandwidth, band multiplier, RSI length, ATR length, smoothing type, and ATR multiplier are adjustable. A take-profit coefficient and reverse-signal switch are strategy inputs. The excerpt ends before the order code, so entries, exits, and stop placement are not shown.

Details

Published by

geraked on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum, Volatility & bands

Markets

Forex

Timeframes

M15-H1

Risk Notes

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

Topics

backtesting-trading-strategiesexpert-advisorexpert-advisorsforex-botgerakedmetatraderpinescriptrabiststock-markettrading-algorithms

Settings

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

SettingTypeDefaultVariable
TP Coeffloat1.5tpCoef
Reverse Signalboolfalsereverse
Bandwidthfloat8.0h
multfloat3.0mult
Repainting Smoothingboolfalserepaint
Lengthint5rsiLength
Lengthint14length
SmoothingstringSMAsmoothing
Multiplierfloat0.5m
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

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]
106 stars

This strategy identifies trend-following entries using a triple exponential moving average alignment and ATR-based exits on the main price chart. Long signals trigger when the fast EMA is above the medium EMA and medium is above slow, accompanied by a close ab

Strategy v4 Moving averagesVolatility & bands Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of 3 EMA + Stochastic RSI + ATR
105 stars

This overlay strategy looks for gold scalps from break of structure and change of character. It enters long when a bullish break, a bullish character change, and an optional volume filter align, and short on the opposite set. Optional RSI levels can block trad

Strategy v6 SMC / ICT / price actionOscillators & momentum Repaints

Take Profits & Stop Losses

by PythonForForex
64 stars

This educational strategy demonstrates moving average crossovers filtered by RSI momentum, incorporating ATR-based risk management. It calculates a 10-period SMA, a 30-period SMA, a 14-period RSI, and a 14-period ATR. Long entries trigger when the fast SMA cro

Strategy v5 Moving averagesOscillators & momentum
Updated 4 years ago · None stated GitHub repository of Take Profits & Stop Losses

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL
57 stars

This strategy identifies trend reversals through market structure changes (CHoCH) filtered by MACD momentum. It initiates long positions on bullish structure breaks when MACD is positive and above its signal line, and short positions on bearish breaks when MAC

Strategy v6 SMC / ICT / price actionOscillators & momentum Repaints
Updated 1 year ago · Apache-2.0 GitHub repository of Market Structure MACD 4H + Trailing

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers