From d0b26963aa9c81c49f7e4a1380e83481315bb158 Mon Sep 17 00:00:00 2001 From: KenTandrian Date: Thu, 11 Sep 2025 23:41:09 +0700 Subject: [PATCH] fix(api): add logic for selling all units --- .../app/portfolio/calculator/portfolio-calculator.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts b/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts index e4d9cdfe8..d3984ad0a 100644 --- a/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts +++ b/apps/api/src/app/portfolio/calculator/portfolio-calculator.ts @@ -937,11 +937,19 @@ export abstract class PortfolioCalculator { ); } } else if (type === 'SELL') { - if (oldAccumulatedSymbol.investment.gt(0)) { + if ( + oldAccumulatedSymbol.quantity.gt(0) && + oldAccumulatedSymbol.quantity.eq(quantity) + ) { + // Selling all units, so investment should be 0 + investment = new Big(0); + } else if (oldAccumulatedSymbol.investment.gt(0)) { + // Selling part of a positive investment investment = oldAccumulatedSymbol.investment.minus( quantity.mul(oldAccumulatedSymbol.averagePrice) ); } else { + // Selling part of a negative investment (short sell) investment = oldAccumulatedSymbol.investment.minus( quantity.mul(unitPrice) );