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
package/src/kalshi.ts ADDED
@@ -0,0 +1,563 @@
1
+ /**
2
+ * sk.kalshi(): the optional live Kalshi client, under the user's own Kalshi
3
+ * membership (ARCHITECTURE 12, story E3; ADR-0022).
4
+ *
5
+ * It calls Kalshi's Trade API (/trade-api/v2) from the user's machine, read
6
+ * only: markets, one market, trades, the orderbook and candlesticks. It
7
+ * writes nothing to disk and its calls never go to a Skewtape host. It is
8
+ * not how Skewtape delivers Kalshi data: markets, fills, candles and
9
+ * resolutions ship from the API and the bundles under the Kalshi data
10
+ * licence; this client is a reading of the live venue beside them.
11
+ *
12
+ * A key is optional and comes from the options only (accessKey and
13
+ * privateKey, the user's own, from wherever the user keeps it); no
14
+ * environment variable is read. With one (the key id and the PEM private key,
15
+ * Ed25519 or RSA) every request carries the headers Kalshi's docs ask for,
16
+ * the timestamp in milliseconds, the method and the path signed with
17
+ * node:crypto, which puts the calls under the account's own rate-limit tier.
18
+ * Without one the calls are public requests. A 429 is retried with an
19
+ * exponential backoff (Kalshi sends no Retry-After); a request past timeout
20
+ * seconds (30 by default) and any other error is a KalshiError.
21
+ *
22
+ * Prices come back as Kalshi sends them, as dollar strings, and counts as
23
+ * fixed-point strings. Every row keeps the whole JSON object in raw for the
24
+ * fields not named here. Kalshi serves older trades and settled markets from
25
+ * its /historical routes, past a cutoff that moves; this client does not call
26
+ * them, so rows before the cutoff are not here: the history is Skewtape's
27
+ * (sk.fills, sk.markets).
28
+ */
29
+
30
+ import { constants, createPrivateKey, sign as signWith, type KeyObject } from "node:crypto";
31
+
32
+ import { ConfigurationError, SkewtapeError, retryAfterSeconds, type ErrorFields } from "./errors.js";
33
+ import { Paginated, type Page } from "./paginated.js";
34
+ import { VERSION } from "./version.js";
35
+
36
+ /** The production Trade API host Kalshi's docs prefer (api.elections.kalshi.com stays supported; pass baseUrl for it or for the demo host). */
37
+ export const DEFAULT_KALSHI_BASE_URL = "https://external-api.kalshi.com/trade-api/v2";
38
+ /** The matched-event member venues whose market_id is a Kalshi ticker. */
39
+ export const KALSHI_VENUES: ReadonlySet<string> = new Set(["kalshi", "kalshi_dflow"]);
40
+ export type KalshiPeriod = "1m" | "1h" | "1d";
41
+ /** Candlestick sizes, as sk.candles names them, to Kalshi's period_interval minutes. */
42
+ export const PERIODS: Readonly<Record<KalshiPeriod, 1 | 60 | 1440>> = { "1m": 1, "1h": 60, "1d": 1440 };
43
+
44
+ /**
45
+ * An error from Kalshi's API. status is the HTTP status, code and message
46
+ * what Kalshi sent ({"error": {"code", "message", "details"}}, or the flat
47
+ * {"code", "message", "details"} its docs' schema shows), details the detail
48
+ * string when there is one (an authentication error says why there).
49
+ */
50
+ export class KalshiError extends SkewtapeError {
51
+ readonly details: string | undefined;
52
+
53
+ constructor(message: string, fields: ErrorFields & { details?: string | undefined } = {}) {
54
+ super(message, fields);
55
+ this.details = fields.details;
56
+ }
57
+ }
58
+
59
+ function str(v: unknown): string | null {
60
+ return typeof v === "string" ? v : null;
61
+ }
62
+
63
+ function record(v: unknown): Record<string, unknown> {
64
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
65
+ }
66
+
67
+ /** The KalshiError for a non-2xx response, from either error shape. */
68
+ export function kalshiError(status: number, headers: Headers, body: string): KalshiError {
69
+ let parsed: unknown;
70
+ try {
71
+ parsed = body ? JSON.parse(body) : {};
72
+ } catch {
73
+ parsed = undefined;
74
+ }
75
+ const outer = record(parsed);
76
+ const e = "error" in outer && outer.error !== null && typeof outer.error === "object" ? record(outer.error) : outer;
77
+ const code = str(e.code) ?? undefined;
78
+ const message = str(e.message) ?? `Kalshi HTTP ${status}${code ? ` ${code}` : ""}`;
79
+ return new KalshiError(message, { status, code, details: str(e.details) ?? undefined, retryAfter: retryAfterSeconds(headers) });
80
+ }
81
+
82
+ /** A Kalshi RFC 3339 time as a Date, null when absent or odd. */
83
+ function time(v: unknown): Date | null {
84
+ if (typeof v !== "string" || v === "") return null;
85
+ const d = new Date(v);
86
+ return Number.isNaN(d.getTime()) ? null : d;
87
+ }
88
+
89
+ /** A moment as Kalshi's Unix seconds: a Date, an ISO string, or seconds already. */
90
+ function unix(v: Date | number | string): number {
91
+ if (v instanceof Date) return Math.floor(v.getTime() / 1000);
92
+ if (typeof v === "number") return Math.floor(v);
93
+ const d = new Date(v);
94
+ if (Number.isNaN(d.getTime())) throw new ConfigurationError(`${v} is not a time`);
95
+ return Math.floor(d.getTime() / 1000);
96
+ }
97
+
98
+ /**
99
+ * The series ticker a Kalshi market ticker starts with: KXSAMPLE for
100
+ * KXSAMPLE-26NOV05-A. Every market ticker is its event
101
+ * ticker and an outcome, and every event ticker its series ticker and a date
102
+ * or a strike, so the first segment is the series (true of every market in
103
+ * tape's Kalshi recordings, test/fixtures/kalshi); candlesticks takes
104
+ * seriesTicker when a market does not follow the pattern.
105
+ */
106
+ export function seriesTickerOf(ticker: string): string {
107
+ return ticker.split("-", 1)[0] ?? ticker;
108
+ }
109
+
110
+ /** One Kalshi market, as GET /markets lists it; series_ticker is derived from the ticker, raw is the whole row. */
111
+ export interface KalshiMarket {
112
+ ticker: string;
113
+ event_ticker: string | null;
114
+ series_ticker: string;
115
+ market_type: string | null;
116
+ title: string | null;
117
+ yes_sub_title: string | null;
118
+ no_sub_title: string | null;
119
+ status: string | null;
120
+ result: string | null;
121
+ open_time: Date | null;
122
+ close_time: Date | null;
123
+ expiration_time: Date | null;
124
+ yes_bid_dollars: string | null;
125
+ yes_ask_dollars: string | null;
126
+ no_bid_dollars: string | null;
127
+ no_ask_dollars: string | null;
128
+ last_price_dollars: string | null;
129
+ volume_fp: string | null;
130
+ volume_24h_fp: string | null;
131
+ open_interest_fp: string | null;
132
+ raw: Record<string, unknown>;
133
+ }
134
+
135
+ export function marketFromRaw(raw: Record<string, unknown>): KalshiMarket {
136
+ const ticker = str(raw.ticker) ?? "";
137
+ return {
138
+ ticker,
139
+ event_ticker: str(raw.event_ticker),
140
+ series_ticker: seriesTickerOf(ticker),
141
+ market_type: str(raw.market_type),
142
+ title: str(raw.title),
143
+ yes_sub_title: str(raw.yes_sub_title),
144
+ no_sub_title: str(raw.no_sub_title),
145
+ status: str(raw.status),
146
+ result: str(raw.result),
147
+ open_time: time(raw.open_time),
148
+ close_time: time(raw.close_time),
149
+ expiration_time: time(raw.expiration_time),
150
+ yes_bid_dollars: str(raw.yes_bid_dollars),
151
+ yes_ask_dollars: str(raw.yes_ask_dollars),
152
+ no_bid_dollars: str(raw.no_bid_dollars),
153
+ no_ask_dollars: str(raw.no_ask_dollars),
154
+ last_price_dollars: str(raw.last_price_dollars),
155
+ volume_fp: str(raw.volume_fp),
156
+ volume_24h_fp: str(raw.volume_24h_fp),
157
+ open_interest_fp: str(raw.open_interest_fp),
158
+ raw,
159
+ };
160
+ }
161
+
162
+ /** One public trade, as GET /markets/trades lists it: the taker's outcome side and book side, both prices, the count. */
163
+ export interface KalshiTrade {
164
+ trade_id: string;
165
+ ticker: string | null;
166
+ created_time: Date | null;
167
+ count_fp: string | null;
168
+ yes_price_dollars: string | null;
169
+ no_price_dollars: string | null;
170
+ taker_outcome_side: string | null;
171
+ taker_book_side: string | null;
172
+ is_block_trade: boolean;
173
+ raw: Record<string, unknown>;
174
+ }
175
+
176
+ export function tradeFromRaw(raw: Record<string, unknown>): KalshiTrade {
177
+ return {
178
+ trade_id: str(raw.trade_id) ?? "",
179
+ ticker: str(raw.ticker),
180
+ created_time: time(raw.created_time),
181
+ count_fp: str(raw.count_fp),
182
+ yes_price_dollars: str(raw.yes_price_dollars),
183
+ no_price_dollars: str(raw.no_price_dollars),
184
+ taker_outcome_side: str(raw.taker_outcome_side),
185
+ taker_book_side: str(raw.taker_book_side),
186
+ is_block_trade: raw.is_block_trade === true,
187
+ raw,
188
+ };
189
+ }
190
+
191
+ /** One orderbook level: the price in dollars and the contracts at it. */
192
+ export interface KalshiLevel {
193
+ price_dollars: string;
194
+ count_fp: string;
195
+ }
196
+
197
+ /**
198
+ * The resting bids of one market, as GET /markets/{ticker}/orderbook returns
199
+ * them: yes bids and no bids, each ascending by price, so the best bid of a
200
+ * side is its last level (a no bid at p is a yes ask at 1 - p). Kalshi
201
+ * returns no asks and no order counts. A market with no book comes back with
202
+ * two empty sides.
203
+ */
204
+ export interface KalshiOrderbook {
205
+ ticker: string;
206
+ yes: KalshiLevel[];
207
+ no: KalshiLevel[];
208
+ best_yes_bid: KalshiLevel | null;
209
+ best_no_bid: KalshiLevel | null;
210
+ raw: Record<string, unknown>;
211
+ }
212
+
213
+ function levels(rows: unknown): KalshiLevel[] {
214
+ if (!Array.isArray(rows)) return [];
215
+ const out: KalshiLevel[] = [];
216
+ for (const row of rows) {
217
+ if (Array.isArray(row) && row.length === 2 && typeof row[0] === "string" && typeof row[1] === "string") out.push({ price_dollars: row[0], count_fp: row[1] });
218
+ }
219
+ return out;
220
+ }
221
+
222
+ /**
223
+ * The book from Kalshi's reply. A reply without an orderbook_fp object is a
224
+ * shape this client does not know and throws KalshiError, so it is never read
225
+ * as an empty book; an empty or null side is an empty side.
226
+ */
227
+ export function orderbookFromRaw(ticker: string, raw: Record<string, unknown>): KalshiOrderbook {
228
+ const fp = raw.orderbook_fp;
229
+ if (fp === null || typeof fp !== "object" || Array.isArray(fp)) {
230
+ throw new KalshiError(`Kalshi's orderbook reply for ${ticker} has no orderbook_fp object: a shape this client does not know`, { status: 200 });
231
+ }
232
+ const book = record(fp);
233
+ const yes = levels(book.yes_dollars);
234
+ const no = levels(book.no_dollars);
235
+ return { ticker, yes, no, best_yes_bid: yes.at(-1) ?? null, best_no_bid: no.at(-1) ?? null, raw };
236
+ }
237
+
238
+ /** Open, high, low and close in dollars, null where the period had none. */
239
+ export interface KalshiOHLC {
240
+ open_dollars: string | null;
241
+ high_dollars: string | null;
242
+ low_dollars: string | null;
243
+ close_dollars: string | null;
244
+ }
245
+
246
+ function ohlc(raw: unknown): KalshiOHLC {
247
+ const r = record(raw);
248
+ return { open_dollars: str(r.open_dollars), high_dollars: str(r.high_dollars), low_dollars: str(r.low_dollars), close_dollars: str(r.close_dollars) };
249
+ }
250
+
251
+ /**
252
+ * One candlestick: the period it ends (end_period, Kalshi's end_period_ts,
253
+ * inclusive) and starts (both null when Kalshi sends no end), its length in
254
+ * minutes; the trade price's open, high, low and close (null in a period with
255
+ * no trade), its volume and open interest, and the yes bid and yes ask
256
+ * distributions.
257
+ */
258
+ export interface KalshiCandlestick {
259
+ end_period: Date | null;
260
+ start_period: Date | null;
261
+ period_minutes: number;
262
+ price: KalshiOHLC;
263
+ yes_bid: KalshiOHLC;
264
+ yes_ask: KalshiOHLC;
265
+ volume_fp: string | null;
266
+ open_interest_fp: string | null;
267
+ raw: Record<string, unknown>;
268
+ }
269
+
270
+ export function candlestickFromRaw(raw: Record<string, unknown>, periodMinutes: number): KalshiCandlestick {
271
+ const end = typeof raw.end_period_ts === "number" ? new Date(raw.end_period_ts * 1000) : null;
272
+ return {
273
+ end_period: end,
274
+ start_period: end === null ? null : new Date(end.getTime() - periodMinutes * 60_000),
275
+ period_minutes: periodMinutes,
276
+ price: ohlc(raw.price),
277
+ yes_bid: ohlc(raw.yes_bid),
278
+ yes_ask: ohlc(raw.yes_ask),
279
+ volume_fp: str(raw.volume_fp),
280
+ open_interest_fp: str(raw.open_interest_fp),
281
+ raw,
282
+ };
283
+ }
284
+
285
+ /**
286
+ * Signs a request as Kalshi's docs say: the timestamp in milliseconds, the
287
+ * method and the path (from /trade-api/v2, no query string), with Ed25519 or
288
+ * RSA-PSS SHA-256 (MGF1 SHA-256, the salt the digest's length), base64, in
289
+ * KALSHI-ACCESS-KEY, KALSHI-ACCESS-SIGNATURE and KALSHI-ACCESS-TIMESTAMP.
290
+ */
291
+ class Signer {
292
+ private readonly signMessage: (message: Buffer) => Buffer;
293
+
294
+ constructor(
295
+ readonly accessKey: string,
296
+ pem: string,
297
+ ) {
298
+ let key: KeyObject;
299
+ try {
300
+ key = createPrivateKey(pem);
301
+ } catch (err) {
302
+ throw new ConfigurationError(`the Kalshi private key is not a PEM private key: ${(err as Error).message}`);
303
+ }
304
+ if (key.asymmetricKeyType === "ed25519") {
305
+ this.signMessage = (message) => signWith(null, message, key);
306
+ } else if (key.asymmetricKeyType === "rsa") {
307
+ this.signMessage = (message) => signWith("sha256", message, { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST });
308
+ } else {
309
+ throw new ConfigurationError(`the Kalshi private key is ${key.asymmetricKeyType ?? "unknown"}; Kalshi keys are Ed25519 or RSA`);
310
+ }
311
+ }
312
+
313
+ headers(method: string, path: string, timestampMs: number): Record<string, string> {
314
+ const signature = this.signMessage(Buffer.from(`${timestampMs}${method}${path}`));
315
+ return { "KALSHI-ACCESS-KEY": this.accessKey, "KALSHI-ACCESS-SIGNATURE": signature.toString("base64"), "KALSHI-ACCESS-TIMESTAMP": String(timestampMs) };
316
+ }
317
+ }
318
+
319
+ /** What the join helpers read of a matched event: sk.events.get's MatchedEvent fits. */
320
+ export interface KalshiEventLike {
321
+ members: ReadonlyArray<{ venue: string; market_id: string; status: string }>;
322
+ }
323
+
324
+ /**
325
+ * The Kalshi tickers of a matched event: the market_id of its members on
326
+ * kalshi and kalshi_dflow (both use the ticker as the id), active ones unless
327
+ * includeInactive, in member order, each once.
328
+ */
329
+ export function kalshiTickers(event: KalshiEventLike, includeInactive = false): string[] {
330
+ const out: string[] = [];
331
+ for (const m of event.members) {
332
+ if (KALSHI_VENUES.has(m.venue) && m.market_id && (includeInactive || m.status === "active") && !out.includes(m.market_id)) out.push(m.market_id);
333
+ }
334
+ return out;
335
+ }
336
+
337
+ export interface KalshiOptions {
338
+ /** The user's own key id; with privateKey, every request is signed. Never read from the environment. */
339
+ accessKey?: string;
340
+ /** The user's own PEM private key (Ed25519 or RSA). */
341
+ privateKey?: string;
342
+ baseUrl?: string;
343
+ /** How many times a 429 is retried, with a backoff of 0.5, 1 and 2 seconds. Three by default. */
344
+ maxRetries?: number;
345
+ /** How long one request may take, in seconds; 30 by default. A request past it throws a KalshiError. */
346
+ timeout?: number;
347
+ /** The fetch to use; the global one by default. */
348
+ fetch?: typeof fetch;
349
+ /** How to wait, in seconds; a timer by default. Tests inject their own. */
350
+ sleep?: (seconds: number) => Promise<void>;
351
+ /** The clock, in milliseconds since the epoch; Date.now by default. */
352
+ now?: () => number;
353
+ }
354
+
355
+ export interface KalshiMarketsOptions {
356
+ /** open, closed, settled or unopened. */
357
+ status?: string;
358
+ seriesTicker?: string;
359
+ eventTicker?: string;
360
+ /** A list of tickers, in one request. */
361
+ tickers?: string[];
362
+ /** false (the default) leaves the multivariate collections out, as the Skewtape data does; true lists only them; null lists both. */
363
+ multivariate?: boolean | null;
364
+ limit?: number;
365
+ }
366
+
367
+ export interface KalshiTradesOptions {
368
+ ticker?: string;
369
+ /** A Date, an ISO string or Unix seconds. */
370
+ since?: Date | number | string;
371
+ until?: Date | number | string;
372
+ /** true keeps block trades only, false leaves them out; left out, all. */
373
+ blockTrades?: boolean;
374
+ limit?: number;
375
+ }
376
+
377
+ export interface KalshiCandlesticksOptions {
378
+ since: Date | number | string;
379
+ /** Now by default. */
380
+ until?: Date | number | string;
381
+ /** 1m, 1h or 1d (as sk.candles names them), or Kalshi's 1, 60 or 1440 minutes; 1h by default. */
382
+ period?: KalshiPeriod | 1 | 60 | 1440;
383
+ /** The series, derived from the ticker when left out. */
384
+ seriesTicker?: string;
385
+ }
386
+
387
+ function defaultSleep(seconds: number): Promise<void> {
388
+ return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
389
+ }
390
+
391
+ /**
392
+ * The live Kalshi client. Build it as sk.kalshi(...) or on its own:
393
+ *
394
+ * const kalshi = sk.kalshi(); // public requests
395
+ * const kalshi = sk.kalshi({ accessKey: keyId, privateKey: pem }); // the user's own key
396
+ * for await (const market of kalshi.markets({ status: "open", seriesTicker: "KXSAMPLE" })) ...
397
+ *
398
+ * The key id and the private key come from the options only, never from the
399
+ * environment, and one without the other is refused.
400
+ */
401
+ export class Kalshi {
402
+ readonly baseUrl: string;
403
+ readonly maxRetries: number;
404
+ readonly timeout: number;
405
+ /** Whether the calls are signed with a key. */
406
+ readonly authenticated: boolean;
407
+ private readonly pathPrefix: string;
408
+ private readonly signer: Signer | undefined;
409
+ private readonly fetchImpl: typeof fetch;
410
+ private readonly sleep: (seconds: number) => Promise<void>;
411
+ private readonly now: () => number;
412
+
413
+ constructor(options: KalshiOptions = {}) {
414
+ const accessKey = options.accessKey || undefined;
415
+ const privateKey = options.privateKey || undefined;
416
+ if ((accessKey === undefined) !== (privateKey === undefined)) {
417
+ throw new ConfigurationError("a Kalshi key is the key id and the private key together: pass accessKey and privateKey");
418
+ }
419
+ if (options.maxRetries !== undefined && options.maxRetries < 0) throw new ConfigurationError("maxRetries must not be negative");
420
+ if (options.timeout !== undefined && !(options.timeout > 0)) throw new ConfigurationError("timeout is seconds, above zero");
421
+ this.timeout = options.timeout ?? 30;
422
+ this.baseUrl = (options.baseUrl ?? DEFAULT_KALSHI_BASE_URL).replace(/\/+$/, "");
423
+ this.pathPrefix = new URL(this.baseUrl).pathname.replace(/\/+$/, "");
424
+ this.signer = accessKey !== undefined && privateKey !== undefined ? new Signer(accessKey, privateKey) : undefined;
425
+ this.authenticated = this.signer !== undefined;
426
+ this.maxRetries = options.maxRetries ?? 3;
427
+ this.fetchImpl = options.fetch ?? fetch;
428
+ this.sleep = options.sleep ?? defaultSleep;
429
+ this.now = options.now ?? Date.now;
430
+ }
431
+
432
+ private async get(path: string, query: Record<string, string | number | undefined> = {}): Promise<unknown> {
433
+ const url = new URL(this.baseUrl + path);
434
+ for (const [k, v] of Object.entries(query)) if (v !== undefined) url.searchParams.set(k, String(v));
435
+ for (let attempt = 0; ; attempt++) {
436
+ const headers: Record<string, string> = { Accept: "application/json", "User-Agent": `skewtape-ts/${VERSION}` };
437
+ if (this.signer) Object.assign(headers, this.signer.headers("GET", this.pathPrefix + path, this.now()));
438
+ let response: Response;
439
+ try {
440
+ // The timeout covers the whole request, the body read included. A
441
+ // redirect is not followed, as Python's client follows none: a 3xx is
442
+ // a KalshiError naming its status.
443
+ response = await this.fetchImpl(url.toString(), { method: "GET", redirect: "manual", headers, signal: AbortSignal.timeout(this.timeout * 1000) });
444
+ } catch (err) {
445
+ throw this.timedOut(err);
446
+ }
447
+ // A browser's fetch hides a manual redirect's status: say what it was.
448
+ if (response.type === "opaqueredirect") throw new KalshiError("Kalshi answered with a redirect, which this client does not follow", { status: response.status });
449
+ if (response.status === 429 && attempt < this.maxRetries) {
450
+ // The body is not read; cancelling it frees the connection.
451
+ await response.body?.cancel();
452
+ await this.sleep(retryAfterSeconds(response.headers) ?? 0.5 * 2 ** attempt);
453
+ continue;
454
+ }
455
+ let body: string;
456
+ try {
457
+ body = await response.text();
458
+ } catch (err) {
459
+ throw this.timedOut(err);
460
+ }
461
+ if (response.ok) {
462
+ try {
463
+ return JSON.parse(body) as unknown;
464
+ } catch {
465
+ throw new KalshiError("Kalshi sent a body that is not JSON", { status: response.status });
466
+ }
467
+ }
468
+ throw kalshiError(response.status, response.headers, body);
469
+ }
470
+ }
471
+
472
+ /** A timeout or abort, while the request or its body is read, as the KalshiError naming the seconds; anything else as it came. */
473
+ private timedOut(err: unknown): unknown {
474
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) return new KalshiError(`the Kalshi request took longer than ${this.timeout} s`);
475
+ return err;
476
+ }
477
+
478
+ /** GET /markets: by status, series, event or tickers, the multivariate collections left out unless asked for. Settled markets past Kalshi's historical cutoff are not listed here; sk.markets has them. */
479
+ markets(options: KalshiMarketsOptions = {}): Paginated<KalshiMarket> {
480
+ const mve = options.multivariate === null ? undefined : options.multivariate ? "only" : "exclude";
481
+ return new Paginated(async (cursor): Promise<Page<KalshiMarket>> => {
482
+ const body = record(
483
+ await this.get("/markets", {
484
+ limit: options.limit ?? 100,
485
+ cursor,
486
+ status: options.status,
487
+ series_ticker: options.seriesTicker,
488
+ event_ticker: options.eventTicker,
489
+ tickers: options.tickers?.length ? options.tickers.join(",") : undefined,
490
+ mve_filter: mve,
491
+ }),
492
+ );
493
+ const rows = Array.isArray(body.markets) ? body.markets : [];
494
+ return { items: rows.map((m) => marketFromRaw(record(m))), nextCursor: str(body.cursor) || null };
495
+ });
496
+ }
497
+
498
+ /** GET /markets/{ticker}: one market. */
499
+ async market(ticker: string): Promise<KalshiMarket> {
500
+ const body = record(await this.get(`/markets/${encodeURIComponent(ticker)}`));
501
+ if (body.market === null || typeof body.market !== "object") throw new KalshiError(`Kalshi sent no market for ${ticker}`, { status: 200 });
502
+ return marketFromRaw(record(body.market));
503
+ }
504
+
505
+ /** GET /markets/trades: public trades of one market or of all, from since to until, in Kalshi's order (newest first). Trades older than Kalshi's historical cutoff are not here; sk.fills has them. */
506
+ trades(options: KalshiTradesOptions = {}): Paginated<KalshiTrade> {
507
+ return new Paginated(async (cursor): Promise<Page<KalshiTrade>> => {
508
+ const body = record(
509
+ await this.get("/markets/trades", {
510
+ limit: options.limit ?? 100,
511
+ cursor,
512
+ ticker: options.ticker,
513
+ min_ts: options.since === undefined ? undefined : unix(options.since),
514
+ max_ts: options.until === undefined ? undefined : unix(options.until),
515
+ is_block_trade: options.blockTrades === undefined ? undefined : String(options.blockTrades),
516
+ }),
517
+ );
518
+ const rows = Array.isArray(body.trades) ? body.trades : [];
519
+ return { items: rows.map((t) => tradeFromRaw(record(t))), nextCursor: str(body.cursor) || null };
520
+ });
521
+ }
522
+
523
+ /** GET /markets/{ticker}/orderbook: the resting bids of one market, every level or the best depth levels of each side (1 to 100). */
524
+ async orderbook(ticker: string, options: { depth?: number } = {}): Promise<KalshiOrderbook> {
525
+ const body = record(await this.get(`/markets/${encodeURIComponent(ticker)}/orderbook`, { depth: options.depth }));
526
+ return orderbookFromRaw(ticker, body);
527
+ }
528
+
529
+ /**
530
+ * GET /series/{series}/markets/{ticker}/candlesticks: the sticks of one size
531
+ * ending from since to until (now by default). Kalshi serves at most 5,000
532
+ * periods a request and a 1d stick is a New York day.
533
+ */
534
+ async candlesticks(ticker: string, options: KalshiCandlesticksOptions): Promise<KalshiCandlestick[]> {
535
+ const period = options.period ?? "1h";
536
+ const minutes = typeof period === "string" ? PERIODS[period] : period;
537
+ if (minutes !== 1 && minutes !== 60 && minutes !== 1440) throw new ConfigurationError(`period is 1m, 1h or 1d (or 1, 60 or 1440 minutes), not ${String(period)}`);
538
+ const series = options.seriesTicker ?? seriesTickerOf(ticker);
539
+ const body = record(
540
+ await this.get(`/series/${encodeURIComponent(series)}/markets/${encodeURIComponent(ticker)}/candlesticks`, {
541
+ start_ts: unix(options.since),
542
+ end_ts: options.until === undefined ? Math.floor(this.now() / 1000) : unix(options.until),
543
+ period_interval: minutes,
544
+ }),
545
+ );
546
+ const rows = Array.isArray(body.candlesticks) ? body.candlesticks : [];
547
+ return rows.map((s) => candlestickFromRaw(record(s), minutes));
548
+ }
549
+
550
+ /** The Kalshi tickers of a Skewtape matched event: the market_id of its kalshi and kalshi_dflow members, active ones unless includeInactive. */
551
+ tickers(event: KalshiEventLike, options: { includeInactive?: boolean } = {}): string[] {
552
+ return kalshiTickers(event, options.includeInactive ?? false);
553
+ }
554
+
555
+ /** The live Kalshi markets of a matched event, one request (GET /markets?tickers=), in the members' order; none for an event with no Kalshi member. */
556
+ async marketsFor(event: KalshiEventLike, options: { includeInactive?: boolean } = {}): Promise<KalshiMarket[]> {
557
+ const wanted = this.tickers(event, options);
558
+ if (wanted.length === 0) return [];
559
+ const byTicker = new Map<string, KalshiMarket>();
560
+ for await (const m of this.markets({ tickers: wanted })) byTicker.set(m.ticker, m);
561
+ return wanted.flatMap((t) => byTicker.get(t) ?? []);
562
+ }
563
+ }
package/src/keccak.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Keccak-256, the hash Ethereum and Hyperliquid's signing use: the original
3
+ * Keccak padding (0x01), not SHA3-256's (0x06). Written here so the package
4
+ * adds no runtime dependency; the inputs it hashes (one order action) are
5
+ * small, so 64-bit lanes as BigInt are fast enough.
6
+ */
7
+
8
+ const MASK = (1n << 64n) - 1n;
9
+ const RATE = 136; // bytes: 1600 - 2 * 256 bits
10
+
11
+ const ROUND_CONSTANTS: readonly bigint[] = [
12
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
13
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
14
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
15
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
16
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
17
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n,
18
+ ];
19
+
20
+ /** ROTATIONS[x][y] is lane (x, y)'s rotation in rho. */
21
+ const ROTATIONS: readonly (readonly number[])[] = [
22
+ [0, 36, 3, 41, 18],
23
+ [1, 44, 10, 45, 2],
24
+ [62, 6, 43, 15, 61],
25
+ [28, 55, 25, 21, 56],
26
+ [27, 20, 39, 8, 14],
27
+ ];
28
+
29
+ const rotl = (v: bigint, n: number): bigint => (n === 0 ? v : ((v << BigInt(n)) | (v >> BigInt(64 - n))) & MASK);
30
+
31
+ /** Keccak-f[1600] on 25 lanes, lane (x, y) at index x + 5y. */
32
+ function permute(a: bigint[]): void {
33
+ for (const rc of ROUND_CONSTANTS) {
34
+ const c: bigint[] = [];
35
+ for (let x = 0; x < 5; x++) c.push(a[x]! ^ a[x + 5]! ^ a[x + 10]! ^ a[x + 15]! ^ a[x + 20]!);
36
+ for (let i = 0; i < 25; i++) a[i] = a[i]! ^ c[(i % 5 + 4) % 5]! ^ rotl(c[(i % 5 + 1) % 5]!, 1);
37
+ const b: bigint[] = new Array<bigint>(25).fill(0n);
38
+ for (let x = 0; x < 5; x++) {
39
+ for (let y = 0; y < 5; y++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(a[x + 5 * y]!, ROTATIONS[x]![y]!);
40
+ }
41
+ for (let y = 0; y < 5; y++) {
42
+ for (let x = 0; x < 5; x++) {
43
+ a[x + 5 * y] = b[x + 5 * y]! ^ (~b[((x + 1) % 5) + 5 * y]! & MASK & b[((x + 2) % 5) + 5 * y]!);
44
+ }
45
+ }
46
+ a[0] = a[0]! ^ rc;
47
+ }
48
+ }
49
+
50
+ /** The 32-byte Keccak-256 digest of data. */
51
+ export function keccak256(data: Uint8Array): Uint8Array {
52
+ const padLen = RATE - ((data.length + 1) % RATE || RATE) + 1;
53
+ const padded = new Uint8Array(data.length + padLen);
54
+ padded.set(data);
55
+ padded[data.length] = 0x01;
56
+ padded[padded.length - 1]! |= 0x80;
57
+ const state: bigint[] = new Array<bigint>(25).fill(0n);
58
+ for (let off = 0; off < padded.length; off += RATE) {
59
+ for (let i = 0; i < RATE / 8; i++) {
60
+ let lane = 0n;
61
+ for (let j = 7; j >= 0; j--) lane = (lane << 8n) | BigInt(padded[off + 8 * i + j]!);
62
+ state[i] = state[i]! ^ lane;
63
+ }
64
+ permute(state);
65
+ }
66
+ const out = new Uint8Array(32);
67
+ for (let i = 0; i < 4; i++) {
68
+ let lane = state[i]!;
69
+ for (let j = 0; j < 8; j++) {
70
+ out[8 * i + j] = Number(lane & 0xffn);
71
+ lane >>= 8n;
72
+ }
73
+ }
74
+ return out;
75
+ }
76
+
77
+ /** Hex with 0x, the shape viem and ethers take. */
78
+ export function toHex(bytes: Uint8Array): `0x${string}` {
79
+ let s = "0x";
80
+ for (const b of bytes) s += b.toString(16).padStart(2, "0");
81
+ return s as `0x${string}`;
82
+ }