From fe0c56fe2da10a2e90facc8aae459b9d0fd5eb5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Szyma=C5=84ski?= Date: Wed, 27 Aug 2025 22:10:00 +0100 Subject: [PATCH] Fix average price for short positions --- .../portfolio/calculator/portfolio-calculator.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts b/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts index 78323a332..6e667efea 100644 --- a/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts +++ b/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts @@ -926,14 +926,22 @@ export abstract class PortfolioCalculator { .mul(factor) .plus(oldAccumulatedSymbol.quantity); - if (type === 'BUY') { + if (type === 'BUY' && oldAccumulatedSymbol.investment.gte(0)) { investment = oldAccumulatedSymbol.investment.plus( quantity.mul(unitPrice) ); - } else if (type === 'SELL') { + } else if (type === 'BUY' && oldAccumulatedSymbol.investment.lt(0)) { + investment = oldAccumulatedSymbol.investment.plus( + quantity.mul(oldAccumulatedSymbol.averagePrice) + ); + } else if (type === 'SELL' && oldAccumulatedSymbol.investment.gt(0)) { investment = oldAccumulatedSymbol.investment.minus( quantity.mul(oldAccumulatedSymbol.averagePrice) ); + } else if (type === 'SELL' && oldAccumulatedSymbol.investment.lte(0)) { + investment = oldAccumulatedSymbol.investment.minus( + quantity.mul(unitPrice) + ); } currentTransactionPointItem = { @@ -942,8 +950,8 @@ export abstract class PortfolioCalculator { investment, skipErrors, symbol, - averagePrice: newQuantity.gt(0) - ? investment.div(newQuantity) + averagePrice: !newQuantity.eq(0) + ? investment.div(newQuantity).abs() : new Big(0), dividend: new Big(0), fee: oldAccumulatedSymbol.fee.plus(fee),