How to get posistions closed in profit?

Hello,

I’m trying to get the deals closed in profit within the previous 12 hours.

if (HistorySelect(TimeCurrent()-(12*60*60), TimeCurrent()))
{
   Print("Found ",HistoryDealsTotal()," deals.");
   for (int i = HistoryDealsTotal() - 1; i >= 0; i--)
   {
     ulong tk = HistoryDealGetTicket(i);
     Print("Checking deal at index: ",i," ",HistoryDealSelect(tk));
     if(HistoryDealGetInteger(tk, DEAL_REASON) == DEAL_REASON_TP)
     {
        Print(HistoryDealGetString(tk,DEAL_COMMENT));
     }
  }
} 

output

2019.05.23 10:07:20.653 Found 6 deals.
2019.05.23 10:07:20.653 Checking deal at index: 5 true
2019.05.23 10:07:20.653 [tp 1.11509]
2019.05.23 10:07:20.653 Checking deal at index: 4 false
2019.05.23 10:07:20.653 Checking deal at index: 3 false
2019.05.23 10:07:20.653 Checking deal at index: 2 false
2019.05.23 10:07:20.653 Checking deal at index: 1 false
2019.05.23 10:07:20.653 Checking deal at index: 0 false

As you can see from the output, only one deal is properly selected with HistoryDealSelect(tk) , and that’s because HistoryDealGetTicket(i) returns the proper ticket only the first time, returning 0 afterwards(I checked, but didn’t include that in the output).

Deals at indexes 3 and 1 should also output their TP. Any ideas?

Add it to the ouput with the error number and show the log please. (0 indicate an error so use GetLastError()to know which one).

if (HistorySelect(TimeCurrent()-(12*60*60), TimeCurrent()))
{
   Print("Found ",HistoryDealsTotal()," deals.");
   for (int i = HistoryDealsTotal() - 1; i >= 0; i--)
   {
     ulong tk = HistoryDealGetTicket(i);
     Print("Checking deal at index: ",i," ",HistoryDealSelect(tk));
     if(HistoryDealGetInteger(tk, DEAL_REASON) == DEAL_REASON_TP)
     {
        Print(HistoryDealGetString(tk,DEAL_COMMENT));
     }
  }
}

Oh, nice catch. I missed it.

Oh, I didn’t need to do HistoryDealSelect(tk)? But why though? Anyways, it works alright now, thanks!

Reason stated in here: " HistoryDealSelect() clears in a mql5-program the list of deals available for reference, and copies the single deal, if the execution of HistoryDealSelect() has been completed successfully. If you need to go through all deals selected by the HistorySelect()function, you should better use HistoryDealGetTicket()."

https://www.mql5.com/en/docs/trading/historydealselect

I see, that makes sense. Thanks!