Loop through open positions and get max profit

Hi everyone,

I want to loop through all open positions for one symbol and get the position with max. profit.

This is my code:

int Positionsforthissymbol=0;
   for(int i=PositionsTotal()-1; i>=0; i--)
      string symbol=PositionGetSymbol(i);

double profit[];
      for(int i=0; i<Positionsforthissymbol; i++)
int positionsid=ArrayMaximum(profit,0,WHOLE_ARRAY);

Does anyone see a mistake?

Thank you in advance!

Arrays in MQL are not like lists in high-level languages. You always need to define a size. If you want a dynamically allocated, automatically sized collection then use CArrayDouble instead.

That was the problem, thank you!

Hello. I can do this. First, are you doing MQL4 or MQL5? I can do it for MQL4/MT4.

As long as you mean MQL4/Metatrader4, let me answer you like this: this is simple…

// Define a function which should return the value you are looking for.

double max_profit(){

double max=-1000000000; /* This is negative 1 billion. Remember -20 is bigger than -35; so your max profit could be -20! */

  for(int i=OrdersTotal-1; i>=0; i--){

    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==True && OrderSymbol()==Symbol()){








So if anyone asks you for maximum profit just give them max_profit() as the answer. The function max_profit() returns the value you are looking for.

Good solution, thank you

Ninnette Thurby, I tried your formulas but failed to get the highest floating profit value as if the trade’s profit dropped, it can’t keep the highest floating profit value. I modified the formulas a little bit as follows :-

double cBUYMxPft=0;//Max Floating Net Profit/Loss per Trade in Value
double cSELMxPft=0;//Max Floating Net Profit/Loss per Trade in Value
for(int i=OrdersTotal()-1; i>=0; i–)
if(OrderMagicNumber()==MagicNumber) {
if(OrderType()==OP_BUY) {
if(OrderType()==OP_SELL) {

Kindly have a look where does it goes wrong, thank you.