Skip to main content

VWAP (Volume Weighted Average Price)

What is VWAP?​

VWAP (volume weighted average price) is the average price a security has traded at since a starting point, usually the session open, with each price weighted by the volume traded at it. On an intraday chart it is a single line over the candles that shows what the average share has cost so far today.

A dark navy intraday chart of three simulated trading days of five-minute candles with a yellow VWAP line that restarts each morning, shaded blue standard deviation bands around it, a purple equal-weight average for comparison, and green and red volume columns underneath that are tallest at each open and close

Three simulated trading days of five-minute candles with session VWAP, ±1σ and ±2σ bands and volume. Try the interactive version.

Key takeaways
  • VWAP is the running total of price × volume divided by the running total of volume, counted from an anchor bar.
  • Session VWAP restarts at each open; anchored VWAP starts at a bar you choose and carries on across days.
  • Bands at 1 and 2 standard deviations show how far price is from the average in units of the session's own spread.
  • It began as a benchmark for judging trade execution, and is also read as an intraday fair-value line.
  • It needs real volume and an anchor, and it moves less and less as a session goes on.

This page explains how VWAP is calculated, read and drawn. It is not investment advice.

How to calculate VWAP​

VWAP is the sum of price times volume divided by the sum of volume, over every bar (or trade) from the anchor up to now.

On a bar chart, each bar's price is usually its typical price, the average of its high, low and close:

Pi=Hi+Li+Ci3VWAPt=∑i=atPi Vi∑i=atViP_i = \frac{H_i + L_i + C_i}{3} \qquad \text{VWAP}_t = \frac{\sum_{i=a}^{t} P_i \, V_i}{\sum_{i=a}^{t} V_i}

where ViV_i is the bar's volume and aa is the anchor bar. The sums keep growing, so VWAP has no length setting and no warm-up: it has a value from the first bar.

Exchanges and trading desks calculate it from individual trades instead, as the sum of each trade's price times its size divided by the total size. That is the exact figure. The typical-price version is an approximation for when you only have bars, and it gets closer to the trade-based figure as bars get shorter.

Worked example: the first 30 minutes​

Here are six five-minute bars from a session open, with the running sums. Prices are in dollars and volumes in shares.

BarHighLowCloseVolumeTypical priceP × VCumulative P × VCumulative volumeVWAP
09:30100.8099.90100.504,200100.40421,680421,6804,200100.40
09:35100.90100.30100.602,600100.60261,560683,2406,800100.48
09:40101.20100.60101.202,100101.00212,100895,3408,900100.60
09:45101.30100.80100.901,500101.00151,5001,046,84010,400100.66
09:50101.00100.40100.701,800100.70181,2601,228,10012,200100.66
09:55100.70100.00100.202,400100.30240,7201,468,82014,600100.60
  • At 09:55, VWAP = 1,468,820 ÷ 14,600 = 100.604, or 100.60.
  • The plain average of the six typical prices is 604.00 ÷ 6 = 100.67. VWAP is lower because the heaviest bar, the 4,200-share opening bar, traded at the lowest typical price apart from the last bar.
  • The last close, 100.20, is 0.40 below VWAP, or −0.40%.
  • The first bar's VWAP is its own typical price, because there is nothing else to average yet.

Session VWAP vs anchored VWAP​

Session VWAP and anchored VWAP use the same formula and differ only in where the sums start.

Session VWAPAnchored VWAP
Starts atThe first bar of each sessionA bar you choose
ResetsEvery sessionNever; it runs on until you move the anchor
Typical anchorsThe regular-hours openAn earnings release, a gap, a swing high or low, the start of a week or year
AnswersWhat has the average share cost today?What has the average share cost since that event?

Session VWAP is the default on most intraday charts. Conventions differ on what a session is: some charts start at the regular open (09:30 New York time for US shares), some include pre-market trading, and markets that trade nearly 24 hours, such as many futures, or around the clock, such as cryptocurrencies, need a chosen reset time, such as the exchange's daily settlement or midnight UTC. Two charts of the same instrument can therefore show different VWAPs.

