How to close all position trade at end of Week

 

Hi everyone!

Now I want to send to all the method to close all positions trade at time end of weekness. Detail as below:

 void OnTick()

   {

      if(close_end_of_week())

      {

      Close_allpending(symbol_index,POSITION_TYPE_SELL);   

      Close_allpending(symbol_index,POSITION_TYPE_BUY);  

      }

}

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

//| Close all positions by opposite positions                        |
//+------------------------------------------------------------------+
void Close_allpending(int symbol_index,ENUM_POSITION_TYPE type)
  {
   int total=PositionsTotal(); // number of open positions   
//--- iterate over all open positions
   for(int i=total-1; i>=0; i--)
     {
      //--- parameters of the order
      ulong  position_ticket=PositionGetTicket(i);                                    // ticket of the position
      string position_symbol=PositionGetString(POSITION_SYMBOL);                      // symbol 
      int    digits=(int)SymbolInfoInteger(position_symbol,SYMBOL_DIGITS);            // ticket of the position
      ulong  magic=PositionGetInteger(POSITION_MAGIC);                                // MagicNumber of the position

      //--- if the MagicNumber matches
      if(magic==EXPERT_MAGIC)
        {
          if(position_symbol==PositionGetSymbol(i)) // symbol of the opposite position
          {
            //--- if the symbols of the opposite and initial positions match
            if(position_symbol==symbol_list[symbol_index] && PositionGetInteger(POSITION_MAGIC)==EXPERT_MAGIC)
             {
               
               //--- leave, if the types of the initial and opposite positions match
               if(type==PositionGetInteger(POSITION_TYPE))
               {
               // close end off week
               trade.PositionClose(position_ticket);
               }
             }
           }
        }
     }
  }
//+------------------------------------------------------------------+

bool close_end_of_week()
{

MqlDateTime Gmt_time;
TimeGMT(Gmt_time);
if(Gmt_time.hour>=hour_end_week && Gmt_time.day_of_week>=end_week)
{
return true;
}
return false;
}



RESULT:

BEFORE:


AFTER:


Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
  • www.mql5.com
Position Properties - Trade Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
When you post code please use the Code button (Alt+S) !

...

Improperly formatted code removed by moderator. Please EDIT your post and use the CODE button (Alt-S) when inserting code.

Code button in editor

Hover your mouse over your post and select "edit" ... 

 
//+------------------------------------------------------------------+
//| Returns true 1-2 hours before Fx market closing on Friday        |
//+------------------------------------------------------------------+
bool TimeFridayEOW()
  {
   MqlDateTime dt;
   TimeToStruct(TimeGMT(), dt);

//--- skip opening new trades after 8:00 pm (GMT) to have enough time for exit
   if(dt.day_of_week == (ENUM_DAY_OF_WEEK)FRIDAY && dt.hour >= 20)  // FX closes Fri, 10:00 PM UTC in winter (and Fri, 09:00 PM UTC in summer)
     {
      return(true);
     }
     
   return(false);
  }
 
Well note
 

The Forex week lasts from Sun. 17:00 - Fri. 17:00 (NY time) that is in seconds:
#define FXOneWeek 432000 // Sun. 22:00 - Fri. 22:00 = 5*24*60*60 = 432000

So detect the first forex trading hour of the actual week of the the broker time (TimeCurrent()) and
add to this time (5*24*60*60 - 2*3600) seconds to get the timestamp of two hours before the forex session closes,
no matter whether DST of NY, your broker, or the location of the pc/server is 'on' or 'out' .

PS: It is better to use EURUSD for this, as gold can have different settings depending on the broker!

 
Thank for your comment
 
Carl Schreiber #:

The Forex week lasts from Sun. 17:00 - Fri. 17:00 (NY time) that is in seconds:
#define FXOneWeek 432000 // Sun. 22:00 - Fri. 22:00 = 5*24*60*60 = 432000

