Download MetaTrader 5

Export closed orders in MT4

To add comments, please log in or register
ralph659
17
ralph659  

Hello,

I notice that it's possible to export closed positions (both open and close on 1 row) to CSV or excel in MT4.

However is it also possible to just export all closed orders (so 1 buy/sell order per row) to CSV or excel in MT4?

Thanks in advance!

Kevin

ralph659
17
ralph659  
Nobody?
JC
1514
JC  
ralph659:
Nobody?

Oh, okay then. Try this script:

#property strict
#property show_inputs

enum FieldSeparators {
   fsComma = 0,         // Comma
   fsSemiColon = 1,     // Semi-colon
   fsTab = 2            // Tab
};

enum VolumeModes {
   vmLots = 0,          // Lots
   vmContracts = 1      // Contracts/notional
};

input string            FileName = "AccountHistoryDeals.csv"; // File name (in MQL4\Files)
input FieldSeparators   Separator = fsComma; // Field separator
input VolumeModes       VolMode = vmLots; // Write volume as...


void OnStart()
{
   // Open file
   int f = FileOpen(FileName, FILE_TXT | FILE_WRITE);
   if (f == INVALID_HANDLE) {
      Alert("Unable to open the file ", FileName);
      return;
   }
   
   // Work out separator
   string strSeparator = ",";
   switch (Separator) {
      case fsSemiColon:
         strSeparator = ";"; break;
      case fsTab:
         strSeparator = "\t"; break;
   }
         
   // Write the header
   string strHeaders = "ticket~action~direction~symbol~lots~time~price~comment~magic-number~s/l~t/p~profit~swap~commission~net-profit\r\n";
   StringReplace(strHeaders, "~", strSeparator);
   FileWriteString(f, strHeaders);
   
   // Scan history list (ignoring credit movements and cancelled pending orders)
   string strLine;
   for (int i = 0; i < OrdersHistoryTotal(); i++) {
      if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
         if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
            // Write opening deal, with blanks for things only known definitively when closed
            strLine = "";
            StringAdd(strLine, IntegerToString(OrderTicket()));
            StringAdd(strLine, strSeparator + "Open");
            StringAdd(strLine, strSeparator + (OrderType() == OP_BUY ? "Buy" : "Sell"));
            StringAdd(strLine, strSeparator + SafeString(OrderSymbol(), strSeparator));
            StringAdd(strLine, strSeparator + DoubleToString(GetVolume(OrderSymbol(), OrderLots()), 6));
            StringAdd(strLine, strSeparator + SafeString(TimeToString(OrderOpenTime(), TIME_DATE | TIME_SECONDS), strSeparator));
            StringAdd(strLine, strSeparator + DoubleToString(OrderOpenPrice(), 6));
            StringAdd(strLine, strSeparator + SafeString(OrderComment(), strSeparator));
            StringAdd(strLine, strSeparator + IntegerToString(OrderMagicNumber()));
            StringAdd(strLine, strSeparator); // s/l
            StringAdd(strLine, strSeparator); // t/p
            StringAdd(strLine, strSeparator); // profit
            StringAdd(strLine, strSeparator); // swap
            StringAdd(strLine, strSeparator); // commission
            StringAdd(strLine, strSeparator); // net profit
            StringAdd(strLine, "\r\n");
            FileWriteString(f, strLine);

            // Write closing deal
            strLine = "";
            StringAdd(strLine, IntegerToString(OrderTicket()));
            StringAdd(strLine, strSeparator + "Close");
            StringAdd(strLine, strSeparator + (OrderType() == OP_BUY ? "Sell" : "Buy"));
            StringAdd(strLine, strSeparator + SafeString(OrderSymbol(), strSeparator));
            StringAdd(strLine, strSeparator + DoubleToString(GetVolume(OrderSymbol(), OrderLots()), 6));
            StringAdd(strLine, strSeparator + SafeString(TimeToString(OrderCloseTime(), TIME_DATE | TIME_SECONDS), strSeparator));
            StringAdd(strLine, strSeparator + DoubleToString(OrderClosePrice(), 6));
            StringAdd(strLine, strSeparator + SafeString(OrderComment(), strSeparator));
            StringAdd(strLine, strSeparator + IntegerToString(OrderMagicNumber()));
            StringAdd(strLine, strSeparator + DoubleToString(OrderStopLoss(), 6));
            StringAdd(strLine, strSeparator + DoubleToString(OrderTakeProfit(), 6));
            StringAdd(strLine, strSeparator + DoubleToString(OrderProfit(), 2));
            StringAdd(strLine, strSeparator + DoubleToString(OrderSwap(), 2));
            StringAdd(strLine, strSeparator + DoubleToString(OrderCommission(), 2));
            StringAdd(strLine, strSeparator + DoubleToString(OrderProfit() + OrderSwap() + OrderCommission(), 2));
            StringAdd(strLine, "\r\n");
            FileWriteString(f, strLine);
         } else {
            // Ignore credit movements and cancelled pending orders
         }
      } else {
         // WTF?
      }
   }
   
   FileClose(f);
}

