skewtape 0.0.1 → 0.1.4

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -0
  3. package/dist/cjs/backtest.d.ts +146 -0
  4. package/dist/cjs/backtest.js +410 -0
  5. package/dist/cjs/client.d.ts +255 -0
  6. package/dist/cjs/client.js +447 -0
  7. package/dist/cjs/download.d.ts +33 -0
  8. package/dist/cjs/download.js +160 -0
  9. package/dist/cjs/errors.d.ts +76 -0
  10. package/dist/cjs/errors.js +159 -0
  11. package/dist/cjs/exact.d.ts +36 -0
  12. package/dist/cjs/exact.js +168 -0
  13. package/dist/cjs/fees.d.ts +68 -0
  14. package/dist/cjs/fees.js +196 -0
  15. package/dist/cjs/geoblock.d.ts +48 -0
  16. package/dist/cjs/geoblock.js +78 -0
  17. package/dist/cjs/index.d.ts +31 -0
  18. package/dist/cjs/index.js +98 -0
  19. package/dist/cjs/kalshi.d.ts +261 -0
  20. package/dist/cjs/kalshi.js +416 -0
  21. package/dist/cjs/keccak.d.ts +10 -0
  22. package/dist/cjs/keccak.js +84 -0
  23. package/dist/cjs/msgpack.d.ts +15 -0
  24. package/dist/cjs/msgpack.js +112 -0
  25. package/dist/cjs/package.json +1 -0
  26. package/dist/cjs/paginated.d.ts +26 -0
  27. package/dist/cjs/paginated.js +51 -0
  28. package/dist/cjs/quote-math.d.ts +146 -0
  29. package/dist/cjs/quote-math.js +446 -0
  30. package/dist/cjs/quote.d.ts +108 -0
  31. package/dist/cjs/quote.js +307 -0
  32. package/dist/cjs/route-hyperliquid.d.ts +228 -0
  33. package/dist/cjs/route-hyperliquid.js +387 -0
  34. package/dist/cjs/route.d.ts +297 -0
  35. package/dist/cjs/route.js +516 -0
  36. package/dist/cjs/stream.d.ts +99 -0
  37. package/dist/cjs/stream.js +529 -0
  38. package/dist/cjs/version.d.ts +6 -0
  39. package/dist/cjs/version.js +9 -0
  40. package/dist/esm/backtest.d.ts +146 -0
  41. package/dist/esm/backtest.js +403 -0
  42. package/dist/esm/client.d.ts +255 -0
  43. package/dist/esm/client.js +441 -0
  44. package/dist/esm/download.d.ts +33 -0
  45. package/dist/esm/download.js +155 -0
  46. package/dist/esm/errors.d.ts +76 -0
  47. package/dist/esm/errors.js +142 -0
  48. package/dist/esm/exact.d.ts +36 -0
  49. package/dist/esm/exact.js +158 -0
  50. package/dist/esm/fees.d.ts +68 -0
  51. package/dist/esm/fees.js +185 -0
  52. package/dist/esm/geoblock.d.ts +48 -0
  53. package/dist/esm/geoblock.js +74 -0
  54. package/dist/esm/index.d.ts +31 -0
  55. package/dist/esm/index.js +30 -0
  56. package/dist/esm/kalshi.d.ts +261 -0
  57. package/dist/esm/kalshi.js +404 -0
  58. package/dist/esm/keccak.d.ts +10 -0
  59. package/dist/esm/keccak.js +80 -0
  60. package/dist/esm/msgpack.d.ts +15 -0
  61. package/dist/esm/msgpack.js +109 -0
  62. package/dist/esm/paginated.d.ts +26 -0
  63. package/dist/esm/paginated.js +47 -0
  64. package/dist/esm/quote-math.d.ts +146 -0
  65. package/dist/esm/quote-math.js +437 -0
  66. package/dist/esm/quote.d.ts +108 -0
  67. package/dist/esm/quote.js +297 -0
  68. package/dist/esm/route-hyperliquid.d.ts +228 -0
  69. package/dist/esm/route-hyperliquid.js +376 -0
  70. package/dist/esm/route.d.ts +297 -0
  71. package/dist/esm/route.js +507 -0
  72. package/dist/esm/stream.d.ts +99 -0
  73. package/dist/esm/stream.js +524 -0
  74. package/dist/esm/version.d.ts +6 -0
  75. package/dist/esm/version.js +6 -0
  76. package/package.json +48 -1
  77. package/src/backtest.ts +490 -0
  78. package/src/client.ts +595 -0
  79. package/src/download.ts +161 -0
  80. package/src/errors.ts +143 -0
  81. package/src/exact.ts +159 -0
  82. package/src/fees.ts +189 -0
  83. package/src/generated/schema.d.ts +2500 -0
  84. package/src/geoblock.ts +90 -0
  85. package/src/index.ts +146 -0
  86. package/src/kalshi.ts +563 -0
  87. package/src/keccak.ts +82 -0
  88. package/src/msgpack.ts +83 -0
  89. package/src/paginated.ts +51 -0
  90. package/src/quote-math.ts +555 -0
  91. package/src/quote.ts +324 -0
  92. package/src/route-hyperliquid.ts +457 -0
  93. package/src/route.ts +631 -0
  94. package/src/stream.ts +539 -0
  95. package/src/version.ts +6 -0
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Errors, one class per thing the caller can act on, built from the API's
3
+ * error envelope: {"error": {"code", "message", "docs_url", "request_id",
4
+ * "plan", "resets_at", "upgrade_url", "block_reason_code"}}.
5
+ */
6
+ export interface ErrorFields {
7
+ status?: number | undefined;
8
+ code?: string | undefined;
9
+ docsUrl?: string | undefined;
10
+ requestId?: string | undefined;
11
+ plan?: string | undefined;
12
+ resetsAt?: string | undefined;
13
+ upgradeUrl?: string | undefined;
14
+ blockReasonCode?: string | undefined;
15
+ retryAfter?: number | undefined;
16
+ }
17
+ /** An error from the API or from this client. message is the API's own sentence. */
18
+ export declare class SkewtapeError extends Error {
19
+ readonly status: number | undefined;
20
+ readonly code: string | undefined;
21
+ readonly docsUrl: string | undefined;
22
+ readonly requestId: string | undefined;
23
+ readonly plan: string | undefined;
24
+ readonly resetsAt: string | undefined;
25
+ readonly upgradeUrl: string | undefined;
26
+ readonly blockReasonCode: string | undefined;
27
+ /** The server's Retry-After in seconds, when it sent one. */
28
+ readonly retryAfter: number | undefined;
29
+ constructor(message: string, fields?: ErrorFields);
30
+ toString(): string;
31
+ }
32
+ /** An order route() refuses to build (route.ts, route-hyperliquid.ts). Nothing was signed or sent. */
33
+ export declare class RouteError extends SkewtapeError {
34
+ constructor(message: string);
35
+ }
36
+ /** The client cannot be built: no API key, or a bad option. */
37
+ export declare class ConfigurationError extends SkewtapeError {
38
+ }
39
+ /** 400 invalid_request: a parameter the API refuses. */
40
+ export declare class InvalidRequestError extends SkewtapeError {
41
+ }
42
+ /** 401 unauthorized: no valid API key; or 429 lookup_rate_limited: too many invalid keys from this address, never retried, since the fix is the key. */
43
+ export declare class AuthenticationError extends SkewtapeError {
44
+ }
45
+ /** 403 forbidden_plan: the request needs another plan; .plan names it. */
46
+ export declare class ForbiddenPlanError extends SkewtapeError {
47
+ }
48
+ /** 403 blocked: the data policy withholds the venue's data; .blockReasonCode says why. */
49
+ export declare class BlockedError extends SkewtapeError {
50
+ }
51
+ /** 404 not_found. */
52
+ export declare class NotFoundError extends SkewtapeError {
53
+ }
54
+ /** 429 rate_limited after the retries. */
55
+ export declare class RateLimitError extends SkewtapeError {
56
+ }
57
+ /** 429 quota_exceeded: the plan's monthly quota; .resetsAt says when. */
58
+ export declare class QuotaExceededError extends SkewtapeError {
59
+ }
60
+ /** 5xx: the API failed; retry later, quoting .requestId to support. */
61
+ export declare class ServerError extends SkewtapeError {
62
+ }
63
+ /** A downloaded file's sha256 is not the one expected. */
64
+ export declare class ChecksumError extends SkewtapeError {
65
+ readonly path: string;
66
+ readonly expected: string;
67
+ readonly actual: string;
68
+ constructor(path: string, expected: string, actual: string);
69
+ }
70
+ /** The Retry-After header as seconds, when it is a number. */
71
+ export declare function retryAfterSeconds(headers: Headers): number | undefined;
72
+ /**
73
+ * The error for a non-2xx response: the envelope's code chooses the class, the
74
+ * status decides when the body is not an envelope.
75
+ */
76
+ export declare function errorFromResponse(status: number, headers: Headers, body: unknown): SkewtapeError;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Errors, one class per thing the caller can act on, built from the API's
3
+ * error envelope: {"error": {"code", "message", "docs_url", "request_id",
4
+ * "plan", "resets_at", "upgrade_url", "block_reason_code"}}.
5
+ */
6
+ /** An error from the API or from this client. message is the API's own sentence. */
7
+ export class SkewtapeError extends Error {
8
+ status;
9
+ code;
10
+ docsUrl;
11
+ requestId;
12
+ plan;
13
+ resetsAt;
14
+ upgradeUrl;
15
+ blockReasonCode;
16
+ /** The server's Retry-After in seconds, when it sent one. */
17
+ retryAfter;
18
+ constructor(message, fields = {}) {
19
+ super(message);
20
+ this.name = new.target.name;
21
+ this.status = fields.status;
22
+ this.code = fields.code;
23
+ this.docsUrl = fields.docsUrl;
24
+ this.requestId = fields.requestId;
25
+ this.plan = fields.plan;
26
+ this.resetsAt = fields.resetsAt;
27
+ this.upgradeUrl = fields.upgradeUrl;
28
+ this.blockReasonCode = fields.blockReasonCode;
29
+ this.retryAfter = fields.retryAfter;
30
+ }
31
+ toString() {
32
+ const parts = [this.message];
33
+ if (this.code)
34
+ parts.push(`[${this.code}]`);
35
+ if (this.requestId)
36
+ parts.push(`(request ${this.requestId})`);
37
+ return parts.join(" ");
38
+ }
39
+ }
40
+ /** An order route() refuses to build (route.ts, route-hyperliquid.ts). Nothing was signed or sent. */
41
+ export class RouteError extends SkewtapeError {
42
+ constructor(message) {
43
+ super(message);
44
+ this.name = "RouteError";
45
+ }
46
+ }
47
+ /** The client cannot be built: no API key, or a bad option. */
48
+ export class ConfigurationError extends SkewtapeError {
49
+ }
50
+ /** 400 invalid_request: a parameter the API refuses. */
51
+ export class InvalidRequestError extends SkewtapeError {
52
+ }
53
+ /** 401 unauthorized: no valid API key; or 429 lookup_rate_limited: too many invalid keys from this address, never retried, since the fix is the key. */
54
+ export class AuthenticationError extends SkewtapeError {
55
+ }
56
+ /** 403 forbidden_plan: the request needs another plan; .plan names it. */
57
+ export class ForbiddenPlanError extends SkewtapeError {
58
+ }
59
+ /** 403 blocked: the data policy withholds the venue's data; .blockReasonCode says why. */
60
+ export class BlockedError extends SkewtapeError {
61
+ }
62
+ /** 404 not_found. */
63
+ export class NotFoundError extends SkewtapeError {
64
+ }
65
+ /** 429 rate_limited after the retries. */
66
+ export class RateLimitError extends SkewtapeError {
67
+ }
68
+ /** 429 quota_exceeded: the plan's monthly quota; .resetsAt says when. */
69
+ export class QuotaExceededError extends SkewtapeError {
70
+ }
71
+ /** 5xx: the API failed; retry later, quoting .requestId to support. */
72
+ export class ServerError extends SkewtapeError {
73
+ }
74
+ /** A downloaded file's sha256 is not the one expected. */
75
+ export class ChecksumError extends SkewtapeError {
76
+ path;
77
+ expected;
78
+ actual;
79
+ constructor(path, expected, actual) {
80
+ super(`${path}: sha256 ${actual} is not the expected ${expected}`);
81
+ this.path = path;
82
+ this.expected = expected;
83
+ this.actual = actual;
84
+ }
85
+ }
86
+ const byCode = {
87
+ invalid_request: InvalidRequestError,
88
+ unauthorized: AuthenticationError,
89
+ lookup_rate_limited: AuthenticationError,
90
+ forbidden_plan: ForbiddenPlanError,
91
+ blocked: BlockedError,
92
+ not_found: NotFoundError,
93
+ rate_limited: RateLimitError,
94
+ quota_exceeded: QuotaExceededError,
95
+ };
96
+ /** The Retry-After header as seconds, when it is a number. */
97
+ export function retryAfterSeconds(headers) {
98
+ const raw = headers.get("retry-after");
99
+ if (raw === null)
100
+ return undefined;
101
+ const n = Number(raw);
102
+ return Number.isFinite(n) ? Math.max(n, 0) : undefined;
103
+ }
104
+ function str(v) {
105
+ return typeof v === "string" ? v : undefined;
106
+ }
107
+ /**
108
+ * The error for a non-2xx response: the envelope's code chooses the class, the
109
+ * status decides when the body is not an envelope.
110
+ */
111
+ export function errorFromResponse(status, headers, body) {
112
+ const envelope = body !== null && typeof body === "object" && "error" in body ? body.error : undefined;
113
+ const e = envelope !== null && typeof envelope === "object" ? envelope : {};
114
+ const code = str(e.code);
115
+ const message = str(e.message) ?? `HTTP ${status}${code ? ` ${code}` : ""}`;
116
+ let cls = code ? byCode[code] : undefined;
117
+ if (!cls) {
118
+ if (status === 400)
119
+ cls = InvalidRequestError;
120
+ else if (status === 401)
121
+ cls = AuthenticationError;
122
+ else if (status === 404)
123
+ cls = NotFoundError;
124
+ else if (status === 429)
125
+ cls = RateLimitError;
126
+ else if (status >= 500)
127
+ cls = ServerError;
128
+ else
129
+ cls = SkewtapeError;
130
+ }
131
+ return new cls(message, {
132
+ status,
133
+ code,
134
+ docsUrl: str(e.docs_url),
135
+ requestId: str(e.request_id) ?? headers.get("x-request-id") ?? undefined,
136
+ plan: str(e.plan),
137
+ resetsAt: str(e.resets_at),
138
+ upgradeUrl: str(e.upgrade_url),
139
+ blockReasonCode: str(e.block_reason_code),
140
+ retryAfter: retryAfterSeconds(headers),
141
+ });
142
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Exact numbers for fees and the backtest: fractions of BigInts, times in
3
+ * microseconds since the epoch, and the formats the Python SDK prints, so
4
+ * both SDKs give the same strings for the same values.
5
+ */
6
+ /** An exact fraction, always reduced, with a positive denominator. */
7
+ export declare class Rat {
8
+ readonly n: bigint;
9
+ readonly d: bigint;
10
+ constructor(n: bigint, d?: bigint);
11
+ static of(v: bigint | number): Rat;
12
+ add(o: Rat): Rat;
13
+ mul(o: Rat): Rat;
14
+ cmp(o: Rat): number;
15
+ isInt(): boolean;
16
+ /** The largest integer at or below. */
17
+ floor(): bigint;
18
+ }
19
+ /** floor(x + 1/2): a half rounds toward the larger integer. */
20
+ export declare function roundHalfUp(x: Rat): bigint;
21
+ /** An exact fraction as a decimal string when it ends ("0.58", "-3"), else "n/d". */
22
+ export declare function fractionStr(x: Rat): string;
23
+ /**
24
+ * An exact fraction from a decimal string ("0.40", "1e-7"), an "n/d" string,
25
+ * a bigint or a number (read as its shortest decimal, as String gives it).
26
+ */
27
+ export declare function parseRat(value: unknown, what: string): Rat;
28
+ /** A raw integer amount from a bigint, a safe integer number or a digit string. */
29
+ export declare function parseInt64(value: unknown, what: string): bigint;
30
+ /**
31
+ * A time as microseconds since the epoch, from a Date or an ISO 8601 string
32
+ * (no offset read as UTC); microseconds are kept, which a Date would drop.
33
+ */
34
+ export declare function parseMicros(value: unknown, what: string): bigint;
35
+ /** Microseconds since the epoch as the Python SDK prints a UTC time: seconds, then six digits when there are microseconds, then Z. */
36
+ export declare function isoMicros(micros: bigint): string;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Exact numbers for fees and the backtest: fractions of BigInts, times in
3
+ * microseconds since the epoch, and the formats the Python SDK prints, so
4
+ * both SDKs give the same strings for the same values.
5
+ */
6
+ import { SkewtapeError } from "./errors.js";
7
+ function gcd(a, b) {
8
+ a = a < 0n ? -a : a;
9
+ b = b < 0n ? -b : b;
10
+ while (b)
11
+ [a, b] = [b, a % b];
12
+ return a;
13
+ }
14
+ /** An exact fraction, always reduced, with a positive denominator. */
15
+ export class Rat {
16
+ n;
17
+ d;
18
+ constructor(n, d = 1n) {
19
+ if (d === 0n)
20
+ throw new SkewtapeError("division by zero");
21
+ if (d < 0n) {
22
+ n = -n;
23
+ d = -d;
24
+ }
25
+ const g = gcd(n, d) || 1n;
26
+ this.n = n / g;
27
+ this.d = d / g;
28
+ }
29
+ static of(v) {
30
+ return new Rat(BigInt(v));
31
+ }
32
+ add(o) {
33
+ return new Rat(this.n * o.d + o.n * this.d, this.d * o.d);
34
+ }
35
+ mul(o) {
36
+ return new Rat(this.n * o.n, this.d * o.d);
37
+ }
38
+ cmp(o) {
39
+ const l = this.n * o.d;
40
+ const r = o.n * this.d;
41
+ return l < r ? -1 : l > r ? 1 : 0;
42
+ }
43
+ isInt() {
44
+ return this.d === 1n;
45
+ }
46
+ /** The largest integer at or below. */
47
+ floor() {
48
+ const q = this.n / this.d;
49
+ return this.n < 0n && this.n % this.d !== 0n ? q - 1n : q;
50
+ }
51
+ }
52
+ /** floor(x + 1/2): a half rounds toward the larger integer. */
53
+ export function roundHalfUp(x) {
54
+ return x.add(new Rat(1n, 2n)).floor();
55
+ }
56
+ /** An exact fraction as a decimal string when it ends ("0.58", "-3"), else "n/d". */
57
+ export function fractionStr(x) {
58
+ let den = x.d;
59
+ let twos = 0;
60
+ let fives = 0;
61
+ while (den % 2n === 0n) {
62
+ den /= 2n;
63
+ twos++;
64
+ }
65
+ while (den % 5n === 0n) {
66
+ den /= 5n;
67
+ fives++;
68
+ }
69
+ if (den !== 1n)
70
+ return `${x.n}/${x.d}`;
71
+ const places = Math.max(twos, fives);
72
+ const abs = x.n < 0n ? -x.n : x.n;
73
+ const scaled = abs * (10n ** BigInt(places) / x.d);
74
+ const sign = x.n < 0n ? "-" : "";
75
+ if (places === 0)
76
+ return `${sign}${scaled}`;
77
+ const digits = scaled.toString().padStart(places + 1, "0");
78
+ const whole = digits.slice(0, -places);
79
+ const frac = digits.slice(-places).replace(/0+$/, "");
80
+ return frac ? `${sign}${whole}.${frac}` : `${sign}${whole}`;
81
+ }
82
+ const DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
83
+ const FRACTION = /^([+-]?\d+)\s*\/\s*(\d+)$/;
84
+ /**
85
+ * An exact fraction from a decimal string ("0.40", "1e-7"), an "n/d" string,
86
+ * a bigint or a number (read as its shortest decimal, as String gives it).
87
+ */
88
+ export function parseRat(value, what) {
89
+ if (value instanceof Rat)
90
+ return value;
91
+ if (typeof value === "bigint")
92
+ return new Rat(value);
93
+ if (typeof value === "number") {
94
+ if (!Number.isFinite(value))
95
+ throw new SkewtapeError(`${what}: ${value} is not finite`, { code: "bad_trade" });
96
+ return parseRat(String(value), what);
97
+ }
98
+ if (typeof value !== "string")
99
+ throw new SkewtapeError(`${what}: ${String(value)} is not a number`, { code: "bad_trade" });
100
+ const s = value.trim();
101
+ const f = FRACTION.exec(s);
102
+ if (f)
103
+ return new Rat(BigInt(f[1]), BigInt(f[2]));
104
+ const m = DECIMAL.exec(s);
105
+ if (!m || (m[2] === "" && (m[3] === undefined || m[3] === "")))
106
+ throw new SkewtapeError(`${what}: ${value} is not a number`, { code: "bad_trade" });
107
+ const digits = `${m[2] ?? ""}${m[3] ?? ""}` || "0";
108
+ const exp = Number(m[4] ?? "0") - (m[3]?.length ?? 0);
109
+ let r = exp >= 0 ? new Rat(BigInt(digits) * 10n ** BigInt(exp)) : new Rat(BigInt(digits), 10n ** BigInt(-exp));
110
+ if (m[1] === "-")
111
+ r = new Rat(-r.n, r.d);
112
+ return r;
113
+ }
114
+ /** A raw integer amount from a bigint, a safe integer number or a digit string. */
115
+ export function parseInt64(value, what) {
116
+ if (typeof value === "bigint")
117
+ return value;
118
+ if (typeof value === "number" && Number.isSafeInteger(value))
119
+ return BigInt(value);
120
+ if (typeof value === "string" && /^[+-]?\d+$/.test(value.trim()))
121
+ return BigInt(value.trim());
122
+ throw new SkewtapeError(`${what}: ${String(value)} is not an integer`, { code: "bad_trade" });
123
+ }
124
+ const ISO = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}:?\d{2})?$/i;
125
+ /**
126
+ * A time as microseconds since the epoch, from a Date or an ISO 8601 string
127
+ * (no offset read as UTC); microseconds are kept, which a Date would drop.
128
+ */
129
+ export function parseMicros(value, what) {
130
+ if (value instanceof Date) {
131
+ if (Number.isNaN(value.getTime()))
132
+ throw new SkewtapeError(`${what}: not a time`, { code: "bad_trade" });
133
+ return BigInt(value.getTime()) * 1000n;
134
+ }
135
+ if (typeof value !== "string")
136
+ throw new SkewtapeError(`${what}: ${String(value)} is not a time`, { code: "bad_trade" });
137
+ const m = ISO.exec(value.trim());
138
+ if (!m)
139
+ throw new SkewtapeError(`${what}: ${value} is not a time`, { code: "bad_trade" });
140
+ const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6] ?? "0"));
141
+ const frac = (m[7] ?? "").padEnd(6, "0").slice(0, 6);
142
+ let micros = BigInt(ms) * 1000n + BigInt(frac || "0");
143
+ const zone = m[8];
144
+ if (zone && zone.toUpperCase() !== "Z") {
145
+ const sign = zone.startsWith("-") ? -1n : 1n;
146
+ const digits = zone.slice(1).replace(":", "");
147
+ const minutes = BigInt(Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2, 4)));
148
+ micros -= sign * minutes * 60000000n;
149
+ }
150
+ return micros;
151
+ }
152
+ /** Microseconds since the epoch as the Python SDK prints a UTC time: seconds, then six digits when there are microseconds, then Z. */
153
+ export function isoMicros(micros) {
154
+ const ms = Number(micros / 1000n - (micros < 0n && micros % 1000n !== 0n ? 1n : 0n));
155
+ const base = new Date(ms).toISOString().slice(0, 19);
156
+ const rem = ((micros % 1000000n) + 1000000n) % 1000000n;
157
+ return rem === 0n ? `${base}Z` : `${base}.${rem.toString().padStart(6, "0")}Z`;
158
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Fees from the schedule: the row in force for a fill and the fee it gives,
3
+ * exactly as Skewtape computes them (tape's internal/fees,
4
+ * docs.skewtape.com/fees). The fee is kept as an exact fraction until it is
5
+ * rounded, as the row says, to a step given in millionths of a dollar; a
6
+ * minimum, when the row has one, raises a fee that is above zero after
7
+ * rounding. conformance/fees.json pins every case, and the tests run all of it.
8
+ */
9
+ import { SkewtapeError } from "./errors.js";
10
+ import { Rat } from "./exact.js";
11
+ export declare const COLLATERAL_MICROS_DECIMALS = 6;
12
+ export declare const FALLBACK_CATEGORY = "*";
13
+ /** A fee that cannot be computed: an unknown formula or rounding, a missing parameter, a size out of range. */
14
+ export declare class FeeError extends SkewtapeError {
15
+ }
16
+ /** One row of the fee schedule, read from the API's Fee or the same shape. */
17
+ export interface FeeRow {
18
+ venue: string;
19
+ category: string;
20
+ /** Microseconds since the epoch. */
21
+ effectiveFrom: bigint;
22
+ effectiveTo: bigint | null;
23
+ formula: string;
24
+ rounding: string;
25
+ takerParams: Record<string, bigint>;
26
+ makerRebateParams: Record<string, bigint>;
27
+ minFeeMicros: bigint | null;
28
+ }
29
+ /** What a fee row can be given as: the API's Fee (snake_case) or a FeeRow. */
30
+ export type FeeRowInput = FeeRow | Record<string, unknown>;
31
+ /** A FeeRow from the API's Fee, its JSON, or a FeeRow. */
32
+ export declare function feeRowOf(row: FeeRowInput): FeeRow;
33
+ /** A millionth-of-a-dollar amount in raw units at decimals. */
34
+ export declare function microsToRaw(micros: bigint, decimals: number): bigint;
35
+ /**
36
+ * A fee formula's value for size shares against notional collateral (any one
37
+ * unit for both), exact, before rounding and any minimum: the one port of
38
+ * tape's internal/fees formulas, which takerFeeRaw and sk.quote both use.
39
+ */
40
+ export declare function exactFee(formula: string, params: Record<string, bigint>, size: bigint, notional: bigint): Rat;
41
+ /**
42
+ * The taker fee in raw units for sizeRaw shares against notionalRaw
43
+ * collateral, both at decimals, under row: the formula exactly, rounded to
44
+ * round_step_micros (1 raw unit without one), then raised to min_fee_micros
45
+ * when it is above zero and below it.
46
+ */
47
+ export declare function takerFeeRaw(row: FeeRowInput, sizeRaw: bigint, notionalRaw: bigint, decimals: number): bigint;
48
+ /** A fee's terms alone: what takerFeeOf reads of a row. */
49
+ export type FeeTerms = Pick<FeeRow, "formula" | "rounding" | "takerParams" | "minFeeMicros">;
50
+ /**
51
+ * takerFeeRaw over a fee's terms alone, for callers that hold no whole row:
52
+ * sk.quote computes its fees with it at 6 decimals.
53
+ */
54
+ export declare function takerFeeOf(fee: FeeTerms, sizeRaw: bigint, notionalRaw: bigint, decimals: number): bigint;
55
+ /**
56
+ * The maker's fee on venues that charge makers (maker_fee_rate_micros in
57
+ * maker_rebate_params, quadratic, with the row's rounding and step); zero
58
+ * elsewhere. A rebate share is data about the venue, not a fee, and is not
59
+ * applied.
60
+ */
61
+ export declare function makerFeeRaw(row: FeeRowInput, sizeRaw: bigint, notionalRaw: bigint, decimals: number): bigint;
62
+ /**
63
+ * The row in force for a fill of venue at time at (microseconds, a Date or
64
+ * an ISO string): the market's fee_category if a row has it, else the row
65
+ * with category *; of several, the latest effective_from. Undefined when no
66
+ * row applies.
67
+ */
68
+ export declare function selectFeeRow(rows: Iterable<FeeRowInput>, venue: string, category: string | null | undefined, at: bigint | Date | string): FeeRow | undefined;
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Fees from the schedule: the row in force for a fill and the fee it gives,
3
+ * exactly as Skewtape computes them (tape's internal/fees,
4
+ * docs.skewtape.com/fees). The fee is kept as an exact fraction until it is
5
+ * rounded, as the row says, to a step given in millionths of a dollar; a
6
+ * minimum, when the row has one, raises a fee that is above zero after
7
+ * rounding. conformance/fees.json pins every case, and the tests run all of it.
8
+ */
9
+ import { SkewtapeError } from "./errors.js";
10
+ import { Rat, parseInt64, parseMicros } from "./exact.js";
11
+ export const COLLATERAL_MICROS_DECIMALS = 6;
12
+ export const FALLBACK_CATEGORY = "*";
13
+ const MICROS_PER_UNIT = 1000000n;
14
+ /** A fee that cannot be computed: an unknown formula or rounding, a missing parameter, a size out of range. */
15
+ export class FeeError extends SkewtapeError {
16
+ }
17
+ function intMap(v) {
18
+ if (v === null || v === undefined)
19
+ return {};
20
+ if (typeof v !== "object")
21
+ throw new FeeError(`${String(v)} is not a parameter map`);
22
+ const out = {};
23
+ for (const [k, x] of Object.entries(v))
24
+ out[k] = parseInt64(x, k);
25
+ return out;
26
+ }
27
+ /** A FeeRow from the API's Fee, its JSON, or a FeeRow. */
28
+ export function feeRowOf(row) {
29
+ if ("effectiveFrom" in row && typeof row.effectiveFrom === "bigint")
30
+ return row;
31
+ const r = row;
32
+ if (r.effective_from === undefined || r.effective_from === null)
33
+ throw new FeeError("a fee row needs effective_from");
34
+ const min = r.min_fee_micros;
35
+ return {
36
+ venue: String(r.venue),
37
+ category: String(r.category),
38
+ effectiveFrom: parseMicros(r.effective_from, "effective_from"),
39
+ effectiveTo: r.effective_to === null || r.effective_to === undefined || r.effective_to === "" ? null : parseMicros(r.effective_to, "effective_to"),
40
+ formula: String(r.formula),
41
+ rounding: String(r.rounding),
42
+ takerParams: intMap(r.taker_params),
43
+ makerRebateParams: intMap(r.maker_rebate_params),
44
+ minFeeMicros: min === null || min === undefined || min === "" ? null : parseInt64(min, "min_fee_micros"),
45
+ };
46
+ }
47
+ /** A millionth-of-a-dollar amount in raw units at decimals. */
48
+ export function microsToRaw(micros, decimals) {
49
+ if (decimals < 0 || decimals > 18 || !Number.isInteger(decimals))
50
+ throw new FeeError(`decimals ${decimals} out of range`);
51
+ if (decimals >= COLLATERAL_MICROS_DECIMALS)
52
+ return micros * 10n ** BigInt(decimals - COLLATERAL_MICROS_DECIMALS);
53
+ const factor = 10n ** BigInt(COLLATERAL_MICROS_DECIMALS - decimals);
54
+ if (micros % factor !== 0n)
55
+ throw new FeeError(`${micros} micros is not representable at ${decimals} decimals`);
56
+ return micros / factor;
57
+ }
58
+ /**
59
+ * A fee formula's value for size shares against notional collateral (any one
60
+ * unit for both), exact, before rounding and any minimum: the one port of
61
+ * tape's internal/fees formulas, which takerFeeRaw and sk.quote both use.
62
+ */
63
+ export function exactFee(formula, params, size, notional) {
64
+ switch (formula) {
65
+ case "quadratic": {
66
+ const rate = params.rate_micros;
67
+ if (rate === undefined)
68
+ throw new FeeError("quadratic needs rate_micros");
69
+ if (rate < 0n)
70
+ throw new FeeError("rate_micros must be >= 0");
71
+ if (rate === 0n || notional === 0n || notional === size)
72
+ return new Rat(0n);
73
+ return new Rat(rate * notional * (size - notional), size * MICROS_PER_UNIT);
74
+ }
75
+ case "complement": {
76
+ const rate = params.rate_micros;
77
+ if (rate === undefined)
78
+ throw new FeeError("complement needs rate_micros");
79
+ if (rate < 0n)
80
+ throw new FeeError("rate_micros must be >= 0");
81
+ return new Rat(rate * (size - notional), MICROS_PER_UNIT);
82
+ }
83
+ case "flat_bps": {
84
+ const bps = params.bps;
85
+ if (bps === undefined)
86
+ throw new FeeError("flat_bps needs bps");
87
+ if (bps < 0n)
88
+ throw new FeeError("bps must be >= 0");
89
+ return new Rat(notional * bps, 10000n);
90
+ }
91
+ case "zero":
92
+ return new Rat(0n);
93
+ default:
94
+ throw new FeeError(`unknown formula ${formula}`);
95
+ }
96
+ }
97
+ function roundFee(exact, mode, step) {
98
+ if (exact.n < 0n)
99
+ throw new FeeError("negative fee");
100
+ if (step <= 0n)
101
+ step = 1n;
102
+ if (mode === "none") {
103
+ if (!exact.isInt())
104
+ throw new FeeError("rounding none needs an integer fee");
105
+ return exact.n;
106
+ }
107
+ if (mode !== "down" && mode !== "up" && mode !== "nearest")
108
+ throw new FeeError(`unknown rounding ${mode}`);
109
+ const den = exact.d * step;
110
+ let q = exact.n / den;
111
+ const r = exact.n % den;
112
+ if (mode === "up" && r !== 0n)
113
+ q += 1n;
114
+ else if (mode === "nearest" && 2n * r >= den)
115
+ q += 1n;
116
+ return q * step;
117
+ }
118
+ /**
119
+ * The taker fee in raw units for sizeRaw shares against notionalRaw
120
+ * collateral, both at decimals, under row: the formula exactly, rounded to
121
+ * round_step_micros (1 raw unit without one), then raised to min_fee_micros
122
+ * when it is above zero and below it.
123
+ */
124
+ export function takerFeeRaw(row, sizeRaw, notionalRaw, decimals) {
125
+ return takerFeeOf(feeRowOf(row), sizeRaw, notionalRaw, decimals);
126
+ }
127
+ /**
128
+ * takerFeeRaw over a fee's terms alone, for callers that hold no whole row:
129
+ * sk.quote computes its fees with it at 6 decimals.
130
+ */
131
+ export function takerFeeOf(fee, sizeRaw, notionalRaw, decimals) {
132
+ if (sizeRaw <= 0n)
133
+ throw new FeeError("size_raw must be positive");
134
+ if (notionalRaw < 0n || notionalRaw > sizeRaw)
135
+ throw new FeeError("notional_raw must be between 0 and size_raw");
136
+ const exact = exactFee(fee.formula, fee.takerParams, sizeRaw, notionalRaw);
137
+ const stepMicros = fee.takerParams.round_step_micros ?? 0n;
138
+ let rounded = roundFee(exact, fee.rounding, stepMicros > 0n ? microsToRaw(stepMicros, decimals) : 1n);
139
+ if (fee.minFeeMicros !== null && rounded > 0n) {
140
+ const min = microsToRaw(fee.minFeeMicros, decimals);
141
+ if (rounded < min)
142
+ rounded = min;
143
+ }
144
+ return rounded;
145
+ }
146
+ /**
147
+ * The maker's fee on venues that charge makers (maker_fee_rate_micros in
148
+ * maker_rebate_params, quadratic, with the row's rounding and step); zero
149
+ * elsewhere. A rebate share is data about the venue, not a fee, and is not
150
+ * applied.
151
+ */
152
+ export function makerFeeRaw(row, sizeRaw, notionalRaw, decimals) {
153
+ const r = feeRowOf(row);
154
+ const rate = r.makerRebateParams.maker_fee_rate_micros ?? 0n;
155
+ if (rate === 0n)
156
+ return 0n;
157
+ const params = { rate_micros: rate };
158
+ if (r.takerParams.round_step_micros !== undefined)
159
+ params.round_step_micros = r.takerParams.round_step_micros;
160
+ return takerFeeRaw({ ...r, formula: "quadratic", takerParams: params, makerRebateParams: {} }, sizeRaw, notionalRaw, decimals);
161
+ }
162
+ function inForce(r, at) {
163
+ return r.effectiveFrom <= at && (r.effectiveTo === null || at < r.effectiveTo);
164
+ }
165
+ /**
166
+ * The row in force for a fill of venue at time at (microseconds, a Date or
167
+ * an ISO string): the market's fee_category if a row has it, else the row
168
+ * with category *; of several, the latest effective_from. Undefined when no
169
+ * row applies.
170
+ */
171
+ export function selectFeeRow(rows, venue, category, at) {
172
+ const t = typeof at === "bigint" ? at : parseMicros(at, "at");
173
+ const all = [...rows].map(feeRowOf);
174
+ const wanted = category && category !== FALLBACK_CATEGORY ? [category, FALLBACK_CATEGORY] : [FALLBACK_CATEGORY];
175
+ for (const cat of wanted) {
176
+ let best;
177
+ for (const r of all) {
178
+ if (r.venue === venue && r.category === cat && inForce(r, t) && (best === undefined || r.effectiveFrom > best.effectiveFrom))
179
+ best = r;
180
+ }
181
+ if (best)
182
+ return best;
183
+ }
184
+ return undefined;
185
+ }