Blog / Code & convert EAs · MQL5 · Indicators · Expert Advisors

Indicator Handles and CopyBuffer Explained

Learn how MQL5 indicator handles work and how to use CopyBuffer() to retrieve moving average, RSI and custom indicator values in an Expert Advisor.

· 4 min read

Your Expert Advisor creates a moving average or RSI indicator, but the values it receives are incorrect or unavailable.

In MQL5, most indicator functions return a handle, not the calculated indicator value. You must use that handle with CopyBuffer() to retrieve the actual data.

Understanding this process helps prevent invalid indicator readings and incorrect trading signals.

1. Create an Indicator Handle

An indicator handle is an identifier that allows your EA to access an indicator instance and its calculated data.

For example, this creates a 20-period Simple Moving Average:

MQL5
int maHandle = iMA(
   _Symbol,
   PERIOD_CURRENT,
   20,
   0,
   MODE_SMA,
   PRICE_CLOSE
);

The returned value is not the moving average itself. It is the handle used to retrieve its values.

Always check whether handle creation succeeded:

MQL5
if(maHandle == INVALID_HANDLE)
{
   Print("Failed to create MA handle: ", GetLastError());
   return INIT_FAILED;
}

Create indicator handles in OnInit() rather than repeatedly inside OnTick(). This allows your EA to reuse the same handle instead of creating unnecessary indicator instances on every tick.

The same approach applies to RSI, MACD, ATR and custom indicators created with iCustom().

2. Retrieve Indicator Values with CopyBuffer()

Once you have a valid handle, use CopyBuffer() to retrieve the calculated values.

Its syntax is:

MQL5
CopyBuffer(
   indicator_handle,
   buffer_num,
   start_pos,
   count,
   buffer[]
);

The parameters mean:

Parameter Purpose
indicator_handle Handle returned by the indicator function
buffer_num Indicator buffer to read
start_pos Starting candle position
count Number of values to retrieve
buffer[] Destination array

For example:

MQL5
double maValues[];

int copied = CopyBuffer(
   maHandle,
   0,
   1,
   2,
   maValues
);

This requests two values from buffer 0, starting at candle position 1.

CopyBuffer() returns the number of elements copied or -1 if an error occurs. It may also return fewer values than requested.

Never assume that requesting two values means both are available.

3. Check That the Indicator Data Is Ready

A valid indicator handle doesn't guarantee that the indicator has finished calculating its values.

Use BarsCalculated() to check how many indicator values are available, then verify the actual result from CopyBuffer().

MQL5
if(BarsCalculated(maHandle) < 2)
{
   Print("Not enough calculated indicator data");
   return;
}

double maValues[];

ArraySetAsSeries(maValues, true);

ResetLastError();

int copied = CopyBuffer(
   maHandle,
   0,
   1,
   2,
   maValues
);

if(copied != 2)
{
   PrintFormat(
      "CopyBuffer failed: copied=%d, error=%d",
      copied,
      GetLastError()
   );

   return;
}

The code checks that both requested values were copied before allowing the EA to use them.

This is important because indicator calculations and historical data may not be ready when your EA first requests them. Reading the array anyway is a common cause of the array out of range error.

4. Understand Buffer Indexes and Candle Positions

Two different indexes determine which indicator value your EA retrieves:

  • Buffer number: Which indicator data series you want.
  • Candle position: Which candle's indicator value you want.

For example:

MQL5
CopyBuffer(maHandle, 0, 1, 2, maValues);

This means:

  • Buffer 0: Read the first indicator buffer.
  • Start position 1: Begin with the most recently completed candle.
  • Count 2: Retrieve two values.

Candle positions are counted backwards:

Position Candle
0 Current, still-forming candle
1 Most recently completed candle
2 Previous completed candle

This distinction matters when your EA should only trade using confirmed candle values.

For example, a moving average crossover calculated using position 0 can change before the current candle closes. Using positions 1 and 2 allows the EA to compare completed candles instead.

Understand the destination array order

