EA not closeing trades

 
Hi all

Please forgive the long SRC code
Disregard most of these functions and variables they are not used and just stuff I wrote for learning.

My Maclosetrade() function is not closeing trades when using Close[1] condition. However it does close when using other indicator comparisons like MA crosses etc.

Anyhow the main used features of this code are currently:
MAtrade,MAclosetrade,OrderEntry, and start() function

MAtrade places trades, and MAclosetrades should close them when Close[1] breeches the MAsignal line

OK I'll repost the SRC thanks

Please advise
Thanks


Images below shows first buy has same sl as the buy price this is wrong. All future sl and tp are correct after the first order
Also the crosses should produce an order but they seem to buy and sell at strange times and disregard the crosses. Additionally they do not seem to close trades via MAclosetrade()
The condition appears to be met and should close as far as I can tell.

//+------------------------------------------------------------------+
//|                                                 functiontest.mq4 |
//|                                                 function testing |
//|                      Function Testing                            |
//+------------------------------------------------------------------+
#property copyright "Open Function Testing"


//---- input parameters
extern double LotSize=0.01;
extern int    TakeProfit=20;
extern int    StopLoss=10;
extern double lotmultiplier=2.0;
extern int    MagicNumber=123486;
extern int    MAperiod1=20;
extern int    MAperiod2=40;
extern int    MAperiod3=66;
extern int    MAsignal =10;

//for reference: http://www.forexfibonacci.com/calculate_fibonacci_levels/04/



//++++ These are adjusted for 5 digit brokers.

int     pips2points;    // slippage  3 pips    3=points    30=points
double  pips2dbl;       // Stoploss 15 pips    0.0015      0.00150


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
   if (Digits == 5 || Digits == 3)
   {    // Adjust for five (5) digit brokers.
      pips2dbl    = Point*10; pips2points = 10;
   } 
   else 
    {    
      pips2dbl    = Point;    pips2points =  1;
    }
    // OrderSend(... Slippage * pips2points, Bid - StopLossPips * pips2dbl
     
   
    
//---- 

//----
   return(0);
  }
  
  
  
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//---- 
   
//----
   return(0);
  }
   
    
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   
   static datetime PreviousTime=0;
   
   if(PreviousTime==Time[0])
      return(0);
   else PreviousTime=Time[0]; // PreviousTime==Time[0] returns until PremiousTime!=Time[0] else makes it ==[0] again and should run the start() once for each new candle
   
   MAtrade();
               
   return(0);
   }  
//+------------------------------------------------------------------+
//| end start function                                               |
//+------------------------------------------------------------------+ 

void MAtrade()
{
   //double faster= iMA(NULL,0,MAperiod1,0,MODE_EMA,PRICE_CLOSE,1);
   //double slower= iMA(NULL,0,MAperiod2,0,MODE_EMA,PRICE_CLOSE,1);
   double slowest= iMA(NULL,0,MAperiod3,0,MODE_SMA,PRICE_CLOSE,1);
   double fastsignal= iMA(NULL,0,MAsignal,0,MODE_EMA,PRICE_CLOSE,1); //MAsignal = fast signal
   //double prevfaster= iMA(NULL,0,MAperiod1,0,MODE_EMA,PRICE_CLOSE,2);
   //double prevslower= iMA(NULL,0,MAperiod2,0,MODE_EMA,PRICE_CLOSE,2);
   double prevslowest= iMA(NULL,0,MAperiod3,0,MODE_SMA,PRICE_CLOSE,2);
   double prevfastsignal= iMA(NULL,0,MAsignal,0,MODE_EMA,PRICE_CLOSE,2);

   if(prevfastsignal<prevslowest && fastsignal>slowest)OrderEntry(0);
   if(prevfastsignal>prevslowest && fastsignal<slowest)OrderEntry(1);
   
}
   
void MAclosetrade()
{
 
   double fastsignal= iMA(NULL,0,MAsignal,0,MODE_EMA,PRICE_CLOSE,1);
      
   bool result;
   for(int i = OrdersTotal()-1; i >= 0 ; i--)
      { 
      if(OrderSelect(i, SELECT_BY_POS)) 
         if(OrderMagicNumber() == MagicNumber)        
            if(OrderSymbol()== Symbol())
               {
                  if(OrderType() == OP_BUY)          
                     if(Close[1]<fastsignal) //if direction goes down on a buy order then close the order
                        {
                        result = OrderClose(OrderTicket(), OrderLots(), Bid, 3*pips2points, Blue);
                           if(result == false)
                              Print("Order",OrderTicket(),"failed to close Error",GetLastError()); 
                        }
                     
                     
                     if(OrderType() == OP_SELL)           
                        if(Close[1]>fastsignal) //if direction goes up on a sell order then close the order     
                           {
                           result = OrderClose(OrderTicket(), OrderLots(), Ask, 3*pips2points, Blue);
                              if(result == false)
                                 Print("Order",OrderTicket(),"failed to close Error",GetLastError());   
                           }   
               }          
      }


}
  

int OrderEntry(int direction)
{     
   int ticket;
   if(OrdersTotal() > 0) MAclosetrade();
   
   if(direction==0)
      if(OrdersTotal()==0)
         ticket = OrderSend(Symbol(),OP_BUY,LotSize,Ask,3*pips2points,Ask-(StopLoss*pips2dbl),Ask+(TakeProfit*pips2dbl),NULL,MagicNumber,0,Green);
         if(ticket<0) Alert("OrderSend Failed: ", GetLastError());
         
   if(direction==1)
      if(OrdersTotal()==0)
         ticket = OrderSend(Symbol(),OP_SELL,LotSize,Bid,3*pips2points,Bid+(StopLoss*pips2dbl),Bid-(TakeProfit*pips2dbl),NULL,MagicNumber,0,Red);
         if(ticket<0) Alert("OrderSend Failed: ", GetLastError());

return(0);
}      

//+------------------------------------------------------------------+





 
Agent86: My Maclosetrade() function is not closeing trades  Please advise
  1. Are your books one column but two feet wide? No because that is unreadable. They are 6 inches, sometimes two columns, so you can read it easily. So should be your code. I'm not going to go scrolling back and forth trying to read it. Edit the post with formatted code and you might get additional help.
  2. If you called the OrderClose, you would have seen the error message. Therefor you aren't calling it. Print out your variables, before and inside IF statements and find out why.
 

WHRoeder, I think you need some FullHD monitor at least :)

Agent86, when I'm backtesting this, it can't find something that looks like in your screenshots. I have no false buys/sells and on a lower timeframes some trades are closed by the EA (not by stops). If you are running this EA on a live account, make sure that there is no another EA running on a different chart. Here is how it looks for me on M1:

http://prntscr.com/578g0h  

 
JDeel:

WHRoeder, I think you need some FullHD monitor at least :)

Agent86, when I'm backtesting this, it can't find something that looks like in your screenshots. I have no false buys/sells and on a lower timeframes some trades are closed by the EA (not by stops). If you are running this EA on a live account, make sure that there is no another EA running on a different chart. Here is how it looks for me on M1:

http://prntscr.com/578g0h  

Look at your pic

I see the sell you pointed out, but why did it buy again, and look at the buy, there was a cross of Close[1]<fastsignal; and it did not close it. It went all the way to the tp level instead.
Then look at the next sell after that. It should have closed when Close[1]>fastsignal but it didn't close.

It is intermittently doing things that I don't understand.
The code seems straight forward enough and sort of typical. Mostly just for learning but I can't seem to make it close correctly.

I'm not sure if my start PreviousTime feature then it trades like crazy but it shouldn't do that either. It seems to disregard the if(OrdersTotal()==0) when I take away the PreviousTime statements; and it starts trading a lot of simultaneous trades that it shouldn't
It really does have me stumped

I have a MACD function and MACDclose with almost identical code that works perfect. The only difference is that the MAclosetrade uses Close[1] for condition instead of indicator crossings for closing the trade.
I'm stumped by this.

No other EA running and yes testing on live account in the tester.
Using MT4 data download.
Oanda data gives me data volume errors when backtesting too far so I just use Metatrader data for now for backtesting.
 
OK got rid of Close[1] from MAclose() and replaced it with if(fastsignal>slowest) and if(fastsignal<lowest) to close orders.

Still buying,selling and closing is strange.

 
AHHHHH !
I think I found part of the problem

Newly created EA's are actually saving to the MQL4 folder and not in MQL4/Experts as they should. The /experts folder automatically added my EA's to the /Experts folder so I thought all that was working for build 600 and up.
So this means that selecting an EA for the tester will select the one in the MQL4/Experts and not the one that is actually on the Metatrader editor for the MQL4 folder.
So making changes to the editor will have no effect on the EA selected in the tester because it's not the same EA file.
So that is one problem and I have no idea why the default saves are going to MQL4 and not MQL4/Experts sub folder. I'll figure that out later.
But at least that explains why making changes to the EA in the editor has no effect because the one in the editor is the one stored in MQL4 and NOT MQL/Experts

However, this does not solve the MAclosetrade() problem that will not close trades properly.
Crosses are now buying and selling as they should




if(Close[1]>fastsignal) should close right ?

 
Use Print() and you should get the value and from there you should know what to do.
 
deysmacro:
Use Print() and you should get the value and from there you should know what to do.
I am printing like crazy and not sure what to make of it

Check this out:
I'll use the first trade as an example of whats going on
From the results tab, but the picture below explains it the best

1       2013.11.04 02:30        buy     1       0.01    1.34955 1.34755 1.35355 0.00    10000.00
2       2013.11.04 21:15        close   1       0.01    1.35079 1.34755 1.35355 1.24    10001.24
However, my print statements produce this
2014.11.18 10:55:44.718 2013.11.04 21:15  pastebin EURUSD,M15: 1.3508 < 1.3511 close LONG ORDER fastsignal
2014.11.18 10:55:44.718 2013.11.04 21:15  pastebin EURUSD,M15: result = 1
2014.11.18 10:55:44.718 2013.11.04 21:15  pastebin EURUSD,M15: close #1 buy 0.01 EURUSD at 1.34955 sl: 1.34755 tp: 1.35355 at price 1.35079
2014.11.18 10:55:44.718 2013.11.04 21:15  pastebin EURUSD,M15: OrdersTotal = 1
2014.11.18 10:55:44.515 2013.11.04 02:30  pastebin EURUSD,M15: open #1 buy 0.01 EURUSD at 1.34955 sl: 1.34755 tp: 1.35355 ok

So the close was 1.35079 which was not a TP but some sort of close for some reason I cannot determine.
The journal shows my print statements just after the result close statement and it shows the price at 1.3508 for Close[1] which is less then 1.3511 for the fastsignal variable

The picture looks like it's closing because of a cross of the faster EMA below the slowest SMA, but there is NO if condition for a CloseOrder() cross. So why is it closing here ?
AND why is it NOT closing when Close[1] < fastsignal which occurs often ? and yet the condition seems to be met by my printout after the if statement.

void MAclosetrade()
{
 
   double fastsignal= iMA(NULL,0,MAsignal,0,MODE_EMA,PRICE_CLOSE,1);
   double slowest= iMA(NULL,0,MAperiod3,0,MODE_SMA,PRICE_CLOSE,1);
   //Print(fastsignal,"/",slowest, " fastsignal / slowest");
   Print("OrdersTotal = ",OrdersTotal());
   bool result;
   for(int i = OrdersTotal()-1; i >= 0 ; i--)
      { 
      if(OrderSelect(i, SELECT_BY_POS)) 
         if(OrderMagicNumber() == MagicNumber)        
            if(OrderSymbol()== Symbol())
               {
                  if(OrderType() == OP_BUY)         
                     if(Close[1]<fastsignal) //if direction goes down on a buy order then close the order
                        {
                        result = OrderClose(OrderTicket(), OrderLots(), Bid, 3*pips2points, White);
                        Print("result = ",result);
                        Print(Close[1]," < ",fastsignal," close LONG ORDER fastsignal");
                           if(result == false)
                              Print("Order",OrderTicket(),"failed to close Error",GetLastError()); 
                        }
                     
                     
                     if(OrderType() == OP_SELL)           
                        if(Close[1]>fastsignal)//if direction goes up on a sell order then close the order     
                           {
                           result = OrderClose(OrderTicket(), OrderLots(), Ask, 3*pips2points, White);
                           Print(Close[1]," > ",fastsignal, " close SHORT ORDER fastsignal");
                              if(result == false)
                                 Print("Order",OrderTicket(),"failed to close Error",GetLastError());   
                           }   
               }          
      }


}
  

int OrderEntry(int direction)
{     
   int ticket;
   if(OrdersTotal() > 0) MAclosetrade();
   
   if(direction==0)
      if(OrdersTotal()==0)
         ticket = OrderSend(Symbol(),OP_BUY,LotSize,Ask,3*pips2points,Ask-(StopLoss*pips2dbl),Ask+(TakeProfit*pips2dbl),NULL,MagicNumber,0,Green);
         if(ticket<0) Alert("OrderSend Failed: ", GetLastError());
         
   if(direction==1)
      if(OrdersTotal()==0)
         ticket = OrderSend(Symbol(),OP_SELL,LotSize,Bid,3*pips2points,Bid+(StopLoss*pips2dbl),Bid-(TakeProfit*pips2dbl),NULL,MagicNumber,0,Red);
         if(ticket<0) Alert("OrderSend Failed: ", GetLastError());

return(0);
}      



And here is the pic of the chart showing the close on the cross where NO cross condition exists




I know how to print things and i have no idea why it's not closing orders and also closing for strange reasons.
The code looks ok to me as far as I can tell. I'm sure I'm missing something simple, but actually expected it to work without any changes.

I can't figure this out and Print is not providing answers for me, at least none that jump out at me.

Please advise

Thanks

 
I'm so screwed

Sorry to go on about this but I can't close orders and this seems relatively simple, but I'm missing something


I've Printed everything and anything as far as I know making minor changes to dumb things down a bit,  no closing.

Well it seems to close whenever it wants it does not seem to have a reason for closing. It closes on s/l and t/p sometimes but mostly closes at unknown condition

 
Agent86:

Agent86:

So the close was 1.35079 which was not a TP but some sort of close for some reason I cannot determine.
The journal shows my print statements just after the result close statement and it shows the price at 1.3508 for Close[1] which is less then 1.3511 for the fastsignal variable
AND why is it NOT closing when Close[1] < fastsignal which occurs often ? and yet the condition seems to be met by my printout after the if statement.


It seems to me that you are calling the function to close the order only when conditions are met for a new order.

Check conditions to close orders every new bar. 

 
GumRai:

It seems to me that you are calling the function to close the order only when conditions are met for a new order.

Check conditions to close orders every new bar. 

Brilliant, I see it now thanks.

So my close function definitely needs to be called in the start() function or something that does not require the open conditions to be met first.

This give me a bunch of cool stuff to think over now,
Thanks again for the response. BIG HELP
Reason: