MQL5 CopyBuffer Error 4806: Fix Indicator Data Not Found

MQL5 CopyBuffer Error 4806: Fix Indicator Data Not Found

By HorizonAI Team · 13 min read · Intermediate

MQL5 CopyBuffer Error 4806: Why It Happens and How to Fix It

Your EA creates an RSI, EMA, ATR, or custom-indicator handle successfully, then CopyBuffer() suddenly returns -1. The log shows error 4806, often on the first ticks after attaching the EA or at the beginning of a Strategy Tester pass. The tempting response is to recreate the handle on every tick. That usually makes the problem worse.

Short answer: MQL5 error 4806 is INDICATOR_DATA_NOT_FOUND. Your indicator handle exists, but the terminal hasn't calculated enough indicator-buffer data to satisfy the CopyBuffer() request yet. Create handles once in OnInit(), check BarsCalculated() before reading, then treat a CopyBuffer() result other than the requested count as a failed read.

Full answer: build the indicator lifecycle around three rules: create each handle once, wait for enough calculated bars, and only trade from values copied successfully. For a closed-bar signal, request start_pos = 1, not 0. That avoids using the still-forming bar and makes live execution match your intended bar-close logic much more closely.

What error 4806 actually means

The official MQL5 error table defines 4806 as indicator data not found. It is not automatically evidence that your RSI period is wrong, that buffer 0 doesn't exist, or that the terminal cannot download history. It means the requested calculated data wasn't available at the moment of the call. MQL5's error-code reference is the useful source of truth here.

An indicator handle is a request for an indicator calculation, not a guarantee that every historical output value already exists. MQL5 can create the handle while price history synchronizes and while the terminal calculates the indicator in the background. The gap is easy to miss because a chart that has been open for hours is normally ready by the time you attach an EA.

You will see 4806 most often in these situations:

  • The EA has just been initialized and the first OnTick() arrives before an indicator has finished calculating.
  • You request more historical values than the indicator has calculated.
  • You test a symbol or timeframe with shallow history, especially at the start of a Strategy Tester range.
  • A custom indicator has multiple buffers, but you request a buffer that isn't ready for the selected range.
  • You ignore a partial copy. CopyBuffer() may return a count smaller than you requested, which is a failed read for a signal that needs every value.

The cure is not a blind Sleep() inside OnTick(). An EA should skip that evaluation, log the state when needed, and try again on the next tick. The terminal will eventually have the data if history and the handle are valid.

Diagnose the failure in the right order

Start with the return value. CopyBuffer() returns the number of elements copied, or -1 on failure. Read _LastError immediately after a failure, because any later terminal call can overwrite it. The CopyBuffer documentation also makes clear that start_pos = 0 refers to the current bar, with older bars addressed by larger positions.

Use this decision tree before changing your strategy logic:

  1. Is the handle INVALID_HANDLE? The failure happened during iRSI, iMA, iCustom, or another handle-creation call. Log GetLastError() in OnInit() and return INIT_FAILED rather than proceeding.
  2. Does BarsCalculated(handle) return fewer bars than your setup needs? This is the normal 4806 path. Skip the signal and wait.
  3. Did CopyBuffer() return -1 with 4806? The buffer isn't ready for that request. Don't use an old variable value by accident.
  4. Did it return 0 or a partial count? Treat that as a failure too. A two-value crossover read that copies one value is not a crossover read.
  5. Did it return the full requested count? Only now use the copied values in entry logic.

BarsCalculated() reports the number of calculated data items for an indicator buffer, and its own documentation recommends retrying later when the calculation is not ready. The reference example uses this exact readiness check.

Rule: a valid handle and ready data are separate checks. Passing the first doesn't allow you to skip the second.

Build handles once, then release them cleanly

Create standard indicator handles in OnInit(). This gives you one predictable place to validate parameters and handle creation. Returning INIT_FAILED stops a broken EA before it can send any trade request. MQL5 documents OnInit() as the initialization event handler for EAs and indicators. See the event-handler reference.

Do not put int rsiHandle = iRSI(_Symbol, _Period, 14, PRICE_CLOSE); inside OnTick(). It creates a fresh calculation handle on every tick. It obscures the real problem, wastes work, and makes it harder to release resources correctly.

Use this lifecycle instead:

StageWhat to doWhy it prevents bad reads
OnInit()Create RSI, EMA, ATR, or custom handles once.A failed handle is detected before trading logic starts.
OnTick()Check bar timing and BarsCalculated() before CopyBuffer().The EA ignores incomplete calculations.
After every copyRequire the exact number of requested values.Partial arrays never become signals.
OnDeinit()Call IndicatorRelease() for every valid handle.The EA releases terminal resources cleanly.

