```
# Price crossing above or below 9 EMA and VWAP
# By BenTen of useThinkScript.com
declare upper;
# Moving Average
input priceMA = close;
input lengthMA = 9;
input displace = 0;
input showBreakoutSignals = yes;
input price = close;
def EMA = ExpAverage(priceMA[-displace], lengthMA);
def UpSignal = priceMA crosses above EMA;
def DownSignal = priceMA crosses below EMA;
# VWAP
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 priceVWAP = volumeVwapSum / volumeSum;
def deviation = Sqrt(Max(volumeVwap2Sum / volumeSum - Sqr(priceVWAP), 0));
def VWAP = priceVWAP;
#plot UpperBand = priceVWAP + numDevUp * deviation;
#plot LowerBand = priceVWAP + numDevDn * deviation;
def UpVWAP = price > VWAP;
def DownVWAP = price < VWAP;
def bullish_signal = UpSignal and UpVWAP;
def bearish_signal = DownSignal and DownVWAP;
# Plot Signals
plot bullish = bullish_signal;
bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
bullish.SetDefaultColor(Color.CYAN);
bullish.SetLineWeight(3);
plot bearish = bearish_signal;
bearish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearish.SetDefaultColor(Color.CYAN);
bearish.SetLineWeight(3);
```