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);

391

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);

176

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.

14

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.

45

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); }

hma.mq4 8 kb

Moderator

32409

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 ?

82

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..

45

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

My EA is working with EURUSD in D1.

Moderator

10568

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

Moderator

32409

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

My EA is working with EURUSD in D1.

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??

Cluster analysis of volumes is now available in MetaTrader 5! The YuСlusters indicator is a professional tool for analyzing the trading volumes. The cluster graph is plotted based on tick data. For the exchange financial instruments these are the volume, type and price of a deal. For the Forex instruments - the real or tick volume (depending on the broker) and Bid price. There are 6 criteria of cluster generation: Time interval, the criterion is set in seconds. Price range, the criteri

Does not support openning multiple orders on a single symbol on MT5 MultiMTCopier MT5Source - new and improved multi-terminal positions copier for your real / demo account, works faster, requires less, flexible in managing and upgrading, new information support. This expert is designed for terminal MetaTrader5 from which the position will be copied. MultiMTCopier: The EA will copy all positions without delays Additionally integrated notification in situations requiring user attention Butt

FULL Automatic is a fully autonomous trading robot for MetaТrader 5 without configurable parameters. It is similar to SAFE Automatic robot intended for traders having no knowledge of trading basics. It works in Low, Medium, High and Extremal trading modes. Trading strategy The EA applies modified versions of well-known strategies, including Elliott waves, following a trend, half-pyramiding, scalping, speculative trading with a double deposit protection. The EA switches the strategies automati

The main purpose of the indicator is to determine and mark trade signals on the histogram of the Accelerator Oscillator, which were described by Bill Williams in his book "New Trading Dimensions". The list of signals: The buy signal when the indicator histogram is below the zero line. The sell signal when the indicator histogram is below the zero line.The sell signal when the indicator histogram is above the zero line. The buy signal when the indicator histogram is above the zero line. The

Volume is an important indicator in combination with price movements. Volumes Overaverage Notifier informs you when activity is entering the market. Features This indicator is able to notify you via push notifications, alerts, sounds and emails when it is recognizing rising volume above a customizable level. The volumes histogram is divided and colored in 4 different parts - low, normal, high and ultrahigh volume levels. Low volume zones are drawn as a rectangle into the chart. How to Use

Fast Copy MT5 allows you to copy trades between different MetaTrader 5 (netting)(hedge) and MetaTrader 4 accounts in any direction and amount, quickly and easily (without loading the system). Any type of copying is available MT4 → MT5 MT4 → MT4 MT5 → MT5 MT5 → MT4 * For the MetaTrader 4 terminal — Fast Copy MT4 * For the MetaTrader 5 terminal — Fast Copy MT5 ** Before the purchase, you can test the program by downloading the free demo versions — Fast

The script is intended for automatic placing of Sell Stop pending orders, Stop Losses and Take Profits on the user specified levels. This script is not that useful as "Virtual pending buy stop", since short positions are opened as Bid price crosses the levels. Thus spread widening is not dangerous. Nevertheless, you need to have this script to prevent unwanted hitting of the Stop Loss levels. Main Purposes: Automation of the process of placing the Sell Stop pending orders, Stop Losses and T

Percent Crosshair is a powerful and easy percentage measure tool. Measure the chart percentage very quick! Don't waste your time anymore! Just attach the Percent Crosshair indicator in the chart, select crosshair mode at toolbars or press "Ctrl+F" and start using the crosshair as you always do! The percent measure will be next to the indicative price. Customize your indicator the way you want! There are 4 entry parameters: Positive % color: set the desired color when % is positive. Negat

Does not support openning multiple orders on a single symbol on MT5 MultiMTCopier MT5Receiver - new and improved multi-terminal positions copier for your real/demo account, works faster, requires less, flexible in managing and upgrading, new information support. This Expert Advisor is designed for the MetaTrader 5 terminal, trades will be copied into this terminal. MultiMTCopier: The EA will copy all positions without delays Additionally integrated notification in situations requiring user

The script is intended for automatic placing of Buy Stop pending orders, Stop Losses and Take Profits on the user specified levels. Main Purposes: Avoiding unwanted entering a long position in case of false hitting the level as a result of widening of the spread by a dealing center. Avoiding unwanted triggering of a Stop Loss in case a quote pierces a significant level (fractal) without further confirmation with the close price. Setting a necessary virtual order and entering the market in

Monitoring and Trend Analysis This product shows the trend strength levels based on 16 standard indicators, time periods and currency groups. Depending on the current trend, the indicator colors change from green to red, allowing you to see the full picture. Advantages Whatever your trading method and strategy are, you should always know, in which direction you are trading and what the probability of the trend change is. This indicator will help you answer these questions by calculating the

This is the Famous Timing Indicator You can now use the most famous Timing indicator on the planet. Millionaire Mostafa Belkhayate earned his reputation by using this specific indicator to validate the entry signals supplied by his also famous Center of Gravity indicator on the Forex market. I spent hours, days, weeks to decrypt the formula and now it is finally available to you. New and Unique for MetaTrader 5 Timing will give you perfect validations for your entry signals. It is the first

This is an open interest indicator for MetaTrader 5. It fixes open interest value once per minute and writes it to the file (on your PC). The product works on any timeframe but only with exchange instruments.

The Trade Manager Pro EA is a MetaTrader Expert Advisor that performs position management for you avoiding human errors and enhancing your trading activity. Amazingly easy to use Trade easily from the chart Trade with precise risk management, hassle free Capital preservation is top priority Let profits run without your attention Enjoy risk-free trades as soon as possible Automatic trailing stops for all opened trades Initial stop losses are placed as soon as trades are

Find Shoulder-Head-Shoulder chart patterns easily with this indicator. Easy to use Customizable colors and sizes It implements breakout signals It implements alerts of all kinds Input Parameters Indicator Settings - The amplitude represents the size of the patterns to be found. The max. history bars parameter is the amount of bars in the chart to look back. Less bars to evaluate means the indicator will load faster. Patterns - Choose the colors of the patterns. Breako

Robust median Renko style indicator for creating custom charts resembling Median Renko, Mean Renko, Turbo Renko and Better Renko candles as well as vanilla Renko with wicks plus PointO charts. This all in one package provides all of the signals needed by day traders, scalpers and even long term traders. These include: The indicator is an overlay on the main chart so it is possible to utilize one-click trading and order manipulation directly on the custom charts. Visual order placement is a

Tick volume is equal to amount of ticks at the unit of time. There is direct correlation between tick volume and real amount of deals. Every change of the price is a result of a real request to perform a deal. Consequently, fewer requests we have, the less price changes we get, and, as a consequence, tick volume is smaller. In this case, when big amount of requests appear on the market, price changes happen more often. Big tick volume appears. Tick volume is an important indicator of trad

Parameters Three variables are available for every strategy, any one of them can be disabled, their period can be changed. type_order=ORDER_FILLING _FOK - order filling type. ReverseTrade=false — trades opens in reverse direction if true. ExitOnBar=true — trades close on each bar only. spreadcover=false — Spread you pay includes in profit trades. It's like trade with zero spread but you should remember that it can decrease exact match between tester's result and live one. It

Market Profile defines a number of day types that can help the trader to determine market behaviour. A key feature is the Value Area, representing the range of price action where 70% of trading took place. Understanding the Value Area can give traders valuable insight into market direction and establish the higher odds trade. It is an excellent addition to any system you may be using. Blahtech Limited presents their Market Profile indicator for the MetaTrader community. Inspired by Jim Dalton’s

