Pseudocode: How to implement MCAD

in #bitcoin7 years ago

I am playing around with MACD. It is described here in German.

How does it looks like?

Macd consists of three signals: macd, macd signal and macd_buy_sell_signal.

To calculate it you need EMA(Period, yAbsolute):

double lastEma = yAbsolute[i];
if (i > 0)
     lastEma = values[i - 1];
values[i] = yAbsolute[i] * 2.0 / (_Period + 1.0) + lastEma * (1.0 - 2.0/(_Period + 1.0));

To calculate MACD you need to make something like this:

MACD(period_slow, period_fast) is calulcated by:

double[] values1 = EMA(period_slow, yAbsolute);
double[] values1 = EMA(period_fast, yAbsolute);
return Enumerable.Range(0, values1.Length).Select(i => values1[i] - values2[i]).ToArray();

Next let's create code for an implementation of MACD_SIGNAL:

MACD_SIGNAL(period_slow, period_fast, period_signal, yAbsolute) is calculated by:

double[] values1 = MACD(period_slow, period_fast, yAbsolute)
return new EMA(period_signal, values1);

When to buy and when to sell? There is a strategy for that. When MACD hits MACD_Signals you buy or sell depending what hit first:

double values1 = MACD(period_slow, period_fast, yAbsolute)
double values 2= MACD_SIGNAL(period_slow, period_fast, period_signal, yAbsolute)

double[] values = new double[y.Length];

for (int i = 0; i < y.Length; i++)
{
    values[i] = 0;

    if (i > 0)
    {
        bool buy  = values1[i - 1] < values2[i - 1] && values1[i] > values2[i];
        bool sell = values1[i - 1] > values2[i - 1] && values1[i] < values2[i];

        if (buy)
            values[i] = 1;
        else if (sell)
            values[i] = -1;
    }
}

That's how you implement MACD. Have fun!

Sort:  

What do you implement this in? It looks like JavaScript...

It is pseudocode but based on C# which I have used.

You got a 1.00% upvote from @buildawhale courtesy of @tallfishinthesea!
If you believe this post is spam or abuse, please report it to our Discord #abuse channel.

If you want to support our Curation Digest or our Spam & Abuse prevention efforts, please vote @themarkymark as witness.