Anchored VWAP is the same running average started somewhere meaningful. Anchored at a sharp low, it shows the average price paid by everyone who has bought or sold since that low. Some charting software anchors at the first bar it has loaded, which makes the line depend on how much history is on screen.

VWAP standard deviation bands​

VWAP bands are lines a set number of standard deviations (σ) above and below VWAP, so they widen when prices since the anchor have been spread out and narrow when they have been tight.

The usual σ is the volume-weighted standard deviation of typical price around VWAP, over the same bars:

σt=∑i=atVi (Pi−VWAPt)2∑i=atVi=∑i=atPi2Vi∑i=atVi−VWAPt2\sigma_t = \sqrt{\frac{\sum_{i=a}^{t} V_i \,(P_i - \text{VWAP}_t)^2}{\sum_{i=a}^{t} V_i}} = \sqrt{\frac{\sum_{i=a}^{t} P_i^2 V_i}{\sum_{i=a}^{t} V_i} - \text{VWAP}_t^2}

The second form needs only one more running sum, so the bands update as cheaply as VWAP itself. Bands are commonly drawn at ±1σ and ±2σ, sometimes ±3σ.

In the worked example, σ at 09:55 is 0.259. The ±1σ band runs from 100.35 to 100.86 and the ±2σ band from 100.09 to 101.12, so the close of 100.20 sits between the lower two lines, 1.6σ below VWAP.

Conventions vary. Some charts use the close instead of the typical price, some take σ without volume weights, and some draw bands a fixed percentage away from VWAP. The numbers on two charts will differ unless they use the same method.

Standard deviation bands assume nothing about where price will go. A close beyond 2σ is unusual for that session's spread so far; it doesn't mean the price must come back.

How to read VWAP​

Read VWAP as the session's average price paid: where price sits against it, which way the line slopes and how far price has stretched from it.

Diagram of a simulated trading day of 39 ten-minute candles with a VWAP line starting at the first bar, shaded one and two standard deviation bands that widen through the morning, labels for the anchor, a morning stretch above VWAP, a midday pullback to VWAP, a close beyond the upper two-sigma band and the flat afternoon VWAP, and volume columns underneath that are tallest at the open and close

These are the conventions traders use. None of them is a reliable signal on its own.

  • Above or below. Price above session VWAP means the latest trades are higher than the average paid today, so the average buyer is in profit for now; below it, the average seller is. Many traders read a session spent mostly above VWAP as an up day and mostly below as a down day.
  • Slope. A rising VWAP means trading has been happening at higher prices as the day goes on. A flat VWAP with price crossing it often marks a range-bound day.
  • Pullbacks to VWAP. On a trending day, price often comes back to VWAP before carrying on. Traders who watch VWAP may buy or sell there, which can make it act as support or resistance, but price also passes straight through it.
  • Stretch from VWAP. Distance from VWAP, in per cent or in σ, shows how far price has run from the session's average. Mean-reversion traders look for moves back towards VWAP from beyond the outer band; trend traders read a close outside the band as strength.
  • Late in the session. By the afternoon, the day's cumulative volume is large and each new bar adds a small share of it, so VWAP barely moves. A sharp move late in the day can leave price far from a nearly flat VWAP.

VWAP as an execution benchmark​

VWAP started as a yardstick for how well a large order was traded: buying below the day's VWAP, or selling above it, counts as a better-than-average result.

Berkowitz, Logue and Noser (1988) proposed measuring the cost of institutional trades against the day's volume weighted average price, because it reflects all the trading that day rather than one moment's quote. The idea spread across buy-side desks, and brokers built VWAP algorithms that split a large order into small pieces timed to follow the day's expected volume pattern.

For a buy order, the shortfall against VWAP in basis points (hundredths of a per cent) is:

slippage (bp)=pˉfill−VWAPVWAP×10,000\text{slippage (bp)} = \frac{\bar{p}_{\text{fill}} - \text{VWAP}}{\text{VWAP}} \times 10{,}000

where pˉfill\bar{p}_{\text{fill}} is the order's average fill price; a positive number means the buyer paid more than the market average. For a sell order the sign flips. A buy of 10,000 shares filled at an average of 100.65 on the example's 09:55 VWAP of 100.604 is 4.6 bp worse than VWAP.

The benchmark has known weaknesses:

  • A large order moves its own benchmark. If an order is a big share of the day's volume, its own trades pull VWAP towards its fill price, so it looks better against VWAP than it was.
  • It rewards trading with the crowd. An order spread evenly through the day will finish close to VWAP whether or not trading at all was a good idea.
  • Volume must be forecast. A VWAP algorithm has to guess how much will trade in each part of the day. Białkowski, Darolles and Le Fol (2008) showed that forecasting intraday volume more accurately brings execution prices closer to VWAP.

Trading volume through the day typically follows a U shape: heavy at the open and close and lighter around midday, a pattern documented in US shares by Jain and Joh (1988). That shape is one reason session VWAP moves quickly in the first hour and slowly after lunch.

VWAP vs moving averages​

VWAP weights prices by volume and runs from a fixed anchor; a simple or exponential moving average weights a fixed number of recent bars and ignores volume.

VWAPSimple moving average (SMA)Exponential moving average (EMA)
WeightsEach bar by its volumeEach bar equallyRecent bars more, falling off geometrically
WindowFrom the anchor to now, growingThe last n barsAll past bars, effectively the last few n
Needs volumeYesNoNo
Speed of responseFast after the anchor, slow late in the sessionConstantConstant, faster than an SMA of the same n
Typical useIntraday average price, execution benchmarkTrend direction on any timeframeTrend direction where faster reaction is wanted
TimeframesIntraday (session) or from an event (anchored)AnyAny

Use VWAP when the question is "what has the average trade cost since the open, or since this event?". Use a moving average when you want a smoothed price that reacts at the same pace all day and on daily or weekly charts. In the demo, switch the comparison between an equal-weight average from the same anchor, which isolates the effect of the volume weights, and a 20-bar SMA, which shows the different window as well.

Limitations of VWAP​

VWAP describes what has already traded, so it lags, it depends on its anchor, and it is only as good as the volume behind it.

  • It is intraday by nature. Session VWAP restarts every day, so a daily-bar chart can't show it, and on multi-day charts the line jumps at each reset.
  • It flattens. The longer a session runs, the less each new bar can move the cumulative average.
  • It needs volume. Without volume, VWAP becomes an equal-weight average. Spot currency (FX) trading is spread across many dealers and venues with no single consolidated volume figure, so FX charts usually weight by a single venue's volume or by tick count, the number of price changes, which is a stand-in for volume.
  • It depends on the data. Bar-based VWAP differs from trade-based VWAP, and charts that include pre-market or after-hours trades, or use a different session time, will show a different line.
  • It describes past trades. VWAP summarises what has already traded and says nothing about where price will go next.

Common VWAP mistakes​

Most VWAP mistakes come from forgetting that it is a running average from a particular anchor.

  • Using session VWAP on daily bars. One bar per day gives one point per session; the indicator has nothing to average.
  • Comparing VWAPs with different sessions. A chart that starts at the pre-market open and one that starts at the regular open give different lines for the same stock.
  • Treating VWAP as a price floor or ceiling. Many traders watch it, but price crosses it every day.
  • Reading the bands as probabilities. Intraday prices are not normally distributed and the bands are built from a handful of bars early in the session, so "95% of prices inside ±2σ" does not hold.
  • Forgetting the anchor. An anchored VWAP from the wrong bar, or one anchored at whatever history happens to be loaded, answers a different question from the one you meant to ask.
  • Weighting by the wrong volume. On instruments without consolidated volume, check what the volume column actually counts before trusting the weights.

How to create a VWAP chart in JavaScript, React or Angular​

The demo below simulates three trading days of 78 five-minute bars with a U-shaped volume pattern and recomputes the VWAP, both bands, the comparison line and the readout from all 234 bars every time you change a control. SciChart.js draws the candles, volume columns, bands and lines with WebGL and WebGPU; the VWAP maths is plain JavaScript.