VirtualTradePad - is a contol panel for working with orders in МetaТrader 5 : buy, sell, buystop, buylimit, sellstop, selllimit, close, delete, modify, tralling stop. VirtualTradePad won 2nd prize in the "Best Control Panel in the MQL5 Language" Contest. The panel consists of 5 tabs. Demo versions: VirtualTradePad PositionsStyle VirtualTradePad Ordersstyle VirtualTradePad SignalsStyleDemo version of the panel - VirtualTradePad LiteProfit or Loss PadINFO PadYou can also try this panel for

The indicator is designed for easy construction of synthetic charts based on data of various financial instruments. It will be useful both arbitrage and pair trading, as well as for analysis purposes. Its main advantage is simplicity and clarity. Each chart is given as a common mathematical formula. For example, if you want to plot the spread (difference) between EURUSD and GBPUSD with coefficients 4 and 3, then set the following formula: EURUSD * 4 - GBPUSD * 3 The resulting chart is shown in

The indicator is intended for determining the spread and swap size, the distance for setting stop orders and stop losses from the current price allowed and the risk per 1 point in the deposit currency. The indicator informs a trader about possible additional expenses and profits connected with transferring a position to the next trade session of the financial instrument. It also informs about the spread size and the distance of pending orders, stop loss and trailing from the current price. In a

The indicator represents an additional chart window with a lower time frame where bars are combined into groups that are equivalent in time to main chart time frame. Bars are synchronized by the right hand side of the window, i.e. the time of the last bar in the main window corresponds to the time of the last bar group in the additional window. The maximum number of groups is 16; the maximum number of bars combined into groups in the additional window is 256. Limitations on the numbers are requi

This indicator is based on Bollinger Bands indicator. It helps user clearly know the Band is expand or contract.

The main purpose of the indicator is to detect and mark trade signals on the histogram of the Awesome Oscillator according to the strategies "Trading Chaos, second edition" and "New Trading Dimensions". The indicator detects and marks the following trade signals: "Two peaks" - Divergence. The signal "Second wise-man" - third consequent bar of the Awesome Oscillator after its color is changed. The histogram crosses the zero line. The signal "Saucer".The indicator includes a signal block th

This is an utility for automatic scaling of a chart and making at least 140 bars visible in it. This is necessary for a correct wave analysis according to the Bill Williams' strategy "Trading Chaos". The utility can be used on any timeframe available in МetaТrader 5. It draws a vertical line through the first bar the calculation starts from. This line allows you to see the probable starting point of the wave sequence along with a sufficient number of bars displayed in the chart. It also makes t

Trade Controller provides multiple methods to protect and maximize your profits. This powerful weapon helps you to set the protect and trailing-stop rules on your trade automatically in many effective methods. Once it is set and turned on, you don't need to monitor your orders anymore, the software will keep watching and control your orders with your predefined rules. It's designed to support multi-protection and trailing strategy: Protect by break-even, protect by percentage, protect by pip, p

Create your own list of trading instruments Watch list* and combine it with several open charts Link **. Using this program, a user can create fully-fledged Watch lists, create and delete trading instruments and move through the list. A selected symbol shows charts in linked windows. Linked windows can have different periods, indicators, experts, trading panels, etc... Moving through his/her Watch list, a trader an see the full image of his/her strategy in all windows. A lot of traders use 1

All traders using VSA realize the importance of the volume. Unfortunately, tick and spot volumes are not suitable for these purposes. I have conducted mathematical calculations and managed to trnsform the price into the volume that is close to the futures one by its ratios. Now, you do not have to wrestle with the question of where to obtain the volume data. Besides, you will be able to use the currency pairs having no futures at all. With RealVolume, you do not need to remember data on each ti

This indicator extracts a trend from a price series and forecasts its further development. Algorithm is based on modern technique of Singular Spectral Analysis (SSA). SSA is used for extracting the main components (trend, seasonal and wave fluctuations), smoothing and eliminating noise. Does not require the series to be stationary, as well as the information on presence of periodic components and their periods. It can be applied both to price series and to the data of other indicators. Implemen