Zero divide error

 

Hi, I have been trying to fix this several times but I just can't find where it's dividing by zero.

Can someone be kind enough to look into this??

 

//+------------------------------------------------------------------+
//|                          spiders101.Pro_Bot_EURUSD_m15.EA.V1.mq4 |
//|                                                       spiders101 |
//|                                      spiders101@Arabictrader.com |
//+------------------------------------------------------------------+
extern string  Note="EURUSD -- 15 Min TimeFrame";
extern int  RiskPercent = 10;
int  MagicNumber = 3148;
int Slippage = 5; 
int T; 
double cA = 0; 
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
 {
  if (Digits == 5 || Digits == 3)
  Slippage = 50;
 }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
Comment("");
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() 
 { 
Comment("Modified by spiders101","\n","spiders101@Arabictrader.com","\n","Lot = ",Lot());
//---------Time & Conditions-------// 
  if (T!=Time[0]) {T=Time[0];cA = Acc(); if(MathAbs(cA)<= 3) cA = 0;}
//------ Buy ---------------------//   
  if(cA > 0)
  if(OrderSend(Symbol(),OP_BUY,Lot(),NormalizeDouble((Ask),Digits),Slippage,0,0,"EA",MagicNumber,0,Blue) != -1)
  cA = 0; //After condition(!= -1) , Order already opened , Value of cA must be 0)
//------ SELL ---------------------// 
  if(cA < 0) 
  if(OrderSend(Symbol(),OP_SELL,Lot(),NormalizeDouble((Bid),Digits),Slippage,0,0,"EA",MagicNumber,0,Red) != -1)
  cA = 0; //After condition(!= -1) , Order already opened , Value of cA must be 0)     
//---------Conditions for Modifing Orders by takeprofit & stoploss-----// 
for(int i=0;i<OrdersTotal();i++){
  if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber&&OrderStopLoss()== 0){
      double HL_Diff = High[iHighest(Symbol(),0,MODE_HIGH,48,1)] - Low[iLowest(Symbol(),0,MODE_LOW,48,1)];//Equation to find the Diff between The Highest and Lowest From Candle 1 To 48
        if (OrderType() == OP_BUY) OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble((Ask - HL_Diff * 0.19),Digits),NormalizeDouble((Ask + HL_Diff * 0.45),Digits),0,Blue);
        if (OrderType() == OP_SELL) OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble((Bid + HL_Diff * 0.19),Digits),NormalizeDouble((Bid - HL_Diff * 0.45),Digits),0,Red);
        } 
      }      
return(0);
} 
// End OF start Function 
//+------------------------------------------------------------------+
//+------------------------Money Managment Function------------------------------------+ // 
double Lot()
 {
  double Lot = (AccountFreeMargin() *  RiskPercent / 1000.0) / 100;
  double LotDigits = MathLog(MarketInfo(Symbol(), MODE_LOTSTEP)) / MathLog(0.1);
  double MinLot = MarketInfo(Symbol(),MODE_MINLOT);
  double MaxLot = MarketInfo(Symbol(),MODE_MAXLOT);  
  return(NormalizeDouble(MathMin(MathMax(MinLot, Lot),MaxLot),LotDigits));//Take The Min Lot From Result
 }
//+------------------------------------------------------------------+
double Acc()
 {
 int Fa=5;
 int Sa=63;
 double sumF = 0; for (int i = 1; i <= Fa; i++) sumF += Close[i] - Open[i];
 double sumS = 0; for (i = 1; i <= Sa; i++) sumS += MathAbs(Close[i+5] - Open[i+5]);
 if(Fa!=0&&Sa!=0)return((sumF / Fa) / (sumS / Sa));
 else 
 return(0);
 }       
//Idea is Dividing The diff between Close and open Of candle(1) /5  and Candel(6) /63
//Then use The result in Start Function  
//-----------------------------------------------------------------+ 
 

Try declare these as double variables.

int Fa=5;
 int Sa=63;

If it does not work,  split operations in more single steps and check their values

