Error 4806 while copying buffers

 

Hello, I am extremely new to MQL5 and MetaTrader in general. I thought I would take a shot at making my own little EA for fun just to get my feet wet in MQL5. I followed a tutorial at www.mql5.com/en/articles/100, but tried to change it to use the CCI indicator only. I thought I did it right, but I am getting error 4806 when copying the buffers.

 

/*
   Lets make sure our array values for the Rates and CCI values
   are stored serially, similar to the timeseries array
*/
//The Rates arrays
   ArraySetAsSeries(mrate,true);
//The CCI DI+values arrays
   ArraySetAsSeries(plsDI,true);
//The CCI DI-values arrays
   ArraySetAsSeries(minDI,true);
//The CCI values arrays
   ArraySetAsSeries(cciVal,true);

I have already checked for an invalid handle earlier in the code 

//---What if handle returns Invalid Handle

   if(cciHandle<0)

      {

      Alert("Error Creating Handle for Indicator - error: ",GetLastError(),"!!");

       return(-1);

      } 

Are the parameters established at the beginning wrong?

 int cciHandle;                   //Handle for CCI Indicator

double plsDI[],minDI[],cciVal[]; //Dynamic arrays to hold values of +DI -DI and CCI values for each bar

double p_close;                  //Variable to store the close price of each bar

int STP, TKP;                    //Used for Stop Loss and Take Profit values

Am I getting the handle wrong?

//---Get handle for CCI Indicator

   cciHandle=iCCI(NULL,0,CCI_Period,PRICE_CLOSE); 

Or is it something wrong with the arrays?

/*

   Lets make sure array values for the Rates and CCI values

   are stored serially, similar to the timeseries array

*/

//The Rates arrays

   ArraySetAsSeries(mrate,true);

//The CCI DI+values arrays

   ArraySetAsSeries(plsDI,true);

//The CCI DI-values arrays

   ArraySetAsSeries(minDI,true);

//The CCI values arrays

   ArraySetAsSeries(cciVal,true); 

I'm very very new to this and apologize if this is a stupid, or repeated question, but any help is greatly appreciated!
 
You show a lot of code but not the one relevant to error 4806, which is CopyBuffer().
 

Okay, I apologize in advance, this will be a lot of code, if it's too much to ask, I understand. I copied the tutorial listed above but only changed the indicators.

The original is the file attached

 And what I did. There is no CopyBuffer() anywhere, only in the if statements (on either set of code)

//+------------------------------------------------------------------+
//|                                                   CCI Trader.mq5 |
//|                                     Copyright 2016, MetaQuotes   |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2016, MetaQuotes"
#property link      "https://www.mql5.com"
#property version   "1.00"
//--- input parameters
input int      StopLoss=15;     //Stop Loss
input int      TakeProfit=50;  //Take Profit
input int      CCI_Period=14;  //CCI Period
input int      EA_Magic=12345; //EA Magic Number
input int      CCI_Min = -150.0;  //Minimum CCI Value
input int      CCI_Crossover = -100;  //CCI cross of -100 for buy
input int      CCI_Sell_Value = 115;  //CCI cross of 115 for sell
input double   Lot=1.0;        //Number of lots to trade
//--- Other Parameters
int cciHandle;                   //Handle for CCI Indicator
double plsDI[],minDI[],cciVal[]; //Dynamic arrays to hold values of +DI -DI and CCI values for each bar
double p_close;                  //Variable to store the close price of each bar
int STP, TKP;                    //Used for Stop Loss and Take Profit values
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---Get handle for CCI Indicator
   cciHandle=iCCI(NULL,0,CCI_Period,PRICE_CLOSE);
   
//---What if handle returns Invalid Handle
   if(cciHandle<0)
      {
      Alert("Error Creating Handle for Indicator - error: ",GetLastError(),"!!");
       return(-1);
      }
      
//--- Lets handle currency pairs with 5 or 3 digits instead of 4
   STP = StopLoss;
   TKP = TakeProfit;
   if(_Digits==5 || _Digits==3)
   {
    STP = STP*10;
    TKP = TKP*10;
   }
   return(0); 
  
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---Release our Indicator Handle
   IndicatorRelease(cciHandle);
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---Do we have enough bars in the chart to work with
   if(Bars(_Symbol,_Period)<36) //if the total bars are less than 36
      {
      Alert("We have less than 36 bars, EA will now exit!!");
      return;
      }
      
//We will use the static Old_Time variable to serve the bar time.
//At each OnTick execution we will check the current bar time against the saved one.
//If the bar time does not equal the saved time, it indicated a new tick.

   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;
   
//Copying the last bar time to the element New_Time[0]
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0) //Okay, the data has been copied successfully
      {
       if(Old_Time!=New_Time[0])  //If the old time IS NOT equal to the new bar time
        {
         IsNewBar=true;  //If it isn't a first call, the new bar has appeared
         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have a new bar here ",New_Time[0]," old time was ",Old_Time);
         Old_Time=New_Time[0];    //Saving bar time, the new time now becomes the old time, awaiting another new time.
        }    
     }
    else
    {
     Alert("Error in copying historical times data, error =",GetLastError());
     ResetLastError();
     return;
    } 
//---EA should only check for a new trade if we have a new bar
   if(IsNewBar==false)
   {
    return;
   }
   
//---Do we have enough bars to work with
   int Mybars=Bars(_Symbol,_Period);
   if(Mybars<36) //If total bars is less than 36
     {
      Alert("We have less than 36 bars, EA will now exit!!");
      return;
     }
     
