for loop questions

 

So I either do not understand for loops or visibility scope or both. I am just trying to loop through the history of my MA's and make sure they have not crossed over each other in a certain amount of time before I move on to my next criteria checks. For some reason I cant seem to get the loop to work. It's only looking at the loop once. It should be looking at the last 40 MA indexes. I compare the indexes each loop then once it gets to the end it should return true or false based on whether or not the MA's have crossed in the last 40 candles. I highlighted the functions that loop. I also highlighted the print line that keeps showing me that it has only looked at index number 1 in the tester journal


//+------------------------------------------------------------------+
//|                                          Ride-The-fast-MA_EA.mq4 |
//|                              Copyright 2021, Erick Fenstermaker. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
//Note: A Buy is closed with a Sell at Bid, a Sell is closed with a Buy at Ask
#property copyright "Copyright 2021, Erick Fenstermaker."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#include <stderror.mqh>
#include <stdlib.mqh>
//+------------------------------------------------------------------+
//|                          Variables                               |
//+------------------------------------------------------------------+
extern int candleRange = 40;
extern int fastMaPeriod = 20;
extern int fastMaShift = 0;
extern int fastMaMethod = 0;
extern int fastMaAppliedTo = 0;

extern int slowMaPeriod = 200;
extern int slowMaShift = 0;
extern int slowMaMethod = 0;
extern int slowMaAppliedTo = 0;


extern double maToClose1 = 0;
extern double maToClose2 = 0;
extern double maToHigh3 = 0;
extern double maToHigh4 = 0;
extern double maToHigh5 = 0;
extern double maToLow3 = 0;
extern double maToLow4 = 0;
extern double maToLow5 = 0;


double pips = 0;
extern double lotSize = 0.01;
extern int slippage = 30;
extern int magicNumber = 1234;
extern double stopLoss = 0;
extern double takeProfit = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   pips = Point;
   if(Digits==3||Digits==5)
      pips*=10;


   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(isNewCandle())
     {
      Print("We have a new Candle");
      if(OrdersTotal()==0)
         Print("No open orders right now. Lets look for an oportunity.");
      if(maTrendUp())
         buyFractal();
      if(maTrendDown())
         sellFractal();
     }
  }




//+------------------------------------------------------------------+
//|                           Functions                              |
//+------------------------------------------------------------------+
//Checks for a new candle
bool isNewCandle()
  {
   static datetime savedCandleTime;
   if(Time[0]==savedCandleTime)
      return false;
   else
      savedCandleTime=Time[0];
   return true;
  }


//places a long order
void buy()
  {
   int err = 0;
   double price = Ask, sl=0, tp=0;

   int ticket = OrderSend(Symbol(),OP_BUY,lotSize,price,slippage,0,0,"Trade Placed By Ride The Fast MA EA. ",magicNumber,0,clrBlue);
   if(ticket<0)
     {

      Print("Could not place order due to Error: "+(string)err+" "+ErrorDescription(err));
      if(err==ERR_TRADE_NOT_ALLOWED)
         MessageBox("You can not place a trade because \"Allow Live Trade\" is not turned on.");
     }
   else
      if(ticket>0)
        {
         if(OrderSelect(ticket,SELECT_BY_POS))
           {
            sl = Open[0];
            tp = OrderOpenPrice() + (sl*1.5);
            Print("We were able to place our buy order.");
           }
         else
           {
            if(!OrderModify(ticket,price,sl,tp,0,clrBlue))
              {
               Print("Could not modify order due to error: "+(string)err);
              }
           }
        }
  }


//places a short order
void sell()
  {
   int err = 0;
   double price = Bid, sl=0, tp=0;

   int ticket = OrderSend(Symbol(),OP_BUY,lotSize,price,slippage,0,0,"Trade Placed By Ride The Fast MA EA. ",magicNumber,0,clrBlue);
   if(ticket<0)
     {

      Print("Could not place order due to Error: "+(string)err+" "+ErrorDescription(err));
      if(err==ERR_TRADE_NOT_ALLOWED)
         MessageBox("You can not place a trade because \"Allow Live Trade\" is not turned on.");
     }
   else
      if(ticket>0)
        {
         if(OrderSelect(ticket,SELECT_BY_POS))
           {
            sl = High[0];
            tp = Open[0]-(sl*1.5);
            Print("We were able to place our buy order.");
           }
         else
           {
            if(!OrderModify(ticket,price,sl,tp,0,clrBlue))
              {
               Print("Could not modify order due to error: "+(string)err);
              }
           }
        }
  }


