@pod-network/trade-sdk 0.1.0-rc.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 (102) hide show
  1. package/README.md +113 -0
  2. package/dist/client.d.ts +93 -0
  3. package/dist/client.d.ts.map +1 -0
  4. package/dist/client.js +168 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/codec/decode.d.ts +22 -0
  7. package/dist/codec/decode.d.ts.map +1 -0
  8. package/dist/codec/decode.js +251 -0
  9. package/dist/codec/decode.js.map +1 -0
  10. package/dist/codec/fixed.d.ts +11 -0
  11. package/dist/codec/fixed.d.ts.map +1 -0
  12. package/dist/codec/fixed.js +37 -0
  13. package/dist/codec/fixed.js.map +1 -0
  14. package/dist/codec/resolution.d.ts +14 -0
  15. package/dist/codec/resolution.d.ts.map +1 -0
  16. package/dist/codec/resolution.js +35 -0
  17. package/dist/codec/resolution.js.map +1 -0
  18. package/dist/codec/units.d.ts +35 -0
  19. package/dist/codec/units.d.ts.map +1 -0
  20. package/dist/codec/units.js +86 -0
  21. package/dist/codec/units.js.map +1 -0
  22. package/dist/datafeed.d.ts +4 -0
  23. package/dist/datafeed.d.ts.map +1 -0
  24. package/dist/datafeed.js +73 -0
  25. package/dist/datafeed.js.map +1 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +19 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/stores/resource.d.ts +50 -0
  31. package/dist/stores/resource.d.ts.map +1 -0
  32. package/dist/stores/resource.js +154 -0
  33. package/dist/stores/resource.js.map +1 -0
  34. package/dist/sync/account-metrics.d.ts +26 -0
  35. package/dist/sync/account-metrics.d.ts.map +1 -0
  36. package/dist/sync/account-metrics.js +41 -0
  37. package/dist/sync/account-metrics.js.map +1 -0
  38. package/dist/sync/candles.d.ts +68 -0
  39. package/dist/sync/candles.d.ts.map +1 -0
  40. package/dist/sync/candles.js +318 -0
  41. package/dist/sync/candles.js.map +1 -0
  42. package/dist/sync/order-preview.d.ts +74 -0
  43. package/dist/sync/order-preview.d.ts.map +1 -0
  44. package/dist/sync/order-preview.js +86 -0
  45. package/dist/sync/order-preview.js.map +1 -0
  46. package/dist/sync/orders.d.ts +49 -0
  47. package/dist/sync/orders.d.ts.map +1 -0
  48. package/dist/sync/orders.js +210 -0
  49. package/dist/sync/orders.js.map +1 -0
  50. package/dist/sync/positions-live.d.ts +3 -0
  51. package/dist/sync/positions-live.d.ts.map +1 -0
  52. package/dist/sync/positions-live.js +86 -0
  53. package/dist/sync/positions-live.js.map +1 -0
  54. package/dist/sync/sources.d.ts +40 -0
  55. package/dist/sync/sources.d.ts.map +1 -0
  56. package/dist/sync/sources.js +197 -0
  57. package/dist/sync/sources.js.map +1 -0
  58. package/dist/transport/rest.d.ts +83 -0
  59. package/dist/transport/rest.d.ts.map +1 -0
  60. package/dist/transport/rest.js +146 -0
  61. package/dist/transport/rest.js.map +1 -0
  62. package/dist/transport/ws.d.ts +60 -0
  63. package/dist/transport/ws.d.ts.map +1 -0
  64. package/dist/transport/ws.js +235 -0
  65. package/dist/transport/ws.js.map +1 -0
  66. package/dist/types/public.d.ts +292 -0
  67. package/dist/types/public.d.ts.map +1 -0
  68. package/dist/types/public.js +4 -0
  69. package/dist/types/public.js.map +1 -0
  70. package/dist/types/wire.d.ts +283 -0
  71. package/dist/types/wire.d.ts.map +1 -0
  72. package/dist/types/wire.js +6 -0
  73. package/dist/types/wire.js.map +1 -0
  74. package/dist/write/delegation.d.ts +54 -0
  75. package/dist/write/delegation.d.ts.map +1 -0
  76. package/dist/write/delegation.js +81 -0
  77. package/dist/write/delegation.js.map +1 -0
  78. package/dist/write/index.d.ts +261 -0
  79. package/dist/write/index.d.ts.map +1 -0
  80. package/dist/write/index.js +428 -0
  81. package/dist/write/index.js.map +1 -0
  82. package/package.json +43 -0
  83. package/src/client.ts +229 -0
  84. package/src/codec/decode.ts +277 -0
  85. package/src/codec/fixed.ts +41 -0
  86. package/src/codec/resolution.ts +39 -0
  87. package/src/codec/units.ts +100 -0
  88. package/src/datafeed.ts +94 -0
  89. package/src/index.ts +49 -0
  90. package/src/stores/resource.ts +172 -0
  91. package/src/sync/account-metrics.ts +71 -0
  92. package/src/sync/candles.ts +326 -0
  93. package/src/sync/order-preview.ts +152 -0
  94. package/src/sync/orders.ts +205 -0
  95. package/src/sync/positions-live.ts +102 -0
  96. package/src/sync/sources.ts +239 -0
  97. package/src/transport/rest.ts +213 -0
  98. package/src/transport/ws.ts +255 -0
  99. package/src/types/public.ts +335 -0
  100. package/src/types/wire.ts +301 -0
  101. package/src/write/delegation.ts +113 -0
  102. package/src/write/index.ts +642 -0
