whats wrong with my positon open price function?

 
//+------------------------------------------------------------------+
double positonPrice(long type)
{
   double price = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      string symbol = PositionGetSymbol(i);
      long position_type = PositionGetInteger(POSITION_TYPE);
      if(Symbol() == symbol)
      {
         if(position_type == type)
         {
            price = PositionGetDouble(POSITION_PRICE_OPEN);
         }
      }
   }
   return price;
}

I don't understand whats wrong with this function. it find only first position open price but i need latest opened position open price

 
Revazi Tchitanava:

I don't understand whats wrong with this function. it find only first position open price but i need latest opened position open price

The loop starts with the latest open position and continues towards the oldest open position, and sets the price when a match occurs. That's ok to loop from back to front. But since you are only interested in the latest matching position you need to jump off from the loop as soon as you got the first match. This is what break is for, it quits the loop.

//+------------------------------------------------------------------+
double positonPrice(long type)
{
   double price = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      string symbol = PositionGetSymbol(i);
      long position_type = PositionGetInteger(POSITION_TYPE);
      if(Symbol() == symbol)
      {
         if(position_type == type)
         {
            price = PositionGetDouble(POSITION_PRICE_OPEN);
            break;
         }
      }
   }
   return price;
}

And that's it.

Reason: