close position on friday

 

hello guys,

I'm trying a very simple EA that should close position at the end of the week . it enters long when the price is above the last high and exit on friday at 23 or for a stoploss triggered. same thing for short position.

during backtesting it enters and triggers stoplosses but does not close on friday night!!

it's called on every tick and works on weekly bars data.

it's the very first advisor I write, i started by modifing my_first_EA.

I hope someone exeprienced could see at glance my mistake.

the code is below

//+------------------------------------------------------------------+
//|                                                  My_Second_EA.mq5 |
//|                        Copyright 2013, MBTrader. |
//|                                         
//+------------------------------------------------------------------+
#property copyright " Copyright 2013, MBTrader."
#property version   "1.00"
//includes
#include <Trade\Trade.mqh>
//--- input parameters
input int      StopLoss=30;      // Stop Loss
input int      ATR_Period=8;     // ADX Period
input int      MA_Period=8;      // Moving Average Period
input double   Lot=1;          // Lots to Trade fixed ratio => balance/100000 * Lot = lots to trade
input int      EA_Magic=12345;   // EA Magic Number
input double      triggerPerc=1.0;
input bool     long_only=false;
input bool     short_only=false;
//--- Other parameters
int atrHandle; // handle for our ADX indicator
int maHandle;  // handle for our Moving Average indicator
double maVal[],atrVal[]; // Dynamic array to hold the values of Moving Average for each bars
double p_close,p_open,p_high,p_low; // Variable to store the close value of a bar
double stop_price; //variable to store the orice where to stop. updated by trailing stop
double enter_price; //price at which the system have entered thre market
int STP,TKP;   // To be used for Stop Loss & Take Profit values
bool this_bar_traded=false;
double longTrigger_price;
double shortTrigger_price;
CTrade mytrade;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Get handle for ATR indicator
   atrHandle=iATR(_Symbol,PERIOD_D1,ATR_Period);
//--- Get the handle for Moving Average indicator
   maHandle=iMA(_Symbol,PERIOD_D1,MA_Period,0,MODE_EMA,PRICE_CLOSE);
//--- What if handle returns Invalid Handle
   if(atrHandle<0 || maHandle<0)
     {
      Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!!");
      return(-1);
     }

//--- Let us handle currency pairs with 5 or 3 digit prices instead of 4
   STP=StopLoss;

   if(_Digits==5 || _Digits==3)
     {
      STP=STP*10;
     }
   return(0);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- Release our indicator handles
   IndicatorRelease(atrHandle);
   IndicatorRelease(maHandle);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {

   double now_ask,now_bid;
   double Lots=1;
   double SL=STP; //mysymbol.Ask() – Stoploss*_Point;   
   double TP= 0.0;
   bool Entry_Condition_1;
   bool Entry_Condition_2;
//--- Do we have enough bars to work with
   if(Bars(_Symbol,_Period)<MA_Period) // if total bars is less than twice MA_Period bars
     {
      Alert("We have less than MA needs bars, EA will now exit!!");
      return;
     }

// We will use the static Old_Time variable to serve the bar time.
// At each OnTick execution we will check the current bar time with the saved one.
// If the bar time isn't equal to the saved time, it indicates that we have a new tick.
   MqlDateTime now_time;
   bool we=false;
   static datetime Old_Time;
   datetime New_Time[1];
   bool IsNewBar=false;
   uint return_code;
   MqlTick latest_price;      // To be used for getting recent/latest price quotes
   MqlRates mrate[];          // To be used to store the prices, volumes and spread of each bar
                              // copying the last bar time to the element New_Time[0]
   TimeCurrent(now_time);
   we=now_time.day_of_week==5 && now_time.hour==23;
   if(we) Alert("WE true");
   int copied=CopyTime(_Symbol,_Period,0,1,New_Time);
   if(copied>0) // ok, the data has been copied successfully
     {
      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time
        {
         IsNewBar=true;   // if it isn't a first call, the new bar has appeared
         this_bar_traded=false;
         if(MQL5InfoInteger(MQL5_DEBUGGING)) Print("We have new bar here ",New_Time[0]," old time was ",Old_Time);
         Alert("We have new bar here ",New_Time[0]," old time was ",Old_Time);
         //Alert("dayoftheweek: ",now_time.day_of_week," hour ",now_time.hour);
         Old_Time=New_Time[0];            // saving bar time
        }
     }
   else
     {
      Alert("Error in copying historical times data, error =",GetLastError());
      ResetLastError();
      return;
     }

//--- EA should only check for new trade if we have a new bar
   if(IsNewBar)
     {
      int Mybars=Bars(_Symbol,_Period);
      if(Mybars<MA_Period) // if total bars is less than 60 bars
        {
         Alert("We have less than 60 bars, EA will now exit!!");
         return;
        }
      //--- Define some MQL5 Structures we will use for our trade

/*
     Let's make sure our arrays values for the Rates, ADX Values and MA values 
     is store serially similar to the timeseries array
*/
      // the rates arrays
      ArraySetAsSeries(mrate,true);
      // the ATR values arrays
      ArraySetAsSeries(atrVal,true);
      // the MA-8 values arrays
      ArraySetAsSeries(maVal,true);

      //--- Get the details of the latest 3 bars
      if(CopyRates(_Symbol,_Period,0,3,mrate)<0)
        {
         Alert("Error copying rates/history data - error:",GetLastError(),"!!");
         ResetLastError();
         return;
        }

      //--- Copy the new values of our indicators to buffers (arrays) using the handle
      if(CopyBuffer(atrHandle,0,0,3,atrVal)<0)
        {
         Alert("Error copying ATR indicator Buffers - error:",GetLastError(),"!!");
         ResetLastError();
         return;
        }
      if(CopyBuffer(maHandle,0,0,3,maVal)<0)
        {
         Alert("Error copying Moving Average indicator buffer - error:",GetLastError());
         ResetLastError();
         return;
        }

      // Copy the bar close price for the previous bar prior to the current bar, that is Bar 1
      p_close=mrate[1].close;  // bar 1 close price
      p_open=mrate[1].open;  // bar 1 open price
      p_high=mrate[1].high;  // bar 1 high price
      p_low=mrate[1].low;  // bar 1 low price
      longTrigger_price=p_close>p_open? p_close+(p_high-p_close)*triggerPerc : p_open+(p_high-p_open)*triggerPerc;
      shortTrigger_price=p_close>p_open? p_open-(p_open-p_low)*triggerPerc : p_close-(p_close-p_low)*triggerPerc;
      //Alert("ATR VALUE ",atrVal[ArraySize(atrVal)-1]);
     }

//--- Do we have enough bars to work with

//--- Get the last price quote using the MQL5 MqlTick Structure
   if(!SymbolInfoTick(_Symbol,latest_price))
     {
      Alert("Error getting the latest price quote - error:",GetLastError(),"!!");
      return;
     }
   now_ask = latest_price.ask;
   now_bid = latest_price.bid;

//--- we have no errors, so continue
//--- Do we have positions opened already?
   bool Buy_opened=false;  // variable to hold the result of Buy opened position
   bool Sell_opened=false; // variables to hold the result of Sell opened position

   if(PositionSelect(_Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //It is a Buy
                           //then test wheter to update stoplosses or close the position
         if(we)
           {
            mytrade.PositionClose(_Symbol,10.0);
            // a trade operation has just been carried out
            return_code=mytrade.ResultRetcode();
            // get the result code
            if(return_code==10009 || return_code==10008) //Request is completed or order placed
              {
               Alert("A CLOSE order on long position has been successfully placed with Ticket#:",mytrade.ResultDeal(),"!!closing price is: ",mytrade.ResultPrice(),"WE",we);
               this_bar_traded=true;
              }
            else
              {
               Alert("The Buy order request could not be completed -error:",GetLastError());
               ResetLastError();
               return;
              }
           }
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // It is a Sell

         if(we)
           {
            mytrade.PositionClose(_Symbol,10.0);
            // a trade operation has just been carried out
            return_code=mytrade.ResultRetcode();
            // get the result code
            if(return_code==10009 || return_code==10008) //Request is completed or order placed
              {
               Alert("A CLOSE order on short position has been successfully placed with Ticket#:",mytrade.ResultDeal(),"!!closing price is: ",mytrade.ResultPrice(),"WE",we);
               this_bar_traded=true;
              }
            else
              {
               Alert("The Buy order request could not be completed -error:",GetLastError());
               ResetLastError();
               return;
              }
           }
        }
     }

   Entry_Condition_1=now_time.day_of_week!=1;
   Entry_Condition_2=!this_bar_traded; //&&now_time.hour<23 
/*
    1. Check for a long/Buy Setup : MA-8 increasing upwards, 
    previous price close above it, ADX > 22, +DI > -DI
*/
//--- Declare bool type variables to hold our Buy Conditions
   bool Buy_Condition_1=(now_ask>longTrigger_price) && !short_only; // MA-8 Increasing upwards
   bool Buy_Condition_2=true;//(now_time.day_of_week!=1) && (now_time.day_of_week!=0);      

//--- Putting all together   
   if(Buy_Condition_1 && Buy_Condition_2 && Entry_Condition_1 && Entry_Condition_2)
     {

      // any opened Buy position?
      if(Buy_opened)
        {
         //Alert("We already have a Buy Position!!!");
         //update step_price for traling stop
         if(we)
           {
            mytrade.PositionClose(_Symbol,10.0);
            // a trade operation has just been carried out
            return_code=mytrade.ResultRetcode();
            // get the result code
            if(return_code==10009 || return_code==10008) //Request is completed or order placed
              {
               Alert("A CLOSE order on short position has been successfully placed with Ticket#:",mytrade.ResultDeal(),"!!closing price is: ",mytrade.ResultPrice(),"WE",we);
               this_bar_traded=true;
              }
            else
              {
               Alert("The Buy order request could not be completed -error:",GetLastError());
               ResetLastError();
               return;
              }
           }
         return;    // Don't open a new Buy Position
        }
      Alert("goin long day ",now_time.day_of_week," hour ",now_time.hour);
      SL=now_ask -STP*_Point; //remember 1pip = 10points 
      mytrade.PositionOpen(_Symbol,ORDER_TYPE_BUY,Lots,
                           now_ask,SL,TP,"Test Buy");
      // a trade operation has just been carried out
      return_code=mytrade.ResultRetcode();
      // get the result code
      if(return_code==10009 || return_code==10008) //Request is completed or order placed
        {
         enter_price=mytrade.ResultPrice();
         Alert("A Buy order has been successfully placed with Ticket#:",mytrade.ResultDeal(),"!! enter: ",enter_price);
        }
      else
        {
         Alert("The Buy order request could not be completed -error:",GetLastError());
         ResetLastError();
         return;
        }
     }
/*
    2. Check for a Short/Sell Setup : MA-8 decreasing downwards, 
    previous price close below it, ADX > 22, -DI > +DI
*/
//--- Declare bool type variables to hold our Sell Conditions
   bool Sell_Condition_1=(now_bid<shortTrigger_price) && !long_only;  // MA-8 decreasing downwards
   bool Sell_Condition_2=true;//(now_time.day_of_week!=1) && (now_time.day_of_week!=0); 

//--- Putting all together
   if(Sell_Condition_1 && Sell_Condition_2 && Entry_Condition_1 && Entry_Condition_2)
     {
      // any opened Sell position?
      if(Sell_opened)
        {
         //Alert("We already have a Sell position!!!");
         if(we)
           {
            mytrade.PositionClose(_Symbol,10.0);
            // a trade operation has just been carried out
            return_code=mytrade.ResultRetcode();
            // get the result code
            if(return_code==10009 || return_code==10008) //Request is completed or order placed
              {
               Alert("A CLOSE order on short position has been successfully placed with Ticket#:",mytrade.ResultDeal(),"!!closing price is: ",mytrade.ResultPrice(),"WE",we);
               this_bar_traded=true;
              }
            else
              {
               Alert("The Buy order request could not be completed -error:",GetLastError());
               ResetLastError();
               return;
              }
           }
         return;    // Don't open a new Sell Position
        }
      Alert("goin short day ",now_time.day_of_week," hour ",now_time.hour);
      SL=now_bid+STP*_Point; //remember 1pip = 10points 
      mytrade.PositionOpen(_Symbol,ORDER_TYPE_SELL,Lots,
                           now_bid,SL,TP,"Test Sell");
      // a trade operation has just been carried out
      return_code=mytrade.ResultRetcode();
      // get the result code
      if(return_code==10009 || return_code==10008) //Request is completed or order placed
        {
         enter_price=mytrade.ResultPrice();
         Alert("A Sell order has been successfully placed with Ticket#:",mytrade.ResultDeal(),"!! enter: ",enter_price);
        }
      else
        {
         Alert("The Sell order request could not be completed -error:",GetLastError());
         ResetLastError();
         return;
        }

     }

//here whatever position is open close at the end of the bar
   if(Sell_opened || Buy_opened)
     {
      //if(now_time.day_of_week==5) Alert("EOC BUY/SELL OPENed day ",now_time.day_of_week," hour ",now_time.hour);
      if(now_time.day_of_week==5 && now_time.hour==23)
        {
         Alert("FRIDAY H22");
         mytrade.PositionClose(_Symbol,10.0);
         // a trade operation has just been carried out
         return_code=mytrade.ResultRetcode();
         // get the result code
         if(return_code==10009 || return_code==10008) //Request is completed or order placed
           {
            Alert("A CLOSE order on FRIDAY has been successfully placed with Ticket#:",mytrade.ResultDeal(),"!!closing price is: ",mytrade.ResultPrice());
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError());
            ResetLastError();
            return;
           }
        }
     }
   return;
  }
