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.
- 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
package/src/client.ts
ADDED
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The facade: sk.markets, sk.events (and sk.events.get), sk.pairs, sk.fills,
|
|
3
|
+
* sk.candles, sk.resolutions, sk.fees, sk.venues, sk.download and sk.quote
|
|
4
|
+
* (quote.ts), over the openapi-fetch client typed by the generated schema.
|
|
5
|
+
* Lists come back as a Paginated: iterate (for await) for every item across
|
|
6
|
+
* pages, .pages() for the pages themselves, .first() for the first item. A 429
|
|
7
|
+
* rate_limited is retried with the server's Retry-After; every other error, a
|
|
8
|
+
* quota_exceeded 429 included, is a SkewtapeError with the envelope's fields,
|
|
9
|
+
* thrown at once.
|
|
10
|
+
* sk.kalshi() is the optional live Kalshi client (./kalshi.ts), apart from
|
|
11
|
+
* the API. sk.route builds an unsigned order with the developer's own code
|
|
12
|
+
* (./route.ts) and sk.geoblock asks a venue's own geoblock check
|
|
13
|
+
* (./geoblock.ts); neither sends the API key.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { resolve, sep } from "node:path";
|
|
17
|
+
|
|
18
|
+
import createOpenapiClient from "openapi-fetch";
|
|
19
|
+
|
|
20
|
+
import { CANDLE_MICROS, runBacktest, settledAt, type BacktestResult, type Trade } from "./backtest.js";
|
|
21
|
+
import { downloadFile, holds, verifyChecksums, type DownloadOptions } from "./download.js";
|
|
22
|
+
import { ConfigurationError, NotFoundError, SkewtapeError, errorFromResponse, retryAfterSeconds } from "./errors.js";
|
|
23
|
+
import { Stream, feedUrl, type StreamOptions } from "./stream.js";
|
|
24
|
+
import { geoblock } from "./geoblock.js";
|
|
25
|
+
import { route } from "./route.js";
|
|
26
|
+
import type { components, paths } from "./generated/schema.js";
|
|
27
|
+
import { parseMicros } from "./exact.js";
|
|
28
|
+
import type { FeeRowInput } from "./fees.js";
|
|
29
|
+
import { Kalshi, type KalshiOptions } from "./kalshi.js";
|
|
30
|
+
import { Paginated, type Page } from "./paginated.js";
|
|
31
|
+
import { quoteFromContext, type QuoteContext, type QuoteOptions } from "./quote.js";
|
|
32
|
+
import type { QuoteResult } from "./quote-math.js";
|
|
33
|
+
import { VERSION } from "./version.js";
|
|
34
|
+
|
|
35
|
+
export { Paginated, type Page } from "./paginated.js";
|
|
36
|
+
|
|
37
|
+
export const DEFAULT_BASE_URL = "https://api.skewtape.com";
|
|
38
|
+
export const ENV_API_KEY = "SKEWTAPE_API_KEY";
|
|
39
|
+
|
|
40
|
+
type Schemas = components["schemas"];
|
|
41
|
+
export type Market = Schemas["Market"];
|
|
42
|
+
export type MatchedEvent = Schemas["MatchedEvent"];
|
|
43
|
+
export type MatchedEventMember = Schemas["MatchedEventMember"];
|
|
44
|
+
export type Fill = Schemas["Fill"];
|
|
45
|
+
export type Candle = Schemas["Candle"];
|
|
46
|
+
export type Resolution = Schemas["Resolution"];
|
|
47
|
+
export type Fee = Schemas["Fee"];
|
|
48
|
+
export type Venue = Schemas["Venue"];
|
|
49
|
+
export type Bundle = Schemas["Bundle"];
|
|
50
|
+
export type BundleFile = Schemas["BundleFile"];
|
|
51
|
+
export type DownloadURL = Schemas["DownloadURL"];
|
|
52
|
+
|
|
53
|
+
/** Options of sk.download.bundle: the plain fetch for the files, and progress per file. */
|
|
54
|
+
export interface BundleDownloadOptions {
|
|
55
|
+
/** The fetch for the files (the global one by default). The file host never sees the API key. */
|
|
56
|
+
fetch?: typeof fetch | undefined;
|
|
57
|
+
/** Called after each chunk with the file's path, the bytes so far and its size. */
|
|
58
|
+
onProgress?: ((path: string, done: number, total: number | undefined) => void) | undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
type Query<P extends keyof paths> = paths[P] extends { get: { parameters: { query?: infer Q } } } ? NonNullable<Q> : never;
|
|
62
|
+
|
|
63
|
+
export interface SkewtapeOptions {
|
|
64
|
+
/** The API key; SKEWTAPE_API_KEY when left out. */
|
|
65
|
+
apiKey?: string;
|
|
66
|
+
baseUrl?: string;
|
|
67
|
+
/** How many times a 429 rate_limited is retried, after the server's Retry-After. Three by default. */
|
|
68
|
+
maxRetries?: number;
|
|
69
|
+
/** How long one request may take, in seconds; 30 by default. A request past it throws a SkewtapeError. */
|
|
70
|
+
timeout?: number;
|
|
71
|
+
/** The fetch to use; the global one by default. */
|
|
72
|
+
fetch?: typeof fetch;
|
|
73
|
+
/** How to wait, in seconds; a timer by default. Tests inject their own. */
|
|
74
|
+
sleep?: (seconds: number) => Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface MarketsOptions {
|
|
78
|
+
venue?: string;
|
|
79
|
+
marketId?: string[];
|
|
80
|
+
updatedSince?: Date | string;
|
|
81
|
+
/**
|
|
82
|
+
* Keeps the markets whose status is (or is not) resolved; applied on the
|
|
83
|
+
* client, so every page is still fetched, each a metered call: pass a venue
|
|
84
|
+
* or marketId with it. TODO(decision): a server-side status filter on
|
|
85
|
+
* /v1/markets would make it one request per page of results.
|
|
86
|
+
*/
|
|
87
|
+
resolved?: boolean;
|
|
88
|
+
limit?: number;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface EventsOptions {
|
|
92
|
+
minConfidence?: number;
|
|
93
|
+
resolutionEqual?: boolean;
|
|
94
|
+
venue?: string;
|
|
95
|
+
status?: "approved" | "needs_rereview" | "retired";
|
|
96
|
+
limit?: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface FillsOptions {
|
|
100
|
+
since: Date | string;
|
|
101
|
+
/** Now by default. */
|
|
102
|
+
until?: Date | string;
|
|
103
|
+
venue?: string;
|
|
104
|
+
marketId?: string;
|
|
105
|
+
eventId?: string;
|
|
106
|
+
/** maker by default. */
|
|
107
|
+
leg?: "maker" | "taker" | "all";
|
|
108
|
+
limit?: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface CandlesOptions {
|
|
112
|
+
res: "1m" | "1h" | "1d";
|
|
113
|
+
since: Date | string;
|
|
114
|
+
until?: Date | string;
|
|
115
|
+
venue?: string;
|
|
116
|
+
marketId?: string;
|
|
117
|
+
eventId?: string;
|
|
118
|
+
limit?: number;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface ResolutionsOptions {
|
|
122
|
+
venue?: string;
|
|
123
|
+
/** Up to 100 market ids. */
|
|
124
|
+
marketId?: string[];
|
|
125
|
+
createdSince?: Date | string;
|
|
126
|
+
limit?: number;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface FeesOptions {
|
|
130
|
+
venue?: string;
|
|
131
|
+
limit?: number;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Options of sk.backtest: asOf (now by default), the history that prices
|
|
136
|
+
* trades without a price and marks open positions (fills by default, Builder
|
|
137
|
+
* and Pro; candles at candleRes, 1h by default, any size on Builder and Pro
|
|
138
|
+
* and Polymarket 1d only on Free and History; none), the window looked back
|
|
139
|
+
* before each such time (a day by default), voidPayout and onMissingFee as
|
|
140
|
+
* in runBacktest, and any of the inputs to use instead of fetching them.
|
|
141
|
+
*/
|
|
142
|
+
export interface SkBacktestOptions {
|
|
143
|
+
asOf?: Date | string;
|
|
144
|
+
history?: "fills" | "candles" | "none";
|
|
145
|
+
candleRes?: "1m" | "1h" | "1d";
|
|
146
|
+
lookbackSeconds?: number;
|
|
147
|
+
voidPayout?: string | number;
|
|
148
|
+
onMissingFee?: "error" | "zero";
|
|
149
|
+
fees?: Iterable<FeeRowInput>;
|
|
150
|
+
markets?: Iterable<Record<string, unknown>>;
|
|
151
|
+
resolutions?: Iterable<Record<string, unknown>>;
|
|
152
|
+
fills?: Iterable<Record<string, unknown>>;
|
|
153
|
+
candles?: Iterable<Record<string, unknown>>;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The windows [t - lookback, t + 1 ms) up to each time (microseconds), as the
|
|
158
|
+
* API's exclusive to reads them: dateOf drops the microseconds, so the next
|
|
159
|
+
* millisecond keeps a row at t itself in. Overlapping ones merged.
|
|
160
|
+
*/
|
|
161
|
+
function windows(times: bigint[], lookback: bigint): Array<[bigint, bigint]> {
|
|
162
|
+
const spans = times.map((t): [bigint, bigint] => [t - lookback, t + 1000n]).sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
|
|
163
|
+
const merged: Array<[bigint, bigint]> = [];
|
|
164
|
+
for (const [start, end] of spans) {
|
|
165
|
+
const last = merged.at(-1);
|
|
166
|
+
if (last && start <= last[1]) last[1] = end > last[1] ? end : last[1];
|
|
167
|
+
else merged.push([start, end]);
|
|
168
|
+
}
|
|
169
|
+
return merged;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function dateOf(micros: bigint): Date {
|
|
173
|
+
return new Date(Number(micros / 1000n));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function iso(v: Date | string | undefined): string | undefined {
|
|
177
|
+
return v instanceof Date ? v.toISOString() : v;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function defaultSleep(seconds: number): Promise<void> {
|
|
181
|
+
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** How many of an event's members are active. */
|
|
185
|
+
export function activeMembers(event: MatchedEvent): number {
|
|
186
|
+
return event.members.filter((m) => m.status === "active").length;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
type Result<T> = { data?: T; error?: unknown; response: Response };
|
|
190
|
+
|
|
191
|
+
/** The envelope's code in an openapi-fetch error body, when it is one. */
|
|
192
|
+
function envelopeCode(error: unknown): string | undefined {
|
|
193
|
+
if (error === null || typeof error !== "object" || !("error" in error)) return undefined;
|
|
194
|
+
const e = (error as { error: unknown }).error;
|
|
195
|
+
return e !== null && typeof e === "object" && typeof (e as { code?: unknown }).code === "string" ? (e as { code: string }).code : undefined;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** A fetch that gives up after timeout seconds, unless the caller brought its own abort handle. */
|
|
199
|
+
function withTimeout(fetchImpl: typeof fetch, timeout: number): typeof fetch {
|
|
200
|
+
return (input, init) => fetchImpl(input, { ...init, signal: init?.signal ?? AbortSignal.timeout(timeout * 1000) });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export class Skewtape {
|
|
204
|
+
readonly baseUrl: string;
|
|
205
|
+
readonly maxRetries: number;
|
|
206
|
+
readonly timeout: number;
|
|
207
|
+
private readonly api: ReturnType<typeof createOpenapiClient<paths>>;
|
|
208
|
+
private readonly sleep: (seconds: number) => Promise<void>;
|
|
209
|
+
private readonly userSleep: ((seconds: number) => Promise<void>) | undefined;
|
|
210
|
+
/** A private field: inspecting or logging the client does not show the key. */
|
|
211
|
+
readonly #apiKey: string;
|
|
212
|
+
|
|
213
|
+
constructor(options: SkewtapeOptions = {}) {
|
|
214
|
+
const key = options.apiKey ?? process.env[ENV_API_KEY] ?? "";
|
|
215
|
+
if (!key) throw new ConfigurationError(`no API key: pass apiKey or set ${ENV_API_KEY}`);
|
|
216
|
+
if (options.maxRetries !== undefined && options.maxRetries < 0) throw new ConfigurationError("maxRetries must not be negative");
|
|
217
|
+
if (options.timeout !== undefined && !(options.timeout > 0)) throw new ConfigurationError("timeout is seconds, above zero");
|
|
218
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
219
|
+
this.#apiKey = key;
|
|
220
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
221
|
+
this.timeout = options.timeout ?? 30;
|
|
222
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
223
|
+
this.userSleep = options.sleep;
|
|
224
|
+
this.api = createOpenapiClient<paths>({
|
|
225
|
+
baseUrl: this.baseUrl,
|
|
226
|
+
fetch: withTimeout(options.fetch ?? fetch, this.timeout),
|
|
227
|
+
headers: { "X-API-Key": key, "User-Agent": `skewtape-ts/${VERSION}` },
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Run one request: a 429 whose envelope says rate_limited (or carries no
|
|
233
|
+
* envelope, as a proxy's would) retried up to maxRetries times after the
|
|
234
|
+
* server's Retry-After (one second without it); a 2xx returned as parsed;
|
|
235
|
+
* anything else, a quota_exceeded 429 included, thrown at once from the
|
|
236
|
+
* error envelope. A request past the timeout is a SkewtapeError.
|
|
237
|
+
*/
|
|
238
|
+
private async call<T>(run: () => Promise<Result<T>>): Promise<T> {
|
|
239
|
+
for (let attempt = 0; ; attempt++) {
|
|
240
|
+
let result: Result<T>;
|
|
241
|
+
try {
|
|
242
|
+
result = await run();
|
|
243
|
+
} catch (err) {
|
|
244
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
245
|
+
throw new SkewtapeError(`the request took longer than ${this.timeout} s`);
|
|
246
|
+
}
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
const { data, error, response } = result;
|
|
250
|
+
if (response.ok) {
|
|
251
|
+
if (data === undefined) throw new SkewtapeError(`HTTP ${response.status} with no body the client knows`, { status: response.status });
|
|
252
|
+
return data;
|
|
253
|
+
}
|
|
254
|
+
const code = envelopeCode(error);
|
|
255
|
+
if (response.status === 429 && (code === "rate_limited" || code === undefined) && attempt < this.maxRetries) {
|
|
256
|
+
await this.sleep(retryAfterSeconds(response.headers) ?? 1);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
throw errorFromResponse(response.status, response.headers, error);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** sk.markets({venue, resolved}) lists markets; sk.markets.get(venue, marketId) reads one. */
|
|
264
|
+
readonly markets = Object.assign(
|
|
265
|
+
(options: MarketsOptions = {}): Paginated<Market> =>
|
|
266
|
+
new Paginated(
|
|
267
|
+
async (cursor) => {
|
|
268
|
+
const query: Query<"/v1/markets"> = {
|
|
269
|
+
venue: options.venue,
|
|
270
|
+
market_id: options.marketId,
|
|
271
|
+
updated_since: iso(options.updatedSince),
|
|
272
|
+
limit: options.limit ?? 100,
|
|
273
|
+
cursor,
|
|
274
|
+
};
|
|
275
|
+
const data = await this.call(() => this.api.GET("/v1/markets", { params: { query } }));
|
|
276
|
+
return { items: data.data, nextCursor: data.next_cursor ?? null };
|
|
277
|
+
},
|
|
278
|
+
options.resolved === undefined ? undefined : (m) => (m.status === "resolved") === options.resolved,
|
|
279
|
+
),
|
|
280
|
+
{
|
|
281
|
+
get: (venue: string, marketId: string): Promise<Market> =>
|
|
282
|
+
this.call(() => this.api.GET("/v1/markets/{venue}/{market_id}", { params: { path: { venue, market_id: marketId } } })),
|
|
283
|
+
},
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
/** sk.events({minConfidence, resolutionEqual}) lists matched events; sk.events.get(eventId) reads one. */
|
|
287
|
+
readonly events = Object.assign(
|
|
288
|
+
(options: EventsOptions = {}): Paginated<MatchedEvent> => new Paginated(this.eventsPage(options)),
|
|
289
|
+
{
|
|
290
|
+
get: (eventId: string): Promise<MatchedEvent> =>
|
|
291
|
+
this.call(() => this.api.GET("/v1/matched_events/{event_id}", { params: { path: { event_id: eventId } } })),
|
|
292
|
+
},
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
/** sk.pairs(...) is sk.events(...) kept to the pairs: a pair is a matched event with exactly two active members. sk.pairs.get refuses, as a 404 would, any other. */
|
|
296
|
+
readonly pairs = Object.assign(
|
|
297
|
+
(options: EventsOptions = {}): Paginated<MatchedEvent> => new Paginated(this.eventsPage(options), (e) => activeMembers(e) === 2),
|
|
298
|
+
{
|
|
299
|
+
get: async (eventId: string): Promise<MatchedEvent> => {
|
|
300
|
+
const event = await this.events.get(eventId);
|
|
301
|
+
const n = activeMembers(event);
|
|
302
|
+
if (n !== 2) throw new NotFoundError(`${eventId} is not a pair: ${n} active members`, { status: 404, code: "not_found" });
|
|
303
|
+
return event;
|
|
304
|
+
},
|
|
305
|
+
},
|
|
306
|
+
);
|
|
307
|
+
|
|
308
|
+
private eventsPage(options: EventsOptions): (cursor?: string) => Promise<Page<MatchedEvent>> {
|
|
309
|
+
return async (cursor) => {
|
|
310
|
+
const query: Query<"/v1/matched_events"> = {
|
|
311
|
+
min_confidence: options.minConfidence,
|
|
312
|
+
resolution_equal: options.resolutionEqual,
|
|
313
|
+
venue: options.venue,
|
|
314
|
+
status: options.status,
|
|
315
|
+
limit: options.limit ?? 100,
|
|
316
|
+
cursor,
|
|
317
|
+
};
|
|
318
|
+
const data = await this.call(() => this.api.GET("/v1/matched_events", { params: { query } }));
|
|
319
|
+
return { items: data.data, nextCursor: data.next_cursor ?? null };
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** sk.fills({eventId, since}) lists fills from since to until (now by default), maker legs by default. */
|
|
324
|
+
fills(options: FillsOptions): Paginated<Fill> {
|
|
325
|
+
const to = iso(options.until) ?? new Date().toISOString();
|
|
326
|
+
return new Paginated(async (cursor) => {
|
|
327
|
+
const query: Query<"/v1/fills"> = {
|
|
328
|
+
venue: options.venue,
|
|
329
|
+
market_id: options.marketId,
|
|
330
|
+
event_id: options.eventId,
|
|
331
|
+
from: iso(options.since) as string,
|
|
332
|
+
to,
|
|
333
|
+
leg: options.leg ?? "maker",
|
|
334
|
+
limit: options.limit ?? 100,
|
|
335
|
+
cursor,
|
|
336
|
+
};
|
|
337
|
+
const data = await this.call(() => this.api.GET("/v1/fills", { params: { query } }));
|
|
338
|
+
return { items: data.data, nextCursor: data.next_cursor ?? null };
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** sk.candles({res, since}) lists candles of one size from since to until. */
|
|
343
|
+
candles(options: CandlesOptions): Paginated<Candle> {
|
|
344
|
+
const to = iso(options.until) ?? new Date().toISOString();
|
|
345
|
+
return new Paginated(async (cursor) => {
|
|
346
|
+
const query: Query<"/v1/candles"> = {
|
|
347
|
+
venue: options.venue,
|
|
348
|
+
market_id: options.marketId,
|
|
349
|
+
event_id: options.eventId,
|
|
350
|
+
from: iso(options.since) as string,
|
|
351
|
+
to,
|
|
352
|
+
res: options.res,
|
|
353
|
+
limit: options.limit ?? 100,
|
|
354
|
+
cursor,
|
|
355
|
+
};
|
|
356
|
+
const data = await this.call(() => this.api.GET("/v1/candles", { params: { query } }));
|
|
357
|
+
return { items: data.data, nextCursor: data.next_cursor ?? null };
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** sk.resolutions({venue, marketId, createdSince}) lists resolution events, of up to 100 markets when marketId is given. */
|
|
362
|
+
resolutions(options: ResolutionsOptions = {}): Paginated<Resolution> {
|
|
363
|
+
return new Paginated(async (cursor) => {
|
|
364
|
+
const query: Query<"/v1/resolutions"> = {
|
|
365
|
+
venue: options.venue,
|
|
366
|
+
market_id: options.marketId,
|
|
367
|
+
created_since: iso(options.createdSince),
|
|
368
|
+
limit: options.limit ?? 100,
|
|
369
|
+
cursor,
|
|
370
|
+
};
|
|
371
|
+
const data = await this.call(() => this.api.GET("/v1/resolutions", { params: { query } }));
|
|
372
|
+
return { items: data.data, nextCursor: data.next_cursor ?? null };
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** sk.fees({venue}) lists the fee schedule rows. */
|
|
377
|
+
fees(options: FeesOptions = {}): Paginated<Fee> {
|
|
378
|
+
return new Paginated(async (cursor) => {
|
|
379
|
+
const query: Query<"/v1/fees"> = { venue: options.venue, limit: options.limit ?? 100, cursor };
|
|
380
|
+
const data = await this.call(() => this.api.GET("/v1/fees", { params: { query } }));
|
|
381
|
+
return { items: data.data, nextCursor: data.next_cursor ?? null };
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** sk.venues() lists the venues with their rights and flags. */
|
|
386
|
+
async venues(): Promise<Venue[]> {
|
|
387
|
+
const data = await this.call(() => this.api.GET("/v1/venues"));
|
|
388
|
+
return data.data;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** sk.quoteContext(eventId) reads a matched event's quote context: its active members' tokens, outcome maps and fee rows (one metered data call). */
|
|
392
|
+
quoteContext(eventId: string): Promise<QuoteContext> {
|
|
393
|
+
return this.call(() => this.api.GET("/v1/quote-context/{event_id}", { params: { path: { event_id: eventId } } }));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* sk.quote(eventId, {outcome, side, size}) is the best venue, or split
|
|
398
|
+
* across venues, for size contracts of one outcome once each venue's taker
|
|
399
|
+
* fee is counted, in micro-units: the plan and its legs, every reachable
|
|
400
|
+
* venue alone, the members left out and why, and warnings (rule_mismatch,
|
|
401
|
+
* fee_unknown, partial). One call to Skewtape for the context; the books
|
|
402
|
+
* are read from each venue with a plain fetch that never carries the key.
|
|
403
|
+
* It places nothing. A rule mismatch throws RuleMismatchError unless
|
|
404
|
+
* allowRuleMismatch; no readable book throws VenueUnreachableError.
|
|
405
|
+
*/
|
|
406
|
+
async quote(eventId: string, options: QuoteOptions): Promise<QuoteResult> {
|
|
407
|
+
return quoteFromContext(await this.quoteContext(eventId), options);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* sk.backtest(trades, {asOf}) replays trades the caller supplies and gives
|
|
412
|
+
* their fee-aware P&L (runBacktest, which this feeds). It is arithmetic on
|
|
413
|
+
* history: it forecasts nothing, suggests no trade and optimises nothing.
|
|
414
|
+
* Unless passed in, it reads the fee rows of the trades' venues, their
|
|
415
|
+
* markets and those markets' resolution events (a request per 100
|
|
416
|
+
* markets), and the history window up to each trade without a price, and
|
|
417
|
+
* up to asOf for a market its resolutions do not settle by then, per
|
|
418
|
+
* market. A candle window starts a candle earlier, since a candle prices a
|
|
419
|
+
* time once it has ended. A backtest whose trades have prices and whose
|
|
420
|
+
* markets are settled reads no history. A window with no row at or before
|
|
421
|
+
* a trade's time is a BacktestError price_missing: widen lookbackSeconds
|
|
422
|
+
* or give the price.
|
|
423
|
+
*/
|
|
424
|
+
async backtest(trades: Iterable<Trade>, options: SkBacktestOptions = {}): Promise<BacktestResult> {
|
|
425
|
+
const history = options.history ?? "fills";
|
|
426
|
+
if (history !== "fills" && history !== "candles" && history !== "none") throw new ConfigurationError(`history is fills, candles or none, not ${String(history)}`);
|
|
427
|
+
const candleRes = options.candleRes ?? "1h";
|
|
428
|
+
if (candleRes !== "1m" && candleRes !== "1h" && candleRes !== "1d") throw new ConfigurationError(`candleRes is 1m, 1h or 1d, not ${String(candleRes)}`);
|
|
429
|
+
const list = [...trades];
|
|
430
|
+
const asOf = options.asOf ?? new Date();
|
|
431
|
+
const asOfMicros = parseMicros(asOf, "asOf");
|
|
432
|
+
const lookback = BigInt(Math.round((options.lookbackSeconds ?? 86_400) * 1e6));
|
|
433
|
+
const byVenue = new Map<string, string[]>();
|
|
434
|
+
for (const t of list) {
|
|
435
|
+
const ids = byVenue.get(t.venue) ?? [];
|
|
436
|
+
if (!ids.includes(t.market_id)) ids.push(t.market_id);
|
|
437
|
+
byVenue.set(t.venue, ids);
|
|
438
|
+
}
|
|
439
|
+
let fees = options.fees;
|
|
440
|
+
if (fees === undefined) {
|
|
441
|
+
const rows: FeeRowInput[] = [];
|
|
442
|
+
for (const venue of byVenue.keys()) rows.push(...((await this.fees({ venue }).toArray()) as unknown as FeeRowInput[]));
|
|
443
|
+
fees = rows;
|
|
444
|
+
}
|
|
445
|
+
let markets = options.markets ? [...options.markets] : undefined;
|
|
446
|
+
if (markets === undefined) {
|
|
447
|
+
markets = [];
|
|
448
|
+
for (const [venue, ids] of byVenue) {
|
|
449
|
+
for (let start = 0; start < ids.length; start += 100) {
|
|
450
|
+
markets.push(...((await this.markets({ venue, marketId: ids.slice(start, start + 100) }).toArray()) as unknown as Array<Record<string, unknown>>));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
let resolutions = options.resolutions;
|
|
455
|
+
if (resolutions === undefined) {
|
|
456
|
+
const rows: Array<Record<string, unknown>> = [];
|
|
457
|
+
for (const [venue, ids] of byVenue) {
|
|
458
|
+
for (let start = 0; start < ids.length; start += 100) {
|
|
459
|
+
rows.push(...((await this.resolutions({ venue, marketId: ids.slice(start, start + 100), limit: 1000 }).toArray()) as unknown as Array<Record<string, unknown>>));
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
resolutions = rows;
|
|
463
|
+
}
|
|
464
|
+
const resolutionRows = [...resolutions];
|
|
465
|
+
let fills = options.fills;
|
|
466
|
+
let candles = options.candles;
|
|
467
|
+
if (history !== "none" && (history === "fills" ? fills : candles) === undefined) {
|
|
468
|
+
const rows: Array<Record<string, unknown>> = [];
|
|
469
|
+
const bucket = history === "candles" ? CANDLE_MICROS[candleRes]! : 0n;
|
|
470
|
+
for (const [venue, ids] of byVenue) {
|
|
471
|
+
for (const marketId of ids) {
|
|
472
|
+
const times = list
|
|
473
|
+
.filter((t) => t.venue === venue && t.market_id === marketId && (t.price === undefined || t.price === null) && (t.notional_raw === undefined || t.notional_raw === null))
|
|
474
|
+
.map((t) => parseMicros(t.ts, "trade ts"));
|
|
475
|
+
const own = resolutionRows.filter((r) => r.venue === venue && r.market_id === marketId);
|
|
476
|
+
if (!settledAt(own, asOf)) times.push(asOfMicros);
|
|
477
|
+
for (const [since, until] of windows(times, lookback + bucket)) {
|
|
478
|
+
const page =
|
|
479
|
+
history === "fills"
|
|
480
|
+
? await this.fills({ venue, marketId, since: dateOf(since), until: dateOf(until) }).toArray()
|
|
481
|
+
: await this.candles({ res: candleRes, venue, marketId, since: dateOf(since), until: dateOf(until) }).toArray();
|
|
482
|
+
rows.push(...(page as unknown as Array<Record<string, unknown>>));
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (history === "fills") fills = rows;
|
|
487
|
+
else candles = rows;
|
|
488
|
+
}
|
|
489
|
+
return runBacktest(list, {
|
|
490
|
+
asOf,
|
|
491
|
+
fees,
|
|
492
|
+
markets,
|
|
493
|
+
resolutions: resolutionRows,
|
|
494
|
+
fills: fills ?? [],
|
|
495
|
+
candles: candles ?? [],
|
|
496
|
+
prefer: history === "candles" ? "candles" : "fills",
|
|
497
|
+
...(options.voidPayout !== undefined ? { voidPayout: options.voidPayout } : {}),
|
|
498
|
+
...(options.onMissingFee !== undefined ? { onMissingFee: options.onMissingFee } : {}),
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* sk.stream({topics}) is the live feed (Builder and Pro), an async iterable
|
|
504
|
+
* of the server's messages that reconnects by itself: it resumes from the
|
|
505
|
+
* last seq it yielded, so nothing is missed or sent twice, and drops a
|
|
506
|
+
* trade it already yielded. venues, markets and events filter as the feed's
|
|
507
|
+
* subscribe does; resumeFrom starts from a seq kept earlier; maxReconnects
|
|
508
|
+
* bounds the failed connections in a row. It uses the platform's WebSocket;
|
|
509
|
+
* on Node 20 pass one (the ws package's): {WebSocket}.
|
|
510
|
+
*/
|
|
511
|
+
stream(options: StreamOptions): Stream {
|
|
512
|
+
// The client's own sleep only when one was given (tests): the stream's
|
|
513
|
+
// default is a timer close() clears.
|
|
514
|
+
return new Stream(feedUrl(this.baseUrl), this.#apiKey, options, this.userSleep);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* sk.kalshi() is the optional live Kalshi client, under the user's own
|
|
519
|
+
* Kalshi membership ({accessKey, privateKey} sign its calls; without them
|
|
520
|
+
* they are public requests). It calls Kalshi's host from this machine and
|
|
521
|
+
* shares nothing with this client, not the API key: Skewtape's Kalshi data
|
|
522
|
+
* ships from sk.markets, sk.fills, sk.candles and sk.resolutions, under the
|
|
523
|
+
* Kalshi data licence; this is a reading of the live venue beside it.
|
|
524
|
+
*/
|
|
525
|
+
kalshi(options: KalshiOptions = {}): Kalshi {
|
|
526
|
+
return new Kalshi(options);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** sk.route: an unsigned order with your own code or fee (route.ts); it sends nothing, the API key included. */
|
|
530
|
+
readonly route = route;
|
|
531
|
+
/** sk.geoblock: the venues' own checks (geoblock.ts); they never send the API key. */
|
|
532
|
+
readonly geoblock = geoblock;
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* The History snapshot and the monthly deltas, file by file, with an API key
|
|
536
|
+
* on the Builder or Pro plan (a History purchase downloads from the
|
|
537
|
+
* dashboard; a key on Free or History is a ForbiddenPlanError naming
|
|
538
|
+
* builder):
|
|
539
|
+
* - sk.download.bundles() lists the bundles the account may download, each
|
|
540
|
+
* with its files' paths, sizes and sha256 (GET /v1/bundles);
|
|
541
|
+
* - sk.download.url(bundle, path) is a file's link, valid for an hour and
|
|
542
|
+
* logged against the account (POST /v1/downloads/{bundle}/url);
|
|
543
|
+
* - sk.download.file(bundle, path, dest) fetches that link to dest, resuming
|
|
544
|
+
* a partial download and checking the sha256;
|
|
545
|
+
* - sk.download.bundle(bundle, folder) does that for every file, skipping
|
|
546
|
+
* those already there, then checks the folder against its
|
|
547
|
+
* CHECKSUMS.sha256;
|
|
548
|
+
* - sk.download(url, dest, {sha256}) fetches a link already in hand, such as
|
|
549
|
+
* one the dashboard gave, and sk.download.verify(folder) checks a folder.
|
|
550
|
+
* A link carries no key: files are fetched with a plain fetch (options.fetch
|
|
551
|
+
* to pass one), so the file host never sees the API key.
|
|
552
|
+
*/
|
|
553
|
+
readonly download = Object.assign(
|
|
554
|
+
(url: string, dest: string, options: DownloadOptions = {}): Promise<string> => downloadFile(url, dest, options),
|
|
555
|
+
{
|
|
556
|
+
verify: (folder: string): Promise<string[]> => verifyChecksums(folder),
|
|
557
|
+
bundles: async (): Promise<Bundle[]> => (await this.call(() => this.api.GET("/v1/bundles"))).bundles,
|
|
558
|
+
url: (bundle: string, path: string): Promise<DownloadURL> =>
|
|
559
|
+
this.call(() => this.api.POST("/v1/downloads/{bundle}/url", { params: { path: { bundle } }, body: { path } })),
|
|
560
|
+
file: async (bundle: string, path: string, dest: string, options: DownloadOptions = {}): Promise<string> => {
|
|
561
|
+
const sha256 = options.sha256 ?? (await this.bundleFile(bundle, path)).sha256;
|
|
562
|
+
if (await holds(dest, sha256)) return dest;
|
|
563
|
+
const link = await this.download.url(bundle, path);
|
|
564
|
+
return downloadFile(link.url, dest, { ...options, sha256 });
|
|
565
|
+
},
|
|
566
|
+
bundle: async (bundle: string, folder: string, options: BundleDownloadOptions = {}): Promise<string> => {
|
|
567
|
+
const root = resolve(folder);
|
|
568
|
+
for (const f of (await this.findBundle(bundle)).files) {
|
|
569
|
+
const dest = resolve(root, f.path);
|
|
570
|
+
if (!dest.startsWith(root + sep)) throw new SkewtapeError(`${bundle} lists ${f.path}, a path outside the folder`);
|
|
571
|
+
const progress = options.onProgress;
|
|
572
|
+
await this.download.file(bundle, f.path, dest, {
|
|
573
|
+
sha256: f.sha256,
|
|
574
|
+
fetch: options.fetch,
|
|
575
|
+
onProgress: progress && ((done, total) => progress(f.path, done, total)),
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
await verifyChecksums(root);
|
|
579
|
+
return root;
|
|
580
|
+
},
|
|
581
|
+
},
|
|
582
|
+
);
|
|
583
|
+
|
|
584
|
+
private async findBundle(bundle: string): Promise<Bundle> {
|
|
585
|
+
const found = (await this.download.bundles()).find((b) => b.id === bundle);
|
|
586
|
+
if (!found) throw new NotFoundError(`${bundle} is not among the bundles this account may download`, { status: 404 });
|
|
587
|
+
return found;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
private async bundleFile(bundle: string, path: string): Promise<BundleFile> {
|
|
591
|
+
const found = (await this.findBundle(bundle)).files.find((f) => f.path === path);
|
|
592
|
+
if (!found) throw new NotFoundError(`${bundle} lists no file ${path}`, { status: 404 });
|
|
593
|
+
return found;
|
|
594
|
+
}
|
|
595
|
+
}
|