# function to calculate average price

Do you want to become a well-known developer? Execute the orders of traders in the Freelance service!
335
2013.01.09 17:37

I am newbie to MQL5. Can someone help me to create a mql5 function like the one in mql4 below. In addition to modify all open positions takeProfit to AVPrice + TakeProfit for buy or   AVPrice - TakeProfit  for sell.

//----------------------- CALCULATE AVERAGE OPENING PRICE

double AVPrice(int type)

{

int total=OrderCount(Symbol(), type);

double AveragePrice=0;

double Count=0;

for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)

{

if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)

continue;

if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)

if(OrderType()==type)

{

AveragePrice=AveragePrice+OrderOpenPrice()*OrderLots();

Count=Count + OrderLots();

}

}

if(total > 0)

AveragePrice=NormalizeDouble(AveragePrice/Count, Digits);

return (AveragePrice);

}

Documentation on MQL5: Standard Constants, Enumerations and Structures / Indicator Constants / Price Constants
• www.mql5.com
Standard Constants, Enumerations and Structures / Indicator Constants / Price Constants - Documentation on MQL5
Moderator
1943
2013.01.10 05:09
xlitang:

I am newbie to MQL5. Can someone help me to create a mql5 function like the one in mql4 below. In addition to modify all open positions takeProfit to AVPrice + TakeProfit for buy or   AVPrice - TakeProfit  for sell.

//----------------------- CALCULATE AVERAGE OPENING PRICE

double AVPrice(int type)

{

int total=OrderCount(Symbol(), type);

double AveragePrice=0;

double Count=0;

for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)

{

if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)

continue;

if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)

if(OrderType()==type)

{

AveragePrice=AveragePrice+OrderOpenPrice()*OrderLots();

Count=Count + OrderLots();

}

}

if(total > 0)

AveragePrice=NormalizeDouble(AveragePrice/Count, Digits);

return (AveragePrice);

}

You don't need to caculate average price because there always one position of a symbol in MT5.

You just need to use PositionGetDouble(POSITION_PRICE_OPEN) to get the open price of your position.

2184
2013.01.10 16:42
xlitang:

I am newbie to MQL5. Can someone help me to create a mql5 function like the one in mql4 below. In addition to modify all open positions takeProfit to AVPrice + TakeProfit for buy or   AVPrice - TakeProfit  for sell.