@icgio/icg-utils 1.9.54 → 1.9.55

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/utils.js CHANGED
@@ -451,51 +451,62 @@ function vol_position_orderbook(input_array, vol_target) {
451
451
  // )
452
452
 
453
453
  function combine_orderbooks(orderbooks_dict, length = undefined) {
454
- function merge_sorted(type) {
455
- let count = {}
456
- for (let exchange in orderbooks_dict) {
457
- count[exchange] = 0
458
- }
459
- let result = []
460
- // * -1 check if all exchanges are done
461
- while (_.sum(_.values(count)) !== _.keys(orderbooks_dict).length * -1) {
462
- let picked
463
- for (let exchange in orderbooks_dict) {
464
- if (_.get(orderbooks_dict, [exchange, type], []).length === 0) {
465
- count[exchange] = -1 // -1 means finished
466
- }
467
- if (count[exchange] === -1) {
468
- continue
469
- }
470
- if (_.get(orderbooks_dict, [exchange, type, count[exchange], 'length']) === 2) {
471
- orderbooks_dict[exchange][type][count[exchange]].push(exchange)
472
- }
473
- if (!picked) {
474
- picked = orderbooks_dict[exchange][type][count[exchange]]
475
- } else if (type === 'asks' && picked[0] > orderbooks_dict[exchange][type][count[exchange]][0]) {
476
- picked = orderbooks_dict[exchange][type][count[exchange]]
477
- } else if (type === 'bids' && picked[0] < orderbooks_dict[exchange][type][count[exchange]][0]) {
478
- picked = orderbooks_dict[exchange][type][count[exchange]]
479
- }
454
+ const exchanges = Object.keys(orderbooks_dict)
455
+ const numExchanges = exchanges.length
456
+ const limit = length === undefined ? Infinity : length
457
+
458
+ function merge_sorted(type, direction) {
459
+ const lists = new Array(numExchanges)
460
+ const indexes = new Array(numExchanges)
461
+ let activeCount = 0
462
+
463
+ for (let i = 0; i < numExchanges; i++) {
464
+ const list = orderbooks_dict[exchanges[i]][type]
465
+ if (list && list.length > 0) {
466
+ lists[i] = list
467
+ indexes[i] = 0
468
+ activeCount++
469
+ } else {
470
+ lists[i] = null
480
471
  }
481
- if (picked) {
482
- result.push(picked)
483
- let picked_exchange = picked[2]
484
- if (count[picked_exchange] < orderbooks_dict[picked_exchange][type].length - 1) {
485
- count[picked_exchange] += 1
486
- } else {
487
- count[picked_exchange] = -1 // -1 means finished
472
+ }
473
+
474
+ const result = []
475
+
476
+ while (activeCount > 0 && result.length < limit) {
477
+ let bestIdx = -1
478
+ let bestPrice = 0
479
+
480
+ for (let i = 0; i < numExchanges; i++) {
481
+ const list = lists[i]
482
+ if (list === null) continue
483
+ const price = list[indexes[i]][0]
484
+ if (bestIdx === -1 || (direction === 1 ? price < bestPrice : price > bestPrice)) {
485
+ bestPrice = price
486
+ bestIdx = i
488
487
  }
489
488
  }
490
- if (result.length === length) {
491
- break
489
+
490
+ if (bestIdx === -1) break
491
+
492
+ result.push(lists[bestIdx][indexes[bestIdx]])
493
+
494
+ const next = indexes[bestIdx] + 1
495
+ if (next < lists[bestIdx].length) {
496
+ indexes[bestIdx] = next
497
+ } else {
498
+ lists[bestIdx] = null
499
+ activeCount--
492
500
  }
493
501
  }
502
+
494
503
  return result
495
504
  }
496
- let asks = merge_sorted('asks')
497
- let bids = merge_sorted('bids')
498
- return { asks, bids }
505
+
506
+ return {
507
+ asks: merge_sorted('asks', 1),
508
+ bids: merge_sorted('bids', -1),
509
+ }
499
510
  }
500
511
 
501
512
  // console.log(
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@icgio/icg-utils",
3
- "version": "1.9.54",
3
+ "version": "1.9.55",
4
4
  "description": "Utils package.",
5
5
  "main": "index.js",
6
6
  "directories": {
7
7
  "lib": "lib"
8
8
  },
9
9
  "scripts": {
10
- "test": "node test/rate-limiter.test.js"
10
+ "test": "node test/rate-limiter.test.js && node test/combine-orderbooks.test.js"
11
11
  },
12
12
  "repository": {
13
13
  "type": "git",
@@ -0,0 +1,226 @@
1
+ const assert = require('node:assert/strict')
2
+ const { combine_orderbooks } = require('../lib/utils')
3
+
4
+ /*
5
+ * Tests for combine_orderbooks.
6
+ *
7
+ * The function does a k-way merge across per-exchange orderbooks. Three
8
+ * properties matter for the icg-exchanges-wrapper hot path:
9
+ * 1. Correctness — asks ascend, bids descend, limit is honoured.
10
+ * 2. Non-mutation — the input dict and its tuples are never touched.
11
+ * 3. Reference sharing — result tuples are the same objects as the inputs
12
+ * (Flavor 2). Callers rely on this to skip a deep clone upstream.
13
+ */
14
+
15
+ function testBasicMergeAscDesc() {
16
+ const input = {
17
+ binance: { asks: [[100, 1], [102, 2], [105, 3]], bids: [[99, 1], [97, 2], [95, 3]] },
18
+ bybit: { asks: [[101, 1], [103, 2], [104, 3]], bids: [[98, 1], [96, 2], [94, 3]] },
19
+ }
20
+ const r = combine_orderbooks(input, 4)
21
+ assert.deepStrictEqual(
22
+ r.asks.map((t) => t[0]),
23
+ [100, 101, 102, 103],
24
+ 'asks should merge ascending',
25
+ )
26
+ assert.deepStrictEqual(
27
+ r.bids.map((t) => t[0]),
28
+ [99, 98, 97, 96],
29
+ 'bids should merge descending',
30
+ )
31
+ assert.equal(r.asks.length, 4, 'asks should respect length limit')
32
+ assert.equal(r.bids.length, 4, 'bids should respect length limit')
33
+ }
34
+
35
+ function testTuplesAreLengthTwo() {
36
+ const input = {
37
+ binance: { asks: [[100, 1]], bids: [[99, 1]] },
38
+ bybit: { asks: [[101, 2]], bids: [[98, 2]] },
39
+ }
40
+ const r = combine_orderbooks(input, 10)
41
+ for (const t of r.asks) {
42
+ assert.equal(t.length, 2, 'result asks tuples should remain [price, amount] (no [2] augmentation)')
43
+ }
44
+ for (const t of r.bids) {
45
+ assert.equal(t.length, 2, 'result bids tuples should remain [price, amount] (no [2] augmentation)')
46
+ }
47
+ }
48
+
49
+ function testInputNeverMutated() {
50
+ const input = {
51
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1], [97, 2]] },
52
+ bybit: { asks: [[101, 1], [103, 2]], bids: [[98, 1], [96, 2]] },
53
+ }
54
+ // Snapshot input shape so we can detect any mutation
55
+ const snapshot = JSON.parse(JSON.stringify(input))
56
+ combine_orderbooks(input, 10)
57
+ assert.deepStrictEqual(input, snapshot, 'input dict should be byte-equal to its pre-call snapshot')
58
+ for (const ex of Object.keys(input)) {
59
+ for (const side of ['asks', 'bids']) {
60
+ for (const t of input[ex][side]) {
61
+ assert.equal(t.length, 2, `input ${ex}.${side} tuples should still be length 2 (no exchange tag pushed)`)
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ function testIdempotentOnRepeatedCalls() {
68
+ // Calling twice on the same input must produce identical output and still
69
+ // not mutate. This is the regression guard against the old behaviour where
70
+ // combine_orderbooks pushed exchange names onto input tuples.
71
+ const input = {
72
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1], [97, 2]] },
73
+ bybit: { asks: [[101, 1], [103, 2]], bids: [[98, 1], [96, 2]] },
74
+ }
75
+ const r1 = combine_orderbooks(input, 4)
76
+ const r2 = combine_orderbooks(input, 4)
77
+ assert.deepStrictEqual(
78
+ r1.asks.map((t) => [t[0], t[1]]),
79
+ r2.asks.map((t) => [t[0], t[1]]),
80
+ 'repeated calls should return identical asks',
81
+ )
82
+ assert.deepStrictEqual(
83
+ r1.bids.map((t) => [t[0], t[1]]),
84
+ r2.bids.map((t) => [t[0], t[1]]),
85
+ 'repeated calls should return identical bids',
86
+ )
87
+ }
88
+
89
+ function testResultAliasesInput() {
90
+ // Flavor 2: result tuples must be the SAME object refs as input tuples.
91
+ // This is the contract orders.js relies on to skip cloneDeep.
92
+ const input = {
93
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1]] },
94
+ bybit: { asks: [[101, 1]], bids: [[98, 1], [96, 2]] },
95
+ }
96
+ const r = combine_orderbooks(input, 10)
97
+ assert.equal(r.asks[0], input.binance.asks[0], 'asks[0] should be a ref to binance.asks[0]')
98
+ assert.equal(r.asks[1], input.bybit.asks[0], 'asks[1] should be a ref to bybit.asks[0]')
99
+ assert.equal(r.asks[2], input.binance.asks[1], 'asks[2] should be a ref to binance.asks[1]')
100
+ assert.equal(r.bids[0], input.binance.bids[0], 'bids[0] should be a ref to binance.bids[0]')
101
+ assert.equal(r.bids[1], input.bybit.bids[0], 'bids[1] should be a ref to bybit.bids[0]')
102
+ assert.equal(r.bids[2], input.bybit.bids[1], 'bids[2] should be a ref to bybit.bids[1]')
103
+ }
104
+
105
+ function testEmptyDict() {
106
+ const r = combine_orderbooks({}, 10)
107
+ assert.deepStrictEqual(r.asks, [], 'empty dict asks should be []')
108
+ assert.deepStrictEqual(r.bids, [], 'empty dict bids should be []')
109
+ }
110
+
111
+ function testEmptySidePerExchange() {
112
+ // One exchange has only asks, the other has only bids. Each side should
113
+ // be drawn from whichever exchange supplies it.
114
+ const input = {
115
+ binance: { asks: [[100, 1], [101, 2]], bids: [] },
116
+ bybit: { asks: [], bids: [[99, 1], [97, 2]] },
117
+ }
118
+ const r = combine_orderbooks(input, 5)
119
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101], 'asks should come from binance only')
120
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 97], 'bids should come from bybit only')
121
+ }
122
+
123
+ function testSingleExchange() {
124
+ const input = {
125
+ binance: { asks: [[100, 1], [101, 2], [102, 3]], bids: [[99, 1], [98, 2]] },
126
+ }
127
+ const r = combine_orderbooks(input, 10)
128
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101, 102])
129
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 98])
130
+ }
131
+
132
+ function testLengthLargerThanAvailable() {
133
+ // Asking for 100 levels when only 4 exist total per side should return
134
+ // exactly the 4 available, not pad or loop forever.
135
+ const input = {
136
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1], [97, 2]] },
137
+ bybit: { asks: [[101, 1], [103, 2]], bids: [[98, 1], [96, 2]] },
138
+ }
139
+ const r = combine_orderbooks(input, 100)
140
+ assert.equal(r.asks.length, 4)
141
+ assert.equal(r.bids.length, 4)
142
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101, 102, 103])
143
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 98, 97, 96])
144
+ }
145
+
146
+ function testNoLengthLimit() {
147
+ const input = {
148
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1]] },
149
+ bybit: { asks: [[101, 1]], bids: [[98, 1], [96, 2]] },
150
+ }
151
+ const r = combine_orderbooks(input)
152
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [100, 101, 102], 'asks unbounded')
153
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [99, 98, 96], 'bids unbounded')
154
+ }
155
+
156
+ function testThreeExchangesInterleaving() {
157
+ const input = {
158
+ a: { asks: [[100, 1], [104, 1], [107, 1]], bids: [[99, 1], [95, 1], [92, 1]] },
159
+ b: { asks: [[101, 1], [103, 1], [108, 1]], bids: [[98, 1], [96, 1], [91, 1]] },
160
+ c: { asks: [[102, 1], [105, 1], [106, 1]], bids: [[97, 1], [94, 1], [93, 1]] },
161
+ }
162
+ const r = combine_orderbooks(input, 9)
163
+ assert.deepStrictEqual(
164
+ r.asks.map((t) => t[0]),
165
+ [100, 101, 102, 103, 104, 105, 106, 107, 108],
166
+ '3-way ask merge should produce sorted ascending',
167
+ )
168
+ assert.deepStrictEqual(
169
+ r.bids.map((t) => t[0]),
170
+ [99, 98, 97, 96, 95, 94, 93, 92, 91],
171
+ '3-way bid merge should produce sorted descending',
172
+ )
173
+ }
174
+
175
+ function testTiedPricesDeterministic() {
176
+ // Two exchanges quote the same top price. The result is implementation-
177
+ // defined but must be deterministic and must include both tuples.
178
+ const input = {
179
+ binance: { asks: [[100, 1], [102, 2]], bids: [[99, 1]] },
180
+ bybit: { asks: [[100, 5], [101, 5]], bids: [[99, 5]] },
181
+ }
182
+ const r1 = combine_orderbooks(input, 4)
183
+ const r2 = combine_orderbooks(input, 4)
184
+ assert.deepStrictEqual(
185
+ r1.asks.map((t) => [t[0], t[1]]),
186
+ r2.asks.map((t) => [t[0], t[1]]),
187
+ 'tied-price merge should be deterministic across calls',
188
+ )
189
+ // Both 100s should be present somewhere in the first two slots
190
+ const top_two = r1.asks.slice(0, 2).map((t) => t[0])
191
+ assert.deepStrictEqual(top_two, [100, 100], 'both tied tuples at price 100 should appear in the first two slots')
192
+ }
193
+
194
+ function testFractionalPrices() {
195
+ const input = {
196
+ binance: { asks: [[0.0001234, 1], [0.0001236, 2]], bids: [[0.0001233, 1]] },
197
+ bybit: { asks: [[0.0001235, 1]], bids: [[0.0001232, 1], [0.0001230, 2]] },
198
+ }
199
+ const r = combine_orderbooks(input, 5)
200
+ assert.deepStrictEqual(r.asks.map((t) => t[0]), [0.0001234, 0.0001235, 0.0001236])
201
+ assert.deepStrictEqual(r.bids.map((t) => t[0]), [0.0001233, 0.0001232, 0.000123])
202
+ }
203
+
204
+ function main() {
205
+ testBasicMergeAscDesc()
206
+ testTuplesAreLengthTwo()
207
+ testInputNeverMutated()
208
+ testIdempotentOnRepeatedCalls()
209
+ testResultAliasesInput()
210
+ testEmptyDict()
211
+ testEmptySidePerExchange()
212
+ testSingleExchange()
213
+ testLengthLargerThanAvailable()
214
+ testNoLengthLimit()
215
+ testThreeExchangesInterleaving()
216
+ testTiedPricesDeterministic()
217
+ testFractionalPrices()
218
+ console.log('combine_orderbooks tests passed')
219
+ }
220
+
221
+ try {
222
+ main()
223
+ } catch (err) {
224
+ console.error(err)
225
+ process.exit(1)
226
+ }