ta.vwma in MQL5: no native, sum(src*vol)/sum(vol)

Short answer

MQL5 has no VWMA: loop over the window and divide sum(source × volume) by sum(volume). Choose tick volume or real volume deliberately, because MetaTrader offers both and they are not interchangeable.

ta.vwma(source, length) is the volume weighted moving average: each of the last length values is weighted by its bar's volume. MQL5 has no iMA mode for it and no built-in indicator that produces it, so the equivalent is a loop that sums source * volume and volume over the window and divides. The one decision the Pine code never had to make is which volume to use: MetaTrader hands you both tick volume and real volume, and they are not interchangeable.

What ta.vwma computes

Pine defines it as ta.sma(source * volume, length) / ta.sma(volume, length), which simplifies to sum(source[k] * volume[k]) / sum(volume[k]) for k = 0 … length - 1. It is na until length bars exist, and na if the volume sum is zero, because Pine's division by zero yields na rather than an error. There is no recursion, so history depth does not matter and only the bars inside the window influence the result.

The volume series in Pine is whatever TradingView's data feed reports for the symbol: real traded volume for exchange-listed instruments, tick counts for most forex and CFD feeds. The VWMA therefore already means two different things depending on the market, and the MQL5 version should use the same kind of volume the TradingView chart used.

The MQL5 equivalent

//@version=6
indicator("VWMA", overlay = true)
len = input.int(20, "Length")
plot(ta.vwma(close, len), "VWMA")

A complete MQL5 indicator. OnCalculate receives tick_volume[] and volume[] as long arrays; the input selects which one is used, and the cast to double keeps the products from overflowing or truncating:

//+------------------------------------------------------------------+
//| ta.vwma(source, length) = sum(source * volume) / sum(volume)     |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "VWMA (ta.vwma)"

input int  InpLength     = 20;    // length
input bool InpRealVolume = false; // use real volume (volume[]) instead of tick volume

double VwmaBuffer[];

int OnInit()
{
   SetIndexBuffer(0, VwmaBuffer, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength - 1);
   return INIT_SUCCEEDED;
}

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[])
{
   if(InpLength <= 0)
      return 0;
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i < InpLength - 1)
        {
         VwmaBuffer[i] = EMPTY_VALUE;
         continue;
        }
      double pv = 0.0, vv = 0.0;
      for(int k = 0; k < InpLength; k++)
        {
         const double v = (double)(InpRealVolume ? volume[i - k] : tick_volume[i - k]);
         pv += close[i - k] * v;
         vv += v;
        }
      VwmaBuffer[i] = vv > 0.0 ? pv / vv : EMPTY_VALUE;   // Pine: x / 0 is na
     }
   return rates_total;
}

On a forex or CFD symbol volume[] is usually all zeros, which is why the default is tick volume. On futures and stocks from an exchange feed, real volume is populated and matches what TradingView shows as volume. A quick check is volume[rates_total - 1] > 0 on the current bar.

Where the two differ

TopicPine ScriptMQL5
Native functionta.vwmaNone; iMA has no volume-weighted mode
Volume sourceOne volume series from the feedtick_volume[] or volume[]; you choose
Typefloat serieslong arrays; cast to double before multiplying
Zero volume windowna (division by zero)Division by zero is a runtime error that stops the indicator; test vv > 0.0
First barsna for length - 1 barsEMPTY_VALUE written by you
Realtime barVolume grows during the bar, so the current value moves with each tickSame, provided the loop recomputes the forming bar

Different volume definitions produce a different line, not a slightly different one. Tick volume counts price changes; real volume counts contracts or shares. The weights differ by orders of magnitude and by shape within the day, so a VWMA on tick volume can cross price on bars where the real-volume VWMA does not.

What the Stratlate converter emits

The engine maps ta.vwma to its runtime helper pine_vwma(src, volume, bar, length), which sums source * volume and volume over the window, returns na until length bars exist and uses the runtime's safe division so a zero volume sum gives na instead of an error. A computed source is handled by pine_vwma_step through a per-call-site window array. The volume passed in is chosen once per indicator: the generated OnCalculate uses the real volume[] array when the newest bar's real volume is above zero and tick_volume[] otherwise. The call is reported as exact, and the script above converts CLEAN. Compile and backtest the result, and check that the volume kind matches the TradingView chart you compare against.

Pitfalls

  • Using real volume on a forex symbol. volume[] is zero on every bar, the denominator is zero, and the indicator either stops with a division error or plots nothing. Use tick volume or guard the division.
  • Integer arithmetic on long. close[i] * tick_volume[i] promotes to double, but a sum of volumes kept in a long and then divided truncates. Accumulate in doubles.
  • Comparing against TradingView on a different volume kind. The lines look alike and never match. Confirm what the TradingView feed reports for that symbol before concluding the code is wrong.
  • Treating the realtime bar as fixed. The weight of the current bar grows with every tick, so the last VWMA value changes more than an SMA does. This is expected on both platforms.
  • Forgetting the window guard. close[i - k] before length - 1 bars reads outside the array.

FAQ

Is there an iMA mode for a volume weighted average?

No. iMA offers MODE_SMA, MODE_EMA, MODE_SMMA and MODE_LWMA, none of which uses volume. MetaTrader also ships no standard VWMA indicator, so the loop above or a custom indicator called through iCustom is the way to get one.

Should I use tick_volume or volume in MQL5?

Use the one that corresponds to what your TradingView chart shows. For forex and most CFDs that is tick volume; for exchange-traded futures and stocks with a real volume feed it is volume[]. If volume[] is zero on the latest bar, the broker does not supply real volume.

Why does my VWMA differ from TradingView even with the same candles?

Tick volume is broker-specific: it counts the ticks that broker's server delivered, so two brokers give different tick volumes for the same minute. TradingView's forex tick volume comes from its own feed. Expect small differences from the volume weights even when the prices agree.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related