@@ -0,0 +1,326 @@
1
+ // CandleSeries: a SeriesResource<Bar> that loads history as epoch-anchored
2
+ // canonical pages (so settled pages are byte-identical across clients and the
3
+ // server flags them immutable) and builds the forming bar in memory by folding
4
+ // the pod_candles tick stream. No polling of the hot edge.
5
+ //
6
+ // Every REST request this class makes is a fully-elapsed window, so every
7
+ // response is `immutable` and browser/CDN-cacheable: full canonical pages
8
+ // forever, and the trailing page clamped to the last closed bucket (its URL
9
+ // rotates once per bucket close). The forming bucket never comes from REST —
10
+ // the tick subscription replays it from the bucket boundary; for buckets
11
+ // longer than the server's tick-replay ring, the forming bar is first seeded
12
+ // from settled 1h bars (also cacheable) and ticks fold on top.
13
+
14
+ import type { Bar, MarketId, Resolution, TimeRange } from "../types/public.js";
15
+ import type { WireCandleTick } from "../types/wire.js";
16
+ import { dec, usToMs, WAD } from "../codec/units.js";
17
+ import { RESOLUTION_PAGE_BUCKETS, RESOLUTION_SECONDS } from "../codec/resolution.js";
18
+ import { BaseResource, type ResourceHandle } from "../stores/resource.js";
19
+ import type { Subscription } from "../transport/ws.js";
20
+ import type { SyncContext } from "./sources.js";
21
+
22
+ export interface SeriesResource<Item> {
23
+ get(): Item[] | undefined;
24
+ subscribe(listener: () => void): () => void;
25
+ ready(): Promise<Item[]>;
26
+ readonly error?: Error;
27
+ setWindow(range: TimeRange): void;
28
+ loadOlder(): Promise<void>;
29
+ hasMore(): boolean;
30
+ loading(): boolean;
31
+ }
32
+
33
+ const bmax = (a: bigint, b: bigint) => (a > b ? a : b);
34
+ const bmin = (a: bigint, b: bigint) => (a < b ? a : b);
35
+
36
+ // pod_candles `since` replays from a bounded server-side tick ring (~16k
37
+ // batches ≈ 2.3h at a 500ms cadence). An hour of ticks fits comfortably, so
38
+ // resolutions up to 1h replay their whole forming bucket; coarser buckets
39
+ // can't, and seed their forming bar from settled 1h bars instead.
40
+ const REPLAY_SAFE_SECS = 3_600;
41
+ const SEED_RESOLUTION: Resolution = "1h";
42
+
43
+ export class CandleSeries implements SeriesResource<Bar> {
44
+ private readonly base: BaseResource<Bar[]>;
45
+ private handle: ResourceHandle<Bar[]> | undefined;
46
+
47
+ private readonly pages = new Map<number, Bar[]>(); // pageIndex -> closed bars
48
+ private readonly live = new Map<number, Bar>(); // bucketStartMs -> forming bar
49
+ private readonly resSecs: number;
50
+ private readonly pageBuckets: number;
51
+ private readonly pageSpanSecs: number;
52
+
53
+ private window: TimeRange;
54
+ private minPage: number | undefined;
55
+ private maxPage: number | undefined;
56
+ private _loading = false;
57
+ private _hasMore = true;
58
+ private lastTickUs = 0;
59
+ private tickSub: Subscription | undefined;
60
+ private alive = false;
61
+ private subRetries = 0;
62
+ private retryTimer?: ReturnType<typeof setTimeout>;
63
+
64
+ constructor(
65
+ private readonly ctx: SyncContext,
66
+ private readonly id: MarketId,
67
+ private readonly resolution: Resolution,
68
+ range?: TimeRange,
69
+ ) {
70
+ this.resSecs = RESOLUTION_SECONDS[resolution];
71
+ this.pageBuckets = RESOLUTION_PAGE_BUCKETS[resolution];
72
+ this.pageSpanSecs = this.resSecs * this.pageBuckets;
73
+ const span = this.pageSpanSecs * 1000;
74
+ this.window = range ?? { from: Date.now() - span };
75
+
76
+ this.base = new BaseResource<Bar[]>((h) => {
77
+ this.handle = h;
78
+ this.alive = true;
79
+ // Load the initial window, then subscribe from the forming bucket's
80
+ // boundary — the server replays the ticks inside it then streams live
81
+ // (no gap), so the forming bar is complete from its first trade. Never
82
+ // anchor `since` on a REST response watermark: settled responses are
83
+ // immutable and may come from the HTTP cache with a stale solutionNow.
84
+ // `since` advances as ticks arrive (so reconnects replay minimally) and
85
+ // falls back to a REST re-seed via onError when it is too old.
86
+ void this.loadWindow(this.window).then(async () => {
87
+ if (!this.alive) return;
88
+ const sinceUs = await this.prepareLiveEdge();
89
+ if (!this.alive) return;
90
+ this.lastTickUs = sinceUs;
91
+ this.tickSub = this.ctx.ws.subscribe(
92
+ "pod_candles",
93
+ { clobIds: [this.id], since: sinceUs },
94
+ (r) => this.onTick(r),
95
+ () => this.onSubError(),
96
+ );
97
+ });
98
+ // On reconnect, refresh closed bars (the WS auto-resubscribes pod_candles
99
+ // itself with the advanced `since`).
100
+ const offOpen = this.ctx.ws.on("open", () => { if (this.alive) void this.loadWindow(this.window); });
101
+ return () => {
102
+ this.alive = false;
103
+ offOpen();
104
+ if (this.retryTimer) clearTimeout(this.retryTimer);
105
+ this.tickSub?.unsubscribe();
106
+ this.tickSub = undefined;
107
+ this.handle = undefined;
108
+ };
109
+ });
110
+ }
111
+
112
+ get(): Bar[] | undefined { return this.base.get(); }
113
+ subscribe(listener: () => void): () => void { return this.base.subscribe(listener); }
114
+ ready(): Promise<Bar[]> { return this.base.ready(); }
115
+ get error(): Error | undefined { return this.base.error; }
116
+ hasMore(): boolean { return this._hasMore; }
117
+ loading(): boolean { return this._loading; }
118
+ destroy(): void { this.base.destroy(); }
119
+
120
+ setWindow(range: TimeRange): void {
121
+ this.window = range;
122
+ if (this.handle) void this.loadWindow(range);
123
+ }
124
+
125
+ async loadOlder(): Promise<void> {
126
+ if (!this.handle || this.minPage === undefined) return;
127
+ const target = this.minPage - 1;
128
+ if (target < 0) { this._hasMore = false; return; }
129
+ await this.fetchPages([target]);
130
+ }
131
+
132
+ // --- internals ---
133
+
134
+ private pageOf(secs: number): number {
135
+ return Math.floor(secs / this.pageSpanSecs);
136
+ }
137
+
138
+ private async loadWindow(range: TimeRange): Promise<void> {
139
+ const fromSecs = Math.floor(range.from / 1000);
140
+ const toSecs = Math.floor((range.to ?? Date.now()) / 1000);
141
+ const startPage = this.pageOf(fromSecs);
142
+ const endPage = this.pageOf(Math.max(fromSecs, toSecs - 1));
143
+ const nowSecs = Math.floor(Date.now() / 1000);
144
+ const trailingPage = this.pageOf(nowSecs);
145
+
146
+ const wanted: number[] = [];
147
+ for (let p = startPage; p <= endPage; p++) {
148
+ if (p === trailingPage || !this.pages.has(p)) wanted.push(p);
149
+ }
150
+ await this.fetchPages(wanted);
151
+ }
152
+
153
+ private async fetchPages(pageIndices: number[]): Promise<void> {
154
+ if (!pageIndices.length) { this.rebuild(); return; }
155
+ this._loading = true;
156
+ this.rebuild(); // surface loading state
157
+ try {
158
+ // The trailing page's window is clamped to the last closed bucket: the
159
+ // server returns only closed bars either way, so the content is
160
+ // identical — but a fully-elapsed window is served `immutable`
161
+ // (browser/CDN-cacheable; its URL rotates once per bucket close), while
162
+ // a `to` in the future would be `no-store` on every open. The forming
163
+ // bucket comes from the tick subscription (see prepareLiveEdge).
164
+ const lastClosedMs = Math.floor(Date.now() / 1000 / this.resSecs) * this.resSecs * 1000;
165
+ await Promise.all(pageIndices.map(async (p) => {
166
+ const fromMs = p * this.pageSpanSecs * 1000;
167
+ const toMs = Math.min((p + 1) * this.pageSpanSecs * 1000, lastClosedMs);
168
+ if (toMs <= fromMs) {
169
+ // Page holds nothing but the forming bucket (it just started) —
170
+ // nothing closed to fetch yet; keep bookkeeping consistent.
171
+ this.pages.set(p, this.pages.get(p) ?? []);
172
+ this.minPage = this.minPage === undefined ? p : Math.min(this.minPage, p);
173
+ this.maxPage = this.maxPage === undefined ? p : Math.max(this.maxPage, p);
174
+ return;
175
+ }
176
+ try {
177
+ const page = await this.ctx.rest.candles(this.id, {
178
+ resolution: this.resolution,
179
+ from: fromMs,
180
+ to: toMs,
181
+ limit: this.pageBuckets,
182
+ });
183
+ this.pages.set(p, page.bars);
184
+ this.minPage = this.minPage === undefined ? p : Math.min(this.minPage, p);
185
+ this.maxPage = this.maxPage === undefined ? p : Math.max(this.maxPage, p);
186
+ if (page.bars.length === 0 && this.minPage === p) this._hasMore = false;
187
+ } catch {
188
+ this.pages.set(p, this.pages.get(p) ?? []);
189
+ }
190
+ }));
191
+ } finally {
192
+ this._loading = false;
193
+ this.rebuild();
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Decide the tick subscription's `since` watermark (µs), and — for buckets
199
+ * longer than the replay ring — seed the forming bar from settled finer
200
+ * bars first: REST never returns the forming bucket and the ring can't
201
+ * replay a whole 4h/1d/1W/1M of ticks, so without the seed those bars would
202
+ * only reflect trades since page load. Seed requests are fully-elapsed
203
+ * windows, so they're `immutable` and cacheable like everything else.
204
+ * Returns `bucketBoundaryUs - 1` (`since` replays strictly-greater
205
+ * deadlines, and a batch can land exactly on the boundary).
206
+ */
207
+ private async prepareLiveEdge(): Promise<number> {
208
+ const nowSecs = Math.floor(Date.now() / 1000);
209
+ const bucketStart = Math.floor(nowSecs / this.resSecs) * this.resSecs;
210
+ if (this.resSecs <= REPLAY_SAFE_SECS) return bucketStart * 1_000_000 - 1;
211
+
212
+ const seedSecs = RESOLUTION_SECONDS[SEED_RESOLUTION];
213
+ const seedEnd = Math.floor(nowSecs / seedSecs) * seedSecs;
214
+ try {
215
+ // Chunked by the server's row cap; ≥2 chunks only for 1M (≤744 hours).
216
+ const bars: Bar[] = [];
217
+ for (let from = bucketStart; from < seedEnd; ) {
218
+ const to = Math.min(seedEnd, from + 500 * seedSecs);
219
+ const page = await this.ctx.rest.candles(this.id, {
220
+ resolution: SEED_RESOLUTION, from: from * 1000, to: to * 1000, limit: 500,
221
+ });
222
+ bars.push(...page.bars);
223
+ from = to;
224
+ }
225
+ if (bars.length && this.alive) {
226
+ bars.sort((a, b) => a.time - b.time);
227
+ const first = bars[0]!;
228
+ const last = bars[bars.length - 1]!;
229
+ this.live.set(bucketStart * 1000, {
230
+ time: bucketStart * 1000,
231
+ open: first.open,
232
+ high: bars.reduce((m, b) => bmax(m, b.high), first.high),
233
+ low: bars.reduce((m, b) => bmin(m, b.low), first.low),
234
+ close: last.close,
235
+ volume: bars.reduce((s, b) => s + b.volume, 0n),
236
+ quoteVolume: bars.reduce((s, b) => s + b.quoteVolume, 0n),
237
+ });
238
+ this.rebuild();
239
+ }
240
+ } catch { /* seed is best-effort — ticks still build the bar from here on */ }
241
+ return seedEnd * 1_000_000 - 1;
242
+ }
243
+
244
+ private onTick(result: unknown): void {
245
+ this.subRetries = 0; // live ticks flowing → subscription is healthy
246
+ const ticks = Array.isArray(result) ? result : [result];
247
+ const bucketMs = this.resSecs * 1000;
248
+ let maxUs = this.lastTickUs;
249
+ for (const t of ticks) {
250
+ const w = t as WireCandleTick;
251
+ maxUs = Math.max(maxUs, w.timestamp_us);
252
+ const tMs = usToMs(w.timestamp_us);
253
+ const start = Math.floor(tMs / bucketMs) * bucketMs;
254
+ const price = dec(w.price);
255
+ // Ticks arrive for every orderbook in the batch; price 0 means the
256
+ // market has never cleared (the indexer skips these rows too) — folding
257
+ // it would draw a $0 forming bar on never-traded markets.
258
+ if (price === 0n) continue;
259
+ const vol = dec(w.volume);
260
+ const quote = (vol * price) / WAD;
261
+ const cur = this.live.get(start);
262
+ if (cur) {
263
+ cur.high = bmax(cur.high, price);
264
+ cur.low = bmin(cur.low, price);
265
+ cur.close = price;
266
+ cur.volume += vol;
267
+ cur.quoteVolume += quote;
268
+ } else {
269
+ this.live.set(start, {
270
+ time: start, open: price, high: price, low: price, close: price,
271
+ volume: vol, quoteVolume: quote,
272
+ });
273
+ }
274
+ }
275
+ // Advance the subscription watermark so a reconnect resumes from here
276
+ // instead of replaying from the original `since`.
277
+ if (maxUs > this.lastTickUs) {
278
+ this.lastTickUs = maxUs;
279
+ this.tickSub?.update({ since: maxUs });
280
+ }
281
+ // Keep the live map small: only retain the most recent few buckets.
282
+ if (this.live.size > 8) {
283
+ const cutoff = [...this.live.keys()].sort((a, b) => b - a)[7]!;
284
+ for (const k of this.live.keys()) if (k < cutoff) this.live.delete(k);
285
+ }
286
+ this.rebuild();
287
+ }
288
+
289
+ /**
290
+ * Subscription rejected — re-seed from REST, then resubscribe. Backed off (and
291
+ * capped) so a server that keeps rejecting can't spin this into a tight loop;
292
+ * after a couple of failures we drop `since` (the likely culprit). Reset once
293
+ * live ticks flow (`onTick`).
294
+ */
295
+ private onSubError(): void {
296
+ if (!this.alive) return;
297
+ this.subRetries++;
298
+ const delay = Math.min(30_000, 500 * 2 ** (this.subRetries - 1));
299
+ if (this.retryTimer) clearTimeout(this.retryTimer);
300
+ this.retryTimer = setTimeout(() => {
301
+ void this.loadWindow(this.window).then(async () => {
302
+ if (!this.alive) return;
303
+ // Re-anchor at the current bucket boundary (re-seeding the forming
304
+ // bar for coarse resolutions). If the server keeps rejecting, drop
305
+ // `since` and go live-only — the fresh seed keeps the forming bar
306
+ // right up to now, and ticks take it from there.
307
+ const anchorUs = await this.prepareLiveEdge();
308
+ if (!this.alive) return;
309
+ const sinceUs = this.subRetries > 2 ? undefined : anchorUs;
310
+ this.lastTickUs = sinceUs ?? 0;
311
+ this.tickSub?.update({ since: sinceUs });
312
+ this.tickSub?.resubscribe();
313
+ });
314
+ }, delay);
315
+ }
316
+
317
+ private rebuild(): void {
318
+ if (!this.handle) return;
319
+ const merged = new Map<number, Bar>();
320
+ for (const bars of this.pages.values()) for (const b of bars) merged.set(b.time, b);
321
+ // Live wins only where REST has no (yet) closed bar — i.e. the forming bucket.
322
+ for (const [time, bar] of this.live) if (!merged.has(time)) merged.set(time, bar);
323
+ const out = [...merged.values()].sort((a, b) => a.time - b.time);
324
+ this.handle.set(out);
325
+ }
326
+ }
@@ -0,0 +1,152 @@
1
+ // Pre-trade preview math — the financial logic behind an order-entry panel,
2
+ // kept out of the UI. Pure function over the live account snapshot + market.
3
+ //
4
+ // Mirrors the backend's cross-margin check:
5
+ // margin_required = notional · initial_margin_rate (rate = 1/max_leverage)
6
+ // available_margin = withdrawable_cash (free cross margin)
7
+ // max_notional = available_margin / initial_margin_rate (≈ available · max_leverage)
8
+ // implied_leverage = (Σ current perp notional + notional) / perps_equity
9
+
10
+ import type { Market, PerpPosition, PositionsSnapshot, Trigger } from "../types/public.js";
11
+ import { div, imRate, mul } from "../codec/fixed.js";
12
+ import { parseAmount, toNumber, WAD } from "../codec/units.js";
13
+
14
+ export interface ReturnPriceInput {
15
+ entryPrice: bigint; // 1e18
16
+ /** Position leverage (notional / initial margin). */
17
+ leverage: number;
18
+ side: "long" | "short";
19
+ /** Target return on initial margin, signed: +20 = 20% gain, −10 = 10% loss. */
20
+ returnPct: number;
21
+ }
22
+
23
+ /**
24
+ * Mark price at which a perp position reaches `returnPct` return **on its
25
+ * initial margin** (not a raw price move). Since margin = notional / leverage,
26
+ * return-on-margin = price-move% × leverage, so the price move needed is
27
+ * `returnPct / (100·leverage)` — e.g. +20% on a 10x long needs only a +2% move.
28
+ * Used to turn a TP "gain %" / SL "loss %" into a trigger price.
29
+ */
30
+ export function priceForReturn(p: ReturnPriceInput): bigint {
31
+ if (p.leverage <= 0 || p.entryPrice <= 0n) return p.entryPrice;
32
+ const move = p.returnPct / (100 * p.leverage); // fractional price move
33
+ const dir = p.side === "long" ? 1 : -1; // longs profit up, shorts profit down
34
+ const human = toNumber(p.entryPrice) * (1 + dir * move);
35
+ return human > 0 ? parseAmount(human.toFixed(8)) : 0n;
36
+ }
37
+
38
+ /**
39
+ * The TP and SL triggers nearest the mark for a position — i.e. the ones that
40
+ * would fire first. "Nearest" depends on the side: a long's TPs sit above the
41
+ * mark (nearest = lowest price) and its SLs below (nearest = highest); a short
42
+ * is mirrored. Pass the position's triggers (already filtered to its market).
43
+ */
44
+ export function closestTriggers(
45
+ side: "long" | "short",
46
+ triggers: Trigger[],
47
+ ): { takeProfit?: Trigger; stopLoss?: Trigger } {
48
+ const pick = (list: Trigger[], wantLowest: boolean): Trigger | undefined =>
49
+ list.reduce<Trigger | undefined>((best, t) => {
50
+ if (!best) return t;
51
+ return (wantLowest ? t.triggerPrice < best.triggerPrice : t.triggerPrice > best.triggerPrice) ? t : best;
52
+ }, undefined);
53
+ const tps = triggers.filter((t) => t.triggerType === "take_profit");
54
+ const sls = triggers.filter((t) => t.triggerType === "stop_loss");
55
+ return {
56
+ takeProfit: pick(tps, side === "long"), // long TP nearest = lowest; short = highest
57
+ stopLoss: pick(sls, side === "short"), // long SL nearest = highest; short = lowest
58
+ };
59
+ }
60
+
61
+ export interface OrderPreviewInput {
62
+ side: "long" | "short";
63
+ /** 1e18-scaled price: the limit price, or the current mark for a market order. */
64
+ price: bigint;
65
+ /** 1e18-scaled USD notional the user wants to open. */
66
+ notional: bigint;
67
+ /** Picks the fee rate for `estimatedFee`: market → taker, limit → maker.
68
+ * Default market. (A crossing limit really pays taker — an estimate.) */
69
+ orderType?: "limit" | "market";
70
+ }
71
+
72
+ export interface OrderPreview {
73
+ /** Signed order size = notional / price (+ long, − short). */
74
+ size: bigint;
75
+ /** Free cross margin = withdrawable cash. */
76
+ availableMargin: bigint;
77
+ /** Initial margin this order locks = notional · initial_margin_rate. */
78
+ marginRequired: bigint;
79
+ /** Largest notional the free margin supports at this market's initial margin. */
80
+ maxNotional: bigint;
81
+ /** Account cross leverage if this order fills = (current + new notional) / equity. */
82
+ impliedLeverage: number;
83
+ /** Whether free margin covers the required margin. */
84
+ sufficientMargin: boolean;
85
+ /** Estimated fee = notional · fee rate (taker for market, maker for limit). */
86
+ estimatedFee: bigint;
87
+ }
88
+
89
+ export function previewOrder(
90
+ snap: PositionsSnapshot,
91
+ market: Market,
92
+ input: OrderPreviewInput,
93
+ ): OrderPreview {
94
+ // Spot has no leverage: the order locks the full notional in cash (im = 1.0).
95
+ // Perps use the market's initial-margin rate (1 / max_leverage).
96
+ const im = market.type === "spot" ? WAD : imRate(market.maxLeverage);
97
+ const availableMargin = snap.withdrawableCash;
98
+ const marginRequired = mul(input.notional, im);
99
+ const maxNotional = im > 0n ? div(availableMargin, im) : 0n;
100
+
101
+ const magnitude = input.price > 0n ? div(input.notional, input.price) : 0n;
102
+ const size = input.side === "short" ? -magnitude : magnitude;
103
+
104
+ const currentPerpNotional = snap.positions.reduce(
105
+ (acc, p) => (p.kind === "perp" ? acc + p.notional : acc),
106
+ 0n,
107
+ );
108
+ const impliedLeverage = snap.perpsEquity > 0n
109
+ ? toNumber(currentPerpNotional + input.notional) / toNumber(snap.perpsEquity)
110
+ : 0;
111
+
112
+ return {
113
+ size,
114
+ availableMargin,
115
+ marginRequired,
116
+ maxNotional,
117
+ impliedLeverage,
118
+ sufficientMargin: marginRequired <= availableMargin,
119
+ estimatedFee: mul(input.notional, input.orderType === "limit" ? market.makerFee : market.takerFee),
120
+ };
121
+ }
122
+
123
+ export interface ClosePreview {
124
+ /** PnL realized by closing `size` at `price` (funding and fees not included). */
125
+ expectedPnl: bigint;
126
+ /** USD notional of the closed size at `price`. */
127
+ notional: bigint;
128
+ /** Estimated fee = notional · `feeRate` (0 when no rate given). */
129
+ fee: bigint;
130
+ }
131
+
132
+ /**
133
+ * Expected result of closing `size` (magnitude) of a position at `price`:
134
+ * long → (price − entry)·size, short → (entry − price)·size. Pass the intended
135
+ * exit price — the limit price, or the protective bound for a market close —
136
+ * and the market's fee rate (taker for a market close) for the fee estimate.
137
+ */
138
+ export function closePreview(
139
+ position: PerpPosition,
140
+ input: { size: bigint; price: bigint; feeRate?: bigint },
141
+ ): ClosePreview {
142
+ const size = input.size < 0n ? -input.size : input.size;
143
+ const move = position.side === "long"
144
+ ? input.price - position.entryPrice
145
+ : position.entryPrice - input.price;
146
+ const notional = (input.price * size) / WAD;
147
+ return {
148
+ expectedPnl: (move * size) / WAD,
149
+ notional,
150
+ fee: mul(notional, input.feeRate ?? 0n),
151
+ };
152
+ }
@@ -0,0 +1,205 @@
1
+ // OrderHistory: a SeriesResource<Order> seeded from the warm first page, kept
2
+ // live by the pod_orders stream (bidder-filtered, `since`-resumed, all update
3
+ // variants incl. `modified`), and paged backwards by cursor for deep history.
4
+ //
5
+ // Reconnect: on every (re)connect we re-seed the first page (authoritative open
6
+ // orders) and refresh `since` from its watermark; the WS auto-resubscribes, and
7
+ // if `since` is too old (down too long) `onError` re-seeds and resubscribes.
8
+
9
+ import type { Address, MarketId, Order, OrderStatus, OrdersQuery } from "../types/public.js";
10
+ import type { WireOrderUpdate } from "../types/wire.js";
11
+ import { dec, WAD } from "../codec/units.js";
12
+ import { decodeOrder } from "../codec/decode.js";
13
+ import { BaseResource, type ResourceHandle } from "../stores/resource.js";
14
+ import type { Subscription } from "../transport/ws.js";
15
+ import type { SeriesResource } from "./candles.js";
16
+ import type { SyncContext } from "./sources.js";
17
+
18
+ export class OrderHistory implements SeriesResource<Order> {
19
+ private readonly base: BaseResource<Order[]>;
20
+ private handle: ResourceHandle<Order[]> | undefined;
21
+ private readonly byId = new Map<string, Order>();
22
+ private nextCursor: string | null = null;
23
+ private sub: Subscription | undefined;
24
+ private watermarkUs = 0;
25
+ private alive = false;
26
+ private _hasMore = true;
27
+ private _loading = false;
28
+ private subRetries = 0;
29
+ private retryTimer?: ReturnType<typeof setTimeout>;
30
+
31
+ constructor(
32
+ private readonly ctx: SyncContext,
33
+ private readonly account: Address,
34
+ private readonly query: OrdersQuery = {},
35
+ /** Maps a WS order's token pair to its orderbook id (see rebuild). */
36
+ private readonly resolveOrderbookId?: (pair: { base: Address; quote: Address }) => MarketId | undefined,
37
+ ) {
38
+ this.base = new BaseResource<Order[]>((h) => {
39
+ this.handle = h;
40
+ this.alive = true;
41
+ const offOpen = this.ctx.ws.on("open", () => { if (this.alive) this.seed(); });
42
+ this.seed(); // initial paint (REST is independent of the socket being open)
43
+ return () => {
44
+ this.alive = false;
45
+ offOpen();
46
+ if (this.retryTimer) clearTimeout(this.retryTimer);
47
+ this.sub?.unsubscribe();
48
+ this.sub = undefined;
49
+ this.handle = undefined;
50
+ };
51
+ });
52
+ }
53
+
54
+ get(): Order[] | undefined { return this.base.get(); }
55
+ subscribe(listener: () => void): () => void { return this.base.subscribe(listener); }
56
+ ready(): Promise<Order[]> { return this.base.ready(); }
57
+ get error(): Error | undefined { return this.base.error; }
58
+ hasMore(): boolean { return this._hasMore; }
59
+ loading(): boolean { return this._loading; }
60
+ destroy(): void { this.base.destroy(); }
61
+
62
+ setWindow(): void { /* order history pages by cursor, not by time window */ }
63
+
64
+ async loadOlder(): Promise<void> {
65
+ if (!this.handle || !this.nextCursor || this._loading) return;
66
+ this._loading = true;
67
+ this.rebuild();
68
+ try {
69
+ const page = await this.ctx.rest.orders(this.account, {
70
+ cursor: this.nextCursor,
71
+ limit: this.query.limit ?? 100,
72
+ });
73
+ for (const o of page.orders) if (!this.byId.has(o.id)) this.byId.set(o.id, o);
74
+ this.nextCursor = page.nextCursor;
75
+ this._hasMore = page.nextCursor !== null;
76
+ } finally {
77
+ this._loading = false;
78
+ this.rebuild();
79
+ }
80
+ }
81
+
82
+ // --- internals ---
83
+
84
+ private async fetchFirstPage(): Promise<boolean> {
85
+ try {
86
+ const page = await this.ctx.rest.orders(this.account, { limit: this.query.limit ?? 100 });
87
+ if (!this.alive) return false;
88
+ for (const o of page.orders) this.byId.set(o.id, o);
89
+ this.nextCursor = page.nextCursor;
90
+ this._hasMore = page.nextCursor !== null;
91
+ this.watermarkUs = page.solutionNow * 1000;
92
+ this.rebuild();
93
+ return true;
94
+ } catch (e) {
95
+ if (this.byId.size === 0) this.handle?.fail(e as Error);
96
+ return false;
97
+ }
98
+ }
99
+
100
+ private seed(): void {
101
+ void this.fetchFirstPage().then((ok) => {
102
+ if (!ok || !this.alive) return;
103
+ if (!this.sub) {
104
+ this.sub = this.ctx.ws.subscribe(
105
+ "pod_orders",
106
+ { account: this.account, since: this.watermarkUs },
107
+ (r) => this.onUpdates(r),
108
+ () => this.onSubError(),
109
+ );
110
+ } else {
111
+ this.sub.update({ since: this.watermarkUs }); // refresh for the next reconnect
112
+ }
113
+ });
114
+ }
115
+
116
+ /**
117
+ * Subscription rejected — re-seed then resubscribe. Backed off (and capped),
118
+ * so a server that keeps rejecting can't spin this into a tight re-seed /
119
+ * resubscribe loop. After a couple of failures we drop `since` (the likely
120
+ * culprit) and just stream live. Reset once live data flows (`onUpdates`).
121
+ */
122
+ private onSubError(): void {
123
+ if (!this.alive) return;
124
+ this.subRetries++;
125
+ const delay = Math.min(30_000, 500 * 2 ** (this.subRetries - 1));
126
+ if (this.retryTimer) clearTimeout(this.retryTimer);
127
+ this.retryTimer = setTimeout(() => {
128
+ void this.fetchFirstPage().then((ok) => {
129
+ if (!ok || !this.alive) return;
130
+ this.sub?.update({ since: this.subRetries > 2 ? undefined : this.watermarkUs });
131
+ this.sub?.resubscribe();
132
+ });
133
+ }, delay);
134
+ }
135
+
136
+ private onUpdates(result: unknown): void {
137
+ this.subRetries = 0; // live data flowing → subscription is healthy
138
+ const updates = (Array.isArray(result) ? result : [result]) as WireOrderUpdate[];
139
+ for (const u of updates) this.applyUpdate(u);
140
+ this.rebuild();
141
+ }
142
+
143
+ private applyUpdate(u: WireOrderUpdate): void {
144
+ switch (u.type) {
145
+ case "new":
146
+ case "invalid": {
147
+ const o = decodeOrder(u);
148
+ this.byId.set(o.id, o);
149
+ break;
150
+ }
151
+ case "fill": {
152
+ const e = this.byId.get(u.order_id);
153
+ if (e) {
154
+ e.filledBase = dec(u.filled_base_amount);
155
+ e.filledQuote = dec(u.filled_quote_amount);
156
+ e.fee = dec(u.fee);
157
+ e.status = u.status as OrderStatus;
158
+ if (u.effective_price != null) e.effectivePrice = dec(u.effective_price);
159
+ // Keep the per-fill breakdown live too. The push carries this fill's
160
+ // base/quote delta but no timestamp — receipt time is close enough.
161
+ const base = dec(u.base_amount);
162
+ const quote = dec(u.quote_amount);
163
+ e.fills = [...e.fills, { base, quote, price: base > 0n ? (quote * WAD) / base : 0n, time: Date.now() }];
164
+ }
165
+ break;
166
+ }
167
+ case "modified": {
168
+ const e = this.byId.get(u.order_id);
169
+ if (e) {
170
+ e.price = dec(u.new_price);
171
+ const sign = e.initialSize < 0n ? -1n : 1n;
172
+ e.initialSize = sign * dec(u.new_size); // new_size is an unsigned magnitude
173
+ }
174
+ break;
175
+ }
176
+ case "expired": {
177
+ const e = this.byId.get(u.order_id);
178
+ if (e) e.status = "expired";
179
+ break;
180
+ }
181
+ case "canceled": {
182
+ const e = this.byId.get(u.order_id);
183
+ if (e) e.status = "canceled";
184
+ break;
185
+ }
186
+ }
187
+ }
188
+
189
+ private rebuild(): void {
190
+ if (!this.handle) return;
191
+ // WS stream orders carry a token `pair` instead of orderbook_id — resolve
192
+ // it here so consumers can always filter by market. Retried every rebuild,
193
+ // so orders that streamed in before the markets list loaded still resolve.
194
+ if (this.resolveOrderbookId) {
195
+ for (const o of this.byId.values()) {
196
+ if (o.orderbookId === undefined && o.pair) o.orderbookId = this.resolveOrderbookId(o.pair);
197
+ }
198
+ }
199
+ let arr = [...this.byId.values()];
200
+ if (this.query.status) arr = arr.filter((o) => o.status === this.query.status);
201
+ if (this.query.orderbookId) arr = arr.filter((o) => o.orderbookId === this.query.orderbookId);
202
+ arr.sort((a, b) => b.deadlineMs - a.deadlineMs || b.nonce - a.nonce);
203
+ this.handle.set(arr);
204
+ }
205
+ }