vdemydiuk / mtapi

MetaTrader API (terminal bridge)
http://mtapi4.net/
MIT License
521 stars 281 forks source link

Closing Price of Trade/Order in MT5 #159

Open carlor12 opened 5 years ago

carlor12 commented 5 years ago

How do I pull the closing price of a trade when it is no longer open using its order reference?

KptKuck commented 5 years ago

How do I pull the closing price of a trade when it is no longer open using its order reference?

I can show you an example for mql5. You can then in your target language with the MT5API. greetings

MQL5

double LastDealsPrice(string _symbol, int back=3600)
{
   datetime limit=TimeCurrent();
   datetime start=limit-back;                   // 3600=seconds of 1 hour, 86400=seconds of 1 day

   if(!HistorySelect(start,limit))              // select history
      return(NULL);                             // no history available

   uint     idx, 
            idxMax=HistoryDealsTotal()-1;
   ulong    deal_ticket;
   string   deal_symbol;
   long     deal_entry;
   long     deal_reason;

   double   deal_price;

   for(idx=idxMax; idx>0; idx--)
      {
         deal_ticket = HistoryDealGetTicket(idx);                       // get ticket
         deal_symbol = HistoryDealGetString(deal_ticket,DEAL_SYMBOL);   // get symbol
         if(deal_symbol==_symbol)                                       // check symbol
            {
               deal_entry  = (ENUM_DEAL_ENTRY )HistoryDealGetInteger(deal_ticket,DEAL_ENTRY);
               deal_reason = (ENUM_DEAL_REASON)HistoryDealGetInteger(deal_ticket,DEAL_REASON);
               if(deal_entry==DEAL_ENTRY_OUT)                           // check entrytype
                //if(deal_reason==DEAL_REASON_SL)                       // check reason
                     {
                        deal_price   = HistoryDealGetDouble (deal_ticket,DEAL_PRICE);
                        return(deal_price);
                     }
            }
      }

   return(NULL);
}