# 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);

if(Symbol()==symbol)
{
Positionsforthissymbol+=1;
}
}
double profit[];
if(Positionsforthissymbol>0)
{
for(int i=0; i<Positionsforthissymbol; i++)
{
if(PositionSelect(_Symbol)==true)
{
profit[i]=PositionGetDouble(POSITION_PROFIT);
}
}
}
int positionsid=ArrayMaximum(profit,0,WHOLE_ARRAY);

Does anyone see a mistake?

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.

nicholi shen:
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.

Demosfen:

Hi everyone,

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

This is my code:

Does anyone see a mistake?

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(OrderProfit()>max){
max=OrderProfit();
}
}
}
return(max);
}

bagaya:

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.

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.

bagaya:
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

This will work for MQL5
double maxprofit()
{
static double max  = 0;
for(int i = PositionsTotal() - 1; i>=0; i--)
{
if(PositionSelect(_Symbol)==true){
if(m_position.Profit() > max)
{
max = m_position.Profit();
}
}
}
return(max);
}

Doesn't PositionSelect(_Symbol) only return the position with the lowest ticket number on that symbol?

Wouldn't it be better to use PositionGetTicket to select the positions by index count?

Esténio Manhiça #:
This will work for MQL5

No, it won't. you need to use functions to select position by index.
Reason: