Session VWAP: TradingView (Pine Script) to MT5 (MQL5)

Short answer

VWAP is the sum of price × volume divided by the sum of volume since the session started. MetaTrader 5 has no VWAP, so keep the two running sums in calculation buffers and reset them each day. The lines differ in practice over where the day starts and what volume means.

VWAP is the volume-weighted average price since the start of the current session: the sum of price × volume divided by the sum of volume, both reset when a new day begins. TradingView has ta.vwap and an anchored VWAP indicator; MetaTrader 5 has no VWAP at all, so the MQL5 version below keeps the two running sums in calculation buffers and resets them on the server-day boundary. The arithmetic is trivial. What makes the two lines differ in practice is where the day starts and what "volume" means on each platform.

How session VWAP is calculated

On each bar t of a session, with p the chosen price (usually hlc3) and v the bar's volume:

  • sumPV = Σ p × v over the bars of the session so far
  • sumV = Σ v over the same bars
  • VWAP = sumPV / sumV

Both sums restart at the first bar of a new session. On an intraday chart that is the first bar of the day; on a daily or higher chart the "session" is a single bar and VWAP equals the bar's own price. The first bar of the day has VWAP = p, so there is no warm-up and no seeding; two implementations that agree on the session boundary and the volume agree exactly.

Volume is where they stop agreeing. For exchange-traded symbols both platforms have real traded volume. For forex and CFDs MetaTrader's volume[] array is zero at most brokers and tick_volume[] (the number of price changes in the bar) is what everyone uses; TradingView's forex volume is also a tick count, but from its own feed, so the weights differ and so does the line. That is not an error in either program. Choose the volume source deliberately and compare VWAP across platforms only on symbols with real volume.

Pine Script v6 version

An original script written with explicit sums rather than ta.vwap, so the reset rule is visible. var keeps the sums across bars; timeframe.change("D") is true on the first bar of each new day in the symbol's session calendar.

//@version=6
indicator("Session VWAP", shorttitle="VWAP", overlay=true)

src = input.source(hlc3, "Source")

// Accumulate price * volume and volume from the first bar of each day.
newDay = timeframe.change("D")

var float sumPV = 0.0
var float sumV  = 0.0
if newDay
    sumPV := 0.0
    sumV  := 0.0
sumPV += src * volume
sumV  += volume

vwap = sumV > 0 ? sumPV / sumV : na

plot(vwap, "VWAP", color=color.blue, linewidth=2)

Pine handles the realtime bar for you: on every new tick the var variables are rolled back to the values they had at the close of the previous bar before the script runs again, so the forming bar's volume is never counted twice. The MQL5 version has to reproduce that rollback by hand.

MQL5 version

Three buffers: the line and two INDICATOR_CALCULATIONS buffers for the running sums. Storing the sums per bar is the MQL5 equivalent of Pine's var rollback: when OnCalculate recomputes the forming bar on the next tick it starts from SumPVBuf[i - 1], the previous bar's total, which never changes. A global accumulator would add the forming bar's volume on every tick.

//+------------------------------------------------------------------+
//| Session VWAP: sum(price * volume) / sum(volume) since the start   |
//| of the current server day.                                        |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots   1
#property indicator_label1  "VWAP"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_width1  2

enum ENUM_VWAP_SOURCE
  {
   VWAP_HLC3  = 0,  // (high + low + close) / 3
   VWAP_CLOSE = 1,  // close
   VWAP_HL2   = 2,  // (high + low) / 2
   VWAP_OHLC4 = 3   // (open + high + low + close) / 4
  };

input ENUM_VWAP_SOURCE InpSource     = VWAP_HLC3;  // Source
input bool             InpRealVolume = false;      // Use real volume (exchange symbols only)

double VwapBuf[];
double SumPVBuf[], SumVBuf[];   // running sums, one value per bar

int OnInit()
  {
   SetIndexBuffer(0, VwapBuf,  INDICATOR_DATA);
   SetIndexBuffer(1, SumPVBuf, INDICATOR_CALCULATIONS);
   SetIndexBuffer(2, SumVBuf,  INDICATOR_CALCULATIONS);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   IndicatorSetString(INDICATOR_SHORTNAME, "VWAP");
   return INIT_SUCCEEDED;
  }

double Price(const double &open[], const double &high[], const double &low[],
             const double &close[], const int i)
  {
   switch(InpSource)
     {
      case VWAP_CLOSE: return close[i];
      case VWAP_HL2:   return (high[i] + low[i]) / 2.0;
      case VWAP_OHLC4: return (open[i] + high[i] + low[i] + close[i]) / 4.0;
      default:         return (high[i] + low[i] + close[i]) / 3.0;
     }
  }

int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[],
                const double &open[], const double &high[], const double &low[],
                const double &close[], const long &tick_volume[], const long &volume[],
                const int &spread[])
  {
   int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      // New day in server time. Pine's timeframe.change("D") uses the symbol's
      // exchange calendar instead, which may not be midnight on the server.
      bool newDay = (i == 0) || ((long)time[i] / 86400 != (long)time[i - 1] / 86400);
      double v  = (double)(InpRealVolume ? volume[i] : tick_volume[i]);
      double pv = Price(open, high, low, close, i) * v;
      // Sums are stored per bar, so recomputing the forming bar on every tick
      // starts from the previous bar's totals instead of adding to itself.
      SumPVBuf[i] = (newDay ? 0.0 : SumPVBuf[i - 1]) + pv;
      SumVBuf[i]  = (newDay ? 0.0 : SumVBuf[i - 1])  + v;
      VwapBuf[i]  = (SumVBuf[i] > 0.0) ? SumPVBuf[i] / SumVBuf[i] : EMPTY_VALUE;
     }
   return rates_total;
  }

The day boundary is time[i] / 86400 changing, which is midnight in server time. If your broker's server runs on GMT+2 or GMT+3 (common for forex), the "day" starts at 22:00 or 21:00 UTC, which for currency pairs is close to the New York 17:00 rollover TradingView uses, but not identical. For US stocks TradingView's session starts at 09:30 exchange time and MetaTrader's day at server midnight; to match, replace the test with one on the broker's session start, for example by comparing the bar's minutes-of-day to the open time from SymbolInfoSessionTrade.

Differences you will see on the chart

TradingViewMetaTrader 5 (this port)
Session startSymbol's exchange session, in the exchange time zoneServer midnight; change the newDay test to use a session table if needed
VolumeReal volume on exchanges, feed tick count on forexvolume[] (real, often zero on forex) or tick_volume[]; the input picks
First bar of the dayVWAP = source priceSame
Bars with zero volumena until the first non-zero volume of the dayEMPTY_VALUE until then
Realtime barSums rolled back and recomputed on every tickPer-bar sums; the forming bar is recomputed from the previous bar's totals
Higher timeframesDaily and above: VWAP equals the bar's priceSame, since every bar starts a new day

Using it in MetaTrader 5

Save as SessionVWAP.mq5 under MQL5\Indicators, compile with F7 and attach to an intraday chart. Leave Use real volume off for forex and CFDs; turn it on for stocks and futures if your broker delivers real volume (check that the Volumes indicator shows non-zero values). From an EA, iCustom(_Symbol, _Period, "SessionVWAP", 0, false) gives the handle and buffer 0 is the line; buffers 1 and 2 (the sums) are also readable, which is handy for building VWAP bands without recomputing.

For an alert on a VWAP cross, compare close[i - 1] and close[i] with VwapBuf[i - 1] and VwapBuf[i] on the last closed bar; the forming bar's VWAP moves with each tick and would fire repeatedly.

What the Stratlate converter emits

The Pine version converts CLEAN. timeframe.change("D") becomes pine_timeframe_change("D", time, bar), a calendar-aware test that compares the day, month and year of the bar's time with the previous bar's, so a new day is a real date change in server time rather than a fixed 86400-second bucket. The var sums become globals that the generated OnCalculate saves before the forming bar and restores on the next tick (the __pineSaveState/__pineRestoreState pair), which is how the engine reproduces Pine's rollback. For volume, the generated code checks whether the newest bar has real volume and passes volume[] if so and tick_volume[] otherwise. Had the script used ta.vwap(src) instead, the engine would emit pine_vwap, which resets on the server-day boundary, and report it as an approximation (PM290) because TradingView anchors to the exchange session. Compile and compare on a symbol with real volume before trading on it.

Pitfalls

  • Accumulating into a global variable in OnCalculate. Every tick of the forming bar adds its volume again; VWAP drifts towards the current price during the bar and jumps back at the next bar. Store the sums per bar.
  • Using volume[] on a forex symbol. It is zero, sumV stays zero and the line is empty all day. Use tick_volume[] or make it an input.
  • Expecting the forex line to match TradingView. Both weight by tick counts from different feeds; shapes agree, values do not. Compare on exchange-traded symbols.
  • Detecting the new day with TimeDay() alone. A gap longer than a month (holiday, missing history) where the day-of-month happens to repeat skips the reset; compare the full date or the day number as the port does.
  • Testing on a daily chart. Each bar is its own session, so the line sits on the price and looks broken. Session VWAP is an intraday tool.

FAQ

Is there an iVWAP function in MQL5?

No. MetaTrader 5 has no built-in VWAP indicator and no VWAP applied price. The indicator on this page is the complete replacement, with no includes.

Why does my MT5 VWAP reset at a different time than TradingView's?

Because the port resets at server midnight while TradingView resets at the start of the symbol's exchange session. Either accept the difference, or replace the newDay test with a check against the broker's trading-session start for the symbol.

Can I add standard-deviation bands?

Yes. Keep a third running sum of price² × volume per bar, then variance = sumP2V / sumV − VWAP², and bands are VWAP ± k × sqrt(variance). Clamp the variance at zero before the square root to absorb floating-point noise on the first bars of the day.

Convert your own version

Have a variant of this indicator, or any other TradingView script? Paste it and get MQL5 that is checked against the original on the same price history, with every construct that could not be carried over reported.

Open the converter

Related