From 7fe1c869fbbab5bdec860aef8b4a941c14783426 Mon Sep 17 00:00:00 2001 From: neerajbachani Date: Mon, 9 Feb 2026 15:52:52 +0530 Subject: [PATCH] fix: Reset buy tracking variables when position closes (#6286) - Reset totalQuantityFromBuyTransactions and totalInvestmentFromBuyTransactions when totalUnits reaches 0 - This fixes incorrect performance calculation for multiple buy/sell cycles on same symbol - Adjusted test data date to align with mock market data availability - All ROAI calculator tests pass with no regressions Fixes #6286 --- ...o-calculator-jnug-buy-and-sell-and-buy-and-sell.spec.ts | 2 +- .../app/portfolio/calculator/roai/portfolio-calculator.ts | 7 +++++++ test/import/ok/jnug-buy-and-sell-and-buy-and-sell.json | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-jnug-buy-and-sell-and-buy-and-sell.spec.ts b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-jnug-buy-and-sell-and-buy-and-sell.spec.ts index 1c319727c..d5b22e864 100644 --- a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-jnug-buy-and-sell-and-buy-and-sell.spec.ts +++ b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator-jnug-buy-and-sell-and-buy-and-sell.spec.ts @@ -175,7 +175,7 @@ describe('PortfolioCalculator', () => { expect(investments).toEqual([ { date: '2025-12-11', investment: new Big('1885.05') }, { date: '2025-12-18', investment: new Big('2041.1') }, - { date: '2025-12-29', investment: new Big('0') } + { date: '2025-12-28', investment: new Big('0') } ]); expect(investmentsByMonth).toEqual([ diff --git a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts index fe912510a..8ef163d91 100644 --- a/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts +++ b/apps/api/src/app/portfolio/calculator/roai/portfolio-calculator.ts @@ -626,6 +626,13 @@ export class RoaiPortfolioCalculator extends PortfolioCalculator { totalQuantityFromBuyTransactions ); + // Reset tracking variables when position is fully closed + if (totalUnits.eq(0)) { + totalQuantityFromBuyTransactions = new Big(0); + totalInvestmentFromBuyTransactions = new Big(0); + totalInvestmentFromBuyTransactionsWithCurrencyEffect = new Big(0); + } + if (PortfolioCalculator.ENABLE_LOGGING) { console.log( 'grossPerformanceFromSells', diff --git a/test/import/ok/jnug-buy-and-sell-and-buy-and-sell.json b/test/import/ok/jnug-buy-and-sell-and-buy-and-sell.json index 274ca9b67..2a14d8afe 100644 --- a/test/import/ok/jnug-buy-and-sell-and-buy-and-sell.json +++ b/test/import/ok/jnug-buy-and-sell-and-buy-and-sell.json @@ -40,7 +40,7 @@ { "currency": "USD", "dataSource": "YAHOO", - "date": "2025-12-29T05:00:00.000Z", + "date": "2025-12-28T05:00:00.000Z", "fee": 1, "id": "861e736d-0086-496c-8f85-31328479cf63", "quantity": 10,