iOBV in Pine Script: ta.obv and the first-bar offset

Short answer

Use ta.obv. The bar-to-bar changes are identical, but OBV is a running total and MetaTrader starts it from the first bar's volume, so the absolute level differs.

iOBV returns a handle to MetaTrader's On-Balance Volume; Pine Script's equivalent is the built-in series ta.obv. Both add the bar's volume when the close rises, subtract it when the close falls and carry the total forward when the close is unchanged. The bar-to-bar changes are identical; the absolute level is not, because OBV is a running total and the two platforms start it on different bars with different starting values.

What iOBV computes

The signature is iOBV(symbol, timeframe, applied_volume), where applied_volume is VOLUME_TICK (the number of price changes in the bar, the default) or VOLUME_REAL (exchange volume, available only on instruments whose broker supplies it). The stock indicator (Indicators\Examples\OBV.mq5) sets the first value to the first bar's volume, then for every following bar adds the volume if the close is above the previous close, subtracts it if below and repeats the previous value if equal. There is no period and no smoothing, and every bar has a value from bar 0.

The Pine Script equivalent

ta.obv is the cumulative sum of math.sign(ta.change(close)) * volume; the first bar contributes nothing because it has no previous close. If you need MetaTrader's exact starting value, write the recursion with a var variable as below. The volume series is whatever the TradingView data feed supplies for the symbol: real volume for stocks and futures, tick volume or a provider's aggregate for most forex and CFD feeds.

//@version=6
indicator("iOBV port", overlay = false)

// Exact MetaTrader form: seeded with the first bar's volume, then +/- volume on each close change.
var float obvMt5 = 0.0
if bar_index == 0
    obvMt5 := volume
else
    obvMt5 += close > close[1] ? volume : close < close[1] ? -volume : 0.0

plot(obvMt5, "OBV (iOBV)", color.rgb(30, 144, 255))
plot(ta.obv, "ta.obv", color.gray)

The MQL5 indicator this replaces:

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue

input ENUM_APPLIED_VOLUME InpVolume = VOLUME_TICK; // applied_volume

double ObvBuffer[];
int    obvHandle;

int OnInit()
  {
   SetIndexBuffer(0, ObvBuffer, INDICATOR_DATA);
   obvHandle = iOBV(_Symbol, _Period, InpVolume);
   if(obvHandle == INVALID_HANDLE)
      return(INIT_FAILED);
   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(BarsCalculated(obvHandle) < rates_total)
      return(0);
   int to_copy = (prev_calculated == 0) ? rates_total : rates_total - prev_calculated + 1;
   if(CopyBuffer(obvHandle, 0, 0, to_copy, ObvBuffer) <= 0)
      return(0);
   return(rates_total);
  }

Where the two differ

TopicMQL5 iOBVPine ta.obv
Step rule+volume on higher close, −volume on lower, 0 on equalIdentical
First valueVolume of the first loaded barFirst bar adds nothing
Start barFirst bar of the terminal's historyFirst bar TradingView loads
Volume sourceVOLUME_TICK or VOLUME_REAL from the brokerThe feed's volume; no choice
Comparable quantityChanges, slopes and divergences; never the absolute level
Warm-upNoneNone

Even with identical rules the two lines are only offset copies of each other if both platforms use the same volumes. A forex symbol on TradingView rarely has the same tick counts as a given MetaTrader broker, so expect the shape to be similar and the numbers to differ.

What the Stratlate converter emits

The MQL5 → Pine engine maps iOBV to the constant series ta.obv (PineCatalog, entry iOBV), replaces the handle and its CopyBuffer with that series, and reports it as an approximation: our probe logged MQLW0501 "iOBV mapped as constant; ignoring 3 args". The applied_volume argument is not modelled (the probe also logged VOLUME_TICK as an identifier with no Pine mapping, MQLW0512, and turned the input into a plain number), and the first-bar starting value is not reproduced. If anything in the original compares OBV to a fixed level, rewrite that part by hand; slope and divergence logic carries over. Compile the output and compare it on the chart.

Pitfalls

  • Comparing OBV values between platforms. A running total depends on where the history starts; only differences such as obv − obv[10] are comparable.
  • Porting a fixed-threshold rule (for example "OBV > 0"). Its outcome depends on the first loaded bar and will not match MetaTrader.
  • Assuming volume in Pine is tick volume. For stocks and futures it is traded volume; for forex it depends on the data provider.
  • Writing the recursion without var. A plain variable is reset on every bar and the total never accumulates.
  • Expecting VOLUME_REAL to work on every MT5 symbol. On forex it is usually zero and the OBV line is flat.

FAQ

Is ta.obv the same as MetaTrader's OBV?

The rule is the same; the starting point is not. MetaTrader starts at the first bar's volume on its first loaded bar, Pine starts at zero on its own first bar, so the lines are offset and their volumes may come from different feeds.

How do I port applied_volume?

There is nothing to choose in Pine: volume is the only volume series. If the MQL5 code relied on VOLUME_REAL for a stock or future, TradingView's volume is normally that real volume.

How do I get an OBV signal line?

Smooth it like any series, for example ta.ema(ta.obv, 20). In MQL5 that requires an iMA created on the OBV handle or a hand-written average over the copied buffer.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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