Total Margin Position By Position Type

 

Hey , I've been trying to work with OrderCalcMargin which does a good job of obtaining the Margin Used by Each Order , But I'm trying to get the total of all margin Outside at the Margin Variable definition level but I'm getting same value outside the block and correct value inside the block but when I try to add them to get their total It seems the same value is been adding to its own self 

Someone explain to me how, why and what should be done  I'm pretty sure something is wrong at Margin Variable storage of value its a double& since I haven't Used it before in situation Like this ,  and I don't fully understand how it works

double MarginCalculation(ENUM_POSITION_TYPE type)
 { 
  double Margin=0; // store the margin
  double MPlus = -1;
  for (int i=PositionsTotal()-1; i>=0; i--)
    if (m_position.SelectByIndex(i))
      if (m_position.Magic()==MagicNumber && m_position.Symbol()==Symbol() && m_position.PositionType()==type)
        {
           bool calc = OrderCalcMargin(m_position.PositionType()==POSITION_TYPE_BUY ? ORDER_TYPE_BUY : ORDER_TYPE_SELL,Symbol(),m_position.Volume(),m_position.PriceOpen(),Margin);
           Print(EnumToString(type)," Ticket ",m_position.Ticket()," ",EnumToString(type)," Margin ",Margin);
          //Print("Margin++ ",Margin+=Margin); //you I'll get the same value being added to its own self several times
        }
    Print(" OUTSIDE BLOCK "EnumToString(type)," Ticket ",m_position.Ticket()," ",EnumToString(type)," Margin ",Margin); //here you'll get the ssame 
       //order and same value all the time 
     return(Margin);
 }


 

Reason: