How do I get my ea to stop trading for the rest of the day after... - page 2

 

Hello OpenGates,

 I suppose you know how to code but you are asking for the way of implementing the solution you are after; because as has been said, I  doubt anyone will offer you a solution for free. Regarding you question, I am supposing that you have to figure out a way of counting; yep, you have to count (or to be precise, your EA) every now and then in order to be able to deactivate your expert. Hopefully, MQL has a very easy to use built in timer which is OnTimer(). OnTimer can work along with OnTick, so ou can have OnTick perform your market algorithm and put a counter (like count++) inside OnTimer (in case you are using OnTick of course - or else, you can put all your code inside OnTimer). Supposedely, OnTimer will be stable, so 100 increments of "count" on a 10 seconds OnTimer will result at about 1000 seconds. Since I will not ...count on it, I propose to implement a time check from time to time , in conjuction with OnTimer and make necessary adjustements. 

 

best reagrds 

 
WHRoeder:
I understood you completely. You have not posted any code since my previous post. You just rejected my post and asked for simple codes again. Since you haven't learned the mql4 language, we have nothing to communicate with.

WHRoeder,

Sorry if I also misunderstood you. I said the codes you posted was beyond my scope and understanding, I already posted a code at the beginning of my post, the codes do closed all positions but it fails to stop the expert from opening another positions until the specified time and day, this is exactly where I became helpless. I only want somebody to help add or correct my codes to be able to stop trading until the specified time I AM NOT LOOKING FOR NEW CODES. So sorry if I slighted you in anyway neither do I rejected your post, in fact I have to admit that I respect you in terms of unparalleled coding and intelligence. I HONESTLY DON'T KNOW HOW TO RECONCILE MY SIMPLE CODING WITH YOUR OWN TO MAKE IT WORK FOR ME. THAT IS ALL I AM SAYING. Below is the code again: Thank you

 
 int StartTrdg=9; //start trading for the day
 int StopTrdg=20; //stop trading for the day
 double AcctBal = AccountBalance(); 
 double Equity = AccountEquity();
 double Ppt=15;
 double Dtot = AcctBal+Ppt;
 datetime tdaymdngt=TimeCurrent()-TimeCurrent()%(PERIOD_D1*60); 
 tmoro=tdaymdngt+StartTrdg*3600; 
 bool trade_disabled=false;
 //close both buy and sell in profits
  bool trade_disabled=false;
  if(UseDailyTarget==true && Equity>=Dtot && Hour()>StartTrdg) 
  {
  for(int fmd=OrdersTotal()-1; fmd>=0; fmd--) {
  if(OrderSelect(fmd, SELECT_BY_POS, MODE_TRADES)) {
  if(OrderType()==OP_BUY || OrderType()==OP_SELL) {
  OrdCls=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage);
  if(OrdCls && UseDailyTarget) {
  trade_disabled=true; //Disable expert to stop opening another positions
  break;   //stop trading untill...
     } else {
  if(OrdCls==true && TimeDayOfYear(TimeCurrent())>=tmoro) {  
  trade_disabled=false; // start trading again at this time
  } } } } } }
//========================================================

This is the one I devised through your code but yet not working. It is supposed to resume trading by 9am the second day.
Thank you. 
 
 int StartTrdg=9; //start trading for the day
 int StopTrdg=20; //stop trading for the day
 double AcctBal = AccountBalance(); 
 double Equity = AccountEquity();
 double Ppt=15;
 double Dtot = AcctBal+Ppt;
 datetime tdaymdngt=TimeCurrent()-TimeCurrent()%(PERIOD_D1*60); 
 tmoro=tdaymdngt+StartTrdg*3600; 
 bool trade_disabled=false;
 //close both buy and sell in profits
 if(UseDailyTarget==true && Equity>=Dtot && Hour()>StartTrdg) 
 {
     for(int fmd=OrdersTotal()-1; fmd>=0; fmd--)
     {  
         if(OrderSelect(fmd, SELECT_BY_POS, MODE_TRADES)) 
         {
             if(OrderType()==OP_BUY || OrderType()==OP_SELL) 
             {
                 OrdCls=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage);

                 if(OrdCls && UseDailyTarget) 
                 {
                     trade_disabled=true; //Disable expert to stop opening another positions
                     break;   //stop trading untill...
                 } 
                 else 
                 {
                     if(OrdCls==true && TimeDayOfYear(TimeCurrent())>=tmoro) trade_disabled=false; // start trading again at this time
  } } } } } }
