@icgio/icg-utils 1.9.76 → 1.9.78

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
@@ -13,9 +13,10 @@ npm install @icgio/icg-utils
13
13
  | `crypto_rates(cb, curs, type)` | `'curs'`: Coinpaprika USD prices for a list of symbols. `'curs_dict'`: mid of `<cur>/USDT` on the exchange named per currency, e.g. `{ B3TR: 'mexc' }`. Calls back with `{ CUR: { USD, USDT } }`, leaving out currencies it could not price. |
14
14
  | `forex_rate.get_forex_rate_usd(curs, cb)` | USD value of one unit of each fiat currency. |
15
15
  | `influx` | `new Influx({ url, token, org, org_id, bucket, schema, transportOptions })` with `query(flux, cb)` and `write_points_with_check(points, cb)`. Writes drop points or fields that `schema` does not know and values that are missing or not finite, and create the bucket on first use. |
16
- | `rate_limiter` | `new RateLimiter({ max_concurrent, interval_concurrent, abandon_tx, only_same_args })`, then `limiter.process(fn, ...args)`. Setting `limiter.priority` before `process` queues that call ahead of higher numbers; priority 0 runs at once even when the window is spent, and still counts in it. |
16
+ | `rate_limiter` | `new RateLimiter({ max_concurrent, interval_concurrent, abandon_tx, only_same_args })`, then `limiter.process(fn, ...args)`. Setting `limiter.priority` before `process` queues that call ahead of higher numbers; priority 0 runs at once even when the window is spent, up to one extra window's worth (beyond that it queues ahead of everything else), and still counts in it. |
17
17
  | `sorted_book`, `utils.ordered_dict` | Price-level books keyed by price: a red-black tree for large books, a binary-searched array for small ones. |
18
18
  | `market_history_buffer` | Record, prune and read the per-pair trade buffers in `market.market_history_dict`. |
19
+ | `tracked_dict(held, reads)` | A dict behind a Proxy that notes each key set on or deleted from it (with `reads`, read from it too) and what the key held before, and counts its keys. |
19
20
  | `observable` | Minimal `subscribe` / `notify` class. |
20
21
  | `ohlcv(pair, interval, cb)` | Binance klines. |
21
22
  | `logger` | Winston console logger. |
package/index.js CHANGED
@@ -10,5 +10,6 @@ module.exports = {
10
10
  market_history_buffer: require('./lib/market-history-buffer.js'),
11
11
  rate_limiter: require('./lib/rate-limiter.js'),
12
12
  sorted_book: require('./lib/sorted-book.js'),
13
+ tracked_dict: require('./lib/tracked-dict.js'),
13
14
  utils: require('./lib/utils.js'),
14
15
  }
@@ -48,19 +48,34 @@ function maybe_prune(market, pair, arr) {
48
48
  if (i > 0) arr.splice(0, i)
49
49
  }
50
50
 
