5

I'm trying to calculate the EMA with this script. But it does not give me the correct EMA. This could be of many reasons, but i'm not sure what it is. I've tried different formulas for the EMA without any better results, I'm really not a professional coder nor mathematician and thus i can't see what I'm doing wrong.

How Is the EMA value calculated over time? For the first value I calculate the first EMA using the SMA, i guess that should work - right?

My EMA value = 0.033144798412698406

Real EMA value = 0.033084

Close = last closing price

Period = 20;

Multiplier = (2 / (period + 1));

function calculateEMA() {
    if (EMA == 0) {
        EMA = (Close - SMA) * multiplier + SMA;
        calculateEMA();
    } else {
        for (a = 0; a < period; a++) {
            EMA = (Close - previous_ema) * multiplier + previous_ema;
            console.log(EMA + " ema");
            previous_ema = EMA;
        }
    }
}

// UPDATE Added my whole script (which can be runned)- https://pastebin.com/91GEuATM You need Nodejs and the binance node api installed (npm install node-binance-api --save) ; Keep in mind that this is just my "test script" hence all the weird variable names etc.

//UPDATE 2 Ticks sample data https://pastebin.com/AFzf7GwQ

Jonas
  • 85
  • 11
  • Can you provide a working example that can be ran in something like https://repl.it/languages/nodejs ? – Cody G Oct 16 '18 at 19:26
  • Your issue is probably... floating point arithmetic https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Cody G Oct 16 '18 at 19:29
  • If you can't provide a working example provide the the variable values. The first time you run this previous_ema will always be zero did you intend to set this? How are you setting the SMA? – Landy Oct 16 '18 at 19:42
  • @Landy The previous_ema is zero the first time yes. But i have a function that sets the previous_ema using SMA (if previous_ema == 0), i think the guy who updated / edited my post removed that part. I updated and added my whole test script. – Jonas Oct 16 '18 at 20:25
  • @CodyG. Updated! – Jonas Oct 16 '18 at 20:27
  • have you considered limiting your multiplier by multiplier = Number(2 / (period + 1)).toFixed(2); or multiplier = Number(2 / (period + 1)).toFixed(4); ? – Landy Oct 17 '18 at 12:15
  • @Jonas can you provide `ticks` sample data ? – Cody G Oct 17 '18 at 12:35
  • @CodyG. I have provided ticks sample data, or atleast the data im using. – Jonas Oct 17 '18 at 16:27

0 Answers0