FOR statement nested in a WHILE

 
Hi I need some help, please. I'm trying do write a script reading an input file creating an otput one. My problem is:

1) I have a WHILE loop to read the input file

2) FOR each record it must do some processing a write an output

3) When the FOR is not in the script ALL the commands are executed

4) When the FOR is there the script "jumps" to the FOR and does not execute the previous lines

please give me a hand. Thanks
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net/"

#property show_inputs

extern int    EmaUsar = 5;             //  EMA a usar
extern double DistEma = 0.00220;       // distância para o Trailing stop da EMA 
extern double OPip    = 0.00015;       // variação a mais para a entrada
extern double BreakEv = 0.00435;       // valor para BreakEven
extern double Target  = 0.99005;  


//--------------------------------------------------------------------
// timetablenews.mq4
// The code should be used for educational purpose only.
//--------------------------------------------------------------- 1 --
int start()                            // Spec. function start()
  {
//--------------------------------------------------------------- 2 --

   Print (" start");
   int Handle,                         // File descriptor
       handleout,                      // ficheiro output
       oper;                           // 1 buy/2 sell buy se open barra < close sell se close > open 
       Print ( " handle ", Handle, " handleout ", handleout);

   int BE,
       registo,
       stopado;
       
   double   nbar,                      // num barra por hora fich input
            nbar1,                     // barra seguinte (-1)
            CLOSESY,                   // close SYNERGY
            VlCalcEnt,                 // O mais alto/baixo entre o Close da barra da hora e Open da barra seguinte
            VlTarget,                  // target = close barra Synergy + Target
            MaxLow,
            MaxHigh,
            result,
            max,
            contra,
            ema,
            stop,
            stopsell,
            HighSY,
            LowSY,
            total,
            nbar15,
            contador,
            OpenSY,
            CloseSY;
        
   string File_Name="teste_1.csv",        // Name of the file
          Str_DtTm,                     // Date and time of the event (line)
          DOper,
          var2;                        // designação operação
          
   datetime Dat_DtTm;                  // Date and time of the event (date)
 
//-----------------------abertura de ficheiros ---------------------------------------- 3 --

   handleout=FileOpen("Teste_Out_15_st_1.csv", FILE_CSV|FILE_WRITE, ",");
     Print ( " 2 "); 
   if(handleout<0)                        // File opening fails
     {
      Alert("Error while opening file Teste_Out.csv ");//..this message
      PlaySound("Trumpet.wav");          // Sound accompaniment
      Print ("erro open output");
      return(0);                              
     }
   
    Print ( " 3 "); 
   Handle=FileOpen(File_Name,FILE_CSV|FILE_READ,";");// File opening
   if(Handle<0)                        // File opening fails
     {
      if(GetLastError()==4103)         // If the file does not exist,..
         Alert("No file named ",File_Name);//.. inform trader
      else                             // If any other error occurs..
         Alert("Error while opening file ",File_Name);//..this message
      PlaySound("Bzrrr.wav");          // Sound accompaniment
      Print ("aqui vai ele 1 ");
      return(0);                          // Exit start()      
     }
    Print ( " 4 ");  
 
//    return;
//--------------------------------------------------------------- 4 --
   while(FileIsEnding(Handle)==false)  // While the file pointer..
     {                                 // ..is not at the end of the file
    
      //--------------------------------------------------------- 5 --
           Print ("aqui vai ele 1 ");
           Print ( " 5 ");
           registo ++;
           
           Str_DtTm =FileReadString(Handle);// Date and time of the event (date)

           if(FileIsEnding(Handle)==true)   // File pointer is at the end
             break;                        // Exit reading and drawing
      //--------------------------------------------------------- 6 --
           Dat_DtTm =StrToTime(Str_DtTm);   // Transformation of data type

//           Print ("  new ", Str_DtTm, " "); 
      
//---------------- aqui vai o processamento

           nbar=iBarShift(NULL, PERIOD_H1, Dat_DtTm, true); // buscar o índice da barra
           nbar1 = nbar -1;
           Print ( " 6 ");
          var2=TimeToStr(iTime(Symbol(),60,nbar),TIME_DATE|TIME_SECONDS); 
           Print (" nbar ", nbar, " hora 60 ", var2);
            Print ( " 7 ");
          if (nbar == -1)
              {
              Print (" barra não encontrada");
              Print (" nbar ", nbar, " hora  ", var2);
              total = total * 10000;
              Print (" resultado ", total);
              return(0);
              }
           Print ( " 8 "); 
          nbar15=iBarShift(NULL, PERIOD_M15, Dat_DtTm, true); // buscar o índice da barra
          var2=TimeToStr(iTime(Symbol(),15,nbar15),TIME_DATE|TIME_SECONDS); 
          Print ( " 9 ");
          Print (" nbar15 ", nbar15, " hora 15m ", var2);
          Print  ( " inicio ");
          if (nbar15 == -1)
              {
              Print (" barra não encontrada");
              Print (" nbar15 ", nbar15, " hora 15m ", var2);
              total = total * 10000;
              Print (" resultado ", total);
              return;
              }
          Print ( " 10 ");
//------------- tipo operação  1 = buy   2 = sell --------------------------------           
           
           
           OpenSY  = iCustom(NULL, 0, "Synergy_APB_PS",2, nbar);
           CloseSY = iCustom(NULL, 0, "Synergy_APB_PS",3, nbar);
           if(OpenSY > CloseSY) oper=2;
           if(OpenSY < CloseSY) oper=1; 
           Print (" oper ", oper, " nbar ", nbar,  " opensy ", OpenSY, " closesy ", CloseSY); 
//----------------- buy
           if (oper == 1)
              {
               CLOSESY=iCustom(NULL, 0, "Synergy_APB_PS",3, nbar);
               VlTarget = CLOSESY + Target;
               VlCalcEnt = (iOpen(Symbol(),60,nbar1)) + OPip;
               if ( (iClose(Symbol(),60,nbar)) > (iOpen(Symbol(),60,nbar1)))
                   {
                    VlCalcEnt = (iClose(Symbol(),60,nbar)) + OPip;
                   } 
               DOper = "buy"; 
              } 
             
//----------------- sell               
           if (oper == 2)
              {
               CLOSESY=iCustom(NULL, 0, "Synergy_APB_PS",3, nbar);
               VlTarget = CLOSESY - Target;
               VlCalcEnt = (iClose(Symbol(),60,nbar)) - OPip;
               if ( (iClose(Symbol(),60,nbar)) > (iOpen(Symbol(),60,nbar1)))
                    VlCalcEnt = (iOpen(Symbol(),60,nbar1)) - OPip;
               DOper  = "sel"; 
              }  
// ------------------   inicia variáveis para o ciclo  
//             VlCalcBE=(iCustom(NULL, 0, "Synergy_APB_PS",1, tbar)); //--- high synergy              
//             MaxLow = 9;
//             MaxHigh = 0;
             MaxLow = (iLow(Symbol(),60,nbar-1));
             MaxHigh = (iHigh(Symbol(),60,nbar-1));
             stop = (iMA(Symbol(),60,EmaUsar,2,MODE_EMA,5,nbar+1) - DistEma);
             stopsell= (iMA(Symbol(),60,EmaUsar,2,MODE_EMA,5,nbar+1) + DistEma);
             Print (" stopsell ", stopsell, " ema ", ema);
             
             string var1=TimeToStr(iTime(Symbol(),60,nbar),TIME_DATE|TIME_SECONDS);
             Print("Current bar for H1: ", var1);
             BE =0;
             stopado=0;
             contador = 0;
             int tbar;

      Print ( " nbar15  ", nbar15);

//   the 7400 is only for testing  
// the inpit file was this
//  2011.02.03 09:00
//  2020.01.01 00:00   

//       for (tbar=nbar15-4;tbar>=0;tbar--)   // accionar tbar=0 quando atingir target ou for stopada
      for (tbar=nbar15-4;tbar>=7400;tbar--)   // accionar tbar=0 quando atingir target ou for stopada
           {
              ema = (iMA(Symbol(),60,EmaUsar,2,MODE_EMA,5,nbar+1));
              
              Print ("  ema  --  ", ema);
              contador ++;
              if (contador == 4)
                 {
                 contador = 0;
                 nbar--; 
                 }    
                Print (" tbar ciclo ", tbar, " registo ", registo, " ema ", ema); 
              var1=TimeToStr(iTime(Symbol(),15,tbar),TIME_DATE|TIME_SECONDS);
                     
                      Print("Current bar for 15min: ", var1);
                      
                      
              var2=TimeToStr(iTime(Symbol(),60,nbar),TIME_DATE|TIME_SECONDS);
                     
                      Print("Current bar for hora : ", var2);
// there is more code that gives the break but is not necessary for my question 
// with only this he already jumps to the for                      
            }          
      
     }
     
     return(0);
}
 
  1.    handleout=FileOpen("Teste_Out_15_st_1.csv", FILE_CSV|FILE_WRITE, ",");
         Print ( " 2 "); 
    You've just created a zero length file so the following open/read is useless
  2.    while(FileIsEnding(Handle)==false)  // While the file pointer..
         {                                 // ..is not at the end of the file
               registo ++;
               Str_DtTm =FileReadString(Handle);// Date and time of the event (date)
    
               if(FileIsEnding(Handle)==true)   // File pointer is at the end
                 break;                        // Exit reading and drawing
    Why don't you want to process that last item? if(true==true) is redundant, likewise while(false==false) simplify while(!FileIsEnding(Handle)) // while not ending.
  3.       for (tbar=nbar15-4;tbar>=7400;tbar--)
    infinite loop tbar is counting down so tbar>=7400 will always be true.
  4. 1) I have a WHILE loop to read the input file

    2) FOR each record it must do some processing a write an output
    why do you need two loops. read a record, process it, loop.
 
WHRoeder:
  1. You've just created a zero length file so the following open/read is useless
  2. Why don't you want to process that last item? if(true==true) is redundant, likewise while(false==false) simplify while(!FileIsEnding(Handle)) // while not ending.
  3. infinite loop tbar is counting down so tbar>=7400 will always be true.
  4. 1) I have a WHILE loop to read the input file

    2) FOR each record it must do some processing a write an output
    why do you need two loops. read a record, process it, loop.

infinite loop tbar is counting down so tbar>=7400 will always be true.

Exactly. Many thanks.

Why don't you want to process that last item? if(true==true) is redundant, likewise while(false==false) simplify while(!FileIsEnding(Handle)) // while not ending.

I've decided to use FileReadArray so I close that file at once. The same for the output.

Thanks

Reason: