@icgio/icg-utils 1.9.66 → 1.9.67
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 +49 -44
- package/package.json +1 -1
- package/test/merge-trades.test.js +206 -8
package/lib/utils.js
CHANGED
|
@@ -504,6 +504,9 @@ function merge_trades_with_same_time(array) {
|
|
|
504
504
|
}
|
|
505
505
|
}
|
|
506
506
|
|
|
507
|
+
// Groups fills by order_id into one row per order (name is historical): amounts/totals
|
|
508
|
+
// summed, fees merged, open_time earliest, close_time latest, per-fill detail kept in
|
|
509
|
+
// fill_history. O(n) single pass; does not mutate the input rows.
|
|
507
510
|
function merge_trades_with_same_id(array) {
|
|
508
511
|
let normalize_fee_amount = (value) => {
|
|
509
512
|
const normalized = parseFloat(value || 0)
|
|
@@ -542,57 +545,59 @@ function merge_trades_with_same_id(array) {
|
|
|
542
545
|
}
|
|
543
546
|
|
|
544
547
|
if (array.length === 1) {
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
548
|
+
let trade = Object.assign({}, array[0])
|
|
549
|
+
if (trade.fees && typeof trade.fees === 'object') trade.fees = normalize_fee_map(trade.fees)
|
|
550
|
+
trade.fill_history = get_fill_history(trade)
|
|
551
|
+
strip_trade_fill_id(trade)
|
|
552
|
+
return [trade]
|
|
549
553
|
} else {
|
|
554
|
+
// Single-pass group-by: rows sharing an order_id fold into the first occurrence
|
|
555
|
+
// (a copy — the input rows are never mutated). Output keeps first-occurrence order.
|
|
550
556
|
let trades = []
|
|
551
|
-
let
|
|
552
|
-
for (
|
|
553
|
-
|
|
554
|
-
|
|
557
|
+
let row_by_order_id = new Map()
|
|
558
|
+
for (const source of array) {
|
|
559
|
+
// Strict-equality grouping like the original pairwise scan: null/undefined never
|
|
560
|
+
// group, and neither does NaN (Map would treat NaN keys as equal).
|
|
561
|
+
const groupable = source.order_id != null && source.order_id === source.order_id
|
|
562
|
+
let trade = groupable ? row_by_order_id.get(source.order_id) : undefined
|
|
563
|
+
if (!trade) {
|
|
564
|
+
trade = Object.assign({}, source)
|
|
555
565
|
if (trade.fees && typeof trade.fees === 'object') trade.fees = normalize_fee_map(trade.fees)
|
|
556
566
|
trade.fill_history = get_fill_history(trade)
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
trade.fees[cur] = sum_numeric_fee_amount(trade.fees[cur], amount)
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
if (to_compare_trade.open_time && (!trade.open_time || to_compare_trade.open_time < trade.open_time)) {
|
|
575
|
-
trade.open_time = to_compare_trade.open_time
|
|
576
|
-
}
|
|
577
|
-
// Use latest close_time so grouped trades remain visible when later fills land near reconciliation cutoffs.
|
|
578
|
-
if (to_compare_trade.close_time && (!trade.close_time || to_compare_trade.close_time > trade.close_time)) {
|
|
579
|
-
trade.close_time = to_compare_trade.close_time
|
|
580
|
-
}
|
|
581
|
-
processed_index_set.add(j)
|
|
582
|
-
}
|
|
567
|
+
if (groupable) row_by_order_id.set(source.order_id, trade)
|
|
568
|
+
trades.push(trade)
|
|
569
|
+
continue
|
|
570
|
+
}
|
|
571
|
+
trade.amount = trade.amount + source.amount
|
|
572
|
+
trade.total = trade.total + source.total
|
|
573
|
+
trade.fill_history = trade.fill_history.concat(get_fill_history(source))
|
|
574
|
+
if (source.fees && typeof source.fees === 'object') {
|
|
575
|
+
if (!trade.fees || typeof trade.fees !== 'object') {
|
|
576
|
+
trade.fees = normalize_fee_map(source.fees)
|
|
577
|
+
} else {
|
|
578
|
+
for (const [cur, amount] of Object.entries(source.fees)) {
|
|
579
|
+
trade.fees[cur] = sum_numeric_fee_amount(trade.fees[cur], amount)
|
|
583
580
|
}
|
|
584
581
|
}
|
|
585
|
-
trade.amount = parseFloat(trade.amount)
|
|
586
|
-
trade.total = parseFloat(trade.total)
|
|
587
|
-
trade.price = trade.total / trade.amount
|
|
588
|
-
trade.fill_history = trade.fill_history.sort((a, b) => {
|
|
589
|
-
let a_time = a.time ? new Date(a.time).getTime() : 0
|
|
590
|
-
let b_time = b.time ? new Date(b.time).getTime() : 0
|
|
591
|
-
return a_time - b_time
|
|
592
|
-
})
|
|
593
|
-
strip_trade_fill_id(trade)
|
|
594
|
-
trades.push(trade)
|
|
595
582
|
}
|
|
583
|
+
if (source.open_time && (!trade.open_time || source.open_time < trade.open_time)) {
|
|
584
|
+
trade.open_time = source.open_time
|
|
585
|
+
}
|
|
586
|
+
// Use latest close_time so grouped trades remain visible when later fills land near reconciliation cutoffs.
|
|
587
|
+
if (source.close_time && (!trade.close_time || source.close_time > trade.close_time)) {
|
|
588
|
+
trade.close_time = source.close_time
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
for (const trade of trades) {
|
|
592
|
+
trade.amount = parseFloat(trade.amount)
|
|
593
|
+
trade.total = parseFloat(trade.total)
|
|
594
|
+
trade.price = trade.total / trade.amount
|
|
595
|
+
trade.fill_history = trade.fill_history.sort((a, b) => {
|
|
596
|
+
let a_time = a.time ? new Date(a.time).getTime() : 0
|
|
597
|
+
let b_time = b.time ? new Date(b.time).getTime() : 0
|
|
598
|
+
return a_time - b_time
|
|
599
|
+
})
|
|
600
|
+
strip_trade_fill_id(trade)
|
|
596
601
|
}
|
|
597
602
|
return trades
|
|
598
603
|
}
|
package/package.json
CHANGED
|
@@ -1,19 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
const { merge_trades_with_same_id } = require('../lib/utils.js')
|
|
3
3
|
|
|
4
|
-
let pass = 0,
|
|
4
|
+
let pass = 0,
|
|
5
|
+
fail = 0
|
|
5
6
|
function assert(condition, msg) {
|
|
6
|
-
if (condition) {
|
|
7
|
-
|
|
7
|
+
if (condition) {
|
|
8
|
+
pass++
|
|
9
|
+
} else {
|
|
10
|
+
fail++
|
|
11
|
+
console.log(' FAIL:', msg)
|
|
12
|
+
}
|
|
8
13
|
}
|
|
9
14
|
function eq(a, b, msg) {
|
|
10
|
-
const as = JSON.stringify(a),
|
|
11
|
-
|
|
12
|
-
|
|
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
|
+
}
|
|
13
23
|
}
|
|
14
24
|
function approx(a, b, epsilon, msg) {
|
|
15
|
-
if (Math.abs(a - b) <= epsilon) {
|
|
16
|
-
|
|
25
|
+
if (Math.abs(a - b) <= epsilon) {
|
|
26
|
+
pass++
|
|
27
|
+
} else {
|
|
28
|
+
fail++
|
|
29
|
+
console.log(' FAIL:', msg, '— got', a, 'expected', b)
|
|
30
|
+
}
|
|
17
31
|
}
|
|
18
32
|
|
|
19
33
|
console.log('--- merge_trades_with_same_id ---')
|
|
@@ -127,3 +141,187 @@ eq(typeof singleTrade[0].fill_history[0].fees.USDT, 'number', 'normalizes single
|
|
|
127
141
|
|
|
128
142
|
console.log(`pass=${pass} fail=${fail}`)
|
|
129
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)
|