double num= (sumF / Fa);
double denum = (sumS / Sa);
if(denum!=0)
    return(num/denum);
 

Good practice for avoiding zero divide errors:

1) Always leave a space before and after the "/" division symbol in calculations. That way it is easier to use the Ctrl+F search function to find all the divisions without having to go through all the "//" comment pre-fixes as well.

2) Always place calculations which use the division symbol inside the command braces of a conditional which checks to make sure the number you are dividing by does not equal zero. This will prevent the program from stopping with a zero divide error if the denominator ever happens to be zero. eg.

   if ( denominator != 0 )
      { answer =  numerator / denominator; }

3) It's a good idea to add some sort of error reporting to make sure that the program does not proceed onwards without warning you that the calculation inside those command braces was not carried out when the denominator equals zero - otherwise you might never realise, because the zero divide error would no longer occur. It is probably correct to assume that if the denominator is ever zero then something has already gone wrong before the zero divide error can occur, and you would want to know about it. eg.

   if ( denominator != 0 )
      { answer =  numerator / denominator; }
   else
      { Alert("WARNING: denominator == 0 !"); }

These three additions may take a few extra seconds to type each time in the code, but they will save minutes or hours in preventing a zero divide error from ever occurring.

Add these into your code and the problem will reveal itself.

 

Good points to remember, clerin6! Divide by zero errors are fairly easy to prevent in this way or if you know how the calculations are made on the variables that are involved in a divide operation. Related, though a bit different are unintentional and sinister zero creation via integer division bugs. For instance, if length is an external int input and the desired output is a floating point number:

 double emaWeight = 2/(length+1);

 If length is an integer the above line will produce a zero for most lengths. While the following is what is actually intended: (will produce a floating point weight that can be used as part of an Exponential weighting calculation).

double emaWeight = 2.0/(length + 1); // 2.0 forces floating point division rather than integer division. 
 

Hi,

From a few time, with changing to new version of MT4 (build 610), i have the same error on my indicator when I'm using it with iCustom in my EA.

This indicator is the famous Hull Moving Average 2.0 (bicolor smouthed MA). It's new name is HMA now.

Some syntaxe errors are corrected like "char by "Char".

But not the zero divide error.

Somebody can help me ?

Thanks

//+------------------------------------------------------------------+
//|                                              Hull moving average |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1  SpringGreen
#property indicator_color2  Magenta
#property indicator_color3  Yellow
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2

//

extern string TimeFrame       = "Current time frame"; // "Current time frame"
extern int    HMAPeriod       = 28; // 35
extern int    HMAPrice        = PRICE_CLOSE;
extern double HMASpeed        = 2.0;
extern bool   alertsOn        = false;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = true;
extern bool   alertsEmail     = false;

//

double hma[];
double hmada[];
double hmadb[];
double work[];
double trend[];

int    HalfPeriod;
int    HullPeriod;

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------

int init()
{
   IndicatorBuffers(5);
      SetIndexBuffer(0,hma);
      SetIndexBuffer(1,hmada);
      SetIndexBuffer(2,hmadb);
      SetIndexBuffer(3,trend);
      SetIndexBuffer(4,work);
      
   //
      HMAPeriod  = MathMax(2,HMAPeriod);
      HalfPeriod = MathFloor(HMAPeriod/HMASpeed);
      HullPeriod = MathFloor(MathSqrt(HMAPeriod));

         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);

   //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" HMA ("+HMAPeriod+")");
   return(0);
}


//------------------------------------------------------------------
//
//------------------------------------------------------------------

