diff --git a/src/controllers/stats.controller.ts b/src/controllers/stats.controller.ts index 03b7330..5c3353a 100644 --- a/src/controllers/stats.controller.ts +++ b/src/controllers/stats.controller.ts @@ -139,7 +139,7 @@ class StatsController { const allRates = ( (await Pair.findAll({ - attributes: ['id', 'rate'], + attributes: ['id', 'rate', 'volume'], include: [ { model: Currency, diff --git a/src/models/ExchangeTransactions.ts b/src/models/ExchangeTransactions.ts index e57dd25..511c669 100644 --- a/src/models/ExchangeTransactions.ts +++ b/src/models/ExchangeTransactions.ts @@ -10,6 +10,56 @@ import Order from '../schemes/Order'; import Pair from '../schemes/Pair.js'; class ExchangeModel { + async runPairStatsDaemon() { + (async () => { + while (true) { + console.log('Running pair stats update...'); + const date = +new Date(); + + try { + const pairs = await Pair.findAll({ + attributes: ['id'], + }); + + for (const pair of pairs) { + const statsResult = await this.calculatePairStats(pair.id.toString()); + + if (!statsResult.success || typeof statsResult.data === 'string') { + throw new Error('Error while getting pair stats'); + } + + const stats = statsResult.data; + + await Pair.update( + { + rate: stats.rate, + coefficient: stats.coefficient, + high: stats.high, + low: stats.low, + volume: stats.volume, + }, + { + where: { + id: pair.id, + }, + }, + ); + + sendUpdatePairStatsMessage(io, pair.id.toString(), stats); + } + } catch (error) { + console.log(error); + } + + console.log( + `Pair stats update completed in ${Math.floor((+new Date() - date) / 1000)}s`, + ); + + await new Promise((resolve) => setTimeout(resolve, 1000 * 60 * 5)); + } + })(); + } + private async calculatePairStats(pairId: string) { try { const date = new Date(); diff --git a/src/server.ts b/src/server.ts index 3c8230d..2316650 100644 --- a/src/server.ts +++ b/src/server.ts @@ -21,6 +21,7 @@ import sequelize from './sequelize'; import Currency, { Asset } from './schemes/Currency'; import User from './schemes/User'; import statsRouter from './routes/stats.router'; +import exchangeModel from './models/ExchangeTransactions'; const PORT = process.env.PORT || 3000; @@ -67,6 +68,7 @@ process.on('unhandledRejection', (reason, promise) => { } assetsUpdateChecker.run(); + exchangeModel.runPairStatsDaemon(); socketStart(io);