# ema_vwap_dist
#https://usethinkscript.com/threads/label-that-shows-of-9ema-from-the-vwap.15263/
#Label that shows % of 9ema from the VWAP.
def na = Double.NaN;
def bn = BarNumber();
#def lastbar = !isnan(close[0]) and isnan(close[-1]);
#--------------------
def price2 = close;
input ma1_len = 9;
input ma1_type = AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price2, ma1_len);
input show_lines = yes;
plot z1 = if show_lines then ma1 else na;
z1.SetDefaultColor(color.cyan);
#z1.setlineweight(1);
z1.HideBubble();
addlabel(show_lines, "AVG", z1.TakeValueColor());
#--------------------
# VWAP
# TD Ameritrade IP Company, Inc. (c) 2011-2023
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));
plot VWAP = price;
input show_vwap_bands = no;
plot UpperBand = if show_vwap_bands then (price + numDevUp * deviation) else na;
plot LowerBand = if show_vwap_bands then (price + numDevDn * deviation) else na;
VWAP.SetDefaultColor(color.yellow);
UpperBand.SetDefaultColor(GetColor(2));
LowerBand.SetDefaultColor(GetColor(4));
addlabel(1, "VWAP", vwap.TakeValueColor());
#--------------------
def diff = ma1 - vwap;
def diff_per = round(100*diff/vwap,2);
input percent_trip = 1.0;
addlabel(1, diff_per + " %", (if diff_per < percent_trip then color.white else color.green));
addlabel(1, "set % " + percent_trip , color.yellow);
#--------------------
#