I got stuck on getting correct datetime data from history. Please help.

 
Hi everyone.

During coding of my 1st EA, I always found a solution for every issue that appeared and everything surprisingly works well, so far.... till yesterday.
I intend to code another of the functions - specifically: Re-entering a trade, if that trade ends on BE or in loss, but only if the trade has been entered today (not yesterday or earlier). That's why I'm trying to get the information about when the trade was executed/sent to a broker.

Here is the appropriate code part:
//--- Trend determination
void  OnTradeTransaction( 
   const MqlTradeTransaction&    trans,      
   const MqlTradeRequest&        request,   
   const MqlTradeResult&         result      
   )
   {
    if(trans.type == TRADE_TRANSACTION_DEAL_ADD)                                       
      {
       CDealInfo deal;
       deal.Ticket(trans.deal);
       HistorySelect(TimeCurrent() - (PeriodSeconds(PERIOD_W1) * 2),TimeCurrent() + 10);    
       if(deal.Magic() == EA_Magic && deal.Symbol() == _Symbol)                       
         {
          if(deal.Entry() == DEAL_ENTRY_IN)                                           
            {
             if(deal.DealType() == DEAL_TYPE_BUY)                                      
               {
                Bull_Trend = true;                                                     
                Bear_Trend = false;
                if(MQL5InfoInteger(MQL5_DEBUGGING)) 
                  {
                   Print("The Bull trend has been set.");
                  }
               }
              else if (deal.DealType() == DEAL_TYPE_SELL)                              
               {
                Bull_Trend = false;                                                    
                Bear_Trend = true;
                if(MQL5InfoInteger(MQL5_DEBUGGING)) 
                  {
                   Print("The Bear trend has been set.");
                  }               
               }
            }
//--- Re-entry            
    else if(deal.Entry() == DEAL_ENTRY_OUT)                                            
           {
            double lastProfit = HistoryDealGetDouble(deal.Ticket() , DEAL_PROFIT);     
            Print("Last Trade Profit/Loss - ticket #",(deal.Ticket()), ": $", DoubleToString(lastProfit)); 
            if(ReEntry && (LossPips >= lastProfit))
              {
               if(HistoryOrderSelect(trans.deal))
                 {
                  datetime TimeNow = TimeCurrent();
                  datetime OpenTime = HistoryOrderGetInteger(deal.Ticket(),ORDER_TIME_SETUP);
                  MqlDateTime STimeNow, SOpenTime;
                  
                  TimeToStruct(TimeNow,STimeNow);
                  TimeToStruct(OpenTime,SOpenTime);
                  Print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX " , "Day now: ", (STimeNow.day_of_year), " /Time now: ",(TimeNow), " // Open day: ", (SOpenTime.day_of_year)," / Open Time: ",(OpenTime), " // Ticket: ",(deal.Ticket()));
                 }
              }
           }           
         }      
      }      
   }


The trend determination section works just fine for me, I intended to share its "History Select" part with the newly created Re-entry section. Originally the range of the downloaded history cache, in the 12th line, was only 1 minute. For this purpouse I modified it to 14 days. And if anybody would ask- the bull/bear variables are on global scope.

But what it do (but it shouldn't) is: When firstly conditions for this function are met, it looks it works good, but every next such action couse that the "OpenTime" of the just closed trade isn't correct but is replaced by the same data as the "TimeNow" of the previous action, although in reality the pending order was sent and executed the same day as closed (conditions are met).

The picture in the attachment tells more. Look for the XXXX-higlighted lines.

I believe an appropriate trade from the history in the code is selected (or am I wrong?), but anyway, I've tried to add the "History Select" function - the result was the same.
Another thing that I guess is that a reason of this issue will be a trifle but I can't see it. So kindly please for any advice if you see it and know a solution.

The Fundamentals of Testing in MetaTrader 5
The Fundamentals of Testing in MetaTrader 5
  • www.mql5.com
What are the differences between the three modes of testing in MetaTrader 5, and what should be particularly looked for? How does the testing of an EA, trading simultaneously on multiple instruments, take place? When and how are the indicator values calculated during testing, and how are the events handled? How to synchronize the bars from different instruments during testing in an "open prices only" mode? This article aims to provide answers to these and many other questions.
Files:
 

I would lie, if I would say that I don't feel stupid to twrite only for myself on a public forum, but I don't want to let the thread open as I don't know how to delete it.

I was right - it was a trifle (but took me over 20hrs to solve it:). Strange that nobody knew it / nobody willing to help. So maybe this post isn't useless in the end.
The point was: there isn't a ticket # as a ticket #. Originally is used identifier POSITION_TICKET, which (simply said) is different on opening possition and different on closing possition. So as a solution is used identifier POSITION_IDENTIFIER, which (simply said) shouldn't change during the whole trade life cycle. It should survive any changes and modifications in the position and even reversing a positio. But after reading these identifiers descriptions on MQL5 Reference page I don't know anymore what is different between a possiton, a deal, an order or a trade.

Updated code which looks it works (check the picture below the code):

//--- Re-entry            
    else if(deal.Entry() == DEAL_ENTRY_OUT)                                           
           {
            double lastProfit = HistoryDealGetDouble(deal.Ticket() , DEAL_PROFIT);     
            Print("Last Trade Profit/Loss of trade #",(deal.Ticket()), ": $", DoubleToString(lastProfit)); 
            if(ReEntry && (LossPips >= lastProfit))
              {   
               datetime timeNow = TimeCurrent();  
               long oldestTicket = CHAR_MAX; 
               long ordTicket = CHAR_MAX;                                              
               long positionID = HistoryDealGetInteger(deal.Ticket(),DEAL_POSITION_ID);          // Find the Positon ID, based on the deal ticket,
               HistorySelectByPosition(positionID);                                              // download an appropriate history of that ID.
               
               for(int i = HistoryOrdersTotal() - 1; i >= 0 && !IsStopped(); i--)                // Browsing thru loaded history records.
                   ordTicket = HistoryOrderGetTicket(i);
                   if(HistoryOrderSelect(ordTicket))
                     { 
                      oldestTicket = MathMin(ordTicket,oldestTicket);                            // Get a ticket of the first order of this position
                     }  

               datetime openTime = HistoryOrderGetInteger(oldestTicket,ORDER_TIME_SETUP);        // and get the time of its placement at the market
               
               
               MqlDateTime StimeNow, SopenTime;
               
               TimeToStruct(timeNow,StimeNow);
               TimeToStruct(openTime,SopenTime);
               Print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX " , "Day now: ", StimeNow.day_of_year, " /Time now: ",timeNow, " // Open day: ",
                    SopenTime.day_of_year," / Open Time: ",openTime, " // Ticket#: ",deal.Ticket(), " / Position ID#: ", positionID);
              }
           }       
         }      
      }      
   }



Thanks to everybody participating for your help and have a niceone!

Reply: No worries, that's why we're here.

Reply2: Anytime, bro B-/

Files:
Issue_solved.png  182 kb
 

edit: Just noticed you were already using HistorySelect

It's not written very clearly in the documentation, but from what I gather... positions are positions which are active or just closed in other words "current", deals are historical positions, and orders are the pending orders and not the instantly executed positions.

Reason: