Getting a Problem with code: "Array out of range TrendLines (62, 16)".

 

//+------------------------------------------------------------------+

//|                                                   5MinTrader.mq4 | //|                        Copyright 2024, MetaTrader 4               | //|                                       https://www.mql4.com       | //+------------------------------------------------------------------+ #property strict // Input parameters input double Lots = 0.1; input int StopLoss = 20;            // Stop Loss in pips input int TakeProfit = 50;          // Take Profit in pips input int TrailingStop = 30;        // Trailing Stop in pips input int MagicNumber = 123456;     // Magic Number for trade identification input int Slippage = 3;             // Slippage in points input int ModifyLag = 2000;         // Lag in milliseconds for OrderModify input color SpreadColor = clrYellow; // Color for spread visualization input color DateTimeColor = clrWhite; // Color for date and time visualization // Indicators input int MA_Period = 14;           // Moving Average period input int RSI_Period = 14;          // RSI period input int MACD_FastEMA = 12;        // MACD Fast EMA input int MACD_SlowEMA = 26;        // MACD Slow EMA input int MACD_SignalSMA = 9;       // MACD Signal SMA input int StochK_Period = 5;        // Stochastic K period input int StochD_Period = 3;        // Stochastic D period input int StochSlowing = 3;         // Stochastic slowing input int BollingerBands_Period = 20; // Bollinger Bands period input double BollingerBands_Deviation = 2.0; // Bollinger Bands deviation // Global variables double maCurrent, maPrevious; double rsiCurrent; double macdCurrent, macdSignal; double stochK, stochD; double upperBB, lowerBB; // Custom indicator values double trendLineHigh[62]; double trendLineLow[62]; int OnInit() {     // Initialization     ChartSetInteger(0, CHART_FOREGROUND, true);          // Initialize custom indicator values     ArraySetAsSeries(trendLineHigh, true);     ArraySetAsSeries(trendLineLow, true);     for (int i = 0; i < 62; i++)     {         trendLineHigh[i] = iCustom(NULL, 0, "TrendLines", 0, i);         trendLineLow[i] = iCustom(NULL, 0, "TrendLines", 1, i);     }     return(INIT_SUCCEEDED); } void OnTick() {     // Get indicator values     maCurrent = iMA(NULL, 0, MA_Period, 0, MODE_SMA, PRICE_CLOSE, 0);     maPrevious = iMA(NULL, 0, MA_Period, 0, MODE_SMA, PRICE_CLOSE, 1);     rsiCurrent = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 0);     macdCurrent = iMACD(NULL, 0, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_MAIN, 0);     macdSignal = iMACD(NULL, 0, MACD_FastEMA, MACD_SlowEMA, MACD_SignalSMA, PRICE_CLOSE, MODE_SIGNAL, 0);     stochK = iStochastic(NULL, 0, StochK_Period, StochD_Period, StochSlowing, MODE_SMA, 0, MODE_MAIN, 0);     stochD = iStochastic(NULL, 0, StochK_Period, StochD_Period, StochSlowing, MODE_SMA, 0, MODE_SIGNAL, 0);     upperBB = iBands(NULL, 0, BollingerBands_Period, BollingerBands_Deviation, 0, PRICE_CLOSE, MODE_UPPER, 0);     lowerBB = iBands(NULL, 0, BollingerBands_Period, BollingerBands_Deviation, 0, PRICE_CLOSE, MODE_LOWER, 0);        // Visualize spread     double spread = (Ask - Bid) / Point;     string spreadText = "Spread: " + DoubleToString(spread, 1) + " pips";     ObjectCreate(0, "SpreadLabel", OBJ_LABEL, 0, 0, 0);     ObjectSetInteger(0, "SpreadLabel", OBJPROP_CORNER, CORNER_LEFT_UPPER);     ObjectSetInteger(0, "SpreadLabel", OBJPROP_XDISTANCE, 10);     ObjectSetInteger(0, "SpreadLabel", OBJPROP_YDISTANCE, 10);     ObjectSetInteger(0, "SpreadLabel", OBJPROP_COLOR, SpreadColor);     ObjectSetString(0, "SpreadLabel", OBJPROP_TEXT, spreadText);        // Visualize date and time     string dateTimeText = "Date: " + TimeToString(TimeCurrent(), TIME_DATE) + " Time: " + TimeToString(TimeCurrent(), TIME_MINUTES);     ObjectCreate(0, "DateTimeLabel", OBJ_LABEL, 0, 0, 0);     ObjectSetInteger(0, "DateTimeLabel", OBJPROP_CORNER, CORNER_RIGHT_UPPER);     ObjectSetInteger(0, "DateTimeLabel", OBJPROP_XDISTANCE, 10);     ObjectSetInteger(0, "DateTimeLabel", OBJPROP_YDISTANCE, 10);     ObjectSetInteger(0, "DateTimeLabel", OBJPROP_COLOR, DateTimeColor);     ObjectSetString(0, "DateTimeLabel", OBJPROP_TEXT, dateTimeText);        // Read trend lines     double trendLinePrice = 0.0;     bool trendLineExists = false;        for (int i = ObjectsTotal() - 1; i >= 0; i--)     {         string objName = ObjectName(i);         if (ObjectType(objName) == OBJ_TREND)         {             datetime trendLineTime1 = (datetime)ObjectGetInteger(0, objName, OBJPROP_TIME1);             double trendLinePrice1 = ObjectGetDouble(0, objName, OBJPROP_PRICE1);             datetime trendLineTime2 = (datetime)ObjectGetInteger(0, objName, OBJPROP_TIME2);             double trendLinePrice2 = ObjectGetDouble(0, objName, OBJPROP_PRICE2);                      if (Time[0] >= trendLineTime1 && Time[0] <= trendLineTime2)             {                 trendLinePrice = trendLinePrice1 + (trendLinePrice2 - trendLinePrice1) * (Time[0] - trendLineTime1) / (trendLineTime2 - trendLineTime1);                 trendLineExists = true;                 break;             }         }     }        // Buy conditions     if (maCurrent > maPrevious && rsiCurrent > 50 && macdCurrent > macdSignal && stochK > stochD && Close[0] > upperBB)     {         if (OrdersTotal() == 0 && (!trendLineExists || Close[0] > trendLinePrice))         {             int ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, 0, 0, "Buy order", MagicNumber, 0, Blue);             if (ticket > 0)             {                 if (OrderSelect(ticket, SELECT_BY_TICKET))                 {                     double sl = Bid - StopLoss * Point;                     double tp = Bid + TakeProfit * Point;                     Sleep(ModifyLag);                     if (!OrderModify(ticket, OrderOpenPrice(), sl, tp, 0, clrGreen))                     {                         Print("Error modifying buy order: ", GetLastError());                     }                 }                 else                 {                     Print("Error selecting buy order: ", GetLastError());                 }             }             else             {                 Print("Error sending buy order: ", GetLastError());             }         }     }        // Sell conditions     if (maCurrent < maPrevious && rsiCurrent < 50 && macdCurrent < macdSignal && stochK < stochD && Close[0] < lowerBB)     {         if (OrdersTotal() == 0 && (!trendLineExists || Close[0] < trendLinePrice))         {             int ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, "Sell order", MagicNumber, 0, Red);             if (ticket > 0)             {                 if (OrderSelect(ticket, SELECT_BY_TICKET))                 {                     double sl = Ask + StopLoss * Point;                     double tp = Ask - TakeProfit * Point;                     Sleep(ModifyLag);                     if (!OrderModify(ticket, OrderOpenPrice(), sl, tp, 0, clrRed))                     {                         Print("Error modifying sell order: ", GetLastError());                     }                 }                 else                 {                     Print("Error selecting sell order: ", GetLastError());                 }             }             else             {                 Print("Error sending sell order: ", GetLastError());             }         }     }        // Trailing stop for buy orders     for (int i = 0; i < OrdersTotal(); i++)     {         if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))         {             if (OrderType() == OP_BUY && OrderMagicNumber() == MagicNumber)             {                 double newSL = Bid - TrailingStop * Point;                 if (Bid - OrderOpenPrice() > TrailingStop * Point && OrderStopLoss() < newSL)                 {                     Sleep(ModifyLag);                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrGreen))                     {                         Print("Error modifying trailing stop for buy order: ", GetLastError());                     }                 }             }                      // Trailing stop for sell orders             if (OrderType() == OP_SELL && OrderMagicNumber() == MagicNumber)             {                 double newSL = Ask + TrailingStop * Point;                 if (OrderOpenPrice() - Ask > TrailingStop * Point && OrderStopLoss() > newSL)                 {                     Sleep(ModifyLag);                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), newSL, OrderTakeProfit(), 0, clrRed))                     {                         Print("Error modifying trailing stop for sell order: ", GetLastError());                     }                 }             }         }         else         {             Print("Error selecting order for trailing stop: ", GetLastError());         }     } } int Deinit() {     // Cleanup     ObjectDelete(0, "SpreadLabel");     ObjectDelete(0, "DateTimeLabel");     return(0); }