If you're converting a TradingView strategy, remember that a Pine series usually feels instantly available because the platform manages the history loop for you. In MQL5, the EA explicitly asks the terminal for values. Our manual Pine Script-to-MQL5 translation guide covers the broader differences; 4806 is one of the practical reasons an otherwise faithful translation can fail on its first live ticks.

Working RSI and EMA EA with safe buffer reads

The EA below enters only on a new bar. It reads the last closed bar at shift 1, waits until its RSI and two EMA handles have enough calculated values, and refuses to trade if any one-buffer copy fails.

The signal is deliberately simple so the data-handling pattern stays visible:

  • Buy when RSI(14) is below 30 and EMA(9) is above EMA(21).
  • Sell when RSI(14) is above 70 and EMA(9) is below EMA(21).
  • Use a 300-point stop loss and a 600-point take profit.
  • Allow only one position per symbol and magic number.
#property strict
#property version   "1.00"
#property description "Safe CopyBuffer pattern for RSI and EMA indicator handles"

#include <Trade/Trade.mqh>

CTrade trade;

input int    RsiPeriod        = 14;
input int    FastEmaPeriod    = 9;
input int    SlowEmaPeriod    = 21;
input double OversoldLevel    = 30.0;
input double OverboughtLevel  = 70.0;
input double Lots             = 0.10;
input int    StopLossPoints   = 300;
input int    TakeProfitPoints = 600;
input long   MagicNumber      = 4806001;

int      rsiHandle     = INVALID_HANDLE;
int      fastEmaHandle = INVALID_HANDLE;
int      slowEmaHandle = INVALID_HANDLE;
datetime lastBarTime   = 0;

// Returns true only after the indicator has calculated enough values.
bool WaitForIndicatorData(const int handle,
                          const int requiredBars,
                          const string indicatorName)
{
   if(handle == INVALID_HANDLE)
   {
      PrintFormat("%s handle is invalid.", indicatorName);
      return false;
   }

   int calculatedBars = BarsCalculated(handle);
   if(calculatedBars < requiredBars)
   {
      PrintFormat("%s is not ready: BarsCalculated=%d, required=%d",
                  indicatorName, calculatedBars, requiredBars);
      return false;
   }

   return true;
}

// Reads one buffer element and rejects errors, zero copies, and partial copies.
bool ReadBufferValue(const int handle,
                     const int bufferIndex,
                     const int shift,
                     double &value,
                     const string indicatorName)
{
   double values[];
   ArraySetAsSeries(values, true);

   ResetLastError();
   int copied = CopyBuffer(handle, bufferIndex, shift, 1, values);
   if(copied != 1)
   {
      int errorCode = GetLastError();
      PrintFormat("CopyBuffer failed for %s. copied=%d, error=%d",
                  indicatorName, copied, errorCode);
      return false;
   }

   value = values[0];
   return true;
}

// Prevents duplicate entries from this EA on the current symbol.
bool HasOpenPositionForThisEA()
{
   for(int index = PositionsTotal() - 1; index >= 0; index--)
   {
      ulong ticket = PositionGetTicket(index);
      if(ticket == 0)
         continue;

      string positionSymbol = PositionGetString(POSITION_SYMBOL);
      long positionMagic = PositionGetInteger(POSITION_MAGIC);

      if(positionSymbol == _Symbol && positionMagic == MagicNumber)
         return true;
   }

   return false;
}

bool IsNewBar()
{
   datetime currentBarTime = iTime(_Symbol, _Period, 0);
   if(currentBarTime == 0)
      return false;

   if(currentBarTime == lastBarTime)
      return false;

   lastBarTime = currentBarTime;
   return true;
}

int OnInit()
{
   if(RsiPeriod < 2 || FastEmaPeriod < 2 || SlowEmaPeriod < 2 || Lots <= 0.0)
   {
      Print("Invalid input parameters.");
      return INIT_PARAMETERS_INCORRECT;
   }

   rsiHandle     = iRSI(_Symbol, _Period, RsiPeriod, PRICE_CLOSE);
   fastEmaHandle = iMA(_Symbol, _Period, FastEmaPeriod, 0, MODE_EMA, PRICE_CLOSE);
   slowEmaHandle = iMA(_Symbol, _Period, SlowEmaPeriod, 0, MODE_EMA, PRICE_CLOSE);

   if(rsiHandle == INVALID_HANDLE || fastEmaHandle == INVALID_HANDLE || slowEmaHandle == INVALID_HANDLE)
   {
      PrintFormat("Indicator handle creation failed. error=%d", GetLastError());
      return INIT_FAILED;
   }

   trade.SetExpertMagicNumber((ulong)MagicNumber);
   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   if(rsiHandle != INVALID_HANDLE)
      IndicatorRelease(rsiHandle);
   if(fastEmaHandle != INVALID_HANDLE)
      IndicatorRelease(fastEmaHandle);
   if(slowEmaHandle != INVALID_HANDLE)
      IndicatorRelease(slowEmaHandle);
}