CopyBuffer() places the oldest copied value at the beginning of the array's physical memory.

For a dynamic array, using:

MQL5
ArraySetAsSeries(maValues, true);

allows you to access the copied values in reverse chronological order:

  • maValues[0] — newest requested value.
  • maValues[1] — older requested value.

Without series indexing, the logical array indexes follow the opposite order.

Be consistent with your indexing so your EA doesn't accidentally compare the wrong candles.

5. Use CopyBuffer() with Custom Indicators

The same process works with custom indicators.

Create a handle using iCustom():

MQL5
int customHandle = iCustom(
   _Symbol,
   PERIOD_CURRENT,
   "MyCustomIndicator"
);

The compiled indicator must be available in the appropriate MQL5/Indicators location, and its input parameters must match its declared inputs.

Then retrieve its values:

MQL5
if(customHandle == INVALID_HANDLE)
{
   Print("Custom indicator handle creation failed");
   return;
}

double customValues[];

ArraySetAsSeries(customValues, true);

int copied = CopyBuffer(
   customHandle,
   0,
   1,
   2,
   customValues
);

if(copied != 2)
{
   PrintFormat("Failed to retrieve custom indicator data: %d",
               GetLastError());
   return;
}

Buffer 0 is only an example. If the indicator has multiple buffers, check its source code or documentation to identify the correct buffer number.

6. Release Indicator Handles

When your EA no longer needs an indicator, release its handle using IndicatorRelease().

This is normally done in OnDeinit():

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

You generally don't need to release and recreate an indicator on every tick. Keep the handle while the EA needs it, then release it during deinitialization.

Complete Example: Moving Average Handle in an EA

The following EA creates a 20-period moving average, retrieves its two most recently completed values and prints them in the Experts log.

MQL5
int maHandle = INVALID_HANDLE;

int OnInit()
{
   maHandle = iMA(
      _Symbol,
      PERIOD_CURRENT,
      20,
      0,
      MODE_SMA,
      PRICE_CLOSE
   );

   if(maHandle == INVALID_HANDLE)
   {
      Print("MA handle creation failed: ", GetLastError());
      return INIT_FAILED;
   }

   return INIT_SUCCEEDED;
}

void OnTick()
{
   if(maHandle == INVALID_HANDLE)
      return;

   if(BarsCalculated(maHandle) < 2)
      return;

   double maValues[];

   ArraySetAsSeries(maValues, true);

   ResetLastError();

   int copied = CopyBuffer(
      maHandle,
      0,
      1,
      2,
      maValues
   );

   if(copied != 2)
   {
      PrintFormat(
         "CopyBuffer failed: copied=%d, error=%d",
         copied,
         GetLastError()
      );
      return;
   }

   double currentClosedMA  = maValues[0];
   double previousClosedMA = maValues[1];

   if(currentClosedMA == EMPTY_VALUE ||
      previousClosedMA == EMPTY_VALUE)
      return;

   PrintFormat(
      "Current closed MA: %.5f | Previous closed MA: %.5f",
      currentClosedMA,
      previousClosedMA
   );
}

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

This example doesn't place trades. It demonstrates the essential handle lifecycle: creation, data retrieval, validation and release.

Conclusion

MQL5 indicator handles and CopyBuffer() work together. The handle identifies the indicator, while CopyBuffer() retrieves its calculated values.

When indicator data is missing or incorrect, check four things:

  1. Was the handle created successfully?
  2. Has the indicator calculated enough values?
  3. Did CopyBuffer() return the requested number of elements?
  4. Are you reading the correct buffer and candle positions?

Getting these details right helps prevent unreliable indicator readings and incorrect EA signals.

Rather not write the handle and buffer code yourself? In PositionAlpha's Bot Builder you describe when the strategy buys or sells and how it gets out, and the AI writes the MT5 Expert Advisor with every rule explained. Compile it and test it in the Strategy Tester and on a demo account before you rely on it.

Build a bot from your idea

Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.

More from the blog