string SafeString(string X, string strSeparator)
{
   StringReplace(X, strSeparator, "");
   return X;
}

double GetVolume(string strSym, double lots)
{
   if (VolMode == vmLots) {
      return lots;
   } else {
      return lots * MarketInfo(strSym, MODE_LOTSIZE);
   }
}
Mladen Rakic
61768
Mladen Rakic  
//------------------------------------------------------------------
//
//------------------------------------------------------------------
#property show_inputs
#property strict

input string FileToSaveTo = "AccountHistory"; // File name to use to save the history data

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void OnStart()
{

   int handle = FileOpen(FileToSaveTo+".csv",FILE_CSV|FILE_WRITE);
   if (handle!=INVALID_HANDLE) 
   {
      int saved=0;   
      for(int i=OrdersHistoryTotal()-1; i>=0; i--)
      {
         if (!OrderSelect(i, SELECT_BY_POS,MODE_HISTORY)) continue;
         int type = OrderType();
            switch(type)
            {
               case OP_BUY  :
               case OP_SELL :
                        #define _dts(_arg) TimeToString(_arg,TIME_DATE|TIME_MINUTES)
                        #define _prs(_arg) DoubleToString(_arg,(int)MarketInfo(OrderSymbol(),MODE_DIGITS))
                        #define _lts(_arg) DoubleToString(_arg,2)
                        #define _del ";"
                        saved++;
                        FileWrite(handle,(string)OrderTicket()       +_del+
                                         _dts(OrderOpenTime())       +_del+
                                         (type==OP_SELL?"Sell":"Buy")+_del+
                                         _lts(OrderLots())           +_del+
                                         OrderSymbol()               +_del+
                                         _prs(OrderOpenPrice())      +_del+
                                         _prs(OrderStopLoss())       +_del+
                                         _prs(OrderTakeProfit())     +_del+
                                         _dts(OrderCloseTime())      +_del+
                                         _prs(OrderClosePrice())     +_del+
                                         _prs(OrderCommission())     +_del+
                                         _prs(OrderSwap())           +_del+
                                         _prs(OrderProfit())         +_del+
                                         OrderComment());
            }
      }         
      FileClose(handle); Comment((string)saved+" records saved to "+FileToSaveTo+".csv file");
   }
   return;
}
JC
1514
JC  
Mladen Rakic:
I think the OP wants deals, not tickets.
Mladen Rakic
61768
Mladen Rakic  
JC:
I think the OP wants deals, not tickets.

MT4 - please read the first post

Btw: tickets in your code too

JC
1514
JC  
Mladen Rakic:

MT4 - please read the first post

Btw: tickets in your code too

The OP specifically does not want "both open and close on 1 row". By "order", s/he appears to mean what MT5 calls a deal: in other words, the separate open and close of each ticket in MT4.

Mladen Rakic
61768
Mladen Rakic  
JC:

The OP specifically does not want "both open and close on 1 row". By "order", s/he appears to mean what MT5 calls a deal: in other words, the separate open and close of each ticket in MT4.

I sincerely thank you for your kind attention of interpreting what the OP wants

And I most sincerely thank you for your teaching intentions. All the best.

JC
1514
JC  
Mladen Rakic:

I sincerely thank you for your kind attention of interpreting what the OP wants

And I most sincerely thank you for your teaching intentions. All the best.

And thank you for telling me that I needed to read the first post!
ralph659
17
ralph659  

Thanks guys,


The reason I was asking if it was possible to export a list of orders (so not both buy and sell on same row but 1 row per buy/sell) is because I would like to do the order management (creating open and closed positions from those orders) myself based on different order management methods (FIFO, LIFO,...).

Do I understand it correct then that this in only possible by using a script?


Thanks,

Kevin

To add comments, please log in or register