Verifying the Trend with SMA

To add comments, please log in or register
dapton
7
dapton  

Hi fellow coders/traders

I need help with the following code. I am trying determine that price has closed below the various SMAs in the past 18 periods for example.

But the following caused my mt4 to hang. did I create an endless loop?


               for(int i=1; i<19;){

                  SMA20 = iMA(NULL,0,20,0,MODE_SMMA,PRICE_CLOSE,i);

                  SMA50 = iMA(NULL,0,50,0,MODE_SMMA,PRICE_CLOSE,i);

                  SMA100 = iMA(NULL,0,100,0,MODE_SMMA,PRICE_CLOSE,i);

                  SMA200 = iMA(NULL,0,200,0,MODE_SMMA,PRICE_CLOSE,i);

                  

                  if(Close[i] < SMA20 && SMA20 < SMA50 && SMA50 < SMA100 && SMA100 < SMA200){

                     i++; 

                     if(i == 18){ Alert("#2: ", Symbol(), " ", period); } // on the 18th candle send alert

                  }//end of if

                }//end of for loop

Seng Joo Thio
1105
Seng Joo Thio  
dapton:

did I create an endless loop?

Yes. When this condition is false, 'i' will remain the same, and your loop will never end.

(Close[i] < SMA20 && SMA20 < SMA50 && SMA50 < SMA100 && SMA100 < SMA200)

This is one way:

               bool Failed = false;

               for(int i=1; i<19; i++){

                  SMA20 = iMA(NULL,0,20,0,MODE_SMMA,PRICE_CLOSE,i);
                  SMA50 = iMA(NULL,0,50,0,MODE_SMMA,PRICE_CLOSE,i);
                  SMA100 = iMA(NULL,0,100,0,MODE_SMMA,PRICE_CLOSE,i);
                  SMA200 = iMA(NULL,0,200,0,MODE_SMMA,PRICE_CLOSE,i);
                  if(!(Close[i] < SMA20 && SMA20 < SMA50 && SMA50 < SMA100 && SMA100 < SMA200)){
                     Failed = true;
                     break;
                  }//end of if

                }//end of for loop

                if (!Failed)
                   Alert("#2: ", Symbol(), " ", period);
To add comments, please log in or register