diff --git a/src/api.js b/src/api.js index b300e71..1fcd5cc 100644 --- a/src/api.js +++ b/src/api.js @@ -7,46 +7,47 @@ const queue = new PQueue({ interval: 1000, intervalCap: 10 }); export async function fetchRate(pair) { const key = pair.toUpperCase(); + const max_retries = 3; - return queue.add(async () => { - for (let attempt = 1; attempt <= 3; attempt++) { - let timeout; - try { + for (let attempt = 1; attempt <= max_retries; attempt++) { + let timeout; + try { + const res = await queue.add(async () => { const controller = new AbortController(); timeout = setTimeout(() => controller.abort(), 5000); - const res = await fetch(`https://api.uphold.com/v0/ticker/${key}`, { + return fetch(`https://api.uphold.com/v0/ticker/${key}`, { signal: controller.signal, }); + }); - clearTimeout(timeout); + clearTimeout(timeout); - if (res.status === 429) { - incrementReq("ratelimit"); - throw new Error("Rate limited"); - } - - if (!res.ok) { - incrementReq("fail"); - throw new Error(`HTTP ${res.status}`); - } - - incrementReq("success"); - - const data = await res.json(); - - if (!data.ask || isNaN(parseFloat(data.ask))) { - throw new Error("Invalid ask price"); - } - - return new BigNumber(data.ask); - } catch (err) { - clearTimeout(timeout); - if (attempt === 3) throw err; - await new Promise((r) => setTimeout(r, 500 * Math.pow(2, attempt - 1))); + if (res.status === 429) { + incrementReq("ratelimit"); + throw new Error("Rate limited"); } + + if (!res.ok) { + incrementReq("fail"); + throw new Error(`HTTP ${res.status}`); + } + + incrementReq("success"); + + const data = await res.json(); + + if (!data.ask || isNaN(parseFloat(data.ask))) { + throw new Error("Invalid ask price"); + } + + return new BigNumber(data.ask); + } catch (err) { + clearTimeout(timeout); + if (attempt === 3) throw err; + await new Promise((r) => setTimeout(r, 500 * Math.pow(2, attempt - 1))); } - }); + } } export async function prefetchRates(pairs) { diff --git a/src/bot.js b/src/bot.js index 455fcaa..9f0a345 100644 --- a/src/bot.js +++ b/src/bot.js @@ -39,6 +39,7 @@ export class Bot { this.lastPrice = price; logger.info(`[${this.pair}] Initial price: ${price.toFixed(2)}`); } else { + // Using BigNumber const change = price .minus(this.lastPrice) .dividedBy(this.lastPrice) @@ -69,6 +70,7 @@ export class Bot { }; try { + // onAlert must be fast await this.onAlert(alertData); } catch (err) { logger.error(