Array out of range - Please help !!! - MQL5 Programing

 
I am new to mql5 programming. I wrote a basic code like this. But it is not possible to run it completely.

I hope you guys with experience here can help me fix it. Thanks a lot !

Here is my code:

input double lotsize  =  0.1;
input int    SL       =  100;
input double RR       =  1.5;
input int   GiatriMA1 =  200;
input int   GiatriMA2 =  600;

#include <Trade/Trade.mqh>

int handlema1;
int handlema2;
int handle;
int barsTotal;

CTrade trade;
ulong posTicket;

int OnInit()   {
   handlema1   = iMA(_Symbol,PERIOD_CURRENT,GiatriMA1,0,MODE_EMA,PRICE_CLOSE);
   handlema2   = iMA(_Symbol,PERIOD_CURRENT,GiatriMA2,0,MODE_EMA,PRICE_CLOSE);
   handle      = iMACD(_Symbol, PERIOD_CURRENT, 12, 26, 9, PRICE_CLOSE);
   barsTotal   = iBars(_Symbol, PERIOD_CURRENT);

   return(INIT_SUCCEEDED);
}

void OnDeinit (const int reason) {

}

void OnTick()  {
   int bars = iBars(_Symbol, PERIOD_CURRENT);
   if (bars > barsTotal)   {
      barsTotal = bars;
      
      double close =  iClose(Symbol(), Period(), 1);
      double ma1[2];
      CopyBuffer(handlema1,MAIN_LINE,1,2,ma1);
      double ma2[2];
      CopyBuffer(handlema2,MAIN_LINE,1,2,ma2);
      double macd[];
      CopyBuffer(handle, MAIN_LINE,1, 2, macd);
      double signal[];
      CopyBuffer(handle, SIGNAL_LINE,1, 2, signal);
      
      if (  close >  ma1[1]
         && ma1[1]   >  ma2[1]
         && close >  ma2[1]
         && macd[1]<0
         && macd[1]>signal[1]
         && macd[2]<=signal[2] ) {
         Print(__FUNCTION__," > LUCAS Tin Hieu: Buy...");
         
         double ask        = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
         double stoploss   = ask - SL * _Point;
                stoploss   = NormalizeDouble(stoploss,_Digits);
         double takeprofit = ask + (RR*SL) *_Point  ;
                takeprofit = NormalizeDouble(takeprofit,_Digits);
         
         if(trade.Buy(lotsize,_Symbol,0,stoploss,takeprofit)) {
            posTicket =trade.ResultOrder();
         }
      }else if(  close  <  ma1[1]
               && ma1[1]   <  ma2[1]
               && close <  ma2[1]
               && macd[1]>0
               && macd[1]<signal[1]
               && macd[2]>=signal[2] ) {
         Print(__FUNCTION__," > LUCAS Tin Hieu: Sell...");
         
         double bid        = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         double stoploss   = bid +    SL   * _Point;
                stoploss   = NormalizeDouble(stoploss,_Digits);
         double takeprofit = bid - (RR*SL) * _Point  ;
                takeprofit = NormalizeDouble(takeprofit,_Digits);
         
         if(trade.Sell(lotsize,_Symbol,0,stoploss,takeprofit))   {
            posTicket = trade.ResultOrder(); 
         } 
      }
      
      
      Comment("\nBars Total: ",barsTotal,
               "\nMacd[0]: ",DoubleToString(macd[0],4),
               "\nMacd[1]: ",DoubleToString(macd[1],4),
               "\nSignal[0]: ", DoubleToString(signal[0],4),
               "\nSignal[1]: ", DoubleToString(signal[1],4));
    }
}
 
Nguyen Ncoc Minh:
I am new to mql5 programming. I wrote a basic code like this. But it is not possible to run it completely.

I hope you guys with experience here can help me fix it. Thanks a lot !

Here is my code:

Can you try double inputs with .0's, such as 2.0 instead of 2.

 
Evren Caglar #:

Can you try double inputs with .0's, such as 2.0 instead of 2.

thank for your response.
On what lines do I need to do this. I really don't understand?

 
Nguyen Ncoc Minh:
I am new to mql5 programming. I wrote a basic code like this. But it is not possible to run it completely.

I hope you guys with experience here can help me fix it. Thanks a lot !

