@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 @@
1
+ {"version":3,"file":"resource.js","sourceRoot":"","sources":["../../src/stores/resource.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,0EAA0E;AAqB1E,MAAM,OAAO,YAAY;IAUM;IATrB,KAAK,CAAgB;IACrB,MAAM,CAAoB;IACjB,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;IAC3C,QAAQ,CAA2B;IACnC,OAAO,GAAG,KAAK,CAAC;IAChB,YAAY,CAAyB;IACrC,YAAY,CAA+B;IAC3C,WAAW,CAAmC;IAEtD,YAA6B,MAAyB;QAAzB,WAAM,GAAN,MAAM,CAAmB;IAAG,CAAC;IAE1D,GAAG;QACD,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,SAAS,CAAC,QAAoB;QAC5B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC7B,IAAI,CAAC,aAAa,EAAE,CAAC;QACrB,OAAO,GAAG,EAAE;YACV,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAChC,IAAI,IAAI,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC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,EAAE,CAAC,CAAC;YAClC,IAAI,IAAI,KAAK,SAAS;gBAAE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC3C,CAAC,CAAC;QACF,MAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACtC,qEAAqE;QACrE,+EAA+E;QAC/E,2DAA2D;QAC3D,cAAc,CAAC,KAAK,CAAC,CAAC;QACtB,OAAO,GAAG,EAAE,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { Position, PositionsSnapshot } from "../types/public.js";
2
+ export interface AccountMetrics {
3
+ /** account_value − total P&L (≈ net deposits / capital base). */
4
+ netDeposits: bigint;
5
+ totalPnl: bigint;
6
+ /** % of net deposits. */
7
+ totalPnlPct: number;
8
+ unrealizedPnlPct: number;
9
+ realizedPnlPct: number;
10
+ /** Σ |notional| over perp positions. */
11
+ perpNotional: bigint;
12
+ /** Σ perp notional / perps_equity. */
13
+ effectiveLeverage: number;
14
+ }
15
+ /** Column totals for a perp positions table (sums over perp positions only). */
16
+ export interface PerpPositionTotals {
17
+ count: number;
18
+ notional: bigint;
19
+ margin: bigint;
20
+ fundingAccrued: bigint;
21
+ unrealizedPnl: bigint;
22
+ realizedPnl: bigint;
23
+ }
24
+ export declare function perpPositionTotals(positions: Position[]): PerpPositionTotals;
25
+ export declare function accountMetrics(s: PositionsSnapshot): AccountMetrics;
26
+ //# sourceMappingURL=account-metrics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-metrics.d.ts","sourceRoot":"","sources":["../../src/sync/account-metrics.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAGtE,MAAM,WAAW,cAAc;IAC7B,iEAAiE;IACjE,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,yBAAyB;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,MAAM,CAAC;IACvB,wCAAwC;IACxC,YAAY,EAAE,MAAM,CAAC;IACrB,sCAAsC;IACtC,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,gFAAgF;AAChF,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,QAAQ,EAAE,GAAG,kBAAkB,CAc5E;AAED,wBAAgB,cAAc,CAAC,CAAC,EAAE,iBAAiB,GAAG,cAAc,CAkBnE"}
@@ -0,0 +1,41 @@
1
+ // Derived account metrics — the financial logic for the summary view, kept out
2
+ // of the UI layer. Pure function over a (live) PositionsSnapshot.
3
+ //
4
+ // Conventions (single source of truth so every consumer agrees):
5
+ // net deposits = account_value − total P&L (capital put in; see the
6
+ // accounting identity — exact up to fees + accrued funding)
7
+ // *_pct = component / net_deposits (return on capital)
8
+ // effective leverage = Σ perp notional / perps_equity
9
+ import { toNumber } from "../codec/units.js";
10
+ export function perpPositionTotals(positions) {
11
+ const t = {
12
+ count: 0, notional: 0n, margin: 0n, fundingAccrued: 0n, unrealizedPnl: 0n, realizedPnl: 0n,
13
+ };
14
+ for (const p of positions) {
15
+ if (p.kind !== "perp")
16
+ continue;
17
+ t.count++;
18
+ t.notional += p.notional;
19
+ t.margin += p.margin;
20
+ t.fundingAccrued += p.fundingAccrued;
21
+ t.unrealizedPnl += p.unrealizedPnl;
22
+ t.realizedPnl += p.realizedPnl;
23
+ }
24
+ return t;
25
+ }
26
+ export function accountMetrics(s) {
27
+ const totalPnl = s.totalUnrealizedPnl + s.totalRealizedPnl;
28
+ const netDeposits = s.accountValue - totalPnl;
29
+ const pct = (v) => netDeposits > 0n ? (toNumber(v) / toNumber(netDeposits)) * 100 : 0;
30
+ const perpNotional = s.positions.reduce((acc, p) => (p.kind === "perp" ? acc + p.notional : acc), 0n);
31
+ return {
32
+ netDeposits,
33
+ totalPnl,
34
+ totalPnlPct: pct(totalPnl),
35
+ unrealizedPnlPct: pct(s.totalUnrealizedPnl),
36
+ realizedPnlPct: pct(s.totalRealizedPnl),
37
+ perpNotional,
38
+ effectiveLeverage: s.perpsEquity > 0n ? toNumber(perpNotional) / toNumber(s.perpsEquity) : 0,
39
+ };
40
+ }
41
+ //# sourceMappingURL=account-metrics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-metrics.js","sourceRoot":"","sources":["../../src/sync/account-metrics.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,kEAAkE;AAClE,EAAE;AACF,iEAAiE;AACjE,6EAA6E;AAC7E,kFAAkF;AAClF,yEAAyE;AACzE,wDAAwD;AAGxD,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AA0B7C,MAAM,UAAU,kBAAkB,CAAC,SAAqB;IACtD,MAAM,CAAC,GAAuB;QAC5B,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE;KAC3F,CAAC;IACF,KAAK,MAAM,CAAC,IAAI,SAAS,EAAE,CAAC;QAC1B,IAAI,CAAC,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QAChC,CAAC,CAAC,KAAK,EAAE,CAAC;QACV,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,CAAC;QACzB,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC;QACrB,CAAC,CAAC,cAAc,I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ketId, Resolution, TimeRange } from "../types/public.js";
2
+ import type { SyncContext } from "./sources.js";
3
+ export interface SeriesResource<Item> {
4
+ get(): Item[] | undefined;
5
+ subscribe(listener: () => void): () => void;
6
+ ready(): Promise<Item[]>;
7
+ readonly error?: Error;
8
+ setWindow(range: TimeRange): void;
9
+ loadOlder(): Promise<void>;
10
+ hasMore(): boolean;
11
+ loading(): boolean;
12
+ }
13
+ export declare class CandleSeries implements SeriesResource<Bar> {
14
+ private readonly ctx;
15
+ private readonly id;
16
+ private readonly resolution;
17
+ private readonly base;
18
+ private handle;
19
+ private readonly pages;
20
+ private readonly live;
21
+ private readonly resSecs;
22
+ private readonly pageBuckets;
23
+ private readonly pageSpanSecs;
24
+ private window;
25
+ private minPage;
26
+ private maxPage;
27
+ private _loading;
28
+ private _hasMore;
29
+ private lastTickUs;
30
+ private tickSub;
31
+ private alive;
32
+ private subRetries;
33
+ private retryTimer?;
34
+ constructor(ctx: SyncContext, id: MarketId, resolution: Resolution, range?: TimeRange);
35
+ get(): Bar[] | undefined;
36
+ subscribe(listener: () => void): () => void;
37
+ ready(): Promise<Bar[]>;
38
+ get error(): Error | undefined;
39
+ hasMore(): boolean;
40
+ loading(): boolean;
41
+ destroy(): void;
42
+ setWindow(range: TimeRange): void;
43
+ loadOlder(): Promise<void>;
44
+ private pageOf;
45
+ private loadWindow;
46
+ private fetchPages;
47
+ /**
48
+ * Decide the tick subscription's `since` watermark (µs), and — for buckets
49
+ * longer than the replay ring — seed the forming bar from settled finer
50
+ * bars first: REST never returns the forming bucket and the ring can't
51
+ * replay a whole 4h/1d/1W/1M of ticks, so without the seed those bars would
52
+ * only reflect trades since page load. Seed requests are fully-elapsed
53
+ * windows, so they're `immutable` and cacheable like everything else.
54
+ * Returns `bucketBoundaryUs - 1` (`since` replays strictly-greater
55
+ * deadlines, and a batch can land exactly on the boundary).
56
+ */
57
+ private prepareLiveEdge;
58
+ private onTick;
59
+ /**
60
+ * Subscription rejected — re-seed from REST, then resubscribe. Backed off (and
61
+ * capped) so a server that keeps rejecting can't spin this into a tight loop;
62
+ * after a couple of failures we drop `since` (the likely culprit). Reset once
63
+ * live ticks flow (`onTick`).
64
+ */
65
+ private onSubError;
66
+ private rebuild;
67
+ }
68
+ //# sourceMappingURL=candles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candles.d.ts","sourceRoot":"","sources":["../../src/sync/candles.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAM/E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,WAAW,cAAc,CAAC,IAAI;IAClC,GAAG,IAAI,IAAI,EAAE,GAAG,SAAS,CAAC;IAC1B,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,KAAK,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC;IACvB,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAC;IAClC,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,OAAO,IAAI,OAAO,CAAC;IACnB,OAAO,IAAI,OAAO,CAAC;CACpB;AAYD,qBAAa,YAAa,YAAW,cAAc,CAAC,GAAG,CAAC;IAsBpD,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,EAAE;IACnB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAvB7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAsB;IAC3C,OAAO,CAAC,MAAM,CAAoC;IAElD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA4B;IAClD,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA0B;IAC/C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IAEtC,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAQ;IACxB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,OAAO,CAA2B;IAC1C,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,UAAU,CAAC,CAAgC;gBAGhC,GAAG,EAAE,WAAW,EAChB,EAAE,EAAE,QAAQ,EACZ,UAAU,EAAE,UAAU,EACvC,KAAK,CAAC,EAAE,SAAS;IA4CnB,GAAG,IAAI,GAAG,EAAE,GAAG,SAAS;IACxB,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI;IAC3C,KAAK,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IACvB,IAAI,KAAK,IAAI,KAAK,GAAG,SAAS,CAA4B;IAC1D,OAAO,IAAI,OAAO;IAClB,OAAO,IAAI,OAAO;IAClB,OAAO,IAAI,IAAI;IAEf,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI;IAK3B,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAShC,OAAO,CAAC,MAAM;YAIA,UAAU;YAeV,UAAU;IA4CxB;;;;;;;;;OASG;YACW,eAAe;IAqC7B,OAAO,CAAC,MAAM;IA6Cd;;;;;OAKG;IACH,OAAO,CAAC,UAAU;IAsBlB,OAAO,CAAC,OAAO;CAShB"}
@@ -0,0 +1,318 @@
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
+ import { dec, usToMs, WAD } from "../codec/units.js";
14
+ import { RESOLUTION_PAGE_BUCKETS, RESOLUTION_SECONDS } from "../codec/resolution.js";
15
+ import { BaseResource } from "../stores/resource.js";
16
+ const bmax = (a, b) => (a > b ? a : b);
17
+ const bmin = (a, b) => (a < b ? a : b);
18
+ // pod_candles `since` replays from a bounded server-side tick ring (~16k
19
+ // batches ≈ 2.3h at a 500ms cadence). An hour of ticks fits comfortably, so
20
+ // resolutions up to 1h replay their whole forming bucket; coarser buckets
21
+ // can't, and seed their forming bar from settled 1h bars instead.
22
+ const REPLAY_SAFE_SECS = 3_600;
23
+ const SEED_RESOLUTION = "1h";
24
+ export class CandleSeries {
25
+ ctx;
26
+ id;
27
+ resolution;
28
+ base;
29
+ handle;
30
+ pages = new Map(); // pageIndex -> closed bars
31
+ live = new Map(); // bucketStartMs -> forming bar
32
+ resSecs;
33
+ pageBuckets;
34
+ pageSpanSecs;
35
+ window;
36
+ minPage;
37
+ maxPage;
38
+ _loading = false;
39
+ _hasMore = true;
40
+ lastTickUs = 0;
41
+ tickSub;
42
+ alive = false;
43
+ subRetries = 0;
44
+ retryTimer;
45
+ constructor(ctx, id, resolution, range) {
46
+ this.ctx = ctx;
47
+ this.id = id;
48
+ this.resolution = resolution;
49
+ this.resSecs = RESOLUTION_SECONDS[resolution];
50
+ this.pageBuckets = RESOLUTION_PAGE_BUCKETS[resolution];
51
+ this.pageSpanSecs = this.resSecs * this.pageBuckets;
52
+ const span = this.pageSpanSecs * 1000;
53
+ this.window = range ?? { from: Date.now() - span };
54
+ this.base = new BaseResource((h) => {
55
+ this.handle = h;
56
+ this.alive = true;
57
+ // Load the initial window, then subscribe from the forming bucket's
58
+ // boundary — the server replays the ticks inside it then streams live
59
+ // (no gap), so the forming bar is complete from its first trade. Never
60
+ // anchor `since` on a REST response watermark: settled responses are
61
+ // immutable and may come from the HTTP cache with a stale solutionNow.
62
+ // `since` advances as ticks arrive (so reconnects replay minimally) and
63
+ // falls back to a REST re-seed via onError when it is too old.
64
+ void this.loadWindow(this.window).then(async () => {
65
+ if (!this.alive)
66
+ return;
67
+ const sinceUs = await this.prepareLiveEdge();
68
+ if (!this.alive)
69
+ return;
70
+ this.lastTickUs = sinceUs;
71
+ this.tickSub = this.ctx.ws.subscribe("pod_candles", { clobIds: [this.id], since: sinceUs }, (r) => this.onTick(r), () => this.onSubError());
72
+ });
73
+ // On reconnect, refresh closed bars (the WS auto-resubscribes pod_candles
74
+ // itself with the advanced `since`).
75
+ const offOpen = this.ctx.ws.on("open", () => { if (this.alive)
76
+ void this.loadWindow(this.window); });
77
+ return () => {
78
+ this.alive = false;
79
+ offOpen();
80
+ if (this.retryTimer)
81
+ clearTimeout(this.retryTimer);
82
+ this.tickSub?.unsubscribe();
83
+ this.tickSub = undefined;
84
+ this.handle = undefined;
85
+ };
86
+ });
87
+ }
88
+ get() { return this.base.get(); }
89
+ subscribe(listener) { return this.base.subscribe(listener); }
90
+ ready() { return this.base.ready(); }
91
+ get error() { return this.base.error; }
92
+ hasMore() { return this._hasMore; }
93
+ loading() { return this._loading; }
94
+ destroy() { this.base.destroy(); }
95
+ setWindow(range) {
96
+ this.window = range;
97
+ if (this.handle)
98
+ void this.loadWindow(range);
99
+ }
100
+ async loadOlder() {
101
+ if (!this.handle || this.minPage === undefined)
102
+ return;
103
+ const target = this.minPage - 1;
104
+ if (target < 0) {
105
+ this._hasMore = false;
106
+ return;
107
+ }
108
+ await this.fetchPages([target]);
109
+ }
110
+ // --- internals ---
111
+ pageOf(secs) {
112
+ return Math.floor(secs / this.pageSpanSecs);
113
+ }
114
+ async loadWindow(range) {
115
+ const fromSecs = Math.floor(range.from / 1000);
116
+ const toSecs = Math.floor((range.to ?? Date.now()) / 1000);
117
+ const startPage = this.pageOf(fromSecs);
118
+ const endPage = this.pageOf(Math.max(fromSecs, toSecs - 1));
119
+ const nowSecs = Math.floor(Date.now() / 1000);
120
+ const trailingPage = this.pageOf(nowSecs);
121
+ const wanted = [];
122
+ for (let p = startPage; p <= endPage; p++) {
123
+ if (p === trailingPage || !this.pages.has(p))
124
+ wanted.push(p);
125
+ }
126
+ await this.fetchPages(wanted);
127
+ }
128
+ async fetchPages(pageIndices) {
129
+ if (!pageIndices.length) {
130
+ this.rebuild();
131
+ return;
132
+ }
133
+ this._loading = true;
134
+ this.rebuild(); // surface loading state
135
+ try {
136
+ // The trailing page's window is clamped to the last closed bucket: the
137
+ // server returns only closed bars either way, so the content is
138
+ // identical — but a fully-elapsed window is served `immutable`
139
+ // (browser/CDN-cacheable; its URL rotates once per bucket close), while
140
+ // a `to` in the future would be `no-store` on every open. The forming
141
+ // bucket comes from the tick subscription (see prepareLiveEdge).
142
+ const lastClosedMs = Math.floor(Date.now() / 1000 / this.resSecs) * this.resSecs * 1000;
143
+ await Promise.all(pageIndices.map(async (p) => {
144
+ const fromMs = p * this.pageSpanSecs * 1000;
145
+ const toMs = Math.min((p + 1) * this.pageSpanSecs * 1000, lastClosedMs);
146
+ if (toMs <= fromMs) {
147
+ // Page holds nothing but the forming bucket (it just started) —
148
+ // nothing closed to fetch yet; keep bookkeeping consistent.
149
+ this.pages.set(p, this.pages.get(p) ?? []);
150
+ this.minPage = this.minPage === undefined ? p : Math.min(this.minPage, p);
151
+ this.maxPage = this.maxPage === undefined ? p : Math.max(this.maxPage, p);
152
+ return;
153
+ }
154
+ try {
155
+ const page = await this.ctx.rest.candles(this.id, {
156
+ resolution: this.resolution,
157
+ from: fromMs,
158
+ to: toMs,
159
+ limit: this.pageBuckets,
160
+ });
161
+ this.pages.set(p, page.bars);
162
+ this.minPage = this.minPage === undefined ? p : Math.min(this.minPage, p);
163
+ this.maxPage = this.maxPage === undefined ? p : Math.max(this.maxPage, p);
164
+ if (page.bars.length === 0 && this.minPage === p)
165
+ this._hasMore = false;
166
+ }
167
+ catch {
168
+ this.pages.set(p, this.pages.get(p) ?? []);
169
+ }
170
+ }));
171
+ }
172
+ finally {
173
+ this._loading = false;
174
+ this.rebuild();
175
+ }
176
+ }
177
+ /**
178
+ * Decide the tick subscription's `since` watermark (µs), and — for buckets
179
+ * longer than the replay ring — seed the forming bar from settled finer
180
+ * bars first: REST never returns the forming bucket and the ring can't
181
+ * replay a whole 4h/1d/1W/1M of ticks, so without the seed those bars would
182
+ * only reflect trades since page load. Seed requests are fully-elapsed
183
+ * windows, so they're `immutable` and cacheable like everything else.
184
+ * Returns `bucketBoundaryUs - 1` (`since` replays strictly-greater
185
+ * deadlines, and a batch can land exactly on the boundary).
186
+ */
187
+ async prepareLiveEdge() {
188
+ const nowSecs = Math.floor(Date.now() / 1000);
189
+ const bucketStart = Math.floor(nowSecs / this.resSecs) * this.resSecs;
190
+ if (this.resSecs <= REPLAY_SAFE_SECS)
191
+ return bucketStart * 1_000_000 - 1;
192
+ const seedSecs = RESOLUTION_SECONDS[SEED_RESOLUTION];
193
+ const seedEnd = Math.floor(nowSecs / seedSecs) * seedSecs;
194
+ try {
195
+ // Chunked by the server's row cap; ≥2 chunks only for 1M (≤744 hours).
196
+ const bars = [];
197
+ for (let from = bucketStart; from < seedEnd;) {
198
+ const to = Math.min(seedEnd, from + 500 * seedSecs);
199
+ const page = await this.ctx.rest.candles(this.id, {
200
+ resolution: SEED_RESOLUTION, from: from * 1000, to: to * 1000, limit: 500,
201
+ });
202
+ bars.push(...page.bars);
203
+ from = to;
204
+ }
205
+ if (bars.length && this.alive) {
206
+ bars.sort((a, b) => a.time - b.time);
207
+ const first = bars[0];
208
+ const last = bars[bars.length - 1];
209
+ this.live.set(bucketStart * 1000, {
210
+ time: bucketStart * 1000,
211
+ open: first.open,
212
+ high: bars.reduce((m, b) => bmax(m, b.high), first.high),
213
+ low: bars.reduce((m, b) => bmin(m, b.low), first.low),
214
+ close: last.close,
215
+ volume: bars.reduce((s, b) => s + b.volume, 0n),
216
+ quoteVolume: bars.reduce((s, b) => s + b.quoteVolume, 0n),
217
+ });
218
+ this.rebuild();
219
+ }
220
+ }
221
+ catch { /* seed is best-effort — ticks still build the bar from here on */ }
222
+ return seedEnd * 1_000_000 - 1;
223
+ }
224
+ onTick(result) {
225
+ this.subRetries = 0; // live ticks flowing → subscription is healthy
226
+ const ticks = Array.isArray(result) ? result : [result];
227
+ const bucketMs = this.resSecs * 1000;
228
+ let maxUs = this.lastTickUs;
229
+ for (const t of ticks) {
230
+ const w = t;
231
+ maxUs = Math.max(maxUs, w.timestamp_us);
232
+ const tMs = usToMs(w.timestamp_us);
233
+ const start = Math.floor(tMs / bucketMs) * bucketMs;
234
+ const price = dec(w.price);
235
+ // Ticks arrive for every orderbook in the batch; price 0 means the
236
+ // market has never cleared (the indexer skips these rows too) — folding
237
+ // it would draw a $0 forming bar on never-traded markets.
238
+ if (price === 0n)
239
+ continue;
240
+ const vol = dec(w.volume);
241
+ const quote = (vol * price) / WAD;
242
+ const cur = this.live.get(start);
243
+ if (cur) {
244
+ cur.high = bmax(cur.high, price);
245
+ cur.low = bmin(cur.low, price);
246
+ cur.close = price;
247
+ cur.volume += vol;
248
+ cur.quoteVolume += quote;
249
+ }
250
+ else {
251
+ this.live.set(start, {
252
+ time: start, open: price, high: price, low: price, close: price,
253
+ volume: vol, quoteVolume: quote,
254
+ });
255
+ }
256
+ }
257
+ // Advance the subscription watermark so a reconnect resumes from here
258
+ // instead of replaying from the original `since`.
259
+ if (maxUs > this.lastTickUs) {
260
+ this.lastTickUs = maxUs;
261
+ this.tickSub?.update({ since: maxUs });
262
+ }
263
+ // Keep the live map small: only retain the most recent few buckets.
264
+ if (this.live.size > 8) {
265
+ const cutoff = [...this.live.keys()].sort((a, b) => b - a)[7];
266
+ for (const k of this.live.keys())
267
+ if (k < cutoff)
268
+ this.live.delete(k);
269
+ }
270
+ this.rebuild();
271
+ }
272
+ /**
273
+ * Subscription rejected — re-seed from REST, then resubscribe. Backed off (and
274
+ * capped) so a server that keeps rejecting can't spin this into a tight loop;
275
+ * after a couple of failures we drop `since` (the likely culprit). Reset once
276
+ * live ticks flow (`onTick`).
277
+ */
278
+ onSubError() {
279
+ if (!this.alive)
280
+ return;
281
+ this.subRetries++;
282
+ const delay = Math.min(30_000, 500 * 2 ** (this.subRetries - 1));
283
+ if (this.retryTimer)
284
+ clearTimeout(this.retryTimer);
285
+ this.retryTimer = setTimeout(() => {
286
+ void this.loadWindow(this.window).then(async () => {
287
+ if (!this.alive)
288
+ return;
289
+ // Re-anchor at the current bucket boundary (re-seeding the forming
290
+ // bar for coarse resolutions). If the server keeps rejecting, drop
291
+ // `since` and go live-only — the fresh seed keeps the forming bar
292
+ // right up to now, and ticks take it from there.
293
+ const anchorUs = await this.prepareLiveEdge();
294
+ if (!this.alive)
295
+ return;
296
+ const sinceUs = this.subRetries > 2 ? undefined : anchorUs;
297
+ this.lastTickUs = sinceUs ?? 0;
298
+ this.tickSub?.update({ since: sinceUs });
299
+ this.tickSub?.resubscribe();
300
+ });
301
+ }, delay);
302
+ }
303
+ rebuild() {
304
+ if (!this.handle)
305
+ return;
306
+ const merged = new Map();
307
+ for (const bars of this.pages.values())
308
+ for (const b of bars)
309
+ merged.set(b.time, b);
310
+ // Live wins only where REST has no (yet) closed bar — i.e. the forming bucket.
311
+ for (const [time, bar] of this.live)
312
+ if (!merged.has(time))
313
+ merged.set(time, bar);
314
+ const out = [...merged.values()].sort((a, b) => a.time - b.time);
315
+ this.handle.set(out);
316
+ }
317
+ }
318
+ //# sourceMappingURL=candles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candles.js","sourceRoot":"","sources":["../../src/sync/candles.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,+EAA+E;AAC/E,2DAA2D;AAC3D,EAAE;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IAAI,CAAC,CAAC;gBAC/B,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;gBACzC,IAAI,CAAC,OAAO,EAAE,WAAW,EAAE,CAAC;YAC9B,CAAC,CAAC,CAAC;QACL,CAAC,EAAE,KAAK,CAAC,CAAC;IACZ,CAAC;IAEO,OAAO;QACb,IAAI,CAAC,IAAI,CAAC,MAAM;YAAE,OAAO;QACzB,MAAM,MAAM,GAAG,IAAI,GAAG,EAAe,CAAC;QACtC,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;YAAE,KAAK,MAAM,CAAC,IAAI,IAAI;gBAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QACpF,+EAA+E;QAC/E,KAAK,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI;YAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAClF,MAAM,GAAG,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;CACF"}
@@ -0,0 +1,74 @@
1
+ import type { Market, PerpPosition, PositionsSnapshot, Trigger } from "../types/public.js";
2
+ export interface ReturnPriceInput {
3
+ entryPrice: bigint;
4
+ /** Position leverage (notional / initial margin). */
5
+ leverage: number;
6
+ side: "long" | "short";
7
+ /** Target return on initial margin, signed: +20 = 20% gain, −10 = 10% loss. */
8
+ returnPct: number;
9
+ }
10
+ /**
11
+ * Mark price at which a perp position reaches `returnPct` return **on its
12
+ * initial margin** (not a raw price move). Since margin = notional / leverage,
13
+ * return-on-margin = price-move% × leverage, so the price move needed is
14
+ * `returnPct / (100·leverage)` — e.g. +20% on a 10x long needs only a +2% move.
15
+ * Used to turn a TP "gain %" / SL "loss %" into a trigger price.
16
+ */
17
+ export declare function priceForReturn(p: ReturnPriceInput): bigint;
18
+ /**
19
+ * The TP and SL triggers nearest the mark for a position — i.e. the ones that
20
+ * would fire first. "Nearest" depends on the side: a long's TPs sit above the
21
+ * mark (nearest = lowest price) and its SLs below (nearest = highest); a short
22
+ * is mirrored. Pass the position's triggers (already filtered to its market).
23
+ */
24
+ export declare function closestTriggers(side: "long" | "short", triggers: Trigger[]): {
25
+ takeProfit?: Trigger;
26
+ stopLoss?: Trigger;
27
+ };
28
+ export interface OrderPreviewInput {
29
+ side: "long" | "short";
30
+ /** 1e18-scaled price: the limit price, or the current mark for a market order. */
31
+ price: bigint;
32
+ /** 1e18-scaled USD notional the user wants to open. */
33
+ notional: bigint;
34
+ /** Picks the fee rate for `estimatedFee`: market → taker, limit → maker.
35
+ * Default market. (A crossing limit really pays taker — an estimate.) */
36
+ orderType?: "limit" | "market";
37
+ }
38
+ export interface OrderPreview {
39
+ /** Signed order size = notional / price (+ long, − short). */
40
+ size: bigint;
41
+ /** Free cross margin = withdrawable cash. */
42
+ availableMargin: bigint;
43
+ /** Initial margin this order locks = notional · initial_margin_rate. */
44
+ marginRequired: bigint;
45
+ /** Largest notional the free margin supports at this market's initial margin. */
46
+ maxNotional: bigint;
47
+ /** Account cross leverage if this order fills = (current + new notional) / equity. */
48
+ impliedLeverage: number;
49
+ /** Whether free margin covers the required margin. */
50
+ sufficientMargin: boolean;
51
+ /** Estimated fee = notional · fee rate (taker for market, maker for limit). */
52
+ estimatedFee: bigint;
53
+ }
54
+ export declare function previewOrder(snap: PositionsSnapshot, market: Market, input: OrderPreviewInput): OrderPreview;
55
+ export interface ClosePreview {
56
+ /** PnL realized by closing `size` at `price` (funding and fees not included). */
57
+ expectedPnl: bigint;
58
+ /** USD notional of the closed size at `price`. */
59
+ notional: bigint;
60
+ /** Estimated fee = notional · `feeRate` (0 when no rate given). */
61
+ fee: bigint;
62
+ }
63
+ /**
64
+ * Expected result of closing `size` (magnitude) of a position at `price`:
65
+ * long → (price − entry)·size, short → (entry − price)·size. Pass the intended
66
+ * exit price — the limit price, or the protective bound for a market close —
67
+ * and the market's fee rate (taker for a market close) for the fee estimate.
68
+ */
69
+ export declare function closePreview(position: PerpPosition, input: {
70
+ size: bigint;
71
+ price: bigint;
72
+ feeRate?: bigint;
73
+ }): ClosePreview;
74
+ //# sourceMappingURL=order-preview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"order-preview.d.ts","sourceRoot":"","sources":["../../src/sync/order-preview.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAI3F,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,+EAA+E;IAC/E,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,gBAAgB,GAAG,MAAM,CAM1D;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,OAAO,EACtB,QAAQ,EAAE,OAAO,EAAE,GAClB;IAAE,UAAU,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,CAY9C;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,kFAAkF;IAClF,KAAK,EAAE,MAAM,CAAC;IACd,uDAAuD;IACvD,QAAQ,EAAE,MAAM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