Choose Anchor to switch between a session VWAP that resets each morning and an anchored VWAP. When anchored, move the Anchor bar slider or drag the dashed anchor line along the chart; it snaps to the nearest bar. Band multiplier sets the inner band (the outer band is twice as wide), and 0 hides both. Compare with adds an equal-weight average from the same anchor or a 20-bar simple moving average. New simulated days draws a fresh three days of data. The readout gives the latest VWAP, the distance of the last close from it in per cent and in σ, and the volume since the anchor. Scroll to zoom, drag to pan, double-click to reset and hover for values.

Here is the code for this demo. The simulation and the VWAP maths are plain JavaScript; SciChart.js draws the candles, the volume, the bands and the lines, and handles the draggable anchor. The React and Angular versions below draw a session VWAP with ±1σ and ±2σ bands over your own bars.

// Candles and volume with a VWAP line, standard deviation bands and a draggable anchor, with SciChart.js
const {
SciChartSurface,
SciChartVerticalGroup,
NumericAxis,
NumberRange,
EAxisAlignment,
EAutoRange,
EXyDirection,
ECoordinateMode,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
ELabelPlacement,
OhlcDataSeries,
FastCandlestickRenderableSeries,
XyDataSeries,
XyyDataSeries,
FastLineRenderableSeries,
FastBandRenderableSeries,
FastColumnRenderableSeries,
TextAnnotation,
VerticalLineAnnotation,
SciChartJsNavyTheme,
LegendModifier,
ELegendPlacement,
ELegendOrientation,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- VWAP maths (plain JavaScript, no library needed) ---
// typical price = (high + low + close) / 3
// VWAP = sum(typical price * volume) / sum(volume), summed from the anchor bar
// sigma = volume-weighted standard deviation of typical price around VWAP, over the same bars
// resetEachSession: start the sums again at each day's first bar (session VWAP); otherwise start at bar `anchor`
// (anchored VWAP) and leave earlier bars empty (NaN).
function vwapWithBands(bars, anchor, resetEachSession) {
const vwap = [];
const sigma = [];
const cumulativeVolume = [];
const equalWeight = []; // the plain average of typical price over the same bars, for comparison
let sumPV = 0;
let sumP2V = 0;
let sumV = 0;
let sumP = 0;
let count = 0;
for (let i = 0; i < bars.length; i++) {
const bar = bars[i];
const startsHere = resetEachSession ? i === 0 || bar.session !== bars[i - 1].session : i === anchor;
if (startsHere) {
sumPV = sumP2V = sumV = sumP = count = 0;
}
if (!resetEachSession && i < anchor) {
vwap.push(NaN);
sigma.push(NaN);
cumulativeVolume.push(NaN);
equalWeight.push(NaN);
continue;
}
const typical = (bar.high + bar.low + bar.close) / 3;
sumPV += typical * bar.volume;
sumP2V += typical * typical * bar.volume;
sumV += bar.volume;
sumP += typical;
count += 1;
const mean = sumPV / sumV;
vwap.push(mean);
sigma.push(Math.sqrt(Math.max(0, sumP2V / sumV - mean * mean)));
cumulativeVolume.push(sumV);
equalWeight.push(sumP / count);
}
return { vwap, sigma, cumulativeVolume, equalWeight };
}

// A simple moving average of the close over `length` bars, running across days
function simpleMovingAverage(bars, length) {
let sum = 0;
return bars.map((bar, i) => {
sum += bar.close;
if (i >= length) sum -= bars[i - length].close;
return i >= length - 1 ? sum / length : NaN;
});
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOURS = { up: "#26A69A", down: "#EF5350", vwap: "#F6E05E", band: "#50C7E0", compare: "#C792EA", anchor: "#FFFFFF" };
const pad = (n) => String(n).padStart(2, "0");
const clock = (minutes) => `${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`;
const barAt = (x) => {
const s = Math.floor(Math.round(x) / SLOT);
const b = Math.round(x) - s * SLOT;
return s >= 0 && s < SESSIONS && b >= 0 && b < BARS_PER_SESSION ? s * BARS_PER_SESSION + b : -1;
};
const barName = (i) => `Day ${bars[i].session + 1} ${clock(bars[i].minutes)}`;
const timeLabel = (x) => {
const i = barAt(x);
return i < 0 ? "" : barName(i);
};

// 1. The price pane: candles, VWAP, its bands and the comparison line
const price = await SciChartSurface.create(ui.priceDiv, { theme });
const priceX = new NumericAxis(price.wasmContext, { drawLabels: false, drawMinorGridLines: false });
const priceY = new NumericAxis(price.wasmContext, {
axisAlignment: EAxisAlignment.Right,
autoRange: EAutoRange.Always, // fit the visible bars
growBy: new NumberRange(0.08, 0.12),
labelPrecision: 2,
drawMinorGridLines: false
});
price.sciChartSurface.xAxes.add(priceX);
price.sciChartSurface.yAxes.add(priceY);
const ohlc = new OhlcDataSeries(price.wasmContext, { dataSeriesName: "Price" });
const vwapData = new XyDataSeries(price.wasmContext, { dataSeriesName: "VWAP", containsNaN: true });
const innerBand = new XyyDataSeries(price.wasmContext, { dataSeriesName: "Inner band (k σ)", containsNaN: true });
const outerBand = new XyyDataSeries(price.wasmContext, { dataSeriesName: "Outer band (2k σ)", containsNaN: true });
const compareData = new XyDataSeries(price.wasmContext, { dataSeriesName: "Comparison", containsNaN: true });
const band = (dataSeries, fill, thickness, dash) =>
new FastBandRenderableSeries(price.wasmContext, {
dataSeries,
fill,
fillY1: fill,
stroke: COLOURS.band,
strokeY1: COLOURS.band,
strokeThickness: thickness,
strokeDashArray: dash,
strokeY1DashArray: dash
});
const outerBandSeries = band(outerBand, "#50C7E00D", 1, [3, 4]);
const innerBandSeries = band(innerBand, "#50C7E01F", 1.5, [6, 4]);
const compareLine = new FastLineRenderableSeries(price.wasmContext, { dataSeries: compareData, stroke: COLOURS.compare, strokeThickness: 2 });
price.sciChartSurface.renderableSeries.add(
outerBandSeries,
innerBandSeries,
new FastCandlestickRenderableSeries(price.wasmContext, {
dataSeries: ohlc,
dataPointWidth: 0.7,
brushUp: COLOURS.up,
strokeUp: COLOURS.up,
brushDown: COLOURS.down,
strokeDown: COLOURS.down,
strokeThickness: 1
}),
compareLine,
new FastLineRenderableSeries(price.wasmContext, { dataSeries: vwapData, stroke: COLOURS.vwap, strokeThickness: 2.5 })
);

// 2. The volume pane: one column per bar, green when the bar closed up and red when it closed down
const volume = await SciChartSurface.create(ui.volumeDiv, { theme });
const volumeX = new NumericAxis(volume.wasmContext, { drawMinorGridLines: false });
volumeX.labelProvider.formatLabel = timeLabel;
volumeX.labelProvider.formatCursorLabel = timeLabel;
volume.sciChartSurface.xAxes.add(volumeX);
volume.sciChartSurface.yAxes.add(
new NumericAxis(volume.wasmContext, {
axisAlignment: EAxisAlignment.Right,
autoRange: EAutoRange.Always,
growBy: new NumberRange(0, 0.1),
axisTitle: "Volume",
labelPrecision: 0,
drawMinorGridLines: false
})
);
volume.sciChartSurface.yAxes.get(0).labelProvider.formatLabel = (v) => (v >= 1000 ? `${Math.round(v / 1000)}K` : `${Math.round(v)}`);
const upVolume = new XyDataSeries(volume.wasmContext, { dataSeriesName: "Volume (up bar)", containsNaN: true });
const downVolume = new XyDataSeries(volume.wasmContext, { dataSeriesName: "Volume (down bar)", containsNaN: true });
const columns = (dataSeries, colour) =>
new FastColumnRenderableSeries(volume.wasmContext, { dataSeries, dataPointWidth: 0.7, fill: colour + "B3", stroke: colour, strokeThickness: 0 });
volume.sciChartSurface.renderableSeries.add(columns(upVolume, COLOURS.up), columns(downVolume, COLOURS.down));

// Day labels, and the anchor line: drag it along the chart to move the anchor
const dayLabels = [];
for (let s = 0; s < SESSIONS; s++) {
dayLabels.push(
new TextAnnotation({
x1: s * SLOT,
y1: 0, // relative y: 0 is the top of the chart
yCoordinateMode: ECoordinateMode.Relative,
text: `Day ${s + 1}`,
fontSize: 13,
textColor: "#C8D3E6",
horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
verticalAnchorPoint: EVerticalAnchorPoint.Top,
yCoordShift: 44 // below the legend
})
);
}
price.sciChartSurface.annotations.add(...dayLabels);
const anchorLine = new VerticalLineAnnotation({
x1: bars[Number(ui.anchor.value)].x,
stroke: COLOURS.anchor,
strokeThickness: 2,
strokeDashArray: [4, 3],
isEditable: true,
showLabel: true,
labelPlacement: ELabelPlacement.TopRight,
labelValue: "Anchor (drag me)",
axisLabelFill: COLOURS.anchor,
isHidden: true
});
price.sciChartSurface.annotations.add(anchorLine);

// A short tooltip: the bar's time, its prices, and each visible line's value (a band shows lower to upper)
function tooltipLines(seriesInfos) {
const lines = seriesInfos.length ? [timeLabel(seriesInfos[0].xValue)] : [];
for (const info of seriesInfos) {
if (!info.renderableSeries.isVisible || !info.isWithinDataBounds || isNaN(info.yValue)) continue;
if ("formattedCloseValue" in info) {
lines.push(`O ${info.formattedOpenValue} H ${info.formattedHighValue} L ${info.formattedLowValue} C ${info.formattedCloseValue}`);
} else if ("formattedY1Value" in info) {
lines.push(`${info.seriesName} ${info.formattedY1Value} to ${info.formattedYValue}`);
} else {
lines.push(`${info.seriesName} ${info.formattedYValue}`);
}
}
return lines;
}

// Line up the panes, zoom and pan them together in time, and share one crosshair
const group = new SciChartVerticalGroup();
group.addSurfaceToGroup(price.sciChartSurface);
group.addSurfaceToGroup(volume.sciChartSurface);
for (const surface of [price.sciChartSurface, volume.sciChartSurface]) {
surface.chartModifiers.add(
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection }),
new CursorModifier({
showTooltip: surface === price.sciChartSurface,
showAxisLabels: true,
modifierGroup: "vwap",
tooltipDataTemplate: tooltipLines
})
);
}
// The legend lists each series by name. Its items are made when it is added, so it is replaced when names change.
let legend;
function refreshLegend() {
if (legend) price.sciChartSurface.chartModifiers.remove(legend, true);
legend = new LegendModifier({ placement: ELegendPlacement.TopLeft, orientation: ELegendOrientation.Horizontal, showCheckboxes: false });
price.sciChartSurface.chartModifiers.add(legend);
// Hidden series (bands at 0, no comparison line) stay out of the legend
price.sciChartSurface.renderableSeries.asArray().forEach((rs) => legend.includeSeries(rs, rs.isVisible));
}
let syncing = false;
const link = (from, to) =>
from.visibleRangeChanged.subscribe(() => {
if (syncing) return;
syncing = true;
to.visibleRange = from.visibleRange;
syncing = false;
});
link(priceX, volumeX);
link(volumeX, priceX);

// --- Fill the series from the maths, and the readout ---
// Line data gets a NaN in each overnight gap, so a session VWAP stops at the close instead of joining the next day
function lineData(dataSeries, values) {
dataSeries.clear();
bars.forEach((bar, i) => {
if (i > 0 && bar.session !== bars[i - 1].session) dataSeries.append(bar.x - 1, NaN);
dataSeries.append(bar.x, values[i]);
});
}
// The same for a band: an upper (y) and a lower (y1) value per bar
function bandData(dataSeries, upper, lower) {
dataSeries.clear();
bars.forEach((bar, i) => {
if (i > 0 && bar.session !== bars[i - 1].session) dataSeries.append(bar.x - 1, NaN, NaN);
dataSeries.append(bar.x, upper[i], lower[i]);
});
}

function update() {
const anchored = ui.mode.value === "anchored";
const anchor = Number(ui.anchor.value);
const k = Number(ui.bands.value);
ui.anchor.disabled = !anchored;
ui.anchorOut.textContent = barName(anchor);
ui.bandsOut.textContent = k > 0 ? `±${k}σ and ±${2 * k}σ` : "off";
anchorLine.isHidden = !anchored;
anchorLine.x1 = bars[anchor].x;

const { vwap, sigma, cumulativeVolume, equalWeight } = vwapWithBands(bars, anchor, !anchored);
lineData(vwapData, vwap);
bandData(innerBand, vwap.map((v, i) => v + k * sigma[i]), vwap.map((v, i) => v - k * sigma[i]));
bandData(outerBand, vwap.map((v, i) => v + 2 * k * sigma[i]), vwap.map((v, i) => v - 2 * k * sigma[i]));
innerBandSeries.isVisible = k > 0;
outerBandSeries.isVisible = k > 0;
const compare = ui.compare.value;
compareLine.isVisible = compare !== "none";
compareData.dataSeriesName = compare === "sma20" ? "20-bar SMA" : "Equal-weight average";
innerBand.dataSeriesName = `VWAP ±${k}σ`;
outerBand.dataSeriesName = `VWAP ±${2 * k}σ`;
refreshLegend();
lineData(compareData, compare === "sma20" ? simpleMovingAverage(bars, 20) : equalWeight);

// The readout: where the last close sits against VWAP, in per cent and in standard deviations
const last = bars.length - 1;
const close = bars[last].close;
const distance = close - vwap[last];
const signed = (value, digits) => `${value >= 0 ? "+" : "−"}${Math.abs(value).toFixed(digits)}`;
ui.readout.innerHTML =
`<strong>${barName(last)}</strong> · Close ${close.toFixed(2)} · VWAP ${vwap[last].toFixed(2)} · ` +
`Close is ${signed((distance / vwap[last]) * 100, 2)}% and ${sigma[last] > 0 ? signed(distance / sigma[last], 1) : "0.0"}σ from VWAP · ` +
`σ ${sigma[last].toFixed(2)} · Volume since the ${anchored ? "anchor" : "open"} ${cumulativeVolume[last].toLocaleString("en-US")}`;
}

