skewtape 0.0.1 → 0.1.5
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 +182 -0
- package/dist/cjs/backtest.d.ts +146 -0
- package/dist/cjs/backtest.js +410 -0
- package/dist/cjs/client.d.ts +255 -0
- package/dist/cjs/client.js +447 -0
- package/dist/cjs/download.d.ts +33 -0
- package/dist/cjs/download.js +160 -0
- package/dist/cjs/errors.d.ts +76 -0
- package/dist/cjs/errors.js +159 -0
- package/dist/cjs/exact.d.ts +36 -0
- package/dist/cjs/exact.js +168 -0
- package/dist/cjs/fees.d.ts +68 -0
- package/dist/cjs/fees.js +196 -0
- package/dist/cjs/geoblock.d.ts +48 -0
- package/dist/cjs/geoblock.js +78 -0
- package/dist/cjs/index.d.ts +31 -0
- package/dist/cjs/index.js +98 -0
- package/dist/cjs/kalshi.d.ts +261 -0
- package/dist/cjs/kalshi.js +416 -0
- package/dist/cjs/keccak.d.ts +10 -0
- package/dist/cjs/keccak.js +84 -0
- package/dist/cjs/msgpack.d.ts +15 -0
- package/dist/cjs/msgpack.js +112 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/paginated.d.ts +26 -0
- package/dist/cjs/paginated.js +51 -0
- package/dist/cjs/quote-math.d.ts +146 -0
- package/dist/cjs/quote-math.js +446 -0
- package/dist/cjs/quote.d.ts +108 -0
- package/dist/cjs/quote.js +307 -0
- package/dist/cjs/route-hyperliquid.d.ts +228 -0
- package/dist/cjs/route-hyperliquid.js +387 -0
- package/dist/cjs/route.d.ts +297 -0
- package/dist/cjs/route.js +516 -0
- package/dist/cjs/stream.d.ts +99 -0
- package/dist/cjs/stream.js +529 -0
- package/dist/cjs/version.d.ts +6 -0
- package/dist/cjs/version.js +9 -0
- package/dist/esm/backtest.d.ts +146 -0
- package/dist/esm/backtest.js +403 -0
- package/dist/esm/client.d.ts +255 -0
- package/dist/esm/client.js +441 -0
- package/dist/esm/download.d.ts +33 -0
- package/dist/esm/download.js +155 -0
- package/dist/esm/errors.d.ts +76 -0
- package/dist/esm/errors.js +142 -0
- package/dist/esm/exact.d.ts +36 -0
- package/dist/esm/exact.js +158 -0
- package/dist/esm/fees.d.ts +68 -0
- package/dist/esm/fees.js +185 -0
- package/dist/esm/geoblock.d.ts +48 -0
- package/dist/esm/geoblock.js +74 -0
- package/dist/esm/index.d.ts +31 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/kalshi.d.ts +261 -0
- package/dist/esm/kalshi.js +404 -0
- package/dist/esm/keccak.d.ts +10 -0
- package/dist/esm/keccak.js +80 -0
- package/dist/esm/msgpack.d.ts +15 -0
- package/dist/esm/msgpack.js +109 -0
- package/dist/esm/paginated.d.ts +26 -0
- package/dist/esm/paginated.js +47 -0
- package/dist/esm/quote-math.d.ts +146 -0
- package/dist/esm/quote-math.js +437 -0
- package/dist/esm/quote.d.ts +108 -0
- package/dist/esm/quote.js +297 -0
- package/dist/esm/route-hyperliquid.d.ts +228 -0
- package/dist/esm/route-hyperliquid.js +376 -0
- package/dist/esm/route.d.ts +297 -0
- package/dist/esm/route.js +507 -0
- package/dist/esm/stream.d.ts +99 -0
- package/dist/esm/stream.js +524 -0
- package/dist/esm/version.d.ts +6 -0
- package/dist/esm/version.js +6 -0
- package/package.json +48 -1
- package/src/backtest.ts +490 -0
- package/src/client.ts +595 -0
- package/src/download.ts +161 -0
- package/src/errors.ts +143 -0
- package/src/exact.ts +159 -0
- package/src/fees.ts +189 -0
- package/src/generated/schema.d.ts +2500 -0
- package/src/geoblock.ts +90 -0
- package/src/index.ts +146 -0
- package/src/kalshi.ts +563 -0
- package/src/keccak.ts +82 -0
- package/src/msgpack.ts +83 -0
- package/src/paginated.ts +51 -0
- package/src/quote-math.ts +555 -0
- package/src/quote.ts +324 -0
- package/src/route-hyperliquid.ts +457 -0
- package/src/route.ts +631 -0
- package/src/stream.ts +539 -0
- package/src/version.ts +6 -0
|
@@ -0,0 +1,404 @@
|
|
|
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
|
+
import { constants, createPrivateKey, sign as signWith } from "node:crypto";
|
|
30
|
+
import { ConfigurationError, SkewtapeError, retryAfterSeconds } from "./errors.js";
|
|
31
|
+
import { Paginated } from "./paginated.js";
|
|
32
|
+
import { VERSION } from "./version.js";
|
|
33
|
+
/** The production Trade API host Kalshi's docs prefer (api.elections.kalshi.com stays supported; pass baseUrl for it or for the demo host). */
|
|
34
|
+
export const DEFAULT_KALSHI_BASE_URL = "https://external-api.kalshi.com/trade-api/v2";
|
|
35
|
+
/** The matched-event member venues whose market_id is a Kalshi ticker. */
|
|
36
|
+
export const KALSHI_VENUES = new Set(["kalshi", "kalshi_dflow"]);
|
|
37
|
+
/** Candlestick sizes, as sk.candles names them, to Kalshi's period_interval minutes. */
|
|
38
|
+
export const PERIODS = { "1m": 1, "1h": 60, "1d": 1440 };
|
|
39
|
+
/**
|
|
40
|
+
* An error from Kalshi's API. status is the HTTP status, code and message
|
|
41
|
+
* what Kalshi sent ({"error": {"code", "message", "details"}}, or the flat
|
|
42
|
+
* {"code", "message", "details"} its docs' schema shows), details the detail
|
|
43
|
+
* string when there is one (an authentication error says why there).
|
|
44
|
+
*/
|
|
45
|
+
export class KalshiError extends SkewtapeError {
|
|
46
|
+
details;
|
|
47
|
+
constructor(message, fields = {}) {
|
|
48
|
+
super(message, fields);
|
|
49
|
+
this.details = fields.details;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function str(v) {
|
|
53
|
+
return typeof v === "string" ? v : null;
|
|
54
|
+
}
|
|
55
|
+
function record(v) {
|
|
56
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
57
|
+
}
|
|
58
|
+
/** The KalshiError for a non-2xx response, from either error shape. */
|
|
59
|
+
export function kalshiError(status, headers, body) {
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = body ? JSON.parse(body) : {};
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
parsed = undefined;
|
|
66
|
+
}
|
|
67
|
+
const outer = record(parsed);
|
|
68
|
+
const e = "error" in outer && outer.error !== null && typeof outer.error === "object" ? record(outer.error) : outer;
|
|
69
|
+
const code = str(e.code) ?? undefined;
|
|
70
|
+
const message = str(e.message) ?? `Kalshi HTTP ${status}${code ? ` ${code}` : ""}`;
|
|
71
|
+
return new KalshiError(message, { status, code, details: str(e.details) ?? undefined, retryAfter: retryAfterSeconds(headers) });
|
|
72
|
+
}
|
|
73
|
+
/** A Kalshi RFC 3339 time as a Date, null when absent or odd. */
|
|
74
|
+
function time(v) {
|
|
75
|
+
if (typeof v !== "string" || v === "")
|
|
76
|
+
return null;
|
|
77
|
+
const d = new Date(v);
|
|
78
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
79
|
+
}
|
|
80
|
+
/** A moment as Kalshi's Unix seconds: a Date, an ISO string, or seconds already. */
|
|
81
|
+
function unix(v) {
|
|
82
|
+
if (v instanceof Date)
|
|
83
|
+
return Math.floor(v.getTime() / 1000);
|
|
84
|
+
if (typeof v === "number")
|
|
85
|
+
return Math.floor(v);
|
|
86
|
+
const d = new Date(v);
|
|
87
|
+
if (Number.isNaN(d.getTime()))
|
|
88
|
+
throw new ConfigurationError(`${v} is not a time`);
|
|
89
|
+
return Math.floor(d.getTime() / 1000);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The series ticker a Kalshi market ticker starts with: KXSAMPLE for
|
|
93
|
+
* KXSAMPLE-26NOV05-A. Every market ticker is its event
|
|
94
|
+
* ticker and an outcome, and every event ticker its series ticker and a date
|
|
95
|
+
* or a strike, so the first segment is the series (true of every market in
|
|
96
|
+
* tape's Kalshi recordings, test/fixtures/kalshi); candlesticks takes
|
|
97
|
+
* seriesTicker when a market does not follow the pattern.
|
|
98
|
+
*/
|
|
99
|
+
export function seriesTickerOf(ticker) {
|
|
100
|
+
return ticker.split("-", 1)[0] ?? ticker;
|
|
101
|
+
}
|
|
102
|
+
export function marketFromRaw(raw) {
|
|
103
|
+
const ticker = str(raw.ticker) ?? "";
|
|
104
|
+
return {
|
|
105
|
+
ticker,
|
|
106
|
+
event_ticker: str(raw.event_ticker),
|
|
107
|
+
series_ticker: seriesTickerOf(ticker),
|
|
108
|
+
market_type: str(raw.market_type),
|
|
109
|
+
title: str(raw.title),
|
|
110
|
+
yes_sub_title: str(raw.yes_sub_title),
|
|
111
|
+
no_sub_title: str(raw.no_sub_title),
|
|
112
|
+
status: str(raw.status),
|
|
113
|
+
result: str(raw.result),
|
|
114
|
+
open_time: time(raw.open_time),
|
|
115
|
+
close_time: time(raw.close_time),
|
|
116
|
+
expiration_time: time(raw.expiration_time),
|
|
117
|
+
yes_bid_dollars: str(raw.yes_bid_dollars),
|
|
118
|
+
yes_ask_dollars: str(raw.yes_ask_dollars),
|
|
119
|
+
no_bid_dollars: str(raw.no_bid_dollars),
|
|
120
|
+
no_ask_dollars: str(raw.no_ask_dollars),
|
|
121
|
+
last_price_dollars: str(raw.last_price_dollars),
|
|
122
|
+
volume_fp: str(raw.volume_fp),
|
|
123
|
+
volume_24h_fp: str(raw.volume_24h_fp),
|
|
124
|
+
open_interest_fp: str(raw.open_interest_fp),
|
|
125
|
+
raw,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
export function tradeFromRaw(raw) {
|
|
129
|
+
return {
|
|
130
|
+
trade_id: str(raw.trade_id) ?? "",
|
|
131
|
+
ticker: str(raw.ticker),
|
|
132
|
+
created_time: time(raw.created_time),
|
|
133
|
+
count_fp: str(raw.count_fp),
|
|
134
|
+
yes_price_dollars: str(raw.yes_price_dollars),
|
|
135
|
+
no_price_dollars: str(raw.no_price_dollars),
|
|
136
|
+
taker_outcome_side: str(raw.taker_outcome_side),
|
|
137
|
+
taker_book_side: str(raw.taker_book_side),
|
|
138
|
+
is_block_trade: raw.is_block_trade === true,
|
|
139
|
+
raw,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function levels(rows) {
|
|
143
|
+
if (!Array.isArray(rows))
|
|
144
|
+
return [];
|
|
145
|
+
const out = [];
|
|
146
|
+
for (const row of rows) {
|
|
147
|
+
if (Array.isArray(row) && row.length === 2 && typeof row[0] === "string" && typeof row[1] === "string")
|
|
148
|
+
out.push({ price_dollars: row[0], count_fp: row[1] });
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The book from Kalshi's reply. A reply without an orderbook_fp object is a
|
|
154
|
+
* shape this client does not know and throws KalshiError, so it is never read
|
|
155
|
+
* as an empty book; an empty or null side is an empty side.
|
|
156
|
+
*/
|
|
157
|
+
export function orderbookFromRaw(ticker, raw) {
|
|
158
|
+
const fp = raw.orderbook_fp;
|
|
159
|
+
if (fp === null || typeof fp !== "object" || Array.isArray(fp)) {
|
|
160
|
+
throw new KalshiError(`Kalshi's orderbook reply for ${ticker} has no orderbook_fp object: a shape this client does not know`, { status: 200 });
|
|
161
|
+
}
|
|
162
|
+
const book = record(fp);
|
|
163
|
+
const yes = levels(book.yes_dollars);
|
|
164
|
+
const no = levels(book.no_dollars);
|
|
165
|
+
return { ticker, yes, no, best_yes_bid: yes.at(-1) ?? null, best_no_bid: no.at(-1) ?? null, raw };
|
|
166
|
+
}
|
|
167
|
+
function ohlc(raw) {
|
|
168
|
+
const r = record(raw);
|
|
169
|
+
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) };
|
|
170
|
+
}
|
|
171
|
+
export function candlestickFromRaw(raw, periodMinutes) {
|
|
172
|
+
const end = typeof raw.end_period_ts === "number" ? new Date(raw.end_period_ts * 1000) : null;
|
|
173
|
+
return {
|
|
174
|
+
end_period: end,
|
|
175
|
+
start_period: end === null ? null : new Date(end.getTime() - periodMinutes * 60_000),
|
|
176
|
+
period_minutes: periodMinutes,
|
|
177
|
+
price: ohlc(raw.price),
|
|
178
|
+
yes_bid: ohlc(raw.yes_bid),
|
|
179
|
+
yes_ask: ohlc(raw.yes_ask),
|
|
180
|
+
volume_fp: str(raw.volume_fp),
|
|
181
|
+
open_interest_fp: str(raw.open_interest_fp),
|
|
182
|
+
raw,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Signs a request as Kalshi's docs say: the timestamp in milliseconds, the
|
|
187
|
+
* method and the path (from /trade-api/v2, no query string), with Ed25519 or
|
|
188
|
+
* RSA-PSS SHA-256 (MGF1 SHA-256, the salt the digest's length), base64, in
|
|
189
|
+
* KALSHI-ACCESS-KEY, KALSHI-ACCESS-SIGNATURE and KALSHI-ACCESS-TIMESTAMP.
|
|
190
|
+
*/
|
|
191
|
+
class Signer {
|
|
192
|
+
accessKey;
|
|
193
|
+
signMessage;
|
|
194
|
+
constructor(accessKey, pem) {
|
|
195
|
+
this.accessKey = accessKey;
|
|
196
|
+
let key;
|
|
197
|
+
try {
|
|
198
|
+
key = createPrivateKey(pem);
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
throw new ConfigurationError(`the Kalshi private key is not a PEM private key: ${err.message}`);
|
|
202
|
+
}
|
|
203
|
+
if (key.asymmetricKeyType === "ed25519") {
|
|
204
|
+
this.signMessage = (message) => signWith(null, message, key);
|
|
205
|
+
}
|
|
206
|
+
else if (key.asymmetricKeyType === "rsa") {
|
|
207
|
+
this.signMessage = (message) => signWith("sha256", message, { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST });
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
throw new ConfigurationError(`the Kalshi private key is ${key.asymmetricKeyType ?? "unknown"}; Kalshi keys are Ed25519 or RSA`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
headers(method, path, timestampMs) {
|
|
214
|
+
const signature = this.signMessage(Buffer.from(`${timestampMs}${method}${path}`));
|
|
215
|
+
return { "KALSHI-ACCESS-KEY": this.accessKey, "KALSHI-ACCESS-SIGNATURE": signature.toString("base64"), "KALSHI-ACCESS-TIMESTAMP": String(timestampMs) };
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The Kalshi tickers of a matched event: the market_id of its members on
|
|
220
|
+
* kalshi and kalshi_dflow (both use the ticker as the id), active ones unless
|
|
221
|
+
* includeInactive, in member order, each once.
|
|
222
|
+
*/
|
|
223
|
+
export function kalshiTickers(event, includeInactive = false) {
|
|
224
|
+
const out = [];
|
|
225
|
+
for (const m of event.members) {
|
|
226
|
+
if (KALSHI_VENUES.has(m.venue) && m.market_id && (includeInactive || m.status === "active") && !out.includes(m.market_id))
|
|
227
|
+
out.push(m.market_id);
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
function defaultSleep(seconds) {
|
|
232
|
+
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* The live Kalshi client. Build it as sk.kalshi(...) or on its own:
|
|
236
|
+
*
|
|
237
|
+
* const kalshi = sk.kalshi(); // public requests
|
|
238
|
+
* const kalshi = sk.kalshi({ accessKey: keyId, privateKey: pem }); // the user's own key
|
|
239
|
+
* for await (const market of kalshi.markets({ status: "open", seriesTicker: "KXSAMPLE" })) ...
|
|
240
|
+
*
|
|
241
|
+
* The key id and the private key come from the options only, never from the
|
|
242
|
+
* environment, and one without the other is refused.
|
|
243
|
+
*/
|
|
244
|
+
export class Kalshi {
|
|
245
|
+
baseUrl;
|
|
246
|
+
maxRetries;
|
|
247
|
+
timeout;
|
|
248
|
+
/** Whether the calls are signed with a key. */
|
|
249
|
+
authenticated;
|
|
250
|
+
pathPrefix;
|
|
251
|
+
signer;
|
|
252
|
+
fetchImpl;
|
|
253
|
+
sleep;
|
|
254
|
+
now;
|
|
255
|
+
constructor(options = {}) {
|
|
256
|
+
const accessKey = options.accessKey || undefined;
|
|
257
|
+
const privateKey = options.privateKey || undefined;
|
|
258
|
+
if ((accessKey === undefined) !== (privateKey === undefined)) {
|
|
259
|
+
throw new ConfigurationError("a Kalshi key is the key id and the private key together: pass accessKey and privateKey");
|
|
260
|
+
}
|
|
261
|
+
if (options.maxRetries !== undefined && options.maxRetries < 0)
|
|
262
|
+
throw new ConfigurationError("maxRetries must not be negative");
|
|
263
|
+
if (options.timeout !== undefined && !(options.timeout > 0))
|
|
264
|
+
throw new ConfigurationError("timeout is seconds, above zero");
|
|
265
|
+
this.timeout = options.timeout ?? 30;
|
|
266
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_KALSHI_BASE_URL).replace(/\/+$/, "");
|
|
267
|
+
this.pathPrefix = new URL(this.baseUrl).pathname.replace(/\/+$/, "");
|
|
268
|
+
this.signer = accessKey !== undefined && privateKey !== undefined ? new Signer(accessKey, privateKey) : undefined;
|
|
269
|
+
this.authenticated = this.signer !== undefined;
|
|
270
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
271
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
272
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
273
|
+
this.now = options.now ?? Date.now;
|
|
274
|
+
}
|
|
275
|
+
async get(path, query = {}) {
|
|
276
|
+
const url = new URL(this.baseUrl + path);
|
|
277
|
+
for (const [k, v] of Object.entries(query))
|
|
278
|
+
if (v !== undefined)
|
|
279
|
+
url.searchParams.set(k, String(v));
|
|
280
|
+
for (let attempt = 0;; attempt++) {
|
|
281
|
+
const headers = { Accept: "application/json", "User-Agent": `skewtape-ts/${VERSION}` };
|
|
282
|
+
if (this.signer)
|
|
283
|
+
Object.assign(headers, this.signer.headers("GET", this.pathPrefix + path, this.now()));
|
|
284
|
+
let response;
|
|
285
|
+
try {
|
|
286
|
+
// The timeout covers the whole request, the body read included. A
|
|
287
|
+
// redirect is not followed, as Python's client follows none: a 3xx is
|
|
288
|
+
// a KalshiError naming its status.
|
|
289
|
+
response = await this.fetchImpl(url.toString(), { method: "GET", redirect: "manual", headers, signal: AbortSignal.timeout(this.timeout * 1000) });
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
throw this.timedOut(err);
|
|
293
|
+
}
|
|
294
|
+
// A browser's fetch hides a manual redirect's status: say what it was.
|
|
295
|
+
if (response.type === "opaqueredirect")
|
|
296
|
+
throw new KalshiError("Kalshi answered with a redirect, which this client does not follow", { status: response.status });
|
|
297
|
+
if (response.status === 429 && attempt < this.maxRetries) {
|
|
298
|
+
// The body is not read; cancelling it frees the connection.
|
|
299
|
+
await response.body?.cancel();
|
|
300
|
+
await this.sleep(retryAfterSeconds(response.headers) ?? 0.5 * 2 ** attempt);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
let body;
|
|
304
|
+
try {
|
|
305
|
+
body = await response.text();
|
|
306
|
+
}
|
|
307
|
+
catch (err) {
|
|
308
|
+
throw this.timedOut(err);
|
|
309
|
+
}
|
|
310
|
+
if (response.ok) {
|
|
311
|
+
try {
|
|
312
|
+
return JSON.parse(body);
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
throw new KalshiError("Kalshi sent a body that is not JSON", { status: response.status });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
throw kalshiError(response.status, response.headers, body);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/** A timeout or abort, while the request or its body is read, as the KalshiError naming the seconds; anything else as it came. */
|
|
322
|
+
timedOut(err) {
|
|
323
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))
|
|
324
|
+
return new KalshiError(`the Kalshi request took longer than ${this.timeout} s`);
|
|
325
|
+
return err;
|
|
326
|
+
}
|
|
327
|
+
/** 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. */
|
|
328
|
+
markets(options = {}) {
|
|
329
|
+
const mve = options.multivariate === null ? undefined : options.multivariate ? "only" : "exclude";
|
|
330
|
+
return new Paginated(async (cursor) => {
|
|
331
|
+
const body = record(await this.get("/markets", {
|
|
332
|
+
limit: options.limit ?? 100,
|
|
333
|
+
cursor,
|
|
334
|
+
status: options.status,
|
|
335
|
+
series_ticker: options.seriesTicker,
|
|
336
|
+
event_ticker: options.eventTicker,
|
|
337
|
+
tickers: options.tickers?.length ? options.tickers.join(",") : undefined,
|
|
338
|
+
mve_filter: mve,
|
|
339
|
+
}));
|
|
340
|
+
const rows = Array.isArray(body.markets) ? body.markets : [];
|
|
341
|
+
return { items: rows.map((m) => marketFromRaw(record(m))), nextCursor: str(body.cursor) || null };
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
/** GET /markets/{ticker}: one market. */
|
|
345
|
+
async market(ticker) {
|
|
346
|
+
const body = record(await this.get(`/markets/${encodeURIComponent(ticker)}`));
|
|
347
|
+
if (body.market === null || typeof body.market !== "object")
|
|
348
|
+
throw new KalshiError(`Kalshi sent no market for ${ticker}`, { status: 200 });
|
|
349
|
+
return marketFromRaw(record(body.market));
|
|
350
|
+
}
|
|
351
|
+
/** 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. */
|
|
352
|
+
trades(options = {}) {
|
|
353
|
+
return new Paginated(async (cursor) => {
|
|
354
|
+
const body = record(await this.get("/markets/trades", {
|
|
355
|
+
limit: options.limit ?? 100,
|
|
356
|
+
cursor,
|
|
357
|
+
ticker: options.ticker,
|
|
358
|
+
min_ts: options.since === undefined ? undefined : unix(options.since),
|
|
359
|
+
max_ts: options.until === undefined ? undefined : unix(options.until),
|
|
360
|
+
is_block_trade: options.blockTrades === undefined ? undefined : String(options.blockTrades),
|
|
361
|
+
}));
|
|
362
|
+
const rows = Array.isArray(body.trades) ? body.trades : [];
|
|
363
|
+
return { items: rows.map((t) => tradeFromRaw(record(t))), nextCursor: str(body.cursor) || null };
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
/** GET /markets/{ticker}/orderbook: the resting bids of one market, every level or the best depth levels of each side (1 to 100). */
|
|
367
|
+
async orderbook(ticker, options = {}) {
|
|
368
|
+
const body = record(await this.get(`/markets/${encodeURIComponent(ticker)}/orderbook`, { depth: options.depth }));
|
|
369
|
+
return orderbookFromRaw(ticker, body);
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* GET /series/{series}/markets/{ticker}/candlesticks: the sticks of one size
|
|
373
|
+
* ending from since to until (now by default). Kalshi serves at most 5,000
|
|
374
|
+
* periods a request and a 1d stick is a New York day.
|
|
375
|
+
*/
|
|
376
|
+
async candlesticks(ticker, options) {
|
|
377
|
+
const period = options.period ?? "1h";
|
|
378
|
+
const minutes = typeof period === "string" ? PERIODS[period] : period;
|
|
379
|
+
if (minutes !== 1 && minutes !== 60 && minutes !== 1440)
|
|
380
|
+
throw new ConfigurationError(`period is 1m, 1h or 1d (or 1, 60 or 1440 minutes), not ${String(period)}`);
|
|
381
|
+
const series = options.seriesTicker ?? seriesTickerOf(ticker);
|
|
382
|
+
const body = record(await this.get(`/series/${encodeURIComponent(series)}/markets/${encodeURIComponent(ticker)}/candlesticks`, {
|
|
383
|
+
start_ts: unix(options.since),
|
|
384
|
+
end_ts: options.until === undefined ? Math.floor(this.now() / 1000) : unix(options.until),
|
|
385
|
+
period_interval: minutes,
|
|
386
|
+
}));
|
|
387
|
+
const rows = Array.isArray(body.candlesticks) ? body.candlesticks : [];
|
|
388
|
+
return rows.map((s) => candlestickFromRaw(record(s), minutes));
|
|
389
|
+
}
|
|
390
|
+
/** The Kalshi tickers of a Skewtape matched event: the market_id of its kalshi and kalshi_dflow members, active ones unless includeInactive. */
|
|
391
|
+
tickers(event, options = {}) {
|
|
392
|
+
return kalshiTickers(event, options.includeInactive ?? false);
|
|
393
|
+
}
|
|
394
|
+
/** 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. */
|
|
395
|
+
async marketsFor(event, options = {}) {
|
|
396
|
+
const wanted = this.tickers(event, options);
|
|
397
|
+
if (wanted.length === 0)
|
|
398
|
+
return [];
|
|
399
|
+
const byTicker = new Map();
|
|
400
|
+
for await (const m of this.markets({ tickers: wanted }))
|
|
401
|
+
byTicker.set(m.ticker, m);
|
|
402
|
+
return wanted.flatMap((t) => byTicker.get(t) ?? []);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
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
|
+
/** The 32-byte Keccak-256 digest of data. */
|
|
8
|
+
export declare function keccak256(data: Uint8Array): Uint8Array;
|
|
9
|
+
/** Hex with 0x, the shape viem and ethers take. */
|
|
10
|
+
export declare function toHex(bytes: Uint8Array): `0x${string}`;
|
|
@@ -0,0 +1,80 @@
|
|
|
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
|
+
const MASK = (1n << 64n) - 1n;
|
|
8
|
+
const RATE = 136; // bytes: 1600 - 2 * 256 bits
|
|
9
|
+
const ROUND_CONSTANTS = [
|
|
10
|
+
0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
|
|
11
|
+
0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
|
|
12
|
+
0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
|
|
13
|
+
0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
|
|
14
|
+
0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
|
|
15
|
+
0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n,
|
|
16
|
+
];
|
|
17
|
+
/** ROTATIONS[x][y] is lane (x, y)'s rotation in rho. */
|
|
18
|
+
const ROTATIONS = [
|
|
19
|
+
[0, 36, 3, 41, 18],
|
|
20
|
+
[1, 44, 10, 45, 2],
|
|
21
|
+
[62, 6, 43, 15, 61],
|
|
22
|
+
[28, 55, 25, 21, 56],
|
|
23
|
+
[27, 20, 39, 8, 14],
|
|
24
|
+
];
|
|
25
|
+
const rotl = (v, n) => (n === 0 ? v : ((v << BigInt(n)) | (v >> BigInt(64 - n))) & MASK);
|
|
26
|
+
/** Keccak-f[1600] on 25 lanes, lane (x, y) at index x + 5y. */
|
|
27
|
+
function permute(a) {
|
|
28
|
+
for (const rc of ROUND_CONSTANTS) {
|
|
29
|
+
const c = [];
|
|
30
|
+
for (let x = 0; x < 5; x++)
|
|
31
|
+
c.push(a[x] ^ a[x + 5] ^ a[x + 10] ^ a[x + 15] ^ a[x + 20]);
|
|
32
|
+
for (let i = 0; i < 25; i++)
|
|
33
|
+
a[i] = a[i] ^ c[(i % 5 + 4) % 5] ^ rotl(c[(i % 5 + 1) % 5], 1);
|
|
34
|
+
const b = new Array(25).fill(0n);
|
|
35
|
+
for (let x = 0; x < 5; x++) {
|
|
36
|
+
for (let y = 0; y < 5; y++)
|
|
37
|
+
b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(a[x + 5 * y], ROTATIONS[x][y]);
|
|
38
|
+
}
|
|
39
|
+
for (let y = 0; y < 5; y++) {
|
|
40
|
+
for (let x = 0; x < 5; x++) {
|
|
41
|
+
a[x + 5 * y] = b[x + 5 * y] ^ (~b[((x + 1) % 5) + 5 * y] & MASK & b[((x + 2) % 5) + 5 * y]);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
a[0] = a[0] ^ rc;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** The 32-byte Keccak-256 digest of data. */
|
|
48
|
+
export function keccak256(data) {
|
|
49
|
+
const padLen = RATE - ((data.length + 1) % RATE || RATE) + 1;
|
|
50
|
+
const padded = new Uint8Array(data.length + padLen);
|
|
51
|
+
padded.set(data);
|
|
52
|
+
padded[data.length] = 0x01;
|
|
53
|
+
padded[padded.length - 1] |= 0x80;
|
|
54
|
+
const state = new Array(25).fill(0n);
|
|
55
|
+
for (let off = 0; off < padded.length; off += RATE) {
|
|
56
|
+
for (let i = 0; i < RATE / 8; i++) {
|
|
57
|
+
let lane = 0n;
|
|
58
|
+
for (let j = 7; j >= 0; j--)
|
|
59
|
+
lane = (lane << 8n) | BigInt(padded[off + 8 * i + j]);
|
|
60
|
+
state[i] = state[i] ^ lane;
|
|
61
|
+
}
|
|
62
|
+
permute(state);
|
|
63
|
+
}
|
|
64
|
+
const out = new Uint8Array(32);
|
|
65
|
+
for (let i = 0; i < 4; i++) {
|
|
66
|
+
let lane = state[i];
|
|
67
|
+
for (let j = 0; j < 8; j++) {
|
|
68
|
+
out[8 * i + j] = Number(lane & 0xffn);
|
|
69
|
+
lane >>= 8n;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
/** Hex with 0x, the shape viem and ethers take. */
|
|
75
|
+
export function toHex(bytes) {
|
|
76
|
+
let s = "0x";
|
|
77
|
+
for (const b of bytes)
|
|
78
|
+
s += b.toString(16).padStart(2, "0");
|
|
79
|
+
return s;
|
|
80
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MessagePack, the subset an exchange action holds.
|
|
3
|
+
*
|
|
4
|
+
* Hyperliquid hashes an action's MessagePack bytes (msgpack.packb in its
|
|
5
|
+
* Python SDK: maps keep their keys' insertion order, strings use the
|
|
6
|
+
* str8/16/32 formats), and a byte off is another hash and a refused
|
|
7
|
+
* signature. This writes what an order action holds: plain objects (their
|
|
8
|
+
* keys in insertion order), arrays, strings, safe integers, booleans and
|
|
9
|
+
* null, each in the smallest format, as msgpack.packb does. Anything else
|
|
10
|
+
* is refused rather than guessed.
|
|
11
|
+
*/
|
|
12
|
+
export type Packable = null | boolean | number | string | readonly Packable[] | {
|
|
13
|
+
readonly [key: string]: Packable;
|
|
14
|
+
};
|
|
15
|
+
export declare function packb(value: Packable): Uint8Array;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MessagePack, the subset an exchange action holds.
|
|
3
|
+
*
|
|
4
|
+
* Hyperliquid hashes an action's MessagePack bytes (msgpack.packb in its
|
|
5
|
+
* Python SDK: maps keep their keys' insertion order, strings use the
|
|
6
|
+
* str8/16/32 formats), and a byte off is another hash and a refused
|
|
7
|
+
* signature. This writes what an order action holds: plain objects (their
|
|
8
|
+
* keys in insertion order), arrays, strings, safe integers, booleans and
|
|
9
|
+
* null, each in the smallest format, as msgpack.packb does. Anything else
|
|
10
|
+
* is refused rather than guessed.
|
|
11
|
+
*/
|
|
12
|
+
export function packb(value) {
|
|
13
|
+
const out = [];
|
|
14
|
+
pack(value, out);
|
|
15
|
+
return Uint8Array.from(out);
|
|
16
|
+
}
|
|
17
|
+
const be = (n, bytes) => {
|
|
18
|
+
const out = [];
|
|
19
|
+
for (let i = bytes - 1; i >= 0; i--)
|
|
20
|
+
out.push(Math.floor(n / 2 ** (8 * i)) % 256);
|
|
21
|
+
return out;
|
|
22
|
+
};
|
|
23
|
+
function pack(v, out) {
|
|
24
|
+
if (v === null) {
|
|
25
|
+
out.push(0xc0);
|
|
26
|
+
}
|
|
27
|
+
else if (v === true) {
|
|
28
|
+
out.push(0xc3);
|
|
29
|
+
}
|
|
30
|
+
else if (v === false) {
|
|
31
|
+
out.push(0xc2);
|
|
32
|
+
}
|
|
33
|
+
else if (typeof v === "number") {
|
|
34
|
+
packInt(v, out);
|
|
35
|
+
}
|
|
36
|
+
else if (typeof v === "string") {
|
|
37
|
+
const b = new TextEncoder().encode(v);
|
|
38
|
+
const n = b.length;
|
|
39
|
+
if (n < 32)
|
|
40
|
+
out.push(0xa0 | n);
|
|
41
|
+
else if (n < 2 ** 8)
|
|
42
|
+
out.push(0xd9, n);
|
|
43
|
+
else if (n < 2 ** 16)
|
|
44
|
+
out.push(0xda, ...be(n, 2));
|
|
45
|
+
else
|
|
46
|
+
out.push(0xdb, ...be(n, 4));
|
|
47
|
+
for (const x of b)
|
|
48
|
+
out.push(x);
|
|
49
|
+
}
|
|
50
|
+
else if (Array.isArray(v)) {
|
|
51
|
+
const n = v.length;
|
|
52
|
+
if (n < 16)
|
|
53
|
+
out.push(0x90 | n);
|
|
54
|
+
else if (n < 2 ** 16)
|
|
55
|
+
out.push(0xdc, ...be(n, 2));
|
|
56
|
+
else
|
|
57
|
+
out.push(0xdd, ...be(n, 4));
|
|
58
|
+
for (const item of v)
|
|
59
|
+
pack(item, out);
|
|
60
|
+
}
|
|
61
|
+
else if (typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype) {
|
|
62
|
+
const entries = Object.entries(v);
|
|
63
|
+
const n = entries.length;
|
|
64
|
+
if (n < 16)
|
|
65
|
+
out.push(0x80 | n);
|
|
66
|
+
else if (n < 2 ** 16)
|
|
67
|
+
out.push(0xde, ...be(n, 2));
|
|
68
|
+
else
|
|
69
|
+
out.push(0xdf, ...be(n, 4));
|
|
70
|
+
for (const [key, item] of entries) {
|
|
71
|
+
pack(key, out);
|
|
72
|
+
pack(item, out);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
throw new TypeError(`msgpack: ${typeof v} is not written (an action holds objects, arrays, strings, integers, booleans and null)`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function packInt(v, out) {
|
|
80
|
+
if (!Number.isSafeInteger(v))
|
|
81
|
+
throw new TypeError(`msgpack: ${v} is not a safe integer`);
|
|
82
|
+
if (v >= 0 && v < 0x80)
|
|
83
|
+
out.push(v);
|
|
84
|
+
else if (v >= -32 && v < 0)
|
|
85
|
+
out.push(v & 0xff);
|
|
86
|
+
else if (v >= 0) {
|
|
87
|
+
if (v < 2 ** 8)
|
|
88
|
+
out.push(0xcc, v);
|
|
89
|
+
else if (v < 2 ** 16)
|
|
90
|
+
out.push(0xcd, ...be(v, 2));
|
|
91
|
+
else if (v < 2 ** 32)
|
|
92
|
+
out.push(0xce, ...be(v, 4));
|
|
93
|
+
else
|
|
94
|
+
out.push(0xcf, ...be(v, 8));
|
|
95
|
+
}
|
|
96
|
+
else if (v >= -(2 ** 7))
|
|
97
|
+
out.push(0xd0, v & 0xff);
|
|
98
|
+
else if (v >= -(2 ** 15))
|
|
99
|
+
out.push(0xd1, ...be(v + 2 ** 16, 2));
|
|
100
|
+
else if (v >= -(2 ** 31))
|
|
101
|
+
out.push(0xd2, ...be(v + 2 ** 32, 4));
|
|
102
|
+
else {
|
|
103
|
+
// int64: two's complement over 8 bytes.
|
|
104
|
+
const big = BigInt.asUintN(64, BigInt(v));
|
|
105
|
+
out.push(0xd3);
|
|
106
|
+
for (let i = 7; i >= 0; i--)
|
|
107
|
+
out.push(Number((big >> BigInt(8 * i)) & 0xffn));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paginated lists: the shape every list of the Skewtape client and of the
|
|
3
|
+
* Kalshi client comes back as. for await yields every item, fetching each
|
|
4
|
+
* page as the one before runs out; nothing is fetched until it is iterated.
|
|
5
|
+
*/
|
|
6
|
+
/** One page of a list: its items and the cursor of the next page, null on the last. */
|
|
7
|
+
export interface Page<T> {
|
|
8
|
+
items: T[];
|
|
9
|
+
nextCursor: string | null;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A list the API pages: for await yields every item, fetching each page as
|
|
13
|
+
* the one before runs out. Nothing is fetched until it is iterated.
|
|
14
|
+
*/
|
|
15
|
+
export declare class Paginated<T> implements AsyncIterable<T> {
|
|
16
|
+
private readonly fetchPage;
|
|
17
|
+
private readonly keep?;
|
|
18
|
+
constructor(fetchPage: (cursor?: string) => Promise<Page<T>>, keep?: ((item: T) => boolean) | undefined);
|
|
19
|
+
/** The pages as the API returns them; a client-side filter (markets resolved, pairs) applies to each. */
|
|
20
|
+
pages(): AsyncGenerator<Page<T>, void, undefined>;
|
|
21
|
+
[Symbol.asyncIterator](): AsyncGenerator<T, void, undefined>;
|
|
22
|
+
/** The first item, or undefined when there is none. */
|
|
23
|
+
first(): Promise<T | undefined>;
|
|
24
|
+
/** Every item, in one array. */
|
|
25
|
+
toArray(): Promise<T[]>;
|
|
26
|
+
}
|