@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.
- package/README.md +113 -0
- package/dist/client.d.ts +93 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +168 -0
- package/dist/client.js.map +1 -0
- package/dist/codec/decode.d.ts +22 -0
- package/dist/codec/decode.d.ts.map +1 -0
- package/dist/codec/decode.js +251 -0
- package/dist/codec/decode.js.map +1 -0
- package/dist/codec/fixed.d.ts +11 -0
- package/dist/codec/fixed.d.ts.map +1 -0
- package/dist/codec/fixed.js +37 -0
- package/dist/codec/fixed.js.map +1 -0
- package/dist/codec/resolution.d.ts +14 -0
- package/dist/codec/resolution.d.ts.map +1 -0
- package/dist/codec/resolution.js +35 -0
- package/dist/codec/resolution.js.map +1 -0
- package/dist/codec/units.d.ts +35 -0
- package/dist/codec/units.d.ts.map +1 -0
- package/dist/codec/units.js +86 -0
- package/dist/codec/units.js.map +1 -0
- package/dist/datafeed.d.ts +4 -0
- package/dist/datafeed.d.ts.map +1 -0
- package/dist/datafeed.js +73 -0
- package/dist/datafeed.js.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/dist/stores/resource.d.ts +50 -0
- package/dist/stores/resource.d.ts.map +1 -0
- package/dist/stores/resource.js +154 -0
- package/dist/stores/resource.js.map +1 -0
- package/dist/sync/account-metrics.d.ts +26 -0
- package/dist/sync/account-metrics.d.ts.map +1 -0
- package/dist/sync/account-metrics.js +41 -0
- package/dist/sync/account-metrics.js.map +1 -0
- package/dist/sync/candles.d.ts +68 -0
- package/dist/sync/candles.d.ts.map +1 -0
- package/dist/sync/candles.js +318 -0
- package/dist/sync/candles.js.map +1 -0
- package/dist/sync/order-preview.d.ts +74 -0
- package/dist/sync/order-preview.d.ts.map +1 -0
- package/dist/sync/order-preview.js +86 -0
- package/dist/sync/order-preview.js.map +1 -0
- package/dist/sync/orders.d.ts +49 -0
- package/dist/sync/orders.d.ts.map +1 -0
- package/dist/sync/orders.js +210 -0
- package/dist/sync/orders.js.map +1 -0
- package/dist/sync/positions-live.d.ts +3 -0
- package/dist/sync/positions-live.d.ts.map +1 -0
- package/dist/sync/positions-live.js +86 -0
- package/dist/sync/positions-live.js.map +1 -0
- package/dist/sync/sources.d.ts +40 -0
- package/dist/sync/sources.d.ts.map +1 -0
- package/dist/sync/sources.js +197 -0
- package/dist/sync/sources.js.map +1 -0
- package/dist/transport/rest.d.ts +83 -0
- package/dist/transport/rest.d.ts.map +1 -0
- package/dist/transport/rest.js +146 -0
- package/dist/transport/rest.js.map +1 -0
- package/dist/transport/ws.d.ts +60 -0
- package/dist/transport/ws.d.ts.map +1 -0
- package/dist/transport/ws.js +235 -0
- package/dist/transport/ws.js.map +1 -0
- package/dist/types/public.d.ts +292 -0
- package/dist/types/public.d.ts.map +1 -0
- package/dist/types/public.js +4 -0
- package/dist/types/public.js.map +1 -0
- package/dist/types/wire.d.ts +283 -0
- package/dist/types/wire.d.ts.map +1 -0
- package/dist/types/wire.js +6 -0
- package/dist/types/wire.js.map +1 -0
- package/dist/write/delegation.d.ts +54 -0
- package/dist/write/delegation.d.ts.map +1 -0
- package/dist/write/delegation.js +81 -0
- package/dist/write/delegation.js.map +1 -0
- package/dist/write/index.d.ts +261 -0
- package/dist/write/index.d.ts.map +1 -0
- package/dist/write/index.js +428 -0
- package/dist/write/index.js.map +1 -0
- package/package.json +43 -0
- package/src/client.ts +229 -0
- package/src/codec/decode.ts +277 -0
- package/src/codec/fixed.ts +41 -0
- package/src/codec/resolution.ts +39 -0
- package/src/codec/units.ts +100 -0
- package/src/datafeed.ts +94 -0
- package/src/index.ts +49 -0
- package/src/stores/resource.ts +172 -0
- package/src/sync/account-metrics.ts +71 -0
- package/src/sync/candles.ts +326 -0
- package/src/sync/order-preview.ts +152 -0
- package/src/sync/orders.ts +205 -0
- package/src/sync/positions-live.ts +102 -0
- package/src/sync/sources.ts +239 -0
- package/src/transport/rest.ts +213 -0
- package/src/transport/ws.ts +255 -0
- package/src/types/public.ts +335 -0
- package/src/types/wire.ts +301 -0
- package/src/write/delegation.ts +113 -0
- package/src/write/index.ts +642 -0
package/src/datafeed.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Minimal TradingView Charting Library datafeed (IDatafeedChartApi-shaped),
|
|
2
|
+
// backed by the SDK's CandleSeries. Typed loosely so the SDK takes no
|
|
3
|
+
// dependency on the (private) charting library types.
|
|
4
|
+
|
|
5
|
+
import type { PodTradeClient } from "./client.js";
|
|
6
|
+
import type { Bar, MarketId, Resolution } from "./types/public.js";
|
|
7
|
+
import { toNumber } from "./codec/units.js";
|
|
8
|
+
|
|
9
|
+
const TV_TO_RESOLUTION: Record<string, Resolution> = {
|
|
10
|
+
"1": "1m", "5": "5m", "15": "15m", "30": "30m",
|
|
11
|
+
"60": "1h", "240": "4h", "1D": "1d", "1W": "1W", "1M": "1M",
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
interface TvBar { time: number; open: number; high: number; low: number; close: number; volume: number }
|
|
15
|
+
|
|
16
|
+
function toTvBar(b: Bar, quoteDecimals = 18): TvBar {
|
|
17
|
+
return {
|
|
18
|
+
time: b.time,
|
|
19
|
+
open: toNumber(b.open, quoteDecimals),
|
|
20
|
+
high: toNumber(b.high, quoteDecimals),
|
|
21
|
+
low: toNumber(b.low, quoteDecimals),
|
|
22
|
+
close: toNumber(b.close, quoteDecimals),
|
|
23
|
+
volume: toNumber(b.volume),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Returns an object implementing the TradingView IDatafeedChartApi surface. */
|
|
28
|
+
export function createPodDatafeed(client: PodTradeClient): unknown {
|
|
29
|
+
const subs = new Map<string, () => void>();
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
onReady(cb: (config: unknown) => void) {
|
|
33
|
+
setTimeout(() => cb({
|
|
34
|
+
supported_resolutions: Object.keys(TV_TO_RESOLUTION),
|
|
35
|
+
supports_time: true,
|
|
36
|
+
}), 0);
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
resolveSymbol(symbolName: string, onResolve: (info: unknown) => void) {
|
|
40
|
+
setTimeout(() => onResolve({
|
|
41
|
+
name: symbolName, ticker: symbolName, description: symbolName,
|
|
42
|
+
type: "crypto", session: "24x7", timezone: "Etc/UTC",
|
|
43
|
+
minmov: 1, pricescale: 100_000_000, has_intraday: true,
|
|
44
|
+
supported_resolutions: Object.keys(TV_TO_RESOLUTION),
|
|
45
|
+
volume_precision: 2, data_status: "streaming",
|
|
46
|
+
}), 0);
|
|
47
|
+
},
|
|
48
|
+
|
|
49
|
+
async getBars(
|
|
50
|
+
symbolInfo: { ticker?: string; name: string },
|
|
51
|
+
resolution: string,
|
|
52
|
+
periodParams: { from: number; to: number; firstDataRequest: boolean },
|
|
53
|
+
onResult: (bars: TvBar[], meta: { noData: boolean }) => void,
|
|
54
|
+
onError: (reason: string) => void,
|
|
55
|
+
) {
|
|
56
|
+
try {
|
|
57
|
+
const id = (symbolInfo.ticker ?? symbolInfo.name) as MarketId;
|
|
58
|
+
const res = TV_TO_RESOLUTION[resolution] ?? "1h";
|
|
59
|
+
const series = client.candles(id, res, {
|
|
60
|
+
from: periodParams.from * 1000,
|
|
61
|
+
to: periodParams.to * 1000,
|
|
62
|
+
});
|
|
63
|
+
const bars = await series.ready();
|
|
64
|
+
const inRange = bars
|
|
65
|
+
.filter((b) => b.time >= periodParams.from * 1000 && b.time < periodParams.to * 1000)
|
|
66
|
+
.map((b) => toTvBar(b));
|
|
67
|
+
onResult(inRange, { noData: inRange.length === 0 });
|
|
68
|
+
} catch (e) {
|
|
69
|
+
onError(String(e));
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
subscribeBars(
|
|
74
|
+
symbolInfo: { ticker?: string; name: string },
|
|
75
|
+
resolution: string,
|
|
76
|
+
onTick: (bar: TvBar) => void,
|
|
77
|
+
listenerGuid: string,
|
|
78
|
+
) {
|
|
79
|
+
const id = (symbolInfo.ticker ?? symbolInfo.name) as MarketId;
|
|
80
|
+
const res = TV_TO_RESOLUTION[resolution] ?? "1h";
|
|
81
|
+
const series = client.candles(id, res);
|
|
82
|
+
const unsub = series.subscribe(() => {
|
|
83
|
+
const bars = series.get();
|
|
84
|
+
if (bars && bars.length) onTick(toTvBar(bars[bars.length - 1]!));
|
|
85
|
+
});
|
|
86
|
+
subs.set(listenerGuid, unsub);
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
unsubscribeBars(listenerGuid: string) {
|
|
90
|
+
subs.get(listenerGuid)?.();
|
|
91
|
+
subs.delete(listenerGuid);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// @pod-network/trade-sdk — read/stream market-data SDK for the pod indexer.
|
|
2
|
+
|
|
3
|
+
export { PodTradeClient } from "./client.js";
|
|
4
|
+
export type { PodTradeClientOptions } from "./client.js";
|
|
5
|
+
export type { MarketsCache } from "./sync/sources.js";
|
|
6
|
+
|
|
7
|
+
// Layer 1 — low-level transports (exposed for one-shot reads & debugging)
|
|
8
|
+
export { PodRestClient, PodHttpError } from "./transport/rest.js";
|
|
9
|
+
export type {
|
|
10
|
+
MarketDynamicsPatch, MarketStatsPage, OrdersPage, BackstopPage, TriggersPage,
|
|
11
|
+
CandlesPage, OrdersQueryRest, TriggersQueryRest, RestClientOptions,
|
|
12
|
+
} from "./transport/rest.js";
|
|
13
|
+
export { PodWsClient } from "./transport/ws.js";
|
|
14
|
+
export type {
|
|
15
|
+
Channel, SubParams, Subscription, ConnectionState, WsEvent, WebSocketCtor,
|
|
16
|
+
WsClientOptions,
|
|
17
|
+
} from "./transport/ws.js";
|
|
18
|
+
|
|
19
|
+
// Layer 2 — resources
|
|
20
|
+
export type { Resource } from "./stores/resource.js";
|
|
21
|
+
export { combineResources, derivedResource } from "./stores/resource.js";
|
|
22
|
+
export { enrichPositions } from "./sync/positions-live.js";
|
|
23
|
+
export {
|
|
24
|
+
accountMetrics, type AccountMetrics,
|
|
25
|
+
perpPositionTotals, type PerpPositionTotals,
|
|
26
|
+
} from "./sync/account-metrics.js";
|
|
27
|
+
export {
|
|
28
|
+
previewOrder, type OrderPreview, type OrderPreviewInput,
|
|
29
|
+
closePreview, type ClosePreview,
|
|
30
|
+
priceForReturn, type ReturnPriceInput,
|
|
31
|
+
closestTriggers,
|
|
32
|
+
} from "./sync/order-preview.js";
|
|
33
|
+
export type { SeriesResource } from "./sync/candles.js";
|
|
34
|
+
export { CandleSeries } from "./sync/candles.js";
|
|
35
|
+
export { OrderHistory } from "./sync/orders.js";
|
|
36
|
+
|
|
37
|
+
// Framework-agnostic TradingView Charting Library datafeed (no React needed).
|
|
38
|
+
export { createPodDatafeed } from "./datafeed.js";
|
|
39
|
+
|
|
40
|
+
// Public data types
|
|
41
|
+
export * from "./types/public.js";
|
|
42
|
+
|
|
43
|
+
// Codec helpers
|
|
44
|
+
export {
|
|
45
|
+
formatAmount, formatPrice, decimalsForTick, toNumber, parseAmount, dec, WAD, WAD_DECIMALS,
|
|
46
|
+
} from "./codec/units.js";
|
|
47
|
+
export {
|
|
48
|
+
RESOLUTION_SECONDS, RESOLUTION_PAGE_BUCKETS, RESOLUTIONS, isResolution,
|
|
49
|
+
} from "./codec/resolution.js";
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// The core observable abstraction. A Resource holds an in-memory value, is
|
|
2
|
+
// ref-counted (its source starts on the first subscriber and tears down after
|
|
3
|
+
// the last leaves), and exposes the useSyncExternalStore-shaped contract.
|
|
4
|
+
|
|
5
|
+
export interface Resource<T> {
|
|
6
|
+
get(): T | undefined;
|
|
7
|
+
subscribe(listener: () => void): () => void;
|
|
8
|
+
ready(): Promise<T>;
|
|
9
|
+
/** Restart the source for a fresh seed (optional — see BaseResource). */
|
|
10
|
+
refresh?(): void;
|
|
11
|
+
readonly error?: Error;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ResourceHandle<T> {
|
|
15
|
+
set(value: T): void;
|
|
16
|
+
update(fn: (prev: T | undefined) => T): void;
|
|
17
|
+
current(): T | undefined;
|
|
18
|
+
fail(err: Error): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A source seeds + subscribes and returns a teardown function. */
|
|
22
|
+
export type ResourceSource<T> = (handle: ResourceHandle<T>) => () => void;
|
|
23
|
+
|
|
24
|
+
export class BaseResource<T> implements Resource<T> {
|
|
25
|
+
private value: T | undefined;
|
|
26
|
+
private _error: Error | undefined;
|
|
27
|
+
private readonly listeners = new Set<() => void>();
|
|
28
|
+
private teardown: (() => void) | undefined;
|
|
29
|
+
private started = false;
|
|
30
|
+
private readyPromise: Promise<T> | undefined;
|
|
31
|
+
private readyResolve: ((v: T) => void) | undefined;
|
|
32
|
+
private readyReject: ((e: Error) => void) | undefined;
|
|
33
|
+
|
|
34
|
+
constructor(private readonly source: ResourceSource<T>) {}
|
|
35
|
+
|
|
36
|
+
get(): T | undefined {
|
|
37
|
+
return this.value;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
get error(): Error | undefined {
|
|
41
|
+
return this._error;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
subscribe(listener: () => void): () => void {
|
|
45
|
+
this.listeners.add(listener);
|
|
46
|
+
this.ensureStarted();
|
|
47
|
+
return () => {
|
|
48
|
+
this.listeners.delete(listener);
|
|
49
|
+
if (this.listeners.size === 0) this.stop();
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
ready(): Promise<T> {
|
|
54
|
+
if (this.value !== undefined) return Promise.resolve(this.value);
|
|
55
|
+
if (!this.readyPromise) {
|
|
56
|
+
this.readyPromise = new Promise<T>((resolve, reject) => {
|
|
57
|
+
this.readyResolve = resolve;
|
|
58
|
+
this.readyReject = reject;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
this.ensureStarted();
|
|
62
|
+
return this.readyPromise;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Force teardown (used by the client on close). */
|
|
66
|
+
destroy(): void {
|
|
67
|
+
this.stop();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Tear down and restart the source, forcing a fresh seed while keeping
|
|
72
|
+
* subscribers and the current value (no flicker — the old snapshot stays
|
|
73
|
+
* until the new seed lands). No-op when the resource isn't running. For
|
|
74
|
+
* out-of-band mutations the streams don't announce (e.g. a faucet mint).
|
|
75
|
+
*/
|
|
76
|
+
refresh(): void {
|
|
77
|
+
if (!this.started) return;
|
|
78
|
+
this.stop();
|
|
79
|
+
this.ensureStarted();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private ensureStarted(): void {
|
|
83
|
+
if (this.started) return;
|
|
84
|
+
this.started = true;
|
|
85
|
+
const handle: ResourceHandle<T> = {
|
|
86
|
+
set: (v) => this.commit(v),
|
|
87
|
+
update: (fn) => this.commit(fn(this.value)),
|
|
88
|
+
current: () => this.value,
|
|
89
|
+
fail: (err) => {
|
|
90
|
+
this._error = err;
|
|
91
|
+
if (this.readyReject) {
|
|
92
|
+
this.readyReject(err);
|
|
93
|
+
this.readyResolve = undefined;
|
|
94
|
+
this.readyReject = undefined;
|
|
95
|
+
this.readyPromise = undefined; // allow a later ready() to retry
|
|
96
|
+
}
|
|
97
|
+
this.emit();
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
try {
|
|
101
|
+
this.teardown = this.source(handle);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
this._error = err as Error;
|
|
104
|
+
this.started = false;
|
|
105
|
+
this.emit();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
private stop(): void {
|
|
110
|
+
if (!this.started) return;
|
|
111
|
+
this.started = false;
|
|
112
|
+
const t = this.teardown;
|
|
113
|
+
this.teardown = undefined;
|
|
114
|
+
if (t) try { t(); } catch { /* ignore */ }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private commit(v: T): void {
|
|
118
|
+
this.value = v;
|
|
119
|
+
this._error = undefined;
|
|
120
|
+
if (this.readyResolve) {
|
|
121
|
+
this.readyResolve(v);
|
|
122
|
+
this.readyResolve = undefined;
|
|
123
|
+
this.readyReject = undefined;
|
|
124
|
+
}
|
|
125
|
+
this.emit();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private emit(): void {
|
|
129
|
+
this.listeners.forEach((l) => {
|
|
130
|
+
try { l(); } catch { /* ignore */ }
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A read-only view derived from several resources; recomputes on any change. */
|
|
136
|
+
export function combineResources<T>(
|
|
137
|
+
parents: Resource<unknown>[],
|
|
138
|
+
compute: () => T | undefined,
|
|
139
|
+
): Resource<T> {
|
|
140
|
+
return new BaseResource<T>((handle) => {
|
|
141
|
+
let alive = true;
|
|
142
|
+
const apply = () => {
|
|
143
|
+
if (!alive) return;
|
|
144
|
+
const next = compute();
|
|
145
|
+
if (next !== undefined) handle.set(next);
|
|
146
|
+
};
|
|
147
|
+
const unsubs = parents.map((p) => p.subscribe(apply));
|
|
148
|
+
queueMicrotask(apply);
|
|
149
|
+
return () => { alive = false; unsubs.forEach((u) => u()); };
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A read-only view derived from another resource. */
|
|
154
|
+
export function derivedResource<S, T>(
|
|
155
|
+
parent: Resource<S>,
|
|
156
|
+
select: (s: S | undefined) => T | undefined,
|
|
157
|
+
): Resource<T> {
|
|
158
|
+
return new BaseResource<T>((handle) => {
|
|
159
|
+
let alive = true;
|
|
160
|
+
const apply = () => {
|
|
161
|
+
if (!alive) return;
|
|
162
|
+
const next = select(parent.get());
|
|
163
|
+
if (next !== undefined) handle.set(next);
|
|
164
|
+
};
|
|
165
|
+
const unsub = parent.subscribe(apply);
|
|
166
|
+
// Defer the initial emit: never call handle.set synchronously inside
|
|
167
|
+
// subscribe() — a synchronous store notification during a useSyncExternalStore
|
|
168
|
+
// subscribe can loop if the subscribe closure is unstable.
|
|
169
|
+
queueMicrotask(apply);
|
|
170
|
+
return () => { alive = false; unsub(); };
|
|
171
|
+
});
|
|
172
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
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
|
+
|
|
10
|
+
import type { Position, PositionsSnapshot } from "../types/public.js";
|
|
11
|
+
import { toNumber } from "../codec/units.js";
|
|
12
|
+
|
|
13
|
+
export interface AccountMetrics {
|
|
14
|
+
/** account_value − total P&L (≈ net deposits / capital base). */
|
|
15
|
+
netDeposits: bigint;
|
|
16
|
+
totalPnl: bigint;
|
|
17
|
+
/** % of net deposits. */
|
|
18
|
+
totalPnlPct: number;
|
|
19
|
+
unrealizedPnlPct: number;
|
|
20
|
+
realizedPnlPct: number;
|
|
21
|
+
/** Σ |notional| over perp positions. */
|
|
22
|
+
perpNotional: bigint;
|
|
23
|
+
/** Σ perp notional / perps_equity. */
|
|
24
|
+
effectiveLeverage: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Column totals for a perp positions table (sums over perp positions only). */
|
|
28
|
+
export interface PerpPositionTotals {
|
|
29
|
+
count: number;
|
|
30
|
+
notional: bigint;
|
|
31
|
+
margin: bigint;
|
|
32
|
+
fundingAccrued: bigint;
|
|
33
|
+
unrealizedPnl: bigint;
|
|
34
|
+
realizedPnl: bigint;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function perpPositionTotals(positions: Position[]): PerpPositionTotals {
|
|
38
|
+
const t: PerpPositionTotals = {
|
|
39
|
+
count: 0, notional: 0n, margin: 0n, fundingAccrued: 0n, unrealizedPnl: 0n, realizedPnl: 0n,
|
|
40
|
+
};
|
|
41
|
+
for (const p of positions) {
|
|
42
|
+
if (p.kind !== "perp") continue;
|
|
43
|
+
t.count++;
|
|
44
|
+
t.notional += p.notional;
|
|
45
|
+
t.margin += p.margin;
|
|
46
|
+
t.fundingAccrued += p.fundingAccrued;
|
|
47
|
+
t.unrealizedPnl += p.unrealizedPnl;
|
|
48
|
+
t.realizedPnl += p.realizedPnl;
|
|
49
|
+
}
|
|
50
|
+
return t;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function accountMetrics(s: PositionsSnapshot): AccountMetrics {
|
|
54
|
+
const totalPnl = s.totalUnrealizedPnl + s.totalRealizedPnl;
|
|
55
|
+
const netDeposits = s.accountValue - totalPnl;
|
|
56
|
+
const pct = (v: bigint): number =>
|
|
57
|
+
netDeposits > 0n ? (toNumber(v) / toNumber(netDeposits)) * 100 : 0;
|
|
58
|
+
const perpNotional = s.positions.reduce(
|
|
59
|
+
(acc, p) => (p.kind === "perp" ? acc + p.notional : acc),
|
|
60
|
+
0n,
|
|
61
|
+
);
|
|
62
|
+
return {
|
|
63
|
+
netDeposits,
|
|
64
|
+
totalPnl,
|
|
65
|
+
totalPnlPct: pct(totalPnl),
|
|
66
|
+
unrealizedPnlPct: pct(s.totalUnrealizedPnl),
|
|
67
|
+
realizedPnlPct: pct(s.totalRealizedPnl),
|
|
68
|
+
perpNotional,
|
|
69
|
+
effectiveLeverage: s.perpsEquity > 0n ? toNumber(perpNotional) / toNumber(s.perpsEquity) : 0,
|
|
70
|
+
};
|
|
71
|
+
}
|