Things to avoid due to performance

Moderator: admin

Things to avoid due to performance

Postby Nikolay.Gekht » Wed Mar 30, 2011 4:58 pm

Often, when you port MT4 indicators you may find pretty strange constructions which could harm the indicator performance dramatically. Here is a fresh example. I ported the MACD_Colored_v102.mq4
(http://www.forexfactory.com/showthread.php?t=20349) and found such construction there:

Code: Select all
double priMACD=(iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,1)-
                         iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,1))/Point;
while(curMACD<priMACD)
{
    pips++;
    close[0]+=Point;
    curMACD=(iMAOnArray(close,0,FastEMA,0,MODE_EMA,0) -
                   iMAOnArray(close,0,SlowEMA,0,MODE_EMA,0))/Point;
}


The intention of the indicator author is clear. He is trying to find such price at which the current bar of the MACD histogram will be equal to the previous bar. This function takes as long as far is the current price from the price he is trying to find. If it is 1000 pips here will be 1000 loops and EACH of them will calculate EMA.

This is the good code to think and write it properly.

Let's see what do we need? We need such price so
MACD(i) = MACD(i - 1)
we know that
MACD(i) = EMAFAST(i) - EMASLOW(i)
or
MACD(i) = Afast x price + (1 - Afast) x EMAFAST(i - 1) - (Aslow x price + (1 - Aslow) x EMASLOW(i - 1))
where
An = 2 / (n + 1)
(just a EMA formula)
So, we need MACD(i) equal to MACD(i - 1) (constant). The previous EMA values and Afast/Aslow are also constants. So, this is just a linear equation. Let's solve it. Put all constants to one side:
MACD(i - 1) - ((1 - Afast) x EMAFAST(i - 1) - (1 - Aslow) x EMASLOW(i - 1)) = Afast x price - Aslow x price
Put price out of brackets
MACD(i - 1) - ((1 - Afast) x EMAFAST(i - 1) - (1 - Aslow) x EMASLOW(i - 1)) = (Afast - Aslow) x price
And divide both sides to (Afast - Aslow)
(MACD(i - 1) - ((1 - Afast) x EMAFAST(i - 1) - (1 - Aslow) x EMASLOW(i - 1))) / (Afast - Aslow) = price

Voila! We have constants in left side and our price to find on right. Just one formula and no more loops! The indicator becomes lighting fast :-)
Nikolay.Gekht
FXCodeBase: Site Admin
 
Posts: 1235
Joined: Wed Dec 16, 2009 6:39 pm
Location: Cary, NC

Return to Indicator Development

Who is online

Users browsing this forum: No registered users and 7 guests