2021-07-08 22:42:19 +02:00
|
|
|
import { DataProviderService } from '@ghostfolio/api/services/data-provider.service';
|
2021-07-01 23:11:41 +02:00
|
|
|
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
|
2021-07-03 16:37:33 +02:00
|
|
|
import { Injectable } from '@nestjs/common';
|
|
|
|
import { Currency } from '@prisma/client';
|
2021-07-08 22:42:19 +02:00
|
|
|
import { isToday } from 'date-fns';
|
2021-07-01 23:11:41 +02:00
|
|
|
|
2021-07-03 16:37:33 +02:00
|
|
|
import { MarketDataService } from './market-data.service';
|
2021-07-01 23:11:41 +02:00
|
|
|
|
2021-07-03 16:37:33 +02:00
|
|
|
@Injectable()
|
|
|
|
export class CurrentRateService {
|
2021-07-01 23:11:41 +02:00
|
|
|
public constructor(
|
2021-07-08 22:42:19 +02:00
|
|
|
private readonly dataProviderService: DataProviderService,
|
2021-07-01 23:11:41 +02:00
|
|
|
private readonly exchangeRateDataService: ExchangeRateDataService,
|
2021-07-03 16:37:33 +02:00
|
|
|
private readonly marketDataService: MarketDataService
|
2021-07-01 23:11:41 +02:00
|
|
|
) {}
|
|
|
|
|
2021-07-03 16:37:33 +02:00
|
|
|
public async getValue({
|
|
|
|
currency,
|
|
|
|
date,
|
|
|
|
symbol,
|
|
|
|
userCurrency
|
|
|
|
}: GetValueParams): Promise<number> {
|
2021-07-08 22:42:19 +02:00
|
|
|
if (isToday(date)) {
|
|
|
|
const dataProviderResult = await this.dataProviderService.get([symbol]);
|
|
|
|
return dataProviderResult?.[symbol]?.marketPrice ?? 0;
|
|
|
|
}
|
|
|
|
|
2021-07-03 16:37:33 +02:00
|
|
|
const marketData = await this.marketDataService.get({
|
|
|
|
date,
|
|
|
|
symbol
|
2021-07-01 23:11:41 +02:00
|
|
|
});
|
|
|
|
|
2021-07-03 16:37:33 +02:00
|
|
|
if (marketData) {
|
|
|
|
return this.exchangeRateDataService.toCurrency(
|
|
|
|
marketData.marketPrice,
|
|
|
|
currency,
|
|
|
|
userCurrency
|
|
|
|
);
|
|
|
|
}
|
2021-07-01 23:11:41 +02:00
|
|
|
|
2021-07-03 16:37:33 +02:00
|
|
|
throw new Error(`Value not found for ${symbol} at ${date}`);
|
2021-07-01 23:11:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface GetValueParams {
|
|
|
|
date: Date;
|
|
|
|
symbol: string;
|
|
|
|
currency: Currency;
|
|
|
|
userCurrency: Currency;
|
|
|
|
}
|