[javascript] qwe

Viewer

  1. const request = require('node-fetch')
  2. const BigNumber = require('bignumber.js')
  3.  
  4. class ETHPrice {
  5.   getKlines({ startTime, endTime, interval = '1m', limit }) {
  6.     const params = {
  7.       symbol: 'ETHUSDT',
  8.       startTime,
  9.       interval
  10.     }
  11.     if (limit) params.limit = limit
  12.     if (endTime) params.endTime = endTime
  13.  
  14.     const queryString = new URLSearchParams(params)
  15.  
  16.     return request(`https://www.binance.com/api/v1/klines?${queryString}`).then(res => res.json())
  17.   }
  18.  
  19.   async getPriceAt(time, { includePriceTime = false } = {}) {
  20.     const startTime = new Date(time).getTime()
  21.     const endTime = startTime + 15 * 60e3
  22.  
  23.     const klines = await this.getKlines({ startTime, endTime, limit: 5 })
  24.     if (!klines || !klines.length) throw new Error('Unable to fetch klines')
  25.  
  26.     const [priceTime, open] = klines[0]
  27.     const price = new BigNumber(open)
  28.     if (price.isNaN()) throw new Error(`Price ${open} is not a number`)
  29.  
  30.     if (!includePriceTime) return price.toNumber()
  31.  
  32.     return {
  33.       time: new Date(priceTime),
  34.       price: price.toNumber()
  35.     }
  36.   }
  37.  
  38.   async getPrices({ startTime, endTime, interval, limit }) {
  39.     const klines = await this.getKlines({ startTime, endTime, interval, limit })
  40.     if (!klines || !klines.length) throw new Error('Unable to fetch klines')
  41.  
  42.     return klines.map(=> {
  43.       const [time, open] = k
  44.       const price = new BigNumber(open)
  45.       if (price.isNaN()) throw new Error(`Price ${open} is not a number`)
  46.  
  47.       return {
  48.         time: new Date(time),
  49.         price: price.toNumber()
  50.       }
  51.     })
  52.   }
  53. }
  54.  
  55. const ethPrice = new ETHPrice()
  56. module.exports = ethPrice

Editor

You can edit this paste and save as new:


File Description
  • qwe
  • Paste Code
  • 30 Jun-2022
  • 1.64 Kb
You can Share it: