Help with OnTradeTransaction() function in closing deals

 
In the following MQL5 OnTradeTransaction() function allows me to retrieve 'deal' data and output it to a CSV file one deal at a time. (My EA simply works on the basis 

of opening market orders - no pending orders) This is outputting the data fine. 

void OnTradeTransaction(const MqlTradeTransaction &transaction,
                                         const MqlTradeRequest &request,
                                            const MqlTradeResult &result)
{
  ulong      dealID      =   transaction.deal;

  if(HistoryDealSelect(dealID)) 
  {
    // deal 'integer' properties 
    long              dealTicketID                  = HistoryDealGetInteger(dealID, DEAL_TICKET);
    long              dealOrderID                  = HistoryDealGetInteger(dealID, DEAL_ORDER);
    long              dealPositionID               = HistoryDealGetInteger(dealID, DEAL_POSITION_ID);

    string tradeData = (IntegerToString(dealTicketID) + "," + IntegerToString(dealOrderID) + "," + IntegerToString(dealPositionID)); 

    // Go to End of File
    FileSeek(gl_FileHandle, 0, SEEK_END);
    
    // Append details to the end of the previous line 
    FileWrite(gl_FileHandle, tradeData);
  }  
}

The issue I would like help with, using the example above is there a way I could retrieve the CLOSING dealTicketIDs and amend it to my CSV file ??!? (I know its tricky because the closing deals are not created until further down - the logic for my 'for loop' is ideally what i require assistance with ) 

Any help would be greatly appreciated 

Many thanks in advance 
 
Please don't post randomly in any section. Topic has been moved to the section: Expert Advisors and Automated Trading
 
Fernando Carreiro #:
Please don't post randomly in any section. Topic has been moved to the section: Expert Advisors and Automated Trading

Sorry Fernando

 
HermanMunster:
In the following MQL5 OnTradeTransaction() function allows me to retrieve 'deal' data and output it to a CSV file one deal at a time. (My EA simply works on the basis 

of opening market orders - no pending orders) This is outputting the data fine. 

The issue I would like help with, using the example above is there a way I could retrieve the CLOSING dealTicketIDs and amend it to my CSV file ??!? (I know its tricky because the closing deals are not created until further down - the logic for my 'for loop' is ideally what i require assistance with ) 

Any help would be greatly appreciated 

Many thanks in advance 

Something like this may work - give it a try

void OnTradeTransaction(const MqlTradeTransaction &transaction,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)

  {
   ulong dealID = 0;

   if(HistorySelectByPosition(request.position))
     {
      int dealsTotal = HistoryDealsTotal();

      for(int i=0; i<dealsTotal; i++)
        {
         dealID = HistoryDealGetTicket(i);

         //Parse deal records as needed
        }
     }

  }
 
R4tna C #:

Something like this may work - give it a try

Hey so sorry for responding so late (have been trying to get this thing to work). Thanks for the help R4tna C but unfortunately that did not work. 

My issue is that the 'closing' deal does not appear straight away but at a later time, hence I would like to update the row in my csv file with 

- the opening deal ticket, opening order ticket and the 'closing deal ticket'

However, whenever a trade transaction occurs i only get the information for the deal 'at that time' hence have to wait for its closing ticket and then add that to the row when it arrives. 

I have been trying to see if I create an array and send all the details to that and then output the array details to my csv file. 

If this is a good avenue to go down, or if anyone can help or point me in the right direction that would be extremely helpful. 

R4tna C
R4tna C
  • www.mql5.com
Trader's profile
 

try to get what you need on all funtions before when a new tick shows .

for example  :

put all code such as "update the row to your  csv file  " on Ontick() first line


Recently, I have also been studying those trade funtions , There are many hidden issues here .

In a simple way ,  Print all Positions in OnTradeTransaction() you will see It doesn't always print correctly because of the queuen .

//---

the documentation says:

When transactions are processed by the EA's OnTradeTransaction() handler, the terminal goes on handling the incoming trade transactions. Thus, the trading account status may change at the course of OnTradeTransaction() operation. For example, while an MQL5 program handles adding a new order, it can be executed, deleted from the list of open orders and moved to history. The program is notified of all these events.

//---

It means that the deal you want to process , may not have received its information yet .


Another thing ,  before handling the issue  ,  perhaps you should confirm  the  " ENUM_TRADE_TRANSACTION_TYPE   type;             // Trade transaction type "  first .

Because an deal will enter this OnTradexxxx() funtion at least 4 times or more .

 
HermanMunster #:

Hey so sorry for responding so late (have been trying to get this thing to work). Thanks for the help R4tna C but unfortunately that did not work. 

My issue is that the 'closing' deal does not appear straight away but at a later time, hence I would like to update the row in my csv file with 

- the opening deal ticket, opening order ticket and the 'closing deal ticket'

However, whenever a trade transaction occurs i only get the information for the deal 'at that time' hence have to wait for its closing ticket and then add that to the row when it arrives. 

I have been trying to see if I create an array and send all the details to that and then output the array details to my csv file. 

If this is a good avenue to go down, or if anyone can help or point me in the right direction that would be extremely helpful. 

I think it could work if you wait until you detect a closing deal (see ENUM_DEAL_ENTRY). The loop will thus process the the IN record and the OUT record so you can collect all data on closure. I do that in my code - it was fiddly to get right but it works for my requirement. 

In terms of an array, I do that also (for other reasons) - again it took some effort to get it right but for my need it was worth it.

Not sure if these approaches fit your scenario, but I believe you can make it work the way you want

Help with OnTradeTransaction() function in closing deals
Help with OnTradeTransaction() function in closing deals
  • 2023.05.16
  • www.mql5.com
In the following MQL5 OnTradeTransaction() function allows me to retrieve 'deal' data and output it to a CSV file one deal at a time...
 
R4tna C #:

I think it could work if you wait until you detect a closing deal (see ENUM_DEAL_ENTRY). The loop will thus process the the IN record and the OUT record so you can collect all data on closure. I do that in my code - it was fiddly to get right but it works for my requirement. 

In terms of an array, I do that also (for other reasons) - again it took some effort to get it right but for my need it was worth it.

Not sure if these approaches fit your scenario, but I believe you can make it work the way you want

On second thoughts, it may be enough to just check if the ticket is still live before executing - you will have to experiment


void OnTradeTransaction(const MqlTradeTransaction &transaction,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)

  {
   if(!PositionSelectByTicket(request.position)) //Do not process if ticket is still live
     {
      ulong dealID = 0;

      if(HistorySelectByPosition(request.position))
        {
         int dealsTotal = HistoryDealsTotal();

         for(int i=0; i<dealsTotal; i++)
           {
            dealID = HistoryDealGetTicket(i);

            //Parse deal records as needed
           }
        }

     }


  }
 

Hi R4tna C #

Thanks for the advice. I have resolved trying to get IN and OUT trades as shown below

void    OutputTrades()
{
  //--- set the start and end date to request the history of deals
  datetime  startDate       = (TimeCurrent() - (PeriodSeconds(PERIOD_W1) * 2));   // from 2 weeks ago
  datetime  endDate         = TimeCurrent();                                      // till the current moment
  ulong     dealOutTicket   = -1;
  ulong     dealInTicket    = -1;
  // create array to hold trades  
  struct_TradeDetails tradesArray[];

  // RETRIEVE: ALL orders & deals for the previous TWO weeks 
  if(HistorySelect(startDate, endDate))             
  { // RETRIEVE: ONLY deals for the previous TWO weeks
    int totalDealsLoop = HistoryDealsTotal();  
    // LOOP: if "dealOutTicket = HistoryDealGetTicket(i)" AND the deal is an 'OUT' trade
    for( int i = totalDealsLoop; i >= 0; i-- )       
    {      
      if((dealOutTicket = HistoryDealGetTicket(i)) > 0 && 
                          HistoryDealGetInteger(dealOutTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT) 
      { // RETRIEVE: GET DEAL 'OUT' DATA
        ulong   positionID    = HistoryDealGetInteger(dealOutTicket, DEAL_POSITION_ID);  
        ulong   closeDealID   = HistoryDealGetInteger(dealOutTicket, DEAL_TICKET); 
        string  symbolID      = HistoryDealGetString(dealOutTicket, DEAL_SYMBOL);
        
        // RETRIEVE: ONLY deals with the previous CLOSING position ID & is an 'IN' trade
        for( int j = totalDealsLoop; j >= 0; j-- )
        { 
          if( (dealInTicket = HistoryDealGetTicket(j) ) > 0 && 
              HistoryDealGetInteger(dealInTicket, DEAL_ENTRY) == DEAL_ENTRY_IN && 
              HistoryDealGetInteger(dealInTicket, DEAL_POSITION_ID) == positionID)
          { // RETRIEVE: GET DEAL 'IN' DATA
            ulong     openOrderID     = HistoryDealGetInteger(dealInTicket, DEAL_ORDER);
            ulong     openDealID      = HistoryDealGetInteger(dealInTicket, DEAL_TICKET);
            datetime  openDealTime    = (datetime)HistoryDealGetInteger(dealInTicket, DEAL_TIME);           
          }  
        }  
      } 
    }
  }
}