@arca-network/sdk 1.1.0

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.
Files changed (67) hide show
  1. package/LICENSE +91 -0
  2. package/README.md +65 -0
  3. package/dist/admin.d.ts +159 -0
  4. package/dist/admin.d.ts.map +1 -0
  5. package/dist/admin.js +399 -0
  6. package/dist/admin.js.map +1 -0
  7. package/dist/arca.d.ts +1343 -0
  8. package/dist/arca.d.ts.map +1 -0
  9. package/dist/arca.js +3454 -0
  10. package/dist/arca.js.map +1 -0
  11. package/dist/cache.d.ts +29 -0
  12. package/dist/cache.d.ts.map +1 -0
  13. package/dist/cache.js +74 -0
  14. package/dist/cache.js.map +1 -0
  15. package/dist/candle-cdn.d.ts +17 -0
  16. package/dist/candle-cdn.d.ts.map +1 -0
  17. package/dist/candle-cdn.js +138 -0
  18. package/dist/candle-cdn.js.map +1 -0
  19. package/dist/client.d.ts +98 -0
  20. package/dist/client.d.ts.map +1 -0
  21. package/dist/client.js +225 -0
  22. package/dist/client.js.map +1 -0
  23. package/dist/errors.d.ts +153 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +243 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/events.d.ts +2 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +6 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/index.d.ts +21 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +71 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/ladder.d.ts +40 -0
  36. package/dist/ladder.d.ts.map +1 -0
  37. package/dist/ladder.js +145 -0
  38. package/dist/ladder.js.map +1 -0
  39. package/dist/ladder.test.d.ts +2 -0
  40. package/dist/ladder.test.d.ts.map +1 -0
  41. package/dist/ladder.test.js +112 -0
  42. package/dist/ladder.test.js.map +1 -0
  43. package/dist/operation-handle.d.ts +88 -0
  44. package/dist/operation-handle.d.ts.map +1 -0
  45. package/dist/operation-handle.js +262 -0
  46. package/dist/operation-handle.js.map +1 -0
  47. package/dist/recovery.d.ts +20 -0
  48. package/dist/recovery.d.ts.map +1 -0
  49. package/dist/recovery.js +91 -0
  50. package/dist/recovery.js.map +1 -0
  51. package/dist/revalue.d.ts +22 -0
  52. package/dist/revalue.d.ts.map +1 -0
  53. package/dist/revalue.js +153 -0
  54. package/dist/revalue.js.map +1 -0
  55. package/dist/streams.d.ts +661 -0
  56. package/dist/streams.d.ts.map +1 -0
  57. package/dist/streams.js +2272 -0
  58. package/dist/streams.js.map +1 -0
  59. package/dist/types.d.ts +2814 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/types.js +118 -0
  62. package/dist/types.js.map +1 -0
  63. package/dist/websocket.d.ts +240 -0
  64. package/dist/websocket.d.ts.map +1 -0
  65. package/dist/websocket.js +1288 -0
  66. package/dist/websocket.js.map +1 -0
  67. package/package.json +48 -0
