# VWAPALOOZA
# By Prospectus @ http://readtheprospectus.worspress.com
#
# This Thinkscript calculates four different types of VWAP:
# OneDay (standard type), Rolling (N bar lookback), Bar
# Incremental (discrete N bar periods) and Volume Incremental
# (discrete N-shares-traded periods).
#H Kaczmarczyk added Deviation Lines & Clouds
declare upper;
#
# Check if we are on the current day:
#
def istoday = if getDay() == getLastDay() then 1 else 0;
#
# Input Rolling / Incremental period, VWAP type, and
# Averaging method ( (H+L)/2 or Close):
#
input Period = 20;
input DPeriod = 20;
input VWAPStdev1 = 1.0;
input VWAPStdev2 = 2.0;
input VWAPStdev3 = 3.0;
def n = Period;
input VolIncrement=20000;
def v=VolIncrement;
input VWAPType = {Rolling, BarIncremental, VolIncremental, default OneDay};
def type;
switch (VWAPType){
case Rolling:
type = 1;
case BarIncremental:
type = 0;
case OneDay:
type = 2;
case VolIncremental:
type=3;
}
input AverageMethod = {CLOSE, default H_L};
def num;
switch (AverageMethod){
case CLOSE:
num = close;
case H_L:
num = (high + low) / 2;
}
#
# Define volume for today only (other days zero):
#
def todayvol = if istoday then volume else 0;
#
# Calculate the P*V term for VWAP:
#
def pv = num * todayvol;
#
# Code for BarIncremental counter:
#
rec k = if k[1] == n then 1 else k[1] + 1;
#
# Code for VolIncremental volume sum:
#
rec volsum=if volsum[1]>v then volume else volsum[1]+volume;
#
# Code for VolIncremental price*volume:
#
rec pvsum =if volsum[1]>v then num*volume else pvsum[1] + num*volume;
#
# Now define the VolIncremental to display:
#
rec volinc=if volsum[1]==0 then num else if volsum[1]>v then pvsum[1]/volsum[1] else volinc[1];
#
# Now the final VWAP calculations:
#
rec calcVWAP = if type == 2 then TotalSum(pv) / TotalSum(todayvol) else if type == 1 then sum(num*volume, n) / sum(volume, n) else if type==3 then volinc else if type==0 and k == n then sum(num*volume, n) / sum(volume, n) else calcvwap[1];
#
# Define the plot:
#
plot VWAPALOOZA = calcvwap;
def vwapSD = StDev(CalcVWAP,DPeriod);
plot r1 = VWAPALOOZA+VWAPStdev1*vwapSD;
plot s1 = VWAPALOOZA-vwapStdev1*vwapSD;
plot r2 = VWAPALOOZA+VWAPStdev2*vwapSD;
plot s2 = VWAPALOOZA-VWAPStdev2*vwapSD;
plot r3 = VWAPALOOZA+VWAPStdev3*vwapSD;
plot s3 = VWAPALOOZA-VWAPStdev3*vwapSD;
r1.setDefaultColor(color.orange);
r2.setDefaultColor(color.pink);
r3.setDefaultColor(color.cyan);
s1.setDefaultColor(color.orange);
s2.setDefaultColor(color.pink);
s3.setDefaultColor(color.cyan);
r1.SetStyle(curve.SHORT_DASH);
r2.SetStyle(curve.SHORT_DASH);
r3.SetStyle(curve.SHORT_DASH);
s1.SetStyle(curve.SHORT_DASH);
s2.SetStyle(curve.SHORT_DASH);
s3.SetStyle(curve.SHORT_DASH);
Def HMax = Max(High,Low);
Def LMin = Min(High,Low);
addCloud(LMin,VWAPALOOZA,Color.Lime,Color.Black);
addCloud(HMax,VWAPALOOZA,Color.Black,Color.Pink);
#
# Formatting:
#
VWAPALOOZA.setdefaultcolor(color.white);
VWAPALOOZA.setstyle(curve.long_dash);
VWAPALOOZA.setlineweight(3);