@icgio/icg-utils 1.9.41 → 1.9.43

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/README.md CHANGED
@@ -1,2 +1,193 @@
1
- # icgio Utils
2
- Utils package.
1
+ # ICG Utils
2
+
3
+ A comprehensive utility package for the ICG trading system, providing common functions for rate fetching, data processing, logging, and orderbook manipulation.
4
+
5
+ ## Features
6
+
7
+ - **Crypto Rate Fetching**: Get cryptocurrency prices from CoinMarketCap and CoinGecko
8
+ - **Forex Rates**: Fetch foreign exchange rates
9
+ - **InfluxDB Integration**: Write and query time-series data
10
+ - **Orderbook Utilities**: Advanced orderbook processing and combination
11
+ - **Rate Limiting**: Control request frequency to avoid API throttling
12
+ - **Observable Pattern**: Reactive data streams implementation
13
+ - **OHLCV Processing**: Candlestick data aggregation and manipulation
14
+ - **Logging**: Structured logging with Winston
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @icgio/icg-utils
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ### Crypto Rates
25
+
26
+ ```javascript
27
+ const { coinmarketcap, coingecko } = require('@icgio/icg-utils')
28
+
29
+ // Get crypto prices
30
+ const btc_price = await coinmarketcap.get_price('BTC')
31
+ const eth_price = await coingecko.get_price('ETH')
32
+ ```
33
+
34
+ ### InfluxDB
35
+
36
+ ```javascript
37
+ const { influx } = require('@icgio/icg-utils')
38
+
39
+ // Write data points
40
+ await influx.write_point(measurement, tags, fields)
41
+
42
+ // Query data
43
+ const results = await influx.query(query)
44
+ ```
45
+
46
+ ### Rate Limiter
47
+
48
+ ```javascript
49
+ const { rate_limiter: RateLimiter } = require('@icgio/icg-utils')
50
+
51
+ const limiter = new RateLimiter({
52
+ max_concurrent: 5,
53
+ interval_concurrent: 1000,
54
+ abandon_tx: false,
55
+ only_same_args: false
56
+ })
57
+
58
+ // Process function with rate limiting
59
+ await limiter.process(async_function, arg1, arg2)
60
+ ```
61
+
62
+ ### Orderbook Utilities
63
+
64
+ ```javascript
65
+ const { utils } = require('@icgio/icg-utils')
66
+
67
+ // Get position by volume
68
+ const position = utils.vol_position(orderbook, target_volume)
69
+
70
+ // Get position by sum (quote currency)
71
+ const position = utils.sum_position(orderbook, target_sum)
72
+
73
+ // Combine orderbooks from multiple exchanges
74
+ const combined = utils.combine_orderbooks(orderbooks_dict, depth)
75
+
76
+ // Find arbitrage opportunities
77
+ const opportunities = utils.arb_opportunities_from_combined_orderbook(
78
+ combined_orderbook,
79
+ profit_percentage,
80
+ amount_cap
81
+ )
82
+
83
+ // Parse trading pair
84
+ const [base, quote] = utils.parse_pair('BTCUSDT') // ['BTC', 'USDT']
85
+ ```
86
+
87
+ ### Observable
88
+
89
+ ```javascript
90
+ const { observable } = require('@icgio/icg-utils')
91
+
92
+ // Create observable
93
+ const obs = observable.create()
94
+
95
+ // Subscribe to changes
96
+ obs.subscribe((value) => {
97
+ console.log('Value changed:', value)
98
+ })
99
+
100
+ // Update value
101
+ obs.next(new_value)
102
+ ```
103
+
104
+ ### OHLCV
105
+
106
+ ```javascript
107
+ const { ohlcv } = require('@icgio/icg-utils')
108
+
109
+ // Process OHLCV data
110
+ const processed = ohlcv.aggregate(candles, interval)
111
+ ```
112
+
113
+ ### Logger
114
+
115
+ ```javascript
116
+ const { logger } = require('@icgio/icg-utils')
117
+
118
+ logger.info('Info message')
119
+ logger.error('Error message')
120
+ logger.warn('Warning message')
121
+ ```
122
+
123
+ ### Constants
124
+
125
+ ```javascript
126
+ const { constants } = require('@icgio/icg-utils')
127
+ ```
128
+
129
+ ## Project Structure
130
+
131
+ ```
132
+ icg-utils/
133
+ ├── index.js # Main entry point
134
+ ├── lib/
135
+ │ ├── crypto-rates.js # CoinMarketCap/CoinGecko integration
136
+ │ ├── dex-rate.js # DEX rate fetching
137
+ │ ├── forex-rate.js # Forex rate fetching
138
+ │ ├── influxdb.js # InfluxDB client
139
+ │ ├── ip.js # IP utilities
140
+ │ ├── logger.js # Winston logger
141
+ │ ├── observable.js # Observable pattern
142
+ │ ├── ohlcv.js # OHLCV processing
143
+ │ ├── rate-limiter.js # Rate limiting
144
+ │ └── utils.js # General utilities
145
+ ├── constants/
146
+ │ ├── coins-map-coingecko.js # CoinGecko mappings
147
+ │ └── coins-map-coinmarketcap.js # CMC mappings
148
+ └── package.json
149
+ ```
150
+
151
+ ## Key Utility Functions
152
+
153
+ ### Orderbook Processing
154
+
155
+ | Function | Description |
156
+ |----------|-------------|
157
+ | `vol_position` | Find position in orderbook by volume |
158
+ | `sum_position` | Find position in orderbook by quote sum |
159
+ | `price_position` | Find position in orderbook by price |
160
+ | `level_position` | Find position by orderbook level |
161
+ | `combine_orderbooks` | Merge orderbooks from multiple exchanges |
162
+ | `arb_opportunities_from_combined_orderbook` | Find arbitrage opportunities |
163
+
164
+ ### General Utilities
165
+
166
+ | Function | Description |
167
+ |----------|-------------|
168
+ | `parse_pair` | Parse trading pair into base/quote |
169
+ | `reverse_pair` | Reverse a trading pair |
170
+ | `round` | Round number to precision |
171
+ | `ordered_dict` | Sorted dictionary for orderbooks |
172
+ | `number_with_commas` | Format numbers with comma separators |
173
+
174
+ ## Dependencies
175
+
176
+ | Package | Purpose |
177
+ |---------|---------|
178
+ | `@influxdata/influxdb-client` | InfluxDB v2 client |
179
+ | `@influxdata/influxdb-client-apis` | InfluxDB management APIs |
180
+ | `lodash` | Utility library |
181
+ | `needle` | HTTP client |
182
+ | `winston` | Logging framework |
183
+ | `csv-parse` | CSV parsing |
184
+
185
+ ## Code Style
186
+
187
+ - CommonJS modules (`require()` / `module.exports`)
188
+ - Variable naming: `snake_case`
189
+ - Extends native prototypes for convenience (Number, Date, String)
190
+
191
+ ## License
192
+
193
+ ISC License
package/index.js CHANGED
@@ -9,7 +9,5 @@ module.exports = {
9
9
  ohlcv: require('./lib/ohlcv'),
10
10
  rate_limiter: require('./lib/rate-limiter.js'),
11
11
  utils: require('./lib/utils.js'),
12
- constants: {
13
- stablecoins: require('./constants/stablecoins.js'),
14
- },
12
+ constants: {},
15
13
  }
