Nadaraya-Watson Envelope - Non Repaint[Sam4cok] for ThinkOrSwim

samer800

Conversion Expert
VIP
Lifetime
Aje7dqp.png


this is non repaint Nadaraya Watson Envelope. Not exact lux repaint indicator. try it! :)

CODE Update V3.0 -
# v3.0 Some code fixes, change on band style and added option for signal wait bar - 11/2022

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.
#// The non-repainting implementation of Nadaraya–Watson Regression using a Rational Quadratic Kernel is an original idea from @jdehorty i added the upper band an lower band using ATR, with this
#// we get an aproximation of Nadaraya-Watson Envelope
#indicator('Nadaraya-Watson non repainting', overlay=true, timeframe="")
# Converted and mod by Sam4Cok@Samer800 - 10/2022
# v2.0 Add 2 methods of calculating NW. Both non repating.
# v2.5 Added super NW. All calc typs are non repating - 11 / 2022.
# v3.0 Some code fixes, change on band style and added option for signal wait bar - 11/2022
input ShowBubble = yes;
input ShowBandLines = yes;
input ShowCloud  = yes;
input src = close;
input SmaplePeriod = 50;
input NadarayaType = {default Quadratic, Lux, Super};
input SignalStyle  = {Default Bubbles, Arrows, None};
input LookbackWindow = 8;      # The number of bars used for the estimation. Recommended range: 3-50
input RelativeWeighting = 8.0; # Relative weighting of time frames. Recommended Range: 0.25-25
input RegressionStartBar = 25; # Bar index on which to start regression. Recommended range: 5-25
input ColorLag = 1;            # This often results in less color transitions overall.
input SignalLag = 3;           # Lag for crossover detection. Lower values result in earlier crossovers.
input AtrPeriod = 60;          # ATR Period
input MultiForNearBand = 1.5;  # Multiplier for near band.
input MultiForFarBand  = 7.0;  # Multiplier for far band.
input smoothing = no;
input smoothLength = 3;

def na = Double.NaN;
def h = high;
def l = low;
def CalcType = if NadarayaType==NadarayaType.Quadratic then 1 else
               if NadarayaType==NadarayaType.Lux then 2 else 0;
def CalcPeriod = min(SmaplePeriod + 500, 750);
def Sample     = min(SmaplePeriod, 500);
def size = if CalcType==0 then sample else CalcPeriod;
def style= if SignalStyle.Bubbles then 1 else
           if SignalStyle.Arrows then -1 else 0;
#kernel_atr(length, _high, _low, _close) =>
script kernel_atr {
  input length = 60;
  input _high = high;
  input _low = low;
  input _close = close;
    def tr = if isNaN(_high[1]) then _high - _low else TrueRange(_high,_close,_low);
    plot kATR = WildersAverage(tr, length);
}
#-- counter
script counter {
    input length = 500;
    input Bandwidth = 8;
    def counter = fold i = 0 to length - 1 with p do
              p +  Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
    plot result = counter;
}
#super(src, len) =>
script super {
input src = close;
input len = 50;
    def f = (1.414 * Double.Pi)/len;
    def a = exp(-f);
    def c2 = 2 * a * cos(f);
    def c3 = -a * a;
    def c1 = 1 - c2 - c3;
    def smooth;
    smooth = c1 * (src+src[1]) * 0.5 + c2 * (smooth[1]) + c3 * (smooth[2]);
plot return = smooth;
}
#kernel_regression1(_src, _size, LookbackWindow, RegressionStartBar, RelativeWeighting) =>
script kernel {
   input _src = close;
   input _size = 500;
   input _h = 8;
   input x_0 = 2;
   input r = 8;
    def _currentWeight;
    def _cumulativeWeight;
    _currentWeight = fold i = 0 to _size + x_0 with p do
        p + GetValue(_src, i) * Power(1 + (Power(i, 2) / ((Power(_h, 2) * 2 * r))), -r);
    _cumulativeWeight = fold j = 0 to  _size + x_0 with q do
        q + Power(1 + (Power(j, 2) / ((Power(_h, 2) * 2 * r))), -r);
    plot currentWeight = _currentWeight / _cumulativeWeight;
}
script Lux {
    input src = close;
    input size = 500;
    input LookbackWindow = 8;
        def sum;
        def sumw;
        def y2;
        def Bandwidth = LookbackWindow;
        sum  = fold j = 0 to size-1 with p do
           p +  src[j] *  Exp(-(Power(counter(size, Bandwidth)-j,2)/(Bandwidth*Bandwidth*2)));
        sumw = fold k = 0 to size-1 with q do
           q + Exp(-(Power(counter(size,Bandwidth)-k,2)/(Bandwidth*Bandwidth*2)));
        y2 = sum/sumw;
    plot YNW = y2;
}
# //----Type 1 Calc
def kerSrc1 = kernel(src, size, LookbackWindow, RegressionStartBar, RelativeWeighting);
def kerHi1 = kernel(h, size, LookbackWindow, RegressionStartBar, RelativeWeighting);
def kerLo1 = kernel(l, size, LookbackWindow, RegressionStartBar, RelativeWeighting);
def nwHigh1 = if !Smoothing then kerHi1 else WMA(kerHi1, smoothLength);
def nwLow1  = if !Smoothing then kerLo1 else WMA(kerLo1, smoothLength);
def nwSrc1  = if !Smoothing then kerSrc1 else WMA(kerSrc1, smoothLength);;
# //--- Type 2 Calc
def luxSrc2  = Lux(src, size, LookbackWindow);
def luxHigh2 = Lux(h,size, LookbackWindow);
def luxLow2  = Lux(l,size, LookbackWindow);
def nwHigh2  = if !Smoothing then luxHigh2 else WMA(luxHigh2,smoothLength);
def nwLow2   = if !Smoothing then luxLow2 else WMA(luxLow2,smoothLength);
def nwSrc2   = if !Smoothing then luxSrc2 else WMA(luxSrc2,smoothLength);
# //------Type3 Calc
def SupHi3 = super(h, size);
def SupLo3 = super(l, size);
def SupSrc3 = super(src, size);
def nwHigh3 = if !Smoothing then SupHi3 else WMA(SupHi3, smoothLength);
def nwLow3  = if !Smoothing then SupLo3 else WMA(SupLo3, smoothLength);
def nwSrc3  = if !Smoothing then SupSrc3 else WMA(SupSrc3, smoothLength);

#// Plot
def KernelHi = if CalcType == 1 then nwHigh1 else
               if CalcType == 2 then nwHigh2 else nwHigh3;    # Nadaraya-Watson Estimate - High
def KernelLo = if CalcType == 1 then nwLow1 else
               if CalcType == 2 then nwLow2 else nwLow3;      # Nadaraya-Watson Estimate - Low
def KernelEst =if CalcType == 1 then nwSrc1 else
               if CalcType == 2 then nwSrc2 else nwSrc3;     # Nadaraya-Watson Estimate - src