//---Define some MQL5 Structures we will use for our trade
   MqlTick latest_price;       //To be used for getting recent/latest price quotes
   MqlTradeRequest mrequest;   //To be used for sending our trade requests
   MqlTradeResult mresult;     //To be used to get the results of our trade
   MqlRates mrate[];           //To be used to store the prices, volumes, and spread of each bar
   ZeroMemory(mrequest);       //Initialization of mrequest structure
/*
   Lets make sure our array values for the Rates and CCI values
   are stored serially, similar to the timeseries array
*/
//The Rates arrays
   ArraySetAsSeries(mrate,true);
//The CCI DI+values arrays
   ArraySetAsSeries(plsDI,true);
//The CCI DI-values arrays
   ArraySetAsSeries(minDI,true);
//The CCI values arrays
   ArraySetAsSeries(cciVal,true);
   
   
//---Get the last price quote using the MQL5 MqlTick Structure
   if(!SymbolInfoTick(_Symbol,latest_price))
      {
       Alert("Error getting the latest price quote - error: ",GetLastError(),"!!");
       return;
      }
      
//---Get the details of the last 3 bars
   if(CopyRates(_Symbol,_Period,0,3,mrate)<0)
     {
      Alert("Error copying rates/history data - error: ",GetLastError(),"!!");
      ResetLastError();
      return;
     }
     
//---Copy the new values of our indicator to a buffer using the handle
   if(CopyBuffer(cciHandle,0,0,3,cciVal)<0 || CopyBuffer(cciHandle,1,0,3,plsDI)<0
      || CopyBuffer(cciHandle,2,0,3,minDI)<0)
     {
      Alert("Error copying CCI Indicator Buffers - error: ",GetLastError(),"!!");
      ResetLastError();
      return;
     }
//---We have no errors so continue
//---Do we have open positions already?
   bool Buy_opened=false; //Variable to hold the result of Buy Opened position
   bool Sell_opened=false; //Variable to hold the result of the Sell Opened Position
   
   if(PositionSelect(_Symbol)==true) //We have an open position
      {
       if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
         {
          Buy_opened=true; //It is a buy
         }
       else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
         {
          Sell_opened=true; //It is a sell
         }
      } 
      
//Copy the bar close price for the previous bar prior to the current bar, that is bar 1
   p_close=mrate[1].close;  //bar 1 close price
   
/*
   Check for a long/buy setup: CCI rising from at or below -125 and crossing -100
*/
//---Declare bool type variables to hold buy conditions
   bool Buy_Condition_1 = (cciVal[1]<=CCI_Min) || (cciVal[2]<=CCI_Min) && (cciVal[0]>=CCI_Crossover);
   bool Buy_Condition_2 = (plsDI[0]>minDI[0]); 
   
//---Putting it all together
   if(Buy_Condition_1 && Buy_Condition_2)
      {
       if(Buy_opened)
         {
          Alert("We already have a buy position!!");
          return;
         }
       ZeroMemory(mrequest);
         mrequest.action = TRADE_ACTION_DEAL;                                // immediate order execution
         mrequest.price = NormalizeDouble(latest_price.ask,_Digits);          // latest ask price
         mrequest.sl = NormalizeDouble(latest_price.ask - STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.ask + TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = _Symbol;                                         // currency pair
         mrequest.volume = Lot;                                            // number of lots to trade
         mrequest.magic = EA_Magic;                                        // Order Magic Number
         mrequest.type = ORDER_TYPE_BUY;                                     // Buy Order
         mrequest.type_filling = ORDER_FILLING_FOK;                          // Order execution type
         mrequest.deviation=50;                                            // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         
// get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError());
            ResetLastError();           
            return;
           }
        } 
        
// Check for a short/sell setup, CCI greater than or equal to 115 

//Declare bool type variables to hold the sell conditions
   bool Sell_Condition_1 = (cciVal[0]>=CCI_Sell_Value);
   bool Sell_Condition_2 = (plsDI[0]<minDI[0]);
   
//Putting it all together
   if(Sell_Condition_1 && Sell_Condition_2)
      {
       if(Sell_opened)
         {
          Alert("We already have a sell position!!");
          return;
         }
       ZeroMemory(mrequest);
       mrequest.action=TRADE_ACTION_DEAL;
       mrequest.price = NormalizeDouble(latest_price.bid,_Digits);
       mrequest.sl = NormalizeDouble(latest_price.bid + STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(latest_price.bid - TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = _Symbol;                                          // currency pair
         mrequest.volume = Lot;                                              // number of lots to trade
         mrequest.magic = EA_Magic;                                          // Order Magic Number
         mrequest.type= ORDER_TYPE_SELL;                                     // Sell Order
         mrequest.type_filling = ORDER_FILLING_FOK;                          // Order execution type
         mrequest.deviation=100;                                             // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult);
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Sell order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Sell order request could not be completed -error:",GetLastError());
            ResetLastError();
            return;
           }                             
       }
     return;                           
  }
//+------------------------------------------------------------------+

 Again, I'm sorry if it is too much to ask of any of you, i just learn best by jumping in head first to things, but perhaps I should take a different approach.

Files:
my_first_ea.mq5  12 kb
 
Balthozar09:

Okay, I apologize in advance, this will be a lot of code, if it's too much to ask, I understand. I copied the tutorial listed above but only changed the indicators.

The original is the file attached

 And what I did. There is no CopyBuffer() anywhere, only in the if statements (on either set of code)

 Again, I'm sorry if it is too much to ask of any of you, i just learn best by jumping in head first to things, but perhaps I should take a different approach.

There is no problem with this code.
 
Alain Verleyen:
There is no problem with this code.
Hmm. It compiles just fine, but when I go to test it, I get error 4806. Could it be possible that MetaTrader hasn't had enough time to calculate the indicator data and the handle isn't pointing to the correct data?