← BlogExpert Advisors
Expert Advisors

iCustom in MQL5: reading the right bar

In MQL5, iCustom returns a handle. Read the right bar with explicit shifts, exact CopyBuffer counts and the indicator's empty-value rules.

iCustom in MQL5: reading the right bar

When we compare an EA log with an indicator on the chart, we start with the bar's timestamp. A valid number from the wrong bar can look convincing. In MQL5, iCustom returns an indicator handle, not a price or signal. CopyBuffer reads the values.

An apparently old value can come from the wrong bar shift, reversed array indexing, an unsuccessful copy followed by reuse of previous data, or the indicator's own calculation rules. A missing chart marker alone cannot tell us which one occurred.

iCustom creates a handle, CopyBuffer reads it

Create the custom indicator handle once in OnInit, check for INVALID_HANDLE, and reuse it for buffer reads. The official technical indicator documentation recommends this lifecycle and warns that values need time to become available after creation.

The iCustom reference requires a compiled EX5 file and matching input parameter types and order. Its first arguments select the indicator's symbol and timeframe. Reading a different timeframe and comparing the result with the chart's current candle is already a mismatch.

The terminal can reuse a cached calculation instance for identical parameters. That does not establish data readiness or justify repeatedly creating handles in OnTick. Release the handle in OnDeinit with IndicatorRelease. The terminal frees the calculation block once no other program uses it. In the Strategy Tester, IndicatorRelease is not executed.

What does current mean in CopyBuffer?

CopyBuffer starts counting at the present and moves into the past. Source shift 0 is the forming bar; shift 1 is the most recent closed bar. The destination array's index is a separate question.

The CopyBuffer reference says the oldest requested element goes first in physical memory, regardless of the recipient's AS_SERIES flag. For an ordinary static array, this produces the following mapping.

Copy order in a static destination array
Requested source barsDestination index 0Destination index 1Destination index 2
Start 0, count 3Shift 2Shift 1Shift 0, forming
Start 1, count 2Shift 2Shift 1, last closedNot requested
Start 1, count 1Shift 1, last closedNot requestedNot requested

Thus, CopyBuffer(handle, 0, 1, 1, value) writes the last closed bar to value[0]. Index 0 in that destination does not mean the forming bar.

ArraySetAsSeries changes logical indexing for a dynamic array, without reversing the copied data in memory. It cannot set the flag on a static array such as double values[2]. Even with a dynamic series array, logical index 0 means the newest element of the requested slice. A slice starting at source shift 1 contains no forming-bar value.

BarsCalculated is a count, not a freshness guarantee

BarsCalculated returns the number of calculated values, or -1 on error, including when data have not yet been calculated. It helps identify insufficient data. It provides no timestamp or last-tick version for a buffer value.

Comparing it with Bars(symbol, timeframe) can help assess history coverage for that same series. Equality cannot prove that the indicator has processed the current tick. Many ticks arrive without the bar count changing. Nor does a calculated bar count mean that every buffer slot contains a usable signal.

What each check actually establishes
CheckWhat we knowWhat remains unknown
Handle is validThe indicator was createdWhether the requested values are ready
Calculated count is sufficientThe indicator reports enough calculated dataLatest-tick freshness and signal validity
Copied count equals requested countThe requested number of values was transferredWhether they are empty or appropriate for the strategy
Value passes the empty and finite checksThe number passes those checksWhether the indicator later revises that bar

CopyBuffer returns the copied count or -1 on error. An EA may receive fewer values than requested while data are being prepared. A failed or short copy is not automatically a harmless startup delay, so log it. Require the exact count before reading any element, and never fall back to an earlier successful read.

Use ResetLastError immediately before the request and capture GetLastError immediately after it. Otherwise a diagnostic can report an error left over from another operation.

A common explanation for old values is that the EA reads the buffer before the indicator recalculates on a new bar. The runtime documentation describes a separate thread for each EA and one shared indicator thread per symbol. It does not guarantee that order on every new bar, and thread layout alone cannot prove that a successful copy put the previous bar's value in the current bar's slot.

A complete custom indicator and reader

These two source files isolate buffer reading from order execution. The indicator publishes the change in closing price over InpLookback bars, measured in symbol points. The EA logs two closed-bar values once per successfully processed latest closed bar. It sends no trades.