So detect the first forex trading hour of the actual week of the the broker time (TimeCurrent()) and
add to this time (5*24*60*60 - 2*3600) seconds to get the timestamp of two hours before the forex session closes,
no matter whether DST of NY, your broker, or the location of the pc/server is 'on' or 'out' .

PS: It is better to use EURUSD for this, as gold can have different settings depending on the broker!

One can also look at this tutorial https://www.youtube.com/watch?v=mQtluW5hgC8 for a professional approach to close trade(s) at weekend. 

How to Automate Closing All MT5 Trades at a Scheduled Time | Boost Your Trading Efficiency
How to Automate Closing All MT5 Trades at a Scheduled Time | Boost Your Trading Efficiency
  • 2023.02.24
  • www.youtube.com
If you're an experienced trader who uses the popular MetaTrader platform, you may know that closing all trades manually can be a tedious and time-consuming t...
 
Thank for all
 
Anil Varma #:

One can also look at this tutorial https://www.youtube.com/watch?v=mQtluW5hgC8 for a professional approach to close trade(s) at weekend. 

Anil the posted code on YouTube

1. It is not portable for all brokers, as it requires you to enter broker hour and minute of close which is different. Forex close time on brokers can range from Fri, 02:00 PM server time, up to Sat, 09:00 AM server time depending on its offset from GMT,  therefore my method using TimeGMT() is more portable, it is 1 or 2 hours before Fx close time. Carl's methods is accurate but requires a ton of code.

2. The code contains logical errors with timers, (a) it will only fire for the first weekend then stops next weeks. (b) if the expert advisor is launched after the set hour and minute on Friday simply it will not fire at all.

 

For more precise control of the weekend:

//+-------------------------------------------------------------------+
//| Time remaining in seconds till the next weekend.                  |
//| Returns 0 remaining sec, if called during the weekend.            |
//+-------------------------------------------------------------------+
int SecTillWeekend(void)
  {
   datetime now       = TimeGMT();
   datetime sunday    = now-(now+345600)%604800; // Begin of Week 2017.08.03 11:30 => Sun, 2017.07.30 00:00

//--- US summer starts on the second Sunday of March
//--- and ends before the first Sunday of November.
   MqlDateTime dt;
   TimeToStruct(sunday, dt);
   datetime dst_start = StringToTime((string)dt.year+".03.08");
   datetime dst_end   = StringToTime((string)dt.year+".11.01");
   int      hour      = (sunday>=dst_start && sunday<dst_end) ? 21 : 22;
   datetime open      = sunday + hour*3600; // FX opens  Sun, 22:00 UTC in winter (and Sun, 21:00 UTC in summer)
   datetime close     = open   + 5*24*3600; // FX closes Fri, 22:00 UTC in winter (and Fri, 21:00 UTC in summer)
   int      remaining = 0;
   if(now >= open && now < close)
     {
      remaining = (int)(close - now) - 1;
     }
   return(remaining);
  }

possible uses:

input int pHoursBefore   = 2;  // Hours before weekend
input int pMinutesBefore = 0;  // Minutes before weekend

void OnTick()  // or OnTimer()
  {
   //--- close before the weekend
   if(SecTillWeekend() <= pHoursBefore*3600 + pMinutesBefore*60)
     {
      // CloseAll();
     }

   //--- get the start of the next weekend
   if(SecTillWeekend() != 0)
     {
      Print("Start of weekend is ", TimeToString(TimeCurrent() + SecTillWeekend()));
     }
  }
 

Based on SecTillWeekend():

//+------------------------------------------------------------------+
//| Returns true if time now is pHour and pMinute before weekend.    |
//+------------------------------------------------------------------+
bool CheckBeforeWeekend(int pHoursBefore, int pMinutesBefore)
  {
   int secs = SecTillWeekend();
   return(secs > 0 && secs <= pHoursBefore*3600 + pMinutesBefore*60);
  }

Usage:

void OnTick()  // or OnTimer()
  {
//--- close before the weekend
   if(CheckBeforeWeekend(pHoursBefore, pMinutesBefore))
     {
      CloseAll();
     }  
  }