//Function to look for a sell fractal settup
double sellFractal()
  {
   int candleNum =0;
   double lowLevel=0;

   Print("The Slow moving average has been above the fast moving average for a while so lets check our candles.");
   if(Low[1]>Low[2]&&Low[2]>Low[3]&&Low[3]>Low[4]&&Low[4]>Low[5]&&Low[5]<Low[6]&&Low[6]<Low[7]&&Low[7]<Low[8]&&Low[8]<Low[9])
     {
      lowLevel = Low[5];
      Print("There is a fractal sell pattern the new low is: "+(string)lowLevel);
      return lowLevel;
     }
   else
     {
      Print("There is no sell fractal pattern right now.");
      return 0;
     }
  }

//Function to look for a buy fractal settup
double buyFractal()
  {

   int candleNum = 0;
   double highLevel=0;

   Print("The Slow moving average has been below the fast moving average for a while so lets check our candles.");
   if(High[1]<High[2]&&High[2]<High[3]&&High[3]<High[4]&&High[4]<High[5]&&High[5]>High[6]&&High[6]>High[7]&&High[7]>High[8]&&High[8]>High[9])
     {
      highLevel = High[5];
      Print("There is a fractal sell pattern the new low is: "+(string)highLevel);
      return highLevel;
     }
   else
     {
      Print("There is no sell fractal pattern right now.");
      return 0;
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//Function to sell based on if we have a breakout under the low of the fractal candle
bool sellBreakout()
  {
   if(sellFractal()>Bid)
     {
      Print("The current price has just surpassed the low of the fractal candle we should sell.");
      return true;
     }

   else
     {
      Print("No sign of a downward breakout at this time. Not entering a sell order.");
      return false;
     }
  }

//Function to buy based on if we have a breakout over the high of the fractal candle
bool buyBreakout()
  {
   if(buyFractal()<Ask)
     {
      Print("The current price has just surpassed the high of the fractal candle we should buy.");
      return true;
     }

   else
     {
      Print("No sign of a upward breakout at this time. Not entering a buy order.");
      return false;
     }
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool maTrendUp()
  {
   int i=0;
   int candleNum = 0;
   bool retval = false;

   Print("We are begining our look at an up trend.");

//Loop to look at the moving averages and make sure they have not crossed in the resont history.
   for(i=0; i<=candleRange; i++)
     {
      double candleSlow = iMA(NULL,0,slowMaPeriod,slowMaShift,slowMaMethod,slowMaAppliedTo,candleNum);
      double candleFast = iMA(NULL,0,fastMaPeriod,fastMaShift,fastMaMethod,fastMaAppliedTo,candleNum);
      candleNum++;
      Print("Looking at candle: "+(string)candleNum);
      if(candleSlow>candleFast)
        {
         Print("The slow ma has gone above the fast ma resontly, we are not taking buy entries.");
         break;
        }
      if(candleSlow<candleFast&&candleNum==candleRange)
        {
         Print("The fast MA has been above the slow MA for a while now. Lets look at our candles for a buy fractal pattern.");
         retval = true;
         return retval;
        }
      else
        {
         Print("There is no up trend lets look for down drends.");
         retval=false;
         return retval;
        }
     }
   return false;
  }


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool maTrendDown()
  {
   int i=0;
   int candleNum = 0;
   bool retval = false;

   Print("We are begining our look at an down trend.");

//Loop to look at the moving averages and make sure they have not crossed in the resont history.
   for(i=0; i<=candleRange; i++)
     {
      double candleSlow = iMA(NULL,0,slowMaPeriod,slowMaShift,slowMaMethod,slowMaAppliedTo,candleNum);
      double candleFast = iMA(NULL,0,fastMaPeriod,fastMaShift,fastMaMethod,fastMaAppliedTo,candleNum);
      candleNum++;
      Print("Looking at candle: "+(string)candleNum);
      if(candleSlow<candleFast)
        {
         Print("The slow ma has gone below the fast ma resontly, we are not taking sell entries.");
         break;
        }
      if(candleSlow>candleFast&&candleNum==candleRange)
        {
         Print("The slow MA has been above the fast MA for a while now. Lets look at our candles for a sell fractal pattern.");
         retval = true;
         return retval;
        }
      else
        {
        Print("There is no down trend either. No need to check for a fractal pattern yet.");
         retval=false;
         return retval;
        }
     }
   return false;
  }

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

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

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


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

//+------------------------------------------------------------------+
 
  1. SirFency compare the indexes each loop then once it gets to the end it should return true or false based on whether or not the MA's have crossed in the last 40 candles.

    What you actually do is break out of the loop when you see the first slow above the fast and return false. Look for a cross.

    double aPrev = …, aCurr = …,
           bPrev = …, bCurr = …;
    bool   wasUp = aPrev > bPrev,
            isUp = aCurr > bCurr,
           isCross = isUp != wasUp;

  2. You set candleNum to zero pre-loop and then increment it at the end of the loop. You also do the same thing in the for statement (variable i) but never use i. Simplify: replace i with candleNum and remove the extra statements.

Reason: