@perpbrain/sdk 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +25 -2
- package/dist/cjs/card.d.ts +2 -0
- package/dist/cjs/card.js +311 -0
- package/dist/cjs/cli.d.ts +3 -0
- package/dist/cjs/cli.js +33 -0
- package/dist/cjs/guarded.d.ts +12 -0
- package/dist/cjs/guarded.js +52 -0
- package/dist/cjs/guards.d.ts +154 -0
- package/dist/cjs/guards.js +855 -0
- package/dist/cjs/index.d.ts +16 -0
- package/dist/cjs/index.js +66 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/receipt.d.ts +45 -0
- package/dist/cjs/receipt.js +855 -0
- package/dist/cjs/study.d.ts +29 -0
- package/dist/cjs/study.js +259 -0
- package/dist/cjs/vendor/costs.d.ts +64 -0
- package/dist/cjs/vendor/costs.js +247 -0
- package/dist/cjs/vendor/execution.d.ts +44 -0
- package/dist/cjs/vendor/execution.js +132 -0
- package/dist/cjs/vendor/fees.d.ts +17 -0
- package/dist/cjs/vendor/fees.js +82 -0
- package/dist/cjs/vendor/funding_adapter.d.ts +11 -0
- package/dist/cjs/vendor/funding_adapter.js +33 -0
- package/dist/cjs/vendor/info.d.ts +24 -0
- package/dist/cjs/vendor/info.js +55 -0
- package/dist/cjs/vendor/queries.d.ts +69 -0
- package/dist/cjs/vendor/queries.js +210 -0
- package/dist/cjs/vendor/rateLimit.d.ts +14 -0
- package/dist/cjs/vendor/rateLimit.js +57 -0
- package/dist/cjs/vendor/simDefaults.d.ts +31 -0
- package/dist/cjs/vendor/simDefaults.js +49 -0
- package/dist/cjs/vendor/simulate.d.ts +130 -0
- package/dist/cjs/vendor/simulate.js +610 -0
- package/dist/esm/card.d.ts +2 -0
- package/dist/esm/card.js +308 -0
- package/dist/esm/cli.d.ts +3 -0
- package/dist/esm/cli.js +31 -0
- package/dist/esm/guarded.d.ts +12 -0
- package/dist/esm/guarded.js +49 -0
- package/dist/esm/guards.d.ts +154 -0
- package/dist/esm/guards.js +841 -0
- package/dist/esm/index.d.ts +16 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/receipt.d.ts +45 -0
- package/dist/esm/receipt.js +839 -0
- package/dist/esm/study.d.ts +29 -0
- package/dist/esm/study.js +249 -0
- package/dist/esm/vendor/costs.d.ts +64 -0
- package/dist/esm/vendor/costs.js +240 -0
- package/dist/esm/vendor/execution.d.ts +44 -0
- package/dist/esm/vendor/execution.js +122 -0
- package/dist/esm/vendor/fees.d.ts +17 -0
- package/dist/esm/vendor/fees.js +74 -0
- package/dist/esm/vendor/funding_adapter.d.ts +11 -0
- package/dist/esm/vendor/funding_adapter.js +30 -0
- package/dist/esm/vendor/info.d.ts +24 -0
- package/dist/esm/vendor/info.js +49 -0
- package/dist/esm/vendor/queries.d.ts +69 -0
- package/dist/esm/vendor/queries.js +196 -0
- package/dist/esm/vendor/rateLimit.d.ts +14 -0
- package/dist/esm/vendor/rateLimit.js +53 -0
- package/dist/esm/vendor/simDefaults.d.ts +31 -0
- package/dist/esm/vendor/simDefaults.js +44 -0
- package/dist/esm/vendor/simulate.d.ts +130 -0
- package/dist/esm/vendor/simulate.js +605 -0
- package/package.json +64 -4
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/** Execution assumptions for book-based fills (slippage floors and book metadata). */
|
|
2
|
+
import { parseDecimal } from "./fees.js";
|
|
3
|
+
export const DEFAULT_MIN_STOP_SLIPPAGE_BPS = "10";
|
|
4
|
+
export const DEFAULT_MIN_TAKER_SLIPPAGE_BPS = "0";
|
|
5
|
+
export const NON_HISTORICAL_BOOK_LABEL = "non_historical_book";
|
|
6
|
+
export function normalizedExecution(config) {
|
|
7
|
+
return config === null || config === undefined ? {} : { ...config };
|
|
8
|
+
}
|
|
9
|
+
/** Stop slippage floor in bps. "0" disables it; the default is version-pinned. */
|
|
10
|
+
export function minStopBps(config, fallback = DEFAULT_MIN_STOP_SLIPPAGE_BPS) {
|
|
11
|
+
const value = config.minStopSlippageBps ?? fallback;
|
|
12
|
+
if (parseDecimal(value) < 0n) {
|
|
13
|
+
throw new Error("min_stop_slippage_bps must be non-negative");
|
|
14
|
+
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
export function minTakerBps(config) {
|
|
18
|
+
// Issue 3: the same validation as Python (_non_negative_bps).
|
|
19
|
+
return nonNegative(config.minTakerSlippageBps ?? DEFAULT_MIN_TAKER_SLIPPAGE_BPS, "min_taker_slippage_bps");
|
|
20
|
+
}
|
|
21
|
+
export function volatilityScale(config) {
|
|
22
|
+
const value = config.volatilitySlippageScale;
|
|
23
|
+
return value === undefined ? null : nonNegative(value, "volatility_slippage_scale");
|
|
24
|
+
}
|
|
25
|
+
function nonNegative(value, label) {
|
|
26
|
+
if (decimal(value, label) < 0n) {
|
|
27
|
+
throw new Error(`${label} must be non-negative`);
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
export function bookLabels(book) {
|
|
32
|
+
if (book.historical === false) {
|
|
33
|
+
return [NON_HISTORICAL_BOOK_LABEL];
|
|
34
|
+
}
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
export function checkBookTime(book, bar, config, warnings) {
|
|
38
|
+
const barTime = bar.timeMs;
|
|
39
|
+
const bookTime = book.timeMs;
|
|
40
|
+
if (barTime === undefined || bookTime === undefined) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (barTime === bookTime) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const message = `book time_ms ${bookTime} does not match bar time_ms ${barTime}`;
|
|
47
|
+
const mode = config.bookTimeMismatch ?? "warn";
|
|
48
|
+
if (mode === "fail") {
|
|
49
|
+
throw new Error(message);
|
|
50
|
+
}
|
|
51
|
+
if (mode !== "warn") {
|
|
52
|
+
throw new Error("book_time_mismatch must be warn or fail");
|
|
53
|
+
}
|
|
54
|
+
warnings.push(message);
|
|
55
|
+
}
|
|
56
|
+
export function applySlippageFloor(side, anchor, legs, minBps, bar, volScale) {
|
|
57
|
+
const min = parseDecimal(minBps);
|
|
58
|
+
if (min <= 0n) {
|
|
59
|
+
return legs;
|
|
60
|
+
}
|
|
61
|
+
let filled = 0n;
|
|
62
|
+
let notional = 0n;
|
|
63
|
+
const scale = 10n ** 18n;
|
|
64
|
+
for (const leg of legs) {
|
|
65
|
+
filled += leg.qty;
|
|
66
|
+
notional += (leg.qty * leg.px) / scale;
|
|
67
|
+
}
|
|
68
|
+
if (filled <= 0n || notional <= 0n) {
|
|
69
|
+
return legs;
|
|
70
|
+
}
|
|
71
|
+
const bps = scaledBps(min, bar, volScale);
|
|
72
|
+
const minimum = (notional * bps) / (10000n * scale);
|
|
73
|
+
const current = slippageTotal(side, anchor, legs);
|
|
74
|
+
if (current >= minimum) {
|
|
75
|
+
return legs;
|
|
76
|
+
}
|
|
77
|
+
const shortfall = minimum - current;
|
|
78
|
+
const delta = (shortfall * scale) / filled;
|
|
79
|
+
return legs.map((leg) => ({
|
|
80
|
+
qty: leg.qty,
|
|
81
|
+
px: side === "buy" ? leg.px + delta : leg.px - delta,
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
function scaledBps(minBps, bar, volScale) {
|
|
85
|
+
if (volScale === null || bar === null) {
|
|
86
|
+
return minBps;
|
|
87
|
+
}
|
|
88
|
+
const scale = parseDecimal(volScale);
|
|
89
|
+
if (scale <= 0n) {
|
|
90
|
+
return minBps;
|
|
91
|
+
}
|
|
92
|
+
const opened = decimal(bar.open, "open");
|
|
93
|
+
const high = decimal(bar.high, "high");
|
|
94
|
+
const low = decimal(bar.low, "low");
|
|
95
|
+
if (opened <= 0n) {
|
|
96
|
+
return minBps;
|
|
97
|
+
}
|
|
98
|
+
// All values are 10^18 fixed point. rangeBps = (high - low) / open * 10000, and
|
|
99
|
+
// factor = 1 + scale * rangeBps / 10000 (Python execution._scaled_bps). The product
|
|
100
|
+
// scale * rangeBps is 10^36 scaled, so divide by 10^18 as well as by 10000.
|
|
101
|
+
const one = 10n ** 18n;
|
|
102
|
+
const rangeBps = ((high - low) * 10000n * one) / opened;
|
|
103
|
+
const factor = one + (scale * rangeBps) / (10000n * one);
|
|
104
|
+
return (minBps * factor) / one;
|
|
105
|
+
}
|
|
106
|
+
function slippageTotal(side, anchor, legs) {
|
|
107
|
+
const scale = 10n ** 18n;
|
|
108
|
+
let total = 0n;
|
|
109
|
+
for (const leg of legs) {
|
|
110
|
+
total +=
|
|
111
|
+
side === "buy" ? ((leg.px - anchor) * leg.qty) / scale : ((anchor - leg.px) * leg.qty) / scale;
|
|
112
|
+
}
|
|
113
|
+
return total;
|
|
114
|
+
}
|
|
115
|
+
function decimal(value, label) {
|
|
116
|
+
try {
|
|
117
|
+
return parseDecimal(value);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
throw new Error(`${label} must be a decimal`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Versioned perp fee table. Tier-0 base rates from the public fee docs. */
|
|
2
|
+
export declare const DOCS_URL = "https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees";
|
|
3
|
+
export declare const DEFAULT_FEE_VERSION = "hl-perp-tier0-base-2026-10-16";
|
|
4
|
+
export declare const TIER1_FEE_VERSION = "hl-perp-tier1-base-2026-10-16";
|
|
5
|
+
export declare const LEGACY_TIER0_FEE_VERSION = "hl-perp-tier0-base-pre-2025-05-05";
|
|
6
|
+
export declare const HL_FEE_CUTOFF_MS = 1746414000000;
|
|
7
|
+
export interface FeeSchedule {
|
|
8
|
+
version: string;
|
|
9
|
+
takerBps: string;
|
|
10
|
+
makerBps: string;
|
|
11
|
+
docsUrl: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function feeSchedule(version?: string | null): FeeSchedule;
|
|
14
|
+
export declare function feeScheduleAtTime(tradeTimeMs: number): FeeSchedule;
|
|
15
|
+
export declare function parseDecimal(text: string): bigint;
|
|
16
|
+
export declare function formatDecimal(value: bigint): string;
|
|
17
|
+
export declare function feeAmount(notional: bigint, bps: string): bigint;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** Versioned perp fee table. Tier-0 base rates from the public fee docs. */
|
|
2
|
+
export const DOCS_URL = "https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees";
|
|
3
|
+
export const DEFAULT_FEE_VERSION = "hl-perp-tier0-base-2026-10-16";
|
|
4
|
+
export const TIER1_FEE_VERSION = "hl-perp-tier1-base-2026-10-16";
|
|
5
|
+
export const LEGACY_TIER0_FEE_VERSION = "hl-perp-tier0-base-pre-2025-05-05";
|
|
6
|
+
export const HL_FEE_CUTOFF_MS = 1_746_414_000_000;
|
|
7
|
+
const SCHEDULES = [
|
|
8
|
+
{
|
|
9
|
+
version: LEGACY_TIER0_FEE_VERSION,
|
|
10
|
+
takerBps: "3.5",
|
|
11
|
+
makerBps: "1",
|
|
12
|
+
docsUrl: DOCS_URL,
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
version: DEFAULT_FEE_VERSION,
|
|
16
|
+
takerBps: "4.5",
|
|
17
|
+
makerBps: "1.5",
|
|
18
|
+
docsUrl: DOCS_URL,
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
version: TIER1_FEE_VERSION,
|
|
22
|
+
takerBps: "4",
|
|
23
|
+
makerBps: "1.2",
|
|
24
|
+
docsUrl: DOCS_URL,
|
|
25
|
+
},
|
|
26
|
+
];
|
|
27
|
+
export function feeSchedule(version = null) {
|
|
28
|
+
const chosen = version ?? DEFAULT_FEE_VERSION;
|
|
29
|
+
return scheduleOf(chosen);
|
|
30
|
+
}
|
|
31
|
+
export function feeScheduleAtTime(tradeTimeMs) {
|
|
32
|
+
if (!Number.isInteger(tradeTimeMs) || tradeTimeMs < 0) {
|
|
33
|
+
throw new Error("trade_time_ms must be a positive integer");
|
|
34
|
+
}
|
|
35
|
+
if (tradeTimeMs < HL_FEE_CUTOFF_MS) {
|
|
36
|
+
return scheduleOf(LEGACY_TIER0_FEE_VERSION);
|
|
37
|
+
}
|
|
38
|
+
return scheduleOf(DEFAULT_FEE_VERSION);
|
|
39
|
+
}
|
|
40
|
+
function scheduleOf(version) {
|
|
41
|
+
const found = SCHEDULES.find((item) => item.version === version);
|
|
42
|
+
if (found === undefined) {
|
|
43
|
+
throw new Error("unknown fee schedule version");
|
|
44
|
+
}
|
|
45
|
+
return found;
|
|
46
|
+
}
|
|
47
|
+
const SCALE = 18n;
|
|
48
|
+
const SCALE_FACTOR = 10n ** SCALE;
|
|
49
|
+
export function parseDecimal(text) {
|
|
50
|
+
if (!/^-?\d+(\.\d+)?$/.test(text)) {
|
|
51
|
+
throw new Error("decimal required");
|
|
52
|
+
}
|
|
53
|
+
const negative = text.startsWith("-");
|
|
54
|
+
const body = negative ? text.slice(1) : text;
|
|
55
|
+
const [whole, frac = ""] = body.split(".");
|
|
56
|
+
if (frac.length > Number(SCALE)) {
|
|
57
|
+
throw new Error("decimal scale exceeded");
|
|
58
|
+
}
|
|
59
|
+
const padded = frac + "0".repeat(Number(SCALE) - frac.length);
|
|
60
|
+
const value = BigInt(whole) * SCALE_FACTOR + BigInt(padded);
|
|
61
|
+
return negative ? -value : value;
|
|
62
|
+
}
|
|
63
|
+
export function formatDecimal(value) {
|
|
64
|
+
const negative = value < 0n;
|
|
65
|
+
const abs = negative ? -value : value;
|
|
66
|
+
const whole = abs / SCALE_FACTOR;
|
|
67
|
+
const frac = (abs % SCALE_FACTOR).toString().padStart(Number(SCALE), "0").replace(/0+$/, "");
|
|
68
|
+
const text = frac.length === 0 ? whole.toString() : `${whole.toString()}.${frac}`;
|
|
69
|
+
return negative ? `-${text}` : text;
|
|
70
|
+
}
|
|
71
|
+
export function feeAmount(notional, bps) {
|
|
72
|
+
const rate = parseDecimal(bps);
|
|
73
|
+
return (notional * rate) / (SCALE_FACTOR * 10000n);
|
|
74
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Map Hyperliquid fundingHistory rows to simulator FundingSample values. */
|
|
2
|
+
import { type FundingSample } from "./simulate.ts";
|
|
3
|
+
export interface FundingHistoryRow {
|
|
4
|
+
coin?: string;
|
|
5
|
+
fundingRate: string;
|
|
6
|
+
time: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function fundingSamplesFromHistory(rows: FundingHistoryRow[], oracleByGridTime: Record<number, string>, options?: {
|
|
9
|
+
coin?: string;
|
|
10
|
+
fundingIntervalMs?: number;
|
|
11
|
+
}): FundingSample[];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Map Hyperliquid fundingHistory rows to simulator FundingSample values. */
|
|
2
|
+
import { fundingGridTime, HL_FUNDING_INTERVAL_MS } from "./simulate.js";
|
|
3
|
+
import { formatDecimal, parseDecimal } from "./fees.js";
|
|
4
|
+
export function fundingSamplesFromHistory(rows, oracleByGridTime, options = {}) {
|
|
5
|
+
const interval = options.fundingIntervalMs ?? HL_FUNDING_INTERVAL_MS;
|
|
6
|
+
if (!Number.isInteger(interval) || interval <= 0) {
|
|
7
|
+
throw new Error("funding_interval_ms must be a positive integer");
|
|
8
|
+
}
|
|
9
|
+
const samples = [];
|
|
10
|
+
for (const row of rows) {
|
|
11
|
+
if (options.coin !== undefined && row.coin !== options.coin) {
|
|
12
|
+
throw new Error("funding coin does not match the request");
|
|
13
|
+
}
|
|
14
|
+
if (!Number.isInteger(row.time) || row.time < 0) {
|
|
15
|
+
throw new Error("funding time must be a positive integer");
|
|
16
|
+
}
|
|
17
|
+
const grid = fundingGridTime(row.time, interval);
|
|
18
|
+
const oracle = oracleByGridTime[grid];
|
|
19
|
+
if (oracle === undefined || oracle === "") {
|
|
20
|
+
throw new Error("oracle price missing for funding grid time");
|
|
21
|
+
}
|
|
22
|
+
samples.push({
|
|
23
|
+
timeMs: row.time,
|
|
24
|
+
ratePerHour: formatDecimal(parseDecimal(row.fundingRate)),
|
|
25
|
+
oraclePxUsd: oracle,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
samples.sort((left, right) => left.timeMs - right.timeMs);
|
|
29
|
+
return samples;
|
|
30
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Public info endpoint client. POST types are an allowlist. No order endpoint. */
|
|
2
|
+
import { TokenBucket } from "./rateLimit.ts";
|
|
3
|
+
export declare const INFO_URL = "https://api.hyperliquid.xyz/info";
|
|
4
|
+
export declare const READ_TYPES: readonly ["meta", "metaAndAssetCtxs", "l2Book", "candleSnapshot", "clearinghouseState", "userFees", "fundingHistory"];
|
|
5
|
+
export type ReadType = (typeof READ_TYPES)[number];
|
|
6
|
+
export type Transport = (url: string, body: Readonly<Record<string, unknown>>) => unknown;
|
|
7
|
+
export declare function assertInfoUrl(url: string): void;
|
|
8
|
+
export declare class InfoClient {
|
|
9
|
+
readonly limiter: TokenBucket;
|
|
10
|
+
readonly url: string;
|
|
11
|
+
private readonly transport;
|
|
12
|
+
constructor(transport: Transport, limiter?: TokenBucket, url?: string);
|
|
13
|
+
post(body: Readonly<Record<string, unknown>>): unknown;
|
|
14
|
+
}
|
|
15
|
+
export interface FetchLike {
|
|
16
|
+
(url: string, init: {
|
|
17
|
+
method: string;
|
|
18
|
+
headers: Record<string, string>;
|
|
19
|
+
body: string;
|
|
20
|
+
}): Promise<{
|
|
21
|
+
json(): Promise<unknown>;
|
|
22
|
+
}>;
|
|
23
|
+
}
|
|
24
|
+
export declare function fetchInfoTransport(fetchImpl: FetchLike): (url: string, body: Readonly<Record<string, unknown>>) => Promise<unknown>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Public info endpoint client. POST types are an allowlist. No order endpoint. */
|
|
2
|
+
import { TokenBucket } from "./rateLimit.js";
|
|
3
|
+
export const INFO_URL = "https://api.hyperliquid.xyz/info";
|
|
4
|
+
export const READ_TYPES = [
|
|
5
|
+
"meta",
|
|
6
|
+
"metaAndAssetCtxs",
|
|
7
|
+
"l2Book",
|
|
8
|
+
"candleSnapshot",
|
|
9
|
+
"clearinghouseState",
|
|
10
|
+
"userFees",
|
|
11
|
+
"fundingHistory",
|
|
12
|
+
];
|
|
13
|
+
export function assertInfoUrl(url) {
|
|
14
|
+
if (!url.endsWith("/info") || url.includes("/exchange")) {
|
|
15
|
+
throw new Error("info url must be the public /info endpoint");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function isReadType(value) {
|
|
19
|
+
return READ_TYPES.some((kind) => kind === value);
|
|
20
|
+
}
|
|
21
|
+
export class InfoClient {
|
|
22
|
+
limiter;
|
|
23
|
+
url;
|
|
24
|
+
transport;
|
|
25
|
+
constructor(transport, limiter, url = INFO_URL) {
|
|
26
|
+
assertInfoUrl(url);
|
|
27
|
+
this.transport = transport;
|
|
28
|
+
this.limiter = limiter ?? new TokenBucket();
|
|
29
|
+
this.url = url;
|
|
30
|
+
}
|
|
31
|
+
post(body) {
|
|
32
|
+
if (!isReadType(body.type)) {
|
|
33
|
+
throw new Error("info type is not allowed");
|
|
34
|
+
}
|
|
35
|
+
assertInfoUrl(this.url);
|
|
36
|
+
this.limiter.acquire();
|
|
37
|
+
return this.transport(this.url, body);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function fetchInfoTransport(fetchImpl) {
|
|
41
|
+
return async (url, body) => {
|
|
42
|
+
const response = await fetchImpl(url, {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "content-type": "application/json" },
|
|
45
|
+
body: JSON.stringify(body),
|
|
46
|
+
});
|
|
47
|
+
return response.json();
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Read-only info queries. Every result carries data age. No order path. */
|
|
2
|
+
import { InfoClient } from "./info.ts";
|
|
3
|
+
export declare const STALE_AFTER_MS = 20000;
|
|
4
|
+
export declare const MAX_BOOK_LEVELS = 20;
|
|
5
|
+
export interface DataAge {
|
|
6
|
+
ageMs: number;
|
|
7
|
+
stale: boolean;
|
|
8
|
+
asOfMs: number;
|
|
9
|
+
}
|
|
10
|
+
export interface Level {
|
|
11
|
+
px: string;
|
|
12
|
+
sz: string;
|
|
13
|
+
n: number;
|
|
14
|
+
}
|
|
15
|
+
export interface Market {
|
|
16
|
+
name: string;
|
|
17
|
+
szDecimals: number;
|
|
18
|
+
maxLeverage: number;
|
|
19
|
+
}
|
|
20
|
+
export interface MarketsResult extends DataAge {
|
|
21
|
+
markets: Market[];
|
|
22
|
+
}
|
|
23
|
+
export interface BookResult extends DataAge {
|
|
24
|
+
coin: string;
|
|
25
|
+
bids: Level[];
|
|
26
|
+
asks: Level[];
|
|
27
|
+
}
|
|
28
|
+
export interface FundingResult extends DataAge {
|
|
29
|
+
coin: string;
|
|
30
|
+
funding: string;
|
|
31
|
+
openInterest: string;
|
|
32
|
+
markPx: string;
|
|
33
|
+
oraclePx: string;
|
|
34
|
+
midPx: string;
|
|
35
|
+
}
|
|
36
|
+
export interface Position {
|
|
37
|
+
coin: string;
|
|
38
|
+
size: string;
|
|
39
|
+
entryPx: string;
|
|
40
|
+
liquidationPx: string | null;
|
|
41
|
+
unrealizedPnl: string;
|
|
42
|
+
leverageType: string;
|
|
43
|
+
leverageValue: number;
|
|
44
|
+
}
|
|
45
|
+
export interface PositionsResult extends DataAge {
|
|
46
|
+
address: string;
|
|
47
|
+
positions: Position[];
|
|
48
|
+
}
|
|
49
|
+
export interface FeesResult extends DataAge {
|
|
50
|
+
address: string;
|
|
51
|
+
takerRate: string;
|
|
52
|
+
makerRate: string;
|
|
53
|
+
takerBps: string;
|
|
54
|
+
makerBps: string;
|
|
55
|
+
}
|
|
56
|
+
export declare function fractionToBps(fraction: string): string;
|
|
57
|
+
export declare function requireAddress(address: string): string;
|
|
58
|
+
export declare function messageTime(payload: unknown): number | null;
|
|
59
|
+
export declare function makeAge(asOfMs: number, nowMs: number): DataAge;
|
|
60
|
+
export declare function clampDepth(depth: number): number;
|
|
61
|
+
export declare function parseL2Levels(value: unknown, depth: number): {
|
|
62
|
+
bids: Level[];
|
|
63
|
+
asks: Level[];
|
|
64
|
+
};
|
|
65
|
+
export declare function markets(client: InfoClient, nowMs: number, receivedMs?: number): MarketsResult;
|
|
66
|
+
export declare function orderBook(client: InfoClient, coin: string, nowMs: number, depth?: number, receivedMs?: number): BookResult;
|
|
67
|
+
export declare function funding(client: InfoClient, coin: string, nowMs: number, receivedMs?: number): FundingResult;
|
|
68
|
+
export declare function positions(client: InfoClient, address: string, nowMs: number, receivedMs?: number): PositionsResult;
|
|
69
|
+
export declare function fees(client: InfoClient, address: string, nowMs: number, receivedMs?: number): FeesResult;
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/** Read-only info queries. Every result carries data age. No order path. */
|
|
2
|
+
export const STALE_AFTER_MS = 20_000;
|
|
3
|
+
export const MAX_BOOK_LEVELS = 20;
|
|
4
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
5
|
+
export function fractionToBps(fraction) {
|
|
6
|
+
if (!/^\d+(\.\d+)?$/.test(fraction)) {
|
|
7
|
+
throw new Error("rate must be a decimal string");
|
|
8
|
+
}
|
|
9
|
+
const [whole, frac = ""] = fraction.split(".");
|
|
10
|
+
const digits = `${whole}${frac}`.replace(/^0+/, "") || "0";
|
|
11
|
+
const shift = 4 - frac.length;
|
|
12
|
+
let text;
|
|
13
|
+
if (shift >= 0) {
|
|
14
|
+
text = digits + "0".repeat(shift);
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
const index = digits.length + shift;
|
|
18
|
+
text = index <= 0 ? `0.${"0".repeat(-index)}${digits}` : `${digits.slice(0, index)}.${digits.slice(index)}`;
|
|
19
|
+
}
|
|
20
|
+
if (!text.includes(".")) {
|
|
21
|
+
return text;
|
|
22
|
+
}
|
|
23
|
+
const trimmed = text.replace(/0+$/, "").replace(/\.$/, "");
|
|
24
|
+
return trimmed === "" ? "0" : trimmed;
|
|
25
|
+
}
|
|
26
|
+
export function requireAddress(address) {
|
|
27
|
+
if (!ADDRESS.test(address)) {
|
|
28
|
+
throw new Error("address must be a 0x-prefixed 40 hex character string");
|
|
29
|
+
}
|
|
30
|
+
return address;
|
|
31
|
+
}
|
|
32
|
+
function isRecord(value) {
|
|
33
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
function expectRecord(value, label) {
|
|
36
|
+
if (!isRecord(value)) {
|
|
37
|
+
throw new Error(`${label} must be an object`);
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function expectList(value, label) {
|
|
42
|
+
if (!Array.isArray(value)) {
|
|
43
|
+
throw new Error(`${label} must be a list`);
|
|
44
|
+
}
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
function expectString(value, label) {
|
|
48
|
+
if (typeof value !== "string") {
|
|
49
|
+
throw new Error(`${label} must be a string`);
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
}
|
|
53
|
+
function expectInt(value, label) {
|
|
54
|
+
if (typeof value !== "number" || !Number.isInteger(value)) {
|
|
55
|
+
throw new Error(`${label} must be an integer`);
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
export function messageTime(payload) {
|
|
60
|
+
if (!isRecord(payload)) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const raw = payload.time;
|
|
64
|
+
if (typeof raw !== "number" || !Number.isInteger(raw)) {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
return raw;
|
|
68
|
+
}
|
|
69
|
+
export function makeAge(asOfMs, nowMs) {
|
|
70
|
+
const elapsed = Math.max(0, nowMs - asOfMs);
|
|
71
|
+
return { ageMs: elapsed, stale: elapsed >= STALE_AFTER_MS, asOfMs };
|
|
72
|
+
}
|
|
73
|
+
function aged(payload, nowMs, receivedMs) {
|
|
74
|
+
return makeAge(messageTime(payload) ?? receivedMs, nowMs);
|
|
75
|
+
}
|
|
76
|
+
export function clampDepth(depth) {
|
|
77
|
+
if (depth < 1) {
|
|
78
|
+
throw new Error("depth must be at least 1");
|
|
79
|
+
}
|
|
80
|
+
return Math.min(depth, MAX_BOOK_LEVELS);
|
|
81
|
+
}
|
|
82
|
+
function parseLevel(value) {
|
|
83
|
+
const body = expectRecord(value, "level");
|
|
84
|
+
return {
|
|
85
|
+
px: expectString(body.px, "px"),
|
|
86
|
+
sz: expectString(body.sz, "sz"),
|
|
87
|
+
n: expectInt(body.n, "n"),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
export function parseL2Levels(value, depth) {
|
|
91
|
+
const limit = clampDepth(depth);
|
|
92
|
+
const sides = expectList(value, "levels");
|
|
93
|
+
if (sides.length !== 2) {
|
|
94
|
+
throw new Error("levels must have a bid side and an ask side");
|
|
95
|
+
}
|
|
96
|
+
const bids = expectList(sides[0], "bids").map(parseLevel).slice(0, limit);
|
|
97
|
+
const asks = expectList(sides[1], "asks").map(parseLevel).slice(0, limit);
|
|
98
|
+
return { bids, asks };
|
|
99
|
+
}
|
|
100
|
+
export function markets(client, nowMs, receivedMs = nowMs) {
|
|
101
|
+
const payload = expectRecord(client.post({ type: "meta" }), "meta");
|
|
102
|
+
const rows = expectList(payload.universe, "universe").map((item) => {
|
|
103
|
+
const body = expectRecord(item, "market");
|
|
104
|
+
return {
|
|
105
|
+
name: expectString(body.name, "name"),
|
|
106
|
+
szDecimals: expectInt(body.szDecimals, "szDecimals"),
|
|
107
|
+
maxLeverage: expectInt(body.maxLeverage, "maxLeverage"),
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
return { markets: rows, ...aged(payload, nowMs, receivedMs) };
|
|
111
|
+
}
|
|
112
|
+
export function orderBook(client, coin, nowMs, depth = 20, receivedMs = nowMs) {
|
|
113
|
+
if (coin === "") {
|
|
114
|
+
throw new Error("market is required");
|
|
115
|
+
}
|
|
116
|
+
const payload = expectRecord(client.post({ type: "l2Book", coin }), "l2 book");
|
|
117
|
+
if (payload.coin !== coin) {
|
|
118
|
+
throw new Error("order book coin does not match the request");
|
|
119
|
+
}
|
|
120
|
+
const levels = parseL2Levels(payload.levels, depth);
|
|
121
|
+
return { coin, ...levels, ...aged(payload, nowMs, receivedMs) };
|
|
122
|
+
}
|
|
123
|
+
export function funding(client, coin, nowMs, receivedMs = nowMs) {
|
|
124
|
+
if (coin === "") {
|
|
125
|
+
throw new Error("market is required");
|
|
126
|
+
}
|
|
127
|
+
const payload = client.post({ type: "metaAndAssetCtxs" });
|
|
128
|
+
const sides = expectList(payload, "metaAndAssetCtxs");
|
|
129
|
+
if (sides.length !== 2) {
|
|
130
|
+
throw new Error("metaAndAssetCtxs must contain meta and contexts");
|
|
131
|
+
}
|
|
132
|
+
const meta = expectRecord(sides[0], "meta");
|
|
133
|
+
const contexts = expectList(sides[1], "contexts");
|
|
134
|
+
const universe = expectList(meta.universe, "universe");
|
|
135
|
+
const index = universe.findIndex((item) => expectRecord(item, "market").name === coin);
|
|
136
|
+
if (index < 0) {
|
|
137
|
+
throw new Error("coin is not in the universe");
|
|
138
|
+
}
|
|
139
|
+
if (index >= contexts.length) {
|
|
140
|
+
throw new Error("asset context is missing");
|
|
141
|
+
}
|
|
142
|
+
const ctx = expectRecord(contexts[index], "asset context");
|
|
143
|
+
return {
|
|
144
|
+
coin,
|
|
145
|
+
funding: expectString(ctx.funding, "funding"),
|
|
146
|
+
openInterest: expectString(ctx.openInterest, "openInterest"),
|
|
147
|
+
markPx: expectString(ctx.markPx, "markPx"),
|
|
148
|
+
oraclePx: expectString(ctx.oraclePx, "oraclePx"),
|
|
149
|
+
midPx: expectString(ctx.midPx, "midPx"),
|
|
150
|
+
...aged(payload, nowMs, receivedMs),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
export function positions(client, address, nowMs, receivedMs = nowMs) {
|
|
154
|
+
const user = requireAddress(address);
|
|
155
|
+
const payload = expectRecord(client.post({ type: "clearinghouseState", user }), "clearinghouse state");
|
|
156
|
+
const rows = expectList(payload.assetPositions, "assetPositions").map(parsePosition);
|
|
157
|
+
return { address: user, positions: rows, ...aged(payload, nowMs, receivedMs) };
|
|
158
|
+
}
|
|
159
|
+
export function fees(client, address, nowMs, receivedMs = nowMs) {
|
|
160
|
+
const user = requireAddress(address);
|
|
161
|
+
const payload = expectRecord(client.post({ type: "userFees", user }), "user fees");
|
|
162
|
+
const [takerRate, makerRate] = feeRates(payload);
|
|
163
|
+
return {
|
|
164
|
+
address: user,
|
|
165
|
+
takerRate,
|
|
166
|
+
makerRate,
|
|
167
|
+
takerBps: fractionToBps(takerRate),
|
|
168
|
+
makerBps: fractionToBps(makerRate),
|
|
169
|
+
...aged(payload, nowMs, receivedMs),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function parsePosition(value) {
|
|
173
|
+
const wrapper = expectRecord(value, "asset position");
|
|
174
|
+
if (wrapper.type !== "oneWay") {
|
|
175
|
+
throw new Error("only one-way positions are supported");
|
|
176
|
+
}
|
|
177
|
+
const body = expectRecord(wrapper.position, "position");
|
|
178
|
+
const leverage = expectRecord(body.leverage, "leverage");
|
|
179
|
+
const liquidation = body.liquidationPx;
|
|
180
|
+
return {
|
|
181
|
+
coin: expectString(body.coin, "coin"),
|
|
182
|
+
size: expectString(body.szi, "szi"),
|
|
183
|
+
entryPx: expectString(body.entryPx, "entryPx"),
|
|
184
|
+
liquidationPx: liquidation === null ? null : expectString(liquidation, "liquidationPx"),
|
|
185
|
+
unrealizedPnl: expectString(body.unrealizedPnl, "unrealizedPnl"),
|
|
186
|
+
leverageType: expectString(leverage.type, "leverage type"),
|
|
187
|
+
leverageValue: expectInt(leverage.value, "leverage value"),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function feeRates(payload) {
|
|
191
|
+
if (typeof payload.userCrossRate === "string" && typeof payload.userAddRate === "string") {
|
|
192
|
+
return [payload.userCrossRate, payload.userAddRate];
|
|
193
|
+
}
|
|
194
|
+
const schedule = expectRecord(payload.feeSchedule, "feeSchedule");
|
|
195
|
+
return [expectString(schedule.cross, "cross"), expectString(schedule.add, "add")];
|
|
196
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Process-wide token bucket: 8 requests per second, burst 10. */
|
|
2
|
+
export declare const RATE_PER_SEC = 8;
|
|
3
|
+
export declare const BURST = 10;
|
|
4
|
+
export declare class TokenBucket {
|
|
5
|
+
readonly ratePerSec: number;
|
|
6
|
+
readonly burst: number;
|
|
7
|
+
private milliTokens;
|
|
8
|
+
private updatedMs;
|
|
9
|
+
private readonly clockMs;
|
|
10
|
+
private readonly sleepFn;
|
|
11
|
+
constructor(ratePerSec?: number, burst?: number, clockMs?: () => number, sleepFn?: (durationMs: number) => void);
|
|
12
|
+
acquire(tokens?: number): number;
|
|
13
|
+
private refill;
|
|
14
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Process-wide token bucket: 8 requests per second, burst 10. */
|
|
2
|
+
export const RATE_PER_SEC = 8;
|
|
3
|
+
export const BURST = 10;
|
|
4
|
+
function defaultSleep(durationMs) {
|
|
5
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, durationMs);
|
|
6
|
+
}
|
|
7
|
+
export class TokenBucket {
|
|
8
|
+
ratePerSec;
|
|
9
|
+
burst;
|
|
10
|
+
milliTokens;
|
|
11
|
+
updatedMs;
|
|
12
|
+
clockMs;
|
|
13
|
+
sleepFn;
|
|
14
|
+
constructor(ratePerSec = RATE_PER_SEC, burst = BURST, clockMs = () => Date.now(), sleepFn = defaultSleep) {
|
|
15
|
+
if (ratePerSec < 1 || burst < 1) {
|
|
16
|
+
throw new Error("rate and burst must be positive");
|
|
17
|
+
}
|
|
18
|
+
this.ratePerSec = ratePerSec;
|
|
19
|
+
this.burst = burst;
|
|
20
|
+
this.clockMs = clockMs;
|
|
21
|
+
this.sleepFn = sleepFn;
|
|
22
|
+
this.milliTokens = burst * 1000;
|
|
23
|
+
this.updatedMs = clockMs();
|
|
24
|
+
}
|
|
25
|
+
acquire(tokens = 1) {
|
|
26
|
+
if (tokens < 1 || tokens > this.burst) {
|
|
27
|
+
throw new Error("token count is out of range");
|
|
28
|
+
}
|
|
29
|
+
const needed = tokens * 1000;
|
|
30
|
+
let slept = 0;
|
|
31
|
+
for (;;) {
|
|
32
|
+
this.refill();
|
|
33
|
+
if (this.milliTokens >= needed) {
|
|
34
|
+
this.milliTokens -= needed;
|
|
35
|
+
return slept;
|
|
36
|
+
}
|
|
37
|
+
const deficit = needed - this.milliTokens;
|
|
38
|
+
const wait = Math.ceil(deficit / this.ratePerSec);
|
|
39
|
+
this.sleepFn(wait);
|
|
40
|
+
slept += wait;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
refill() {
|
|
44
|
+
const now = this.clockMs();
|
|
45
|
+
const elapsed = now - this.updatedMs;
|
|
46
|
+
if (elapsed <= 0) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
this.updatedMs = now;
|
|
50
|
+
const added = elapsed * this.ratePerSec;
|
|
51
|
+
this.milliTokens = Math.min(this.burst * 1000, this.milliTokens + added);
|
|
52
|
+
}
|
|
53
|
+
}
|