@icgio/icg-utils 1.9.73 → 1.9.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/rates.js CHANGED
@@ -1,4 +1,3 @@
1
- const _ = require('lodash')
2
1
  const needle = require('needle')
3
2
  const Limiter = require('./rate-limiter.js')
4
3
 
@@ -7,8 +6,6 @@ let limiter = new Limiter({
7
6
  interval_concurrent: 3000,
8
7
  })
9
8
 
10
- const options = {}
11
-
12
9
  // --- Forex rates ---
13
10
 
14
11
  function get_forex_rate_usd(curs, cb) {
@@ -29,214 +26,86 @@ function get_forex_rate_usd(curs, cb) {
29
26
  })
30
27
  }
31
28
 
32
- // --- Crypto rates (Coinpaprika + exchange orderbook) ---
29
+ // --- Crypto rates: 'curs' = Coinpaprika USD prices of a symbol list, 'curs_dict' = { cur: exchange } orderbook mids ---
33
30
 
34
- let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type) => {
35
- if (type === 'cur') {
36
- let cur = pair_or_pairs_or_cur_curs
37
- limiter.process(needle.get, 'https://api.coinpaprika.com/v1/tickers', (err, res, body) => {
38
- if (err) {
39
- console.error(cur, err)
40
- cb(null)
41
- return
42
- }
43
- if (body && Array.isArray(body)) {
44
- for (let ticker of body) {
45
- if (ticker.symbol.toUpperCase() === cur.toUpperCase()) {
46
- cb(ticker.quotes.USD.price)
47
- return
48
- }
49
- }
50
- }
51
- console.error('coinpaprika cur not found:', cur)
52
- cb(null)
53
- })
54
- } else if (type === 'curs') {
55
- let curs = pair_or_pairs_or_cur_curs
56
- let curs_upper = curs.map((c) => c.toUpperCase())
57
- let result = {}
58
- limiter.process(needle.get, 'https://api.coinpaprika.com/v1/tickers', (err, res, body) => {
59
- if (err) {
60
- console.error(err)
61
- cb(result)
62
- return
63
- }
64
- if (body && Array.isArray(body)) {
65
- for (let ticker of body) {
66
- let symbol = ticker.symbol.toUpperCase()
67
- if (curs_upper.includes(symbol)) {
68
- let price = ticker.quotes.USD.price
69
- result[symbol] = { USD: price, USDT: price }
70
- }
71
- }
72
- }
73
- cb(result)
74
- })
75
- } else if (type === 'curs_dict') {
76
- _fetch_exchange_rates(cb, pair_or_pairs_or_cur_curs)
77
- } else {
78
- _fetch_all_coinpaprika(cb)
79
- }
31
+ function get_crypto_rates(cb, curs, type) {
32
+ if (type === 'curs') return fetch_coinpaprika_rates(cb, curs)
33
+ if (type === 'curs_dict') return fetch_exchange_rates(cb, curs)
34
+ throw new Error(`crypto_rates: unsupported type "${type}"`)
80
35
  }
81
36
 
82
- // --- curs_dict: per-exchange orderbook mid-price ---
37
+ function fetch_coinpaprika_rates(cb, curs) {
38
+ const wanted = new Set(curs.map((c) => c.toUpperCase()))
39
+ const result = {}
40
+ limiter.process(needle.get, 'https://api.coinpaprika.com/v1/tickers', (err, res, body) => {
41
+ if (err) console.error(err)
42
+ // Tickers come ranked, so the first one with a symbol is the main coin behind it
43
+ for (const ticker of Array.isArray(body) ? body : []) {
44
+ const symbol = ticker.symbol.toUpperCase()
45
+ if (wanted.has(symbol) && !result[symbol]) {
46
+ const price = ticker.quotes.USD.price
47
+ result[symbol] = { USD: price, USDT: price }
48
+ }
49
+ }
50
+ cb(result)
51
+ })
52
+ }
83
53
 
84
- function _fetch_exchange_rates(cb, curs_dict) {
85
- let length = _.keys(curs_dict).length
86
- let result = {}
87
- let completed = 0
54
+ // <cur>/USDT orderbook per exchange: [depth url, response body -> { asks, bids }]
55
+ const BOOKS = {
56
+ binance: [(cur) => `https://www.binance.com/api/v3/depth?symbol=${cur}USDT&limit=20`, (body) => body],
57
+ binancefutures: [(cur) => `https://fapi.binance.com/fapi/v1/depth?symbol=${cur}USDT&limit=20`, (body) => body],
58
+ biconomy: [(cur) => `https://api.biconomy.com/api/v1/depth?symbol=${cur}_USDT&size=5`, (body) => body],
59
+ bingx: [(cur) => `https://open-api.bingx.com/openApi/spot/v1/market/depth?symbol=${cur}-USDT&limit=20`, (body) => body.data],
60
+ bitget: [(cur) => `https://api.bitget.com/api/v2/spot/market/orderbook?symbol=${cur}USDT&type=step0`, (body) => body.data],
61
+ bybit: [(cur) => `https://api.bybit.com/v5/market/orderbook?category=spot&symbol=${cur}USDT&limit=20`, (body) => ({ asks: body.result.a, bids: body.result.b })],
62
+ coinex: [(cur) => `https://api.coinex.com/v1/market/depth?market=${cur.toLowerCase()}usdt&limit=20&merge=0`, (body) => body.data],
63
+ coinstore: [
64
+ (cur) => `https://api.coinstore.com/api/v1/market/depth/${(cur === 'SWAGG' ? 'SWAGGERC20' : cur).toLowerCase()}usdt`,
65
+ (body) => ({ asks: body.data.a, bids: body.data.b }),
66
+ ],
67
+ cryptocom: [(cur) => `https://api.crypto.com/v2/public/get-book?instrument_name=${cur}_USDT&depth=20`, (body) => body.result.data[0]],
68
+ // limit=1 because asks come back worst-first
69
+ digifinex: [(cur) => `https://openapi.digifinex.com/v3/order_book?symbol=${cur}_USDT&limit=1`, (body) => body],
70
+ gate: [(cur) => `https://api.gateio.ws/api/v4/spot/order_book?currency_pair=${cur}_USDT`, (body) => body],
71
+ htx: [(cur) => `https://api.htx.com/market/depth?symbol=${cur.toLowerCase()}usdt&type=step0`, (body) => body.tick],
72
+ kucoin: [(cur) => `https://api.kucoin.com/api/v1/market/orderbook/level2_100?symbol=${cur}-USDT`, (body) => body.data],
73
+ lbank: [(cur) => `https://api.lbank.info/v2/depth.do?symbol=${cur.toLowerCase()}_usdt&size=10`, (body) => body.data],
74
+ mexc: [(cur) => `https://api.mexc.com/api/v3/depth?symbol=${cur}USDT`, (body) => body],
75
+ okx: [(cur) => `https://www.okx.com/api/v5/market/books?instId=${cur}-USDT&sz=20`, (body) => (typeof body === 'string' ? JSON.parse(body) : body).data[0]],
76
+ p2b: [(cur) => `https://api.p2pb2b.com/api/v2/public/depth/result?market=${cur}_USDT`, (body) => body.result],
77
+ weex: [(cur) => `https://api-spot.weex.com/api/v2/market/depth?symbol=${cur.toUpperCase()}USDT_SPBL&type=step0&limit=200`, (body) => body.data],
78
+ xt: [(cur) => `https://sapi.xt.com/v4/public/depth?symbol=${cur.toLowerCase()}_usdt&limit=20`, (body) => body.result],
79
+ }
88
80
 
89
- if (length === 0) {
90
- cb(result)
91
- return
81
+ function fetch_exchange_rates(cb, curs_dict) {
82
+ const result = {}
83
+ let pending = Object.keys(curs_dict).length
84
+ if (pending === 0) return cb(result)
85
+ const done = (cur, rate) => {
86
+ if (Number.isFinite(rate)) result[cur] = { USD: rate, USDT: rate }
87
+ if (--pending === 0) cb(result)
92
88
  }
93
-
94
- function onResult(cur, rate) {
95
- if (rate !== null) {
96
- result[cur] = { USD: rate, USDT: rate }
97
- }
98
- completed++
99
- if (completed === length) {
100
- cb(result)
89
+ for (const cur in curs_dict) {
90
+ const exchange = curs_dict[cur]
91
+ if (!Object.hasOwn(BOOKS, exchange)) {
92
+ console.error(`crypto_rates: unsupported exchange "${exchange}" for ${cur}`)
93
+ done(cur, null)
94
+ continue
101
95
  }
102
- }
103
-
104
- function fetchMidPrice(cur, exchange, url, parseBody) {
105
- limiter.process(needle.get, url, (err, res, body) => {
96
+ const [url, book] = BOOKS[exchange]
97
+ limiter.process(needle.get, url(cur), (err, res, body) => {
98
+ let rate = null
106
99
  try {
107
100
  if (err) throw err
108
- onResult(cur, parseBody(body))
101
+ const { asks, bids } = book(body)
102
+ rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
109
103
  } catch (error) {
110
104
  console.error(`${exchange} ${cur}:`, error.message || error)
111
- onResult(cur, null)
112
- }
113
- })
114
- }
115
-
116
- function midOf(asks, bids) {
117
- return (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
118
- }
119
-
120
- for (let cur in curs_dict) {
121
- let exchange = curs_dict[cur]
122
- let pair
123
-
124
- if (exchange === 'binance') {
125
- pair = cur + 'USDT'
126
- fetchMidPrice(cur, exchange, `https://www.binance.com/api/v3/depth?symbol=${pair}&limit=20`, (body) => midOf(body.asks, body.bids))
127
- } else if (exchange === 'binancefutures') {
128
- pair = cur + 'USDT'
129
- fetchMidPrice(cur, exchange, `https://fapi.binance.com/fapi/v1/depth?symbol=${pair}&limit=20`, (body) => midOf(body.asks, body.bids))
130
- } else if (exchange === 'biconomy') {
131
- pair = cur + '_USDT'
132
- fetchMidPrice(cur, exchange, `https://api.biconomy.com/api/v1/depth?symbol=${pair}&size=5`, (body) => midOf(body.asks, body.bids))
133
- } else if (exchange === 'bingx') {
134
- pair = cur + '-USDT'
135
- fetchMidPrice(cur, exchange, `https://open-api.bingx.com/openApi/spot/v1/market/depth?symbol=${pair}&limit=20`, (body) => midOf(body.data.asks, body.data.bids))
136
- } else if (exchange === 'bitget') {
137
- pair = cur + 'USDT'
138
- fetchMidPrice(cur, exchange, `https://api.bitget.com/api/v2/spot/market/orderbook?symbol=${pair}&type=step0`, (body) => midOf(body.data.asks, body.data.bids))
139
- } else if (exchange === 'bybit') {
140
- pair = cur + 'USDT'
141
- fetchMidPrice(cur, exchange, `https://api.bybit.com/v5/market/orderbook?category=spot&symbol=${pair}&limit=20`, (body) => midOf(body.result.a, body.result.b))
142
- } else if (exchange === 'coinex') {
143
- pair = cur.toLowerCase() + 'usdt'
144
- fetchMidPrice(cur, exchange, `https://api.coinex.com/v1/market/depth?market=${pair}&limit=20&merge=0`, (body) => midOf(body.data.asks, body.data.bids))
145
- } else if (exchange === 'coinstore') {
146
- let storeCur = cur === 'SWAGG' ? 'SWAGGERC20' : cur
147
- pair = storeCur.toLowerCase() + 'usdt'
148
- fetchMidPrice(cur, exchange, `https://api.coinstore.com/api/v1/market/depth/${pair}`, (body) => midOf(body.data.a, body.data.b))
149
- } else if (exchange === 'cryptocom') {
150
- pair = cur + '_USDT'
151
- fetchMidPrice(cur, exchange, `https://api.crypto.com/v2/public/get-book?instrument_name=${pair}&depth=20`, (body) =>
152
- midOf(body.result.data[0].asks, body.result.data[0].bids),
153
- )
154
- } else if (exchange === 'digifinex') {
155
- pair = cur + '_USDT'
156
- fetchMidPrice(cur, exchange, `https://openapi.digifinex.com/v3/spot/orderbook?symbol=${pair}`, (body) => midOf(body.data.asks, body.data.bids))
157
- } else if (exchange === 'gate') {
158
- pair = cur + '_USDT'
159
- fetchMidPrice(cur, exchange, `https://api.gateio.ws/api/v4/spot/order_book?currency_pair=${pair}`, (body) => midOf(body.asks, body.bids))
160
- } else if (exchange === 'htx') {
161
- pair = cur.toLowerCase() + 'usdt'
162
- fetchMidPrice(cur, exchange, `https://api.htx.com/market/depth?symbol=${pair}&type=step0`, (body) => midOf(body.tick.asks, body.tick.bids))
163
- } else if (exchange === 'kucoin') {
164
- pair = cur + '-USDT'
165
- fetchMidPrice(cur, exchange, `https://api.kucoin.com/api/v1/market/orderbook/level2_100?symbol=${pair}`, (body) => midOf(body.data.asks, body.data.bids))
166
- } else if (exchange === 'lbank') {
167
- pair = cur.toLowerCase() + '_usdt'
168
- fetchMidPrice(cur, exchange, `https://api.lbank.info/v2/depth.do?symbol=${pair}&size=10`, (body) => midOf(body.data.asks, body.data.bids))
169
- } else if (exchange === 'mexc') {
170
- pair = cur + 'USDT'
171
- fetchMidPrice(cur, exchange, `https://api.mexc.com/api/v3/depth?symbol=${pair}`, (body) => midOf(body.asks, body.bids))
172
- } else if (exchange === 'okx') {
173
- pair = cur + 'USDT'
174
- fetchMidPrice(cur, exchange, `https://www.okx.com/api/v5/market/books?instId=${pair}&sz=20`, (body) => {
175
- if (typeof body === 'string') body = JSON.parse(body)
176
- return midOf(body.data[0].asks, body.data[0].bids)
177
- })
178
- } else if (exchange === 'p2b') {
179
- pair = cur + '_USDT'
180
- fetchMidPrice(cur, exchange, `https://api.p2pb2b.com/api/v2/public/depth/result?market=${pair}`, (body) => midOf(body.result.asks, body.result.bids))
181
- } else if (exchange === 'weex') {
182
- pair = cur.toUpperCase() + 'USDT'
183
- fetchMidPrice(cur, exchange, `https://api-spot.weex.com/api/v2/market/depth?symbol=${pair}_SPBL&type=step0&limit=200`, (body) => midOf(body.data.asks, body.data.bids))
184
- } else if (exchange === 'xt') {
185
- pair = cur.toLowerCase() + '_usdt'
186
- fetchMidPrice(cur, exchange, `https://sapi.xt.com/v4/public/depth?symbol=${pair}&limit=20`, (body) => midOf(body.result.asks, body.result.bids))
187
- } else {
188
- console.error(`crypto_rates: unsupported exchange "${exchange}" for ${cur}`)
189
- onResult(cur, null)
190
- }
191
- }
192
- }
193
-
194
- // --- Default mode: fetch all coinpaprika tickers ---
195
-
196
- function _fetch_all_coinpaprika(cb) {
197
- let result = {}
198
- function fetch(cb) {
199
- limiter.process(needle.get, 'https://api.coinpaprika.com/v1/tickers', options, (err, res, body) => {
200
- console.log('fetching coinpaprika rate: body length', _.get(body, 'length', body))
201
- if (body && Array.isArray(body) && body.length > 0) {
202
- for (let coin of body) {
203
- let symbol = coin.symbol
204
- if (!symbol || !coin.quotes || !coin.quotes.USD || !coin.quotes.USD.price) {
205
- continue
206
- }
207
- symbol = symbol.toUpperCase()
208
- if (symbol === 'BAT' && coin.id !== 'bat-basic-attention-token') {
209
- continue
210
- } else if (symbol === 'SBTC' && coin.id !== 'sbtc-super-bitcoin') {
211
- continue
212
- }
213
- result[symbol] = {
214
- USD: parseFloat(coin.quotes.USD.price),
215
- USDT: parseFloat(coin.quotes.USD.price),
216
- '24h_change': parseFloat(coin.quotes.USD.percent_change_24h),
217
- '24h_volume_usd': parseFloat(coin.quotes.USD.volume_24h),
218
- rank: parseInt(coin.rank) || 10000,
219
- market_cap: parseInt(coin.quotes.USD.market_cap),
220
- update_time: new Date(coin.last_updated),
221
- }
222
- }
223
- // Calculate BTC/ETH rates for all currencies
224
- for (let cur in result) {
225
- if (result.BTC) result[cur].BTC = result[cur].USD / result.BTC.USD
226
- if (result.ETH) result[cur].ETH = result[cur].USD / result.ETH.USD
227
- }
228
- cb(result)
229
- } else {
230
- console.error('Coinpaprika error:', err || (body && body.error) || body)
231
- setTimeout(() => {
232
- console.log('fetching coinpaprika rate: retry')
233
- fetch(cb)
234
- }, 60000)
235
105
  }
106
+ done(cur, rate)
236
107
  })
237
108
  }
238
- console.log('fetching coinpaprika rate: starting')
239
- fetch(cb)
240
109
  }
241
110
 
242
111
  module.exports = {