void OnTick()
{
   if(!IsNewBar())
      return;

   // Shift 1 means the completed candle. Add a small margin for warm-up history.
   int requiredBars = SlowEmaPeriod + 2;
   if(RsiPeriod + 2 > requiredBars)
      requiredBars = RsiPeriod + 2;

   if(!WaitForIndicatorData(rsiHandle, requiredBars, "RSI"))
      return;
   if(!WaitForIndicatorData(fastEmaHandle, requiredBars, "Fast EMA"))
      return;
   if(!WaitForIndicatorData(slowEmaHandle, requiredBars, "Slow EMA"))
      return;

   double rsiClosed;
   double fastEmaClosed;
   double slowEmaClosed;

   if(!ReadBufferValue(rsiHandle, 0, 1, rsiClosed, "RSI"))
      return;
   if(!ReadBufferValue(fastEmaHandle, 0, 1, fastEmaClosed, "Fast EMA"))
      return;
   if(!ReadBufferValue(slowEmaHandle, 0, 1, slowEmaClosed, "Slow EMA"))
      return;

   if(HasOpenPositionForThisEA())
      return;

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   if(ask <= 0.0 || bid <= 0.0)
      return;

   if(rsiClosed < OversoldLevel && fastEmaClosed > slowEmaClosed)
   {
      double stopLoss = NormalizeDouble(ask - StopLossPoints * _Point, _Digits);
      double takeProfit = NormalizeDouble(ask + TakeProfitPoints * _Point, _Digits);

      if(!trade.Buy(Lots, _Symbol, 0.0, stopLoss, takeProfit, "RSI EMA buy"))
         PrintFormat("Buy failed: %s", trade.ResultRetcodeDescription());
   }
   else if(rsiClosed > OverboughtLevel && fastEmaClosed < slowEmaClosed)
   {
      double stopLoss = NormalizeDouble(bid + StopLossPoints * _Point, _Digits);
      double takeProfit = NormalizeDouble(bid - TakeProfitPoints * _Point, _Digits);

      if(!trade.Sell(Lots, _Symbol, 0.0, stopLoss, takeProfit, "RSI EMA sell"))
         PrintFormat("Sell failed: %s", trade.ResultRetcodeDescription());
   }
}

This is an EA template, not a claim that the RSI/EMA rule has an edge on every market. Its important artifact is the read path: readiness gate, exact-copy check, closed-bar indexing, and early return.

Closed bar versus current bar: choose the index deliberately

CopyBuffer(handle, 0, 0, 1, values) reads the current, unfinished candle. CopyBuffer(handle, 0, 1, 1, values) reads the candle that has closed. Neither call is inherently wrong, but they answer different questions.

For a bar-close EA, use shift 1. RSI and moving averages can still change as ticks update the open candle, so shift 0 can trigger a condition intrabar that disappears before the candle closes. This is the MQL5 equivalent of the timing problem behind Pine Script repainting.

If you really need an intrabar system, read shift 0, evaluate on every tick, and design the order rules around that fact. Don't accidentally combine a new-bar gate with shift 0 and assume you are getting a continuously updated signal.

A crossover needs more data than the one-value helper above. Request two values and require copied == 2:

bool ReadTwoClosedValues(const int handle, double &latestClosed, double &previousClosed)
{
   double values[];
   ArraySetAsSeries(values, true);

   ResetLastError();
   int copied = CopyBuffer(handle, 0, 1, 2, values);
   if(copied != 2)
   {
      PrintFormat("Two-bar CopyBuffer read failed. copied=%d, error=%d",
                  copied, GetLastError());
      return false;
   }

   latestClosed = values[0];   // Shift 1
   previousClosed = values[1]; // Shift 2
   return true;
}

Use that helper when the entry condition needs fast[1] > slow[1] and fast[2] <= slow[2]. Checking just the current relationship is a filter, not a crossover.

Strategy Tester and history-loading edge cases

4806 often appears in the Strategy Tester because the first test bars are the least forgiving point in an EA's lifecycle. The tester loads the requested range, initializes the program, and starts producing modeled ticks. Your indicator may not have accumulated the lookback you assumed at the first signal evaluation.

Set your required bar count from the largest lookback plus the values you intend to inspect. For this EA, max(21, 14) + 2 gives 23 calculated bars: enough for the slower EMA, the RSI, and a completed-bar read. A two-bar crossover helper needs the same indicator warm-up plus two closed positions, so add that requirement explicitly.

Also distinguish signal readiness from trading permission. If CopyBuffer() is clean but an order fails, move to the order diagnostics: symbol trade mode, volume step, margin, stop-distance rules, and the server return code. The MT5 EA not opening trades checklist starts where this article ends.