#// Trend

def isBullish = KernelEst > KernelEst[1];
def isBearish = KernelEst < KernelEst[1];
def isBullishCount = if isBullish then isBullishCount[1] + 1 else 0;
def isBearishCount = if isBearish then isBearishCount[1] + 1 else 0;
def isBullishCross = isBullishCount>=ColorLag;
def isBearishCross = isBearishCount>=ColorLag;

def plotColor = if isBullish then isBullishCross else
                if isBearish then isBearishCross else 0;
#--- Plots
plot nwEst = KernelEst;
nwEst.AssignValueColor(if plotColor==isBullishCross then CreateColor(0, 255, 255) else
                       if plotColor==isBearishCross then CreateColor(255, 0, 255) else Color.GRAY);
nwEst.SetLineWeight(2);

#--- Band Cals
def nATR = kernel_atr(AtrPeriod, KernelHi, KernelLo, KernelEst);
  def _upper_far  = KernelEst + MultiForFarBand * natr;
  def _upper_near = KernelEst + MultiForNearBand  * natr;
  def _lower_near = KernelEst - MultiForNearBand  * natr;
  def _lower_far  = KernelEst - MultiForFarBand * natr;
  def _upper_avg = (_upper_far + _upper_near) / 2;
  def _lower_avg = (_lower_far + _lower_near) / 2;

plot upNear = _upper_near;
plot upMid  = _upper_avg;
plot upFar  = _upper_far;
plot loNear = _lower_near;
plot loMid  = _lower_avg;
plot loFar  = _lower_far;

upNear.SetHiding(!ShowBandLines);
upMid.SetHiding(!ShowBandLines);
upFar.SetHiding(!ShowBandLines);
loNear.SetHiding(!ShowBandLines);
loMid.SetHiding(!ShowBandLines);
loFar.SetHiding(!ShowBandLines);
upNear.SetDefaultColor(CreateColor(94,0,0));
upMid.SetDefaultColor(CreateColor(94,0,0));
upFar.SetDefaultColor(CreateColor(94,0,0));
loNear.SetDefaultColor(CreateColor(1,31,20));
loMid.SetDefaultColor(CreateColor(1,31,20));
loFar.SetDefaultColor(CreateColor(1,31,20));

#----- Signal
def SigU = src > loMid;
def SigD = src < upMid;
def SigUCount = if SigU then SigUCount[1] + 1 else 0;
def SigDCount = if SigD then SigDCount[1] + 1 else 0;
def SigUp = SigU and SigUCount== SignalLag;
def SigDn = SigD and SigDCount== SignalLag;

plot ArrowUp = if (SigUp and style<0) then l else na;
plot ArrowDn = if (SigDn and style<0) then h else na;
ArrowUp.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
ArrowDn.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);


#------ CLOUD---
AddCloud(if ShowCloud then upFar else na, upMid, CreateColor(94,0,0));
AddCloud(if ShowCloud then upFar else na, upNear,CreateColor(94,0,0));

AddCloud(if ShowCloud then loMid else na, loFar, CreateColor(1,31,20));
AddCloud(if ShowCloud then loNear else na, loFar,CreateColor(1,31,20));

#------ Bubbles
AddChartBubble(style>0 and SigUp, l, "B", CreateColor(0, 255, 255), no);
AddChartBubble(style>0 and SigDn, h, "S", CreateColor(255, 0, 255), yes);

#---- END
CODE:

CSS:
# Not typical converstion of "Nadaraya-Watson Envelope [LUX]"
# #'Nadaraya-Watson Non with non Repaint option'
# Mod by Sam4cok@samer800 - 09/2022

input ShowBand = yes;
input ShowSignal = yes;
input ShowBubble = yes;
input length = 500;
input Bandwidth = 8.0;    # 'Bandwidth'
input src = hlc3;
input lag = yes;
input mult = 2.7;         # "Multiplier"
input smooth = no;
input smoothLength = 3;

def na = Double.NaN;