int start()
{
   int i,counted_bars = IndicatorCounted();
      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;   
           int limit=MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { hma[0] = MathMin(limit+1,Bars-1); return(0); }

   //
   if (calculateValue || timeFrame == Period())
   {
      if (trend[limit] == -1) CleanPoint(limit,hmada,hmadb);
      for(i=limit; i>=0; i--) work[i] = 2.0 * iMA(NULL,0,HalfPeriod,0,MODE_LWMA,HMAPrice,i)-iMA(NULL,0,HMAPeriod,0,MODE_LWMA,HMAPrice,i);
      for(i=limit; i>=0; i--)
      {
         hma[i]   = iMAOnArray(work,0,HullPeriod,0,MODE_LWMA,i);
         hmada[i] = EMPTY_VALUE;
         hmadb[i] = EMPTY_VALUE;
         trend[i] = trend[i+1];
            if (hma[i] > hma[i+1]) trend[i] =  1;
            if (hma[i] < hma[i+1]) trend[i] = -1;
            if (trend[i] == -1) PlotPoint(i,hmada,hmadb,hma);
      }      
      manageAlerts();
      return(0);
   }
   
   //
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame / Period()));
   if (trend[limit]== -1) CleanPoint(limit,hmada,hmadb);
   for (i=limit; i>= 0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HMAPeriod,HMAPrice,HMASpeed,3,y);
         hma[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",HMAPeriod,HMAPrice,HMASpeed,0,y);
         hmada[i] = EMPTY_VALUE;
         hmadb[i] = EMPTY_VALUE;
   }
   for (i=limit;i>= 0;i--) if (trend[i]== -1) PlotPoint(i,hmada,hmadb,hma);
   manageAlerts();
   
   //
   //
   //
   //
   //

   return(0);
         
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert(whichBar,"up");
         if (trend[whichBar] == -1) doAlert(whichBar,"down");
      }
   }
}

//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

//
       message =  Symbol()+" "+timeFrameToString(timeFrame)+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" HMA trend changed to "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(Symbol()+" HMA ",message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}


//-------------------------------------------------------------------
//
//-------------------------------------------------------------------

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

//

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (first[i+1] == EMPTY_VALUE)
      {
         if (first[i+2] == EMPTY_VALUE) {
                first[i]   = from[i];
                first[i+1] = from[i+1];
                second[i]  = EMPTY_VALUE;
            }
         else {
                second[i]   =  from[i];
                second[i+1] =  from[i+1];
                first[i]    = EMPTY_VALUE;
            }
      }
   else
      {
         first[i]  = from[i];
         second[i] = EMPTY_VALUE;
      }
}

//

string sTfTable[] = {"M1","M5","M15","M27","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//

int stringToTimeFrame(string tfs)
{
   tfs = stringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}
string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//

string stringUpperCase(string str)
{
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--)
   {
      double Char;
      
      Char = StringGetChar(s, length);
         if((Char > 96 && Char < 123) || (Char > 223 && Char < 256))
                     s = StringSetChar(s, length, Char - 32);
         else if(Char > -33 && Char < 0)
                     s = StringSetChar(s, length, Char + 224);
   }
   return(s);
}
Files:
hma.mq4  8 kb
 
goldy-40:

Hi,

From a few time, with changing to new version of MT4 (build 610), i have the same error on my indicator when I'm using it with iCustom in my EA.

This indicator is the famous Hull Moving Average 2.0 (bicolor smouthed MA). It's new name is HMA now.

Some syntaxe errors are corrected like "char by "Char".

But not the zero divide error.

Somebody can help me ?

Thanks

Hi, I don't have this error with your code. Can you explain how to reproduce this error ? Which symbol/timeframe are you using, which indicator settings ?

 

In V610, instead of this :

 if ( denominator != 0 ) 
   
      { answer =  numerator / denominator; }

I had to use :

 if ( denominator == 0 ) {return;}
     else
      { answer =  numerator / denominator; }


Seems like != 0 doesn't run well..

 

To reproduce this error, you must integrate it with iCustom in a EA.

My EA is working with EURUSD in D1.

 
goldy-40:

To reproduce this error, you must integrate it with iCustom in a EA.

My EA is working with EURUSD in D1.


Then the problem is probably in the EA's code, not the indicator's
 
goldy-40:

To reproduce this error, you must integrate it with iCustom in a EA.

My EA is working with EURUSD in D1.

If you want help, please provide code to reproduce the error.
Reason: