explanation of Stochastic

94

Hi,

In the Stochastic Indicator that you can find in MT4, there is a recurring if statement

```pos=InpKPeriod-1;if(pos+1<prev_calculated)
pos=prev_calculated-2;```

which I do not understand. Why does it subtract -2 ? what the point of the code above?

This is the onCalculate() function to give a bit more of context around the code above:

```int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
{
int    i,k,pos;
//--- check for bars count
if(rates_total<=InpKPeriod+InpDPeriod+InpSlowing)
return(0);
//--- counting from 0 to rates_total
ArraySetAsSeries(ExtMainBuffer,false);
ArraySetAsSeries(ExtSignalBuffer,false);
ArraySetAsSeries(ExtHighesBuffer,false);
ArraySetAsSeries(ExtLowesBuffer,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(high,false);
ArraySetAsSeries(close,false);
//---
pos=InpKPeriod-1;
if(pos+1<prev_calculated)
pos=prev_calculated-2;
else
{
for(i=0; i<pos; i++)
{
ExtLowesBuffer[i]=0.0;
ExtHighesBuffer[i]=0.0;
}
}
//--- calculate HighesBuffer[] and ExtHighesBuffer[]
for(i=pos; i<rates_total && !IsStopped(); i++)
{
double dmin=1000000.0;
double dmax=-1000000.0;
for(k=i-InpKPeriod+1; k<=i; k++)
{
if(dmin>low[k])
dmin=low[k];
if(dmax<high[k])
dmax=high[k];
}
ExtLowesBuffer[i]=dmin;
ExtHighesBuffer[i]=dmax;
}
//--- %K line
pos=InpKPeriod-1+InpSlowing-1;
if(pos+1<prev_calculated)
pos=prev_calculated-2;
else
{
for(i=0; i<pos; i++)
ExtMainBuffer[i]=0.0;
}
//--- main cycle
for(i=pos; i<rates_total && !IsStopped(); i++)
{
double sumlow=0.0;
double sumhigh=0.0;
for(k=(i-InpSlowing+1); k<=i; k++)
{
sumlow +=(close[k]-ExtLowesBuffer[k]);
sumhigh+=(ExtHighesBuffer[k]-ExtLowesBuffer[k]);
}
if(sumhigh==0.0)
ExtMainBuffer[i]=100.0;
else
ExtMainBuffer[i]=sumlow/sumhigh*100.0;
}
//--- signal
pos=InpDPeriod-1;
if(pos+1<prev_calculated)
pos=prev_calculated-2;
else
{
for(i=0; i<pos; i++)
ExtSignalBuffer[i]=0.0;
}
for(i=pos; i<rates_total && !IsStopped(); i++)
{
double sum=0.0;
for(k=0; k<InpDPeriod; k++)
sum+=ExtMainBuffer[i-k];
ExtSignalBuffer[i]=sum/InpDPeriod;
}
//--- OnCalculate done. Return new prev_calculated.
return(rates_total);
}
```
Moderator
108452

94

Sergey Golubev:

thanks @Sergey Golubev

good thread, unfortunately does not help me understand more of what is going in that piece of code.

do you have any idea?

Moderator
108452

billysballo:

thanks @Sergey Golubev

good thread, unfortunately does not help me understand more of what is going in that piece of code.

do you have any idea?

I am not a coder sorry..