@@ -2,8 +2,6 @@ const _ = require('lodash')
2
2
 
3
3
  const needle = require('needle')
4
4
 
5
- const parse_pair = require('./utils.js').parse_pair
6
- const stablecoins = require('../constants/stablecoins.js')
7
5
  let coins_map_raw_coingecko = require('../constants/coins-map-coingecko.js')
8
6
  let coins_map_raw_coinmarketcap = require('../constants/coins-map-coinmarketcap.js')
9
7
  let coins_map = {}
@@ -12,8 +10,6 @@ const sort_keys = require('./utils.js').sort_keys
12
10
 
13
11
  const Limiter = require('./rate-limiter.js')
14
12
 
15
- const dex_rate = require('./dex-rate.js')
16
-
17
13
  let limiter = new Limiter({
18
14
  max_concurrent: 1,
19
15
  interval_concurrent: 3000,
@@ -67,49 +63,7 @@ let get_coins_map_coinmarketcap = (cb) => {
67
63
  let result = {}
68
64
  let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko') => {
69
65
  function get_crypto_rates_base(cb, pair_or_pairs_or_cur_curs, type) {
70
- if (type === 'pair') {
71
- let pair = pair_or_pairs_or_cur_curs
72
- let [cur, quote_cur] = parse_pair(pair)
73
- let cur_id = coins_map[cur],
74
- vs_cur = stablecoins.indexOf(quote_cur) > -1 ? 'usd' : quote_cur.toLowerCase()
75
- limiter.process(needle.get, `https://api.coingecko.com/api/v3/simple/price?ids=${cur_id}&vs_currencies=${vs_cur}`, (err, res, body) => {
76
- if (err) {
77
- console.error(pair, err)
78
- } else if (!body[cur_id]) {
79
- console.error('coingecko cur_id incorrect:', pair, cur_id, vs_cur, err)
80
- }
81
- cb(body[cur_id][vs_cur])
82
- })
83
- } else if (type === 'pairs') {
84
- let pairs = pair_or_pairs_or_cur_curs
85
- let cur_id_map = _.fromPairs(
86
- pairs.map((pair) => {
87
- let [cur, quote_cur] = parse_pair(pair)
88
- return [coins_map[cur], cur]
89
- })
90
- )
91
- let url = `https://api.coingecko.com/api/v3/simple/price?ids=${String(_.keys(cur_id_map))}&vs_currencies=usd`
92
- limiter.process(needle.get, url, (err, res, body) => {
93
- if (err) {
94
- console.error(err)
95
- return
96
- }
97
- for (let cur_id in body) {
98
- let temp = body[cur_id]
99
- temp.USD = temp.usd
100
- temp.USDT = temp.usd
101
- delete temp['usd']
102
- result[cur_id_map[cur_id]] = body[cur_id]
103
- }
104
- for (let stable of stablecoins) {
105
- result[stable] = {
106
- USD: 1,
107
- USDT: 1,
108
- }
109
- }
110
- cb(result)
111
- })
112
- } else if (type === 'cur') {
66
+ if (type === 'cur') {
113
67
  let cur = pair_or_pairs_or_cur_curs,
114
68
  cur_id = coins_map[cur]
115
69
  limiter.process(needle.get, `https://api.coingecko.com/api/v3/simple/price?ids=${cur_id}&vs_currencies=usd`, (err, res, body) => {
@@ -126,7 +80,7 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
126
80
  let cur_id_map = _.fromPairs(
127
81
  curs.map((cur) => {
128
82
  return [coins_map[cur], cur]
129
- })
83
+ }),
130
84
  )
131
85
  let url = `https://api.coingecko.com/api/v3/simple/price?ids=${String(_.keys(cur_id_map))}&vs_currencies=usd`
132
86
  limiter.process(needle.get, url, (err, res, body) => {
@@ -141,12 +95,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
141
95
  delete temp['usd']
142
96
  result[cur_id_map[cur_id]] = body[cur_id]
143
97
  }
144
- for (let stable of stablecoins) {
145
- result[stable] = {
146
- USD: 1,
147
- USDT: 1,
148
- }
149
- }
150
98
  cb(result)
151
99
  })
152
100
  } else if (type === 'curs' && source === 'coinmarketcap') {
@@ -171,12 +119,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
171
119
  }
172
120
  result[cur] = temp
173
121
  }
174
- for (let stable of stablecoins) {
175
- result[stable] = {
176
- USD: 1,
177
- USDT: 1,
178
- }
179
- }
180
122
  cb(result)
181
123
  })
182
124
  } else if (type === 'curs_dict') {
@@ -198,12 +140,64 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
198
140
  }