script counter {
    input length = 500;
    input Bandwidth = 8;
    def counter = fold i = 0 to length - 1 with p do
              p +  Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
    plot result = counter;
}
def sum;
def mae;
def sumw;
def sum_e;
def y2;

    sum  = fold j = 0 to length-1 with p do
           p +  src[j] *  Exp(-(Power(if lag then counter(length, Bandwidth)-j else
                j,2)/(Bandwidth*Bandwidth*2)));

    sumw = fold k = 0 to length-1 with q do
           q + Exp(-(Power(if lag then counter(length,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

    y2 = if smooth then Average(sum/sumw, smoothLength) else (sum/sumw);

    sum_e = fold i = 0 to length-1 with r do
                r + absValue(src[i] - y2[i]);

    mae = if smooth then Average(sum_e/length*mult, smoothLength) else sum_e / length*mult;

    def mcol = if y2>y2[1] and y2[1]>y2[2] then 1 else 0;

    def SMAUp = y2 + mae;# "Upper"
    def SMALo = y2 - mae;# "Lower"

    plot middle = y2;    # "Midle"

    middle.AssignValueColor( if mcol then CreateColor(33, 150, 243) else CreateColor(255, 152, 0));
    middle.SetLineWeight(2);

addcloud(if ShowBand then SMAUp else na,middle, Color.DARK_GREEN, Color.DARK_RED, yes);
addcloud(if ShowBand then middle else na, SMALo, Color.DARK_RED, Color.DARK_RED, yes);
#---------------------------------------------
    def up = If(src crosses above y2 and  mcol and src[1]>open[1], middle, na);
    def dn = If(src crosses below y2 and !mcol and src[1]<open[1], middle, na);

    plot SigUp = up;
         SigUp.SetHiding(!ShowSignal);
    plot SigDn = dn;
         SigDn.SetHiding(!ShowSignal);
    SigUp.SetLineWeight(3);
    SigDn.SetLineWeight(3);
    SigUp.SetDefaultColor(Color.GREEN);
    SigDn.SetDefaultColor(Color.MAGENTA);
    SigUp.SetPaintingStrategy(PaintingStrategy.POINTS);
    SigDn.SetPaintingStrategy(PaintingStrategy.POINTS);

    plot bandUp = if src>SMALo and src[1]<SMALo then low else na;
    plot bandDn = if src<SMAUp and src[1]>SMAUp then high else na;

AddChartBubble(ShowBubble and bandUp, bandUp, "B", Color.GREEN, no);
AddChartBubble(ShowBubble and bandDn, bandDn, "S", Color.RED, yes);

#### END

V 2.0

Nadaraya-Watson Envelope - Non Repaint​

added 2 type of NW calculation methods to select from. Type1 based on ATR band the other one based on LUX modified code.
mDWtfSX.png

Updated Code:
CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.
#// © Lupown
#// The non-repainting implementation of Nadaraya–Watson Regression using a Rational Quadratic Kernel is an original idea from @jdehorty i added the upper band an lower band using ATR, with this
#// we get an aproximation of Nadaraya-Watson Envelope
#indicator('Nadaraya-Watson non repainting', overlay=true, timeframe="")
# Converted and mod by Sam4Cok@Samer800 - 10/2022
# v2.0 Add 2 methods of calculating NW. Both non repating.
input ShowBubble = yes;
input ShowBand   = yes;
input ShowCloud  = no;
input src = close;#, 'Source')
input NadarayaType = {default Type1, Type2};
input LookbackWindow = 8; # The number of bars used for the estimation. Recommended range: 3-50
input RelativeWeighting = 8.0;# Relative weighting of time frames. Recommended Range: 0.25-25
input RegressionStartBar = 25;# Bar index on which to start regression. Recommended range: 5-25
input smoothColors = no; # This often results in less color transitions overall.
input lag = 2;# "Lag for crossover detection. Lower values result in earlier crossovers.
input AtrPeriod = 32;#, "ATR Period")
input Multiplier = 2.7;#,"Multiplier")
input smoothing = no;
input smoothLength = 3;

def na = Double.NaN;
def size = if !IsNaN(close[1]) then size[1] + 1 else size[1];

script counter {
    input length = 500;
    input Bandwidth = 8;
    def counter = fold i = 0 to length - 1 with p do
              p +  Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
    plot result = counter;
}
def o = open;
def h = high;
def l = low;

#kernel_regression1(_src, _size, LookbackWindow, RegressionStartBar, RelativeWeighting) =>
script kernel_regression1 {
    input _src = close;
    input _size = 500;
    input _h = 8;
    input x_0 = 2;
    input r = 8;
    def _currentWeight;
    def _cumulativeWeight;
    _currentWeight = fold i = 0 to _size + x_0 with p do
        p + GetValue(_src, i) * Power(1 + (Power(i, 2) / ((Power(_h, 2) * 2 * r))), -r);
    _cumulativeWeight = fold j = 0 to  _size + x_0 with q do
        q + Power(1 + (Power(j, 2) / ((Power(_h, 2) * 2 * r))), -r);
    plot currentWeight = _currentWeight;
    plot cumulativeWeight = _cumulativeWeight;
}
def sum;
def mae;
def sumw;
def sum_e;
def y2;
def length = 500;
def Bandwidth = LookbackWindow;
    sum  = fold j = 0 to length-1 with p do
           p +  src[j] *  Exp(-(Power(if lag then counter(length, Bandwidth)-j else
                j,2)/(Bandwidth*Bandwidth*2)));

    sumw = fold k = 0 to length-1 with q do
           q + Exp(-(Power(if lag then counter(length,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

    y2 = if smoothing then Average(sum/sumw, smoothLength) else (sum/sumw);

    sum_e = fold i = 0 to length-1 with r do
                r + absValue(src[i] - y2[i]);

    mae = if smoothing then Average(sum_e/length*Multiplier, smoothLength) else sum_e / length*Multiplier;

#def mcol = if y2 > y2[1] and y2[1] > y2[2] then 1 else 0;

def currentWeight1 = kernel_regression1(src, size, LookbackWindow, RegressionStartBar, RelativeWeighting).currentWeight;
def cumulativeWeight1 = kernel_regression1(src, size, LookbackWindow, RegressionStartBar, RelativeWeighting).cumulativeWeight;
def currentWeight2 = kernel_regression1(src, size, LookbackWindow - lag, RegressionStartBar, RelativeWeighting).currentWeight;
def cumulativeWeight2 = kernel_regression1(src, size, LookbackWindow - lag, RegressionStartBar, RelativeWeighting).cumulativeWeight;

def yhat1 = currentWeight1 / cumulativeWeight1;
def yhat2 = currentWeight2 / cumulativeWeight2;

#// Rates of Change
def wasBearish = yhat1[2] > yhat1[1];
def wasBullish = yhat1[2] < yhat1[1];
def isBearish  = yhat1[1] > yhat1;
def isBullish  = yhat1[1] < yhat1;
def isBearishChange = isBearish and wasBullish;
def isBullishChange = isBullish and wasBearish;

#// Crossovers
def isBullishCross = Crosses(yhat2, yhat1, CrossingDirection.ABOVE);
def isBearishCross = Crosses(yhat2, yhat1, CrossingDirection.BELOW);
def isBullishSmooth = yhat2 > yhat1;
def isBearishSmooth = yhat2 < yhat1;

#// Colors
def colorByCross = if isBullishSmooth then 1 else 0;
def colorByRate = if isBullish then 1 else 0;
def plotColor = if NadarayaType == NadarayaType.Type1 then
                if smoothColors then colorByCross else colorByRate else
                if y2 > y2[1] and y2[1] > y2[2] then 1 else 0;

#// Plot
def KernelEst = if NadarayaType == NadarayaType.Type1 then
            If(smoothing, WMA(yhat1, smoothLength), yhat1) else y2;# "Rational Quadratic Kernel Estimate"
plot RQKernelEst = KernelEst;
RQKernelEst.AssignValueColor(if plotColor then CreateColor(0, 255, 255) else CreateColor(255, 0, 255));
RQKernelEst.SetLineWeight(2);

def upperBand = if NadarayaType == NadarayaType.Type1 then
                RQKernelEst + Multiplier * ATR(AtrPeriod) else y2 + mae;
def lowerBand = if NadarayaType == NadarayaType.Type1 then
                RQKernelEst - Multiplier * ATR(AtrPeriod) else y2 - mae;

plot upperje = if ShowBand then upperBand else na;    # "Rational Quadratic Kernel Upper"
plot lowerje = if ShowBand then lowerBand else na;    # "Rational Quadratic Kernel Lower"
upperje.SetDefaultColor(CreateColor(0, 255, 255));
lowerje.SetDefaultColor(CreateColor(255, 0, 255));

#/plot(yhat1 + multi, "Rational Quadratic Kernel Estimate", color=color.silver, linewidth=2)
def SigUp = Crosses(close, lowerBand, CrossingDirection.ABOVE);#,char = "🥀", location = location.abovebar)
def SigDn = Crosses(close, upperBand, CrossingDirection.BELOW);#,char = "🍀",location = location.belowbar)

#------ CLOUD---
AddCloud(if ShowCloud then upperBand else na, RQKernelEst, CreateColor(4, 103, 117));
AddCloud(if ShowCloud then RQKernelEst else na, lowerBand, CreateColor(100, 2, 117));

#------ Bubbles
AddChartBubble(ShowBubble and SigUp, low, "B", CreateColor(0, 255, 255), no);
AddChartBubble(ShowBubble and SigDn, high, "S", CreateColor(255, 0, 255), yes);

#### END

Update - V2.5
added super Nadaraya calc method. You can try all options from the same code below.

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.
#// The non-repainting implementation of Nadaraya–Watson Regression using a Rational Quadratic Kernel is an original idea from @jdehorty i added the upper band an lower band using ATR, with this
#// we get an aproximation of Nadaraya-Watson Envelope
#indicator('Nadaraya-Watson non repainting', overlay=true, timeframe="")
# Converted and mod by Sam4Cok@Samer800 - 10/2022
# v2.0 Add 2 methods of calculating NW. Both non repating.
# v2.5 added super NW. All calc typs are non repating - 11 / 2022.
input ShowBubble = yes;
input ShowBand   = yes;
input ShowCloud  = no;
input SmaplePeriod = 50;
input src = close;#, 'Source')
input NadarayaType = {Quadratic, Lux,default Super};
input LookbackWindow = 8; # The number of bars used for the estimation. Recommended range: 3-50
input RelativeWeighting = 8.0;# Relative weighting of time frames. Recommended Range: 0.25-25
input RegressionStartBar = 25;# Bar index on which to start regression. Recommended range: 5-25
input smoothColors = no; # This often results in less color transitions overall.
input lag = 2;# "Lag for crossover detection. Lower values result in earlier crossovers.
input AtrPeriod = 32;#, "ATR Period")
input Multiplier = 2.7;#,"Multiplier")
input smoothing = no;
input smoothLength = 3;

def na = Double.NaN;
def o = open;
def h = high;
def l = low;
def c = close;
def CalcType = if NadarayaType==NadarayaType.Quadratic then 1 else
               if NadarayaType==NadarayaType.Lux then 2 else 0;
def CalcPeriod = min(SmaplePeriod + 500, 750);
def size = CalcPeriod;
script counter {
    input length = 500;
    input Bandwidth = 8;
    def counter = fold i = 0 to length - 1 with p do
              p +  Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
    plot result = counter;
}
#super(src, len) =>
script super {
input src = close;
input len = 50;
    def f = (1.414 * Double.Pi)/len;
    def a = exp(-f);
    def c2 = 2 * a * cos(f);
    def c3 = -a*a;
    def c1 = 1-c2-c3;
    def smooth;;
    smooth = c1 * (src+src[1]) * 0.5 + c2 * (smooth[1]) + c3 * (smooth[2]);
plot return = smooth;
}
#kernel_regression1(_src, _size, LookbackWindow, RegressionStartBar, RelativeWeighting) =>
script kernel {
    input _src = close;
    input _size = 500;
    input _h = 8;
    input x_0 = 2;
    input r = 8;
    def _currentWeight;
    def _cumulativeWeight;
    _currentWeight = fold i = 0 to _size + x_0 with p do
        p + GetValue(_src, i) * Power(1 + (Power(i, 2) / ((Power(_h, 2) * 2 * r))), -r);
    _cumulativeWeight = fold j = 0 to  _size + x_0 with q do
        q + Power(1 + (Power(j, 2) / ((Power(_h, 2) * 2 * r))), -r);
    plot currentWeight = _currentWeight;
    plot cumulativeWeight = _cumulativeWeight;
}
# //----Type 1 Calc

def currentWeight1 = kernel(src, size, LookbackWindow, RegressionStartBar, RelativeWeighting).currentWeight;
def cumulativeWeight1 = kernel(src, size, LookbackWindow, RegressionStartBar, RelativeWeighting).cumulativeWeight;
def currentWeight2 = kernel(src, size, LookbackWindow - lag, RegressionStartBar, RelativeWeighting).currentWeight;
def cumulativeWeight2 = kernel(src, size, LookbackWindow - lag, RegressionStartBar, RelativeWeighting).cumulativeWeight;
def yha1 = currentWeight1 / cumulativeWeight1;
def yha2 = currentWeight2 / cumulativeWeight2;

def yhat1 = if Smoothing then WMA(yha1, smoothLength) else yha1;
def yhat2 = if Smoothing then WMA(yha2, smoothLength) else yha2;
#// Rates of Change
def wasBearish = yhat1[2] > yhat1[1];
def wasBullish = yhat1[2] < yhat1[1];
def isBearish  = yhat1[1] > yhat1;
def isBullish  = yhat1[1] < yhat1;
def isBearishChange = isBearish and wasBullish;
def isBullishChange = isBullish and wasBearish;
#// Crossovers
def isBullishCross = Crosses(yhat2, yhat1, CrossingDirection.ABOVE);
def isBearishCross = Crosses(yhat2, yhat1, CrossingDirection.BELOW);
def isBullishSmooth = yhat2 > yhat1;
def isBearishSmooth = yhat2 < yhat1;
# //--- Type 2 Calc
def sum;
def mae;
def sumw;
def sum_e;
def y2;
def Bandwidth = LookbackWindow;
    sum  = fold j = 0 to size-1 with p do
           p +  src[j] *  Exp(-(Power(if lag then counter(size, Bandwidth)-j else
                j,2)/(Bandwidth*Bandwidth*2)));

    sumw = fold k = 0 to size-1 with q do
           q + Exp(-(Power(if lag then counter(size,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

    y2 = if smoothing then Average(sum/sumw, smoothLength) else (sum/sumw);

    sum_e = fold i = 0 to size-1 with r do
                r + absValue(src[i] - y2[i]);

    mae = if smoothing then WMA(sum_e/size*Multiplier, smoothLength) else sum_e / size*Multiplier;

# //------Type3 Calc
def Sample = min(SmaplePeriod, 1000);
def SuperHi = super(h, Sample);
def SuperLo = super(l, Sample);
def Dev = (SuperHi - SuperLo) / 2 * Multiplier;
def d = SuperLo + (SuperHi - SuperLo)/2;
def Mid = if smoothing then WMA(d, smoothLength) else d;

#// Colors
def plotColor = if CalcType == 1 then
                if smoothColors then isBullishSmooth else isBullish else
                if CalcType == 2 then if y2 > y2[1] and y2[1] > y2[2] then 1 else 0 else
                if Mid>Mid[1] then 1 else 0;

#// Plot
def KernelEst = if CalcType == 1 then yhat1 else
                if CalcType == 2 then y2 else Mid;# "Rational Quadratic Kernel Estimate"
plot RQKernelEst = KernelEst;
RQKernelEst.AssignValueColor(if plotColor then CreateColor(0, 255, 255) else CreateColor(255, 0, 255));
RQKernelEst.SetLineWeight(2);

def upperBand = if CalcType == 1 then
                RQKernelEst + Multiplier * ATR(AtrPeriod) else
                if CalcType == 2 then y2 + mae else SuperHi + dev;
def lowerBand = if CalcType == 1 then
                RQKernelEst - Multiplier * ATR(AtrPeriod) else
                if CalcType == 2 then y2 - mae else SuperLo - dev;

plot upperje = if ShowBand then upperBand else na;    # "Rational Quadratic Kernel Upper"
plot lowerje = if ShowBand then lowerBand else na;    # "Rational Quadratic Kernel Lower"
upperje.SetDefaultColor(CreateColor(0, 255, 255));
lowerje.SetDefaultColor(CreateColor(255, 0, 255));

#/plot(yhat1 + multi, "Rational Quadratic Kernel Estimate", color=color.silver, linewidth=2)
def SigU = Crosses(c, lowerBand, CrossingDirection.ABOVE);#,char = "?", location = location.abovebar)
def SigD = Crosses(c, upperBand, CrossingDirection.BELOW);#,char = "?",location = location.belowbar)
def SigUCount = if SigU then 1 else SigUCount[1] + 1;
def SigDCount = if SigD then 1 else SigDCount[1] + 1;
def SigUp = SigU and SigUCount[1]> 5;
def SigDn = SigD and SigDCount[1]> 5;
#------ CLOUD---
AddCloud(if ShowCloud then upperBand else na, RQKernelEst, CreateColor(4, 103, 117));
AddCloud(if ShowCloud then RQKernelEst else na, lowerBand, CreateColor(100, 2, 117));

#------ Bubbles
AddChartBubble(ShowBubble and SigUp, l, "B", CreateColor(0, 255, 255), no);
AddChartBubble(ShowBubble and SigDn, h, "S", CreateColor(255, 0, 255), yes);

#### END
 
Last edited:
https://usethinkscript.com/threads/convert-tradingview-nadaraya-watson-envelope.10415/post-107992
@samer800 was kind enough to convert a Nadarya Watson Envelope by Lux from trading view to ToS. his conversion does not repaint, unlike LuxAlgo's. I really love the indicator, especially for the unpinning reason and many more.
Works very well on intraday trades.


However, with the background of this indicator shaded, its tough to layer anything in the upper along with it.
Could anyone help edit the script so that they're just lines with out a green/red background?


thank you!


# Not typical converstion of "Nadaraya-Watson Envelope [LUX]"
# #'Nadaraya-Watson Non with non Repaint option'
# Mod by Sam4cok@samer800 - 09/2022

input ShowBand = yes;
input ShowSignal = yes;
input ShowBubble = yes;
input length = 500;
input Bandwidth = 8.0; # 'Bandwidth'
input src = hlc3;
input lag = yes;
input mult = 2.7; # "Multiplier"
input smooth = no;
input smoothLength = 3;

def na = Double.NaN;

script counter {
input length = 500;
input Bandwidth = 8;
def counter = fold i = 0 to length - 1 with p do
p + Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
plot result = counter;
}
def sum;
def mae;
def sumw;
def sum_e;
def y2;

sum = fold j = 0 to length-1 with p do
p + src[j] * Exp(-(Power(if lag then counter(length, Bandwidth)-j else
j,2)/(Bandwidth*Bandwidth*2)));

sumw = fold k = 0 to length-1 with q do
q + Exp(-(Power(if lag then counter(length,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

y2 = if smooth then Average(sum/sumw, smoothLength) else (sum/sumw);

sum_e = fold i = 0 to length-1 with r do
r + absValue(src - y2);

mae = if smooth then Average(sum_e/length*mult, smoothLength) else sum_e / length*mult;

def mcol = if y2>y2[1] and y2[1]>y2[2] then 1 else 0;

def SMAUp = y2 + mae;# "Upper"
def SMALo = y2 - mae;# "Lower"

plot middle = y2; # "Midle"

middle.AssignValueColor( if mcol then CreateColor(33, 150, 243) else CreateColor(255, 152, 0));
middle.SetLineWeight(2);

addcloud(if ShowBand then SMAUp else na,middle, Color.DARK_GREEN, Color.DARK_RED, yes);
addcloud(if ShowBand then middle else na, SMALo, Color.DARK_RED, Color.DARK_RED, yes);
#---------------------------------------------
def up = If(src crosses above y2 and mcol and src[1]>open[1], middle, na);
def dn = If(src crosses below y2 and !mcol and src[1]<open[1], middle, na);

plot SigUp = up;
SigUp.SetHiding(!ShowSignal);
plot SigDn = dn;
SigDn.SetHiding(!ShowSignal);
SigUp.SetLineWeight(3);
SigDn.SetLineWeight(3);
SigUp.SetDefaultColor(Color.GREEN);
SigDn.SetDefaultColor(Color.MAGENTA);
SigUp.SetPaintingStrategy(PaintingStrategy.POINTS);
SigDn.SetPaintingStrategy(PaintingStrategy.POINTS);

plot bandUp = if src>SMALo and src[1]<SMALo then low else na;
plot bandDn = if src<SMAUp and src[1]>SMAUp then high else na;

AddChartBubble(ShowBubble and bandUp, bandUp, "B", Color.GREEN, no);
AddChartBubble(ShowBubble and bandDn, bandDn, "S", Color.RED, yes);

#### END
 
https://usethinkscript.com/threads/convert-tradingview-nadaraya-watson-envelope.10415/post-107992
@samer800 was kind enough to convert a Nadarya Watson Envelope by Lux from trading view to ToS. his conversion does not repaint, unlike LuxAlgo's. I really love the indicator, especially for the unpinning reason and many more.
Works very well on intraday trades.


However, with the background of this indicator shaded, its tough to layer anything in the upper along with it.
Could anyone help edit the script so that they're just lines with out a green/red background?


thank you!


# Not typical converstion of "Nadaraya-Watson Envelope [LUX]"
# #'Nadaraya-Watson Non with non Repaint option'
# Mod by Sam4cok@samer800 - 09/2022

input ShowBand = yes;
input ShowSignal = yes;
input ShowBubble = yes;
input length = 500;
input Bandwidth = 8.0; # 'Bandwidth'
input src = hlc3;
input lag = yes;
input mult = 2.7; # "Multiplier"
input smooth = no;
input smoothLength = 3;

def na = Double.NaN;

script counter {
input length = 500;
input Bandwidth = 8;
def counter = fold i = 0 to length - 1 with p do
p + Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
plot result = counter;
}
def sum;
def mae;
def sumw;
def sum_e;
def y2;

sum = fold j = 0 to length-1 with p do
p + src[j] * Exp(-(Power(if lag then counter(length, Bandwidth)-j else
j,2)/(Bandwidth*Bandwidth*2)));

sumw = fold k = 0 to length-1 with q do
q + Exp(-(Power(if lag then counter(length,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

y2 = if smooth then Average(sum/sumw, smoothLength) else (sum/sumw);

sum_e = fold i = 0 to length-1 with r do
r + absValue(src - y2);

mae = if smooth then Average(sum_e/length*mult, smoothLength) else sum_e / length*mult;

def mcol = if y2>y2[1] and y2[1]>y2[2] then 1 else 0;

def SMAUp = y2 + mae;# "Upper"
def SMALo = y2 - mae;# "Lower"

plot middle = y2; # "Midle"

middle.AssignValueColor( if mcol then CreateColor(33, 150, 243) else CreateColor(255, 152, 0));
middle.SetLineWeight(2);

addcloud(if ShowBand then SMAUp else na,middle, Color.DARK_GREEN, Color.DARK_RED, yes);
addcloud(if ShowBand then middle else na, SMALo, Color.DARK_RED, Color.DARK_RED, yes);
#---------------------------------------------
def up = If(src crosses above y2 and mcol and src[1]>open[1], middle, na);
def dn = If(src crosses below y2 and !mcol and src[1]<open[1], middle, na);

plot SigUp = up;
SigUp.SetHiding(!ShowSignal);
plot SigDn = dn;
SigDn.SetHiding(!ShowSignal);
SigUp.SetLineWeight(3);
SigDn.SetLineWeight(3);
SigUp.SetDefaultColor(Color.GREEN);
SigDn.SetDefaultColor(Color.MAGENTA);
SigUp.SetPaintingStrategy(PaintingStrategy.POINTS);
SigDn.SetPaintingStrategy(PaintingStrategy.POINTS);

plot bandUp = if src>SMALo and src[1]<SMALo then low else na;
plot bandDn = if src<SMAUp and src[1]>SMAUp then high else na;

AddChartBubble(ShowBubble and bandUp, bandUp, "B", Color.GREEN, no);
AddChartBubble(ShowBubble and bandDn, bandDn, "S", Color.RED, yes);

#### END
Delete these lines of code
Code:
addcloud(if ShowBand then SMAUp else na,middle, Color.DARK_GREEN, Color.DARK_RED, yes);
addcloud(if ShowBand then middle else na, SMALo, Color.DARK_RED, Color.DARK_RED, yes);
 
I have been trying to make this change as well. Deleting the two lines of code does delete the cloud, but it also deletes the outer bands that are trying to be kept.
 
Delete these lines of code
Code:
addcloud(if ShowBand then SMAUp else na,middle, Color.DARK_GREEN, Color.DARK_RED, yes);
addcloud(if ShowBand then middle else na, SMALo, Color.DARK_RED, Color.DARK_RED, yes);
Replace “addcloud“ lines with the below


plot Upper = SMAUp;
plot Lower = SMALo;
 
I have been trying to make this change as well. Deleting the two lines of code does delete the cloud, but it also deletes the outer bands that are trying to be kept.
try this


CSS:
# Not typical converstion of "Nadaraya-Watson Envelope [LUX]"
# #'Nadaraya-Watson Non with non Repaint option'
# V1.1 Added option to enable/disable cloud and band lines.
# Mod by Sam4cok@samer800 - 09/2022

input BandLines = yes;
input ShowCloud = no;
input ShowSignal = yes;
input ShowBubble = yes;
input length = 500;
input Bandwidth = 8.0;    # 'Bandwidth'
input src = hlc3;
input lag = yes;
input mult = 2.7;         # "Multiplier"
input smooth = no;
input smoothLength = 3;

def na = Double.NaN;

script counter {
    input length = 500;
    input Bandwidth = 8;
    def counter = fold i = 0 to length - 1 with p do
              p +  Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
    plot result = counter;
}
def sum;
def mae;
def sumw;
def sum_e;
def y2;

    sum  = fold j = 0 to length-1 with p do
           p +  src[j] *  Exp(-(Power(if lag then counter(length, Bandwidth)-j else
                j,2)/(Bandwidth*Bandwidth*2)));

    sumw = fold k = 0 to length-1 with q do
           q + Exp(-(Power(if lag then counter(length,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

    y2 = if smooth then Average(sum/sumw, smoothLength) else (sum/sumw);

    sum_e = fold i = 0 to length-1 with r do
                r + absValue(src[i] - y2[i]);

    mae = if smooth then Average(sum_e/length*mult, smoothLength) else sum_e / length*mult;

    def mcol = if y2>y2[1] and y2[1]>y2[2] then 1 else 0;

    def SMAUp = y2 + mae;# "Upper"
    def SMALo = y2 - mae;# "Lower"

    plot UpperBand = SMAUp;
    plot LowerBand = SMALo;
    plot middle = y2;    # "Midle"
    UpperBand.SetHiding(!BandLines);
    LowerBand.SetHiding(!BandLines);
    UpperBand.SetDefaultColor(CreateColor(0,255,255));
    LowerBand.SetDefaultColor(CreateColor(255,0,255));
    LowerBand.SetHiding(!BandLines);
    middle.AssignValueColor( if mcol then CreateColor(0,255,255) else CreateColor(255,0,255));
    middle.SetLineWeight(2);

#---------------------------------------------
    def up = If(src crosses above y2 and  mcol and src[1]>open[1], middle, na);
    def dn = If(src crosses below y2 and !mcol and src[1]<open[1], middle, na);

    plot SigUp = up;
         SigUp.SetHiding(!ShowSignal);
    plot SigDn = dn;
         SigDn.SetHiding(!ShowSignal);
    SigUp.SetLineWeight(3);
    SigDn.SetLineWeight(3);
    SigUp.SetDefaultColor(Color.GREEN);
    SigDn.SetDefaultColor(Color.MAGENTA);
    SigUp.SetPaintingStrategy(PaintingStrategy.POINTS);
    SigDn.SetPaintingStrategy(PaintingStrategy.POINTS);

    plot bandUp = if src>SMALo and src[1]<SMALo then low else na;
    plot bandDn = if src<SMAUp and src[1]>SMAUp then high else na;

#------ CLOUD---
addcloud(if ShowCloud then SMAUp else na,middle, CreateColor(4,103,117));
addcloud(if ShowCloud then middle else na, SMALo,CreateColor(100,2,117));

#------ Bubbles
AddChartBubble(ShowBubble and bandUp, bandUp, "B", Color.GREEN, no);
AddChartBubble(ShowBubble and bandDn, bandDn, "S", Color.RED, yes);

#### END
 
I have been trying to make this change as well. Deleting the two lines of code does delete the cloud, but it also deletes the outer bands that are trying to be kept.
A friend of mine helped me modify it without the clouds.Here's the modified script



# Not typical converstion of "Nadaraya-Watson Envelope [LUX]"
# #'Nadaraya-Watson Non with non Repaint option'
# Mod by Sam4cok@samer800 - 09/2022

input ShowBand = yes;
input ShowSignal = yes;
input ShowBubble = yes;
input length = 500;
input Bandwidth = 8.0; # 'Bandwidth'
input src = hlc3;
input lag = yes;
input mult = 2.7; # "Multiplier"
input smooth = no;
input smoothLength = 3;

def na = Double.NaN;

script counter {
input length = 500;
input Bandwidth = 8;
def counter = fold i = 0 to length - 1 with p do
p + Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
plot result = counter;
}
def sum;
def mae;
def sumw;
def sum_e;
def y2;

sum = fold j = 0 to length-1 with p do
p + src[j] * Exp(-(Power(if lag then counter(length, Bandwidth)-j else
j,2)/(Bandwidth*Bandwidth*2)));

sumw = fold k = 0 to length-1 with q do
q + Exp(-(Power(if lag then counter(length,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

y2 = if smooth then Average(sum/sumw, smoothLength) else (sum/sumw);

sum_e = fold i = 0 to length-1 with r do
r + absValue(src - y2);

mae = if smooth then Average(sum_e/length*mult, smoothLength) else sum_e / length*mult;

def mcol = if y2>y2[1] and y2[1]>y2[2] then 1 else 0;

def SMAUp = y2 + mae;# "Upper"
def SMALo = y2 - mae;# "Lower"

plot middle = y2; # "Midle"

middle.AssignValueColor( if mcol then CreateColor(33, 150, 243) else CreateColor(255, 152, 0));
middle.SetLineWeight(2);

plot UpperBand = SMAup;
UpperBand.SetHiding(!ShowBand);
UpperBand.SetDefaultColor(Color.DARK_GREEN);
plot LowerBand = SMALo;
LowerBand.SetHiding(!ShowBand);
LowerBand.SetDefaultColor(Color.DARK_RED);
#addcloud(if ShowBand then SMAUp else na,middle, Color.DARK_GREEN, Color.DARK_RED, yes);
#addcloud(if ShowBand then middle else na, SMALo, Color.DARK_RED, Color.DARK_RED, yes);
#---------------------------------------------
def up = If(src crosses above y2 and mcol and src[1]>open[1], middle, na);
def dn = If(src crosses below y2 and !mcol and src[1]<open[1], middle, na);

plot SigUp = up;
SigUp.SetHiding(!ShowSignal);
plot SigDn = dn;
SigDn.SetHiding(!ShowSignal);
SigUp.SetLineWeight(3);
SigDn.SetLineWeight(3);
SigUp.SetDefaultColor(Color.GREEN);
SigDn.SetDefaultColor(Color.MAGENTA);
SigUp.SetPaintingStrategy(PaintingStrategy.POINTS);
SigDn.SetPaintingStrategy(PaintingStrategy.POINTS);

plot bandUp = if src>SMALo and src[1]<SMALo then low else na;
plot bandDn = if src<SMAUp and src[1]>SMAUp then high else na;

AddChartBubble(ShowBubble and bandUp, bandUp, "B", Color.GREEN, no);
AddChartBubble(ShowBubble and bandDn, bandDn, "S", Color.RED, yes);

#### END
 
This is a great indicator. Thanks for sharing! I added a little bit to the bottom of the script to make it useful on TOS mobile
Code:
input ShowArrows = yes;

#------ Arrows
plot buyArrow = ShowArrows and SigUp;
buyArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
buyArrow.setDefaultColor(Color.Green);

plot sellArrow =  ShowArrows and SigDn;
sellArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_Down);
sellArrow.setDefaultColor(Color.Red);
 
for the version 2.5 above, this line in the super{} script:
Code:
    smooth = c1 * (src+src[1]) * 0.5 + c2 * (smooth[1]) + c3 * (smooth[2]);

needs to account for NaNs in the series

Code:
    def smooth = c1 * (src + src[1]) * 0.5 + c2 * (if !isNan(smooth[1]) then smooth[1] else 0) + c3 * (if !isNan(smooth[2]) then smooth[2] else 0);

otherwise, it doesn't plot anything (for me at least)

-mashume
 
Does anyone happen to have a stock scan for the Nadaraya-Watson Envelope if it crosses either the bottom or top boundary?
 
Thanks a Ton @samer800 !! Awesome work. Wondering if you can help with a different one? Nadaraya??

//@version=5
indicator("Nadaraya-Watson Envelope [LuxAlgo]",overlay=true,max_bars_back=1000,max_lines_count=500,max_labels_count=500)
length = input.float(500,'Window Size',maxval=500,minval=0)
h = input.float(8.,'Bandwidth')
mult = input.float(3.)
src = input.source(close,'Source')

up_col = input.color(#39ff14,'Colors',inline='col')
dn_col = input.color(#ff1100,'',inline='col')
disclaimer = input(false, 'Hide Disclaimer')
//----
n = bar_index
var k = 2
var upper = array.new_line(0)
var lower = array.new_line(0)
lset(l,x1,y1,x2,y2,col)=>
line.set_xy1(l,x1,y1)
line.set_xy2(l,x2,y2)
line.set_color(l,col)
line.set_width(l,2)
if barstate.isfirst
for i = 0 to length/k-1
array.push(upper,line.new(na,na,na,na))
array.push(lower,line.new(na,na,na,na))
//----
line up = na
line dn = na
//----
cross_up = 0.
cross_dn = 0.
if barstate.islast
y = array.new_float(0)

sum_e = 0.
for i = 0 to length-1
sum = 0.
sumw = 0.

for j = 0 to length-1
w = math.exp(-(math.pow(i-j,2)/(h*h*2)))
sum += src[j]*w
sumw += w

y2 = sum/sumw
sum_e += math.abs(src - y2)
array.push(y,y2)
mae = sum_e/length*mult

for i = 1 to length-1
y2 = array.get(y,i)
y1 = array.get(y,i-1)

up := array.get(upper,i/k)
dn := array.get(lower,i/k)

lset(up,n-i+1,y1 + mae,n-i,y2 + mae,up_col)
lset(dn,n-i+1,y1 - mae,n-i,y2 - mae,dn_col)

if src > y1 + mae and src[i+1] < y1 + mae
label.new(n-i,src,'▼',color=#00000000,style=label.style_label_down,textcolor=dn_col,textalign=text.align_center)
if src < y1 - mae and src[i+1] > y1 - mae
label.new(n-i,src,'▲',color=#00000000,style=label.style_label_up,textcolor=up_col,textalign=text.align_center)

cross_up := array.get(y,0) + mae
cross_dn := array.get(y,0) - mae
alertcondition(ta.crossover(src,cross_up),'Down','Down')
alertcondition(ta.crossunder(src,cross_dn),'Up','Up')
//----
var tb = table.new(position.top_right, 1, 1
, bgcolor = #35202b)
if barstate.isfirst and not disclaimer
table.cell(tb, 0, 0, 'Nadaraya-Watson Envelope [LUX] Repaints'
, text_size = size.small
, text_color = #cc2f3c)
check this.

https://usethinkscript.com/threads/...pe-non-repaint-sam4cok-for-thinkorswim.12647/
 
try this.

CSS:
#//@version=4
#study(title="Average True Range Stop Loss Finder", shorttitle="ATR", overlay=true)
# Converted by Sam4Cok@Samer800 - 08/2022
input length = 14;#(title="Length", defval=14, minval=1)
input smoothing = {default RMA, SMA, EMA, WMA};#"Smoothing",
input ATRFactor = 1.0;       # Multiplier
input Target1   = 1.5;
input Target2   = 1.75;
input wicks = yes;
input addSrpead = yes;
input ShowBand = yes;#(true, "Show Price Lines")
input label = yes;

def c = close;
def h = high;
def l = low;


def ask  = Average(close(priceType = PriceType.ASK), 3);
def bid  = Average(close(priceType = PriceType.BID), 3);
def diff = AbsValue(ask - bid);

def spread = if IsNaN(diff) then 0 else diff;

#ma_function(type, source, length) =>
script ma_function {
    input smoothing = "RMA";
    input source = close;
    input length = 14;
    def maType;
        if smoothing == "RMA" {
            maType = WildersSmoothing(source, length);
        } else {
            if smoothing == "SMA" {
                maType = SimpleMovingAvg(source, length);
            } else {
                if smoothing == "EMA" {
                    maType =  ExpAverage(source, length);
                } else {
                    maType = WMA(source, length);
                }
            }
        }
        plot return = maType;
}
    def tr = TrueRange(h, c, l);
    def ATR = ma_function(smoothing, tr, length) + If(addSrpead, spread, 0);
    def ATR1 = ATR * ATRFactor;
    def ATRUp = ATR1 + If(wicks , h , c);
    def ATRDn = If(wicks , l , c) - ATR1;
#def tar1 =
#def tar2 =

#///find TP SL
    def slLong  = Round(c - ATRDn, 2);
    def tp1Long = Round((Target1 * slLong), 2);
    def tp2Long = Round((Target2 * slLong), 2);

    def slShort  = Round(ATRUp - c, 2);
    def tp1Short = Round((Target1 * slShort), 2);
    def tp2Short = Round((Target2 * slShort), 2);


#### LAbel ##########################

    AddLabel (label, "ATR(" + Round(ATR1, 2) + ")", CreateColor(33, 150, 243));
    AddLabel (label, "SL(" + slLong + ") TP1(" + tp1Long + ") TP2(" + tp2Long + ")", Color.LIGHT_GREEN);
    AddLabel (label, "SL(" + slShort + ") TP1(" + tp1Short + ") TP2(" + tp2Short + ")", Color.PINK);

    plot p1 = ATRUp;#, title = "ATR Short Stop Loss", color= colshort, transp=20, trackprice = pline ? true : false)
    p1.SetDefaultColor(CreateColor(255, 82, 82));
    p1.SetHiding(!ShowBand);

    plot p2 = ATRDn;#e = "ATR Long Stop Loss", color= collong, transp=20, trackprice = pline ? true : false)
    p2.SetDefaultColor(CreateColor(0, 137, 123));
    p2.SetHiding(!ShowBand);

#---- END CODE
Thanks @samer800. This is really cool but not exact replica of TV. May be you can guide me with the best settings? The issue I am facing is that the settings I am using do not work with all the charts. Example: It works well with Index but not with stocks. Any suggestions?
 
try this


CSS:
# Not typical converstion of "Nadaraya-Watson Envelope [LUX]"
# #'Nadaraya-Watson Non with non Repaint option'
# V1.1 Added option to enable/disable cloud and band lines.
# Mod by Sam4cok@samer800 - 09/2022

input BandLines = yes;
input ShowCloud = no;
input ShowSignal = yes;
input ShowBubble = yes;
input length = 500;
input Bandwidth = 8.0;    # 'Bandwidth'
input src = hlc3;
input lag = yes;
input mult = 2.7;         # "Multiplier"
input smooth = no;
input smoothLength = 3;

def na = Double.NaN;

script counter {
    input length = 500;
    input Bandwidth = 8;
    def counter = fold i = 0 to length - 1 with p do
              p +  Exp(-(Power(i,2)/(Bandwidth*Bandwidth*2)));
    plot result = counter;
}
def sum;
def mae;
def sumw;
def sum_e;
def y2;

    sum  = fold j = 0 to length-1 with p do
           p +  src[j] *  Exp(-(Power(if lag then counter(length, Bandwidth)-j else
                j,2)/(Bandwidth*Bandwidth*2)));

    sumw = fold k = 0 to length-1 with q do
           q + Exp(-(Power(if lag then counter(length,Bandwidth)-k else k,2)/(Bandwidth*Bandwidth*2)));

    y2 = if smooth then Average(sum/sumw, smoothLength) else (sum/sumw);

    sum_e = fold i = 0 to length-1 with r do
                r + absValue(src[i] - y2[i]);

    mae = if smooth then Average(sum_e/length*mult, smoothLength) else sum_e / length*mult;

    def mcol = if y2>y2[1] and y2[1]>y2[2] then 1 else 0;

    def SMAUp = y2 + mae;# "Upper"
    def SMALo = y2 - mae;# "Lower"

    plot UpperBand = SMAUp;
    plot LowerBand = SMALo;
    plot middle = y2;    # "Midle"
    UpperBand.SetHiding(!BandLines);
    LowerBand.SetHiding(!BandLines);
    UpperBand.SetDefaultColor(CreateColor(0,255,255));
    LowerBand.SetDefaultColor(CreateColor(255,0,255));
    LowerBand.SetHiding(!BandLines);
    middle.AssignValueColor( if mcol then CreateColor(0,255,255) else CreateColor(255,0,255));
    middle.SetLineWeight(2);

#---------------------------------------------
    def up = If(src crosses above y2 and  mcol and src[1]>open[1], middle, na);
    def dn = If(src crosses below y2 and !mcol and src[1]<open[1], middle, na);

    plot SigUp = up;
         SigUp.SetHiding(!ShowSignal);
    plot SigDn = dn;
         SigDn.SetHiding(!ShowSignal);
    SigUp.SetLineWeight(3);
    SigDn.SetLineWeight(3);
    SigUp.SetDefaultColor(Color.GREEN);
    SigDn.SetDefaultColor(Color.MAGENTA);
    SigUp.SetPaintingStrategy(PaintingStrategy.POINTS);
    SigDn.SetPaintingStrategy(PaintingStrategy.POINTS);

    plot bandUp = if src>SMALo and src[1]<SMALo then low else na;
    plot bandDn = if src<SMAUp and src[1]>SMAUp then high else na;

#------ CLOUD---
addcloud(if ShowCloud then SMAUp else na,middle, CreateColor(4,103,117));
addcloud(if ShowCloud then middle else na, SMALo,CreateColor(100,2,117));

#------ Bubbles
AddChartBubble(ShowBubble and bandUp, bandUp, "B", Color.GREEN, no);
AddChartBubble(ShowBubble and bandDn, bandDn, "S", Color.RED, yes);

#### END
@samer800
Could you please add mobile arrows it would help to create a scan with arrow (up & down) variables.
Thanks in advance.
 
@Molarman You copied the wrong code. That's for TradingView.

The TOS version is in the first message.
 
Does anyone have a scan for when buy signal is activated?
This script can't be used for the scanner, watchlist, conditional orders, or chart alerts as it is too advanced for the Condition Wizard, which is the engine behind these features.
GV3thSA.png

TDA allocates limited resources to the Condition Wizard, and this script goes beyond its capabilities.
We attempted multiple iterations to simplify the complexity of this code, to no avail :(
 
Last edited:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
320 Online
Create Post

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top