Get current profit?

 

Hi,

I have searching and testing everything and dont get it...

I want a function returning current profit / loss for all open positions.

This function that I found here does not match what is showing in MT5 Trade tab??

What I want to achive is,,
Take three trades, Monitor each ones profit/loss, Read them in to three variables, double Trade1, Trade2, Trade3;


double OpenPositionsProfit()
  {
   double allProfit = 0;
   if(PositionsTotal() > 0)
      for(int i = 0; i < PositionsTotal(); i++)
        {
         ulong ticket = PositionGetTicket(i);
         if(PositionSelectByTicket(ticket))
            if(PositionGetInteger(POSITION_MAGIC) == magicNumber)
               if(PositionGetString(POSITION_SYMBOL) == _Symbol)
                  allProfit += PositionGetDouble(POSITION_PROFIT);
        }
   return allProfit;
  }
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Position Properties
  • www.mql5.com
Execution of trade operations results in the opening of a position, changing of its volume and/or direction, or its disappearance. Trade operations...
 
skrantz71:

Hi,

I have searching and testing everything and dont get it...

I want a function returning current profit / loss for all open positions.

This function that I found here does not match what is showing in MT5 Trade tab??

What I want to achive is,,
Take three trades, Monitor each ones profit/loss, Read them in to three variables, double Trade1, Trade2, Trade3;


i suggest that you search the website for mql5 functions. There is a 1 line function that callse the Profit/Liability value for current open trades.

 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 

In OnTick it can keep running the function and loop over the same tickets. In terms of logic, I think you need to add the PnL of unique tickets only. You can do this with ArrayBSearch


ulong ticketsArray[]; // store unique ticket numbers



double OpenPositionsProfit()
  {
   double allProfit = 0;

   if(PositionsTotal() > 0)
      for(int i = 0; i < PositionsTotal(); i++)
        {
         ulong ticket = PositionGetTicket(i);
         if(PositionSelectByTicket(ticket))
            if(PositionGetInteger(POSITION_MAGIC) == magicNumber)
               if(PositionGetString(POSITION_SYMBOL) == _Symbol)
                if(ArrayBsearch(ticketsArray, ticket) == -1)    // Only consider the ticket if it hasn't already been considered
                  allProfit += PositionGetDouble(POSITION_PROFIT);
        }
   return allProfit;
  }