@@ -0,0 +1,2272 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FundingWatchStream = exports.FillWatchStream = exports.TwapWatchStream = exports.ExchangeWatchStream = exports.CandleChartStream = exports.CoverageTracker = exports.TradeWatchStream = exports.CandleWatchStream = exports.PriceWatchStream = exports.MaxOrderSizeWatchStream = exports.PnlChartStream = exports.EquityChartStream = exports.AggregationWatchStream = exports.ObjectsWatchStream = exports.ObjectWatchStream = exports.BalanceWatchStream = exports.OperationWatchStream = exports.WatchStreamReadyTimeoutError = void 0;
4
+ exports.deriveActiveAssetDataFromState = deriveActiveAssetDataFromState;
5
+ const revalue_1 = require("./revalue");
6
+ /**
7
+ * Thrown by `WatchStream.ready(timeoutMs)` when the stream does not reach
8
+ * `connected` within the given timeout. The stream itself is not torn down
9
+ * — it keeps trying in the background. Call `.close()` if you want to stop.
10
+ */
11
+ class WatchStreamReadyTimeoutError extends Error {
12
+ timeoutMs;
13
+ name = 'WatchStreamReadyTimeoutError';
14
+ constructor(timeoutMs) {
15
+ super(`Watch stream did not reach 'connected' within ${timeoutMs}ms`);
16
+ this.timeoutMs = timeoutMs;
17
+ }
18
+ }
19
+ exports.WatchStreamReadyTimeoutError = WatchStreamReadyTimeoutError;
20
+ /**
21
+ * Base class for all watch streams. Manages callbacks, cleanup,
22
+ * lifecycle state, and provides Symbol.asyncDispose / Symbol.asyncIterator support.
23
+ *
24
+ * Streams follow a state machine: loading → connected ⇄ reconnecting.
25
+ * They never enter a terminal error state; they keep retrying indefinitely
26
+ * via the underlying WebSocket reconnection.
27
+ */
28
+ class WatchStream {
29
+ updateCallbacks = new Set();
30
+ stateCallbacks = new Set();
31
+ _state = 'loading';
32
+ closed = false;
33
+ readyResolve;
34
+ readyPromise;
35
+ constructor() {
36
+ this.readyPromise = new Promise((resolve) => {
37
+ this.readyResolve = resolve;
38
+ });
39
+ }
40
+ /** Current lifecycle state of the stream. */
41
+ get state() {
42
+ return this._state;
43
+ }
44
+ /**
45
+ * Returns a promise that resolves when the first snapshot is received.
46
+ *
47
+ * By default this never rejects — the stream retries indefinitely via
48
+ * the underlying WebSocket reconnection logic. Pass `timeoutMs` to
49
+ * bound the wait and reject with `WatchStreamReadyTimeoutError` if the
50
+ * stream does not reach `connected` within that window. This is useful
51
+ * at app startup when you want to fall back to a degraded state (or
52
+ * show an error to the user) instead of hanging forever if the backend
53
+ * is unreachable.
54
+ *
55
+ * If the stream is already connected, resolves immediately regardless
56
+ * of `timeoutMs`.
57
+ *
58
+ * @param timeoutMs - Optional timeout in milliseconds.
59
+ */
60
+ ready(timeoutMs) {
61
+ if (this._state === 'connected')
62
+ return Promise.resolve();
63
+ if (timeoutMs === undefined)
64
+ return this.readyPromise;
65
+ return new Promise((resolve, reject) => {
66
+ const timer = setTimeout(() => {
67
+ reject(new WatchStreamReadyTimeoutError(timeoutMs));
68
+ }, timeoutMs);
69
+ this.readyPromise.then(() => {
70
+ clearTimeout(timer);
71
+ resolve();
72
+ });
73
+ });
74
+ }
75
+ /**
76
+ * Register a callback for each update. Returns an unsubscribe function.
77
+ */
78
+ onUpdate(cb) {
79
+ this.updateCallbacks.add(cb);
80
+ return () => { this.updateCallbacks.delete(cb); };
81
+ }
82
+ /**
83
+ * Register a callback for state changes. Returns an unsubscribe function.
84
+ */
85
+ onStateChange(cb) {
86
+ this.stateCallbacks.add(cb);
87
+ return () => { this.stateCallbacks.delete(cb); };
88
+ }
89
+ /**
90
+ * Stop listening and release the underlying subscription.
91
+ */
92
+ close() {
93
+ if (this.closed)
94
+ return;
95
+ this.closed = true;
96
+ this.updateCallbacks.clear();
97
+ this.stateCallbacks.clear();
98
+ this.doClose();
99
+ }
100
+ get isClosed() {
101
+ return this.closed;
102
+ }
103
+ setState(newState) {
104
+ if (newState === this._state || this.closed)
105
+ return;
106
+ this._state = newState;
107
+ if (newState === 'connected' && this.readyResolve) {
108
+ this.readyResolve();
109
+ this.readyResolve = undefined;
110
+ }
111
+ this.stateCallbacks.forEach(cb => cb(newState));
112
+ }
113
+ emit(data) {
114
+ if (this.closed)
115
+ return;
116
+ this.updateCallbacks.forEach(cb => cb(data));
117
+ }
118
+ /**
119
+ * Iterate over updates asynchronously.
120
+ * If the consumer is slower than the stream, updates are queued.
121
+ * The queue is capped at 1000 items to prevent unbounded memory growth.
122
+ * If the queue overflows, the oldest items are dropped.
123
+ */
124
+ [Symbol.asyncIterator]() {
125
+ const queue = [];
126
+ const MAX_QUEUE = 1000;
127
+ let resolve = null;
128
+ let done = false;
129
+ const unsub = this.onUpdate((data) => {
130
+ if (resolve) {
131
+ const r = resolve;
132
+ resolve = null;
133
+ r({ value: data, done: false });
134
+ }
135
+ else {
136
+ queue.push(data);
137
+ if (queue.length > MAX_QUEUE) {
138
+ queue.shift(); // drop oldest on overflow
139
+ }
140
+ }
141
+ });
142
+ const cleanup = () => {
143
+ done = true;
144
+ unsub();
145
+ if (resolve) {
146
+ const r = resolve;
147
+ resolve = null;
148
+ r({ value: undefined, done: true });
149
+ }
150
+ };
151
+ return {
152
+ next: () => {
153
+ if (done)
154
+ return Promise.resolve({ value: undefined, done: true });
155
+ if (queue.length > 0) {
156
+ return Promise.resolve({ value: queue.shift(), done: false });
157
+ }
158
+ return new Promise((r) => { resolve = r; });
159
+ },
160
+ return: () => {
161
+ cleanup();
162
+ this.close();
163
+ return Promise.resolve({ value: undefined, done: true });
164
+ },
165
+ [Symbol.asyncIterator]() { return this; },
166
+ };
167
+ }
168
+ [Symbol.asyncDispose]() {
169
+ this.close();
170
+ return Promise.resolve();
171
+ }
172
+ }
173
+ class OperationWatchStream extends WatchStream {
174
+ ws;
175
+ path;
176
+ refetchOperations;
177
+ maxOperations;
178
+ operations = [];
179
+ unsubs = [];
180
+ gapRefetchInFlight = false;
181
+ constructor(ws, path, refetchOperations, maxOperations = 500) {
182
+ super();
183
+ this.ws = ws;
184
+ this.path = path;
185
+ this.refetchOperations = refetchOperations;
186
+ this.maxOperations = maxOperations;
187
+ this.unsubs.push(this.ws.onStatus((status) => {
188
+ if (status === 'disconnected' && this.state !== 'loading') {
189
+ this.setState('reconnecting');
190
+ }
191
+ }), this.ws.onOperationCreated((op, event) => {
192
+ if (this.path !== '/' && event.entityPath && !event.entityPath.startsWith(this.path))
193
+ return;
194
+ const synthIdx = this.operations.findIndex(o => o.id === op.path && o.state === 'submitting');
195
+ if (synthIdx >= 0) {
196
+ this.operations[synthIdx] = op;
197
+ }
198
+ else {
199
+ this.operations.unshift(op);
200
+ if (this.operations.length > this.maxOperations) {
201
+ this.operations.length = this.maxOperations;
202
+ }
203
+ }
204
+ this.emit({ operation: op, event });
205
+ }), this.ws.onOperationUpdated((op, event) => {
206
+ if (this.path !== '/' && event.entityPath && !event.entityPath.startsWith(this.path))
207
+ return;
208
+ const idx = this.operations.findIndex(o => o.id === op.id);
209
+ if (idx >= 0)
210
+ this.operations[idx] = op;
211
+ this.emit({ operation: op, event });
212
+ }), this.ws.onGap(() => { this.handleGap(); }));
213
+ this.ws.watchPath(path).then((snapshot) => {
214
+ this.operations.length = 0;
215
+ if (snapshot.operations) {
216
+ this.operations.push(...snapshot.operations);
217
+ }
218
+ if (snapshot.bufferedOperations) {
219
+ for (const op of snapshot.bufferedOperations) {
220
+ const idx = this.operations.findIndex(o => o.id === op.id);
221
+ if (idx >= 0) {
222
+ this.operations[idx] = op;
223
+ }
224
+ else {
225
+ this.operations.unshift(op);
226
+ if (this.operations.length > this.maxOperations) {
227
+ this.operations.length = this.maxOperations;
228
+ }
229
+ }
230
+ }
231
+ }
232
+ this.setState('connected');
233
+ }).catch(() => { });
234
+ }
235
+ handleGap() {
236
+ if (!this.refetchOperations || this.gapRefetchInFlight || this.isClosed)
237
+ return;
238
+ this.gapRefetchInFlight = true;
239
+ this.refetchOperations()
240
+ .then((ops) => {
241
+ if (this.isClosed)
242
+ return;
243
+ this.operations.length = 0;
244
+ this.operations.push(...ops);
245
+ })
246
+ .catch(() => { })
247
+ .finally(() => { this.gapRefetchInFlight = false; });
248
+ }
249
+ /**
250
+ * Track an operation from the moment it is submitted (before HTTP completes).
251
+ * Immediately adds a synthetic `{ state: 'submitting' }` entry so the UI
252
+ * can show that something is in progress. Transitions to `pending` when
253
+ * the HTTP response arrives, then to the terminal state on server events.
254
+ */
255
+ trackSubmission(handle) {
256
+ const now = new Date().toISOString();
257
+ const predictedType = handle.predicted?.type;
258
+ const opType = (predictedType === 'transfer' || predictedType === 'order') ? predictedType : 'transfer';
259
+ const syntheticOp = {
260
+ id: `op_${'0'.repeat(26)}`,
261
+ realmId: `rlm_${'0'.repeat(26)}`,
262
+ path: '',
263
+ type: opType,
264
+ state: 'pending',
265
+ sourceArcaPath: null,
266
+ targetArcaPath: null,
267
+ input: null,
268
+ outcome: null,
269
+ parsedOutcome: null,
270
+ failureMessage: null,
271
+ actorType: null,
272
+ actorId: null,
273
+ tokenJti: null,
274
+ workflowIds: null,
275
+ createdAt: now,
276
+ updatedAt: now,
277
+ _synthetic: true,
278
+ };
279
+ this.operations.unshift(syntheticOp);
280
+ if (this.operations.length > this.maxOperations) {
281
+ this.operations.length = this.maxOperations;
282
+ }
283
+ this.emit({ operation: syntheticOp, event: { type: 'operation.submitting' } });
284
+ handle.submitted.then(response => {
285
+ const idx = this.operations.indexOf(syntheticOp);
286
+ if (idx >= 0 && response.operation) {
287
+ this.operations[idx] = response.operation;
288
+ this.emit({ operation: response.operation, event: { type: 'operation.created' } });
289
+ }
290
+ else if (idx >= 0) {
291
+ this.operations.splice(idx, 1);
292
+ }
293
+ }).catch(() => {
294
+ const idx = this.operations.indexOf(syntheticOp);
295
+ if (idx >= 0)
296
+ this.operations.splice(idx, 1);
297
+ });
298
+ }
299
+ doClose() {
300
+ this.unsubs.forEach(u => u());
301
+ this.ws.unwatchPath(this.path);
302
+ }
303
+ }
304
+ exports.OperationWatchStream = OperationWatchStream;
305
+ class BalanceWatchStream extends WatchStream {
306
+ ws;
307
+ path;
308
+ refetchEntityBalances;
309
+ balances = new Map();
310
+ unsubs = [];
311
+ activePredictions = new Map();
312
+ gapRefetchInFlight = false;
313
+ constructor(ws, path, refetchEntityBalances) {
314
+ super();
315
+ this.ws = ws;
316
+ this.path = path;
317
+ this.refetchEntityBalances = refetchEntityBalances;
318
+ this.unsubs.push(this.ws.onStatus((status) => {
319
+ if (status === 'disconnected' && this.state !== 'loading') {
320
+ this.setState('reconnecting');
321
+ }
322
+ }), this.ws.onGap(() => { this.handleGap(); }), this.ws.onBalanceUpdated((entityId, event) => {
323
+ if (this.path !== '/' && event.entityPath && !event.entityPath.startsWith(this.path)) {
324
+ return;
325
+ }
326
+ const rawBalances = event.balances;
327
+ if (event.entityPath) {
328
+ this.activePredictions.delete(event.entityPath);
329
+ }
330
+ const update = {
331
+ entityId,
332
+ entityPath: event.entityPath,
333
+ balances: rawBalances,
334
+ event,
335
+ };
336
+ if (rawBalances) {
337
+ this.balances.set(entityId, {
338
+ entityId,
339
+ entityPath: event.entityPath,
340
+ balances: rawBalances,
341
+ });
342
+ }
343
+ this.emit(update);
344
+ }));
345
+ this.ws.watchPath(path).then((snapshot) => {
346
+ this.balances.clear();
347
+ if (snapshot.balances) {
348
+ for (const entry of snapshot.balances) {
349
+ this.balances.set(entry.entityId, {
350
+ entityId: entry.entityId,
351
+ entityPath: entry.entityPath,
352
+ balances: entry.balances,
353
+ });
354
+ }
355
+ }
356
+ this.setState('connected');
357
+ }).catch(() => { });
358
+ }
359
+ /**
360
+ * Optimistically apply predicted balance effects from an operation handle.
361
+ * Immediately emits a balance update with the predicted `departing`/`arriving`
362
+ * amounts overlaid on the current snapshot. When the server's `balance.updated`
363
+ * event arrives, the prediction is reconciled and replaced. If the operation
364
+ * fails, the prediction is rolled back.
365
+ */
366
+ applyPrediction(handle) {
367
+ if (!handle.predicted?.balanceChanges)
368
+ return;
369
+ const id = String(Date.now()) + Math.random();
370
+ for (const [path, changes] of Object.entries(handle.predicted.balanceChanges)) {
371
+ this.activePredictions.set(path, { prediction: handle.predicted, submitted: handle.submitted });
372
+ const existing = this.findSnapshotByPath(path);
373
+ if (!existing)
374
+ continue;
375
+ const balances = (existing.balances ?? []).map(b => {
376
+ const patched = { ...b };
377
+ if (changes.departing) {
378
+ const current = parseFloat(patched.departing ?? '0');
379
+ patched.departing = String(current + parseFloat(changes.departing));
380
+ const settled = parseFloat(patched.settled ?? patched.amount ?? '0');
381
+ patched.settled = String(settled - parseFloat(changes.departing));
382
+ }
383
+ if (changes.arriving) {
384
+ const current = parseFloat(patched.arriving ?? '0');
385
+ patched.arriving = String(current + parseFloat(changes.arriving));
386
+ const total = parseFloat(patched.total ?? patched.amount ?? '0');
387
+ patched.total = String(total + parseFloat(changes.arriving));
388
+ }
389
+ return patched;
390
+ });
391
+ this.balances.set(existing.entityId, { ...existing, balances });
392
+ this.emit({
393
+ entityId: existing.entityId,
394
+ entityPath: path,
395
+ balances,
396
+ event: { type: 'balance.predicted' },
397
+ });
398
+ }
399
+ // Roll back on failure
400
+ handle.submitted.catch(() => {
401
+ for (const path of Object.keys(handle.predicted.balanceChanges)) {
402
+ if (this.activePredictions.get(path)?.prediction === handle.predicted) {
403
+ this.activePredictions.delete(path);
404
+ }
405
+ }
406
+ });
407
+ }
408
+ findSnapshotByPath(path) {
409
+ for (const snap of this.balances.values()) {
410
+ if (snap.entityPath === path)
411
+ return snap;
412
+ }
413
+ return undefined;
414
+ }
415
+ handleGap() {
416
+ if (!this.refetchEntityBalances || this.gapRefetchInFlight || this.isClosed)
417
+ return;
418
+ this.gapRefetchInFlight = true;
419
+ const entries = Array.from(this.balances.entries());
420
+ Promise.all(entries.map(([entityId, snap]) => this.refetchEntityBalances(entityId)
421
+ .then((bals) => {
422
+ if (this.isClosed)
423
+ return;
424
+ this.balances.set(entityId, { ...snap, balances: bals });
425
+ })
426
+ .catch(() => { }))).finally(() => { this.gapRefetchInFlight = false; });
427
+ }
428
+ doClose() {
429
+ this.unsubs.forEach(u => u());
430
+ this.ws.unwatchPath(this.path);
431
+ }
432
+ }
433
+ exports.BalanceWatchStream = BalanceWatchStream;
434
+ class ObjectWatchStream extends WatchStream {
435
+ ws;
436
+ path;
437
+ exchange;
438
+ refetchValuation;
439
+ valuation;
440
+ unsubs = [];
441
+ latestMids = {};
442
+ structuralValuation;
443
+ gapRefetchInFlight = false;
444
+ constructor(ws, path, exchange = 'sim', refetchValuation) {
445
+ super();
446
+ this.ws = ws;
447
+ this.path = path;
448
+ this.exchange = exchange;
449
+ this.refetchValuation = refetchValuation;
450
+ this.ws.acquireMids(exchange);
451
+ this.unsubs.push(this.ws.onStatus((status) => {
452
+ if (status === 'disconnected' && this.state !== 'loading') {
453
+ this.setState('reconnecting');
454
+ }
455
+ }), this.ws.onGap(() => { this.handleGap(); }), this.ws.onObjectValuation((eventPath, valuation, watchId, event) => {
456
+ if (eventPath !== this.path)
457
+ return;
458
+ if (event.driftCorrected) {
459
+ console.warn(`[Arca] Valuation drift corrected for ${eventPath} (watchId: ${watchId}). Previous value was stale.`);
460
+ }
461
+ const resolved = valuation ?? {
462
+ objectId: 'obj_',
463
+ path: eventPath,
464
+ type: '',
465
+ denomination: null,
466
+ valueUsd: '0',
467
+ balances: [],
468
+ reservedBalances: [],
469
+ positions: null,
470
+ };
471
+ this.structuralValuation = resolved;
472
+ const hasPrice = Object.keys(this.latestMids).length > 0;
473
+ const revalued = hasPrice ? (0, revalue_1.revalueObject)(resolved, this.latestMids) : resolved;
474
+ this.valuation = revalued;
475
+ this.setState('connected');
476
+ this.emit(revalued);
477
+ }), this.ws.onMidsUpdated((mids) => {
478
+ Object.assign(this.latestMids, mids);
479
+ if (!this.structuralValuation)
480
+ return;
481
+ const revalued = (0, revalue_1.revalueObject)(this.structuralValuation, this.latestMids);
482
+ this.valuation = revalued;
483
+ this.emit(revalued);
484
+ }));
485
+ this.ws.watchPath(path).then((snapshot) => {
486
+ if (snapshot.valuation && !this.structuralValuation) {
487
+ this.structuralValuation = snapshot.valuation;
488
+ const hasPrice = Object.keys(this.latestMids).length > 0;
489
+ const revalued = hasPrice ? (0, revalue_1.revalueObject)(snapshot.valuation, this.latestMids) : snapshot.valuation;
490
+ this.valuation = revalued;
491
+ this.setState('connected');
492
+ this.emit(revalued);
493
+ }
494
+ }).catch(() => { });
495
+ }
496
+ handleGap() {
497
+ if (!this.refetchValuation || this.gapRefetchInFlight || this.isClosed)
498
+ return;
499
+ this.gapRefetchInFlight = true;
500
+ this.refetchValuation()
501
+ .then((valuation) => {
502
+ if (this.isClosed)
503
+ return;
504
+ this.structuralValuation = valuation;
505
+ const hasPrice = Object.keys(this.latestMids).length > 0;
506
+ const revalued = hasPrice ? (0, revalue_1.revalueObject)(valuation, this.latestMids) : valuation;
507
+ this.valuation = revalued;
508
+ this.emit(revalued);
509
+ })
510
+ .catch(() => { })
511
+ .finally(() => { this.gapRefetchInFlight = false; });
512
+ }
513
+ doClose() {
514
+ this.unsubs.forEach(u => u());
515
+ this.ws.releaseMids();
516
+ this.ws.unwatchPath(this.path);
517
+ }
518
+ }
519
+ exports.ObjectWatchStream = ObjectWatchStream;
520
+ /**
521
+ * Manages multiple ObjectWatchStream instances and emits a merged
522
+ * Map<path, ObjectValuation> on every update from any child stream.
523
+ * Close this stream to close all children.
524
+ */
525
+ class ObjectsWatchStream extends WatchStream {
526
+ valuations = new Map();
527
+ children = [];
528
+ childUnsubs = [];
529
+ constructor(streams) {
530
+ super();
531
+ this.children = streams;
532
+ for (const child of streams) {
533
+ if (child.valuation) {
534
+ this.valuations.set(child['path'], child.valuation);
535
+ }
536
+ const unsub = child.onUpdate((val) => {
537
+ this.valuations.set(child['path'], val);
538
+ this.emit(new Map(this.valuations));
539
+ });
540
+ this.childUnsubs.push(unsub);
541
+ }
542
+ const allReady = streams.every(s => s.state === 'connected');
543
+ if (allReady && streams.length > 0) {
544
+ this.setState('connected');
545
+ this.emit(new Map(this.valuations));
546
+ }
547
+ else if (streams.length === 0) {
548
+ this.setState('connected');
549
+ this.emit(new Map());
550
+ }
551
+ else {
552
+ const readyChecks = streams.map(s => s.ready());
553
+ Promise.all(readyChecks).then(() => {
554
+ if (this.isClosed)
555
+ return;
556
+ this.setState('connected');
557
+ this.emit(new Map(this.valuations));
558
+ }).catch(() => { });
559
+ }
560
+ }
561
+ doClose() {
562
+ this.childUnsubs.forEach(u => u());
563
+ this.children.forEach(c => c.close());
564
+ }
565
+ }
566
+ exports.ObjectsWatchStream = ObjectsWatchStream;
567
+ class AggregationWatchStream extends WatchStream {
568
+ ws;
569
+ refreshWatch;
570
+ aggregation;
571
+ _watchId;
572
+ unsubs = [];
573
+ latestMids = {};
574
+ structuralAggregation;
575
+ destroyWatch;
576
+ refreshing = false;
577
+ get watchId() { return this._watchId; }
578
+ constructor(ws, watchId, initialAggregation, destroyWatch, refreshWatch, exchange = 'sim') {
579
+ super();
580
+ this.ws = ws;
581
+ this.refreshWatch = refreshWatch;
582
+ this._watchId = watchId;
583
+ this.structuralAggregation = initialAggregation;
584
+ this.aggregation = initialAggregation;
585
+ this.destroyWatch = destroyWatch;
586
+ this.ws.acquireMids(exchange);
587
+ this.unsubs.push(this.ws.onStatus((status) => {
588
+ if (status === 'disconnected' && this.state !== 'loading') {
589
+ this.setState('reconnecting');
590
+ }
591
+ else if (status === 'connected' && this.state === 'reconnecting') {
592
+ this.handleReconnect();
593
+ }
594
+ }), this.ws.onAggregationUpdated((eventWatchId, agg) => {
595
+ if (eventWatchId !== this._watchId || !agg)
596
+ return;
597
+ this.structuralAggregation = agg;
598
+ const hasPrice = Object.keys(this.latestMids).length > 0;
599
+ const revalued = hasPrice ? (0, revalue_1.revalueAggregation)(agg, this.latestMids) : agg;
600
+ this.aggregation = revalued;
601
+ this.emit(revalued);
602
+ }), this.ws.onMidsUpdated((mids) => {
603
+ Object.assign(this.latestMids, mids);
604
+ if (!this.structuralAggregation)
605
+ return;
606
+ const revalued = (0, revalue_1.revalueAggregation)(this.structuralAggregation, this.latestMids);
607
+ this.aggregation = revalued;
608
+ this.emit(revalued);
609
+ }));
610
+ this.setState('connected');
611
+ }
612
+ handleReconnect() {
613
+ if (this.refreshing)
614
+ return;
615
+ this.refreshing = true;
616
+ this.refreshWatch()
617
+ .then(({ watchId: newId, aggregation, destroyWatch: newDestroy }) => {
618
+ this.destroyWatch?.().catch(() => { });
619
+ if (this.isClosed) {
620
+ newDestroy().catch(() => { });
621
+ return;
622
+ }
623
+ this._watchId = newId;
624
+ this.destroyWatch = newDestroy;
625
+ this.structuralAggregation = aggregation;
626
+ const hasPrice = Object.keys(this.latestMids).length > 0;
627
+ const revalued = hasPrice ? (0, revalue_1.revalueAggregation)(aggregation, this.latestMids) : aggregation;
628
+ this.aggregation = revalued;
629
+ this.emit(revalued);
630
+ this.setState('connected');
631
+ })
632
+ .catch(() => {
633
+ this.setState('connected');
634
+ })
635
+ .finally(() => { this.refreshing = false; });
636
+ }
637
+ doClose() {
638
+ this.unsubs.forEach(u => u());
639
+ this.ws.releaseMids();
640
+ this.destroyWatch?.().catch(() => { });
641
+ }
642
+ }
643
+ exports.AggregationWatchStream = AggregationWatchStream;
644
+ function resolutionToMs(resolution) {
645
+ switch (resolution) {
646
+ case '15s': return 15_000;
647
+ case '1m': return 60_000;
648
+ case '5m': return 300_000;
649
+ case '1h':
650
+ case 'hour': return 3_600_000;
651
+ case '1d':
652
+ case 'day': return 86_400_000;
653
+ default: return 3_600_000;
654
+ }
655
+ }
656
+ class EquityChartStream extends WatchStream {
657
+ // Boundary timer cadence: 30 s is responsive enough to catch a quiet-realm
658
+ // boundary cross within a fraction of any normal resolution (>= 1 m), yet
659
+ // cheap enough that even a 1 d chart only does ~2880 timer ticks/day.
660
+ static BOUNDARY_CHECK_INTERVAL_MS = 30_000;
661
+ // If no aggregation event has arrived for this much wall-clock time AND
662
+ // the bucket boundary has advanced, we treat it as a tab freeze / quiet
663
+ // realm and refetch the dense server window. 1.5 x interval gives one
664
+ // grace bucket for ordinary network jitter before we suspect the stream.
665
+ static BOUNDARY_AGG_SILENCE_FACTOR = 1.5;
666
+ historicalPoints;
667
+ liveEquityUsd = null;
668
+ aggStream;
669
+ intervalMs;
670
+ lastBoundary;
671
+ lastAggAt = Date.now();
672
+ aggUnsub = null;
673
+ snapshotUnsub = null;
674
+ gapUnsub = null;
675
+ statusUnsub = null;
676
+ resumeUnsub = null;
677
+ authUnsub = null;
678
+ boundaryTimer = null;
679
+ destroyChartWatch;
680
+ refreshingHistory = false;
681
+ cacheInvalidated = false;
682
+ onInvalidateHistory;
683
+ refreshHistory;
684
+ lastEmitTime = -250;
685
+ emitTimer = null;
686
+ lastEmittedLiveEquityUsd = null;
687
+ lastEmittedHistoryLength = -1;
688
+ constructor(initialHistory, aggStream, resolution, onInvalidateHistory, refreshHistory, ws, chartWatchId, destroyChartWatch) {
689
+ super();
690
+ this.aggStream = aggStream;
691
+ this.intervalMs = resolutionToMs(resolution);
692
+ this.lastBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
693
+ this.historicalPoints = this.trimOpenHistory(initialHistory);
694
+ this.onInvalidateHistory = onInvalidateHistory;
695
+ this.refreshHistory = refreshHistory;
696
+ this.destroyChartWatch = destroyChartWatch;
697
+ if (aggStream.aggregation) {
698
+ this.liveEquityUsd = aggStream.aggregation.totalEquityUsd;
699
+ }
700
+ while (this.historicalPoints.length > 0) {
701
+ const lastTs = new Date(this.historicalPoints[this.historicalPoints.length - 1].timestamp).getTime();
702
+ if (lastTs > this.lastBoundary) {
703
+ this.historicalPoints.pop();
704
+ }
705
+ else {
706
+ break;
707
+ }
708
+ }
709
+ this.aggUnsub = aggStream.onUpdate((agg) => {
710
+ this.lastAggAt = Date.now();
711
+ const prevEquityUsd = this.liveEquityUsd;
712
+ this.liveEquityUsd = agg.totalEquityUsd;
713
+ if (!this.cacheInvalidated && this.shouldInvalidateCache(agg.totalEquityUsd)) {
714
+ this.cacheInvalidated = true;
715
+ this.onInvalidateHistory?.();
716
+ }
717
+ const currentBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
718
+ if (currentBoundary - this.lastBoundary > this.intervalMs && this.historicalPoints.length > 0) {
719
+ // Multi-bucket gap: more than one bucket has elapsed since the last
720
+ // agg event. Single-point patching here would leave intermediate
721
+ // buckets empty (the visible-on-resume bug). Refetch the dense
722
+ // server window which fills every bucket, then advance from there.
723
+ this.refreshHistoryFromServer();
724
+ }
725
+ else if (currentBoundary > this.lastBoundary && this.historicalPoints.length > 0 && prevEquityUsd !== null) {
726
+ this.historicalPoints.push({
727
+ timestamp: new Date(this.lastBoundary).toISOString(),
728
+ equityUsd: prevEquityUsd,
729
+ });
730
+ this.lastBoundary = currentBoundary;
731
+ }
732
+ this.queueEmitChart();
733
+ });
734
+ if (ws && chartWatchId && refreshHistory) {
735
+ this.snapshotUnsub = ws.onChartSnapshotUpdated((eventWatchId) => {
736
+ if (eventWatchId !== chartWatchId)
737
+ return;
738
+ this.refreshHistoryFromServer();
739
+ });
740
+ this.gapUnsub = ws.onGap(() => this.refreshHistoryFromServer());
741
+ this.statusUnsub = ws.onStatus((status) => {
742
+ if (status === 'disconnected' && this.state !== 'loading') {
743
+ this.setState('reconnecting');
744
+ }
745
+ else if (status === 'connected' && this.state === 'reconnecting') {
746
+ // Refresh handled by `onAuthenticated` below — that fires after
747
+ // the WS has finished re-issuing all subscriptions, so the
748
+ // chart-history watch is already re-registered before we refetch.
749
+ this.setState('connected');
750
+ }
751
+ });
752
+ // Tab-resume / app-foreground: refresh on any browser visibility
753
+ // transition past the WS-manager threshold (catches the case where
754
+ // the WS stayed nominally alive through a tab freeze).
755
+ this.resumeUnsub = ws.onResume(() => this.refreshHistoryFromServer());
756
+ // Every successful auth (initial post-reconnect re-auth, token
757
+ // refresh re-auth, etc.) refreshes. Registered after the manager
758
+ // is already authenticated, so the very first auth does not fire.
759
+ this.authUnsub = ws.onAuthenticated(() => this.refreshHistoryFromServer());
760
+ // Wall-clock boundary check for quiet realms: when the bucket
761
+ // boundary advances but no agg events have flowed (no fills /
762
+ // funding in the window), the materializer isn't pushing chart
763
+ // snapshots either. Refetch periodically so the chart still
764
+ // advances at every boundary even on a fully idle realm.
765
+ this.boundaryTimer = setInterval(() => {
766
+ if (this.refreshingHistory || this.isClosed)
767
+ return;
768
+ const currentBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
769
+ const aggSilence = Date.now() - this.lastAggAt;
770
+ if (currentBoundary > this.lastBoundary &&
771
+ aggSilence > EquityChartStream.BOUNDARY_AGG_SILENCE_FACTOR * this.intervalMs) {
772
+ this.refreshHistoryFromServer();
773
+ }
774
+ }, EquityChartStream.BOUNDARY_CHECK_INTERVAL_MS);
775
+ }
776
+ this.setState('connected');
777
+ // Defer the FIRST emit to the next macrotask. A constructor-scheduled
778
+ // microtask can run before the `await arca.watchEquityChart(...)`
779
+ // continuation gets a chance to register `.onUpdate(...)`, dropping the
780
+ // initial history payload and leaving chart state empty until a live tick.
781
+ setTimeout(() => this.queueEmitChart(), 0);
782
+ }
783
+ queueEmitChart() {
784
+ const now = Date.now();
785
+ const delay = Math.max(0, 250 - (now - this.lastEmitTime));
786
+ if (delay === 0) {
787
+ this.doEmitChart();
788
+ }
789
+ else if (!this.emitTimer) {
790
+ this.emitTimer = setTimeout(() => {
791
+ this.emitTimer = null;
792
+ this.doEmitChart();
793
+ }, delay);
794
+ }
795
+ }
796
+ trimOpenHistory(points) {
797
+ const trimmed = [...points];
798
+ while (trimmed.length > 0) {
799
+ const last = trimmed[trimmed.length - 1];
800
+ const lastTs = new Date(last.timestamp).getTime();
801
+ if (last.status === 'open' || lastTs > this.lastBoundary) {
802
+ trimmed.pop();
803
+ }
804
+ else {
805
+ break;
806
+ }
807
+ }
808
+ return trimmed;
809
+ }
810
+ /**
811
+ * Trigger a one-off background refetch of the dense server history through
812
+ * the same path used for gap/resume/auth healing. Non-blocking: returns
813
+ * immediately and updates the stream when the refetch lands. Used at
814
+ * startup when the live aggregation contradicts an all-zero cached history
815
+ * (newly funded account) so first paint isn't blocked on a second REST.
816
+ */
817
+ requestHistoryRefresh() {
818
+ this.refreshHistoryFromServer();
819
+ }
820
+ refreshHistoryFromServer() {
821
+ if (!this.refreshHistory || this.refreshingHistory || this.isClosed)
822
+ return;
823
+ this.refreshingHistory = true;
824
+ this.refreshHistory()
825
+ .then((history) => {
826
+ if (this.isClosed)
827
+ return;
828
+ if (history.resolution) {
829
+ this.intervalMs = resolutionToMs(history.resolution);
830
+ }
831
+ this.lastBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
832
+ this.historicalPoints = this.trimOpenHistory(history.equityPoints);
833
+ this.cacheInvalidated = false;
834
+ this.queueEmitChart();
835
+ })
836
+ .finally(() => { this.refreshingHistory = false; });
837
+ }
838
+ doEmitChart() {
839
+ this.lastEmitTime = Date.now();
840
+ const liveEquityFixed = this.liveEquityUsd !== null ? parseFloat(this.liveEquityUsd).toFixed(2) : null;
841
+ if (this.lastEmittedLiveEquityUsd === liveEquityFixed &&
842
+ this.lastEmittedHistoryLength === this.historicalPoints.length) {
843
+ return;
844
+ }
845
+ this.lastEmittedLiveEquityUsd = liveEquityFixed;
846
+ this.lastEmittedHistoryLength = this.historicalPoints.length;
847
+ const points = [...this.historicalPoints];
848
+ if (this.liveEquityUsd !== null) {
849
+ points.push({
850
+ timestamp: new Date().toISOString(),
851
+ equityUsd: this.liveEquityUsd,
852
+ });
853
+ }
854
+ this.emit({ points });
855
+ }
856
+ shouldInvalidateCache(newEquity) {
857
+ const live = parseFloat(newEquity);
858
+ if (!Number.isFinite(live))
859
+ return false;
860
+ const lastHistorical = this.historicalPoints.length > 0
861
+ ? parseFloat(this.historicalPoints[this.historicalPoints.length - 1].equityUsd)
862
+ : 0;
863
+ const diff = Math.abs(live - lastHistorical);
864
+ if (diff < 0.01)
865
+ return false;
866
+ if (lastHistorical === 0)
867
+ return diff > 0;
868
+ return diff / Math.abs(lastHistorical) > 0.05;
869
+ }
870
+ doClose() {
871
+ if (this.emitTimer)
872
+ clearTimeout(this.emitTimer);
873
+ if (this.boundaryTimer)
874
+ clearInterval(this.boundaryTimer);
875
+ this.aggUnsub?.();
876
+ this.snapshotUnsub?.();
877
+ this.gapUnsub?.();
878
+ this.statusUnsub?.();
879
+ this.resumeUnsub?.();
880
+ this.authUnsub?.();
881
+ this.destroyChartWatch?.();
882
+ this.aggStream.close();
883
+ }
884
+ }
885
+ exports.EquityChartStream = EquityChartStream;
886
+ class PnlChartStream extends WatchStream {
887
+ // See EquityChartStream for the rationale of these constants.
888
+ static BOUNDARY_CHECK_INTERVAL_MS = 30_000;
889
+ static BOUNDARY_AGG_SILENCE_FACTOR = 1.5;
890
+ historicalPnlPoints;
891
+ externalFlows;
892
+ startingEquityUsd;
893
+ cumInflows = 0;
894
+ cumOutflows = 0;
895
+ liveEquityUsd = null;
896
+ aggStream;
897
+ intervalMs;
898
+ lastBoundary;
899
+ lastAggAt = Date.now();
900
+ aggUnsub = null;
901
+ snapshotUnsub = null;
902
+ gapUnsub = null;
903
+ statusUnsub = null;
904
+ resumeUnsub = null;
905
+ authUnsub = null;
906
+ boundaryTimer = null;
907
+ destroyChartWatch;
908
+ refreshingHistory = false;
909
+ anchor;
910
+ refreshHistory;
911
+ lastEmitTime = -250;
912
+ emitTimer = null;
913
+ lastEmittedLivePnl = null;
914
+ lastEmittedLiveEquityUsd = null;
915
+ lastEmittedHistoryLength = -1;
916
+ lastEmittedFlowsLength = -1;
917
+ constructor(initialPnlPoints, initialFlows, startingEquityUsd, midPrices, prefix, aggStream, ws, resolution, anchor = 'zero', refreshHistory, chartWatchId, destroyChartWatch) {
918
+ super();
919
+ this.externalFlows = [...initialFlows];
920
+ this.startingEquityUsd = startingEquityUsd;
921
+ this.aggStream = aggStream;
922
+ this.anchor = anchor;
923
+ this.intervalMs = resolutionToMs(resolution);
924
+ this.lastBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
925
+ this.historicalPnlPoints = this.trimOpenHistory(initialPnlPoints);
926
+ this.refreshHistory = refreshHistory;
927
+ this.destroyChartWatch = destroyChartWatch;
928
+ // Compute initial flows from historical data as fallback until the server
929
+ // provides authoritative cumulative values via cumInflowsUsd/cumOutflowsUsd.
930
+ // Once flowsSince is set on the watch, the server computes flows from the
931
+ // same start time as the historical window, making it the single source of
932
+ // truth (no additive combination of two independent windows).
933
+ let baseIn = 0;
934
+ let baseOut = 0;
935
+ for (const flow of initialFlows) {
936
+ const val = parseFloat(flow.valueUsd) || 0;
937
+ if (flow.direction === 'inflow')
938
+ baseIn += val;
939
+ else
940
+ baseOut += val;
941
+ }
942
+ this.cumInflows = baseIn;
943
+ this.cumOutflows = baseOut;
944
+ if (aggStream.aggregation) {
945
+ this.liveEquityUsd = aggStream.aggregation.totalEquityUsd;
946
+ this.applyServerFlows(aggStream.aggregation);
947
+ }
948
+ // Trim trailing points strictly inside the current open bucket. The
949
+ // server's response may include a live-equity-based point for timestamps
950
+ // after lastClosed. Removing it prevents a discontinuity between the
951
+ // server's live equity (Redis at HTTP time) and the SDK's live equity
952
+ // (aggregation watch, potentially revalued with latest mids). Points
953
+ // exactly at the boundary mark the close of the previous bucket and are
954
+ // kept.
955
+ while (this.historicalPnlPoints.length > 0) {
956
+ const lastTs = new Date(this.historicalPnlPoints[this.historicalPnlPoints.length - 1].timestamp).getTime();
957
+ if (lastTs > this.lastBoundary) {
958
+ this.historicalPnlPoints.pop();
959
+ }
960
+ else {
961
+ break;
962
+ }
963
+ }
964
+ this.aggUnsub = aggStream.onUpdate((agg) => {
965
+ this.lastAggAt = Date.now();
966
+ const prevEquityUsd = this.liveEquityUsd;
967
+ const prevPnlUsd = this.computeLivePnl();
968
+ this.liveEquityUsd = agg.totalEquityUsd;
969
+ this.applyServerFlows(agg);
970
+ const currentBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
971
+ if (currentBoundary - this.lastBoundary > this.intervalMs && this.historicalPnlPoints.length > 0) {
972
+ // Multi-bucket gap: refetch the dense server window. See
973
+ // EquityChartStream.aggUnsub for the matching commentary.
974
+ this.refreshHistoryFromServer();
975
+ }
976
+ else if (currentBoundary > this.lastBoundary && this.historicalPnlPoints.length > 0 && prevEquityUsd !== null) {
977
+ this.historicalPnlPoints.push({
978
+ timestamp: new Date(this.lastBoundary).toISOString(),
979
+ pnlUsd: prevPnlUsd,
980
+ equityUsd: prevEquityUsd,
981
+ });
982
+ this.lastBoundary = currentBoundary;
983
+ }
984
+ this.queueEmitChart();
985
+ });
986
+ if (chartWatchId && refreshHistory) {
987
+ this.snapshotUnsub = ws.onChartSnapshotUpdated((eventWatchId) => {
988
+ if (eventWatchId !== chartWatchId)
989
+ return;
990
+ this.refreshHistoryFromServer();
991
+ });
992
+ this.gapUnsub = ws.onGap(() => this.refreshHistoryFromServer());
993
+ this.statusUnsub = ws.onStatus((status) => {
994
+ if (status === 'disconnected' && this.state !== 'loading') {
995
+ this.setState('reconnecting');
996
+ }
997
+ else if (status === 'connected' && this.state === 'reconnecting') {
998
+ // Refresh handled by `onAuthenticated` below.
999
+ this.setState('connected');
1000
+ }
1001
+ });
1002
+ this.resumeUnsub = ws.onResume(() => this.refreshHistoryFromServer());
1003
+ this.authUnsub = ws.onAuthenticated(() => this.refreshHistoryFromServer());
1004
+ this.boundaryTimer = setInterval(() => {
1005
+ if (this.refreshingHistory || this.isClosed)
1006
+ return;
1007
+ const currentBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
1008
+ const aggSilence = Date.now() - this.lastAggAt;
1009
+ if (currentBoundary > this.lastBoundary &&
1010
+ aggSilence > PnlChartStream.BOUNDARY_AGG_SILENCE_FACTOR * this.intervalMs) {
1011
+ this.refreshHistoryFromServer();
1012
+ }
1013
+ }, PnlChartStream.BOUNDARY_CHECK_INTERVAL_MS);
1014
+ }
1015
+ this.setState('connected');
1016
+ // Defer the FIRST emit to the next macrotask so the caller's
1017
+ // `await arca.watchPnlChart(...)` continuation can register an
1018
+ // onUpdate listener first (see EquityChartStream for the full rationale).
1019
+ setTimeout(() => this.queueEmitChart(), 0);
1020
+ }
1021
+ applyServerFlows(agg) {
1022
+ if (agg.cumInflowsUsd != null) {
1023
+ this.cumInflows = parseFloat(agg.cumInflowsUsd) || 0;
1024
+ }
1025
+ if (agg.cumOutflowsUsd != null) {
1026
+ this.cumOutflows = parseFloat(agg.cumOutflowsUsd) || 0;
1027
+ }
1028
+ }
1029
+ computeLivePnl() {
1030
+ const equity = parseFloat(this.liveEquityUsd ?? '0') || 0;
1031
+ const startEq = parseFloat(this.startingEquityUsd) || 0;
1032
+ return (equity - startEq - this.cumInflows + this.cumOutflows).toFixed(2);
1033
+ }
1034
+ queueEmitChart() {
1035
+ const now = Date.now();
1036
+ const delay = Math.max(0, 250 - (now - this.lastEmitTime));
1037
+ if (delay === 0) {
1038
+ this.doEmitChart();
1039
+ }
1040
+ else if (!this.emitTimer) {
1041
+ this.emitTimer = setTimeout(() => {
1042
+ this.emitTimer = null;
1043
+ this.doEmitChart();
1044
+ }, delay);
1045
+ }
1046
+ }
1047
+ trimOpenHistory(points) {
1048
+ const trimmed = [...points];
1049
+ while (trimmed.length > 0) {
1050
+ const last = trimmed[trimmed.length - 1];
1051
+ const lastTs = new Date(last.timestamp).getTime();
1052
+ if (last.status === 'open' || lastTs > this.lastBoundary) {
1053
+ trimmed.pop();
1054
+ }
1055
+ else {
1056
+ break;
1057
+ }
1058
+ }
1059
+ return trimmed;
1060
+ }
1061
+ refreshHistoryFromServer() {
1062
+ if (!this.refreshHistory || this.refreshingHistory || this.isClosed)
1063
+ return;
1064
+ this.refreshingHistory = true;
1065
+ this.refreshHistory()
1066
+ .then((history) => {
1067
+ if (this.isClosed)
1068
+ return;
1069
+ if (history.resolution) {
1070
+ this.intervalMs = resolutionToMs(history.resolution);
1071
+ }
1072
+ this.lastBoundary = Math.floor(Date.now() / this.intervalMs) * this.intervalMs;
1073
+ this.historicalPnlPoints = this.trimOpenHistory(history.pnlPoints);
1074
+ this.externalFlows = [...(history.externalFlows ?? [])];
1075
+ this.queueEmitChart();
1076
+ })
1077
+ .finally(() => { this.refreshingHistory = false; });
1078
+ }
1079
+ doEmitChart() {
1080
+ this.lastEmitTime = Date.now();
1081
+ const livePnl = this.computeLivePnl();
1082
+ const liveEquityFixed = this.liveEquityUsd !== null ? parseFloat(this.liveEquityUsd).toFixed(2) : null;
1083
+ if (this.lastEmittedLivePnl === livePnl &&
1084
+ this.lastEmittedLiveEquityUsd === liveEquityFixed &&
1085
+ this.lastEmittedHistoryLength === this.historicalPnlPoints.length &&
1086
+ this.lastEmittedFlowsLength === this.externalFlows.length) {
1087
+ return;
1088
+ }
1089
+ this.lastEmittedLivePnl = livePnl;
1090
+ this.lastEmittedLiveEquityUsd = liveEquityFixed;
1091
+ this.lastEmittedHistoryLength = this.historicalPnlPoints.length;
1092
+ this.lastEmittedFlowsLength = this.externalFlows.length;
1093
+ const points = this.historicalPnlPoints.map((point) => ({ ...point }));
1094
+ if (this.liveEquityUsd !== null) {
1095
+ points.push({
1096
+ timestamp: new Date().toISOString(),
1097
+ pnlUsd: livePnl,
1098
+ equityUsd: this.liveEquityUsd,
1099
+ valueUsd: this.anchor === 'equity' ? liveEquityFixed ?? undefined : undefined,
1100
+ });
1101
+ }
1102
+ if (this.anchor === 'equity') {
1103
+ for (let i = 0; i < points.length; i++) {
1104
+ if (points[i].valueUsd == null) {
1105
+ points[i] = { ...points[i], valueUsd: (parseFloat(points[i].equityUsd) || 0).toFixed(2) };
1106
+ }
1107
+ }
1108
+ }
1109
+ this.emit({ points, externalFlows: this.externalFlows });
1110
+ }
1111
+ doClose() {
1112
+ if (this.emitTimer)
1113
+ clearTimeout(this.emitTimer);
1114
+ if (this.boundaryTimer)
1115
+ clearInterval(this.boundaryTimer);
1116
+ this.aggUnsub?.();
1117
+ this.snapshotUnsub?.();
1118
+ this.gapUnsub?.();
1119
+ this.statusUnsub?.();
1120
+ this.resumeUnsub?.();
1121
+ this.authUnsub?.();
1122
+ this.destroyChartWatch?.();
1123
+ this.aggStream.close();
1124
+ }
1125
+ }
1126
+ exports.PnlChartStream = PnlChartStream;
1127
+ const SAFETY_MARGIN_FACTOR = 1.001; // 10 bps multiplicative buffer on total cost
1128
+ const DEFAULT_PLATFORM_FEE_RATE = 0.0001; // 1 bps
1129
+ function parsePositiveNumber(value) {
1130
+ const n = typeof value === 'string' ? Number.parseFloat(value) : Number(value);
1131
+ return Number.isFinite(n) && n > 0 ? n : 0;
1132
+ }
1133
+ function floorToDecimals(value, decimals) {
1134
+ if (!Number.isFinite(value) || value <= 0)
1135
+ return 0;
1136
+ const factor = Math.pow(10, decimals);
1137
+ // IEEE 754: division can land epsilon above a tick boundary, e.g.
1138
+ // 0.004099... becomes 0.00410000000000001, making floor(x * 10000) = 41
1139
+ // instead of 40. Nudge down by 1e-9 before flooring to prevent overshoot.
1140
+ return Math.max(0, Math.floor(value * factor - 1e-9)) / factor;
1141
+ }
1142
+ function toDecimalString(value, decimals = 8) {
1143
+ if (!Number.isFinite(value))
1144
+ return '0';
1145
+ return value.toFixed(decimals).replace(/\.?0+$/, '');
1146
+ }
1147
+ function deriveActiveAssetDataFromState(exchangeState, market, markPx, leverage, side, builderFeeBps = 0, szDecimals = 5, feeScale = 1,
1148
+ // Per-asset base MMR resolved by the caller (e.g. from the initial
1149
+ // `getActiveAssetData` fetch). Server derives this from the asset's margin
1150
+ // table (`0.5 / firstTier.maxLeverage`) and falls back to 0.03 when there
1151
+ // is no table. We fall back to the same default when the caller omits it.
1152
+ maintenanceMarginRate,
1153
+ // Ordered margin tiers for laddered leverage. Server populates this for tiered assets.
1154
+ marginTiers,
1155
+ // Directional spread ratios (ask/mid and bid/mid) resolved once from the
1156
+ // server snapshot. The market-order margin check prices buys at the ask and
1157
+ // sells at the bid, so we convert the live mid to the directional execution
1158
+ // price via these ratios. Default 1 (no spread) reproduces mid-based sizing.
1159
+ askRatio = 1, bidRatio = 1) {
1160
+ if (!exchangeState || !Number.isFinite(markPx) || markPx <= 0 || leverage <= 0)
1161
+ return null;
1162
+ const equity = parsePositiveNumber(exchangeState.marginSummary?.equity);
1163
+ const initialMarginUsed = parsePositiveNumber(exchangeState.marginSummary?.initialMarginUsed);
1164
+ const hasPositions = (exchangeState.positions?.length ?? 0) > 0;
1165
+ const availableGuard = hasPositions ? 0.97 : 1.0;
1166
+ const available = Math.max(0, (equity - initialMarginUsed) * availableGuard);
1167
+ const takerRate = parsePositiveNumber(exchangeState.feeRates?.taker);
1168
+ const effectiveScale = Number.isFinite(feeScale) && feeScale > 0 ? feeScale : 1;
1169
+ const platformRate = parsePositiveNumber(exchangeState.feeRates?.platformFee) || DEFAULT_PLATFORM_FEE_RATE;
1170
+ const builderRate = builderFeeBps > 0 ? builderFeeBps / 100000 : 0;
1171
+ const feeRate = takerRate * effectiveScale + platformRate + builderRate;
1172
+ // Directional execution prices. Max notional is price-independent (it's a
1173
+ // function of available budget, margin rate, and fee rate); the price only
1174
+ // enters when converting notional -> tokens. Buys execute at the ask, sells
1175
+ // at the bid, so dividing by the directional price (not the mid) makes the
1176
+ // previewed max match the server's margin check.
1177
+ const safeAskRatio = Number.isFinite(askRatio) && askRatio > 0 ? askRatio : 1;
1178
+ const safeBidRatio = Number.isFinite(bidRatio) && bidRatio > 0 ? bidRatio : 1;
1179
+ const buyPx = markPx * safeAskRatio;
1180
+ const sellPx = markPx * safeBidRatio;
1181
+ const maxTokensForDir = (avail, execPx) => {
1182
+ if (!Number.isFinite(avail) || avail <= 0)
1183
+ return 0;
1184
+ const targetSpend = avail / SAFETY_MARGIN_FACTOR;
1185
+ let activeRate = 1 / leverage;
1186
+ let deduction = 0;
1187
+ if (marginTiers && marginTiers.length > 0) {
1188
+ const tierMaxLev = marginTiers[0].maxLeverage;
1189
+ let effLev = leverage;
1190
+ if (tierMaxLev < effLev)
1191
+ effLev = tierMaxLev;
1192
+ activeRate = 1 / effLev;
1193
+ let prevRate = activeRate;
1194
+ let prevDeduction = 0;
1195
+ for (let i = 0; i < marginTiers.length; i++) {
1196
+ const tier = marginTiers[i];
1197
+ const lowerBound = Number.parseFloat(tier.lowerBound);
1198
+ let tierLev = tier.maxLeverage;
1199
+ let lev = leverage;
1200
+ if (tierLev < lev)
1201
+ lev = tierLev;
1202
+ const rate = 1 / lev;
1203
+ const nextDeduction = prevDeduction + lowerBound * (rate - prevRate);
1204
+ const spendAtBound = lowerBound * rate - nextDeduction + lowerBound * feeRate;
1205
+ if (targetSpend < spendAtBound) {
1206
+ break;
1207
+ }
1208
+ activeRate = rate;
1209
+ prevRate = rate;
1210
+ prevDeduction = nextDeduction;
1211
+ deduction = nextDeduction;
1212
+ }
1213
+ }
1214
+ const notional = (targetSpend + deduction) / (activeRate + feeRate);
1215
+ if (!Number.isFinite(notional) || notional <= 0)
1216
+ return 0;
1217
+ return floorToDecimals(notional / execPx, szDecimals);
1218
+ };
1219
+ const currentPosition = exchangeState.positions?.find((p) => p.market === market);
1220
+ let buyMax = 0;
1221
+ let sellMax = 0;
1222
+ if (!currentPosition) {
1223
+ buyMax = maxTokensForDir(available, buyPx);
1224
+ sellMax = maxTokensForDir(available, sellPx);
1225
+ }
1226
+ else {
1227
+ const posSize = parsePositiveNumber(currentPosition.size);
1228
+ const posMargin = parsePositiveNumber(currentPosition.marginUsed);
1229
+ const closeFees = posSize * markPx * feeRate * SAFETY_MARGIN_FACTOR;
1230
+ const availableAfterClose = Math.max(0, available + posMargin - closeFees);
1231
+ if (currentPosition.side === 'long') {
1232
+ buyMax = maxTokensForDir(available, buyPx);
1233
+ sellMax = posSize + maxTokensForDir(availableAfterClose, sellPx);
1234
+ }
1235
+ else if (currentPosition.side === 'short') {
1236
+ sellMax = maxTokensForDir(available, sellPx);
1237
+ buyMax = posSize + maxTokensForDir(availableAfterClose, buyPx);
1238
+ }
1239
+ }
1240
+ buyMax = floorToDecimals(buyMax, szDecimals);
1241
+ sellMax = floorToDecimals(sellMax, szDecimals);
1242
+ const leverageInfo = { type: 'cross', value: leverage };
1243
+ const rawAvailableUsd = Math.max(0, equity - initialMarginUsed);
1244
+ return {
1245
+ market,
1246
+ leverage: leverageInfo,
1247
+ maxBuySize: toDecimalString(buyMax, szDecimals),
1248
+ maxSellSize: toDecimalString(sellMax, szDecimals),
1249
+ maxBuyUsd: toDecimalString(buyMax * markPx, 8),
1250
+ maxSellUsd: toDecimalString(sellMax * markPx, 8),
1251
+ availableToTrade: toDecimalString(rawAvailableUsd, 8),
1252
+ markPx: toDecimalString(markPx, 8),
1253
+ feeRate: toDecimalString(feeRate, 8),
1254
+ maintenanceMarginRate: maintenanceMarginRate ?? '0.03',
1255
+ // Live directional prices = mid * resolved spread ratio. Equal to markPx
1256
+ // until the spread is resolved (ratio 1).
1257
+ bidPx: toDecimalString(sellPx, 8),
1258
+ askPx: toDecimalString(buyPx, 8),
1259
+ };
1260
+ }
1261
+ class MaxOrderSizeWatchStream extends WatchStream {
1262
+ activeAssetData;
1263
+ exchangeState;
1264
+ prices;
1265
+ unsubs = [];
1266
+ // builderFeeBps is the internal venue-fee value derived from the public
1267
+ // applicationFeeTenthsBps option; it mirrors Hyperliquid's builder-code fee.
1268
+ opts;
1269
+ maintenanceMarginRate;
1270
+ marginTiers;
1271
+ askRatio = 1;
1272
+ bidRatio = 1;
1273
+ priceStream;
1274
+ constructor(priceStream, options, initialExchangeState, initialPrices = {}) {
1275
+ super();
1276
+ this.priceStream = priceStream;
1277
+ this.exchangeState = initialExchangeState;
1278
+ this.prices = { ...initialPrices };
1279
+ this.opts = {
1280
+ market: options.market,
1281
+ side: options.side,
1282
+ leverage: options.leverage,
1283
+ builderFeeBps: options.applicationFeeTenthsBps ?? 0,
1284
+ szDecimals: options.szDecimals ?? 5,
1285
+ feeScale: options.feeScale ?? 1,
1286
+ };
1287
+ this.maintenanceMarginRate = options.maintenanceMarginRate;
1288
+ this.marginTiers = options.marginTiers;
1289
+ // Seed any caller-supplied directional spread ratios so the very first
1290
+ // emit sizes against the execution price, without waiting on (or even
1291
+ // needing) a getActiveAssetData fetch. Non-positive / non-finite values
1292
+ // fall through to the default 1 (no spread).
1293
+ if (options.bidRatio !== undefined && Number.isFinite(options.bidRatio) && options.bidRatio > 0) {
1294
+ this.bidRatio = options.bidRatio;
1295
+ }
1296
+ if (options.askRatio !== undefined && Number.isFinite(options.askRatio) && options.askRatio > 0) {
1297
+ this.askRatio = options.askRatio;
1298
+ }
1299
+ this.unsubs.push(this.priceStream.onUpdate((prices) => {
1300
+ this.prices = { ...prices };
1301
+ this.recompute('mids');
1302
+ }), this.priceStream.onStateChange((state) => {
1303
+ if (state === 'reconnecting')
1304
+ this.setState('reconnecting');
1305
+ }));
1306
+ this.recompute('init');
1307
+ }
1308
+ updateExchangeState(state) {
1309
+ this.exchangeState = state;
1310
+ this.recompute('exchange');
1311
+ }
1312
+ /** Update the per-asset maintenance margin rate used to populate
1313
+ * `ActiveAssetData.maintenanceMarginRate`. Triggers a recompute so
1314
+ * subscribers see the dynamic rate as soon as it's resolved. */
1315
+ updateMaintenanceMarginRate(rate) {
1316
+ if (this.maintenanceMarginRate === rate)
1317
+ return;
1318
+ this.maintenanceMarginRate = rate;
1319
+ this.recompute('init');
1320
+ }
1321
+ /** Update the per-asset margin tiers used for laddered leverage.
1322
+ * Triggers a recompute so subscribers see the dynamic tiers as soon as resolved. */
1323
+ updateMarginTiers(tiers) {
1324
+ if (this.marginTiers === tiers)
1325
+ return;
1326
+ this.marginTiers = tiers;
1327
+ this.recompute('init');
1328
+ }
1329
+ /** Update the directional spread ratios (ask/mid, bid/mid) resolved from the
1330
+ * server snapshot's top-of-book. Lets the live recompute size against the
1331
+ * execution price the market-order margin check uses instead of the mid.
1332
+ * Non-positive or non-finite inputs are ignored (treated as 1 = no spread). */
1333
+ updateSpreadRatios(bidRatio, askRatio) {
1334
+ const nextBid = Number.isFinite(bidRatio) && bidRatio > 0 ? bidRatio : 1;
1335
+ const nextAsk = Number.isFinite(askRatio) && askRatio > 0 ? askRatio : 1;
1336
+ if (this.bidRatio === nextBid && this.askRatio === nextAsk)
1337
+ return;
1338
+ this.bidRatio = nextBid;
1339
+ this.askRatio = nextAsk;
1340
+ this.recompute('init');
1341
+ }
1342
+ addCleanup(fn) {
1343
+ this.unsubs.push(fn);
1344
+ }
1345
+ recompute(event) {
1346
+ const markPx = parsePositiveNumber(this.prices[this.opts.market]);
1347
+ if (!this.exchangeState || markPx <= 0)
1348
+ return;
1349
+ const next = deriveActiveAssetDataFromState(this.exchangeState, this.opts.market, markPx, this.opts.leverage, this.opts.side, this.opts.builderFeeBps, this.opts.szDecimals, this.opts.feeScale, this.maintenanceMarginRate, this.marginTiers, this.askRatio, this.bidRatio);
1350
+ if (!next)
1351
+ return;
1352
+ this.activeAssetData = next;
1353
+ this.setState('connected');
1354
+ this.emit({ activeAssetData: next, event });
1355
+ }
1356
+ doClose() {
1357
+ this.unsubs.forEach((u) => u());
1358
+ this.priceStream.close();
1359
+ }
1360
+ }
1361
+ exports.MaxOrderSizeWatchStream = MaxOrderSizeWatchStream;
1362
+ /**
1363
+ * Real-time mid price stream.
1364
+ *
1365
+ * ## Usage patterns
1366
+ *
1367
+ * **Read on demand** (simplest — use this if you just need to read the
1368
+ * current price of an asset at arbitrary times):
1369
+ * ```ts
1370
+ * const prices = await arca.watchPrices();
1371
+ * const btc = prices.get('hl:0:BTC'); // latest mid, or undefined
1372
+ * const eth = prices.prices['hl:0:ETH']; // same thing, index form
1373
+ * ```
1374
+ *
1375
+ * **Push callback** (use this to react to every tick, e.g. for revaluing
1376
+ * a portfolio or updating a price display):
1377
+ * ```ts
1378
+ * const prices = await arca.watchPrices();
1379
+ * prices.onUpdate((next) => { console.log(next['hl:0:BTC']); });
1380
+ * ```
1381
+ *
1382
+ * ## Keys and values
1383
+ *
1384
+ * - Keys are **canonical market IDs** (e.g. `"hl:0:BTC"`, `"hl:1:TSLA"`),
1385
+ * not bare symbols. Using `"BTC"` will return `undefined`.
1386
+ * - Values are decimal strings (not floats) to preserve precision. Parse
1387
+ * with `Number(...)` for quick math or a decimal library for correctness.
1388
+ * - Missing coins return `undefined` — the platform intentionally omits
1389
+ * unavailable prices rather than sending `"0"`, so `undefined` is a real
1390
+ * signal that you should handle (e.g. show "—" instead of a phantom zero).
1391
+ *
1392
+ * ## Reference semantics
1393
+ *
1394
+ * `.prices` returns a new object on every tick, so `stream.prices` is a
1395
+ * stable reference until the next update. You can safely store it in React
1396
+ * state, Zustand, etc. and reference-equality will correctly signal changes.
1397
+ *
1398
+ * ## Lifecycle
1399
+ *
1400
+ * Opens on first consumer, multiplexed (ref-counted) across callers of
1401
+ * `arca.watchPrices(...)`. Call `.close()` when done. On reconnect the server
1402
+ * re-sends a snapshot so `.prices` is never stale on reconnect — only
1403
+ * temporarily empty during the initial `ready()` wait.
1404
+ */
1405
+ class PriceWatchStream extends WatchStream {
1406
+ ws;
1407
+ exchange;
1408
+ _prices = {};
1409
+ unsubs = [];
1410
+ coinFilter;
1411
+ constructor(ws, exchange, coins) {
1412
+ super();
1413
+ this.ws = ws;
1414
+ this.exchange = exchange;
1415
+ const filteredCoins = coins && coins.length > 0 ? [...new Set(coins)] : undefined;
1416
+ this.coinFilter = filteredCoins ? new Set(filteredCoins) : null;
1417
+ this.unsubs.push(this.ws.onStatus((status) => {
1418
+ if (status === 'disconnected' && this.state !== 'loading') {
1419
+ this.setState('reconnecting');
1420
+ }
1421
+ }), this.ws.onMidsUpdated((mids, meta) => {
1422
+ this.applyMids(mids, meta?.snapshot === true);
1423
+ }));
1424
+ this.ws.acquireMids(exchange, filteredCoins);
1425
+ }
1426
+ /**
1427
+ * Latest mid prices keyed by canonical market ID. Returns a new object
1428
+ * reference on every tick so reference-equality checks (React, Zustand)
1429
+ * correctly detect changes.
1430
+ */
1431
+ get prices() {
1432
+ return this._prices;
1433
+ }
1434
+ /**
1435
+ * Get the latest mid price for a specific canonical market ID, or
1436
+ * `undefined` if no price is currently available.
1437
+ */
1438
+ get(market) {
1439
+ return this._prices[market];
1440
+ }
1441
+ /**
1442
+ * Get the latest mid price as a `number`, or `undefined` if not
1443
+ * available. For trading math that needs exact decimals, prefer
1444
+ * reading the string form via `get(market)` and using a decimal library.
1445
+ */
1446
+ getNumber(market) {
1447
+ const raw = this._prices[market];
1448
+ if (raw === undefined)
1449
+ return undefined;
1450
+ const n = Number(raw);
1451
+ return Number.isFinite(n) ? n : undefined;
1452
+ }
1453
+ applyMids(mids, _isSnapshot) {
1454
+ // Build a new object each tick so reference-equality consumers see a
1455
+ // change. Snapshots are authoritative for the subscribed market set, so
1456
+ // they replace the dict; incremental updates merge over the previous
1457
+ // state. Server filters server-side, but we also filter locally for
1458
+ // defense-in-depth when the SDK is sharing a WS subscription with
1459
+ // another consumer that asked for a broader set.
1460
+ const filter = this.coinFilter;
1461
+ const next = _isSnapshot ? {} : { ...this._prices };
1462
+ for (const [market, price] of Object.entries(mids)) {
1463
+ if (filter && !filter.has(market))
1464
+ continue;
1465
+ next[market] = price;
1466
+ }
1467
+ this._prices = next;
1468
+ this.setState('connected');
1469
+ this.emit(this._prices);
1470
+ }
1471
+ doClose() {
1472
+ this.unsubs.forEach(u => u());
1473
+ const coins = this.coinFilter ? Array.from(this.coinFilter) : undefined;
1474
+ this.ws.releaseMids(coins);
1475
+ }
1476
+ }
1477
+ exports.PriceWatchStream = PriceWatchStream;
1478
+ class CandleWatchStream extends WatchStream {
1479
+ ws;
1480
+ coins;
1481
+ intervals;
1482
+ unsubs = [];
1483
+ constructor(ws, coins, intervals) {
1484
+ super();
1485
+ this.ws = ws;
1486
+ this.coins = coins;
1487
+ this.intervals = intervals;
1488
+ this.setState('connected');
1489
+ this.unsubs.push(this.ws.onStatus((status) => {
1490
+ if (status === 'disconnected') {
1491
+ this.setState('reconnecting');
1492
+ }
1493
+ else if (status === 'connected') {
1494
+ this.setState('connected');
1495
+ }
1496
+ }), this.ws.onCandleClosed((event) => {
1497
+ if (this.matchesCoin(event.market))
1498
+ this.emit(event);
1499
+ }), this.ws.onCandleUpdated((event) => {
1500
+ if (this.matchesCoin(event.market))
1501
+ this.emit(event);
1502
+ }));
1503
+ }
1504
+ matchesCoin(market) {
1505
+ return this.coins.length === 0 || this.coins.includes(market);
1506
+ }
1507
+ doClose() {
1508
+ this.unsubs.forEach(u => u());
1509
+ this.ws.releaseCandles(this.coins, this.intervals);
1510
+ }
1511
+ }
1512
+ exports.CandleWatchStream = CandleWatchStream;
1513
+ class TradeWatchStream extends WatchStream {
1514
+ ws;
1515
+ coins;
1516
+ unsubs = [];
1517
+ constructor(ws, coins) {
1518
+ super();
1519
+ this.ws = ws;
1520
+ this.coins = coins;
1521
+ this.setState('connected');
1522
+ this.unsubs.push(this.ws.onStatus((status) => {
1523
+ if (status === 'disconnected') {
1524
+ this.setState('reconnecting');
1525
+ }
1526
+ else if (status === 'connected') {
1527
+ this.setState('connected');
1528
+ }
1529
+ }), this.ws.onTradeExecuted((event) => {
1530
+ if (this.matchesCoin(event.market))
1531
+ this.emit(event);
1532
+ }));
1533
+ }
1534
+ matchesCoin(market) {
1535
+ return this.coins.length === 0 || this.coins.includes(market);
1536
+ }
1537
+ doClose() {
1538
+ this.unsubs.forEach(u => u());
1539
+ this.ws.releaseTrades(this.coins);
1540
+ }
1541
+ }
1542
+ exports.TradeWatchStream = TradeWatchStream;
1543
+ // ── CoverageTracker ────────────────────────────────────────────────
1544
+ /** Sorted, non-overlapping interval list with merge-on-insert and gap queries. */
1545
+ class CoverageTracker {
1546
+ intervals = [];
1547
+ add(from, to) {
1548
+ this.intervals.push({ from, to });
1549
+ this.intervals.sort((a, b) => a.from - b.from);
1550
+ const merged = [];
1551
+ for (const iv of this.intervals) {
1552
+ const last = merged[merged.length - 1];
1553
+ if (last && iv.from <= last.to + 1) {
1554
+ last.to = Math.max(last.to, iv.to);
1555
+ }
1556
+ else {
1557
+ merged.push({ from: iv.from, to: iv.to });
1558
+ }
1559
+ }
1560
+ this.intervals = merged;
1561
+ }
1562
+ gaps(from, to) {
1563
+ if (from > to)
1564
+ return [];
1565
+ const result = [];
1566
+ let cursor = from;
1567
+ for (const iv of this.intervals) {
1568
+ if (cursor > to)
1569
+ break;
1570
+ if (iv.to < cursor)
1571
+ continue;
1572
+ if (iv.from > cursor) {
1573
+ result.push({ from: cursor, to: Math.min(iv.from - 1, to) });
1574
+ }
1575
+ cursor = Math.max(cursor, iv.to + 1);
1576
+ }
1577
+ if (cursor <= to) {
1578
+ result.push({ from: cursor, to });
1579
+ }
1580
+ return result;
1581
+ }
1582
+ }
1583
+ exports.CoverageTracker = CoverageTracker;
1584
+ // ── CandleChartStream ──────────────────────────────────────────────
1585
+ const DEFAULT_LOAD_COUNT = 300;
1586
+ const GAP_RECOVERY_CANDLES = 50;
1587
+ function mergeRequestedRange(current, next) {
1588
+ if (!current)
1589
+ return next;
1590
+ return {
1591
+ start: Math.min(current.start, next.start),
1592
+ end: Math.max(current.end, next.end),
1593
+ };
1594
+ }
1595
+ function applyCandle(candle, arr) {
1596
+ const last = arr[arr.length - 1];
1597
+ if (last && last.t === candle.t) {
1598
+ arr[arr.length - 1] = candle;
1599
+ return;
1600
+ }
1601
+ if (arr.length === 0 || candle.t > arr[arr.length - 1].t) {
1602
+ arr.push(candle);
1603
+ return;
1604
+ }
1605
+ for (let i = arr.length - 2; i >= 0; i--) {
1606
+ if (arr[i].t === candle.t) {
1607
+ arr[i] = candle;
1608
+ return;
1609
+ }
1610
+ if (arr[i].t < candle.t) {
1611
+ arr.splice(i + 1, 0, candle);
1612
+ return;
1613
+ }
1614
+ }
1615
+ arr.splice(0, 0, candle);
1616
+ }
1617
+ function dedupCandles(candles) {
1618
+ const sorted = [...candles].sort((a, b) => a.t - b.t);
1619
+ if (sorted.length === 0)
1620
+ return [];
1621
+ const result = [sorted[0]];
1622
+ for (let i = 1; i < sorted.length; i++) {
1623
+ if (sorted[i].t === result[result.length - 1].t) {
1624
+ result[result.length - 1] = sorted[i];
1625
+ }
1626
+ else {
1627
+ result.push(sorted[i]);
1628
+ }
1629
+ }
1630
+ return result;
1631
+ }
1632
+ /**
1633
+ * Merges historical candle data with real-time WebSocket candle events.
1634
+ * Maintains a deduped, sorted candle array that updates on every
1635
+ * `candle.updated` and `candle.closed` event. Automatically recovers
1636
+ * gaps on WebSocket reconnection by refetching recent candles.
1637
+ *
1638
+ * Use {@link CandleChartStream.ensureRange} when the chart viewport changes
1639
+ * (zoom, resize, scroll, jump to date). Use {@link CandleChartStream.loadMore}
1640
+ * for simple backward scrolling.
1641
+ */
1642
+ class CandleChartStream extends WatchStream {
1643
+ ws;
1644
+ market;
1645
+ interval;
1646
+ fetchCandles;
1647
+ historySnapshot;
1648
+ _candles = [];
1649
+ unsubs = [];
1650
+ coverage = new CoverageTracker();
1651
+ _reachedStart = false;
1652
+ loading = false;
1653
+ loadingPromise;
1654
+ pendingRange;
1655
+ previousCount = 0;
1656
+ retryTimer;
1657
+ initialRangeStart;
1658
+ initialRangeEnd;
1659
+ constructor(ws, market, interval, fetchCandles, initialCandles, initialHistoryState, initialRangeStart, initialRangeEnd, expectedCount = DEFAULT_LOAD_COUNT) {
1660
+ super();
1661
+ this.ws = ws;
1662
+ this.market = market;
1663
+ this.interval = interval;
1664
+ this.fetchCandles = fetchCandles;
1665
+ this.initialRangeStart = initialRangeStart;
1666
+ this.initialRangeEnd = initialRangeEnd;
1667
+ this.historySnapshot = initialHistoryState;
1668
+ this._candles = dedupCandles(initialCandles);
1669
+ const sparse = this._candles.length < Math.floor(expectedCount / 2);
1670
+ if (this._candles.length > 0 && !sparse) {
1671
+ this.coverage.add(initialRangeStart, initialRangeEnd);
1672
+ }
1673
+ this.unsubs.push(this.ws.onStatus((status) => {
1674
+ if (status === 'disconnected' && this.state !== 'loading') {
1675
+ this.setState('reconnecting');
1676
+ }
1677
+ else if (status === 'connected') {
1678
+ // Recovery is now driven by `onAuthenticated` (every successful
1679
+ // re-auth) and `onResume` (page-visibility return), not by this
1680
+ // status transition — that race-conditions with WS messages
1681
+ // landing before the disconnect callback fires.
1682
+ this.setState('connected');
1683
+ }
1684
+ }),
1685
+ // Recover candle gap on every successful re-auth (post-reconnect).
1686
+ // Registered after the manager is already authenticated, so the very
1687
+ // first auth does not fire — there's no gap on the initial connect.
1688
+ this.ws.onAuthenticated(() => this.recoverGap()),
1689
+ // Recover on tab-resume / app-foreground in case the WS stayed
1690
+ // nominally alive through the freeze.
1691
+ this.ws.onResume(() => this.recoverGap()), this.ws.onCandleClosed((event) => {
1692
+ if (event.market === this.market) {
1693
+ this.applyEvent(event.candle);
1694
+ }
1695
+ }), this.ws.onCandleUpdated((event) => {
1696
+ if (event.market === this.market) {
1697
+ this.applyEvent(event.candle);
1698
+ }
1699
+ }));
1700
+ this.setState('connected');
1701
+ if (this._candles.length > 0) {
1702
+ this.emitSnapshot(this._candles[this._candles.length - 1]);
1703
+ }
1704
+ if (sparse) {
1705
+ this.retryInitialLoad();
1706
+ }
1707
+ }
1708
+ /** Current candle array (historical + live), sorted by `t`, deduped. */
1709
+ get candles() {
1710
+ return this._candles;
1711
+ }
1712
+ /** Whether the start of available history has been reached. */
1713
+ get reachedStart() {
1714
+ return this._reachedStart;
1715
+ }
1716
+ /**
1717
+ * Ensure candles are loaded for the given time range. Tracks which ranges
1718
+ * have already been fetched and only requests the gaps. Calling with an
1719
+ * already-loaded range is a no-op (idempotent). Overlapping calls while a
1720
+ * fetch is already in flight are coalesced into the pending range instead of
1721
+ * being dropped.
1722
+ */
1723
+ async ensureRange(startTime, endTime) {
1724
+ if (this.isClosed || startTime > endTime) {
1725
+ return this.makeResult(0);
1726
+ }
1727
+ if (this.coverage.gaps(startTime, endTime).length === 0) {
1728
+ return this.makeResult(0);
1729
+ }
1730
+ this.pendingRange = mergeRequestedRange(this.pendingRange, { start: startTime, end: endTime });
1731
+ if (this.loading) {
1732
+ await this.loadingPromise;
1733
+ if (this.isClosed || this.coverage.gaps(startTime, endTime).length === 0) {
1734
+ return this.makeResult(0);
1735
+ }
1736
+ return this.ensureRange(startTime, endTime);
1737
+ }
1738
+ this.loading = true;
1739
+ this.loadingPromise = this.drainPendingRanges();
1740
+ try {
1741
+ const totalLoaded = await this.loadingPromise;
1742
+ return this.makeResult(totalLoaded);
1743
+ }
1744
+ finally {
1745
+ this.loading = false;
1746
+ this.loadingPromise = undefined;
1747
+ }
1748
+ }
1749
+ /**
1750
+ * Load older candles backwards from the current earliest candle.
1751
+ * Convenience wrapper around {@link ensureRange}.
1752
+ *
1753
+ * @param count - Number of candle periods to load (default 300).
1754
+ */
1755
+ async loadMore(count = DEFAULT_LOAD_COUNT) {
1756
+ const earliest = this._candles.length > 0 ? this._candles[0].t : 0;
1757
+ if (earliest <= 0) {
1758
+ return this.makeResult(0);
1759
+ }
1760
+ const intervalMs = intervalToMs(this.interval);
1761
+ const end = earliest - 1;
1762
+ const start = Math.max(0, end - intervalMs * count);
1763
+ return this.ensureRange(start, end);
1764
+ }
1765
+ applyEvent(candle) {
1766
+ applyCandle(candle, this._candles);
1767
+ if (this.historySnapshot.type === 'loaded') {
1768
+ this.emitSnapshot(candle);
1769
+ }
1770
+ }
1771
+ emitSnapshot(trigger) {
1772
+ const count = this._candles.length;
1773
+ if (count < this.previousCount)
1774
+ return;
1775
+ this.previousCount = Math.max(this.previousCount, count);
1776
+ this.emit({ candles: [...this._candles], latestCandle: trigger });
1777
+ }
1778
+ async drainPendingRanges() {
1779
+ let totalLoaded = 0;
1780
+ while (!this.isClosed) {
1781
+ const requested = this.pendingRange;
1782
+ this.pendingRange = undefined;
1783
+ if (!requested)
1784
+ break;
1785
+ const gaps = this.coverage.gaps(requested.start, requested.end);
1786
+ await Promise.allSettled(gaps.map(async (gap) => {
1787
+ const res = await this.fetchCandles(this.market, this.interval, {
1788
+ startTime: gap.from,
1789
+ endTime: gap.to,
1790
+ });
1791
+ if (this.isClosed)
1792
+ return;
1793
+ if (res.candles.length > 0) {
1794
+ this._candles.push(...res.candles);
1795
+ this._candles = dedupCandles(this._candles);
1796
+ totalLoaded += res.candles.length;
1797
+ this.coverage.add(gap.from, gap.to);
1798
+ }
1799
+ else {
1800
+ const earliest = this._candles.length > 0 ? this._candles[0].t : Infinity;
1801
+ if (gap.from <= earliest) {
1802
+ this._reachedStart = true;
1803
+ this.coverage.add(gap.from, gap.to);
1804
+ }
1805
+ }
1806
+ if (this._candles.length > 0) {
1807
+ this.emitSnapshot(this._candles[this._candles.length - 1]);
1808
+ }
1809
+ }));
1810
+ }
1811
+ return totalLoaded;
1812
+ }
1813
+ makeResult(loadedCount) {
1814
+ const first = this._candles[0];
1815
+ const last = this._candles[this._candles.length - 1];
1816
+ return {
1817
+ loadedCount,
1818
+ totalCount: this._candles.length,
1819
+ range: { start: first?.t ?? 0, end: last?.t ?? 0 },
1820
+ reachedStart: this._reachedStart,
1821
+ };
1822
+ }
1823
+ recoverGap() {
1824
+ const intervalMs = intervalToMs(this.interval);
1825
+ const gapStart = Date.now() - intervalMs * GAP_RECOVERY_CANDLES;
1826
+ this.fetchCandles(this.market, this.interval, { startTime: gapStart })
1827
+ .then((res) => {
1828
+ if (this.isClosed || res.candles.length === 0)
1829
+ return;
1830
+ this._candles.push(...res.candles);
1831
+ this._candles = dedupCandles(this._candles);
1832
+ this.coverage.add(gapStart, Date.now());
1833
+ const last = this._candles[this._candles.length - 1];
1834
+ if (last)
1835
+ this.emitSnapshot(last);
1836
+ })
1837
+ .catch(() => { });
1838
+ }
1839
+ retryInitialLoad() {
1840
+ const countBefore = this._candles.length;
1841
+ const attempt = (delay) => {
1842
+ this.retryTimer = setTimeout(async () => {
1843
+ if (this.isClosed)
1844
+ return;
1845
+ try {
1846
+ const res = await this.fetchCandles(this.market, this.interval, {
1847
+ startTime: this.initialRangeStart,
1848
+ endTime: this.initialRangeEnd,
1849
+ });
1850
+ if (this.isClosed)
1851
+ return;
1852
+ if (res.candles.length > countBefore) {
1853
+ this._candles.push(...res.candles);
1854
+ this._candles = dedupCandles(this._candles);
1855
+ this.historySnapshot = { type: 'loaded', count: res.candles.length };
1856
+ this.coverage.add(this.initialRangeStart, this.initialRangeEnd);
1857
+ const last = this._candles[this._candles.length - 1];
1858
+ if (last)
1859
+ this.emitSnapshot(last);
1860
+ return;
1861
+ }
1862
+ }
1863
+ catch { /* retry on next attempt */ }
1864
+ attempt(Math.min(delay * 2, 30_000));
1865
+ }, delay);
1866
+ };
1867
+ attempt(1_000);
1868
+ }
1869
+ doClose() {
1870
+ if (this.retryTimer)
1871
+ clearTimeout(this.retryTimer);
1872
+ this.unsubs.forEach(u => u());
1873
+ this.ws.releaseCandles([this.market], [this.interval]);
1874
+ }
1875
+ }
1876
+ exports.CandleChartStream = CandleChartStream;
1877
+ function intervalToMs(interval) {
1878
+ const map = {
1879
+ '15s': 15_000, '1m': 60_000, '5m': 300_000, '15m': 900_000,
1880
+ '1h': 3_600_000, '4h': 14_400_000, '1d': 86_400_000,
1881
+ };
1882
+ return map[interval];
1883
+ }
1884
+ function hasInlineStructuralExchangeState(exchangeState) {
1885
+ return exchangeState?.pendingIntents !== undefined;
1886
+ }
1887
+ /**
1888
+ * Reactive stream of exchange state including positions, orders, and
1889
+ * pending intents. Subscribes to `exchange.updated` events for structural
1890
+ * changes, and to `mids.updated` for real-time client-side P&L revaluation.
1891
+ */
1892
+ class ExchangeWatchStream extends WatchStream {
1893
+ ws;
1894
+ objectPath;
1895
+ objectId;
1896
+ fetchState;
1897
+ exchange;
1898
+ _exchangeState;
1899
+ structuralState;
1900
+ latestMids = {};
1901
+ unsubs = [];
1902
+ fetchInFlight = false;
1903
+ constructor(ws, objectPath, objectId, fetchState, exchange = 'sim') {
1904
+ super();
1905
+ this.ws = ws;
1906
+ this.objectPath = objectPath;
1907
+ this.objectId = objectId;
1908
+ this.fetchState = fetchState;
1909
+ this.exchange = exchange;
1910
+ this.ws.acquireMids(exchange);
1911
+ this.unsubs.push(this.ws.onStatus((status) => {
1912
+ if (status === 'disconnected' && this.state !== 'loading') {
1913
+ this.setState('reconnecting');
1914
+ }
1915
+ else if (status === 'connected' && this._exchangeState) {
1916
+ this.refetch();
1917
+ }
1918
+ }), this.ws.onExchangeNotification((event) => {
1919
+ if (event.entityId !== this.objectId && event.entityPath !== this.objectPath) {
1920
+ return;
1921
+ }
1922
+ const exchangeState = event.exchangeState;
1923
+ if (hasInlineStructuralExchangeState(exchangeState)) {
1924
+ this.applyStructural(exchangeState, event);
1925
+ }
1926
+ else {
1927
+ this.refetch(event);
1928
+ }
1929
+ }), this.ws.onMidsUpdated((mids) => {
1930
+ Object.assign(this.latestMids, mids);
1931
+ if (!this.structuralState)
1932
+ return;
1933
+ const revalued = (0, revalue_1.revalueExchangeState)(this.structuralState, this.latestMids);
1934
+ this._exchangeState = revalued;
1935
+ this.emit({ state: revalued, source: 'mids' });
1936
+ }));
1937
+ this.ws.watchPath(this.objectPath).then((snapshot) => {
1938
+ if (snapshot.exchange && !this._exchangeState) {
1939
+ this.applyStructural(snapshot.exchange);
1940
+ }
1941
+ else {
1942
+ this.refetch();
1943
+ }
1944
+ }).catch(() => {
1945
+ this.refetch();
1946
+ });
1947
+ }
1948
+ get exchangeState() {
1949
+ return this._exchangeState;
1950
+ }
1951
+ get pendingIntents() {
1952
+ return this._exchangeState?.pendingIntents ?? [];
1953
+ }
1954
+ applyStructural(state, event) {
1955
+ this.structuralState = state;
1956
+ const hasMids = Object.keys(this.latestMids).length > 0;
1957
+ const revalued = hasMids ? (0, revalue_1.revalueExchangeState)(state, this.latestMids) : state;
1958
+ this._exchangeState = revalued;
1959
+ this.setState('connected');
1960
+ this.emit({ state: revalued, event, source: 'exchange' });
1961
+ }
1962
+ refetch(triggerEvent) {
1963
+ if (this.fetchInFlight || this.isClosed)
1964
+ return;
1965
+ this.fetchInFlight = true;
1966
+ this.fetchState(this.objectId)
1967
+ .then((state) => {
1968
+ if (this.isClosed)
1969
+ return;
1970
+ this.applyStructural(state, triggerEvent);
1971
+ })
1972
+ .catch(() => { })
1973
+ .finally(() => { this.fetchInFlight = false; });
1974
+ }
1975
+ doClose() {
1976
+ this.unsubs.forEach(u => u());
1977
+ this.ws.unwatchPath(this.objectPath);
1978
+ this.ws.releaseMids();
1979
+ }
1980
+ }
1981
+ exports.ExchangeWatchStream = ExchangeWatchStream;
1982
+ /**
1983
+ * Live TWAP stream for a single TWAP, identified by `operationId`.
1984
+ * Filters the global TWAP event firehose to only the events whose
1985
+ * `twap.operationId` matches the requested operation; keeps the latest
1986
+ * `twap` snapshot in memory for synchronous reads (e.g. rendering "X of N
1987
+ * slices").
1988
+ *
1989
+ * Backed by the same underlying WebSocket as {@link OperationWatchStream}
1990
+ * — closing this stream releases its filter listeners but does not
1991
+ * disturb sibling subscriptions on the same connection.
1992
+ *
1993
+ * The first snapshot comes from the caller (`watchTwap` does the
1994
+ * initial REST fetch). Subsequent updates flow from the per-event
1995
+ * server enrichment (`twap.started`, `twap.progress`, `twap.completed`,
1996
+ * `twap.cancelled`, `twap.failed`).
1997
+ */
1998
+ class TwapWatchStream extends WatchStream {
1999
+ ws;
2000
+ operationId;
2001
+ refetch;
2002
+ _twap;
2003
+ unsubs = [];
2004
+ gapRefetchInFlight = false;
2005
+ constructor(ws, operationId, initial, refetch) {
2006
+ super();
2007
+ this.ws = ws;
2008
+ this.operationId = operationId;
2009
+ this.refetch = refetch;
2010
+ if (initial) {
2011
+ this._twap = initial;
2012
+ this.setState('connected');
2013
+ }
2014
+ this.unsubs.push(this.ws.onStatus((status) => {
2015
+ if (status === 'disconnected' && this.state !== 'loading') {
2016
+ this.setState('reconnecting');
2017
+ }
2018
+ }), this.ws.onTwapEvent((event) => {
2019
+ const twap = event.twap;
2020
+ if (!twap || twap.operationId !== this.operationId)
2021
+ return;
2022
+ this._twap = twap;
2023
+ this.setState('connected');
2024
+ this.emit({ twap, event });
2025
+ }), this.ws.onGap(() => { this.handleGap(); }));
2026
+ }
2027
+ /** Latest server-side TWAP record. Undefined until the first event. */
2028
+ get twap() {
2029
+ return this._twap;
2030
+ }
2031
+ handleGap() {
2032
+ if (!this.refetch || this.gapRefetchInFlight || this.isClosed)
2033
+ return;
2034
+ this.gapRefetchInFlight = true;
2035
+ this.refetch()
2036
+ .then((twap) => {
2037
+ if (this.isClosed || !twap)
2038
+ return;
2039
+ this._twap = twap;
2040
+ })
2041
+ .catch(() => { })
2042
+ .finally(() => { this.gapRefetchInFlight = false; });
2043
+ }
2044
+ doClose() {
2045
+ this.unsubs.forEach(u => u());
2046
+ }
2047
+ }
2048
+ exports.TwapWatchStream = TwapWatchStream;
2049
+ /**
2050
+ * Live trade-history stream for an exchange Arca object.
2051
+ *
2052
+ * Two-phase fill delivery using envelope fields:
2053
+ * 1. `fill.previewed` (sequence=1) — instant preview with venue data
2054
+ * 2. `fill.recorded` (sequence=2) — authoritative fill with platform data
2055
+ *
2056
+ * Matching uses `correlationId` (set to orderId on the backend).
2057
+ * Falls back to `orderId` matching when envelope fields are absent.
2058
+ * If a preview doesn't receive its authoritative update within
2059
+ * `CONVERGENCE_TIMEOUT_MS`, a warning callback fires.
2060
+ *
2061
+ * **Pick the right surface for your use case:**
2062
+ * - Read {@link FillWatchStream.fills} for an activity-feed view: the merged
2063
+ * list, where each fill appears exactly once. Preview rows from
2064
+ * `fill.previewed` are replaced in place by their authoritative
2065
+ * `fill.recorded` counterparts using `correlationId`.
2066
+ * - Subscribe via `onUpdate` for the raw transition stream: it emits **both**
2067
+ * phases as separate events (preview → recorded). Deduping by `Fill.id`
2068
+ * will not work — the preview's `id` is the venue's fill id while the
2069
+ * recorded's `id` is the platform's position-ledger row. Always correlate
2070
+ * by `correlationId` / `orderId` if you consume the stream directly.
2071
+ */
2072
+ class FillWatchStream extends WatchStream {
2073
+ ws;
2074
+ fetchFills;
2075
+ objectId;
2076
+ objectPath;
2077
+ /**
2078
+ * Merged trade-history list: preview rows are replaced in place by their
2079
+ * authoritative `fill.recorded` counterparts. Use this for activity feeds
2080
+ * or any UI that should display one row per fill.
2081
+ */
2082
+ fills = [];
2083
+ unsubs = [];
2084
+ fetchInFlight = false;
2085
+ fillIds = new Set();
2086
+ previewCorrelations = new Map();
2087
+ resolvedCorrelations = new Set();
2088
+ convergenceCallbacks = new Set();
2089
+ static CONVERGENCE_TIMEOUT_MS = 10_000;
2090
+ constructor(ws, fetchFills, objectId, objectPath) {
2091
+ super();
2092
+ this.ws = ws;
2093
+ this.fetchFills = fetchFills;
2094
+ this.objectId = objectId;
2095
+ this.objectPath = objectPath;
2096
+ this.unsubs.push(this.ws.onStatus((status) => {
2097
+ if (status === 'disconnected' && this.state !== 'loading') {
2098
+ this.setState('reconnecting');
2099
+ }
2100
+ else if (status === 'connected' && this.fills.length > 0) {
2101
+ this.refetch();
2102
+ }
2103
+ }), this.ws.onFillPreviewed((simFill, event) => {
2104
+ if (!this.matchesObject(event))
2105
+ return;
2106
+ const correlationKey = event.correlationId || simFill.orderId;
2107
+ if (correlationKey && (this.previewCorrelations.has(correlationKey) || this.resolvedCorrelations.has(correlationKey)))
2108
+ return;
2109
+ const preview = {
2110
+ id: simFill.id,
2111
+ market: simFill.market,
2112
+ side: simFill.side,
2113
+ size: simFill.size,
2114
+ price: simFill.price,
2115
+ fee: simFill.fee,
2116
+ builderFee: simFill.builderFee,
2117
+ realizedPnl: simFill.realizedPnl ?? undefined,
2118
+ isLiquidation: simFill.isLiquidation,
2119
+ orderId: simFill.orderId,
2120
+ createdAt: simFill.createdAt ?? new Date().toISOString(),
2121
+ };
2122
+ this.fills.unshift(preview);
2123
+ if (correlationKey) {
2124
+ const timer = setTimeout(() => {
2125
+ if (this.previewCorrelations.has(correlationKey)) {
2126
+ this.convergenceCallbacks.forEach(cb => cb(correlationKey));
2127
+ }
2128
+ }, FillWatchStream.CONVERGENCE_TIMEOUT_MS);
2129
+ this.previewCorrelations.set(correlationKey, { index: 0, timer });
2130
+ }
2131
+ this.emit({ fill: preview, event });
2132
+ }), this.ws.onFillRecorded((fill, event) => {
2133
+ if (!this.matchesObject(event))
2134
+ return;
2135
+ const correlationKey = event.correlationId || fill.orderId;
2136
+ const replaced = correlationKey ? this.replacePreview(correlationKey, fill) : false;
2137
+ if (!replaced) {
2138
+ if (this.fillIds.has(fill.id))
2139
+ return;
2140
+ this.fills.unshift(fill);
2141
+ }
2142
+ this.fillIds.add(fill.id);
2143
+ if (correlationKey) {
2144
+ const prev = this.previewCorrelations.get(correlationKey);
2145
+ if (prev)
2146
+ clearTimeout(prev.timer);
2147
+ this.previewCorrelations.delete(correlationKey);
2148
+ this.resolvedCorrelations.add(correlationKey);
2149
+ if (this.resolvedCorrelations.size > 2000) {
2150
+ const it = this.resolvedCorrelations.values();
2151
+ for (let i = 0; i < 500; i++)
2152
+ this.resolvedCorrelations.delete(it.next().value);
2153
+ }
2154
+ }
2155
+ this.emit({ fill, event });
2156
+ }), this.ws.onGap(() => { this.refetch(); }));
2157
+ this.ws.watchPath(this.objectPath).catch(() => { });
2158
+ this.refetch();
2159
+ }
2160
+ /**
2161
+ * Register a callback for convergence timeouts. Fires when a preview
2162
+ * (fill.previewed) doesn't receive its authoritative update (fill.recorded)
2163
+ * within the timeout window.
2164
+ */
2165
+ onConvergenceTimeout(cb) {
2166
+ this.convergenceCallbacks.add(cb);
2167
+ return () => { this.convergenceCallbacks.delete(cb); };
2168
+ }
2169
+ replacePreview(correlationKey, fill) {
2170
+ const entry = this.previewCorrelations.get(correlationKey);
2171
+ if (!entry) {
2172
+ const idx = this.fills.findIndex(f => f.orderId === correlationKey && !f.operationId);
2173
+ if (idx === -1)
2174
+ return false;
2175
+ this.fills[idx] = fill;
2176
+ return true;
2177
+ }
2178
+ const idx = this.fills.findIndex(f => (f.orderId === correlationKey || f.orderId === fill.orderId) && !f.operationId);
2179
+ if (idx === -1)
2180
+ return false;
2181
+ this.fills[idx] = fill;
2182
+ return true;
2183
+ }
2184
+ matchesObject(event) {
2185
+ if (event.entityId === this.objectId)
2186
+ return true;
2187
+ if (this.objectPath && event.entityPath === this.objectPath)
2188
+ return true;
2189
+ return false;
2190
+ }
2191
+ refetch(triggerEvent) {
2192
+ if (this.fetchInFlight || this.isClosed)
2193
+ return;
2194
+ this.fetchInFlight = true;
2195
+ this.fetchFills()
2196
+ .then((resp) => {
2197
+ if (this.isClosed)
2198
+ return;
2199
+ this.fills.length = 0;
2200
+ this.fillIds.clear();
2201
+ for (const [, entry] of this.previewCorrelations)
2202
+ clearTimeout(entry.timer);
2203
+ this.previewCorrelations.clear();
2204
+ this.resolvedCorrelations.clear();
2205
+ for (const f of resp.fills) {
2206
+ this.fills.push(f);
2207
+ this.fillIds.add(f.id);
2208
+ }
2209
+ this.setState('connected');
2210
+ if (triggerEvent && resp.fills.length > 0) {
2211
+ this.emit({ fill: resp.fills[0], event: triggerEvent });
2212
+ }
2213
+ })
2214
+ .catch(() => { })
2215
+ .finally(() => { this.fetchInFlight = false; });
2216
+ }
2217
+ doClose() {
2218
+ for (const [, entry] of this.previewCorrelations)
2219
+ clearTimeout(entry.timer);
2220
+ this.unsubs.forEach(u => u());
2221
+ this.ws.unwatchPath(this.objectPath);
2222
+ this.convergenceCallbacks.clear();
2223
+ }
2224
+ }
2225
+ exports.FillWatchStream = FillWatchStream;
2226
+ /**
2227
+ * Live funding payment stream for an exchange Arca object.
2228
+ * Yields each funding payment with its {@link EventEnvelope} for correlation.
2229
+ */
2230
+ class FundingWatchStream extends WatchStream {
2231
+ ws;
2232
+ objectId;
2233
+ objectPath;
2234
+ unsubs = [];
2235
+ constructor(ws, objectId, objectPath) {
2236
+ super();
2237
+ this.ws = ws;
2238
+ this.objectId = objectId;
2239
+ this.objectPath = objectPath;
2240
+ this.unsubs.push(this.ws.onStatus((status) => {
2241
+ if (status === 'disconnected' && this.state !== 'loading') {
2242
+ this.setState('reconnecting');
2243
+ }
2244
+ else if (status === 'connected') {
2245
+ this.setState('connected');
2246
+ }
2247
+ }), this.ws.onExchangeFunding((payment, event) => {
2248
+ if (event.entityId !== this.objectId && event.entityPath !== this.objectPath) {
2249
+ return;
2250
+ }
2251
+ const envelope = {
2252
+ realmId: event.realmId,
2253
+ entityId: event.entityId,
2254
+ entityPath: event.entityPath,
2255
+ eventId: event.eventId,
2256
+ correlationId: event.correlationId,
2257
+ sequence: event.sequence,
2258
+ timestamp: event.timestamp,
2259
+ deliverySeq: event.deliverySeq,
2260
+ };
2261
+ this.emit({ payment, envelope });
2262
+ }));
2263
+ this.ws.watchPath(this.objectPath).catch(() => { });
2264
+ this.setState('connected');
2265
+ }
2266
+ doClose() {
2267
+ this.unsubs.forEach(u => u());
2268
+ this.ws.unwatchPath(this.objectPath);
2269
+ }
2270
+ }
2271
+ exports.FundingWatchStream = FundingWatchStream;
2272
+ //# sourceMappingURL=streams.js.map