diff --git a/calculate.js b/calculate.js index fc3dd17..9466229 100644 --- a/calculate.js +++ b/calculate.js @@ -30,18 +30,40 @@ module.exports = { // get all the years you need from 1 - 10 for (let i = 1; i < 11; i++) { - const y = new Date(new Date().setFullYear(new Date().getFullYear() - i)).toISOString().slice(0, 10) - datelist.push(y) - } - for (let j = 0; j < historical.length; j++) { - const hdate = historical[j]['date'] - if (datelist.includes(hdate)) { - hist_entries.push(historical[j]) + const targetDate = new Date(new Date().setFullYear(new Date().getFullYear() - i)) + const targetDateStr = targetDate.toISOString().slice(0, 10) + + // Find the closest date in historical data + let closestEntry = null + let minDiff = Infinity + + for (let j = 0; j < historical.length; j++) { + const entryDate = new Date(historical[j]['date']) + const diff = Math.abs(entryDate - targetDate) + + if (diff < minDiff) { + minDiff = diff + closestEntry = historical[j] + } + } + + if (closestEntry) { + hist_entries.push(closestEntry) } } // console.log(hist_entries) let final_list = [] - let today_sats = await this.bfx() + + // Try to get current price from API, fallback to latest historical data if API fails + let today_sats + try { + today_sats = await this.bfx() + } catch (apiError) { + console.log("API failed, using latest historical data as fallback") + // Use the most recent entry in historical data as today's price + today_sats = historical[historical.length - 1]['sateur_rate'] + } + for (var v = 0; v < hist_entries.length; v++) { const date = new Date(hist_entries[v]['date']) year = date.getFullYear();