//+------------------------------------------------------------------+

 basically the if(we) PositionClose...is never called it seems it never gets a tick on friday at 23:00 or later...

 
michelino:

hello guys,

I'm trying a very simple EA that should close position at the end of the week . it enters long when the price is above the last high and exit on friday at 23 or for a stoploss triggered. same thing for short position.

during backtesting it enters and triggers stoplosses but does not close on friday night!!

it's called on every tick and works on weekly bars data.

it's the very first advisor I write, i started by modifing my_first_EA.

I hope someone exeprienced could see at glance my mistake.

the code is below

 basically the if(we) PositionClose...is never called it seems it never gets a tick on friday at 23:00 or later...

If trading closes at 23:00  ( going by your Broker's Server time ) then the last tick before the weekend will be before 23:00 on Friday night . . .  what time (Broker Server time) does your Broker stop trading on Friday night ?
 
RaptorUK:
If trading closes at 23:00  ( going by your Broker's Server time ) then the last tick before the weekend will be before 23:00 on Friday night . . .  what time (Broker Server time) does your Broker stop trading on Friday night ?
changed to 22:00 now it works. thanks a lot
 

datetime  TimeTradeServer();

Returns the calculated current time of the trade server.

Unlike TimeCurrent(), the calculation of the time value is performed in the client terminal and depends on the time settings on your computer.

There are 2 variants of the function. 

https://www.mql5.com/en/docs/dateandtime/timetradeserver

Documentation on MQL5: Date and Time / TimeTradeServer
Documentation on MQL5: Date and Time / TimeTradeServer
  • www.mql5.com
Date and Time / TimeTradeServer - Documentation on MQL5
 

my broker fri close one hour earlier

please note that some holidays ends earlier too 

 
michelino:

hello guys,

I'm trying a very simple EA that should close position at the end of the week . it enters long when the price is above the last high and exit on friday at 23 or for a stoploss triggered. same thing for short position.

during backtesting it enters and triggers stoplosses but does not close on friday night!!

it's called on every tick and works on weekly bars data.

it's the very first advisor I write, i started by modifing my_first_EA.

I hope someone exeprienced could see at glance my mistake.

the code is below

 basically the if(we) PositionClose...is never called it seems it never gets a tick on friday at 23:00 or later...

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(chose_stop_end_of_week)

if(Gmt_time.hour>=hour_end_week && Gmt_time.day_of_week>=end_week)

{

return true;

}

return false;

}


result:

before:

after:


Reason: