ta.change in MQL5: src - src[len], bool form and first bars

Short answer

ta.change(src, len) is src[i] - src[i - len] on oldest-first arrays, with an empty value for the first len bars. The boolean form is a != a[i-1].

ta.change(source, length) is the difference between the current value of source and its value length bars ago, with length defaulting to 1. In MQL5 that is src[i] - src[i - length] on oldest-first arrays, guarded so the first length bars produce an empty value instead of reading before the start of the array.

What ta.change computes

ta.change(x, n) equals x - x[n]. When x[n] does not exist yet, which is the case on the first n bars of the chart, or is na, the result is na. The default length is 1, so ta.change(close) is the bar-to-bar close difference and ta.change(close, 10) is the same thing as ta.mom(close, 10).

Passed a bool, ta.change returns a bool: true on bars where the condition flipped from the previous bar, in either direction. ta.change(close > open) is true on the first bar of every run of up bars and of down bars. Scripts use it to detect regime flips, session boundaries (ta.change(time("D"))) and the first bar of a new higher-timeframe candle. On the realtime bar it is re-evaluated each tick like everything else, so a flip can appear and disappear before the bar closes.

The MQL5 equivalent

Pine: the close change over len bars as a histogram.

//@version=6
indicator("Change")
len = input.int(1, "Length")
chg = ta.change(close, len)
plot(chg, "Change", style=plot.style_histogram)

MQL5. ChangeAt carries the na rule; the loop stays oldest-first so "len bars ago" is i - len.

//+------------------------------------------------------------------+
//| Momentum as a difference: Pine's ta.change(close, len) in MQL5    |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "change"
#property indicator_type1   DRAW_HISTOGRAM
#property indicator_color1  clrDodgerBlue
#property indicator_level1  0

input int Length = 1;

double Change[];

// ta.change(src, len) = src - src[len]; na while fewer than len bars precede i.
double ChangeAt(const double &src[], const int i, const int len)
{
   if(len < 1 || i < len) return EMPTY_VALUE;
   return src[i] - src[i - len];
}

int OnInit()
{
   SetIndexBuffer(0, Change, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   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[])
{
   int start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
      Change[i] = ChangeAt(close, i, Length);
   return rates_total;
}

The bool form has no arithmetic, only a comparison of two evaluations of the condition. For "the up/down direction of the bar changed":

bool upNow  = close[i] > open[i];
bool upPrev = close[i - 1] > open[i - 1];     // i >= 1
bool flipped = (upNow != upPrev);             // ta.change(close > open)

For a session boundary the usual MQL5 idiom compares the day of time[i] and time[i - 1] with TimeToStruct, or the integer division time[i] / 86400 != time[i - 1] / 86400 for a server-time day.

Where the two differ

TopicPine ScriptMQL5
Indexx[len] is len bars backx[i - len] oldest-first; x[i + len] in series order
First barsna for i < lenReading x[-1] is an array out of range error at runtime; guard and write EMPTY_VALUE
Bool sourceReturns bool (changed or not)Compare the two evaluations with !=; there is no overload to call
na in the sourcePropagates to naEMPTY_VALUE - x is a huge number, not empty; test both cells first
Default length1No default; write it

What the Stratlate converter emits

The engine maps ta.change as a windowed builtin to pine_change(src, bar, len), whose runtime body reads the earlier value with pine_hist (na when i - len < 0) and returns na if either value is na, otherwise src[i] - prev. A missing length becomes (int)(1). A computed or boolean source is first materialised into a per-script array: ta.change(close > open) converted to __ts0[__pineBar] = (close[__pineBar] > open[__pineBar]); flipped = pine_change(__ts0, __pineBar, (int)(1));, so the bool result is a numeric -1/0/1 that is later tested with pine_truthy, which is true exactly when the condition changed. The mapping is exact.

Pitfalls

  • No guard on the first bars. Symptom: "array out of range" the moment the indicator attaches, since close[-1] is read on bar 0.
  • Subtracting across an EMPTY_VALUE cell. Symptom: a single spike to about 1.8e308 that destroys the subwindow scale.
  • Sign flipped in series order. Symptom: the histogram is a mirror image of TradingView's; x[i] - x[i + len] is correct there, not the other way round.
  • Translating ta.change(cond) as cond && !cond[1]. Symptom: only the false-to-true flips are detected; the true-to-false ones are dropped.
  • Using tick volume where the script expected real volume in ta.change(volume). Symptom: numbers of a completely different magnitude; the shape is similar, the values are not.

FAQ

Is ta.change the same as ta.mom?

For a numeric source with an explicit length, yes: both are source minus source length bars ago. ta.change also accepts a bool source and defaults to a length of 1, which ta.mom does not.

What does ta.change return on the first bar?

na, because there is no previous value. The MQL5 equivalent must return EMPTY_VALUE (or skip the bar) rather than read index -1.

How do I write ta.change(close > open) in MQL5?

Evaluate the condition on bar i and on bar i - 1 and compare them with !=. A true result means the direction flipped, in either direction, which is what Pine's bool overload returns.

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