// Candles and volume: rebuilt for new simulated days
function loadBars() {
ohlc.clear();
upVolume.clear();
downVolume.clear();
for (const bar of bars) {
ohlc.append(bar.x, bar.open, bar.high, bar.low, bar.close);
const up = bar.close >= bar.open;
upVolume.append(bar.x, up ? bar.volume : NaN);
downVolume.append(bar.x, up ? NaN : bar.volume);
}
update();
}

// Dragging the anchor line snaps it to the nearest bar and moves the slider with it
anchorLine.dragEnded.subscribe(() => {
let x = Math.round(anchorLine.x1);
let i = barAt(x);
while (i < 0 && x < bars[bars.length - 1].x) i = barAt(++x); // dropped in a gap: use the next day's first bar
if (i < 0) i = bars.length - 1;
ui.anchor.value = String(i);
update();
});
ui.mode.addEventListener("change", update);
ui.anchor.addEventListener("input", update);
ui.bands.addEventListener("input", update);
ui.compare.addEventListener("change", update);
ui.reseed.addEventListener("click", () => {
seed += 1;
bars = simulateBars(seed);
loadBars();
});
loadBars();
priceX.visibleRange = new NumberRange(-2, bars[bars.length - 1].x + 2);

Key points:

  • VWAP, σ and the equal-weight average come from one pass over the bars with four running sums (vwapWithBands in the demo). Resetting the sums at each session's first bar gives session VWAP; starting them at the anchor bar gives anchored VWAP.
  • Each band is a FastBandRenderableSeries over an XyyDataSeries, with the upper line as y and the lower as y1. The candles are a FastCandlestickRenderableSeries and the volume two FastColumnRenderableSeries, one for up bars and one for down bars.
  • The x axis is a bar number with a three-slot gap between days. A NaN in each gap, with containsNaN: true on the data series, stops a session VWAP from joining one day's close to the next day's open.
  • The anchor is a VerticalLineAnnotation with isEditable: true; its dragEnded event snaps it to a bar and recalculates (see editable annotations). SciChartVerticalGroup lines up the price and volume panes, and each x-axis's visibleRangeChanged event keeps them on the same bars.

