Z-Score Distance From VWAP for ThinkorSwim

horserider

Well-known member
VIP
As asked for, here is the VWAP deviations in several forms, including Z-Score distance from VWAP, lower studies, and more.

LnqgFoc.png


Pink is VWAP and Cyan is 200 period Std Dev

Code:
#
# TD Ameritrade IP Company, Inc. (c) 2018-2019
#

input length = 200;

def zeros = vwap -vwap[2];
def filter = reference EhlersSuperSmootherFilter(price = zeros, "cutoff length" = 0.5 * length);
def rms = Sqrt(Average(Sqr(filter), length));
def scaledFilter = filter / rms;
def alpha = 5 * AbsValue(scaledFilter) / length;
def deviationScaledMovAvg = CompoundValue(1, alpha * vwap + (1 - alpha) * deviationScaledMovAvg[1], vwap);

plot DSMA = deviationScaledMovAvg;
DSMA.SetDefaultColor(GetColor(1));

VWAP deviation at 20 period and 200 period lengths

Code:
declare lower;

input price = close;
input length = 20;

def SMA = Average(vwap[0], length);

plot DEV =(vwap/sma -1 )*100;

plot pdl = .5;
plot ndl = -.5;
plot zero = 0;

DEV.SetDefaultColor(GetColor(1));

input price2 = close;
input length2 = 200;

def SMA2 = Average(vwap[0], length2);

plot DEV2 =(vwap/SMA2 -1 )*100;

DEV2.SetDefaultColor(GetColor(2));

VWAP Z-Score

Code:
# Intraday VWAP Zscore
# Mobius
# 06.10.2019 Chat Room Request

declare lower;
def RTH = GetTime() >= RegularTradingStart(GetYYYYMMDD()) and
          GetTime() <= RegularTradingEnd(GetYYYYMMDD());
def n = if RTH and !RTH[1]
           then 1
           else if RTH
           then n[1] + 1
           else n[1];
def Avg = (fold i = 0 to n
           with s
           do s + getValue(close, i)) / n;
def VWAP_ = (fold ii = 0 to n
            with ss
            do ss + getValue(vwap, ii)) / n;
def StDev = Sqrt((fold iii = 0 to n
                  with sss = 0
                  do sss + Sqr(Avg - getValue(close, iii))) / n);
plot Zscore = (close - VWAP_) / StDev;
plot "0" = if isNaN(close) then double.nan else 0;
"0".SetDefaultColor(Color.white);
plot "1SD" = if isNaN(close) then double.nan else 1;
"1SD".SetDefaultColor(Color.Green);
plot "2SD" = if isNaN(close) then double.nan else 2;
"2SD".SetDefaultColor(Color.Green);
plot "-1SD" = if isNaN(close) then double.nan else -1;
"-1SD".SetDefaultColor(Color.Red);
plot "-2SD" = if isNaN(close) then double.nan else -2;
"-2SD".SetdefaultColor(Color.Red);
AddCloud(0, Zscore, color.red, color.green);
# End Code

Simple VWAP deviation script

Code:
declare lower;

input price = close;
input length = 20;

def vwd = Average(vwap[0], length);


plot DEV =(vwap/vwd -1 )*10;

plot pdl = .05;
plot ndl = -.05;
plot zero = 0;

Alert(DEV crosses below ndl, "", Alert.BAR, Sound.Bell);
Alert(DEV crosses above pdl, "", Alert.BAR, Sound.Bell);


DEV.SetDefaultColor(GetColor(1));
 

Attachments

  • LnqgFoc.png
    LnqgFoc.png
    173.4 KB · Views: 381
Last edited:

V-Score Indicator

Code:
#TOS Indicators - Home of the Volatility Box
#Full YouTube Tutorial: https://youtu.be/mAPEodczf-k
#
#**10/6/19 - Feature Added: Ability for Users to Set Custom Standard Deviation in Label Output

declare lower;
input anchorDate = 20180901;
input barsGoBack = 120;
input showStopLabel = yes;
input devStop = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree, Custom};
input customDev = 0.15;
def chosenDev;
switch(devStop){
case One:
    chosenDev = 1;
case Two:
    chosenDev = 2;
case Three:
    chosenDev = 3;
case Zero:
    chosenDev = 0;
case NegOne:
    chosenDev = -1;
case NegTwo:
    chosenDev = -2;
case NegThree:
    chosenDev = -3;
case Custom:
    chosenDev = customDev;
}



def postAnchorDate = if GetYYYYMMDD() >= anchorDate then 1 else 0;


def yyyyMmDd = getYyyyMmDd();
def periodIndx = if getAggregationPeriod() < AggregationPeriod.HOUR then yyyyMMDD else postAnchorDate;
def isPeriodRolled = compoundValue(1, periodIndx != periodIndx[1], yes);

def volumeSum;
def volumeVwapSum;
def volumeVwap2Sum;

if (isPeriodRolled) {
    volumeSum = volume;
    volumeVwapSum = volume * vwap;
    volumeVwap2Sum = volume * Sqr(vwap);
} else {
    volumeSum = compoundValue(1, volumeSum[1] + volume, volume);
    volumeVwapSum = compoundValue(1, volumeVwapSum[1] + volume * vwap, volume * vwap);
    volumeVwap2Sum = compoundValue(1, volumeVwap2Sum[1] + volume * Sqr(vwap), volume * Sqr(vwap));
}
def price = volumeVwapSum / volumeSum;
def deviation = Sqrt(Max(volumeVwap2Sum / volumeSum - Sqr(price), 0));

plot VScore = if (((price - close)*(-1))/deviation) > 5 or (((price - close)*(-1))/deviation) < -5 then 0 else (((price - close)*(-1))/(deviation));
plot zero = 0;
plot one = 1;
plot two = 2;
plot three = 3;
plot negOne = -1;
plot negTwo = -2;
plot negThree = -3;
plot posInt = 0.3;
plot negInt = -0.3;

