Thomas Kaul 1 week ago
committed by GitHub
parent
commit
4459996fb8
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 6
      CHANGELOG.md
  2. 32
      apps/api/src/app/portfolio/current-rate.service.spec.ts
  3. 69
      apps/api/src/app/portfolio/current-rate.service.ts
  4. 40
      apps/api/src/services/market-data/market-data.service.ts
  5. 4
      package-lock.json
  6. 2
      package.json

6
CHANGELOG.md

@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 2.152.0-beta.2 - 2025-04-13
### Changed
- Optimized the query of the data range functionality (`getRange()`) in the market data service
## 2.151.0 - 2025-04-11 ## 2.151.0 - 2025-04-11
### Added ### Added

32
apps/api/src/app/portfolio/current-rate.service.spec.ts

@ -6,6 +6,7 @@ import { AssetProfileIdentifier } from '@ghostfolio/common/interfaces';
import { DataSource, MarketData } from '@prisma/client'; import { DataSource, MarketData } from '@prisma/client';
import { CurrentRateService } from './current-rate.service'; import { CurrentRateService } from './current-rate.service';
import { DateQuery } from './interfaces/date-query.interface';
import { GetValuesObject } from './interfaces/get-values-object.interface'; import { GetValuesObject } from './interfaces/get-values-object.interface';
jest.mock('@ghostfolio/api/services/market-data/market-data.service', () => { jest.mock('@ghostfolio/api/services/market-data/market-data.service', () => {
@ -25,33 +26,40 @@ jest.mock('@ghostfolio/api/services/market-data/market-data.service', () => {
}, },
getRange: ({ getRange: ({
assetProfileIdentifiers, assetProfileIdentifiers,
dateRangeEnd, dateQuery
dateRangeStart
}: { }: {
assetProfileIdentifiers: AssetProfileIdentifier[]; assetProfileIdentifiers: AssetProfileIdentifier[];
dateRangeEnd: Date; dateQuery: DateQuery;
dateRangeStart: Date; skip?: number;
take?: number;
}) => { }) => {
return Promise.resolve<MarketData[]>([ return Promise.resolve<MarketData[]>([
{ {
createdAt: dateRangeStart, createdAt: dateQuery.gte,
dataSource: assetProfileIdentifiers[0].dataSource, dataSource: assetProfileIdentifiers[0].dataSource,
date: dateRangeStart, date: dateQuery.gte,
id: '8fa48fde-f397-4b0d-adbc-fb940e830e6d', id: '8fa48fde-f397-4b0d-adbc-fb940e830e6d',
marketPrice: 1841.823902, marketPrice: 1841.823902,
state: 'CLOSE', state: 'CLOSE',
symbol: assetProfileIdentifiers[0].symbol symbol: assetProfileIdentifiers[0].symbol
}, },
{ {
createdAt: dateRangeEnd, createdAt: dateQuery.lt,
dataSource: assetProfileIdentifiers[0].dataSource, dataSource: assetProfileIdentifiers[0].dataSource,
date: dateRangeEnd, date: dateQuery.lt,
id: '082d6893-df27-4c91-8a5d-092e84315b56', id: '082d6893-df27-4c91-8a5d-092e84315b56',
marketPrice: 1847.839966, marketPrice: 1847.839966,
state: 'CLOSE', state: 'CLOSE',
symbol: assetProfileIdentifiers[0].symbol symbol: assetProfileIdentifiers[0].symbol
} }
]); ]);
},
getRangeCount: ({}: {
assetProfileIdentifiers: AssetProfileIdentifier[];
dateRangeEnd: Date;
dateRangeStart: Date;
}) => {
return Promise.resolve<number>(2);
} }
}; };
}) })
@ -128,9 +136,15 @@ describe('CurrentRateService', () => {
values: [ values: [
{ {
dataSource: 'YAHOO', dataSource: 'YAHOO',
date: undefined, date: new Date('2020-01-01T00:00:00.000Z'),
marketPrice: 1841.823902, marketPrice: 1841.823902,
symbol: 'AMZN' symbol: 'AMZN'
},
{
dataSource: 'YAHOO',
date: new Date('2020-01-02T00:00:00.000Z'),
marketPrice: 1847.839966,
symbol: 'AMZN'
} }
] ]
}); });

69
apps/api/src/app/portfolio/current-rate.service.ts

