MACD order stoper problem

 

Hi guys, I started experimenting with a new piece of code that closes orders if the macd reaches the max of its values since 20bars(for example-if the order is buy) and reaches the min for a sell order. It is a function I wrote it looks like:

this is the array i use:
double macdarray[20];
and 
int size=20; 




void MACD_Stop ()
{
for(int i =0;i<size;i++)
{
macdarray[i]=iMACD(NULL,TF,12,26,9,PRICE_CLOSE,MODE_MAIN,i);
}
int MacdMax = ArrayMaximum(macdarray,size,1);
double max = macdarray[MacdMax];
int MacdMin = ArrayMinimum(macdarray,size,1);
double min = macdarray[MacdMin];
Print("MACD max : ",max," MACD min : ",min);
int result = 0;
int count = 0;
bool close = false;
if(UseMACDasStop)
{
for(int k = 0;k<OrdersTotal();k++)
{
if(!OrderSelect(k,SELECT_BY_POS,MODE_TRADES))
continue;
if(OrderMagicNumber()==magic && OrderType()==OP_BUY && macdarray[0]>=max)
{
result=1;
count++;
close = OrderClose(OrderTicket(),lot,Bid,1,clrBlack);
if(close)
{
 Print("order closed" );
}
else
 { 
Print("error : ",GetLastError());
}
}
else if (OrderMagicNumber()==magic && OrderType()==OP_SELL && macdarray[0]<=min)
{
result = 2;
count++;
close = OrderClose(OrderTicket(),lot,Ask,1,clrBlack);
if(close)
{
 Print("order closed" );
}
else {
 Print("error : ",GetLastError());
 }
}


}// end of loop
Print("The result is : ",result,"and the total count is: ",count);
}
return  ;



}//end of function

 When i insert this function at the end of OnTick() when is start the expert in the tester the balance drops to zero with the speed of light(it usually doesn`t do that, the expert wins).It usually does that even if i switch the size to 100 bars.Can u help me?

 

PS. I have an error showing in metaeditor in the array`s size if i write "size" there instead of "20". Can u figure this out too?

Thanks 

 

int size=20; 
double macdarray[];
ArrayResize(macdarray,size);
int MacdMax = ArrayMaximum(macdarray,size,1);

This is finding the maximum of element 1 to 20 in the array. I don't know what the result would be as element 20 does not exist.


As a non-coding comment:

The current MACD value being higher than previous MACD values is an indication that an uptrend is continuing. It doesn't make sense to use this as an indication to exit a buy trade.

 
Thanks for the answer it was very helpful, i will rethink my macd order close conception :D