def stopPrice = (chosenDev)*(deviation) + (price);
AddLabel(showStopLabel, "Price at ["+chosenDev+"] SD: "+AsPrice(Round(stopPrice,2)),color.white);
def zeroAndOne = if VScore > zero and VScore <= one then 1 else 0;
def oneAndTwo = if VScore > one and VScore <= two then 1 else 0;
def twoAndThree = if VScore > two and VScore <= three then 1 else 0;

def negZeroAndOne = if VScore > negOne and VScore < zero then 1 else 0;
def negOneAndTwo = if VScore > negTwo and VScore <= negOne then 1 else 0;
def negTwoAndThree = if VScore > negThree and VScore <= negTwo then 1 else 0;

def cloud1;
def cloud2;
if Sum(zeroAndOne, barsGoBack) > Sum(OneAndTwo,barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(twoAndThree,barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(negZeroAndOne,barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(negoneAndTwo,barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(negtwoAndThree,barsGoBack){
    cloud1 = zero;
    cloud2 = one;
}
else if Sum(OneAndTwo, barsGoBack) > Sum(zeroAndOne,barsGoBack) and Sum(OneAndTwo, barsGoBack) > Sum(twoAndThree,barsGoBack) and Sum(OneAndTwo, barsGoBack) > Sum(negZeroAndOne,barsGoBack) and Sum(OneAndTwo, barsGoBack) > Sum(negoneAndTwo,barsGoBack) and Sum(OneAndTwo, barsGoBack) > Sum(negtwoAndThree,barsGoBack){
    cloud1 = one;
    cloud2 = two;
}
else if Sum(twoAndThree, barsGoBack) > Sum(zeroAndOne,barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(oneAndTwo,barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(negZeroAndOne,barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(negoneAndTwo,barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(negtwoAndThree,barsGoBack){
    cloud1 = two;
    cloud2 = three;
}
else if Sum(negZeroAndOne, barsGoBack) > Sum(zeroAndOne,barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(oneAndTwo,barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(twoAndThree,barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(negoneAndTwo,barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(negtwoAndThree,barsGoBack){
    cloud1 = zero;
    cloud2 = negOne;
}
else if Sum(negoneAndTwo, barsGoBack) > Sum(zeroAndOne,barsGoBack) and Sum(negoneAndTwo, barsGoBack) > Sum(oneAndTwo,barsGoBack) and Sum(negoneAndTwo, barsGoBack) > Sum(twoAndThree,barsGoBack) and Sum(negoneAndTwo, barsGoBack) > Sum(negZeroAndOne,barsGoBack) and Sum(negoneAndTwo, barsGoBack) > Sum(negtwoAndThree,barsGoBack){
    cloud1 = negOne;
    cloud2 = negTwo;
}
else if Sum(negtwoAndThree, barsGoBack) > Sum(zeroAndOne,barsGoBack) and Sum(negtwoAndThree, barsGoBack) > Sum(oneAndTwo,barsGoBack) and Sum(negtwoAndThree, barsGoBack) > Sum(twoAndThree,barsGoBack) and Sum(negtwoAndThree, barsGoBack) > Sum(negZeroAndOne,barsGoBack) and Sum(negtwoAndThree, barsGoBack) > Sum(negOneAndTwo,barsGoBack){
    cloud1 = negTwo;
    cloud2 = negThree;
}
else {
    cloud1 = Double.nan;
    cloud2 = Double.nan;
}
AddCloud(cloud1, cloud2, color.light_red, color.light_green);


plot BullSignal = if (cloud1 == one or cloud2 == one or cloud1 == two or cloud2 == two or cloud1 == three or cloud2 ==three) and (VScore <= 0.3 and Vscore[1] >0) and CCI() > -100 then -2 else Double.nan;

plot BearSignal = if (cloud1 == negOne or cloud2 == negOne or cloud1 == negTwo or cloud2 == negTwo or cloud1 == negThree or cloud2 ==negThree) and (VScore >= 0.3 and Vscore[1] < 0) and CCI() < 100 then 2 else Double.nan;

BullSignal.SetPaintingStrategy(PaintingStrategy.Arrow_UP);
BearSignal.SetPaintingStrategy(PaintingStrategy.Arrow_DOWN);
BullSignal.SetLineWeight(3);
BearSignal.SetLineWeight(3);

input soundAlertsOn = no;
Alert((cloud1 == one or cloud2 == one or cloud1 == two or cloud2 == two or cloud1 == three or cloud2 == three) and (VScore <= 0 and VScore[1] > 0) and (SoundAlertsOn), "Bullish VScore Entry", Alert.BAR);
Alert((cloud1 == negOne or cloud2 == negone or cloud1 == negtwo or cloud2 == negtwo or cloud1 == negthree or cloud2 == negthree) and (VScore >= 0 and VScore[1] < 0)and (SoundAlertsOn), "Bearish VScore Entry", Alert.BAR);

V-Score Scans:

Bull Signal (more filter criteria): http://tos.mx/T4Az7C
Bear Signal (more filter criteria): http://tos.mx/fDQ4cn

Wide Bull Scan (less filter criteria): http://tos.mx/1uk28D
Wide Bear Signal (less filter criteria): http://tos.mx/WVv5bw
 
@AGD Thanks for pointing this out. I did those studies a while ago when just starting thinkscript. Do not remember why I put allDev in as it does nothing. Redid the code to correct errors. Hope it passes inspection now.
 
  • Haha
Reactions: AGD
This is a mean reversion indicator to forecast possible price reversal.

ep7CSYr.jpg


Code:
#=====================================
#Computes and plots the Zscore
#Provided courtesy of ThetaTrend.com
#Feel free to share the code with a link back to thetatrend.com

declare lower;

input price = close;
input length = 20;
input ZavgLength = 20;

#Initialize values
def oneSD = stdev(price,length);
def avgClose = simpleMovingAvg(price,length);
def ofoneSD = oneSD*price[1];
def Zscorevalue = ((price-avgClose)/oneSD);
def avgZv = average(Zscorevalue,20);

#Compute and plot Z-Score
plot Zscore = ((price-avgClose)/oneSD);
Zscore.setPaintingStrategy(paintingStrategy.HISTOGRAM);
Zscore.setLineWeight(2);
Zscore.assignValueColor(color.cyan);
Zscore.assignValueColor(if Zscore > 0 then color.cyan else color.red);

plot avgZscore = average(Zscorevalue,ZavgLength);
avgZscore.setPaintingStrategy(paintingStrategy.LINE);
avgZscore.setLineWeight(2);
avgZscore.assignValueColor(color.green);
#This is an optional plot that will display the momentum of the Z-Score average
#plot momZAvg = (avgZv-avgZv[5]);

#Plot zero line and extreme bands
plot zero = 0;
plot two = 2;
two.assignValueColor(color.YELLOW);
plot one = 1;
one.setPaintingStrategy(paintingStrategy.DASHES);
one.setLineWeight(1);
one.assignValueColor(color.GRAY);
plot negone = -1;
negone.setPaintingStrategy(paintingStrategy.DASHES);
negone.setLineWeight(1);
negone.assignValueColor(color.GRAY);
plot negtwo = -2;
negtwo.assignValueColor(color.LIGHT_RED);
zero.setDefaultColor(color.DARK_GRAY);
#=====================================
 

Attachments

  • ep7CSYr.jpg
    ep7CSYr.jpg
    119.8 KB · Views: 158
Last edited by a moderator:
this is a very cool - I think there are multiple uses, I've made some changes to make turn the zscore into a trend indicator, I think it can be use as trend, reversal and maybe even as a exit/stop indicator, please play with it and test it. report back any findings or observations.

juJqMQg.png


toggle color candles on or off to control the candle color as an input.

Code:
#=====================================
#Computes and plots the Zscore
#Provided courtesy of ThetaTrend.com
#Feel free to share the code with a link back to thetatrend.com
#
# Change Log
# 2019.10.01 - diazlaz - added color candles for trend detection
#                      - added threshold and 2 candle confirmation
#                        for trend and reducing intraday noise at
#                        lower timeframes.
#

declare lower;

input price = close;
input length = 20;
input ZavgLength = 20;
input zTresPos = 0.50;
input zTresNeg = -0.50;
input colorBars = yes;

#Initialize values
def oneSD = stdev(price,length);
def avgClose = simpleMovingAvg(price,length);
def ofoneSD = oneSD*price[1];
def Zscorevalue = ((price-avgClose)/oneSD);
def avgZv = average(Zscorevalue,20);

#Compute and plot Z-Score
plot Zscore = ((price-avgClose)/oneSD);
Zscore.setPaintingStrategy(paintingStrategy.HISTOGRAM);
Zscore.setLineWeight(2);
Zscore.assignValueColor(color.cyan);
Zscore.assignValueColor(if Zscore > 0 then color.cyan else color.red);

plot avgZscore = average(Zscorevalue,ZavgLength);
avgZscore.setPaintingStrategy(paintingStrategy.LINE);
avgZscore.setLineWeight(2);
avgZscore.assignValueColor(color.green);
#This is an optional plot that will display the momentum of the Z-Score average
#plot momZAvg = (avgZv-avgZv[5]);

#Plot zero line and extreme bands
plot zero = 0;
plot two = 2;
two.assignValueColor(color.YELLOW);
plot one = 1;
one.setPaintingStrategy(paintingStrategy.DASHES);
one.setLineWeight(1);
one.assignValueColor(color.GRAY);
plot negone = -1;
negone.setPaintingStrategy(paintingStrategy.DASHES);
negone.setLineWeight(1);
negone.assignValueColor(color.GRAY);
plot negtwo = -2;
negtwo.assignValueColor(color.LIGHT_RED);
zero.setDefaultColor(color.DARK_GRAY);

#Color Candles
def state = if Zscore > zTresPos and Zscore[1] > zTresPos then 100 else 
   if Zscore < zTresNeg and Zscore[1] < zTresNeg then -100 else state[1];

AssignPriceColor(
   if colorBars then
    if state == 100 then COLOR.GREEN
        else COLOR.RED
   else
        Color.CURRENT);

#End of ZSCORE Indicator by TheraTrend for ThinkorSwim
 

Attachments

  • juJqMQg.png
    juJqMQg.png
    162.4 KB · Views: 170
Here is an indicator on that I coded with some help. It looks like LazyBear indicator on Trading View but for TOS. Zscore of Distance from VWAP indicator. And like the one you are looking in the video.

Code:
# Intraday VWAP Zscore

declare lower;

input price = close;
input length = 20;

#calc_zvwap(pds) =>
#    mean = sum(volume*close,pds)/sum(volume,pds)
def mean = Sum(Volume*Close, length)/Sum(Volume, length);
#    vwapsd = sqrt(sma(pow(close-mean, 2), pds) )
def vwapsd = Sqrt(Average(Power(Close-mean, 2), length));
#    (close-mean)/vwapsd
def zScore = (Close-mean)/vwapsd;
####

plot "0" = if IsNaN(close) then Double.NaN else 0;
"0".SetDefaultColor(Color.GRAY);
plot "1SD" = if IsNaN(close) then Double.NaN else 1;
"1SD".SetDefaultColor(Color.WHITE);
def "2SD" = if IsNaN(close) then Double.NaN else 2;

def "2.5SD" = if IsNaN(close) then Double.NaN else 2.5;

AddCloud("2SD", "2.5SD", Color.RED, Color.GREEN);

plot "-1SD" = if IsNaN(close) then Double.NaN else -1;
"-1SD".SetDefaultColor(Color.WHITE);
def "-2SD" = if IsNaN(close) then Double.NaN else -2;
def "-2.5SD" = if IsNaN(close) then Double.NaN else -2.5;

AddCloud("-2SD", "-2.5SD", Color.RED, Color.GREEN);
Plot zscorevwap = zscore;
AddCloud(0,  Zscore,  Color.RED,  Color.GREEN);
# End Code

You need to learn to google man. From this: http://traders.com/Documentation/FEEDbk_docs/2019/05/TradersTips.html

There is the script for the reversion strategy. (strategy can do auto trading, you need to watch what your settings are)

"We have put together a strategy for thinkorswim based on Anthony Garner’s article “Backtesting A Mean-Reversion Strategy In Python.” The strategy is built using our proprietary scripting language, thinkscript, as opposed to Python. To ease the loading process, simply click on https://tos.mx/rIy6Qv or enter the address into a web browser and then click open shared item from within thinkorswim. Choose view thinkscript and name it “SimpleMeanReversion.” This can then be added to your chart."
 
Anyone have an idea on how to trade using this indicator setup like is there a video out there or something I could watch tutorial thanks for any help
 
@Harleym2009 Not really an indicator setup. Just a few examples to show deviation from the VWAP as someone had asked about VWAP deviation.
Each study is a different way to show basically the same info. That is deviation of price from the VWAP. The idea would be a larger deviation may result in a reversion. In any deviation from the mean two things can happen, reversion to the mean or mean catches up to the deviation. So price moves back to the VWAP or the VWAP catches up with the price. Nothing is ever certain except at some point the two will come together. So just look those over and see if any can be useful to you. Ask questions about any particular one if you have any.
 
@Harleym2009 I use it to see for momentum change. if it can reach 2.5 positive and negative, strong trend, if it can't and sits within 1 standard deviation, it's a weakness. Further, I look at divergence, if ZScore is going down, and the price is going up, I know there will be a correction soon.
 
Thank you for the break down, spent about an hour reading, interpreting, (watched the video twice), looked at my ZScore study, looked at the code, and am as lost as I was at the beginning. I guess its a sign I need to learn more... discouraging, I hate code, but I love #'s.... all very confusing. Thank you for trying to help... Not even sure what to ask to help me more
 
@VicD thanks for sharing this. I loaded this Study in ThinkorSwim and have a couple of questions. When the Zscore is 0, does that mean the stock price is sitting on the VWAP line? Similarly, if the Zscore is greater than 0, stock price should be above the VWAP line? And when the Zscore is less than 0, stock price should be below the VWAP line. I'm looking at a intraday (1min) chart and noticed that this is not the case. For example, when the Zscore is 2, the stock price can be below the VWAP line. I can share a screen shot if it will help explain things.
 
@megahead34 I think VicD has done some crazy math calculations and is coming up with some sort of 20 bar average of the VWAP, it is not a Z score of the VWAP. Your description of a Z score as far as I understand is correct.
 
@megahead34 I think VicD has done some crazy math calculations and is coming up with some sort of 20 bar average of the VWAP, it is not a Z score of the VWAP.
Your description of a Z score as far as I understand is correct.

Aah ok, that makes sense. I like the way it works without understanding the crazy math calculations lol.
 
I have a indicator that I like but need some help with the strategy for further testing. Long entry is when the avgZscore is below -1 and the signal is when Zscore crosses above -1. Short entry is avgZscore is above 1 and the signal is Zscore crosses below 1. Exit would be ATR multiple for trailing stop and profit target.

Code:
declare lower;
input length = 20;
input Agg = {default current, min5, min15, min30, daily}; def t; switch (Agg){ case current:     t = close; case min5:     t = close(period = AggregationPeriod.FIVE_MIN); case min15:     t = close(period = AggregationPeriod.FIFTEEN_MIN); case min30:     t = close(period = AggregationPeriod.THIRTY_MIN); case daily:     t = close(period = AggregationPeriod.DAY); } def c = close;
plot Zscore = (t - Average(t, length)) / StDev(t, length); Zscore.SetDefaultColor(Color.cyan);
plot zero = if IsNaN(c) then Double.NaN else 0; zero.SetDefaultColor(Color.BLACK);
zero.SetLineWeight(1); zero.HideTitle();
plot PosOne = if IsNaN(c) then Double.NaN else 1; PosOne.SetDefaultColor(Color.white); PosOne.HideTitle();
plot NegOne = if IsNaN(c) then Double.NaN else -1; NegOne.SetDefaultColor(Color.yellow); NegOne.HideTitle();
plot PosTwo = if IsNaN(c) then Double.NaN else 2; PosTwo.SetDefaultColor(Color.GREEN); PosTwo.HideTitle();
plot NegTwo = if IsNaN(c) then Double.NaN else -2; NegTwo.SetDefaultColor(Color.RED);
NegTwo.HideTitle();
plot PosThree = if IsNaN(c) then Double.NaN else 3; PosThree.SetDefaultColor(Color.DARK_GREEN); PosThree.HideTitle();
plot NegThree = if IsNaN(c) then Double.NaN else -3; NegThree.SetDefaultColor(Color.DARK_RED); NegThree.HideTitle();
AddCloud(zero, PosOne, Color.LIGHT_GREEN, Color.LIGHT_GREEN);
AddCloud(PosOne, PosTwo, Color.GREEN, Color.GREEN); AddCloud(PosTwo, PosThree, Color.DARK_GREEN, Color.DARK_GREEN);
AddCloud(NegOne, zero, Color.LIGHT_RED, Color.LIGHT_RED);
AddCloud(NegTwo, NegOne, Color.RED, Color.RED);
AddCloud(NegThree, NegTwo, Color.DARK_RED, Color.DARK_RED);
Zscore input price = close;
input ZavgLength = 20;
#Initialize values
def oneSD = stdev(price,length);
def avgClose = simpleMovingAvg(price,length);
def ofoneSD = oneSD*price[1]; def Zscorevalue = ((price-avgClose)/oneSD); def avgZv = average(Zscorevalue,20);
plot avgZscore = Average(Zscorevalue, ZavgLength);
avgZscore.SetPaintingStrategy(PaintingStrategy.LINE); avgZscore.SetLineWeight(2); avgZscore.AssignValueColor(Color.GREEN);

https://tos.mx/0QQqk26
 
I am trying to get +/- standard deviation labels of VWAP to plot on the VScore indicator. The original code had only one label for 1 SD, but I was able to add 5 additional labels to it which show up correctly on the indicator, however, they all give me the price of 1 standard deviation away from the 0 line. I think the problem is with the definition of "chosendev", but when I try to change "chosendev" to "chosendev1" "chosendev2" etc, I get an error saying "value never assigned to chosendev2" etc. Here is the code and a screenshot of the indicator. Can anyone help fix this? Thanks!

FFh8FAz.jpg


Code:
declare lower;

input anchorDate = 20200820;

input barsGoBack = 120;

input showStopLabel1 = yes;

input devStop1 = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree, Custom};

input showStopLabel2 = yes;

input devStop2 = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree, Custom};

input showStopLabel3 = yes;

input devStop3 = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree, Custom};

input showStopLabel4 = yes;

input devStop4 = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree, Custom};

input showStopLabel5 = yes;

input devStop5 = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree, Custom};

input showStopLabel6 = yes;

input devStop6 = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree, Custom};


input customDev = 0.15;



def chosenDev;

switch (devStop1)

{

case One:

    chosenDev = 1;

case Two:

    chosenDev = 2;

case Three:

    chosenDev = 3;

case Zero:

    chosenDev = 0;

case NegOne:

    chosenDev = -1;

case NegTwo:

    chosenDev = -2;

case NegThree:

    chosenDev = -3;

case Custom:

    chosenDev = customDev;

}




def postAnchorDate = if GetYYYYMMDD() >= anchorDate then 1 else 0;



def yyyyMmDd = GetYYYYMMDD();

def periodIndx = if GetAggregationPeriod() < AggregationPeriod.HOUR then yyyyMmDd else postAnchorDate;

def isPeriodRolled = CompoundValue(1, periodIndx != periodIndx[1], yes);


def volumeSum;

def volumeVwapSum;

def volumeVwap2Sum;


if (isPeriodRolled) {

    volumeSum = volume;

    volumeVwapSum = volume * vwap;

    volumeVwap2Sum = volume * Sqr(vwap);

} else {

    volumeSum = CompoundValue(1, volumeSum[1] + volume, volume);

    volumeVwapSum = CompoundValue(1, volumeVwapSum[1] + volume * vwap, volume * vwap);

    volumeVwap2Sum = CompoundValue(1, volumeVwap2Sum[1] + volume * Sqr(vwap), volume * Sqr(vwap));

}

def price = volumeVwapSum / volumeSum;

def deviation = Sqrt(Max(volumeVwap2Sum / volumeSum - Sqr(price), 0));


plot VScore = if (((price - close) * (-1)) / deviation) > 5 or (((price - close) * (-1)) / deviation) < -5 then 0 else (((price - close) * (-1)) / (deviation));

plot zero = 0;

plot one = 1;

plot two = 2;

plot three = 3;

plot negOne = -1;

plot negTwo = -2;

plot negThree = -3;

plot posInt = 0.3;

plot negInt = -0.3;


def stopPrice = (chosenDev) * (deviation) + (price);

AddLabel(showStopLabel1, "Price at [" + chosenDev + "] SD: " + AsPrice(Round(stopPrice, 2)), Color.WHITE);

def stopPrice2 = (chosenDev) * (deviation) + (price);

AddLabel(showStopLabel2, "Price at [" + chosenDev + "] SD: " + AsPrice(Round(stopPrice2, 2)), Color.WHITE);

def stopPrice3 = (chosenDev) * (deviation) + (price);

AddLabel(showStopLabel3, "Price at [" + chosenDev + "] SD: " + AsPrice(Round(stopPrice3, 2)), Color.WHITE);

def stopPrice4 = (chosenDev) * (deviation) + (price);

AddLabel(showStopLabel4, "Price at [" + chosenDev + "] SD: " + AsPrice(Round(stopPrice4, 2)), Color.WHITE);

def stopPrice5 = (chosenDev) * (deviation) + (price);

AddLabel(showStopLabel5, "Price at [" + chosenDev + "] SD: " + AsPrice(Round(stopPrice5, 2)), Color.WHITE);

def stopPrice6 = (chosenDev) * (deviation) + (price);

AddLabel(showStopLabel6, "Price at [" + chosenDev + "] SD: " + AsPrice(Round(stopPrice6, 2)), Color.WHITE);




def zeroAndOne = if VScore > zero and VScore <= one then 1 else 0;

def oneAndTwo = if VScore > one and VScore <= two then 1 else 0;

def twoAndThree = if VScore > two and VScore <= three then 1 else 0;


def negZeroAndOne = if VScore > negOne and VScore < zero then 1 else 0;

def negOneAndTwo = if VScore > negTwo and VScore <= negOne then 1 else 0;

def negTwoAndThree = if VScore > negThree and VScore <= negTwo then 1 else 0;


def cloud1;

def cloud2;

if Sum(zeroAndOne, barsGoBack) > Sum(oneAndTwo, barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(twoAndThree, barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(negZeroAndOne, barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(negOneAndTwo, barsGoBack) and Sum(zeroAndOne, barsGoBack) > Sum(negTwoAndThree, barsGoBack) {

    cloud1 = zero;

    cloud2 = one;

}

else if Sum(oneAndTwo, barsGoBack) > Sum(zeroAndOne, barsGoBack) and Sum(oneAndTwo, barsGoBack) > Sum(twoAndThree, barsGoBack) and Sum(oneAndTwo, barsGoBack) > Sum(negZeroAndOne, barsGoBack) and Sum(oneAndTwo, barsGoBack) > Sum(negOneAndTwo, barsGoBack) and Sum(oneAndTwo, barsGoBack) > Sum(negTwoAndThree, barsGoBack) {

    cloud1 = one;

    cloud2 = two;

}

else if Sum(twoAndThree, barsGoBack) > Sum(zeroAndOne, barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(oneAndTwo, barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(negZeroAndOne, barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(negOneAndTwo, barsGoBack) and Sum(twoAndThree, barsGoBack) > Sum(negTwoAndThree, barsGoBack) {

    cloud1 = two;

    cloud2 = three;

}

else if Sum(negZeroAndOne, barsGoBack) > Sum(zeroAndOne, barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(oneAndTwo, barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(twoAndThree, barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(negOneAndTwo, barsGoBack) and Sum(negZeroAndOne, barsGoBack) > Sum(negTwoAndThree, barsGoBack) {

    cloud1 = zero;

    cloud2 = negOne;

}

else if Sum(negOneAndTwo, barsGoBack) > Sum(zeroAndOne, barsGoBack) and Sum(negOneAndTwo, barsGoBack) > Sum(oneAndTwo, barsGoBack) and Sum(negOneAndTwo, barsGoBack) > Sum(twoAndThree, barsGoBack) and Sum(negOneAndTwo, barsGoBack) > Sum(negZeroAndOne, barsGoBack) and Sum(negOneAndTwo, barsGoBack) > Sum(negTwoAndThree, barsGoBack) {

    cloud1 = negOne;

    cloud2 = negTwo;

}

else if Sum(negTwoAndThree, barsGoBack) > Sum(zeroAndOne, barsGoBack) and Sum(negTwoAndThree, barsGoBack) > Sum(oneAndTwo, barsGoBack) and Sum(negTwoAndThree, barsGoBack) > Sum(twoAndThree, barsGoBack) and Sum(negTwoAndThree, barsGoBack) > Sum(negZeroAndOne, barsGoBack) and Sum(negTwoAndThree, barsGoBack) > Sum(negOneAndTwo, barsGoBack) {

    cloud1 = negTwo;

    cloud2 = negThree;

}

else {

    cloud1 = Double.NaN;

    cloud2 = Double.NaN;

}

AddCloud(cloud1, cloud2, Color.LIGHT_RED, Color.LIGHT_GREEN);



plot BullSignal = if (cloud1 == one or cloud2 == one or cloud1 == two or cloud2 == two or cloud1 == three or cloud2 == three) and (VScore <= 0.3 and VScore[1] > 0) and CCI() > -100 then -2 else Double.NaN;


plot BearSignal = if (cloud1 == negOne or cloud2 == negOne or cloud1 == negTwo or cloud2 == negTwo or cloud1 == negThree or cloud2 == negThree) and (VScore >= 0.3 and VScore[1] < 0) and CCI() < 100 then 2 else Double.NaN;


BullSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

BearSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

BullSignal.SetLineWeight(3);

BearSignal.SetLineWeight(3);


input soundAlertsOn = no;

Alert((cloud1 == one or cloud2 == one or cloud1 == two or cloud2 == two or cloud1 == three or cloud2 == three) and (VScore <= 0 and VScore[1] > 0) and (soundAlertsOn), "Bullish VScore Entry", Alert.BAR);

Alert((cloud1 == negOne or cloud2 == negOne or cloud1 == negTwo or cloud2 == negTwo or cloud1 == negThree or cloud2 == negThree) and (VScore >= 0 and VScore[1] < 0) and (soundAlertsOn), "Bearish VScore Entry", Alert.BAR);[ATTACH=full]7958[/ATTACH]
 
Just saw this thread. I don't know about the easycator's vwap strat or zscore indicator but I've made something similar that I've based on the vwap deviations indicator that I use. I guess you could consider this a companion to that indicator. I look for daily VWAP 2nd devs to be outside of weekly 2nd deviations and weekly 2nd deviations to be outside of the monthly 2nd deviations. I've found when price is outside of these boundaries there can be a high probability to make a large push back towards the weekly/monthly vwaps. I made this a while ago but come back to it every now and then to make some tweaks. Maybe this can give you some ideas.
A few notes:
this is best used with extended trading hours turned on
the candles are hull MAs based on the high/low/close position relative to the daily VWAP deviations
the orange and red lines are hull MA's based on the close position relative to the weekly/monthy VWAP deviations
0 = VWAP for daily(candles)/weekly(orange line)/monthly(red line)
+/- 25 is = 1st deviation
+/- 50 is = 2nd deviation
+/- 75 is = 3rd deviation
+/- 100 is = 4th deviation
when price is below or above 2nd deviations (+/- 50) a magenta dot (daily) orange dot(weekly) or red dot (monthly) will plot at the top or bottom.
when price touches the daily/weekly/monthly vwap a magenta/orange/red dot will plot on the 0 line
if daily vwap is above or below 2nd deviations dark gray vertical lines will plot
TQXKHdK.png


Code:
#[email protected]
#version 7.29.2020

declare lower;
def NA = Double.NaN;
input thresh =50;
input threshWk = 50;
input threshMnth = 50;

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

DefineGlobalColor("Bullish", CreateColor(0,100,200));
DefineGlobalColor("Bearish", Color.YELLOW);
#VWAP Daily, Weekly, and Monthly
def VWAPDAY =  reference VWAP("time frame" = "DAY");
def VWAPWK = reference VWAP("time frame" = "WEEK");
def VWAPMNTH = reference VWAP("time frame" = "MONTH");
#VWAP UpperBand and LowerBand values
def VWAPDAYLB = reference VWAP("num dev dn" = -4.0, "time frame" = "DAY")."LowerBand";
def VWAPWKLB = reference VWAP("num dev dn" = -4.0, "time frame" = "WEEK")."LowerBand";
def VWAPMNTHLB = reference VWAP("num dev dn" = -4.0, "time frame" = "MONTH")."LowerBand";
def VWAPDAYHB = reference VWAP("num dev up" = 4.0, "time frame" = "DAY")."UpperBand";
def VWAPWKHB = reference VWAP("num dev up" = 4.0, "time frame" = "WEEK")."UpperBand";
def VWAPMNTHHB = reference VWAP("num dev up" = 4.0, "time frame" = "MONTH")."UpperBand";


#VWAP Deviation Bands
def VWAPUB = reference VWAP("num dev up" = 4.0, "time frame" = "DAY")."UpperBand";
def VWAPLB = reference VWAP("num dev dn" = -4.0, "time frame" = "DAY")."LowerBand";

##############################
input price = close;
input avgType = AverageType.HULL;
input avgLength = 5;
def VWDayBP = c - VWAPLB;
def VWDaySP = VWAPUB - c;
def VWDayBPh= h - VWAPLB;
def VWDaySPh = VWAPUB - h;
def VWDayBPl = l - VWAPLB;
def VWDaySPl = VWAPUB - l;
def VWDayRange = VWAPUB - VWAPLB;

#VWDayRange.Hide();
def VWDayBandWidthU = ((VWAPUB - VWAPLB)/VWAPDAY)*1000;
def VWDayBandWidthD = ((VWAPLB - VWAPUB)/VWAPDAY)*1000;

def VWWkBP = c - VWAPWKLB;
def VWWkSP = VWAPWKHB - c;
def VWWkBPh = h - VWAPWKLB;
def VWWkSPh = VWAPWKHB - h;
def VWWkBPl = l - VWAPWKLB;
def VWWkSPl = VWAPWKHB - l;
def VWWkRange = VWAPWKHB - VWAPWKLB;

def VWMnthBP = c - VWAPMNTHLB;
def VWMnthSP = VWAPMNTHHB - c;
def VWMnthBPh = h - VWAPMNTHLB;
def VWMnthSPh = VWAPMNTHHB - h;
def VWMnthBPl = l - VWAPMNTHLB;
def VWMnthSPl = VWAPMNTHHB - l;
def VWMnthRange = VWAPMNTHHB - VWAPMNTHLB;

def VWAPDayZh1 = MovingAverage(avgType,(((VWDayBPh - VWDaySPh)/(VWDayRange))*100),avgLength);
def VWAPDayZl1 = MovingAverage(avgType,(((VWDayBPl - VWDaySPl)/(VWDayRange))*100),avgLength);
def VWAPDayZc1 = MovingAverage(avgType,(((VWDayBP - VWDaySP)/(VWDayRange))*100),avgLength);
def VWAPDayZh = if AbsValue(VWAPDayZh1) > 120 then NA else VWAPDayZh1;
def VWAPDayZl = if AbsValue(VWAPDayZl1) > 120 then NA else VWAPDayZl1;
plot VWAPDayZc = if AbsValue(VWAPDayZc1) > 120 then NA else VWAPDayZc1;
VWAPDayZc.Hide();
def bb = VWAPDayZc > VWAPDayZc[1];
def VWAPWkZ1 = MovingAverage(avgType,(((VWWkBP - VWWkSP)/(VWWkRange))*100),avgLength);
plot VWAPWkZ = if AbsValue(VWAPWkZ1) > 120 then NA else VWAPWkZ1;
def VWAPWkZh1 = MovingAverage(avgType,(((VWWkBPh - VWWkSPh)/(VWWkRange))*100),avgLength);
def VWAPWkZl1 = MovingAverage(avgType,(((VWWkBPl - VWWkSPl)/(VWWkRange))*100),avgLength);
def VWAPWkZh = if AbsValue(VWAPWkZh1) > 120 then NA else VWAPWkZh1;
def VWAPWkZl = if AbsValue(VWAPWkZl1) > 120 then NA else VWAPWkZl1;

def VWAPMnthZ1 = MovingAverage(avgType,(((VWMnthBP - VWMnthSP)/(VWMnthRange))*100),avgLength);
plot VWAPMnthZ = if AbsValue(VWAPMnthZ1) > 120 then NA else VWAPMnthZ1;
def VWAPMnthZh1 = MovingAverage(avgType,(((VWMnthBPh - VWMnthSPh)/(VWMnthRange))*100),avgLength);
def VWAPMnthZl1 = MovingAverage(avgType,(((VWMnthBPl - VWMnthSPl)/(VWMnthRange))*100),avgLength);
def VWAPMnthZh =  if AbsValue(VWAPMnthZh1) > 120 then NA else VWAPMnthZh1;
def VWAPMnthZl =  if AbsValue(VWAPMnthZl1) > 120 then NA else VWAPMnthZl1;
VWAPWkZ.SetHiding(VWAPWkZ == VWAPDayZc);

AddChart(VWAPDayZh,VWAPDayZl,if bb then VWAPDayZl else NA,VWAPDayZc,ChartType.CANDLE, GlobalColor("Bullish"));
AddChart(VWAPDayZh,VWAPDayZl,if !bb then VWAPDayZh else NA,VWAPDayZc,ChartType.CANDLE, GlobalColor("Bearish"));

AddVerticalLine((AbsValue(VWAPDayZh) >= thresh) or (AbsValue(VWAPDayZl) >= thresh) or (AbsValue(VWAPDayZc) >= thresh),"", Color.DARK_GRAY, Curve.POINTS);

plot VWAPDaytopsig = if VWAPDayZc >= threshWk then 100 else NA;
plot VWAPDaybotsig = if VWAPDayZc <= -threshWk then -100 else NA;
plot VWAPWktopsig = if VWAPWkZ >= threshWk then 100 else NA;
plot VWAPWkbotsig = if VWAPWkZ <= -threshWk then -100 else NA;
plot VWAPMnthtopsig = if VWAPMnthZ >= threshMnth then 100 else NA;
plot VWAPMnthbotsig = if VWAPMnthZ <= -threshMnth then -100 else NA;


plot Dev1Pos = 25;
plot Dev1Neg = -25;
plot Dev2Pos = 50;
plot Dev2Neg = -50;
plot Dev3Pos = 75;
plot Dev3Neg = -75;
plot Dev4Pos = 100;
plot Dev4Neg = -100;
plot zero = 0;
zero.SetLineWeight(3);
zero.SetDefaultColor(Color.BLUE);


def VWAPtestD = VWAPDayZl <= 0 and VWAPDayZh >= 0;
def VWAPtestW = VWAPWkZl <= 0 and VWAPWkZh >= 0;
def VWAPtestM = VWAPMnthZl <= 0 and VWAPMnthZh >= 0;

plot VWAPztestD = if VWAPtestD then 0 else NA;
plot VWAPztestW = if VWAPtestW then 0 else NA;
plot VWAPztestM = if VWAPtestM then 0 else NA;

def VWAPDev1PosTest = VWAPDayZl <= Dev1Pos and VWAPDayZh >= Dev1Pos;
def VWAPDev1NegTest = VWAPDayZl <= Dev1Neg and VWAPDayZh >= Dev1Neg;
def VWAPDev2PosTest = VWAPDayZl <= Dev2Pos and VWAPDayZh >= Dev2Pos;
def VWAPDev2NegTest = VWAPDayZl <= Dev2Neg and VWAPDayZh >= Dev2Neg;
def VWAPDev3PosTest = VWAPDayZl <= Dev3Pos and VWAPDayZh >= Dev3Pos;
def VWAPDev3NegTest = VWAPDayZl <= Dev3Neg and VWAPDayZh >= Dev3Neg;
def VWAPDev4PosTest = VWAPDayZl <= Dev4Pos and VWAPDayZh >= Dev4Pos;
def VWAPDev4NegTest = VWAPDayZl <= Dev4Neg and VWAPDayZh >= Dev4Neg;


zero.SetDefaultColor(Color.BLUE);
VWAPztestD.SetDefaultColor(Color.MAGENTA);
VWAPztestW.SetDefaultColor(Color.DARK_ORANGE);
VWAPztestM.SetDefaultColor(Color.RED);
VWAPztestD.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPztestW.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPztestM.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPztestD.SetLineWeight(1);
VWAPztestW.SetLineWeight(3);
VWAPztestM.SetLineWeight(5);

Dev1Pos.SetDefaultColor(Color.DARK_GRAY);
Dev1Neg.SetDefaultColor(Color.DARK_GRAY);
Dev2Pos.SetDefaultColor(Color.DARK_GRAY);
Dev2Neg.SetDefaultColor(Color.DARK_GRAY);
Dev3Pos.SetDefaultColor(Color.DARK_GRAY);
Dev3Neg.SetDefaultColor(Color.DARK_GRAY);
Dev4Pos.SetDefaultColor(Color.RED);
Dev4Neg.SetDefaultColor(Color.GREEN);

VWAPDayZc.SetDefaultColor(Color.YELLOW);
VWAPWkZ.SetDefaultColor(Color.DARK_ORANGE);
VWAPWkZ.SetLineWeight(2);
VWAPMnthZ.SetDefaultColor(Color.RED);
VWAPMnthZ.SetLineWeight(2);
#VWDayBandWidthU.SetDefaultColor(Color.GRAY);
#VWDayBandWidthD.SetDefaultColor(Color.GRAY);

VWAPDaytopsig.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPDaybotsig.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPDaytopsig.SetDefaultColor(Color.MAGENTA);
VWAPDaybotsig.SetDefaultColor(Color.MAGENTA);
VWAPWktopsig.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPWkbotsig.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPWktopsig.SetDefaultColor(Color.DARK_ORANGE);
VWAPWkbotsig.SetDefaultColor(Color.DARK_ORANGE);
VWAPWktopsig.SetLineWeight(3);
VWAPWkbotsig.SetLineWeight(3);
VWAPMnthtopsig.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPMnthbotsig.SetPaintingStrategy(PaintingStrategy.POINTS);
VWAPMnthtopsig.SetDefaultColor(Color.RED);
VWAPMnthbotsig.SetDefaultColor(Color.RED);
VWAPMnthtopsig.SetLineWeight(5);
VWAPMnthbotsig.SetLineWeight(5);
 
Nice work, Welkin... (y) I'm going to watch your lower indicator on one of my charts to see how well it performs... ;)
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
449 Online
Create Post

Similar threads

Similar threads

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