Trade Bot Functions: EMA Calculation

Benjamin Cance
1 min readMay 1, 2023

--

#include <stdio.h>
#include <stdlib.h>

float* calculate_ema(float* prices, int len, int period) {
float* ema = malloc(len * sizeof(float));
float multiplier = 2.0 / (period + 1);
float sum = 0.0;
int i;

for (i = 0; i < period; i++) {
sum += prices[i];
ema[i] = sum / (i + 1);
}

for (; i < len; i++) {
ema[i] = (prices[i] - ema[i - 1]) * multiplier + ema[i - 1];
}

return ema;
}

The given code snippet calculates the exponential moving average (EMA) for a specified array of floating-point values. By taking into account the designated period and alpha value, the function efficiently computes the EMA for the provided dataset. As a result, the function returns a pointer to an array of floating-point values that represent the calculated EMA, with the caller responsible for managing and freeing the associated memory.

The next function takes these values and returns an array of EMA values, such that a “Rainbow” EMA indicator is constructed.

#include <stdio.h>
#include <stdlib.h>

float** calculate_multiple_emas(float* prices, int len, int n_periods) {
float** emas = malloc(n_periods * sizeof(float*));

for (int period = 1; period <= n_periods; period++) {
emas[period - 1] = calculate_ema(prices, len, period);
}

return emas;
}

The trade bot will utilize the two functions to create a trade decision based on the proximity of lower value EMAs to higher value EMAS.

--

--