199
141
  let result_length = _.keys(result).length
200
142
  if (result_length === length) {
201
- for (let stable of stablecoins) {
202
- result[stable] = {
203
- USD: 1,
204
- USDT: 1,
205
- }
206
- }
143
+ cb(result)
144
+ }
145
+ } catch (error) {
146
+ console.error(pair, error)
147
+ }
148
+ })
149
+ } else if (exchange === 'binance') {
150
+ let pair = cur + 'USDT'
151
+ let url = `https://www.binance.com/api/v3/depth?symbol=${pair}&limit=20`
152
+ limiter.process(needle.get, url, (err, res, body) => {
153
+ try {
154
+ const { asks, bids } = body
155
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
156
+ result[cur] = {
157
+ USD: rate,
158
+ USDT: rate,
159
+ }
160
+ let result_length = _.keys(result).length
161
+ if (result_length === length) {
162
+ cb(result)
163
+ }
164
+ } catch (error) {
165
+ console.error(pair, error)
166
+ }
167
+ })
168
+ } else if (exchange === 'bingx') {
169
+ let pair = cur + 'USDT'
170
+ let url = `https://www.binance.com/api/v3/depth?symbol=${pair}&limit=20`
171
+ limiter.process(needle.get, url, (err, res, body) => {
172
+ try {
173
+ const { asks, bids } = body
174
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
175
+ result[cur] = {
176
+ USD: rate,
177
+ USDT: rate,
178
+ }
179
+ let result_length = _.keys(result).length
180
+ if (result_length === length) {
181
+ cb(result)
182
+ }
183
+ } catch (error) {
184
+ console.error(pair, error)
185
+ }
186
+ })
187
+ } else if (exchange === 'bitget') {
188
+ let pair = cur + 'USDT'
189
+ let url = `https://api.bitget.com/api/v2/spot/market/orderbook?symbol=${pair}&type=step0`
190
+ limiter.process(needle.get, url, (err, res, body) => {
191
+ try {
192
+ const asks = body.data.asks
193
+ const bids = body.data.bids
194
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
195
+ result[cur] = {
196
+ USD: rate,
197
+ USDT: rate,
198
+ }
199
+ let result_length = _.keys(result).length
200
+ if (result_length === length) {
207
201
  cb(result)
208
202
  }
209
203
  } catch (error) {
@@ -227,12 +221,66 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
227
221
  }
228
222
  let result_length = _.keys(result).length
229
223
  if (result_length === length) {
230
- for (let stable of stablecoins) {
231
- result[stable] = {
232
- USD: 1,
233
- USDT: 1,
234
- }
235
- }
224
+ cb(result)
225
+ }
226
+ } catch (error) {
227
+ console.error(pair, error)
228
+ }
229
+ })
230
+ } else if (exchange === 'bybit') {
231
+ let pair = cur + 'USDT'
232
+ let url = `https://api.bybit.com/v5/market/orderbook?category=spot&symbol=${pair}&limit=20`
233
+ limiter.process(needle.get, url, (err, res, body) => {
234
+ try {
235
+ const asks = body.result.a
236
+ const bids = body.result.b
237
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
238
+ result[cur] = {
239
+ USD: rate,
240
+ USDT: rate,
241
+ }
242
+ let result_length = _.keys(result).length
243
+ if (result_length === length) {
244
+ cb(result)
245
+ }
246
+ } catch (error) {
247
+ console.error(pair, error)
248
+ }
249
+ })
250
+ } else if (exchange === 'coinex') {
251
+ let pair = cur.toLowerCase() + 'usdt'
252
+ let url = `https://api.coinex.com/v1/market/depth?market=${pair}&limit=20&merge=0`
253
+ limiter.process(needle.get, url, (err, res, body) => {
254
+ try {
255
+ const asks = body.data.asks
256
+ const bids = body.data.bids
257
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
258
+ result[cur] = {
259
+ USD: rate,
260
+ USDT: rate,
261
+ }
262
+ let result_length = _.keys(result).length
263
+ if (result_length === length) {
264
+ cb(result)
265
+ }
266
+ } catch (error) {
267
+ console.error(pair, error)
268
+ }
269
+ })
270
+ } else if (exchange === 'coingecko') {
271
+ let pair = cur.toLowerCase() + 'usdt'
272
+ let url = `https://api.coinex.com/v1/market/depth?market=${pair}&limit=20&merge=0`
273
+ limiter.process(needle.get, url, (err, res, body) => {
274
+ try {
275
+ const asks = body.data.asks
276
+ const bids = body.data.bids
277
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
278
+ result[cur] = {
279
+ USD: rate,
280
+ USDT: rate,
281
+ }
282
+ let result_length = _.keys(result).length
283
+ if (result_length === length) {
236
284
  cb(result)
237
285
  }
238
286
  } catch (error) {
@@ -256,12 +304,46 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
256
304
  }
257
305
  let result_length = _.keys(result).length
258
306
  if (result_length === length) {
259
- for (let stable of stablecoins) {
260
- result[stable] = {
261
- USD: 1,
262
- USDT: 1,
263
- }
264
- }
307
+ cb(result)
308
+ }
309
+ } catch (error) {
310
+ console.error(pair, error)
311
+ }
312
+ })
313
+ } else if (exchange === 'cryptocom') {
314
+ let pair = cur + '_USDT'
315
+ let url = `https://api.crypto.com/v2/public/get-book?instrument_name=${pair}&depth=20`
316
+ limiter.process(needle.get, url, (err, res, body) => {
317
+ try {
318
+ const asks = body.result.data[0].asks
319
+ const bids = body.result.data[0].bids
320
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
321
+ result[cur] = {
322
+ USD: rate,
323
+ USDT: rate,
324
+ }
325
+ let result_length = _.keys(result).length
326
+ if (result_length === length) {
327
+ cb(result)
328
+ }
329
+ } catch (error) {
330
+ console.error(pair, error)
331
+ }
332
+ })
333
+ } else if (exchange === 'digifinex') {
334
+ let pair = cur + '_USDT'
335
+ let url = `https://openapi.digifinex.com/v3/spot/orderbook?symbol=${pair}`
336
+ limiter.process(needle.get, url, (err, res, body) => {
337
+ try {
338
+ const asks = body.data.asks
339
+ const bids = body.data.bids
340
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
341
+ result[cur] = {
342
+ USD: rate,
343
+ USDT: rate,
344
+ }
345
+ let result_length = _.keys(result).length
346
+ if (result_length === length) {
265
347
  cb(result)
266
348
  }
267
349
  } catch (error) {
@@ -282,12 +364,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
282
364
  }
283
365
  let result_length = _.keys(result).length
284
366
  if (result_length === length) {
285
- for (let stable of stablecoins) {
286
- result[stable] = {
287
- USD: 1,
288
- USDT: 1,
289
- }
290
- }
291
367
  cb(result)
292
368
  }
293
369
  } catch (error) {
@@ -307,12 +383,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
307
383
  }
308
384
  let result_length = _.keys(result).length
309
385
  if (result_length === length) {
310
- for (let stable of stablecoins) {
311
- result[stable] = {
312
- USD: 1,
313
- USDT: 1,
314
- }
315
- }
316
386
  cb(result)
317
387
  }
318
388
  } catch (error) {
@@ -332,12 +402,26 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
332
402
  }
333
403
  let result_length = _.keys(result).length
334
404
  if (result_length === length) {
335
- for (let stable of stablecoins) {
336
- result[stable] = {
337
- USD: 1,
338
- USDT: 1,
339
- }
340
- }
405
+ cb(result)
406
+ }
407
+ } catch (error) {
408
+ console.error(pair, error)
409
+ }
410
+ })
411
+ } else if (exchange === 'kucoin') {
412
+ let pair = cur + '-USDT'
413
+ let url = `https://api.kucoin.com/api/v1/market/orderbook/level2_100?symbol=${pair}`
414
+ limiter.process(needle.get, url, (err, res, body) => {
415
+ try {
416
+ const asks = body.data.asks
417
+ const bids = body.data.bids
418
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
419
+ result[cur] = {
420
+ USD: rate,
421
+ USDT: rate,
422
+ }
423
+ let result_length = _.keys(result).length
424
+ if (result_length === length) {
341
425
  cb(result)
342
426
  }
343
427
  } catch (error) {
@@ -357,12 +441,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
357
441
  }
358
442
  let result_length = _.keys(result).length
359
443
  if (result_length === length) {
360
- for (let stable of stablecoins) {
361
- result[stable] = {
362
- USD: 1,
363
- USDT: 1,
364
- }
365
- }
366
444
  cb(result)
367
445
  }
368
446
  } catch (error) {
@@ -382,12 +460,29 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
382
460
  }
383
461
  let result_length = _.keys(result).length
384
462
  if (result_length === length) {
385
- for (let stable of stablecoins) {
386
- result[stable] = {
387
- USD: 1,
388
- USDT: 1,
389
- }
390
- }
463
+ cb(result)
464
+ }
465
+ } catch (error) {
466
+ console.error(pair, error)
467
+ }
468
+ })
469
+ } else if (exchange === 'okx') {
470
+ let pair = cur + 'USDT'
471
+ let url = `https://www.okx.com/api/v5/market/books?instId=${pair}&sz=20`
472
+ limiter.process(needle.get, url, (err, res, body) => {
473
+ try {
474
+ if (typeof body === 'string') {
475
+ body = JSON.parse(body)
476
+ }
477
+ const asks = body.data[0].asks
478
+ const bids = body.data[0].bids
479
+ let rate = (parseFloat(asks[0][0]) + parseFloat(bids[0][0])) / 2
480
+ result[cur] = {
481
+ USD: rate,
482
+ USDT: rate,
483
+ }
484
+ let result_length = _.keys(result).length
485
+ if (result_length === length) {
391
486
  cb(result)
392
487
  }
393
488
  } catch (error) {
@@ -408,12 +503,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
408
503
  }
409
504
  let result_length = _.keys(result).length
410
505
  if (result_length === length) {
411
- for (let stable of stablecoins) {
412
- result[stable] = {
413
- USD: 1,
414
- USDT: 1,
415
- }
416
- }
417
506
  cb(result)
418
507
  }
419
508
  } catch (error) {
@@ -434,12 +523,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
434
523
  }
435
524
  let result_length = _.keys(result).length
436
525
  if (result_length === length) {
437
- for (let stable of stablecoins) {
438
- result[stable] = {
439
- USD: 1,
440
- USDT: 1,
441
- }
442
- }
443
526
  cb(result)
444
527
  }
445
528
  } catch (error) {
@@ -460,57 +543,12 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
460
543
  }
461
544
  let result_length = _.keys(result).length
462
545
  if (result_length === length) {
463
- for (let stable of stablecoins) {
464
- result[stable] = {
465
- USD: 1,
466
- USDT: 1,
467
- }
468
- }
469
546
  cb(result)
470
547
  }
471
548
  } catch (error) {
472
549
  console.error(pair, error)
473
550
  }
