Fix MT5 Custom Indicator return infinity value

Kritthanit Malathong
2 min readMay 9, 2022

--

Post id: 38, 2022/05/09

Infinity Value

Problem

When you write you own custom indicator, some time you will get “infinity” value when you setup your indicator on chart. Due to chart not load complete or anything else.

Solution

As you know, when we call bar 0 it’s mean “current bar” (last bar in the right hand side) as show in above picture but for indicator, the index 0 of indicator buffer is not the value of current bar but it’s the value of last bar as show below

Indicator buffer index of Separate window indicator

(NOTE: If it is “on chart indicator” the index of indicator will same as chart index)

When you create custom indicator, you will see something like this…

“rates_total” is the total bar on chart.

“prev_calculated” is number of bars has calculated.

Assume you have 100 bars on chart, when you setup indicator on chart…

The 1st calculation is…

rates_total = 100
prev_calculated = 0

after calculate complete, prev_calculated will be 100 (same as rates_total) and you will get infinity value in this process but if you write your code like this….

for(int i=prev_calculated; i<rates_total; i++){
...
}

The indicator will not recalculate until chart have a new bar because now “prev_calculated” = “rates_total”

So, you must check the last value of indicator buffer by using…

int start = prev_calculated;       
if(!MathIsValidNumber(valueBuffer[rates_total-1])) start = 0;

That mean, if the last value is not a valid number we will set start calculation index as 0 (recalculate all bars again) and the code will be…

int start = prev_calculated;  

if(!MathIsValidNumber(valueBuffer[rates_total-1])) start = 0;
for(int i=start; i<rates_total; i++){
...
}

When you recalculate all bars again, infinity value will disappear.

--

--

No responses yet