Hello,
As you can see, I reposted your code intended; I did so because I was unable to follow your original formatting 
and since I have done it nevertheless, I posted it - I hope you do not mind . Now, regarding the content of your code, 
I may say that I am not following how and if your EA has a knowledge of what time it is, so as to be able to stop 
trading at a certain one, but I will leave that up to you. What I can say is about the logic of closing the orders depending 
if you are in profit or not. I can see that you are using, for example,
 if(UseDailyTarget==true && Equity>=Dtot && Hour()>StartTrdg) 
That means that all conditions must be true for your program to go on. But guess what happens if UseDailyTarget is not met?
So, your program must halt trading at 20.00pm, no matter if that target has been reached. Consequently, you should in fact have 
two conditions as such: 
 if (UseDailyTarget==true OR time of day == 8 pm) 
 {    
    /* your cleaning goes here */ 
    trade_disabled=true
 }

	          
 

Give variables names that make them easy to identify. If you ask for help it makes it so much easier for potential helpers to follow your code. Not only that, you will forget if you come back to code after not working on it for a while.

You have used code that I posted earlier.

      datetime today_midnight=TimeCurrent()-(TimeCurrent()%(PERIOD_D1*60));
      datetime tomorrow_midnight=today_midnight+PERIOD_D1*60;
      recommence_trading=tomorrow_midnight+trade_hour*3600;

 

but you have changed it
 datetime tdaymdngt=TimeCurrent()-TimeCurrent()%(PERIOD_D1*60); 
 tmoro=tdaymdngt+StartTrdg*3600; 

 today_midnight and tomorrow_midnight are self explanatory

 tdaymdngt is a jumble of letters

tmoro is obviously meant to refer to tomorrow, but it is an undeclared variable ( according to the code that we can see) but it calculates a time for today, not tomorrow

 

Ppt, Dtot,fmd, No idea what they are referring to 

 

The idea behind the ea is to start trading by 9am and stop by 20 (8pm) but then there is added idea that if UseDailyTarget is set to true  and the amount (in dollar) in the input parameter, when that amount (profit only) has been reached i.e if equity is greater than our balance by that amount (Ppt), irrespective of the time, it should close all the orders and stop trading for the rest of the day and to resume the normal time (9am) on the second day. But it was just opening more orders after closing the existing ones without stopping. Dtot is the addition of Target amount+Account balance

Thank you for your advices and helps so far. Have learnt a lot from all your tutorials. But please help me to review the codes in line with my explanations and what I want it to do. 

 

Hello,

This is the new code I was able to write but still not yet working. Pls help take a look at it and let me know what to do next.

Thanks

// The code below already handled the start trading (9am)and stop trading (8pm) issue successfully
  extern bool          UseStartTrdgHour  = false;   // Activate Start-Trading Hour (Select True)
  extern int           StartTradingHour  = 9.0;     // Set time to start trading (0-23: 24hr-Clock)
  extern bool          UseStopTrdgHour   = false;   // Activate Stop-Trading Hour (Select True)
  extern int           StopTradingHour   = 20.0;    // Set time to stop trading (0-23: 24hr-Clock)
  if(UseStopTrdgHour==true && UseStartTrdgHour==true) {
  if(Hour()>StopTradingHour || Hour()<StartTradingHour) {
  Comment("Trading is not allowed at this time of the day!");
  return(0);
   }
  }

  if(DayOfWeek()==5 && Hour()>StopTradingHour) {
  Comment("No trading on Weekends! Market is closed!");
  return(0);
     }

//==================================
extern bool          UseDailyTarget   = false;   // Activate Daily Target (Select true)
extern double        target_amount    = 0.0;    // Amount set as target daily - i. e 10.0
double               my_acctBal = AccountBalance(); 
double               my_equity = AccountEquity();
double               overall_total = my_acctBal+target_amount;
static               datetime recommence_trading=0;
 // calculates profits in orders history
  double HProfit=0; 
  for(int fmd=OrdersHistoryTotal()-1; fmd>=0; fmd--) {
  if(OrderSelect(fmd, SELECT_BY_POS, MODE_HISTORY)) {
  if(OrderType()==OP_BUY || OrderType()==OP_SELL) {
  HProfit+=OrderProfit()+OrderSwap()+OrderCommission(); 
  }}}  