Save the indicator as CloseChange.mq5

Save this file in the terminal's MQL5/Indicators folder and compile it in MetaEditor to create CloseChange.ex5. With the default input of 1, buffer 0 contains (close[i] - close[i + 1]) / _Point.

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "Close change (points)"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrOrange

input int InpLookback = 1;
double ChangeBuffer[];

int OnInit()
  {
   if(InpLookback < 1)
      return INIT_PARAMETERS_INCORRECT;
   if(!SetIndexBuffer(0, ChangeBuffer, INDICATOR_DATA))
      return INIT_FAILED;
   ArraySetAsSeries(ChangeBuffer, true);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   IndicatorSetInteger(INDICATOR_DIGITS, 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[])
  {
   ArraySetAsSeries(close, true);
   if(prev_calculated <= 0 || prev_calculated > rates_total)
      ArrayInitialize(ChangeBuffer, EMPTY_VALUE);
   if(rates_total <= InpLookback)
      return 0;

   int start = rates_total - InpLookback - 1;
   if(prev_calculated > 0 && prev_calculated <= rates_total)
     {
      int added = rates_total - prev_calculated;
      if(added < start)
         start = added;
     }
   for(int i = start; i >= 0; --i)
      ChangeBuffer[i] = (close[i] - close[i + InpLookback]) / _Point;
   return rates_total;
  }

SetIndexBuffer explicitly binds buffer 0. The buffer number comes from this call, not from the order of plotted lines. The code sets series indexing after binding and also sets the input close array's direction explicitly.

Unavailable lookback values start as EMPTY_VALUE. On subsequent calls, the indicator recalculates the forming bar and any newly closed bars. When history changes, the terminal can reset prev_calculated to zero, as documented for OnCalculate. The code then rebuilds the buffer.

Save the EA as ReadCloseChange.mq5

Save this second file in MQL5/Experts, compile it, and attach it to a demo chart with incoming ticks. The literal name "CloseChange" matches the indicator file above and lets the Strategy Tester identify the dependency automatically. A dynamically supplied indicator name would instead require #property tester_indicator, according to the iCustom reference.

input int InpLookback = 1;
int g_handle = INVALID_HANDLE;
datetime g_last_closed = 0;

int OnInit()
  {
   if(InpLookback < 1)
      return INIT_PARAMETERS_INCORRECT;
   g_last_closed = 0;
   ResetLastError();
   g_handle = iCustom(_Symbol, _Period, "CloseChange", InpLookback);
   if(g_handle == INVALID_HANDLE)
     {
      PrintFormat("iCustom failed: error=%d", GetLastError());
      return INIT_FAILED;
     }
   return INIT_SUCCEEDED;
  }

void OnDeinit(const int reason)
  {
   if(g_handle != INVALID_HANDLE)
     {
      IndicatorRelease(g_handle);
      g_handle = INVALID_HANDLE;
     }
  }

void OnTick()
  {
   datetime closed_time = iTime(_Symbol, _Period, 1);
   if(closed_time == 0 || closed_time == g_last_closed)
      return;

   double values[2];
   ResetLastError();
   int copied = CopyBuffer(g_handle, 0, 1, 2, values);
   int copy_error = GetLastError();
   if(copied != 2)
     {
      PrintFormat("CopyBuffer: copied=%d/2 error=%d", copied, copy_error);
      return;
     }
   if(BarsCalculated(g_handle) < 3)
      return;
   if(iTime(_Symbol, _Period, 1) != closed_time)
      return;

   double older = values[0];
   double latest = values[1];
   if(older == EMPTY_VALUE || latest == EMPTY_VALUE ||
      !MathIsValidNumber(older) || !MathIsValidNumber(latest))
      return;

   PrintFormat("%s %s closed=%s older=%.1f latest=%.1f points",
               _Symbol, EnumToString(_Period),
               TimeToString(closed_time, TIME_DATE | TIME_MINUTES),
               older, latest);
   g_last_closed = closed_time;
  }

The static array needs no allocation or series flag. With start shift 1 and count 2, values[0] belongs to shift 2, while values[1] belongs to shift 1. Suppose the closes at shifts 3, 2 and 1 are 1.08880, 1.08890 and 1.08910, with _Point = 0.00001 and lookback 1. The copied older value is 10.0 points; the latest is 20.0 points.

The EA requests the data before the coarse BarsCalculated check. In non-visual tester runs, indicators are calculated only when buffer data is requested. Gating the first CopyBuffer call on BarsCalculated could therefore wait for a calculation that nothing triggers.

iTime returns the bar's opening time, or zero on error. The second timestamp check discards the read if the last closed bar changed during the request. It is a rollover check, not proof of atomic synchronization with an arbitrary indicator.

g_last_closed changes only after the complete, usable read and log entry. If data are unavailable, this event ends without consuming the bar. A later OnTick can attempt the read through the normal event lifecycle. There is no Sleep, waiting loop, or timer polling. If no further tick arrives, no further read happens. The example also processes the latest closed bar on startup. It does not replay bars missed while disconnected.

We reset the timestamp in OnInit because chart symbol or timeframe changes can reinitialize an EA without resetting its globals. This follows the documented initialization and deinitialization lifecycle.

A forming-bar signal can disappear without a bug

A signal based on source shift 0 is provisional if its inputs change before the bar closes. Reading shift 1 avoids the unfinished bar, but only the indicator's own rules can determine whether closed-bar values remain unchanged.

Consider a hypothetical EURUSD M15 condition, close > 1.08900. These prices illustrate the distinction; they are not a recorded trade or a strategy result.

One hypothetical bar, before and after its close
ObservationBar being readClosing-price valueCondition
09:1809:15 bar, still forming, shift 01.08920True
09:29Same forming bar, shift 01.08880False
After the next bar exists09:15 bar, now closed, shift 11.08880False

The intrabar condition disappeared before confirmation. That does not demonstrate a stale copy. An indicator that later rewrites closed-bar signals needs a different investigation, including future-bar dependencies, higher-timeframe inputs that remain open, and history corrections.

Neither a new bar nor a successful read promises execution at the next bar's opening price. OnTick responds to incoming ticks on the EA's chart symbol. Data may become usable later, and a trade request would have its own execution outcome. This diagnostic EA places no orders.

Match the value to the same bar on the chart

Compare the same compiled indicator, symbol, timeframe, inputs, buffer number, and bar opening time. A chart screenshot with a similar-looking line is insufficient. Start with this simple indicator so the expected value can be calculated from two closing prices.

Attach CloseChange to the same chart with the EA's lookback value, then compare the logged latest value with the Data Window on the logged closed bar. Inspect failed-copy messages separately. A mismatch can come from indexing, parameters, plot shifts, or indicator logic. It does not by itself prove a timing race between the EA and the indicator.

Repeat the check in the Strategy Tester and on a demo account. Visual and non-visual testing have different indicator calculation rules, so visual agreement alone does not guarantee live behavior. Our MT5 Expert Advisors guide covers the wider deployment workflow; why a backtested MT5 EA can fail live separates data and signal problems from execution problems.

Before substituting another indicator, establish its buffer contract. EMPTY_VALUE equals DBL_MAX, a finite sentinel. MathIsValidNumber rejects NaN and infinities, so both checks are necessary. A custom indicator can configure another empty value with PLOT_EMPTY_VALUE. Zero can be a valid result. In CloseChange, equal closing prices produce zero points.

Frequently asked questions

Does iCustom return an old indicator value in MQL5?

iCustom returns a handle or INVALID_HANDLE. Values come from CopyBuffer. Check the source bar shift, destination array order, copied count, and the indicator's empty-value and repainting rules before treating an apparent old value as a calculation delay.

Does BarsCalculated prove that a buffer is current?

No. BarsCalculated reports a count, not a timestamp or tick version. Sufficient calculated history does not prove latest-tick processing, a non-empty signal, or stable closed-bar values. The requested copy must still succeed with the exact count.

Why is the last closed bar sometimes at array index 0?

A one-element request starting at source shift 1 puts that bar at destination index 0. For a static two-element request starting at shift 1, the older shift 2 occupies index 0 and the last closed bar occupies index 1.

Does reading shift 1 stop repainting?

It avoids using the forming bar. It cannot prevent an indicator from revising historical values or using an unfinished higher-timeframe input. Closed-bar stability depends on the indicator's algorithm and the underlying history.