See it in the demo app: JavaScript multi-pane stock chart · React multi-pane stock chart · Angular multi-pane stock chart. Related techniques: the React line chart, React synchronised multi-chart and React chart annotations.

Go deeper: SciTrader.js VWAP indicator documentation, the candlestick series documentation, the band series documentation, and the learning center guides to the candlestick chart, footprint chart and market depth. For the industry, see SciChart for financial and trading applications.

Building a full trading app?​

SciTrader.js, SciChart's financial charts SDK, has VWAP built in as one of its technical indicators. Its VWAP indicator page shows how to add it to a candlestick chart in JavaScript or React, and explains how it is anchored: at the first loaded candle rather than at each session open. Beside it you get the other indicators, drawing tools, multiple panes and live data feeds; see add technical indicators for the full set. See what it can do on the JavaScript stock charts page.

Frequently asked questions​

What is VWAP?​

VWAP (volume weighted average price) is the average price a security has traded at since a starting point, usually the session open, with each price weighted by the volume traded at it. It answers the question: what has the average share cost today? Traders draw it as a line over an intraday price chart, and institutions use it to judge how well a large order was executed.

How is VWAP calculated?​

For each bar, take the typical price, (high + low + close) / 3, and multiply it by the bar's volume. Add these products up from the first bar of the session, and divide by the total volume over the same bars. Repeat on every new bar, so VWAP is a running total, not a fixed-length average. Calculated from individual trades instead of bars, it is the sum of each trade's price times its size, divided by the total size.