474
551
  })
475
- } else if (exchange === 'pancakeswap') {
476
- dex_rate(cur, (res) => {
477
- result[cur] = {
478
- USD: res[cur],
479
- USDT: res[cur],
480
- }
481
- let result_length = _.keys(result).length
482
- if (result_length === length) {
483
- for (let stable of stablecoins) {
484
- result[stable] = {
485
- USD: 1,
486
- USDT: 1,
487
- }
488
- }
489
- cb(result)
490
- }
491
- })
492
- } else if (exchange === 'coingecko') {
493
- let cur_id = coins_map[cur]
494
- limiter.process(needle.get, `https://api.coingecko.com/api/v3/simple/price?ids=${cur_id}&vs_currencies=usd`, (err, res, body) => {
495
- try {
496
- result[cur] = {
497
- USD: body[cur_id]['usd'],
498
- USDT: body[cur_id]['usd'],
499
- }
500
- let result_length = _.keys(result).length
501
- if (result_length === length) {
502
- for (let stable of stablecoins) {
503
- result[stable] = {
504
- USD: 1,
505
- USDT: 1,
506
- }
507
- }
508
- cb(result)
509
- }
510
- } catch (error) {
511
- console.error(error)
512
- }
513
- })
514
552
  }
515
553
  }
516
554
  } else {
@@ -543,9 +581,24 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
543
581
  update_time: new Date(coin.last_updated),
544
582
  }