Yet when I compile  the code, it comes up as a clean run. When doing "BT", it then shows up the error. I've run through coding and still can't find the problem, can I ask for help please? This is for Mt4 Version!.!.!

 
Aldan Parris:

Yet when I compile  the code, it comes up as a clean run. When doing "BT", it then shows up the error. I've run through coding and still can't find the problem, can I ask for help please? This is for Mt4 Version!.!.!

The error could be as a result of incorrect indexing, static array sizes, or non-valid loop bounds. The error on line 62 seems to be trying to access a non valid array in the initialization for loop. Try to print the iteration values like below and make sure the value you're trying to access is indeed valid. 

   for (int i=0; i<ArraySize(staticArray1); i++){//fix < or negate 1 from limit
      Print("Iteration: ",i+1," when index i = ",i);
      Print(i," = ",staticArray1[i]);
   }
 
Allan Munene Mutiiria #:

The error could be as a result of incorrect indexing, static array sizes, or non-valid loop bounds. The error on line 62 seems to be trying to access a non valid array in the initialization for loop. Try to print the iteration values like below and make sure the value you're trying to access is indeed valid. 

Will try this, and if it works thanks alot
 
Aldan Parris:

Yet when I compile  the code, it comes up as a clean run. When doing "BT", it then shows up the error. I've run through coding and still can't find the problem, can I ask for help please? This is for Mt4 Version!.!.!

Apparently, the error is not in the code you posted, but in TrendLines.mq4.

 
Vladislav Boyko #:

Apparently, the error is not in the code you posted, but in TrendLines.mq4.

Noted, I noticed that. I rewrote code still getting error till yesterday!
 
Aldan Parris #:
Noted, I noticed that. I rewrote code still getting error till yesterday!

You published the wrong code. The error occurs in the "TrendLines" file, not in the code you posted.

Here you call that file:

Aldan Parris:
int OnInit()
{
    // Initialization
    ChartSetInteger(0, CHART_FOREGROUND, true);
    
    // Initialize custom indicator values
    ArraySetAsSeries(trendLineHigh, true);
    ArraySetAsSeries(trendLineLow, true);

    for (int i = 0; i < 62; i++)
    {
        trendLineHigh[i] = iCustom(NULL, 0, "TrendLines", 0, i);
        trendLineLow[i] = iCustom(NULL, 0, "TrendLines", 1, i);
    }

You need to fix TrendLines.mq4 (if you have the source code of that indicator)