What is the difference between VWAP and anchored VWAP?​

The formula is the same; only the starting bar differs. Standard (session) VWAP restarts at each session open. Anchored VWAP starts at a bar the trader chooses, such as an earnings release, a gap or a swing high or low, and runs on across sessions from there, so it shows the average price paid by everyone who traded since that event.

What are VWAP bands?​

VWAP bands are lines drawn a set number of standard deviations above and below VWAP, most often 1 and 2, sometimes 3. The standard deviation is usually the volume-weighted spread of typical prices around VWAP since the same anchor. They show how far price has moved from the average in units of that day's own spread. Some charts use fixed percentage bands instead.

Is VWAP better than a moving average?​

VWAP weights prices by volume and runs from a fixed anchor, so it describes the average price paid within one session and suits intraday charts and execution benchmarks. A simple or exponential moving average weights a fixed number of recent bars without volume, so it works on any timeframe and keeps reacting at the same speed, while session VWAP slows down as the day goes on.

How do I add a VWAP line to a chart in JavaScript?​

Loop over your bars once, keeping running sums of typical price times volume, typical price squared times volume, and volume. VWAP is the first sum divided by the volume sum, and the band width comes from the second. Reset the sums at each session open or at your anchor. With SciChart.js, draw the candles with FastCandlestickRenderableSeries, the VWAP with a FastLineRenderableSeries, and each band with a FastBandRenderableSeries over an XyyDataSeries; the same code runs in React with scichart-react and in Angular with scichart-angular.

Sources​

  • Berkowitz, S. A., Logue, D. E. and Noser, E. A. (1988), The total cost of transactions on the NYSE. The Journal of Finance, 43(1), 97–112. Proposes the day's volume weighted average price as the benchmark for measuring the cost of institutional trades.
  • Harris, L. (2003), Trading and Exchanges: Market Microstructure for Practitioners. Oxford University Press. Trading costs, execution benchmarks and order-splitting strategies.
  • Białkowski, J., Darolles, S. and Le Fol, G. (2008), Improving VWAP strategies: a dynamic volume approach. Journal of Banking & Finance, 32(9), 1709–1722. How intraday volume forecasts affect VWAP execution.
  • Jain, P. C. and Joh, G.-H. (1988), The dependence between hourly prices and trading volume. Journal of Financial and Quantitative Analysis, 23(3), 269–283. Documents the higher trading volume near the open and close of the US trading day.
  • U.S. Securities and Exchange Commission, Investor.gov, Volume-weighted average price (VWAP).