@ -21,6 +21,8 @@ import { GetValuesParams } from './interfaces/get-values-params.interface';
@Injectable() @Injectable()
export class CurrentRateService { export class CurrentRateService {
private static readonly MARKET_DATA_PAGE_SIZE = 50000;
public constructor( public constructor(
private readonly dataProviderService: DataProviderService, private readonly dataProviderService: DataProviderService,
private readonly marketDataService: MarketDataService, private readonly marketDataService: MarketDataService,
@ -41,30 +43,29 @@ export class CurrentRateService {
(!dateQuery.gte || isBefore(dateQuery.gte, new Date())) && (!dateQuery.gte || isBefore(dateQuery.gte, new Date())) &&
(!dateQuery.in || this.containsToday(dateQuery.in)); (!dateQuery.in || this.containsToday(dateQuery.in));
const promises: Promise<GetValueObject[]>[] = [];
const quoteErrors: ResponseError['errors'] = []; const quoteErrors: ResponseError['errors'] = [];
const today = resetHours(new Date()); const today = resetHours(new Date());
const values: GetValueObject[] = [];
if (includesToday) { if (includesToday) {
promises.push( const quotesBySymbol = await this.dataProviderService.getQuotes({
this.dataProviderService items: dataGatheringItems,
.getQuotes({ items: dataGatheringItems, user: this.request?.user }) user: this.request?.user
.then((dataResultProvider) => { });
const result: GetValueObject[] = [];
for (const { dataSource, symbol } of dataGatheringItems) { for (const { dataSource, symbol } of dataGatheringItems) {
if (dataResultProvider?.[symbol]?.dataProviderInfo) { const quote = quotesBySymbol[symbol];
dataProviderInfos.push(
dataResultProvider[symbol].dataProviderInfo if (quote?.dataProviderInfo) {
); dataProviderInfos.push(quote.dataProviderInfo);
} }
if (dataResultProvider?.[symbol]?.marketPrice) { if (quote?.marketPrice) {
result.push({ values.push({
dataSource, dataSource,
symbol, symbol,
date: today, date: today,
marketPrice: dataResultProvider?.[symbol]?.marketPrice marketPrice: quote.marketPrice
}); });
} else { } else {
quoteErrors.push({ quoteErrors.push({
@ -73,10 +74,6 @@ export class CurrentRateService {
}); });
} }
} }
return result;
})
);
} }
const assetProfileIdentifiers: AssetProfileIdentifier[] = const assetProfileIdentifiers: AssetProfileIdentifier[] =
@ -84,34 +81,42 @@ export class CurrentRateService {
return { dataSource, symbol }; return { dataSource, symbol };
}); });
promises.push( const marketDataCount = await this.marketDataService.getRangeCount({
this.marketDataService
.getRange({
assetProfileIdentifiers, assetProfileIdentifiers,
dateQuery dateQuery
}) });
.then((data) => {
return data.map(({ dataSource, date, marketPrice, symbol }) => { for (
return { let i = 0;
i < marketDataCount;
i += CurrentRateService.MARKET_DATA_PAGE_SIZE
) {
// Use pageSize to limit the number of records fetched at once
const data = await this.marketDataService.getRange({
assetProfileIdentifiers,
dateQuery,
skip: i,
take: CurrentRateService.MARKET_DATA_PAGE_SIZE
});
values.push(
...data.map(({ dataSource, date, marketPrice, symbol }) => ({
dataSource, dataSource,
date, date,
marketPrice, marketPrice,
symbol symbol
}; }))
});
})
); );
}
const values = await Promise.all(promises).then((array) => {
return array.flat();
});
const response: GetValuesObject = { const response: GetValuesObject = {
dataProviderInfos, dataProviderInfos,
errors: quoteErrors.map(({ dataSource, symbol }) => { errors: quoteErrors.map(({ dataSource, symbol }) => {
return { dataSource, symbol }; return { dataSource, symbol };
}), }),
values: uniqBy(values, ({ date, symbol }) => `${date}-${symbol}`) values: uniqBy(values, ({ date, symbol }) => {
return `${date}-${symbol}`;
})
}; };
if (!isEmpty(quoteErrors)) { if (!isEmpty(quoteErrors)) {

40
apps/api/src/services/market-data/market-data.service.ts

@ -60,12 +60,18 @@ export class MarketDataService {
public async getRange({ public async getRange({
assetProfileIdentifiers, assetProfileIdentifiers,
dateQuery dateQuery,
skip,
take
}: { }: {
assetProfileIdentifiers: AssetProfileIdentifier[]; assetProfileIdentifiers: AssetProfileIdentifier[];
dateQuery: DateQuery; dateQuery: DateQuery;
skip?: number;
take?: number;
}): Promise<MarketData[]> { }): Promise<MarketData[]> {
return this.prismaService.marketData.findMany({ return this.prismaService.marketData.findMany({
skip,
take,
orderBy: [ orderBy: [
{ {
date: 'asc' date: 'asc'
@ -75,17 +81,33 @@ export class MarketDataService {
} }
], ],
where: { where: {
dataSource: {
in: assetProfileIdentifiers.map(({ dataSource }) => {
return dataSource;
})
},
date: dateQuery, date: dateQuery,
symbol: { OR: assetProfileIdentifiers.map(({ dataSource, symbol }) => {
in: assetProfileIdentifiers.map(({ symbol }) => { return {
return symbol; dataSource,
symbol
};
}) })
} }
});
}
public async getRangeCount({
assetProfileIdentifiers,
dateQuery
}: {
assetProfileIdentifiers: AssetProfileIdentifier[];
dateQuery: DateQuery;
}): Promise<number> {
return this.prismaService.marketData.count({
where: {
date: dateQuery,
OR: assetProfileIdentifiers.map(({ dataSource, symbol }) => {
return {
dataSource,
symbol
};
})
} }
}); });
} }

4
package-lock.json

@ -1,12 +1,12 @@
{ {
"name": "ghostfolio", "name": "ghostfolio",
"version": "2.151.0", "version": "2.152.0-beta.2",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ghostfolio", "name": "ghostfolio",
"version": "2.151.0", "version": "2.152.0-beta.2",
"hasInstallScript": true, "hasInstallScript": true,
"license": "AGPL-3.0", "license": "AGPL-3.0",
"dependencies": { "dependencies": {

2
package.json

@ -1,6 +1,6 @@
{ {
"name": "ghostfolio", "name": "ghostfolio",
"version": "2.151.0", "version": "2.152.0-beta.2",
"homepage": "https://ghostfol.io", "homepage": "https://ghostfol.io",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"repository": "https://github.com/ghostfolio/ghostfolio", "repository": "https://github.com/ghostfolio/ghostfolio",

Loading…
Cancel
Save