// === Helper Functions (must be above run) ===
var vwapPrice(int offset, int type)
{
switch (type) {
case 0: return priceClose(offset);
case 1: return priceOpen(offset);
case 2: return priceHigh(offset);
case 3: return priceLow(offset);
case 4: return (priceHigh(offset) + priceLow(offset)) / 2;
case 5: return (priceHigh(offset) + priceLow(offset) + priceClose(offset)) / 3;
case 6: return (priceHigh(offset) + priceLow(offset) + 2*priceClose(offset)) / 4;
default: return priceClose(offset);
}
}
var stdDevVWAP(int N, int offset, int type, var vwapValue)
{
var s = 0;
int i;
for (i = 0; i < N; i++) {
var p = vwapPrice(offset + i, type);
s += pow(p - vwapValue, 2);
}
return sqrt(s / N);
}
var VWAP_Z(int N, int offset, int type)
{
var sumPV = 0, sumVol = 0;
int i;
for (i = 0; i < N; i++) {
var price = vwapPrice(offset + i, type);
var volume = marketVol(offset + i);
sumPV += price * volume;
sumVol += volume;
}
return ifelse(sumVol > 0, sumPV / sumVol, 0);
}
// === Main Strategy/Indicator Function ===
function run()
{
set(PLOTNOW);
int N = 20;
int type = 0; // 0 = PRICE_CLOSE
var dev1 = 1, dev2 = 2, dev3 = 2.5;
var vwapVal = VWAP_Z(N, 0, type);
var stdDev = stdDevVWAP(N, 0, type, vwapVal);
plot("VWAP", vwapVal, LINE, BLACK);
plot("UpperBand1", vwapVal + dev1 * stdDev, LINE, RED);
plot("LowerBand1", vwapVal - dev1 * stdDev, LINE, RED);
plot("UpperBand2", vwapVal + dev2 * stdDev, LINE, GREEN);
plot("LowerBand2", vwapVal - dev2 * stdDev, LINE, GREEN);
plot("UpperBand3", vwapVal + dev3 * stdDev, LINE, BLUE);
plot("LowerBand3", vwapVal - dev3 * stdDev, LINE, BLUE);
}