Here is my code:

  1. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

  2. Help you with what? You haven't stated a problem. Show us your attempt (using the CODE button) and state the nature of your difficulty.
              No free help (2017)

    Or pay someone. Top of every page is the link Freelance.
              Hiring to write script - General - MQL5 programming forum (2018)

    We're not going to code it for you (although it could happen if you are lucky or the issue is interesting).
              No free help (2017)

  3. int OnInit()   {
       barsTotal   = iBars(_Symbol, PERIOD_CURRENT);
    
    Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

  4.    int bars = iBars(_Symbol, PERIOD_CURRENT);
       if (bars > barsTotal)   {
          barsTotal = bars;
    

    For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
              MT4: New candle - MQL4 programming forum #3 (2014)
              MT5: Accessing variables - MQL4 programming forum #3 (2022)

    I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
              Running EA once at the start of each bar - MQL4 programming forum (2011)

  5.          double ask        = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
             double stoploss   = ask - SL * _Point;
                    stoploss   = NormalizeDouble(stoploss,_Digits);
             double takeprofit = ask + (RR*SL) *_Point  ;
                    takeprofit = NormalizeDouble(takeprofit,_Digits);
    

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  6.       if (  close >  ma1[1]
             && ma1[1]   >  ma2[1]
             && close >  ma2[1]
    
    If close is above one, and one is above two, when will close not be above two?
 

You are using static and dynamic arrays at the same time. This is not a standard behavior. Best approach for CopyBuffer is applying dynamic arrays with timeseries flag set to true. (Check ArraySetAsSeries)

Nguyen Ncoc Minh:
      double ma1[2];       CopyBuffer(handlema1,MAIN_LINE,1,2,ma1);

In the above line you are copying indicator values from index=1.

Which means ma1[1] holds the previous candle value and ma1[0] holds two candles before.

Note that ma1[2] does not exists and is out of range.

 
Nguyen Ncoc Minh:
I am new to mql5 programming. I wrote a basic code like this. But it is not possible to run it completely.

I hope you guys with experience here can help me fix it. Thanks a lot !

Here is my code:


I don't like to do this since it can be considered bad practice but sometimes when starting out you can get overwhelmed. Here's some code and the reasons why your code might be having issues, MACD can be challenging with the multiple emas and such


input double lotsize  =  0.1;
input int    SL       =  100;
input double RR       =  1.5;
input int   GiatriMA1 =  200;
input int   GiatriMA2 =  600;

#include <Trade/Trade.mqh>

int handlema1;
int handlema2;
int handle;
int barsTotal;

CTrade trade;
ulong posTicket;

int OnInit() {
   handlema1 = iMA(_Symbol, PERIOD_CURRENT, GiatriMA1, 0, MODE_EMA, PRICE_CLOSE);
   handlema2 = iMA(_Symbol, PERIOD_CURRENT, GiatriMA2, 0, MODE_EMA, PRICE_CLOSE);
   handle = iMACD(_Symbol, PERIOD_CURRENT, 12, 26, 9, PRICE_CLOSE);
   
   if (handlema1 == INVALID_HANDLE || handlema2 == INVALID_HANDLE || handle == INVALID_HANDLE) {
      Print("Error creating indicator handles");
      return(INIT_FAILED);
   }

   barsTotal = iBars(_Symbol, PERIOD_CURRENT);
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason) {
   // Cleanup code here, if needed
}

void OnTick() {
   int bars = iBars(_Symbol, PERIOD_CURRENT);
   if (bars > barsTotal) {
      barsTotal = bars;
      
      double close = iClose(Symbol(), Period(), 1);
      double ma1[2];
      double ma2[2];
      double macd[3]; // Adjusted to accommodate CopyBuffer call
      double signal[3]; // Adjusted to accommodate CopyBuffer call
      
      if (CopyBuffer(handlema1, 0, 1, 2, ma1) <= 0) {
         Print("Failed to copy buffer for MA1");
         return;
      }
      if (CopyBuffer(handlema2, 0, 1, 2, ma2) <= 0) {
         Print("Failed to copy buffer for MA2");
         return;
      }
      if (CopyBuffer(handle, 0, 1, 3, macd) <= 0) {
         Print("Failed to copy buffer for MACD");
         return;
      }
      if (CopyBuffer(handle, 1, 1, 3, signal) <= 0) {
         Print("Failed to copy buffer for MACD Signal");
         return;
      }
      
      if (close > ma1[1] && ma1[1] > ma2[1] && close > ma2[1] &&
          macd[1] < 0 && macd[1] > signal[1] && macd[2] <= signal[2]) {
         Print(__FUNCTION__, " > LUCAS Tin Hieu: Buy...");
         
         double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
         double stoploss = NormalizeDouble(ask - SL * _Point, _Digits);
         double takeprofit = NormalizeDouble(ask + (RR * SL) * _Point, _Digits);
         
         if (trade.Buy(lotsize, _Symbol, ask, stoploss, takeprofit)) {
            posTicket = trade.ResultOrder();
         }
      } else if (close < ma1[1] && ma1[1] < ma2[1] && close < ma2[1] &&
                 macd[1] > 0 && macd[1] < signal[1] && macd[2] >= signal[2]) {
         Print(__FUNCTION__, " > LUCAS Tin Hieu: Sell...");
         
         double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         double stoploss = NormalizeDouble(bid + SL * _Point, _Digits);
         double takeprofit = NormalizeDouble(bid - (RR * SL) * _Point, _Digits);
         
         if (trade.Sell(lotsize, _Symbol, bid, stoploss, takeprofit)) {
            posTicket = trade.ResultOrder();
         }
      }
      
      Comment("\nBars Total: ", barsTotal,
              "\nMacd[0]: ", DoubleToString(macd[0], 4),
              "\nMacd[1]: ", DoubleToString(macd[1], 4),
              "\nSignal[0]: ", DoubleToString(signal[0], 4),
              "\nSignal[1]: ", DoubleToString(signal[1], 4));
   }
}

1.Make sure that that the indicator handles are properly initialized and check their return values.
2. Initialize arrays to ensure they have the correct size before calling CopyBuffer .
3. Make sure you're using the correct indices when working with the arrays.
!!! Add error handling to ensure you know if something goes wrong with the indicator buffers.