@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,661 @@
1
+ import type { Operation, ArcaBalance, ExchangeState, ExchangeIntent, PredictedEffect, ObjectValuation, PathAggregation, ActiveAssetData, Fill, FillListResponse, FundingPayment, EventEnvelope, Candle, CandleInterval, CandleEvent, CandleChartUpdate, CandlesResponse, LoadRangeResult, TradeEvent, RealmEvent, EquityPoint, PnlPoint, ExternalFlowEntry, MarginTier, Twap } from './types';
2
+ import type { WebSocketManager } from './websocket';
3
+ export type WatchStreamState = 'loading' | 'connected' | 'reconnecting';
4
+ type UpdateCallback<T> = (data: T) => void;
5
+ type StateCallback = (state: WatchStreamState) => void;
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
+ export declare class WatchStreamReadyTimeoutError extends Error {
12
+ readonly timeoutMs: number;
13
+ readonly name = "WatchStreamReadyTimeoutError";
14
+ constructor(timeoutMs: number);
15
+ }
16
+ /**
17
+ * Base class for all watch streams. Manages callbacks, cleanup,
18
+ * lifecycle state, and provides Symbol.asyncDispose / Symbol.asyncIterator support.
19
+ *
20
+ * Streams follow a state machine: loading → connected ⇄ reconnecting.
21
+ * They never enter a terminal error state; they keep retrying indefinitely
22
+ * via the underlying WebSocket reconnection.
23
+ */
24
+ declare abstract class WatchStream<T> {
25
+ protected readonly updateCallbacks: Set<UpdateCallback<T>>;
26
+ private readonly stateCallbacks;
27
+ private _state;
28
+ private closed;
29
+ private readyResolve?;
30
+ private readonly readyPromise;
31
+ constructor();
32
+ /** Current lifecycle state of the stream. */
33
+ get state(): WatchStreamState;
34
+ /**
35
+ * Returns a promise that resolves when the first snapshot is received.
36
+ *
37
+ * By default this never rejects — the stream retries indefinitely via
38
+ * the underlying WebSocket reconnection logic. Pass `timeoutMs` to
39
+ * bound the wait and reject with `WatchStreamReadyTimeoutError` if the
40
+ * stream does not reach `connected` within that window. This is useful
41
+ * at app startup when you want to fall back to a degraded state (or
42
+ * show an error to the user) instead of hanging forever if the backend
43
+ * is unreachable.
44
+ *
45
+ * If the stream is already connected, resolves immediately regardless
46
+ * of `timeoutMs`.
47
+ *
48
+ * @param timeoutMs - Optional timeout in milliseconds.
49
+ */
50
+ ready(timeoutMs?: number): Promise<void>;
51
+ /**
52
+ * Register a callback for each update. Returns an unsubscribe function.
53
+ */
54
+ onUpdate(cb: UpdateCallback<T>): () => void;
55
+ /**
56
+ * Register a callback for state changes. Returns an unsubscribe function.
57
+ */
58
+ onStateChange(cb: StateCallback): () => void;
59
+ /**
60
+ * Stop listening and release the underlying subscription.
61
+ */
62
+ close(): void;
63
+ get isClosed(): boolean;
64
+ protected setState(newState: WatchStreamState): void;
65
+ protected emit(data: T): void;
66
+ protected abstract doClose(): void;
67
+ /**
68
+ * Iterate over updates asynchronously.
69
+ * If the consumer is slower than the stream, updates are queued.
70
+ * The queue is capped at 1000 items to prevent unbounded memory growth.
71
+ * If the queue overflows, the oldest items are dropped.
72
+ */
73
+ [Symbol.asyncIterator](): AsyncIterableIterator<T>;
74
+ [Symbol.asyncDispose](): Promise<void>;
75
+ }
76
+ export interface OperationUpdate {
77
+ operation: Operation;
78
+ event: RealmEvent;
79
+ }
80
+ export declare class OperationWatchStream extends WatchStream<OperationUpdate> {
81
+ private readonly ws;
82
+ private readonly path;
83
+ private readonly refetchOperations?;
84
+ private readonly maxOperations;
85
+ readonly operations: Operation[];
86
+ private readonly unsubs;
87
+ private gapRefetchInFlight;
88
+ constructor(ws: WebSocketManager, path: string, refetchOperations?: (() => Promise<Operation[]>) | undefined, maxOperations?: number);
89
+ private handleGap;
90
+ /**
91
+ * Track an operation from the moment it is submitted (before HTTP completes).
92
+ * Immediately adds a synthetic `{ state: 'submitting' }` entry so the UI
93
+ * can show that something is in progress. Transitions to `pending` when
94
+ * the HTTP response arrives, then to the terminal state on server events.
95
+ */
96
+ trackSubmission(handle: {
97
+ predicted?: PredictedEffect;
98
+ submitted: Promise<{
99
+ operation: Operation | null;
100
+ }>;
101
+ }): void;
102
+ protected doClose(): void;
103
+ }
104
+ export interface BalanceSnapshot {
105
+ entityId: string;
106
+ entityPath?: string;
107
+ balances: ArcaBalance[];
108
+ }
109
+ export interface BalanceUpdate {
110
+ entityId: string;
111
+ entityPath?: string;
112
+ balances?: ArcaBalance[];
113
+ event: RealmEvent;
114
+ }
115
+ export declare class BalanceWatchStream extends WatchStream<BalanceUpdate> {
116
+ private readonly ws;
117
+ private readonly path;
118
+ private readonly refetchEntityBalances?;
119
+ readonly balances: Map<string, BalanceSnapshot>;
120
+ private readonly unsubs;
121
+ private readonly activePredictions;
122
+ private gapRefetchInFlight;
123
+ constructor(ws: WebSocketManager, path: string, refetchEntityBalances?: ((entityId: string) => Promise<ArcaBalance[]>) | undefined);
124
+ /**
125
+ * Optimistically apply predicted balance effects from an operation handle.
126
+ * Immediately emits a balance update with the predicted `departing`/`arriving`
127
+ * amounts overlaid on the current snapshot. When the server's `balance.updated`
128
+ * event arrives, the prediction is reconciled and replaced. If the operation
129
+ * fails, the prediction is rolled back.
130
+ */
131
+ applyPrediction(handle: {
132
+ predicted?: PredictedEffect;
133
+ submitted: Promise<unknown>;
134
+ }): void;
135
+ private findSnapshotByPath;
136
+ private handleGap;
137
+ protected doClose(): void;
138
+ }
139
+ export declare class ObjectWatchStream extends WatchStream<ObjectValuation> {
140
+ private readonly ws;
141
+ private readonly path;
142
+ private readonly exchange;
143
+ private readonly refetchValuation?;
144
+ valuation?: ObjectValuation;
145
+ private readonly unsubs;
146
+ private latestMids;
147
+ private structuralValuation?;
148
+ private gapRefetchInFlight;
149
+ constructor(ws: WebSocketManager, path: string, exchange?: string, refetchValuation?: (() => Promise<ObjectValuation>) | undefined);
150
+ private handleGap;
151
+ protected doClose(): void;
152
+ }
153
+ /**
154
+ * Manages multiple ObjectWatchStream instances and emits a merged
155
+ * Map<path, ObjectValuation> on every update from any child stream.
156
+ * Close this stream to close all children.
157
+ */
158
+ export declare class ObjectsWatchStream extends WatchStream<Map<string, ObjectValuation>> {
159
+ readonly valuations: Map<string, ObjectValuation>;
160
+ private readonly children;
161
+ private readonly childUnsubs;
162
+ constructor(streams: ObjectWatchStream[]);
163
+ protected doClose(): void;
164
+ }
165
+ export declare class AggregationWatchStream extends WatchStream<PathAggregation> {
166
+ private readonly ws;
167
+ private readonly refreshWatch;
168
+ aggregation?: PathAggregation;
169
+ private _watchId;
170
+ private readonly unsubs;
171
+ private latestMids;
172
+ private structuralAggregation?;
173
+ private destroyWatch?;
174
+ private refreshing;
175
+ get watchId(): string;
176
+ constructor(ws: WebSocketManager, watchId: string, initialAggregation: PathAggregation, destroyWatch: () => Promise<void>, refreshWatch: () => Promise<{
177
+ watchId: string;
178
+ aggregation: PathAggregation;
179
+ destroyWatch: () => Promise<void>;
180
+ }>, exchange?: string);
181
+ private handleReconnect;
182
+ protected doClose(): void;
183
+ }
184
+ /**
185
+ * EquityChartStream merges historical equity data with a live aggregation
186
+ * stream. The rightmost (current interval) point updates on each aggregation
187
+ * event. When the interval boundary is crossed, the current point is promoted
188
+ * to historical and a new live point starts.
189
+ */
190
+ export interface EquityChartUpdate {
191
+ points: EquityPoint[];
192
+ }
193
+ export declare class EquityChartStream extends WatchStream<EquityChartUpdate> {
194
+ private static readonly BOUNDARY_CHECK_INTERVAL_MS;
195
+ private static readonly BOUNDARY_AGG_SILENCE_FACTOR;
196
+ private historicalPoints;
197
+ private liveEquityUsd;
198
+ private aggStream;
199
+ private intervalMs;
200
+ private lastBoundary;
201
+ private lastAggAt;
202
+ private aggUnsub;
203
+ private snapshotUnsub;
204
+ private gapUnsub;
205
+ private statusUnsub;
206
+ private resumeUnsub;
207
+ private authUnsub;
208
+ private boundaryTimer;
209
+ private destroyChartWatch?;
210
+ private refreshingHistory;
211
+ private cacheInvalidated;
212
+ private onInvalidateHistory?;
213
+ private refreshHistory?;
214
+ private lastEmitTime;
215
+ private emitTimer;
216
+ private lastEmittedLiveEquityUsd;
217
+ private lastEmittedHistoryLength;
218
+ constructor(initialHistory: EquityPoint[], aggStream: AggregationWatchStream, resolution?: string, onInvalidateHistory?: () => void, refreshHistory?: () => Promise<{
219
+ equityPoints: EquityPoint[];
220
+ resolution?: string;
221
+ }>, ws?: WebSocketManager, chartWatchId?: string, destroyChartWatch?: () => void);
222
+ private queueEmitChart;
223
+ private trimOpenHistory;
224
+ /**
225
+ * Trigger a one-off background refetch of the dense server history through
226
+ * the same path used for gap/resume/auth healing. Non-blocking: returns
227
+ * immediately and updates the stream when the refetch lands. Used at
228
+ * startup when the live aggregation contradicts an all-zero cached history
229
+ * (newly funded account) so first paint isn't blocked on a second REST.
230
+ */
231
+ requestHistoryRefresh(): void;
232
+ private refreshHistoryFromServer;
233
+ private doEmitChart;
234
+ private shouldInvalidateCache;
235
+ protected doClose(): void;
236
+ }
237
+ /**
238
+ * PnlChartStream merges historical P&L data with live aggregation updates
239
+ * and operation events. The rightmost point updates on each aggregation
240
+ * event. Operation events (deposits/transfers) update cumulative flows
241
+ * client-side — zero additional server reads.
242
+ */
243
+ export interface PnlChartUpdate {
244
+ points: PnlPoint[];
245
+ externalFlows: ExternalFlowEntry[];
246
+ }
247
+ export declare class PnlChartStream extends WatchStream<PnlChartUpdate> {
248
+ private static readonly BOUNDARY_CHECK_INTERVAL_MS;
249
+ private static readonly BOUNDARY_AGG_SILENCE_FACTOR;
250
+ private historicalPnlPoints;
251
+ private externalFlows;
252
+ readonly startingEquityUsd: string;
253
+ private cumInflows;
254
+ private cumOutflows;
255
+ private liveEquityUsd;
256
+ private aggStream;
257
+ private intervalMs;
258
+ private lastBoundary;
259
+ private lastAggAt;
260
+ private aggUnsub;
261
+ private snapshotUnsub;
262
+ private gapUnsub;
263
+ private statusUnsub;
264
+ private resumeUnsub;
265
+ private authUnsub;
266
+ private boundaryTimer;
267
+ private destroyChartWatch?;
268
+ private refreshingHistory;
269
+ private readonly anchor;
270
+ private refreshHistory?;
271
+ private lastEmitTime;
272
+ private emitTimer;
273
+ private lastEmittedLivePnl;
274
+ private lastEmittedLiveEquityUsd;
275
+ private lastEmittedHistoryLength;
276
+ private lastEmittedFlowsLength;
277
+ constructor(initialPnlPoints: PnlPoint[], initialFlows: ExternalFlowEntry[], startingEquityUsd: string, midPrices: Record<string, string>, prefix: string, aggStream: AggregationWatchStream, ws: WebSocketManager, resolution?: string, anchor?: 'zero' | 'equity', refreshHistory?: () => Promise<{
278
+ pnlPoints: PnlPoint[];
279
+ externalFlows?: ExternalFlowEntry[];
280
+ startingEquityUsd: string;
281
+ resolution?: string;
282
+ }>, chartWatchId?: string, destroyChartWatch?: () => void);
283
+ private applyServerFlows;
284
+ private computeLivePnl;
285
+ private queueEmitChart;
286
+ private trimOpenHistory;
287
+ private refreshHistoryFromServer;
288
+ private doEmitChart;
289
+ protected doClose(): void;
290
+ }
291
+ export interface MaxOrderSizeWatchOptions {
292
+ objectId: string;
293
+ market: string;
294
+ side: 'buy' | 'sell';
295
+ leverage: number;
296
+ /** Application fee in tenths of a basis point. */
297
+ applicationFeeTenthsBps?: number;
298
+ szDecimals?: number;
299
+ /** HIP-3 fee multiplier for this asset. Defaults to 1 (standard perps). */
300
+ feeScale?: number;
301
+ /** Asset's base maintenance margin rate as a decimal (e.g. "0.01" for 1%).
302
+ * Used to derive `ActiveAssetData.maintenanceMarginRate`, which feeds
303
+ * `Arca.orderBreakdown`'s liquidation estimate. When omitted,
304
+ * `watchMaxOrderSize` auto-fetches it via `getActiveAssetData`. */
305
+ maintenanceMarginRate?: string;
306
+ /** Ordered margin tiers for laddered leverage (tiered assets such as BTC).
307
+ * Used by the client-side max-size derivation to mirror the server's
308
+ * tiered initial-margin schedule. When omitted, `watchMaxOrderSize`
309
+ * auto-fetches them via `getActiveAssetData`; if the asset has no tiers
310
+ * the derivation falls back to a flat `1/leverage` initial margin. */
311
+ marginTiers?: MarginTier[];
312
+ /** Directional spread ratio for sells: `best-bid / mid` at snapshot time.
313
+ * Market sells are margin-checked at the bid, so max-sell sizing prices
314
+ * against `mid * bidRatio` instead of the mid. Defaults to 1 (size at the
315
+ * mid). When omitted, `watchMaxOrderSize` resolves it once from the
316
+ * `getActiveAssetData` top-of-book. Non-positive / non-finite values are
317
+ * ignored (treated as 1). */
318
+ bidRatio?: number;
319
+ /** Directional spread ratio for buys: `best-ask / mid` at snapshot time.
320
+ * Market buys are margin-checked at the ask, so max-buy sizing prices
321
+ * against `mid * askRatio` instead of the mid. Defaults to 1 (size at the
322
+ * mid). When omitted, `watchMaxOrderSize` resolves it once from the
323
+ * `getActiveAssetData` top-of-book. Pass `bidRatio`, `askRatio`,
324
+ * `maintenanceMarginRate`, and `marginTiers` together to skip the
325
+ * `getActiveAssetData` network lookup entirely. */
326
+ askRatio?: number;
327
+ }
328
+ export interface MaxOrderSizeUpdate {
329
+ activeAssetData: ActiveAssetData;
330
+ event: 'exchange' | 'mids' | 'init';
331
+ }
332
+ export declare function deriveActiveAssetDataFromState(exchangeState: ExchangeState, market: string, markPx: number, leverage: number, side: 'buy' | 'sell', builderFeeBps?: number, szDecimals?: number, feeScale?: number, maintenanceMarginRate?: string, marginTiers?: MarginTier[], askRatio?: number, bidRatio?: number): ActiveAssetData | null;
333
+ export declare class MaxOrderSizeWatchStream extends WatchStream<MaxOrderSizeUpdate> {
334
+ activeAssetData?: ActiveAssetData;
335
+ private exchangeState?;
336
+ private prices;
337
+ private readonly unsubs;
338
+ private readonly opts;
339
+ private maintenanceMarginRate?;
340
+ private marginTiers?;
341
+ private askRatio;
342
+ private bidRatio;
343
+ private readonly priceStream;
344
+ constructor(priceStream: PriceWatchStream, options: MaxOrderSizeWatchOptions, initialExchangeState?: ExchangeState, initialPrices?: Record<string, string>);
345
+ updateExchangeState(state: ExchangeState): void;
346
+ /** Update the per-asset maintenance margin rate used to populate
347
+ * `ActiveAssetData.maintenanceMarginRate`. Triggers a recompute so
348
+ * subscribers see the dynamic rate as soon as it's resolved. */
349
+ updateMaintenanceMarginRate(rate: string | undefined): void;
350
+ /** Update the per-asset margin tiers used for laddered leverage.
351
+ * Triggers a recompute so subscribers see the dynamic tiers as soon as resolved. */
352
+ updateMarginTiers(tiers: MarginTier[] | undefined): void;
353
+ /** Update the directional spread ratios (ask/mid, bid/mid) resolved from the
354
+ * server snapshot's top-of-book. Lets the live recompute size against the
355
+ * execution price the market-order margin check uses instead of the mid.
356
+ * Non-positive or non-finite inputs are ignored (treated as 1 = no spread). */
357
+ updateSpreadRatios(bidRatio: number, askRatio: number): void;
358
+ addCleanup(fn: () => void): void;
359
+ private recompute;
360
+ protected doClose(): void;
361
+ }
362
+ /**
363
+ * Real-time mid price stream.
364
+ *
365
+ * ## Usage patterns
366
+ *
367
+ * **Read on demand** (simplest — use this if you just need to read the
368
+ * current price of an asset at arbitrary times):
369
+ * ```ts
370
+ * const prices = await arca.watchPrices();
371
+ * const btc = prices.get('hl:0:BTC'); // latest mid, or undefined
372
+ * const eth = prices.prices['hl:0:ETH']; // same thing, index form
373
+ * ```
374
+ *
375
+ * **Push callback** (use this to react to every tick, e.g. for revaluing
376
+ * a portfolio or updating a price display):
377
+ * ```ts
378
+ * const prices = await arca.watchPrices();
379
+ * prices.onUpdate((next) => { console.log(next['hl:0:BTC']); });
380
+ * ```
381
+ *
382
+ * ## Keys and values
383
+ *
384
+ * - Keys are **canonical market IDs** (e.g. `"hl:0:BTC"`, `"hl:1:TSLA"`),
385
+ * not bare symbols. Using `"BTC"` will return `undefined`.
386
+ * - Values are decimal strings (not floats) to preserve precision. Parse
387
+ * with `Number(...)` for quick math or a decimal library for correctness.
388
+ * - Missing coins return `undefined` — the platform intentionally omits
389
+ * unavailable prices rather than sending `"0"`, so `undefined` is a real
390
+ * signal that you should handle (e.g. show "—" instead of a phantom zero).
391
+ *
392
+ * ## Reference semantics
393
+ *
394
+ * `.prices` returns a new object on every tick, so `stream.prices` is a
395
+ * stable reference until the next update. You can safely store it in React
396
+ * state, Zustand, etc. and reference-equality will correctly signal changes.
397
+ *
398
+ * ## Lifecycle
399
+ *
400
+ * Opens on first consumer, multiplexed (ref-counted) across callers of
401
+ * `arca.watchPrices(...)`. Call `.close()` when done. On reconnect the server
402
+ * re-sends a snapshot so `.prices` is never stale on reconnect — only
403
+ * temporarily empty during the initial `ready()` wait.
404
+ */
405
+ export declare class PriceWatchStream extends WatchStream<Record<string, string>> {
406
+ private readonly ws;
407
+ private readonly exchange;
408
+ private _prices;
409
+ private readonly unsubs;
410
+ private readonly coinFilter;
411
+ constructor(ws: WebSocketManager, exchange: string, coins?: readonly string[]);
412
+ /**
413
+ * Latest mid prices keyed by canonical market ID. Returns a new object
414
+ * reference on every tick so reference-equality checks (React, Zustand)
415
+ * correctly detect changes.
416
+ */
417
+ get prices(): Record<string, string>;
418
+ /**
419
+ * Get the latest mid price for a specific canonical market ID, or
420
+ * `undefined` if no price is currently available.
421
+ */
422
+ get(market: string): string | undefined;
423
+ /**
424
+ * Get the latest mid price as a `number`, or `undefined` if not
425
+ * available. For trading math that needs exact decimals, prefer
426
+ * reading the string form via `get(market)` and using a decimal library.
427
+ */
428
+ getNumber(market: string): number | undefined;
429
+ private applyMids;
430
+ protected doClose(): void;
431
+ }
432
+ export declare class CandleWatchStream extends WatchStream<CandleEvent> {
433
+ private readonly ws;
434
+ private readonly coins;
435
+ private readonly intervals;
436
+ private readonly unsubs;
437
+ constructor(ws: WebSocketManager, coins: string[], intervals: CandleInterval[]);
438
+ private matchesCoin;
439
+ protected doClose(): void;
440
+ }
441
+ export declare class TradeWatchStream extends WatchStream<TradeEvent> {
442
+ private readonly ws;
443
+ private readonly coins;
444
+ private readonly unsubs;
445
+ constructor(ws: WebSocketManager, coins: string[]);
446
+ private matchesCoin;
447
+ protected doClose(): void;
448
+ }
449
+ /** Sorted, non-overlapping interval list with merge-on-insert and gap queries. */
450
+ export declare class CoverageTracker {
451
+ private intervals;
452
+ add(from: number, to: number): void;
453
+ gaps(from: number, to: number): Array<{
454
+ from: number;
455
+ to: number;
456
+ }>;
457
+ }
458
+ export type InitialHistoryState = {
459
+ type: 'loading';
460
+ } | {
461
+ type: 'loaded';
462
+ count: number;
463
+ } | {
464
+ type: 'failed';
465
+ error: string;
466
+ };
467
+ /**
468
+ * Merges historical candle data with real-time WebSocket candle events.
469
+ * Maintains a deduped, sorted candle array that updates on every
470
+ * `candle.updated` and `candle.closed` event. Automatically recovers
471
+ * gaps on WebSocket reconnection by refetching recent candles.
472
+ *
473
+ * Use {@link CandleChartStream.ensureRange} when the chart viewport changes
474
+ * (zoom, resize, scroll, jump to date). Use {@link CandleChartStream.loadMore}
475
+ * for simple backward scrolling.
476
+ */
477
+ export declare class CandleChartStream extends WatchStream<CandleChartUpdate> {
478
+ private readonly ws;
479
+ private readonly market;
480
+ private readonly interval;
481
+ private readonly fetchCandles;
482
+ historySnapshot: InitialHistoryState;
483
+ private _candles;
484
+ private readonly unsubs;
485
+ private readonly coverage;
486
+ private _reachedStart;
487
+ private loading;
488
+ private loadingPromise;
489
+ private pendingRange;
490
+ private previousCount;
491
+ private retryTimer;
492
+ private readonly initialRangeStart;
493
+ private readonly initialRangeEnd;
494
+ constructor(ws: WebSocketManager, market: string, interval: CandleInterval, fetchCandles: (market: string, interval: CandleInterval, options?: {
495
+ startTime?: number;
496
+ endTime?: number;
497
+ }) => Promise<CandlesResponse>, initialCandles: Candle[], initialHistoryState: InitialHistoryState, initialRangeStart: number, initialRangeEnd: number, expectedCount?: number);
498
+ /** Current candle array (historical + live), sorted by `t`, deduped. */
499
+ get candles(): readonly Candle[];
500
+ /** Whether the start of available history has been reached. */
501
+ get reachedStart(): boolean;
502
+ /**
503
+ * Ensure candles are loaded for the given time range. Tracks which ranges
504
+ * have already been fetched and only requests the gaps. Calling with an
505
+ * already-loaded range is a no-op (idempotent). Overlapping calls while a
506
+ * fetch is already in flight are coalesced into the pending range instead of
507
+ * being dropped.
508
+ */
509
+ ensureRange(startTime: number, endTime: number): Promise<LoadRangeResult>;
510
+ /**
511
+ * Load older candles backwards from the current earliest candle.
512
+ * Convenience wrapper around {@link ensureRange}.
513
+ *
514
+ * @param count - Number of candle periods to load (default 300).
515
+ */
516
+ loadMore(count?: number): Promise<LoadRangeResult>;
517
+ private applyEvent;
518
+ private emitSnapshot;
519
+ private drainPendingRanges;
520
+ private makeResult;
521
+ private recoverGap;
522
+ private retryInitialLoad;
523
+ protected doClose(): void;
524
+ }
525
+ export interface ExchangeStateUpdate {
526
+ state: ExchangeState;
527
+ event?: RealmEvent;
528
+ /** What triggered this update: `'exchange'` for server-pushed state, `'mids'` for client-side mid-price revaluation. */
529
+ source?: 'exchange' | 'mids';
530
+ }
531
+ /**
532
+ * Reactive stream of exchange state including positions, orders, and
533
+ * pending intents. Subscribes to `exchange.updated` events for structural
534
+ * changes, and to `mids.updated` for real-time client-side P&L revaluation.
535
+ */
536
+ export declare class ExchangeWatchStream extends WatchStream<ExchangeStateUpdate> {
537
+ private readonly ws;
538
+ private readonly objectPath;
539
+ private readonly objectId;
540
+ private readonly fetchState;
541
+ private readonly exchange;
542
+ private _exchangeState;
543
+ private structuralState;
544
+ private latestMids;
545
+ private readonly unsubs;
546
+ private fetchInFlight;
547
+ constructor(ws: WebSocketManager, objectPath: string, objectId: string, fetchState: (objectId: string) => Promise<ExchangeState>, exchange?: string);
548
+ get exchangeState(): ExchangeState | undefined;
549
+ get pendingIntents(): ExchangeIntent[];
550
+ private applyStructural;
551
+ private refetch;
552
+ protected doClose(): void;
553
+ }
554
+ export interface TwapUpdate {
555
+ twap: Twap;
556
+ event: import('./types').TwapEvent;
557
+ }
558
+ /**
559
+ * Live TWAP stream for a single TWAP, identified by `operationId`.
560
+ * Filters the global TWAP event firehose to only the events whose
561
+ * `twap.operationId` matches the requested operation; keeps the latest
562
+ * `twap` snapshot in memory for synchronous reads (e.g. rendering "X of N
563
+ * slices").
564
+ *
565
+ * Backed by the same underlying WebSocket as {@link OperationWatchStream}
566
+ * — closing this stream releases its filter listeners but does not
567
+ * disturb sibling subscriptions on the same connection.
568
+ *
569
+ * The first snapshot comes from the caller (`watchTwap` does the
570
+ * initial REST fetch). Subsequent updates flow from the per-event
571
+ * server enrichment (`twap.started`, `twap.progress`, `twap.completed`,
572
+ * `twap.cancelled`, `twap.failed`).
573
+ */
574
+ export declare class TwapWatchStream extends WatchStream<TwapUpdate> {
575
+ private readonly ws;
576
+ private readonly operationId;
577
+ private readonly refetch?;
578
+ private _twap?;
579
+ private readonly unsubs;
580
+ private gapRefetchInFlight;
581
+ constructor(ws: WebSocketManager, operationId: string, initial?: Twap, refetch?: (() => Promise<Twap | null>) | undefined);
582
+ /** Latest server-side TWAP record. Undefined until the first event. */
583
+ get twap(): Twap | undefined;
584
+ private handleGap;
585
+ protected doClose(): void;
586
+ }
587
+ export interface FillUpdate {
588
+ fill: Fill;
589
+ event?: RealmEvent;
590
+ }
591
+ /**
592
+ * Live trade-history stream for an exchange Arca object.
593
+ *
594
+ * Two-phase fill delivery using envelope fields:
595
+ * 1. `fill.previewed` (sequence=1) — instant preview with venue data
596
+ * 2. `fill.recorded` (sequence=2) — authoritative fill with platform data
597
+ *
598
+ * Matching uses `correlationId` (set to orderId on the backend).
599
+ * Falls back to `orderId` matching when envelope fields are absent.
600
+ * If a preview doesn't receive its authoritative update within
601
+ * `CONVERGENCE_TIMEOUT_MS`, a warning callback fires.
602
+ *
603
+ * **Pick the right surface for your use case:**
604
+ * - Read {@link FillWatchStream.fills} for an activity-feed view: the merged
605
+ * list, where each fill appears exactly once. Preview rows from
606
+ * `fill.previewed` are replaced in place by their authoritative
607
+ * `fill.recorded` counterparts using `correlationId`.
608
+ * - Subscribe via `onUpdate` for the raw transition stream: it emits **both**
609
+ * phases as separate events (preview → recorded). Deduping by `Fill.id`
610
+ * will not work — the preview's `id` is the venue's fill id while the
611
+ * recorded's `id` is the platform's position-ledger row. Always correlate
612
+ * by `correlationId` / `orderId` if you consume the stream directly.
613
+ */
614
+ export declare class FillWatchStream extends WatchStream<FillUpdate> {
615
+ private readonly ws;
616
+ private readonly fetchFills;
617
+ private readonly objectId;
618
+ private readonly objectPath;
619
+ /**
620
+ * Merged trade-history list: preview rows are replaced in place by their
621
+ * authoritative `fill.recorded` counterparts. Use this for activity feeds
622
+ * or any UI that should display one row per fill.
623
+ */
624
+ readonly fills: Fill[];
625
+ private readonly unsubs;
626
+ private fetchInFlight;
627
+ private readonly fillIds;
628
+ private readonly previewCorrelations;
629
+ private readonly resolvedCorrelations;
630
+ private convergenceCallbacks;
631
+ static readonly CONVERGENCE_TIMEOUT_MS = 10000;
632
+ constructor(ws: WebSocketManager, fetchFills: () => Promise<FillListResponse>, objectId: string, objectPath: string);
633
+ /**
634
+ * Register a callback for convergence timeouts. Fires when a preview
635
+ * (fill.previewed) doesn't receive its authoritative update (fill.recorded)
636
+ * within the timeout window.
637
+ */
638
+ onConvergenceTimeout(cb: (correlationId: string) => void): () => void;
639
+ private replacePreview;
640
+ private matchesObject;
641
+ private refetch;
642
+ protected doClose(): void;
643
+ }
644
+ export interface FundingUpdate {
645
+ payment: FundingPayment;
646
+ envelope: EventEnvelope;
647
+ }
648
+ /**
649
+ * Live funding payment stream for an exchange Arca object.
650
+ * Yields each funding payment with its {@link EventEnvelope} for correlation.
651
+ */
652
+ export declare class FundingWatchStream extends WatchStream<FundingUpdate> {
653
+ private readonly ws;
654
+ private readonly objectId;
655
+ private readonly objectPath;
656
+ private readonly unsubs;
657
+ constructor(ws: WebSocketManager, objectId: string, objectPath: string);
658
+ protected doClose(): void;
659
+ }
660
+ export {};
661
+ //# sourceMappingURL=streams.d.ts.map