ghostfolio/apps/api/src/services/data-gathering.service.ts

436 lines
12 KiB
TypeScript
Raw Normal View History

import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile.service';
import {
benchmarks,
ghostfolioFearAndGreedIndexSymbol
} from '@ghostfolio/common/config';
import { DATE_FORMAT, resetHours } from '@ghostfolio/common/helper';
import { Inject, Injectable } from '@nestjs/common';
import { DataSource } from '@prisma/client';
2021-04-13 21:53:58 +02:00
import {
differenceInHours,
format,
getDate,
getMonth,
getYear,
isBefore,
subDays
} from 'date-fns';
import { ConfigurationService } from './configuration.service';
import { DataProviderService } from './data-provider/data-provider.service';
import { GhostfolioScraperApiService } from './data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service';
import { DataEnhancerInterface } from './data-provider/interfaces/data-enhancer.interface';
import { ExchangeRateDataService } from './exchange-rate-data.service';
import { IDataGatheringItem } from './interfaces/interfaces';
2021-04-13 21:53:58 +02:00
import { PrismaService } from './prisma.service';
@Injectable()
export class DataGatheringService {
public constructor(
private readonly configurationService: ConfigurationService,
@Inject('DataEnhancers')
private readonly dataEnhancers: DataEnhancerInterface[],
private readonly dataProviderService: DataProviderService,
private readonly exchangeRateDataService: ExchangeRateDataService,
private readonly ghostfolioScraperApi: GhostfolioScraperApiService,
private readonly prismaService: PrismaService,
private readonly symbolProfileService: SymbolProfileService
2021-04-13 21:53:58 +02:00
) {}
public async gather7Days() {
const isDataGatheringNeeded = await this.isDataGatheringNeeded();
if (isDataGatheringNeeded) {
console.log('7d data gathering has been started.');
console.time('data-gathering-7d');
2021-04-13 21:53:58 +02:00
2021-08-07 22:38:07 +02:00
await this.prismaService.property.create({
2021-04-13 21:53:58 +02:00
data: {
key: 'LOCKED_DATA_GATHERING',
value: new Date().toISOString()
}
});
const symbols = await this.getSymbols7D();
try {
await this.gatherSymbols(symbols);
2021-08-07 22:38:07 +02:00
await this.prismaService.property.upsert({
2021-04-13 21:53:58 +02:00
create: {
key: 'LAST_DATA_GATHERING',
value: new Date().toISOString()
},
update: { value: new Date().toISOString() },
where: { key: 'LAST_DATA_GATHERING' }
});
} catch (error) {
console.error(error);
}
2021-08-07 22:38:07 +02:00
await this.prismaService.property.delete({
2021-04-13 21:53:58 +02:00
where: {
key: 'LOCKED_DATA_GATHERING'
}
});
console.log('7d data gathering has been completed.');
console.timeEnd('data-gathering-7d');
2021-04-13 21:53:58 +02:00
}
}
public async gatherMax() {
2021-08-07 22:38:07 +02:00
const isDataGatheringLocked = await this.prismaService.property.findUnique({
where: { key: 'LOCKED_DATA_GATHERING' }
});
2021-04-13 21:53:58 +02:00
if (!isDataGatheringLocked) {
2021-04-13 21:53:58 +02:00
console.log('Max data gathering has been started.');
console.time('data-gathering-max');
2021-04-13 21:53:58 +02:00
2021-08-07 22:38:07 +02:00
await this.prismaService.property.create({
2021-04-13 21:53:58 +02:00
data: {
key: 'LOCKED_DATA_GATHERING',
value: new Date().toISOString()
}
});
const symbols = await this.getSymbolsMax();
try {
await this.gatherSymbols(symbols);
2021-08-07 22:38:07 +02:00
await this.prismaService.property.upsert({
2021-04-13 21:53:58 +02:00
create: {
key: 'LAST_DATA_GATHERING',
value: new Date().toISOString()
},
update: { value: new Date().toISOString() },
where: { key: 'LAST_DATA_GATHERING' }
});
} catch (error) {
console.error(error);
}
2021-08-07 22:38:07 +02:00
await this.prismaService.property.delete({
2021-04-13 21:53:58 +02:00
where: {
key: 'LOCKED_DATA_GATHERING'
}
});
console.log('Max data gathering has been completed.');
console.timeEnd('data-gathering-max');
2021-04-13 21:53:58 +02:00
}
}
public async gatherProfileData(aDataGatheringItems?: IDataGatheringItem[]) {
console.log('Profile data gathering has been started.');
console.time('data-gathering-profile');
let dataGatheringItems = aDataGatheringItems;
if (!dataGatheringItems) {
dataGatheringItems = await this.getSymbolsProfileData();
}
const currentData = await this.dataProviderService.get(dataGatheringItems);
const symbolProfiles = await this.symbolProfileService.getSymbolProfiles(
dataGatheringItems.map(({ symbol }) => {
return symbol;
})
);
for (const [symbol, response] of Object.entries(currentData)) {
const symbolMapping = symbolProfiles.find((symbolProfile) => {
return symbolProfile.symbol === symbol;
})?.symbolMapping;
for (const dataEnhancer of this.dataEnhancers) {
try {
currentData[symbol] = await dataEnhancer.enhance({
response,
symbol: symbolMapping[dataEnhancer.getName()] ?? symbol
});
} catch (error) {
console.error(`Failed to enhance data for symbol ${symbol}`, error);
}
}
const {
assetClass,
assetSubClass,
countries,
currency,
dataSource,
name,
sectors
} = currentData[symbol];
try {
2021-08-07 22:38:07 +02:00
await this.prismaService.symbolProfile.upsert({
create: {
assetClass,
assetSubClass,
countries,
currency,
dataSource,
name,
sectors,
symbol
},
update: {
assetClass,
assetSubClass,
countries,
currency,
name,
sectors
},
where: {
dataSource_symbol: {
dataSource,
symbol
}
}
});
} catch (error) {
console.error(`${symbol}: ${error?.meta?.cause}`);
}
}
console.log('Profile data gathering has been completed.');
console.timeEnd('data-gathering-profile');
}
public async gatherSymbols(aSymbolsWithStartDate: IDataGatheringItem[]) {
2021-04-13 21:53:58 +02:00
let hasError = false;
for (const { dataSource, date, symbol } of aSymbolsWithStartDate) {
2021-04-13 21:53:58 +02:00
try {
const historicalData = await this.dataProviderService.getHistoricalRaw(
[{ dataSource, symbol }],
2021-04-13 21:53:58 +02:00
date,
new Date()
);
let currentDate = date;
let lastMarketPrice: number;
while (
isBefore(
currentDate,
new Date(
Date.UTC(
getYear(new Date()),
getMonth(new Date()),
getDate(new Date()),
0
)
)
)
) {
if (
2021-07-28 16:11:19 +02:00
historicalData[symbol]?.[format(currentDate, DATE_FORMAT)]
2021-04-13 21:53:58 +02:00
?.marketPrice
) {
lastMarketPrice =
2021-07-28 16:11:19 +02:00
historicalData[symbol]?.[format(currentDate, DATE_FORMAT)]
2021-04-13 21:53:58 +02:00
?.marketPrice;
}
try {
2021-08-07 22:38:07 +02:00
await this.prismaService.marketData.create({
2021-04-13 21:53:58 +02:00
data: {
dataSource,
2021-04-13 21:53:58 +02:00
symbol,
date: currentDate,
marketPrice: lastMarketPrice
}
});
} catch {}
// Count month one up for iteration
currentDate = new Date(
Date.UTC(
getYear(currentDate),
getMonth(currentDate),
getDate(currentDate) + 1,
0
)
);
}
} catch (error) {
hasError = true;
console.error(error);
}
}
await this.exchangeRateDataService.initialize();
2021-04-13 21:53:58 +02:00
if (hasError) {
throw '';
}
}
public async getIsInProgress() {
return await this.prismaService.property.findUnique({
where: { key: 'LOCKED_DATA_GATHERING' }
});
}
public async getLastDataGathering() {
const lastDataGathering = await this.prismaService.property.findUnique({
where: { key: 'LAST_DATA_GATHERING' }
});
if (lastDataGathering?.value) {
return new Date(lastDataGathering.value);
}
return undefined;
}
public async reset() {
console.log('Data gathering has been reset.');
await this.prismaService.property.deleteMany({
where: {
OR: [{ key: 'LAST_DATA_GATHERING' }, { key: 'LOCKED_DATA_GATHERING' }]
}
});
}
private getBenchmarksToGather(startDate: Date): IDataGatheringItem[] {
const benchmarksToGather = benchmarks.map(({ dataSource, symbol }) => {
return {
dataSource,
symbol,
date: startDate
};
});
if (this.configurationService.get('ENABLE_FEATURE_FEAR_AND_GREED_INDEX')) {
benchmarksToGather.push({
dataSource: DataSource.RAKUTEN,
date: startDate,
symbol: ghostfolioFearAndGreedIndexSymbol
});
}
return benchmarksToGather;
}
private async getSymbols7D(): Promise<IDataGatheringItem[]> {
2021-04-13 21:53:58 +02:00
const startDate = subDays(resetHours(new Date()), 7);
const symbolProfilesToGather = (
await this.prismaService.symbolProfile.findMany({
orderBy: [{ symbol: 'asc' }],
select: {
dataSource: true,
scraperConfiguration: true,
symbol: true
}
2021-04-20 21:52:01 +02:00
})
).map((symbolProfile) => {
return {
...symbolProfile,
date: startDate
};
});
2021-04-13 21:53:58 +02:00
const currencyPairsToGather = this.exchangeRateDataService
.getCurrencyPairs()
.map(({ dataSource, symbol }) => {
return {
dataSource,
symbol,
date: startDate
};
});
2021-04-13 21:53:58 +02:00
return [
...this.getBenchmarksToGather(startDate),
2021-04-13 21:53:58 +02:00
...currencyPairsToGather,
...symbolProfilesToGather
2021-04-13 21:53:58 +02:00
];
}
private async getSymbolsMax(): Promise<IDataGatheringItem[]> {
const startDate =
(
await this.prismaService.order.findFirst({
orderBy: [{ date: 'asc' }]
})
)?.date ?? new Date();
2021-04-13 21:53:58 +02:00
const currencyPairsToGather = this.exchangeRateDataService
.getCurrencyPairs()
.map(({ dataSource, symbol }) => {
return {
dataSource,
symbol,
date: startDate
};
});
2021-04-13 21:53:58 +02:00
const symbolProfilesToGather = (
await this.prismaService.symbolProfile.findMany({
orderBy: [{ symbol: 'asc' }],
select: {
dataSource: true,
Order: {
orderBy: [{ date: 'asc' }],
select: { date: true },
take: 1
},
scraperConfiguration: true,
symbol: true
}
})
).map((symbolProfile) => {
return {
...symbolProfile,
date: symbolProfile.Order?.[0]?.date ?? startDate
};
});
return [
...this.getBenchmarksToGather(startDate),
...currencyPairsToGather,
...symbolProfilesToGather
];
2021-04-13 21:53:58 +02:00
}
private async getSymbolsProfileData(): Promise<IDataGatheringItem[]> {
const startDate = subDays(resetHours(new Date()), 7);
2021-08-07 22:38:07 +02:00
const distinctOrders = await this.prismaService.order.findMany({
distinct: ['symbol'],
orderBy: [{ symbol: 'asc' }],
select: { dataSource: true, symbol: true }
});
return [...this.getBenchmarksToGather(startDate), ...distinctOrders].filter(
(distinctOrder) => {
return (
distinctOrder.dataSource !== DataSource.GHOSTFOLIO &&
distinctOrder.dataSource !== DataSource.RAKUTEN
);
}
);
}
2021-04-13 21:53:58 +02:00
private async isDataGatheringNeeded() {
const lastDataGathering = await this.getLastDataGathering();
2021-04-13 21:53:58 +02:00
2021-08-07 22:38:07 +02:00
const isDataGatheringLocked = await this.prismaService.property.findUnique({
2021-04-13 21:53:58 +02:00
where: { key: 'LOCKED_DATA_GATHERING' }
});
const diffInHours = differenceInHours(new Date(), lastDataGathering);
2021-04-13 21:53:58 +02:00
return (diffInHours >= 1 || !lastDataGathering) && !isDataGatheringLocked;
}
}