545
583
  }
584
+ // Continue pagination if BTC/ETH not found yet
546
585
  if (!result.BTC || !result.ETH) {
547
- get_crypto_rates(cb)
586
+ if (body.length < per_page_nums) {
587
+ // Last page and still no BTC/ETH - return what we have
588
+ console.warn('BTC or ETH not found in CoinGecko pagination, returning partial results')
589
+ for (let cur in result) {
590
+ if (result.BTC) result[cur].BTC = result[cur].USD / result.BTC.USD
591
+ if (result.ETH) result[cur].ETH = result[cur].USD / result.ETH.USD
592
+ }
593
+ cb(result)
594
+ } else {
595
+ // Continue to next page
596
+ page++
597
+ console.log('fetching coingecko rate: page', page, 'good (searching for BTC/ETH)')
598
+ get_coingecko_rate_page(page, cb)
599
+ }
548
600
  } else {
601
+ // BTC and ETH found, calculate BTC/ETH rates for all currencies
549
602
  for (let cur in result) {
550
603
  result[cur].BTC = result[cur].USD / result.BTC.USD
551
604
  result[cur].ETH = result[cur].USD / result.ETH.USD
@@ -559,10 +612,37 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
559
612
  }
560
613
  }
561
614
  } else {
562
- setTimeout(() => {
563
- console.log('fetching coingecko rate: page', page, 'timeout')
564
- get_crypto_rates(cb)
565
- }, 60000)
615
+ // Handle error or empty response
616
+ if (err || (body && body.status && body.status.error_code === 429)) {
617
+ // Rate limit error - wait longer before retrying
618
+ console.error('CoinGecko rate limit error (429), waiting 60s before retry')
619
+ setTimeout(() => {
620
+ console.log('fetching coingecko rate: page', page, 'retry after rate limit')
621
+ get_coingecko_rate_page(page, cb)
622
+ }, 60000)
623
+ } else if (body && body.length === 0) {
624
+ // Empty response - might be last page or error
625
+ if (Object.keys(result).length > 0) {
626
+ // Return what we have
627
+ for (let cur in result) {
628
+ if (result.BTC) result[cur].BTC = result[cur].USD / result.BTC.USD
629
+ if (result.ETH) result[cur].ETH = result[cur].USD / result.ETH.USD
630
+ }
631
+ cb(result)
632
+ } else {
633
+ // No results at all - retry after delay
634
+ console.log('fetching coingecko rate: page', page, 'empty response, retrying')
635
+ setTimeout(() => {
636
+ get_coingecko_rate_page(page, cb)
637
+ }, 60000)
638
+ }
639
+ } else {
640
+ // Unknown error - retry
641
+ console.error('fetching coingecko rate: page', page, 'error', err || body)
642
+ setTimeout(() => {
643
+ get_coingecko_rate_page(page, cb)
644
+ }, 60000)
645
+ }
566
646
  }
567
647
  })
568
648
  }
@@ -593,10 +673,6 @@ let get_crypto_rates = (cb, pair_or_pairs_or_cur_curs, type, source = 'coingecko
593
673
  // 'coinmarketcap'
594
674
  // )
595
675
 
596
- // dex_rate().then((res) => {
597
- // console.log(res)
598
- // })
599
-
600
676
  // get_coins_map_coingecko((res) => {
601
677
  // console.log(res.body)
602
678
  // })
package/lib/utils.js CHANGED
@@ -1,7 +1,5 @@
1
1
  const _ = require('lodash')
2
2
 
3
- const stablecoins = require('../constants/stablecoins')
4
-
5
3
  // Number.prototype.toFixed_old = Number.prototype.toFixed
6
4
 
7
5
  // Number.prototype.toFixed = function(s) {
@@ -557,7 +555,7 @@ function arb_opportunities_from_combined_orderbook(orderbook_combined, profit_pe
557
555
  while (i < asks.length && j < bids.length) {
558
556
  if (asks[i][0] * (1 + profit_percentage) < bids[j][0]) {
559
557
  if (ask_amount === 0 && bid_amount === 0) {
560
- ;(ask_amount = asks[i][1]), (bid_amount = bids[j][1])
558
+ ;((ask_amount = asks[i][1]), (bid_amount = bids[j][1]))
561
559
  } else if (ask_amount <= bid_amount) {
562
560
  i++
563
561
  ask_amount += asks[i][1]
@@ -792,14 +790,15 @@ function similar(a, b, scale) {
792
790
  return false
793
791
  }
794
792
 
793
+ const quote_currencies = ['BTC', 'ETH', 'BNB', 'USD', 'USDC', 'USDT', 'HKD', 'KRW', 'THB']
795
794
  function parse_pair(pair) {
796
795
  pair = pair.toUpperCase()
797
796
  let time
798
797
  ;[pair, time] = _.split(pair, '_')
799
798
  let result = []
800
- let stablecoin = stablecoins.find((c) => pair.endsWith(c))
801
- if (stablecoin) {
802
- result = [pair.slice(0, -stablecoin.length), stablecoin]
799
+ let quote_cur = quote_currencies.find((c) => pair.endsWith(c))
800
+ if (quote_cur) {
801
+ result = [pair.slice(0, -quote_cur.length), quote_cur]
803
802
  } else {
804
803
  result = [pair.slice(0, -3), pair.slice(-3)]
805
804
  }
@@ -817,7 +816,7 @@ function reverse_pair(pair) {
817
816
  function cur_dict_to_pair_list(cur_dict) {
818
817
  return [].concat.apply(
819
818
  [],
820
- Object.entries(cur_dict).map((e) => e[1].map((j) => j + e[0]))
819
+ Object.entries(cur_dict).map((e) => e[1].map((j) => j + e[0])),
821
820
  )
822
821
  }
823
822
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icgio/icg-utils",
3
- "version": "1.9.41",
3
+ "version": "1.9.43",
4
4
  "description": "Utils package.",
5
5
  "main": "index.js",
6
6
  "directories": {
@@ -1 +0,0 @@
1
- module.exports = ['DAI', 'USD', 'USDC', 'USDD', 'USDJ', 'USDK', 'USDP', 'USDT']