Download MetaTrader 5

Closing opened order after a definite number of seconds or minutes

To add comments, please log in or register
mat
52
mat  

Hi,

I'd like to create a simple script which can close an order already opened for some time (i.e 1200 seconds / 20 minutes), not depending on the fact that the trade is yet profitable.

Best would be just before the end of a time period, just before the new one starts.

Should I look for a solution with the Ibarshift function and the given mt4 close script or is there any easier solution ?

thanks in advance for your advice :)

matttt

mat
52
mat  

Maybe that can also be used to launch the closing command ? In that case can i use that in a simple script or must i include it in an EA ?

sourced from here in the site : https://www.mql5.com/en/code/9337 from WHRoeder's post

start(){
  static datetime Time.update;			// No open order,
  if (CurTime() < Time.update)	return(0);	// Can't trade yet.
//...
  if (!Compute()) {		                // Not good enough
    Time.update = CurTime() + X*60;	        // continue waiting X minutes.
  //Time.update = Time[0] + Period()*60;	// continue waiting for next bar.
    //...

mat
52
mat  

this article brings some ideas to answer my question ;

https://www.mql5.com/en/code/8491 from cOd3

but it is mixed in other processes.

cameo
476
cameo  

Hi, 

A script runs one time when you launch it. So if you need to close an order after a definite number of seconds elapsed, you'd have to wait for that moment to launch the script. Inconvenient IMO. It's possible to use a continuous loop with a Sleep(), but that's not a good idea either. 

An Expert is more suited for this job. Attach it once, and it will monitor whether the current time equals or exceeds any order's OrderOpenTime() + 1200 seconds. If it finds one a close attempt will be sent. 

mat
52
mat  
cameofx:

Hi,

A script runs one time when you launch it. So if you need to close an order after a definite number of seconds elapsed, you'd have to wait for that moment to launch the script. Inconvenient IMO. It's possible to use a continuous loop with a Sleep(), but that's not a good idea either.

An Expert is more suited for this job. Attach it once, and it will monitor whether the current time equals or exceeds any order's OrderOpenTime() + 1200 seconds. If it finds one a close attempt will be sent.


Hi Cameofx,

You're obviously right. I had the same thinking after posting the previous posts, but it was already late at night as I'm in Europe.

Well, thanks for the tip, I'll look for the solution and post it when working. Cheers.

mat
52
mat  

Back to the topic

I have "coded" the following, but it miss something to call the order which needs to be closed, I guess.

Something with the order close function would need to be precised, but I am not sure. So at the time being I have :

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
  

//----
   return(0);
  }
//============================================================================
//============================================================================
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }

//====

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int start()
   {
   double OT;
   double CT;
   int cnt, ticket, total;
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
   OT=OrderOpenTime();
   CT=Time(); 
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
   total=OrdersTotal();
   if(total<0.1)
      {
      Print("No order opened yet,  Marging = ", AccountFreeMargin());
      // no opened orders identified
   else 
      {
      if Time()>OrderOpenTime+15 
         {ticket=OrderClose();
         if(ticket>0)
            {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("Order Closed ");
            }
            else Print("Error closing order : ",GetLastError());
            return(0);
         }
      return(0);
      }
}

Any help welcome, but I'll continue to look for it myself as well.

Yet it gives some error when compiling.

cheers.

qjol
3245
qjol  

wrong

1) OT=OrderOpenTime();
order most be selected first

2) CT=Time();
You probably mean

CT=OrderCloseTime() ;

3) if Time()>OrderOpenTime()+15

what 15, 15 seconds?

4) if(total<0.1)
tha var total u assigned for an int, how u want to compare decimal

5) if Time()>OrderOpenTime+15
if u mean the current time

it's if (TimeCurrent() > OrderOpenTime+15

6) if comes with ()

example:

if (TimeCurrent() > OrderOpenTime+15)

wrong

if (TimeCurrent() > OrderOpenTime+15)

right

7) ticket=OrderClose();
is no such thing OrderClose();
c here

& for the end

I would highly recommend you to read it first

mat
52
mat  

Thanks Qjol :)

1) Select order first : I'll look for that, I had guess this was not correct

2) CT : I meant current time so, your point 5 refers to that as well

3)15 seconds : I mean 15minutes

4) if(total<0.1) - tha var total u assigned for an int, how u want to compare decimal ... Good ! I had never understood that (now you can see my starting point :)

5) & 6) if Time()>OrderOpenTime+15 : I mean current time so : if (TimeCurrent() > OrderOpenTime+15) ... with the time unit of course (I'll check how this work)

7) ticket=OrderClose();

is no such thing OrderClose(); : I'll go and check

& for the endI would highly recommend you to read it first : I have read part of it but am not a coder and I am indeed a french speaking person so not so easy. I have nothing to do with coding and I'm only trying to make my trading easier. I have tried to automate my strategy in the past and managed to create simple eas (i.e calling momemtum + rsi + cci etc) but my lack of knowledge prevents me from achieving a satisfying result comparable to my manual trading strategy..... so I'm trying, that's not so bad :)

Cheers and thanks for the tips.

whroeder1
17124
whroeder1  
int maxDuration = 15 * 60; // 15 minutes
for(int pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
    OrderSelect(pos, SELECT_BY_POS)            // Only my orders w/
&&  OrderMagicNumber() == Magic.Number         // my magic number
&&  OrderSymbol()      == Symbol() ){               // and period and symbol
    int duration = TimeCurrent() - OrderOpenTime();
    if (duration >= maxDuration)
         OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(),
                     Slippage.Pips*pips2points);
}
mat
52
mat  
Hi WHRoeder,

Thanks a lot for your input. It made it all !

To be honest, I was trying to catch up with the previous inputs but I was drawn into the code... causing more harm than benefit.

I confirm it works with your code added as follow. I'll post the full updated code for others to benefit from it in a stand alone post below this one, with some explanation of what it does and does not do. I have just taken out the magic number because at the moment I want the code to apply to ALL opened orders.

Again, thx. Great forum.
mat
52
mat  

Hi All,

For those who need a simple "TimeKeeper" EA, here is a code built with the support of the MQL community.

It limits the duration of a trade to the set number of minutes, here set at 15min.

Then, it close the order with the set parameters, here slippage set at 3 and price set at market price.

Please note that as it is, it applies to all orders opened on your plateform. Symbol on which it applies can be change easily.


///+---------------------------------------------------------------------+
//|                                                       TIMEKEEPER.mq4 |
//|                                                                      |
///+---------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
//----
   return(0);
  }
//====================================================================
//====================================================================
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
//----
   return(0);
  }
//====
//+------------------------------------------------------------------+
//| |EXPERT
//+------------------------------------------------------------------+
int start()
   {
int maxDuration = 15 * 60; 
for(int pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
    OrderSelect(pos, SELECT_BY_POS)            // Only my orders w/
&&  OrderSymbol()== "EURUSD"){               // and period and symbol
    int duration = TimeCurrent() - OrderOpenTime();
    if (duration >= maxDuration)
         OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(),
                     3*Point);
}      return(0);
      }

//+------------------------------------------------------------------+
///+---------------------------------------------------------------------+
//|                                                       TIMEKEEPER.mq4 |
//|                                            Thanks to the MQL Forum ! |
///+---------------------------------------------------------------------+
12
To add comments, please log in or register