0

I have the code below that is flagged as 'Index out of range exception' in the first print statement in Visual Studio, but the problem is when I hover over the values, they are all what I would expect (i.e c=1), while the Autos window shows: CurrentBar = 907, LSwDMIbar = 905, c = 1. There is an exception line in the Locals window, but when I expand that, it's not giving me any clue either I've had this issue in the past and when debugging with VS, I could see the negative values, but I can't see anything now.

I traced it down to FlatDMI[a] print in if (PrintDmiSwing && c > 0) block, but I don't understand why.

Where can I look to find the error?

Thank you

  private int c;
   ... 

  if (!FlatInd && Math.Abs(DMI1[1] - DMI1[2]) < 0.0001)   
  {

    var newFlat = DMI1[1];
    FlatDMI.Add(newFlat);
    FlatInd = true;
    if (!FlatIndBar)
    {
      flatDMIbar = CurrentBar - 2;   
      FlatIndBar = true;                                
    }
       if (PrintFlat && a > 0)
         Print("Flat DMI | " + Time[0] + " | Current Bar = " + CurrentBar 
         + string.Format("\r\nFlatDMI[0] =  {0 :F4} | FlatDMI[1] =  {1:F4}", 
         FlatDMI[a], FlatDMI[a-1]) + " | flatDMIbar = " + flatDMIbar + " | a  
          = " + a + "\r\n-");        
     a++;                           
    }
   else
  { 
  FlatInd = false;
  FlatIndBar = false;                           
 }
 if (!LSwDMIbool && DMI1[1] - DMI1[2] > 0.001 && DMI1[3] - DMI1[2] > 
 0.001)
 {                      
    lSwDMI = DMI1[2];
    LSwDMI.Add(lSwDMI);
    LSwDMIbar = CurrentBar - 2;
    var lSwDMIprice = Lows[2].GetValueAt(LSwDMIbar);
    LSwDMIprice.Add(lSwDMIprice);                       
    LSwDMIbool = true;                        
    if (PrintDmiSwing && c > 0)
   {
     Print("DMI Swing Low | " + Time[0] + " | Current Bar = " + CurrentBar 
    + string.Format("\r\nLSwDMI[0] = {0:F4} | LSwDMI[1] = {1:F4}", 
    LSwDMI[c], LSwDMI[c - 1]) + " | FlatDMI[a] = " + FlatDMI[a] + " 
    | LSwDMIbar = " + LSwDMIbar + " | LSwDMIprice[0] = " +     
    LSwDMIprice[c] + " | LSwDMIprice[1] = " + LSwDMIprice[c - 1] + " | c = 
    " + c + "\r\n-");
    foreach (double lSwDM in LSwDMI)
      Print(string.Format("LSwDMI = {0:F4}", lSwDM));
   }    
   c++;                                         
  }     
  • you have lots of indexes, do range checks before you access any index – Charles Jan 05 '20 at 17:50
  • I have to say I am happy I don't have to maintain this code :) Why all these array accesses, can't you have something a bit more defined? Is it an `IndexOutOfRangeException` exception you are receiving? Which one fails exactly when debugging? – Icepickle Jan 05 '20 at 17:53
  • Thank you for the answers, Gents. Unfortunately, Charles, I don't know how to do range checks. Yes, Icepickle, that is the error I'm getting. Please see the edit – Sorin Pascu Jan 05 '20 at 18:17

0 Answers0