# vwap_cross_0
# https://usethinkscript.com/threads/how-many-times-price-has-crossed-vwap-in-the-first-1-hour.11736/
# how many times price has crossed vwap in the first 1 hour?
#------------------------
# vwap
# TD Ameritrade IP Company, Inc. (c) 2011-2022
input numDevDn = -2.0;
input numDevUp = 2.0;
input timeFrame = {default DAY, WEEK, MONTH};
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 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));
input show_vwap_line = yes;
plot VWAP = price;
vwap.SetHiding(!show_vwap_line);
VWAP.setDefaultColor(getColor(0));
input show_vwap_boundry_lines = no;
plot UpperBand = price + numDevUp * deviation;
plot LowerBand = price + numDevDn * deviation;
UpperBand.setDefaultColor(getColor(2));
LowerBand.setDefaultColor(getColor(4));
UpperBand.SetHiding(!show_vwap_boundry_lines);
lowerband.SetHiding(!show_vwap_boundry_lines);
#---------------------------------
#def x = vwap crosses close;
def x = if (high >= vwap and low <= vwap) then 1 else 0;;
input start = 0930;
input end = 1030;
def period = if secondsfromTime(start) >= 0 and secondstillTime(end) > 0 then 1 else 0;
def period_start = if secondsfromTime(start) == 0 then 1 else 0;
def period_end = if secondsfromTime(end) == 0 then 1 else 0;
def cnt = if period_start and !x then 0
else if period_start and x then 1
else if (period and x) then cnt[1] + 1
else cnt[1];
addlabel(1, "VWAP crossings " + cnt, color.yellow);
input show_veretical_lines = yes;
addverticalline(show_veretical_lines and period_start, "-", color.cyan);
addverticalline(show_veretical_lines and period_end, "-", color.cyan);
#