For reproducible logs, print the symbol, timeframe, requested shift, requested count, copied count, BarsCalculated(), and error code. A vague log such as RSI failed hides the one detail that tells you whether this is readiness, a bad handle, or a buffer-selection problem.

Common mistakes that keep 4806 alive

❌ Mistake: recreate the RSI or EMA handle after every failed read. This can restart work repeatedly and masks whether the original calculation is simply warming up.

✅ Do this: create once in OnInit(), leave the handle alone during normal ticks, and retry the read only after BarsCalculated() has reached your threshold.

❌ Mistake: check only CopyBuffer() == -1. A call that requests two values but receives one is also unsafe for a two-bar rule.

✅ Do this: compare the return value to the exact requested count, such as copied != 2, then return without evaluating the setup.

❌ Mistake: use a stale indicator value after a failed call. A double rsiValue from a previous tick may still hold a plausible number, which makes this bug hard to spot.

✅ Do this: keep the indicator value local to the successful-read branch, as the EA template does. If the helper returns false, execution ends before any entry condition.

❌ Mistake: treat shift 0 as the previous candle. It is the active bar. That can change between ticks.

✅ Do this: use shift 1 for closed-bar rules, then use a separate two-value request starting at 1 when you need the prior closed bar too.

❌ Mistake: solve an array bounds warning by changing buffer indexes randomly. Buffer number, bar shift, and destination-array size are separate concepts.

✅ Do this: fix destination indexing with the guide to MQL5 array out-of-range errors, then verify your indicator's documented buffer number independently.

Pro tips for custom indicators and multi-timeframe reads

Name every read in the log. "H1 custom trend buffer 2" tells you far more than "CopyBuffer failed", especially when an EA reads several timeframes.

Warm up to the slowest dependency. If a system uses EMA(200), ATR(14), and a custom indicator that needs 50 bars internally, a 20-bar readiness check is meaningless. Start with at least 202 calculated values for a closed-bar rule and increase it if the custom indicator documents a longer initialization period.

Use the chart timeframe only when it is actually intended. A handle created with PERIOD_H1 must have H1 data ready even if the EA runs on an M5 chart. Log both _Period and the handle's intended timeframe in multi-timeframe systems.

Don't use Sleep() to paper over readiness. It stalls the EA's event handler and doesn't create a reliable data contract. A clean early return is safer, and the next tick performs the same guarded check.

Test the failure path on purpose. Attach the EA to a newly opened symbol or run a short-range tester pass. You want to see the BarsCalculated messages before trusting that a quiet, already-warmed chart proves the code is safe.

Generating this pattern without writing the code yourself

HorizonAI can generate, edit, and compiler-check MQL5 EAs from a plain-English request. Ask for the readiness behavior explicitly, because it is part of the strategy's execution logic, not cosmetic error handling.

Build an MQL5 Expert Advisor using RSI(14), EMA(9), and EMA(21). Create all three indicator handles in OnInit and release them in OnDeinit. On each new bar, require BarsCalculated to be at least max lookback plus 2, then use a safe CopyBuffer helper that requires the exact requested count and logs copied count plus GetLastError. Read shift 1 only. Buy when RSI is below 30 and EMA 9 is above EMA 21; sell when RSI is above 70 and EMA 9 is below EMA 21. Use 0.10 lots, a 300-point stop loss, a 600-point take profit, and one position per symbol and magic number.

It returns MQL5 code you can inspect and refine in chat, with real compiler validation to catch code errors before you paste it into MetaEditor. HorizonAI writes the EA code; you decide how and where to run it. Try it free →

FAQs

What is MQL5 error 4806?

Error 4806 is INDICATOR_DATA_NOT_FOUND. It usually means an indicator handle exists but has not calculated the data requested by CopyBuffer() yet.

Should I call CopyBuffer again immediately after error 4806?

Don't loop or sleep inside the same tick. Check BarsCalculated(), return from the signal evaluation, and let a later tick retry after the terminal has had time to calculate the buffer.

Why does CopyBuffer work on a chart but fail in Strategy Tester?

A long-open chart may already have plenty of history and calculated indicator values. A tester starts at the beginning of its selected history and exposes missing warm-up checks immediately.

Is CopyBuffer shift 0 repainting?

Shift 0 reads the still-forming current bar, so its value can change with incoming ticks. Use shift 1 if your rule is meant to make decisions only after a candle closes.

Final thoughts

Error 4806 is a timing and data-readiness problem. Treat the handle, calculation state, copied-count result, and bar shift as separate checks, and your EA stops turning a temporary missing value into a bad signal or a silent failure.

One practical habit pays off quickly: make every CopyBuffer() read prove it copied exactly what the entry rule needs before the rule can see a value. That single boundary eliminates a large class of fragile MT5 EAs.

Related articles

Questions about MQL5 CopyBuffer error 4806? Join our Discord to discuss with other traders!