Расчет средней цены
C#
Пример метода FIFO/LIFO, который возвращает среднюю цену открытия.
Код
enum CalcMethod
{
,
FIFO
LIFO}
private double GetAvgEntryPrice(CalcMethod method)
{
// calculate total buy and sell volume
double sellVolume = 0;
double buyVolume = 0;
foreach (Transaction transaction in Position.Transactions)
{
if (transaction.Side == TransactionSide.Sell)
+= transaction.Qty;
sellVolume else
+= transaction.Qty;
buyVolume }
double x = 0;
double cumQty = 0;
double openVolume;
if (Position.Side == PositionSide.Long)
{
= buyVolume - sellVolume;
openVolume
if (method == CalcMethod.LIFO)
{
for (int i = 0; i < Position.Transactions.Count; i++)
{
= Position.Transactions[i];
Transaction transaction
if (transaction.Side == TransactionSide.Sell)
continue;
double qty = Math.Min(transaction.Qty, openVolume);
+= qty;
cumQty += qty * transaction.Price;
x
-= qty;
openVolume
if (openVolume == 0)
break;
}
}
if (method == CalcMethod.FIFO)
{
for (int i = Position.Transactions.Count - 1; i >= 0 ; i--)
{
= Position.Transactions[i];
Transaction transaction
if (transaction.Side == TransactionSide.Sell)
continue;
double qty = Math.Min(transaction.Qty, openVolume);
+= qty;
cumQty += qty * transaction.Price;
x
-= qty;
openVolume
if (openVolume== 0)
break;
}
}
}
else
{
= sellVolume - buyVolume;
openVolume
if (method == CalcMethod.LIFO)
{
for (int i = 0; i < Position.Transactions.Count; i++)
{
= Position.Transactions[i];
Transaction transaction
if (transaction.Side == TransactionSide.Buy)
continue;
double qty = Math.Min(transaction.Qty, openVolume);
+= qty;
cumQty += qty * transaction.Price;
x
-= qty;
openVolume
if (openVolume == 0)
break;
}
}
if (method == CalcMethod.FIFO)
{
for (int i = Position.Transactions.Count - 1; i >= 0 ; i--)
{
= Position.Transactions[i];
Transaction transaction
if (transaction.Side == TransactionSide.Buy)
continue;
double qty = Math.Min(transaction.Qty, openVolume);
+= qty;
cumQty += qty * transaction.Price;
x
-= qty;
openVolume
if (openVolume == 0)
break;
}
}
}
return x / cumQty;
}