close all trades?

 

Hello,


I am trying to close all open trades after it as been open for 48 hours. For some reason I cannot seem to code it correctly. Where should I put the orderclose function and how should it be worded? Any bit of advice would help a lot. I'm starting to get better at this coding thing.


Thanks!

 

James please place the attached script in sub-directory "\experts\scripts\", close down and re-start MetaTrader, click on "Navigator", click on "Scripts", click on "_CloseAllMarketAndPendingOrders" (based on the following)

//+------------------------------------------------------------------+
//|                              _CloseAllMarketAndPendingOrders.mq4 |
//|                                         Copyright © 2010, sxTed. |
//|                                        https://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, sxTed."
#property link      "https://www.metaquotes.net"
#include <stdlib.mqh>

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
void start() {
  int  iOrders=OrdersTotal()-1, i, iError;
  bool ok;
  
  for(i=iOrders; i>=0; i--) {
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) {
      if(OrderType()==OP_BUY)       ok=OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),5);
      else if(OrderType()==OP_SELL) ok=OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),5);
      else if(OrderType()>OP_SELL)  ok=OrderDelete(OrderTicket());
      if(!ok) {
        iError=GetLastError();
        Print("Order:",OrderTicket(),"  Error:",iError," ",ErrorDescription(iError));
      } 
    }
    else Print("OrderSelect error: ",GetLastError());
  }
}
//+------------------------------------------------------------------+
 

Hey Ted,


Thank you very much for your quick response. However, I was looking for something to insert into my code. For instance, if I put my EA on a an hourly time frame, I would like to the EA to close all open trades in 48 hours if it did not reach its exit trade criteria by then. Maybe a OrderClose function after the OrderSend criteria? That way it will do it automatically and I would be able to backtest it.


Thanks again for all your help

 

When you loop through your order pool, get OrderOpenTime() and then check how long it's been open to close those open longer than desired amount. You could check the time difference or just iBarShift() back to the open time and if its >48 bars (on hourly chart) close the order.

hth

V

 

I think I got it. This is the part that sends the order in my code:


if(OrdersTotal()>=5) return;
int ticket = OrderSend(Symbol(),type,lots,price,Slippage,sl,tp,ExpertName,MagicNumber,0,col);
if(ticket>=0)


Does this mean that I add in the ibarshift() at the end like this:


if(OrdersTotal()>=5) return;
int ticket = OrderSend(Symbol(),type,lots,price,Slippage,sl,tp,ExpertName,MagicNumber,0,col);
if(ticket>=0)

iBarShift(Symbol(), PERIOD_H4, ???);


Also, I'm not too sure what I'm supposed to put in for the time portion (the part that has the ???). In addition, I'm not too sure how to combine the iBarShift with the OrderClose function.


Thanks

 

Hi James please find code as Viffer suggested

//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
void start() {
  for(int i=OrdersTotal()-1; i>=0; i--) {
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) {
      if(CloseAfter(PERIOD_H4) == false) return;
    }
    else Print("OrderSelect error: ",GetLastError());
  }
}

//+------------------------------------------------------------------+
//| Function..: CloseAfter                                           |
//| Parameters: iPeriod - Period in minutes that an order may remain |
//|                       open.                                      |
//| Purpose...: Place an expiration time on a market order.          |
//| Returns...: true -  order has expired and closed, or the expiry  |
//|                     time for the order has not been reached,     |
//|             false - order could not be closed, the error number  |
//|                     can be obtained using GetLastError().        |
//| Notes.....: The order must have been selected using OrderSelect()|  
//| Sample....: void start() {                                       |
//|               for(int i=OrdersTotal()-1; i>=0; i--) {            |
//|                 if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) {   |
//|                   if(CloseAfter(PERIOD_H4) == false) return;     |
//|                 }                                                |
//|                 else Print("OrderSelect error: ",GetLastError());|
//|               }                                                  |
//|             }                                                    |
//+------------------------------------------------------------------+
bool CloseAfter(int iPeriod) {
  if((OrderType() == OP_BUY) && (TimeCurrent() > OrderOpenTime()+iPeriod*60)) {
    return(OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),5));
  }
  else if((OrderType() == OP_SELL) && (TimeCurrent() > OrderOpenTime()+iPeriod*60)) {
    return(OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),5));
  }
  return(true); 
}
 

