Figuring out the average price of positions

 

for (i=total-1;i>=0;i--) {

if IOrderSelect(i, SELECT_BY_POS, MODE_TRADES)==TRUE) {

if(OrderMagicNumber()==MagicNo) {

if(OrderType()==OP_BUY || OrderType()==OP_SELL) {

SumPrice = OrderOpenPrice();

OpenCount++;

}}}

if(Opencount != 0) {

AvgPrice = SumPrice / OpenCount

}

This is a part of my code... Ive been trying to figure out the average price of my positions..

But,, it works kinda funny.. I want sum up every price of my position, but it regards "SumPrice" as the last open price..

I think my code is wrong.. anyone can help me?

I am trying to figure out the average price and then,, going to emulate the trailing stop based on average price..

 

try

SumPrice = 0; // make sure we start with 0 sum
for (i=total-1;i>=0;i--) {
if IOrderSelect(i, SELECT_BY_POS, MODE_TRADES)==TRUE) {
if(OrderMagicNumber()==MagicNo) {
if(OrderType()==OP_BUY || OrderType()==OP_SELL) {
SumPrice += OrderOpenPrice(); // not = but +=
OpenCount++;
}}}
if(Opencount != 0) {
AvgPrice = SumPrice / OpenCount
}
 
That will work only if all order are the same lot size. Otherwise you need a weighted average:
SumPrice = 0; // make sure we start with 0 sum
double Elots=0
for (i=total-1;i>=0;i--) if (
   OrderSelect(i, SELECT_BY_POS)
&& OrderMagicNumber() == MagicNo
&& OrderType()        <= OP_SELL) {
   SumPrice += OrderOpenPrice(); // not = but +=
   Elots    += OrderLots();
}
if(Elots != 0) AvgPrice = SumPrice / Elots;
 
WHRoeder:
That will work only if all order are the same lot size. Otherwise you need a weighted average:
oops, yes, but code maybe should look like
SumPrice = 0; // make sure we start with 0 sum
double Elots=0;
for (i=total-1;i>=0;i--) if (
   OrderSelect(i, SELECT_BY_POS)
&& OrderMagicNumber() == MagicNo
&& OrderType()        <= OP_SELL) {
   SumPrice += OrderOpenPrice() * OrderLots(); // sum price * lots, not just price
   Elots    += OrderLots();
}
if(Elots != 0) AvgPrice = SumPrice / Elots;
 
brewmanz:
oops, yes, but code maybe should look like
Definitely Eprice += price*lots
Reason: