input numDevDn = -2.0;
input numDevUp = 2.0;
input timeFrame = {default TWO_DAY, DAY, THREE_DAY,WEEK, MONTH};
input showbubbles = yes;
input bubbleoffset = 2;
def cap = getAggregationPeriod();
def errorInAggregation =
timeFrame == timeFrame.DAY and cap >= AggregationPeriod.WEEK or
timeFrame == timeFrame.WEEK and cap >= AggregationPeriod.MONTH;
assert(!errorInAggregation, "timeFrame should be not less than current chart aggregation period");
def yyyyMmDd = getYyyyMmDd();
def periodIndx;
switch (timeFrame) {
case DAY:
periodIndx = yyyyMmDd;
case TWO_DAY:
periodIndx = Floor((daysFromDate(first(yyyyMmDd)) + getDayOfWeek(first(yyyyMmDd))) / 2);
case THREE_DAY:
periodIndx = Floor((daysFromDate(first(yyyyMmDd)) + getDayOfWeek(first(yyyyMmDd))) / 3);
case WEEK:
periodIndx = Floor((daysFromDate(first(yyyyMmDd)) + getDayOfWeek(first(yyyyMmDd))) / 7);
case MONTH:
periodIndx = roundDown(yyyyMmDd / 100, 0);
}
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 VWAP = price;
#plot UpperBand = price + numDevUp * deviation;
#plot LowerBand = price + numDevDn * deviation;
VWAP.setDefaultColor(getColor(6));
#UpperBand.setDefaultColor(getColor(2));
#LowerBand.setDefaultColor(getColor(4));
####Bubbles
def n = BubbleOffset;
def n1 = n + 1;
AddChartBubble(showbubbles and IsNaN(close[n]) and !IsNaN(close[n1]) , price[n1] , "VWAP 2D: " + Round(price[n1] , 2), Color.GREEN);