// Calculates profits in currently opened orders
  double TProfit=0;
  for(int fmd=OrdersTotal()-1; fmd>=0; fmd--) {
  if(OrderSelect(fmd, SELECT_BY_POS, MODE_TRADES)) {
  if(OrderType()==OP_BUY || OrderType()==OP_SELL) {
  TProfit+=OrderProfit()+OrderSwap()+OrderCommission(); 
  }}}  
// Add it al together 
  double all_profits=TProfit+HProfit;
  datetime today_midnight=TimeCurrent()-(TimeCurrent()%(PERIOD_D1*60));
  if(UseDailyTarget==true && all_profits>=target_amount && my_equity>=overall_total &&
Hour()>StartTrdgHour && TimeDayOfYear(OrderOpenTime())>=today_midnight)))
  OrdCls=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage);
  if(OrdCls==true && UseDailyTarget==true && TimeCurrent()>=recommence_trading) 
                 {
        today_midnight=TimeCurrent()-(TimeCurrent()%(PERIOD_D1*60));
        datetime tomorrow_midnight;
   if(Hour()<StartTradingHour)
        recommence_trading=today_midnight+StartTradingHour*3600;
        else
        {
   if(TimeDayOfWeek(TimeCurrent())==5)
         tomorrow_midnight=today_midnight+PERIOD_D1*60*3;
         else
         tomorrow_midnight=today_midnight+PERIOD_D1*60;
         recommence_trading=tomorrow_midnight+StartTradingHour*3600;
        }
     }
  if(TimeCurrent()<recommence_trading)
   return(0);    
 

You are calculating profits for all closed trades, not only those opened today

A simpler way would be

  
  static datetime new_day_start=0;
  static double my_equity=0;
  if(today_midnight>new_day)
     {
     new_day_start=today_midnight;
     my_equity=AccountEquity();
     }
  if(AccountEquity()-my_equity>=target_amount)
     {
     //Close open orders
     //Set recommence_trading
     }
 

WHRoeder, GumRai and others,

Thanks for replying me in spite of my inadequacies. I am very grateful. I have written out a certain code culled out of those given to me here and still testing it, if by tomorrow it has not yet worked as I expected, I will post it here for a review from you people to help look and to see where I have missed it.

Thank you so much.

 

WHRoeder, GumRai and others,

Thanks for your assistance so far, I am yet to get over it, however, below is the codes I used as culled from the ones given above. It is closing the orders as supposed but after that, it continues to open another orders instead of stopping trading and resuming at the time specified. Please help analyze what I did wrong or if I missed it somewhere. Thanks in advance

  
  extern bool          UseDailyTarget   = false;   // Activate Daily Target (Select true)
  extern double        target_amount    = 0.0;    // Amount set as target daily  
  double my_acctBal = AccountBalance(); 
  double my_equity = AccountEquity();
  double overall_total = my_acctBal+target_amount;
  int trade_hour=9;  // Time to start trading every new day
  int stop_trade=20; // Normally stops trading at this hour except the target is reached before this hour
  static datetime recommence_trading=0; // Time to resume trading again if the target amount was reached
  for(int i=1; i<=OrdersTotal(); i++)
   {
  if (OrderSelect(i-1,SELECT_BY_POS))
   {
  if(OrderSymbol()==Symb)
   {
  if(OrderType()==OP_BUY || OrderType()==OP_SELL) 
  {
  if(UseDailyTarget==true && my_equity>=overall_total && TimeCurrent()>=trade_hour) 
   {
  OrdCls=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),2); 
  if(OrdCls)
  Print("Daily Target Achieved. No more trading today!");
  return(0);
  datetime today_midnight=TimeCurrent()-(TimeCurrent()%(PERIOD_D1*60));
  recommence_trading=today_midnight+trade_hour*3600;
  if(OrdersTotal()==0 && TimeCurrent()>=recommence_trading)
  return(1);    
   } } } } }
Reason: