# Help coding EMA for Volume

226

Dear users:

Im trying to code an indicator that shows the MA and EMA of the Volume bars. I have managed to successfully code the SMA but with the EMA, Im getting some issues and I cannot advance. I have detected some stacks overflow also. Anyway below is my code and I dont think I have it good at all. Any more experience can help?

[code]

double EMA_Volume(int i, int size)
{
if (i==MA_Period+2)return MA_Volume(i,size);

double multiplier=(2 / (size + 1) ) ;
return (Volume[i] - EMA_Volume(i+1,10) * multiplier + EMA_Volume(i+1,10));

}

double MA_Volume(int i, int size)
{
double suma=0;
for(int j=i; j<i+size;j++)
{
suma=suma+Volume[j];
}
if ((suma/size)==0){Alert("Something is wrong with the volume of bar nº= ",i," ",GetLastError());return 50;}
else
return (NormalizeDouble((Volume[i]/NormalizeDouble(suma/size,2))*100,2));
}

[/code]

7090

There is a source button SRC beside the camera!
7090

return() needs its own brackets this won't work

`return(Volume[i] - EMA_Volume(i+1,10) * multiplier + EMA_Volume(i+1,10));`

better (I am used to this version):

`return(  multiplier*(Volume[i] - EMA_Volume(i+1,10)) + EMA_Volume(i+1,10) );`

Stack-Overflow or Array out of range?

I would do (using tick_volume[] which should be the prev Volume[]!): (not tested)

``` ...
int i;
if ( prev_calculated < 100 ) {
i= rates_total-1;
emaBuff[i] = (double)tick_volume[i]; // initialize
} else
i = rates_total - prev_calculated + 1;
while(i>0){i--;
emaBuff[i] = multipl*((double)tick_volume[i] - emaBuff[i] ) + emaBuff[i];
...     ```

An ema can be easily calculated in a function:

```//use: emaVol = ema(multipl, Volume[i], emaVol);
double ema(double c, double newVal, double prvVal){
if ( prvEma == EMPTY_VALUE ) return(newVal); // ini prvVal with EMPTY_VALUE !!
return( c*(newVal - prvVal) + prvVal);
} ```
Moderator
10566

Can a function call itself?

```double EMA_Volume(int i, int size)
{
if (i==MA_Period+2)return MA_Volume(i,size);

double multiplier=(2 / (size + 1) ) ;
return (Volume[i] - EMA_Volume(i+1,10) * multiplier + EMA_Volume(i+1,10));

}```