Thanks again for the quick responses.


I'm still having trouble with this. After spending the last hour trying to incorporate some of these methods, I finally got it to compile; but it still doesn't do what it's supposed to do.


I still can't figure out the iBarShift coding, as well as where to put it. I'm thinking it should go below the rest of my order-closing criteria; but the both methods that was suggested wasn't working for me. I had tried and put iBarShift and the CloseAfter suggestion below my code below. Any ideas on what I did wrong?


bool CloseCurrentOrder(double lots = -1.0)
{
        int type = OrderType();
        double price;
        if     (type==OP_BUY)  price = Bid;
        else if(type==OP_SELL) price = Ask;
        else return(false);

        if(lots > OrderLots() || lots==-1.0)
                lots = OrderLots();
        else
                lots = NormalizeLots(lots);

   return(OrderClose(OrderTicket(), lots, price, 0));
}
 
James please try the following: in my script replace "PERIOD_H4" with PERIOD_M1*3" and recompile, open a market order in your demo account, wait 3 minutes and call up the script.
 
sxTed:
James please try the following: in my script replace "PERIOD_H4" with PERIOD_M1*3" and recompile, open a market order in your demo account, wait 3 minutes and call up the script.

Hey sxTed,


Your script works fine. However, I needed to attach it to my EA so that I can backtest it and see how successful it was during the past. Isn't the script that you provided only good for live/demo trading? If it is also good for backtesting, I am not sure how to add it to an original EA.


Thanks!

 
//+------------------------------------------------------------------+
//| My Exepert on top and Function Call Below                                  |
//+------------------------------------------------------------------+
int start(){
//    if(Close_All_Condition){
         Close_All();
      //}
/* The rest of your EA in this Box. Note you could place the 
Close_All function call anywhere you deem appropriate in the 
Expert Advisor.

Function and Function Calls are explained in detail in Book
Link: https://book.mql4.com/basics/functions
*/
return(0);} //--End of EA.



//+------------------------------------------------------------------+
//| Function to Close_All Orders Below                                    |
//+------------------------------------------------------------------+
void Close_All() {
  for(int i=OrdersTotal()-1; i>=0; i--) {
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) {
      if(CloseAfter(PERIOD_H4) == false) return;
    }
    else Print("OrderSelect error: ",GetLastError());
  }
}

//+------------------------------------------------------------------+
//| Function..: CloseAfter                                           |
//| Parameters: iPeriod - Period in minutes that an order may remain |
//|                       open.                                      |
//| Purpose...: Place an expiration time on a market order.          |
//| Returns...: true -  order has expired and closed, or the expiry  |
//|                     time for the order has not been reached,     |
//|             false - order could not be closed, the error number  |
//|                     can be obtained using GetLastError().        |
//| Notes.....: The order must have been selected using OrderSelect()|  
//| Sample....: void start() {                                       |
//|               for(int i=OrdersTotal()-1; i>=0; i--) {            |
//|                 if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) {   |
//|                   if(CloseAfter(PERIOD_H4) == false) return;     |
//|                 }                                                |
//|                 else Print("OrderSelect error: ",GetLastError());|
//|               }                                                  |
//|             }                                                    |
//+------------------------------------------------------------------+
bool CloseAfter(int iPeriod) {
  if((OrderType() == OP_BUY) && (TimeCurrent() > OrderOpenTime()+iPeriod*60)) {
    return(OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),5));
  }
  else if((OrderType() == OP_SELL) && (TimeCurrent() > OrderOpenTime()+iPeriod*60)) {
    return(OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),5));
  }
  return(true); 
}
 

Once again, thanks for all your help. I think I got most of it. I've read the link and tried to incorporate it into my EA. My biggest problem was placing the void-Close_All and the bool-CloseAfter inside the start function.


Once I realize to just put it at the end of my entire EA, I get two warnings:

Function "Close_All" is not referenced and will be removed from exp-file
Function "CloseAfter" is not referenced and will be removed from exp-file


I am assuming that means I have to put something in the "Start" function to call upon the Close_All and CloseAfter functions. Is that correct? I've tried a few different wordings to call upon it, but then it produces many more errors.


Any guidance would be very helpful.


Thanks!

Reason: