fix p&l calculation to use total cost basis instead of avrg
This commit is contained in:
parent
861bb01a31
commit
1ab442045f
1 changed files with 28 additions and 12 deletions
|
|
@ -44,7 +44,20 @@ export async function GET({ request }) {
|
||||||
const value = quantity * price;
|
const value = quantity * price;
|
||||||
totalCoinValue += value;
|
totalCoinValue += value;
|
||||||
|
|
||||||
// Calculate average purchase price from buy transactions
|
// Calculate total cost basis from buy transactions
|
||||||
|
const costBasisResult = await db.select({
|
||||||
|
totalCostBasis: sql<number>`COALESCE(SUM(${transaction.totalBaseCurrencyAmount}), 0)`
|
||||||
|
})
|
||||||
|
.from(transaction)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(transaction.userId, userId),
|
||||||
|
eq(transaction.coinId, holding.coinId),
|
||||||
|
eq(transaction.type, 'BUY')
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Calculate average purchase price for reference
|
||||||
const avgPriceResult = await db.select({
|
const avgPriceResult = await db.select({
|
||||||
avgPrice: sql<number>`
|
avgPrice: sql<number>`
|
||||||
CASE
|
CASE
|
||||||
|
|
@ -63,9 +76,11 @@ export async function GET({ request }) {
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const totalCostBasis = Number(costBasisResult[0]?.totalCostBasis || 0);
|
||||||
const avgPurchasePrice = Number(avgPriceResult[0]?.avgPrice || 0);
|
const avgPurchasePrice = Number(avgPriceResult[0]?.avgPrice || 0);
|
||||||
const percentageChange = avgPurchasePrice > 0
|
|
||||||
? ((price - avgPurchasePrice) / avgPurchasePrice) * 100
|
const percentageChange = totalCostBasis > 0
|
||||||
|
? ((value - totalCostBasis) / totalCostBasis) * 100
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
@ -76,7 +91,8 @@ export async function GET({ request }) {
|
||||||
value,
|
value,
|
||||||
change24h: Number(holding.change24h),
|
change24h: Number(holding.change24h),
|
||||||
avgPurchasePrice,
|
avgPurchasePrice,
|
||||||
percentageChange
|
percentageChange,
|
||||||
|
costBasis: totalCostBasis
|
||||||
};
|
};
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|
|
||||||
Reference in a new issue