Close all trades as fast as possible

 

Hi!

 

I have an EA running on 5 charts. Part of my strategy is that as soon as my profit for the day, + floating P/L reaches 5%, I close all my open trades and stop trading of the day. I have written an EA that I run on a separate chart to monitor and P/L and close the trades. It is working well so far, however I have noticed that the speed at which the orders get close obviously has an impact on the final P/L. As much as I know that there are other factors that come in to play (latency, execution by broker), I want to make sure that my EA is using the most efficient code to close all the trades quickly.

 

I've posted my code here, and would appreciate it if anyone could give me some tips to "speed" up the code?

 

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2012, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
input double ProfitTarget=5;
bool CloseTrades=false;
double OpenOrderProfit;
datetime curday,prevday;
bool msgdone=true;
//+------------------------------------------------------------------+
int start()
//+------------------------------------------------------------------+
  {
   curday=iTime(Symbol(),PERIOD_D1,0);

   if(curday>prevday && 
      iTime(Symbol(),PERIOD_D1,0)>GlobalVariableGet("DailyOpenBalanceTime"))
     {
      GlobalVariableSet("DailyOpenBalance",AccountBalance());
      GlobalVariableSet("DailyOpenBalanceTime",iTime(Symbol(),PERIOD_D1,0));
      GlobalVariableSet("CanTrade",1);
      prevday=iTime(Symbol(),PERIOD_D1,0);
      msgdone=true;
      CloseTrades=false;
     }

//Check for 5%
   int cnt;
   if(!OrdersTotal()==0)
     {
      OpenOrderProfit=0;
      for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
        {
         if(!OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
            continue;
         if(OrderType()==OP_BUY ||
            OrderType()==OP_SELL)
           {
            //--- should it be closed?
            OpenOrderProfit+=OrderProfit();
           }
        }
     }

   double Profit=AccountBalance()+OpenOrderProfit-GlobalVariableGet("DailyOpenBalance");

   if(((Profit/GlobalVariableGet("DailyOpenBalance"))*100)>=ProfitTarget)
     {
      CloseTrades=true;
     }
//Close all orders!!!
   if(CloseTrades==true)
     {
      int cnts;
      if(!OrdersTotal()==0)
        {
         for(cnts=OrdersTotal()-1;cnts>=0;cnts--)
           {
            if(!OrderSelect(cnts,SELECT_BY_POS,MODE_TRADES))
               continue;
            if(OrderType()==OP_BUY)
              {
               if(!OrderClose(OrderTicket(),OrderLots(),Bid,0,0))
                 {
                  Print("OrderClose Error: ",GetLastError());
                 }
              }
            if(OrderType()==OP_SELL)
              {
               if(!OrderClose(OrderTicket(),OrderLots(),Ask,0,0))
                 {
                  Print("OrderClose Error: ",GetLastError());
                 }
              }
           }
        }
      if(GlobalVariableGet("CanTrade")==1)
        {
         GlobalVariableSet("CanTrade",0);
         msgdone=false;
        }
     }

   if(OrdersTotal()==0 && GlobalVariableGet("CanTrade")==0 && msgdone==false)
     {
      double prof=((AccountBalance()-GlobalVariableGet("DailyOpenBalance"))/GlobalVariableGet("DailyOpenBalance"))*100;
      prof=NormalizeDouble(prof,2);
      string msg="DTR! "+prof+"%";
      Alert(msg);
      SendNotification(msg);
      msgdone=true;
      CloseTrades=false;
     }

   if(AccountEquity()<=0)
     {
      //Close all orders!!!
      int cntss;
      if(!OrdersTotal()==0)
        {
         for(cntss=OrdersTotal()-1;cntss>=0;cntss--)
           {
            if(!OrderSelect(cntss,SELECT_BY_POS,MODE_TRADES))
               continue;
            if(OrderType()==OP_BUY)
              {
               if(!OrderClose(OrderTicket(),OrderLots(),Bid,0,0))
                 {
                  Print("OrderClose Error: ",GetLastError());
                 }
              }
            if(OrderType()==OP_SELL)
              {
               if(!OrderClose(OrderTicket(),OrderLots(),Ask,0,0))
                 {
                  Print("OrderClose Error: ",GetLastError());
                 }
              }
           }
        }
      if(GlobalVariableGet("CanTrade")==1)
        {
         GlobalVariableSet("CanTrade",0);
         Alert("Account Wiped Out!");
         SendNotification("Account Wiped Out!");
        }
     }
   return(0);
  }
//+------------------------------------------------------------------+

 Thanks!

Richard 

 
Anyone?
 

I'm still getting back into all of these trading terms - but you might want to look at the AccountFreeMargin , AccountFreeMarginCheck, and esp AccountFreeMarginMode functions to check your profit at a glance instead of looping through orders?

I could have missed something though...

 Also for profit you often have to look at OrderCommision() and OrderSwap()

 
  1. read1985:
                  if(!OrderClose(OrderTicket(),OrderLots(),Bid,0,0))
                     {
                      Print("OrderClose Error: ",GetLastError());
                     }
                  }
                if(OrderType()==OP_SELL)
                  {
                   if(!OrderClose(OrderTicket(),OrderLots(),Ask,0,0))
    1. You can not use any predefined variables when the OrderSymbol is not the current chart symbol.
    2. Don't test Bid/Sell. Just use OrderClosePrice().
    3. Server calls take time. You must RefreshRates() between them.
  2. if(!OrdersTotal()==0)
    if(!    5        ==0)
    if(!   TRUE      ==0)
    if( FALSE        ==0)
    if(   0          ==0) << test is always true.

  3. for(cnts=OrdersTotal()-1;cnts>=0;cnts--)
      profit += ..
    :
       if(((Profit/GlobalVariableGet("DailyOpenBalance"))*100)>=ProfitTarget)
         {
          CloseTrades=true;
         }
    
    All that could be simplified to
    CloseTrades = AccountEquity()/GlobalVariableGet("DailyOpenBalance"))*100 >= ProfitTarget;
    No loop, no if.
 

Awesome thanks so much! have made the changes in point 1 ,2 and 3 with a small difference

 

CloseTrades=((AccountEquity()-GlobalVariableGet("DailyOpenBalance"))/GlobalVariableGet("DailyOpenBalance")) * 100>=ProfitTarget;

 

 Also, I am not sure what you mean by this:

 

if(!OrdersTotal()==0)
if(!    5        ==0)
if(!   TRUE      ==0)
if( FALSE        ==0)
if(   0          ==0) << test is always true.

Thanks for your help!

 
if(!OrdersTotal()==0)
What part of "always true" was unclear?
 

Ok so, are you saying rather:

 

if(OrdersTotal()>0) 
Reason: