How to get price, profit and commission of positions in MQL5?

Hello,

I would like to get opened position price, ticket number and it’s commission and profit. What could be the issue in the code?

Thanks in advance.

//+------------------------------------------------------------------+
//|                                     test_profitcommission_01.mq5 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"


#include<Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\DealInfo.mqh>

CTrade trade;
CPositionInfo pos;
CDealInfo deal;

ulong myticket;


int OnInit()
  {
//---

   OpenPosition();
   
//---
   return(INIT_SUCCEEDED);
  }



void OnDeinit(const int reason)
  {
//---
   
  }



void OnTick()
  {
//---
   
   deal.Ticket(myticket);
   
   double xcom=deal.Commission();
   double xpro=deal.Profit();
   
   Comment("Profit = ",xpro,"  com = ",xcom);
   
   
  }



void OpenPosition()
{
   trade.SetExpertMagicNumber(12345);
   trade.SetDeviationInPoints(10);              
   trade.SetTypeFilling(ORDER_FILLING_RETURN);
   trade.LogLevel(2); 
   trade.SetAsyncMode(true);

   
    if(!trade.Buy(1,_Symbol))
     {
      //--- failure message
      Print("Buy() method failed. Return code=",trade.ResultRetcode(),". Code description: ",trade.ResultRetcodeDescription());
     }
   else
     {
      Print("Buy() method executed successfully. Return code=",trade.ResultRetcode()," (",trade.ResultRetcodeDescription(),")");   
      
      myticket=trade.RequestOrder();
      
      double xopenprice=trade.ResultPrice();
      Print("Open price is = ",xopenprice);
      Print("Ticket number is = ",myticket);
      
     }
   
}

Hello again,

At least any documentation about getting commission, position price?

I’m opening a position but I cannot get the opened price. My target price differs from actual due to slippage thus I need to be sure about the opening price. It was so simple in MQL4 but I could not get how to do it in MQL5.

Thanks

Commission from the position can not be obtained. The commission can be seen from the deals, which closed the position.

The deal ticket is obtained through the ResultDeal method.

When there is a ticket, you need to choose the position: SelectByTicket. After that you can:

  • The price of position opening: PriceOpen.
  • The amount of current profit by position: Profit.

Do you need an example of a code?

Thanks for your reply.

Yes I think I need an example code since I cannot make it mine work. First of all I cannot get the ticket number, it gives zero, so I could not get open price.

I also wonder why I cannot get open price directly using trade.ResultPrice(), it’s the same trade class as I’m getting ticket number. If I can get the ticket number why not to get all other information about the trade.

void OpenPosition()
{
   trade.SetExpertMagicNumber(12345);
   trade.SetDeviationInPoints(10);              
   trade.SetTypeFilling(ORDER_FILLING_RETURN);
   trade.LogLevel(2); 
   trade.SetAsyncMode(true);

    if(!trade.Buy(1,_Symbol))
     {
      //--- failure message
      Print("Buy() method failed. Return code=",trade.ResultRetcode(),". Code description: ",trade.ResultRetcodeDescription());
     }
   else
     {
      Print("Buy() method executed successfully. Return code=",trade.ResultRetcode()," (",trade.ResultRetcodeDescription(),")");   
      
      ulong myticket=trade.ResultDeal();
      
      //pos.SelectByTicket(myticket);
      //double myprice=pos.PriceOpen();
      
      double myprice=trade.ResultPrice();
      double mylot=trade.ResultVolume();
      
      Print("Ticket number is = ",myticket,"  Open price is = ",myprice,"  lots = ",mylot);
      
     }
   
}

I apologize, we receive the ticket for the position via the “ResultOrder” method:

//+------------------------------------------------------------------+
//|                                     test_profitcommission_01.mq5 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object

ulong myticket=0;
bool first_start=true;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   m_trade.SetExpertMagicNumber(12345);
   m_trade.SetDeviationInPoints(10);
   m_trade.SetTypeFilling(ORDER_FILLING_RETURN);
//---
   first_start=true;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(first_start)
      if(OpenBuy())
         first_start=false;

   if(m_position.SelectByTicket(myticket))
     {
      double profit=m_position.Profit();
      Comment("Profit = ",DoubleToString(profit,2));
     }
   else
      Comment("");
  }
//+------------------------------------------------------------------+
//| Open Buy position                                                |
//+------------------------------------------------------------------+
bool OpenBuy(void)
  {
   bool result=m_trade.Buy(1.0);
   if(result)
     {
      if(m_trade.ResultDeal()==0)
        {
         Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription());
        }
      else
        {
         Print("Buy -> true. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription());
         myticket=m_trade.ResultOrder();
         double result_price=m_trade.ResultPrice();
         Print("Open price is = ",DoubleToString(result_price,Digits()));
         Print("Ticket number is = ",IntegerToString(myticket));
        }
     }
   else
     {
      Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
            ", description of result: ",m_trade.ResultRetcodeDescription());
     }
//---
   return(result);
  }
//+------------------------------------------------------------------+

Also I repeat that the commission will be available after the POSITION WILL BE CLOSED.

Or here such variant (with usage OnTradeTransaction):

//+------------------------------------------------------------------+
//|                                     test_profitcommission_01.mq5 |
//|                        Copyright 2017, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
CPositionInfo  m_position;                   // trade position object
CTrade         m_trade;                      // trading object

ulong myticket=0;
bool first_start=true;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   m_trade.SetExpertMagicNumber(12345);
   m_trade.SetDeviationInPoints(10);
   m_trade.SetTypeFilling(ORDER_FILLING_RETURN);
//---
   first_start=true;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(first_start)
      if(OpenBuy())
         first_start=false;

   if(m_position.SelectByTicket(myticket))
     {
      double profit=m_position.Profit();
      Comment("Profit = ",DoubleToString(profit,2));
     }
   else
      Comment("");
  }
//+------------------------------------------------------------------+
//| Open Buy position                                                |
//+------------------------------------------------------------------+
bool OpenBuy(void)
  {
   bool result=m_trade.Buy(1.0);
   if(result)
     {
      if(m_trade.ResultDeal()==0)
        {
         Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription());
        }
      else
        {
         Print("Buy -> true. Result Retcode: ",m_trade.ResultRetcode(),
               ", description of result: ",m_trade.ResultRetcodeDescription());
         myticket=m_trade.ResultOrder();
         double result_price=m_trade.ResultPrice();
         Print("Open price is = ",DoubleToString(result_price,Digits()));
         Print("Ticket number is = ",IntegerToString(myticket));
        }
     }
   else
     {
      Print("Buy -> false. Result Retcode: ",m_trade.ResultRetcode(),
            ", description of result: ",m_trade.ResultRetcodeDescription());
     }
//---
   return(result);
  }
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
   double res=0.0;
   int losses=0.0;
//--- get transaction type as enumeration value 
   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is result of addition of the transaction in history
   if(type==TRADE_TRANSACTION_DEAL_ADD)
     {
      long     deal_entry        =0;
      double   deal_profit       =0.0;
      string   deal_symbol       ="";
      long     deal_pos_id       =0;
      double   deal_commission   =0.0;
      if(HistoryDealSelect(trans.deal))
        {
         deal_entry=HistoryDealGetInteger(trans.deal,DEAL_ENTRY);
         deal_profit=HistoryDealGetDouble(trans.deal,DEAL_PROFIT);
         deal_symbol=HistoryDealGetString(trans.deal,DEAL_SYMBOL);
         deal_pos_id=HistoryDealGetInteger(trans.deal,DEAL_POSITION_ID);
         deal_commission=HistoryDealGetDouble(trans.deal,DEAL_COMMISSION);
        }
      else
         return;
      if(deal_symbol==Symbol())
        {
         if(deal_entry==DEAL_ENTRY_IN)
            myticket=deal_pos_id;
         if(deal_entry==DEAL_ENTRY_OUT)
            Print("Commission = ",DoubleToString(deal_commission,2));
        }
     }
  }
//+------------------------------------------------------------------+

In this variant, we “catch” the transaction “entry” and the deal “exit”. For the “exit” deal, we can already get a commission.

Great, it works now, thank you for the codes.

By the way, SetAsyncMode(true) was also blocking getting results.

trade.SetAsyncMode(true);

That’s why in my example there is no “SetAsyncMode(true)” :slight_smile:

@jplews26 I know, I know, “down with old-thread-reincarnator”.

BUT,

deal_symbol=HistoryDealGetString(trans.deal,DEAL_SYMBOL);

is there any reason not to use trans.symbol (or any other trans.something needed) or it doesn’t make a difference ?

//+------------------------------------------------------------------+
//|                                     test_profitcommission_02.mq5 |
//+------------------------------------------------------------------+

// https://www.mql5.com/en/code/16006
#include <mt4orders.mqh>

#define Ask SymbolInfoDouble(_Symbol, SYMBOL_ASK)

TICKET_TYPE myticket;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   myticket=OrderSend(_Symbol,OP_BUY,1,Ask,50,0,0);

   if(OrderSelect(myticket,SELECT_BY_TICKET))
     {
      Print("Open price is = ",OrderOpenPrice());
      Print("Ticket number is = ",OrderTicket());
     }

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(OrderSelect(myticket,SELECT_BY_TICKET))
      Comment("Profit = ",OrderProfit(),"  com = ",OrderCommission());
  }
//+------------------------------------------------------------------+