From 0230f95001875039995c6f68a3adc80f85ce0eea Mon Sep 17 00:00:00 2001 From: Mononaut Date: Mon, 8 Jan 2024 22:33:11 +0000 Subject: [PATCH] Fix bad coinbase price url, switch to median prices --- backend/src/tasks/price-feeds/coinbase-api.ts | 4 ++-- backend/src/tasks/price-updater.ts | 14 ++++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/backend/src/tasks/price-feeds/coinbase-api.ts b/backend/src/tasks/price-feeds/coinbase-api.ts index 424ac8867..d2c6d063a 100644 --- a/backend/src/tasks/price-feeds/coinbase-api.ts +++ b/backend/src/tasks/price-feeds/coinbase-api.ts @@ -5,14 +5,14 @@ class CoinbaseApi implements PriceFeed { public name: string = 'Coinbase'; public currencies: string[] = ['USD', 'EUR', 'GBP']; - public url: string = 'https://api.coinbase.com/v2/prices/spot?currency='; + public url: string = 'https://api.coinbase.com/v2/prices/BTC-{CURRENCY}/spot'; public urlHist: string = 'https://api.exchange.coinbase.com/products/BTC-{CURRENCY}/candles?granularity={GRANULARITY}'; constructor() { } public async $fetchPrice(currency): Promise { - const response = await query(this.url + currency); + const response = await query(this.url.replace('{CURRENCY}', currency)); if (response && response['data'] && response['data']['amount']) { return parseInt(response['data']['amount'], 10); } else { diff --git a/backend/src/tasks/price-updater.ts b/backend/src/tasks/price-updater.ts index fd799fb87..0d5ca5958 100644 --- a/backend/src/tasks/price-updater.ts +++ b/backend/src/tasks/price-updater.ts @@ -23,6 +23,14 @@ export interface PriceHistory { [timestamp: number]: ApiPrice; } +function getMedian(arr: number[]): number { + const sortedArr = arr.slice().sort((a, b) => a - b); + const mid = Math.floor(sortedArr.length / 2); + return sortedArr.length % 2 !== 0 + ? sortedArr[mid] + : (sortedArr[mid - 1] + sortedArr[mid]) / 2; +} + class PriceUpdater { public historyInserted = false; private timeBetweenUpdatesMs = 360_0000 / config.MEMPOOL.PRICE_UPDATES_PER_HOUR; @@ -173,7 +181,7 @@ class PriceUpdater { if (prices.length === 0) { this.latestPrices[currency] = -1; } else { - this.latestPrices[currency] = Math.round((prices.reduce((partialSum, a) => partialSum + a, 0)) / prices.length); + this.latestPrices[currency] = Math.round(getMedian(prices)); } } @@ -300,9 +308,7 @@ class PriceUpdater { if (grouped[time][currency].length === 0) { continue; } - prices[currency] = Math.round((grouped[time][currency].reduce( - (partialSum, a) => partialSum + a, 0) - ) / grouped[time][currency].length); + prices[currency] = Math.round(getMedian(grouped[time][currency])); } await PricesRepository.$savePrices(parseInt(time, 10), prices); ++totalInserted;