51
+ // per trade array: its last trade when last read, the newest time up to it, and the furthest a trade has landed behind one stored before it
52
+ const arrivals = new WeakMap()
53
+
54
+ // A pair's trades inside the window, newest first; of equal times the later arrival comes first.
51
55
  function read_market_history_since(market, pair, timeframe_in_ms) {
52
56
  const arr = market.market_history_dict[pair]
53
57
  if (!Array.isArray(arr)) return []
54
58
  const cutoff = Date.now() - timeframe_in_ms
59
+ let seen = arrivals.get(arr)
60
+ if (!seen) arrivals.set(arr, (seen = { last: undefined, newest: -Infinity, late: 0 }))
61
+ let i = arr.length
62
+ while (i > 0 && arr[i - 1] !== seen.last) i--
63
+ for (; i < arr.length; i++) {
64
+ const time = arr[i].close_time.valueOf()
65
+ seen.late = Math.max(seen.late, seen.newest - time)
66
+ seen.newest = Math.max(seen.newest, time)
67
+ }
68
+ seen.last = arr[arr.length - 1]
69
+ // Stored in arrival order, and venues push trade batches in either order:
70
+ // walk newest -> oldest until `late` past the cutoff, then sort. A read
71
+ // stays O(K=window) unless a trade landed far behind the ones before it.
55
72
  const result = []
56
- // Walk newest -> oldest. Exchange WS feeds emit trades in venue order per
57
- // pair, so close_time is near-monotonic and we can break early once we
58
- // cross the cutoff. Drops a read from O(N=full_buffer) to O(K=window).
59
- for (let i = arr.length - 1; i >= 0; i--) {
60
- if (arr[i].close_time <= cutoff) break
61
- result.push(arr[i])
73
+ for (i = arr.length - 1; i >= 0; i--) {
74
+ const time = arr[i].close_time.valueOf()
75
+ if (time > cutoff) result.push(arr[i])
76
+ else if (time <= cutoff - seen.late) break
62
77
  }
63
- return result
78
+ return result.sort((a, b) => b.close_time.valueOf() - a.close_time.valueOf())
64
79
  }
65
80
 
66
81
  module.exports = { record_market_history_trade, record_market_history_trades, read_market_history_since }
@@ -38,8 +38,8 @@ class RateLimiter {
38
38
  }, this.interval_concurrent)
39
39
  }
40
40
  } else {
41
- // priority 0 does not wait for the window: it runs now and still counts in it
42
- if (this.count < this.max_concurrent || priority === 0) {
41
+ // priority 0 does not wait for the window, up to one extra window's worth: it runs now and still counts in it; beyond that it queues first
42
+ if (this.count < this.max_concurrent || (priority === 0 && this.count < 2 * this.max_concurrent)) {
43
43
  this.count++
44
44
  this._scheduleResetTimer()
45
45
  func(...args)
@@ -0,0 +1,36 @@
1
+ // A dict that notes what touches it, so a reader can find what changed without visiting every key.
2
+ //
3
+ // Usage:
4
+ // const tracked_dict = require('@icgio/icg-utils').tracked_dict
5
+ // const tracked = tracked_dict()
6
+ // tracked.proxy.a = 1 // set and delete through proxy; dict is the plain object behind it
7
+ // tracked.before // Map { 'a' => undefined }: each key touched, with what it held before
8
+ // tracked.size // 1: how many keys dict holds
9
+ // tracked.before.clear() // start noting afresh
10
+ //
11
+ // held(value) picks what to keep of a key's value before its first touch (default: the value). With reads, a read through
12
+ // proxy is a touch too, for values that change in place, such as an array that is pushed onto. before can name a key dict
13
+ // does not hold: one that was deleted, or read while missing.
14
+
15
+ const tracked_dict = (held = (value) => value, reads = false) => {
16
+ const tracked = { dict: {}, before: new Map(), size: 0 }
17
+ const note = (dict, key) => tracked.before.has(key) || tracked.before.set(key, held(dict[key]))
18
+ const traps = {
19
+ set: (dict, key, value) => {
20
+ note(dict, key)
21
+ if (!Object.hasOwn(dict, key)) tracked.size++
22
+ dict[key] = value
23
+ return true
24
+ },
25
+ deleteProperty: (dict, key) => {
26
+ note(dict, key)
27
+ if (Object.hasOwn(dict, key)) tracked.size--
28
+ return delete dict[key]
29
+ },
30
+ }
31
+ if (reads) traps.get = (dict, key) => (note(dict, key), dict[key])
32
+ tracked.proxy = new Proxy(tracked.dict, traps)
33
+ return tracked
34
+ }
35
+
36
+ module.exports = tracked_dict
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icgio/icg-utils",
3
- "version": "1.9.76",
3
+ "version": "1.9.78",
4
4
  "description": "Utils package.",
5
5
  "main": "index.js",
6
6
  "directories": {