@icgio/icg-utils 1.9.74 → 1.9.76

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/package.json CHANGED
@@ -1,14 +1,11 @@
1
1
  {
2
2
  "name": "@icgio/icg-utils",
3
- "version": "1.9.74",
3
+ "version": "1.9.76",
4
4
  "description": "Utils package.",
5
5
  "main": "index.js",
6
6
  "directories": {
7
7
  "lib": "lib"
8
8
  },
9
- "scripts": {
10
- "test": "node test/rate-limiter.test.js && node test/combine-orderbooks.test.js && node test/ordered-dict.test.js && node test/sorted-book.test.js && node test/merge-trades.test.js"
11
- },
12
9
  "repository": {
13
10
  "type": "git",
14
11
  "url": "git+https://github.com/icgio/icg-utils.git"
package/lib/ip.js DELETED
@@ -1,19 +0,0 @@
1
- /**
2
- * Get external IP address using ipify.org API
3
- * @returns {Promise<string>} The external IP address
4
- */
5
- async function getIP() {
6
- try {
7
- const response = await fetch('https://api.ipify.org?format=json')
8
- if (!response.ok) {
9
- throw new Error(`HTTP error! status: ${response.status}`)
10
- }
11
- const data = await response.json()
12
- return data.ip
13
- } catch (error) {
14
- console.error('Error fetching external IP:', error.message)
15
- throw error
16
- }
17
- }
18
-
19
- module.exports = getIP
@@ -1,226 +0,0 @@
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
- }
@@ -1,327 +0,0 @@
1
- #!/usr/bin/env node
2
- const { merge_trades_with_same_id } = require('../lib/utils.js')
3
-
4
- let pass = 0,
5
- fail = 0
6
- function assert(condition, msg) {
7
- if (condition) {
8
- pass++
9
- } else {
10
- fail++
11
- console.log(' FAIL:', msg)
12
- }
13
- }
14
- function eq(a, b, msg) {
15
- const as = JSON.stringify(a),
16
- bs = JSON.stringify(b)
17
- if (as === bs) {
18
- pass++
19
- } else {
20
- fail++
21
- console.log(' FAIL:', msg, '— got', as, 'expected', bs)
22
- }
23
- }
24
- function approx(a, b, epsilon, msg) {
25
- if (Math.abs(a - b) <= epsilon) {
26
- pass++
27
- } else {
28
- fail++
29
- console.log(' FAIL:', msg, '— got', a, 'expected', b)
30
- }
31
- }
32
-
33
- console.log('--- merge_trades_with_same_id ---')
34
-
35
- const merged = merge_trades_with_same_id([
36
- {
37
- order_id: 'order-1',
38
- trade_id: 'fill-1',
39
- pair: 'SWFTCUSDT',
40
- type: 'buy',
41
- price: 0.0033818,
42
- amount: 4430.6295,
43
- total: 14.9835028431,
44
- open_time: new Date('2026-04-12T11:57:17.154Z'),
45
- close_time: new Date('2026-04-12T11:57:17.154Z'),
46
- fees: { USDT: '0.0299670056862' },
47
- },
48
- {
49
- order_id: 'order-1',
50
- trade_id: 'fill-2',
51
- pair: 'SWFTCUSDT',
52
- type: 'buy',
53
- price: 0.0033818,
54
- amount: 1955.1223,
55
- total: 6.61163708291,
56
- open_time: new Date('2026-04-12T11:57:17.537Z'),
57
- close_time: new Date('2026-04-12T11:57:31.380Z'),
58
- fees: { USDT: '0.01322327416382' },
59
- },
60
- ])
61
-
62
- eq(merged.length, 1, 'merges trades with same order_id')
63
- approx(merged[0].amount, 6385.7518, 1e-10, 'sums amount numerically')
64
- approx(merged[0].total, 21.59513992601, 1e-10, 'sums total numerically')
65
- approx(merged[0].fees.USDT, 0.04319027985002, 1e-14, 'sums string fees numerically')
66
- eq(typeof merged[0].fees.USDT, 'number', 'normalizes merged fee type to number')
67
- eq(merged[0].fill_history.length, 2, 'preserves both fills in fill_history')
68
- eq(typeof merged[0].fill_history[0].fees.USDT, 'number', 'normalizes fill_history fee type to number')
69
- eq(merged[0].close_time.toISOString(), '2026-04-12T11:57:31.380Z', 'keeps latest close_time')
70
- eq(merged[0].trade_id, undefined, 'strips fill ids from merged trade')
71
-
72
- const disjointFees = merge_trades_with_same_id([
73
- {
74
- order_id: 'order-2',
75
- trade_id: 'fill-1',
76
- pair: 'SWFTCUSDT',
77
- type: 'buy',
78
- price: 1,
79
- amount: 1,
80
- total: 1,
81
- fees: { USDT: '0.1' },
82
- },
83
- {
84
- order_id: 'order-2',
85
- trade_id: 'fill-2',
86
- pair: 'SWFTCUSDT',
87
- type: 'buy',
88
- price: 1,
89
- amount: 2,
90
- total: 2,
91
- fees: { BTC: '0.2' },
92
- },
93
- ])
94
-
95
- approx(disjointFees[0].fees.USDT, 0.1, 1e-14, 'preserves first copied fee numerically')
96
- approx(disjointFees[0].fees.BTC, 0.2, 1e-14, 'preserves second copied fee numerically')
97
- eq(typeof disjointFees[0].fees.USDT, 'number', 'normalizes first copied fee type to number')
98
- eq(typeof disjointFees[0].fees.BTC, 'number', 'normalizes second copied fee type to number')
99
-
100
- const copiedFees = merge_trades_with_same_id([
101
- {
102
- order_id: 'order-3',
103
- trade_id: 'fill-1',
104
- pair: 'SWFTCUSDT',
105
- type: 'buy',
106
- price: 1,
107
- amount: 1,
108
- total: 1,
109
- },
110
- {
111
- order_id: 'order-3',
112
- trade_id: 'fill-2',
113
- pair: 'SWFTCUSDT',
114
- type: 'buy',
115
- price: 1,
116
- amount: 2,
117
- total: 2,
118
- fees: { USDT: '0.3' },
119
- },
120
- ])
121
-
122
- approx(copiedFees[0].fees.USDT, 0.3, 1e-14, 'normalizes fee map when copied from later fill')
123
- eq(typeof copiedFees[0].fees.USDT, 'number', 'normalizes copied later-fill fee type to number')
124
-
125
- const singleTrade = merge_trades_with_same_id([
126
- {
127
- order_id: 'order-4',
128
- trade_id: 'fill-1',
129
- pair: 'SWFTCUSDT',
130
- type: 'buy',
131
- price: 1,
132
- amount: 1,
133
- total: 1,
134
- fees: { USDT: '0.4' },
135
- },
136
- ])
137
-
138
- approx(singleTrade[0].fees.USDT, 0.4, 1e-14, 'normalizes fee map for single trade result')
139
- eq(typeof singleTrade[0].fees.USDT, 'number', 'normalizes single trade fee type to number')
140
- eq(typeof singleTrade[0].fill_history[0].fees.USDT, 'number', 'normalizes single trade fill_history fee type to number')
141
-
142
- console.log(`pass=${pass} fail=${fail}`)
143
- if (fail > 0) process.exit(1)
144
-
145
- // --- differential: rewritten O(n) group-by vs the original O(n^2) pairwise scan ---
146
- // The legacy implementation is kept verbatim below; both run on cloned inputs and
147
- // must produce JSON-identical output across randomized fixtures.
148
- function legacy_merge(array) {
149
- let normalize_fee_amount = (value) => {
150
- const normalized = parseFloat(value || 0)
151
- return Number.isFinite(normalized) ? normalized : 0
152
- }
153
- let normalize_fee_map = (fees) => {
154
- if (!fees || typeof fees !== 'object') return fees
155
- return Object.fromEntries(Object.entries(fees).map(([cur, amount]) => [cur, normalize_fee_amount(amount)]))
156
- }
157
- let sum_numeric_fee_amount = (left, right) => normalize_fee_amount(left) + normalize_fee_amount(right)
158
- let get_fill_history = (trade) => {
159
- if (Array.isArray(trade.fill_history) && trade.fill_history.length > 0) {
160
- return trade.fill_history.map((fill) => {
161
- let normalized_fill = Object.assign({}, fill)
162
- if (normalized_fill.fees && typeof normalized_fill.fees === 'object') normalized_fill.fees = normalize_fee_map(normalized_fill.fees)
163
- return normalized_fill
164
- })
165
- }
166
- let fill = { price: parseFloat(trade.price), amount: parseFloat(trade.amount), total: parseFloat(trade.total) }
167
- let time = trade.close_time || trade.open_time
168
- if (time) fill.time = time
169
- if (trade.trade_id != null) fill.trade_id = String(trade.trade_id)
170
- if (trade.fees && typeof trade.fees === 'object') fill.fees = normalize_fee_map(trade.fees)
171
- if (trade.role != null) fill.role = trade.role
172
- return [fill]
173
- }
174
- let strip_trade_fill_id = (trade) => {
175
- delete trade.trade_id
176
- delete trade.id
177
- }
178
- if (array.length === 1) {
179
- if (array[0].fees && typeof array[0].fees === 'object') array[0].fees = normalize_fee_map(array[0].fees)
180
- array[0].fill_history = get_fill_history(array[0])
181
- strip_trade_fill_id(array[0])
182
- return array
183
- } else {
184
- let trades = []
185
- let processed_index_set = new Set()
186
- for (let i = 0; i < array.length; i++) {
187
- if (!processed_index_set.has(i)) {
188
- let trade = array[i]
189
- if (trade.fees && typeof trade.fees === 'object') trade.fees = normalize_fee_map(trade.fees)
190
- trade.fill_history = get_fill_history(trade)
191
- processed_index_set.add(i)
192
- for (let j = i + 1; j < array.length; j++) {
193
- if (!processed_index_set.has(j)) {
194
- let to_compare_trade = array[j]
195
- if (trade.order_id != null && to_compare_trade.order_id === trade.order_id) {
196
- trade.amount = trade.amount + to_compare_trade.amount
197
- trade.total = trade.total + to_compare_trade.total
198
- trade.fill_history = trade.fill_history.concat(get_fill_history(to_compare_trade))
199
- if (to_compare_trade.fees && typeof to_compare_trade.fees === 'object') {
200
- if (!trade.fees || typeof trade.fees !== 'object') {
201
- trade.fees = normalize_fee_map(to_compare_trade.fees)
202
- } else {
203
- for (const [cur, amount] of Object.entries(to_compare_trade.fees)) {
204
- trade.fees[cur] = sum_numeric_fee_amount(trade.fees[cur], amount)
205
- }
206
- }
207
- }
208
- if (to_compare_trade.open_time && (!trade.open_time || to_compare_trade.open_time < trade.open_time)) {
209
- trade.open_time = to_compare_trade.open_time
210
- }
211
- if (to_compare_trade.close_time && (!trade.close_time || to_compare_trade.close_time > trade.close_time)) {
212
- trade.close_time = to_compare_trade.close_time
213
- }
214
- processed_index_set.add(j)
215
- }
216
- }
217
- }
218
- trade.amount = parseFloat(trade.amount)
219
- trade.total = parseFloat(trade.total)
220
- trade.price = trade.total / trade.amount
221
- trade.fill_history = trade.fill_history.sort((a, b) => {
222
- let a_time = a.time ? new Date(a.time).getTime() : 0
223
- let b_time = b.time ? new Date(b.time).getTime() : 0
224
- return a_time - b_time
225
- })
226
- strip_trade_fill_id(trade)
227
- trades.push(trade)
228
- }
229
- }
230
- return trades
231
- }
232
- }
233
-
234
- console.log('--- differential vs legacy ---')
235
- // deterministic LCG so failures reproduce
236
- let seed = 42
237
- const rand = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648
238
- const pick = (arr) => arr[Math.floor(rand() * arr.length)]
239
- function random_row(i) {
240
- const oid_roll = rand()
241
- const order_id = oid_roll < 0.1 ? null : oid_roll < 0.15 ? undefined : oid_roll < 0.18 ? NaN : 'ord-' + Math.floor(rand() * 30)
242
- const price = 0.001 + rand()
243
- const amount = 1 + Math.floor(rand() * 1000)
244
- const row = {
245
- order_id,
246
- trade_id: rand() < 0.8 ? 't-' + i : undefined,
247
- pair: pick(['AUSDT', 'BUSDT']),
248
- type: pick(['buy', 'sell']),
249
- price,
250
- amount,
251
- total: price * amount,
252
- open_time: rand() < 0.9 ? new Date(1786900000000 + Math.floor(rand() * 1e7)) : undefined,
253
- close_time: rand() < 0.9 ? new Date(1786910000000 + Math.floor(rand() * 1e7)) : undefined,
254
- }
255
- const fee_roll = rand()
256
- if (fee_roll < 0.5) row.fees = { USDT: String(rand() * 0.1) }
257
- else if (fee_roll < 0.7) row.fees = { USDT: rand() * 0.1, BNB: 'not-a-number' }
258
- else if (fee_roll < 0.75) row.fees = null
259
- if (rand() < 0.1) row.fill_history = [{ price, amount, total: price * amount, time: row.close_time, trade_id: 'pre-' + i, fees: { USDT: '0.01' } }]
260
- if (rand() < 0.3) row.role = pick(['maker', 'taker'])
261
- return row
262
- }
263
- for (const n of [1, 2, 7, 50, 400]) {
264
- const fixture = Array.from({ length: n }, (_, i) => random_row(i))
265
- const input_snapshot = JSON.stringify(fixture)
266
- const legacy_out = legacy_merge(structuredClone(fixture))
267
- const new_out = merge_trades_with_same_id(fixture)
268
- eq(new_out, legacy_out, `differential n=${n}`)
269
- assert(JSON.stringify(fixture) === input_snapshot, `input not mutated n=${n}`)
270
- }
271
- // NaN order_ids must never group (Map SameValueZero would; strict equality does not)
272
- const nan_out = merge_trades_with_same_id([random_row(0), random_row(1)].map((r) => ({ ...r, order_id: NaN })))
273
- assert(nan_out.length === 2, 'NaN order_ids never merge')
274
- // adversarial edges the random generator does not produce
275
- console.log('--- adversarial edges ---')
276
- const edge_cases = [
277
- ['empty input', []],
278
- [
279
- 'string amounts stay bug-compatible (legacy string-concats then parseFloat)',
280
- [
281
- { order_id: 'o1', trade_id: 'a', price: 1, amount: '40', total: '40', close_time: new Date(1786900000000) },
282
- { order_id: 'o1', trade_id: 'b', price: 1, amount: '60', total: '60', close_time: new Date(1786900001000) },
283
- ],
284
- ],
285
- [
286
- 'string fees value passes through unnormalized',
287
- [
288
- { order_id: 'o1', trade_id: 'a', price: 1, amount: 1, total: 1, fees: 'weird', close_time: new Date(1786900000000) },
289
- { order_id: 'o1', trade_id: 'b', price: 1, amount: 1, total: 1, fees: { USDT: '0.1' }, close_time: new Date(1786900001000) },
290
- ],
291
- ],
292
- [
293
- 'falsy-but-groupable order ids (0 and empty string)',
294
- [
295
- { order_id: 0, trade_id: 'a', price: 1, amount: 1, total: 1, close_time: new Date(1786900000000) },
296
- { order_id: 0, trade_id: 'b', price: 1, amount: 2, total: 2, close_time: new Date(1786900001000) },
297
- { order_id: '', trade_id: 'c', price: 1, amount: 3, total: 3, close_time: new Date(1786900002000) },
298
- { order_id: '', trade_id: 'd', price: 1, amount: 4, total: 4, close_time: new Date(1786900003000) },
299
- ],
300
- ],
301
- [
302
- 'empty fill_history array rebuilds from the row',
303
- [
304
- { order_id: 'o1', trade_id: 'a', price: 1, amount: 1, total: 1, fill_history: [], close_time: new Date(1786900000000) },
305
- { order_id: 'o1', trade_id: 'b', price: 1, amount: 1, total: 1, close_time: new Date(1786900001000) },
306
- ],
307
- ],
308
- ]
309
- for (const [name, fixture] of edge_cases) {
310
- eq(merge_trades_with_same_id(structuredClone(fixture)), legacy_merge(structuredClone(fixture)), 'edge: ' + name)
311
- }
312
- // larger-scale differential once (legacy is quadratic — keep n moderate)
313
- const big_diff = Array.from({ length: 5000 }, (_, i) => random_row(i))
314
- eq(merge_trades_with_same_id(structuredClone(big_diff)), legacy_merge(structuredClone(big_diff)), 'differential n=5000')
315
-
316
- // timing signal only (not asserted)
317
- const big = Array.from({ length: 3000 }, (_, i) => random_row(i))
318
- let t = Date.now()
319
- legacy_merge(structuredClone(big))
320
- const legacy_ms = Date.now() - t
321
- t = Date.now()
322
- merge_trades_with_same_id(big)
323
- const new_ms = Date.now() - t
324
- console.log(` 3000 rows: legacy ${legacy_ms}ms, group-by ${new_ms}ms`)
325
-
326
- console.log(`merge-trades: ${pass} passed, ${fail} failed`)
327
- process.exit(fail > 0 ? 1 : 0)