• Get $30 off VIP with code SUMMER30. Ends July 27. Happy trading!

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));
 
Last edited:

AGD

New member

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
 

horserider

Well-known member
VIP
@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

Camelotnite

New member
VIP
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);
#=====================================
 
Last edited by a moderator:

diazlaz

Well-known member
2019 Donor
VIP
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
 

ansheth

New member
2019 Donor
VIP
I want to create a scan where I am able to at the end of the day, see which stocks closed with a VScore of +/-2.5?

Code:
declare lower;
input anchorDate = 20180801;
input barsGoBack = 120;
input showStopLabel = yes;
input devStop = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree};

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;
}



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);
 
Last edited by a moderator:

tomsk

Well-known member
VIP
@ansheth As requested, I have converted your VScore study to a scan for stocks with a VScore of +/- 2.5. On the S&P 500, I have tested this scan and obtained 25 results. Remember to use Daily aggregation

Code:
input anchorDate = 20180901;
input barsGoBack = 120;
input showStopLabel = yes;
input devStop = {default One, Two, Three, Zero, NegOne, NegTwo, NegThree};
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;
}

def postAnchorDate = GetYYYYMMDD() >= anchorDate;
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));
def VScore = if (((price - close)(-1))/deviation) > 5 or (((price - close)(-1))/deviation) < -5
             then 0
             else (((price - close)*(-1))/(deviation));

plot scan = VScore > 2.5 or VScore < -2.5;
 

VicD

Member
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."
 

Harleym2009

New member
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
 

horserider

Well-known member
VIP
@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.
 

VicD

Member
@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.
 

allnetbrett

New member
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
 

megahead34

New member
@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.
 

horserider

Well-known member
VIP
@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

New member
@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.
 

frick53

New member
VIP
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
 

bp805

New member
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);[img]https://i.imgur.com/FFh8FAz.jpg[/img]
 

Similar threads

Top