skewtape 0.0.0-stage → 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 +181 -2
  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 +46 -4
  77. package/src/backtest.ts +490 -0
  78. package/src/client.ts +595 -0
  79. package/src/download.ts +161 -0
  80. package/src/errors.ts +143 -0
  81. package/src/exact.ts +159 -0
  82. package/src/fees.ts +189 -0
  83. package/src/generated/schema.d.ts +2500 -0
  84. package/src/geoblock.ts +90 -0
  85. package/src/index.ts +146 -0
  86. package/src/kalshi.ts +563 -0
  87. package/src/keccak.ts +82 -0
  88. package/src/msgpack.ts +83 -0
  89. package/src/paginated.ts +51 -0
  90. package/src/quote-math.ts +555 -0
  91. package/src/quote.ts +324 -0
  92. package/src/route-hyperliquid.ts +457 -0
  93. package/src/route.ts +631 -0
  94. package/src/stream.ts +539 -0
  95. package/src/version.ts +6 -0
@@ -0,0 +1,410 @@
1
+ "use strict";
2
+ /**
3
+ * Fee-aware P&L for a list of trades the caller supplies, over the history
4
+ * Skewtape records (story E4).
5
+ *
6
+ * This is arithmetic on history. Each trade is priced at its own price, or at
7
+ * the last recorded fill or candle at or before its time; the fee the schedule
8
+ * in force charges is taken off; every position is then valued at the outcome
9
+ * its market resolved to, or, still open, at the last recorded price at or
10
+ * before asOf. Nothing is read from after asOf. It forecasts nothing, suggests
11
+ * no trade and optimises nothing: the result is what these trades come to on
12
+ * the record, before and after fees.
13
+ *
14
+ * Amounts are exact bigints in raw units (a position's at its fill decimals,
15
+ * totals at the largest decimals among the positions); prices are exact
16
+ * fractions, shown as decimal strings when they end. conformance/backtest.json
17
+ * pins the arithmetic, and the Python and TypeScript SDKs pass the same vectors.
18
+ *
19
+ * import { runBacktest } from "skewtape";
20
+ * const result = runBacktest(trades, { asOf, fees, markets, resolutions, fills });
21
+ * console.log(result.totals.pnl_raw, result.totals.fees_raw);
22
+ *
23
+ * sk.backtest(trades) fetches the fees, markets, resolutions and price history
24
+ * for the trades first, then runs the same function.
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.BacktestError = exports.CANDLE_MICROS = void 0;
28
+ exports.runBacktest = runBacktest;
29
+ exports.settledAt = settledAt;
30
+ exports.backtestToJSON = backtestToJSON;
31
+ const errors_js_1 = require("./errors.js");
32
+ const exact_js_1 = require("./exact.js");
33
+ const fees_js_1 = require("./fees.js");
34
+ exports.CANDLE_MICROS = { "1m": 60000000n, "1h": 3600000000n, "1d": 86400000000n };
35
+ /** A backtest that cannot run as asked; code says why: bad_trade, after_as_of, price_missing, fee_row_missing, decimals_mismatch. */
36
+ class BacktestError extends errors_js_1.SkewtapeError {
37
+ constructor(message, code, fields = {}) {
38
+ super(message, { ...fields, code });
39
+ }
40
+ }
41
+ exports.BacktestError = BacktestError;
42
+ const TRADE_FIELDS = new Set(["venue", "market_id", "token_id", "side", "ts", "size", "size_raw", "price", "notional_raw", "role", "decimals", "fee_category"]);
43
+ function keyOf(venue, marketId, tokenId) {
44
+ return JSON.stringify([venue, marketId, tokenId]);
45
+ }
46
+ function wrap(run) {
47
+ try {
48
+ return run();
49
+ }
50
+ catch (err) {
51
+ if (err instanceof BacktestError)
52
+ throw err;
53
+ if (err instanceof errors_js_1.SkewtapeError)
54
+ throw new BacktestError(err.message, "bad_trade");
55
+ throw err;
56
+ }
57
+ }
58
+ function optMicros(v) {
59
+ if (v === null || v === undefined || v === "")
60
+ return null;
61
+ return wrap(() => (0, exact_js_1.parseMicros)(v, "time"));
62
+ }
63
+ function lastAtOrBefore(rows, t) {
64
+ if (!rows || rows.length === 0)
65
+ return undefined;
66
+ let lo = 0;
67
+ let hi = rows.length;
68
+ while (lo < hi) {
69
+ const mid = (lo + hi) >> 1;
70
+ if (rows[mid].at <= t)
71
+ lo = mid + 1;
72
+ else
73
+ hi = mid;
74
+ }
75
+ return lo ? rows[lo - 1] : undefined;
76
+ }
77
+ /**
78
+ * Replay trades over the history given and value every position at asOf. See
79
+ * the module comment; the arithmetic is the Python SDK's, vector for vector.
80
+ */
81
+ function runBacktest(trades, options) {
82
+ const asOf = wrap(() => (0, exact_js_1.parseMicros)(options.asOf, "as_of"));
83
+ const prefer = options.prefer ?? "fills";
84
+ if (prefer !== "fills" && prefer !== "candles")
85
+ throw new BacktestError(`prefer is fills or candles, not ${String(prefer)}`, "bad_trade");
86
+ const onMissingFee = options.onMissingFee ?? "error";
87
+ if (onMissingFee !== "error" && onMissingFee !== "zero")
88
+ throw new BacktestError(`onMissingFee is error or zero, not ${String(onMissingFee)}`, "bad_trade");
89
+ const voidPayout = options.voidPayout === undefined || options.voidPayout === null ? null : wrap(() => (0, exact_js_1.parseRat)(options.voidPayout, "void_payout"));
90
+ if (voidPayout && (voidPayout.n < 0n || voidPayout.cmp(new exact_js_1.Rat(1n)) > 0))
91
+ throw new BacktestError("void_payout is between 0 and 1", "bad_trade");
92
+ const feeRows = wrap(() => [...options.fees].map(fees_js_1.feeRowOf));
93
+ const marketBy = new Map();
94
+ for (const m of options.markets ?? [])
95
+ marketBy.set(JSON.stringify([String(m.venue), String(m.market_id)]), m);
96
+ const resBy = new Map();
97
+ for (const r of options.resolutions ?? []) {
98
+ const k = JSON.stringify([String(r.venue), String(r.market_id)]);
99
+ resBy.set(k, [...(resBy.get(k) ?? []), r]);
100
+ }
101
+ const byFill = new Map();
102
+ for (const f of options.fills ?? []) {
103
+ if (f.blocked === true)
104
+ continue;
105
+ if (f.size_raw === undefined || f.size_raw === null || f.notional_raw === undefined || f.notional_raw === null)
106
+ continue;
107
+ const size = wrap(() => (0, exact_js_1.parseInt64)(f.size_raw, "fill size_raw"));
108
+ const notional = wrap(() => (0, exact_js_1.parseInt64)(f.notional_raw, "fill notional_raw"));
109
+ if (size <= 0n)
110
+ continue;
111
+ const k = keyOf(String(f.venue), String(f.market_id), String(f.token_id));
112
+ byFill.set(k, [...(byFill.get(k) ?? []), { at: wrap(() => (0, exact_js_1.parseMicros)(f.ts, "fill ts")), price: new exact_js_1.Rat(notional, size), decimals: typeof f.decimals === "number" ? f.decimals : null, source: "fill" }]);
113
+ }
114
+ const byCandle = new Map();
115
+ for (const c of options.candles ?? []) {
116
+ const len = exports.CANDLE_MICROS[String(c.res)];
117
+ if (len === undefined || c.close === null || c.close === undefined)
118
+ continue;
119
+ const k = keyOf(String(c.venue), String(c.market_id), String(c.token_id));
120
+ const end = wrap(() => (0, exact_js_1.parseMicros)(c.ts, "candle ts")) + len;
121
+ byCandle.set(k, [...(byCandle.get(k) ?? []), { at: end, price: wrap(() => (0, exact_js_1.parseRat)(c.close, "candle close")), decimals: typeof c.decimals === "number" ? c.decimals : null, source: "candle" }]);
122
+ }
123
+ for (const table of [byFill, byCandle])
124
+ for (const rows of table.values())
125
+ rows.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
126
+ const historyPrice = (k, t) => {
127
+ const [first, second] = prefer === "fills" ? [byFill, byCandle] : [byCandle, byFill];
128
+ return lastAtOrBefore(first.get(k), t) ?? lastAtOrBefore(second.get(k), t);
129
+ };
130
+ const anyDecimals = (k) => {
131
+ for (const table of [byFill, byCandle])
132
+ for (const p of table.get(k) ?? [])
133
+ if (p.decimals !== null)
134
+ return p.decimals;
135
+ return null;
136
+ };
137
+ const parsed = [];
138
+ let i = 0;
139
+ for (const raw of trades) {
140
+ const t = raw;
141
+ const unknown = Object.keys(t).filter((k) => !TRADE_FIELDS.has(k));
142
+ if (unknown.length)
143
+ throw new BacktestError(`a trade has unknown fields ${JSON.stringify(unknown.sort())}`, "bad_trade");
144
+ const missing = ["venue", "market_id", "token_id", "side", "ts"].filter((k) => t[k] === undefined || t[k] === null || t[k] === "");
145
+ if (missing.length)
146
+ throw new BacktestError(`a trade needs ${JSON.stringify(missing)}`, "bad_trade");
147
+ if (t.side !== "buy" && t.side !== "sell")
148
+ throw new BacktestError(`trade ${i}: side is buy or sell, not ${t.side}`, "bad_trade");
149
+ const role = t.role ?? "taker";
150
+ if (role !== "taker" && role !== "maker")
151
+ throw new BacktestError(`trade ${i}: role is taker or maker, not ${role}`, "bad_trade");
152
+ if ((t.size === undefined || t.size === null) === (t.size_raw === undefined || t.size_raw === null))
153
+ throw new BacktestError(`trade ${i}: give size or size_raw, one of them`, "bad_trade");
154
+ if (t.price !== undefined && t.price !== null && t.notional_raw !== undefined && t.notional_raw !== null)
155
+ throw new BacktestError(`trade ${i}: give price or notional_raw, not both`, "bad_trade");
156
+ const at = i;
157
+ parsed.push({ i, t, ts: wrap(() => (0, exact_js_1.parseMicros)(t.ts, `trade ${at} ts`)) });
158
+ i++;
159
+ }
160
+ parsed.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.i - b.i));
161
+ const warnings = [];
162
+ const missingFee = [];
163
+ const withheld = [];
164
+ const results = [];
165
+ const positions = new Map();
166
+ for (const { i: idx, t, ts } of parsed) {
167
+ if (ts > asOf)
168
+ throw new BacktestError(`trade ${idx} at ${(0, exact_js_1.isoMicros)(ts)} is after as_of ${(0, exact_js_1.isoMicros)(asOf)}`, "after_as_of");
169
+ const role = t.role ?? "taker";
170
+ const k = keyOf(t.venue, t.market_id, t.token_id);
171
+ const hasPrice = t.price !== undefined && t.price !== null;
172
+ const hasNotional = t.notional_raw !== undefined && t.notional_raw !== null;
173
+ let hist;
174
+ if (!hasPrice && !hasNotional) {
175
+ hist = historyPrice(k, ts);
176
+ if (!hist)
177
+ throw new BacktestError(`trade ${idx}: no price given and no fill or candle of ${t.venue} ${t.market_id} ${t.token_id} at or before ${(0, exact_js_1.isoMicros)(ts)}`, "price_missing");
178
+ }
179
+ const decimals = t.decimals ?? (hist && hist.decimals !== null ? hist.decimals : anyDecimals(k)) ?? fees_js_1.COLLATERAL_MICROS_DECIMALS;
180
+ let sizeRaw;
181
+ if (t.size_raw !== undefined && t.size_raw !== null) {
182
+ sizeRaw = wrap(() => (0, exact_js_1.parseInt64)(t.size_raw, `trade ${idx} size_raw`));
183
+ }
184
+ else {
185
+ const shares = wrap(() => (0, exact_js_1.parseRat)(t.size, `trade ${idx} size`)).mul(new exact_js_1.Rat(10n ** BigInt(decimals)));
186
+ if (!shares.isInt())
187
+ throw new BacktestError(`trade ${idx}: size ${String(t.size)} has more places than ${decimals} decimals hold`, "bad_trade");
188
+ sizeRaw = shares.n;
189
+ }
190
+ if (sizeRaw <= 0n)
191
+ throw new BacktestError(`trade ${idx}: the size must be positive`, "bad_trade");
192
+ let notionalRaw;
193
+ let price;
194
+ let source;
195
+ if (hasNotional) {
196
+ notionalRaw = wrap(() => (0, exact_js_1.parseInt64)(t.notional_raw, `trade ${idx} notional_raw`));
197
+ price = new exact_js_1.Rat(notionalRaw, sizeRaw);
198
+ source = "notional";
199
+ }
200
+ else {
201
+ price = hasPrice ? wrap(() => (0, exact_js_1.parseRat)(t.price, `trade ${idx} price`)) : hist.price;
202
+ source = hasPrice ? "given" : hist.source;
203
+ notionalRaw = (0, exact_js_1.roundHalfUp)(price.mul(new exact_js_1.Rat(sizeRaw)));
204
+ }
205
+ if (notionalRaw < 0n || notionalRaw > sizeRaw || price.n < 0n || price.cmp(new exact_js_1.Rat(1n)) > 0)
206
+ throw new BacktestError(`trade ${idx}: the price must be between 0 and 1`, "bad_trade");
207
+ const market = marketBy.get(JSON.stringify([t.venue, t.market_id]));
208
+ const category = t.fee_category !== undefined && t.fee_category !== null ? t.fee_category : market ? (market.fee_category ?? null) : null;
209
+ const row = (0, fees_js_1.selectFeeRow)(feeRows, t.venue, category, ts);
210
+ let fee;
211
+ if (!row) {
212
+ if (onMissingFee === "error") {
213
+ missingFee.push(idx);
214
+ if (category === null && market && market.blocked === true)
215
+ withheld.push(idx);
216
+ continue;
217
+ }
218
+ fee = 0n;
219
+ warnings.push({ code: "fee_row_missing", message: `no fee row covers ${t.venue} category ${category} at ${(0, exact_js_1.isoMicros)(ts)}: its fee is counted as zero`, trade: idx, position: null });
220
+ }
221
+ else {
222
+ fee = wrap(() => (role === "taker" ? fees_js_1.takerFeeRaw : fees_js_1.makerFeeRaw)(row, sizeRaw, notionalRaw, decimals));
223
+ }
224
+ let pos = positions.get(k);
225
+ if (!pos) {
226
+ pos = { venue: t.venue, market_id: t.market_id, token_id: t.token_id, decimals, shares: 0n, bought: 0n, sold: 0n, fees: 0n, cash: 0n };
227
+ positions.set(k, pos);
228
+ }
229
+ if (pos.decimals !== decimals)
230
+ throw new BacktestError(`trade ${idx}: ${decimals} decimals, where this position's other trades have ${pos.decimals}`, "decimals_mismatch");
231
+ let cash;
232
+ if (t.side === "buy") {
233
+ cash = -notionalRaw - fee;
234
+ pos.shares += sizeRaw;
235
+ pos.bought += notionalRaw;
236
+ }
237
+ else {
238
+ cash = notionalRaw - fee;
239
+ pos.shares -= sizeRaw;
240
+ pos.sold += notionalRaw;
241
+ if (pos.shares < 0n)
242
+ warnings.push({ code: "oversold", message: `trade ${idx} sells more ${t.token_id} than the trades before it bought`, trade: idx, position: null });
243
+ }
244
+ pos.fees += fee;
245
+ pos.cash += cash;
246
+ const state = resolutionState(resBy.get(JSON.stringify([t.venue, t.market_id])) ?? [], ts);
247
+ if (state && (state.event_type === "resolved" || state.event_type === "voided")) {
248
+ warnings.push({ code: "trade_after_resolution", message: `trade ${idx} is after its market's ${String(state.event_type)} event`, trade: idx, position: null });
249
+ }
250
+ results.push({
251
+ index: idx,
252
+ venue: t.venue,
253
+ market_id: t.market_id,
254
+ token_id: t.token_id,
255
+ side: t.side,
256
+ role,
257
+ ts: (0, exact_js_1.isoMicros)(ts),
258
+ decimals,
259
+ size_raw: sizeRaw,
260
+ notional_raw: notionalRaw,
261
+ price: (0, exact_js_1.fractionStr)(price),
262
+ price_source: source,
263
+ fee_raw: fee,
264
+ fee_category: row ? row.category : null,
265
+ fee_row_effective_from: row ? (0, exact_js_1.isoMicros)(row.effectiveFrom) : null,
266
+ cash_raw: cash,
267
+ });
268
+ }
269
+ if (missingFee.length) {
270
+ const why = withheld.length ? ` (the data policy withholds the fee_category of the markets of trades ${JSON.stringify(withheld)})` : "";
271
+ throw new BacktestError(`no fee row covers trades ${JSON.stringify(missingFee)}${why}: pass fee_category on the trade, the fee rows that apply, or onMissingFee "zero"`, "fee_row_missing");
272
+ }
273
+ const outPositions = [];
274
+ for (const [k, pos] of positions) {
275
+ const market = marketBy.get(JSON.stringify([pos.venue, pos.market_id]));
276
+ const state = resolutionState(resBy.get(JSON.stringify([pos.venue, pos.market_id])) ?? [], asOf);
277
+ const event = state ? String(state.event_type) : null;
278
+ let status = "open";
279
+ let outcome = null;
280
+ let payout = null;
281
+ let mark = null;
282
+ let valueSource = null;
283
+ let value = null;
284
+ const tuple = [pos.venue, pos.market_id, pos.token_id];
285
+ if (event === "resolved" && state.outcome !== null && state.outcome !== undefined) {
286
+ outcome = String(state.outcome);
287
+ const token = tokenForOutcome(outcome, market, pos.token_id);
288
+ if (token === null) {
289
+ status = "resolved";
290
+ warnings.push({ code: "outcome_unmatched", message: `${pos.venue} ${pos.market_id} resolved to ${outcome}, which no outcome of the market names: pass the market`, trade: null, position: tuple });
291
+ }
292
+ else {
293
+ status = "resolved";
294
+ payout = new exact_js_1.Rat(token === pos.token_id ? 1n : 0n);
295
+ valueSource = "resolution";
296
+ }
297
+ }
298
+ else if (event === "voided") {
299
+ status = "voided";
300
+ if (voidPayout === null) {
301
+ warnings.push({ code: "voided_unsettled", message: `${pos.venue} ${pos.market_id} was voided: pass void_payout to value it`, trade: null, position: tuple });
302
+ }
303
+ else {
304
+ payout = voidPayout;
305
+ valueSource = "void_payout";
306
+ }
307
+ }
308
+ if (payout !== null) {
309
+ value = (0, exact_js_1.roundHalfUp)(payout.mul(new exact_js_1.Rat(pos.shares)));
310
+ }
311
+ else if (status === "open") {
312
+ const hist = historyPrice(k, asOf);
313
+ if (!hist) {
314
+ warnings.push({ code: "no_mark", message: `no fill or candle of ${pos.venue} ${pos.market_id} ${pos.token_id} at or before as_of values this open position`, trade: null, position: tuple });
315
+ }
316
+ else {
317
+ mark = hist.price;
318
+ valueSource = "mark";
319
+ value = (0, exact_js_1.roundHalfUp)(mark.mul(new exact_js_1.Rat(pos.shares)));
320
+ }
321
+ }
322
+ const pnl = value === null ? null : pos.cash + value;
323
+ outPositions.push({
324
+ venue: pos.venue,
325
+ market_id: pos.market_id,
326
+ token_id: pos.token_id,
327
+ decimals: pos.decimals,
328
+ shares_raw: pos.shares,
329
+ bought_raw: pos.bought,
330
+ sold_raw: pos.sold,
331
+ fees_raw: pos.fees,
332
+ cash_raw: pos.cash,
333
+ status,
334
+ outcome,
335
+ payout: payout === null ? null : (0, exact_js_1.fractionStr)(payout),
336
+ mark_price: mark === null ? null : (0, exact_js_1.fractionStr)(mark),
337
+ value_raw: value,
338
+ value_source: valueSource,
339
+ pnl_raw: pnl,
340
+ pnl_before_fees_raw: pnl === null ? null : pnl + pos.fees,
341
+ });
342
+ }
343
+ const top = outPositions.reduce((m, p) => Math.max(m, p.decimals), outPositions.length ? 0 : fees_js_1.COLLATERAL_MICROS_DECIMALS);
344
+ const scaled = (p, v) => v * 10n ** BigInt(top - p.decimals);
345
+ const valued = outPositions.filter((p) => p.pnl_raw !== null);
346
+ const sum = (ps, f) => ps.reduce((s, p) => s + scaled(p, f(p)), 0n);
347
+ const totals = {
348
+ decimals: top,
349
+ pnl_raw: sum(valued, (p) => p.pnl_raw),
350
+ pnl_before_fees_raw: sum(valued, (p) => p.pnl_before_fees_raw),
351
+ fees_raw: sum(valued, (p) => p.fees_raw),
352
+ fees_paid_raw: sum(outPositions, (p) => p.fees_raw),
353
+ realized_pnl_raw: sum(valued.filter((p) => p.value_source !== "mark"), (p) => p.pnl_raw),
354
+ unrealized_pnl_raw: sum(valued.filter((p) => p.value_source === "mark"), (p) => p.pnl_raw),
355
+ complete: valued.length === outPositions.length,
356
+ };
357
+ results.sort((a, b) => a.index - b.index);
358
+ return { as_of: (0, exact_js_1.isoMicros)(asOf), trades: results, positions: outPositions, totals, warnings };
359
+ }
360
+ /** The market's resolution event in force at t: the highest seq whose time (resolved_at, else created_at) is at or before t. */
361
+ function resolutionState(rows, t) {
362
+ let best;
363
+ let bestSeq = -Infinity;
364
+ for (const r of rows) {
365
+ const at = optMicros(r.resolved_at) ?? optMicros(r.created_at);
366
+ if (at === null || at > t)
367
+ continue;
368
+ const seq = Number(r.seq ?? 0);
369
+ if (best === undefined || seq > bestSeq) {
370
+ best = r;
371
+ bestSeq = seq;
372
+ }
373
+ }
374
+ return best;
375
+ }
376
+ /**
377
+ * Whether a market's resolution events settle its positions at asOf, so they
378
+ * need no mark: resolved to an outcome, or voided (valued by voidPayout, or
379
+ * left unvalued with a warning). sk.backtest reads the asOf window only for
380
+ * markets this is false for.
381
+ */
382
+ function settledAt(rows, asOf) {
383
+ const state = resolutionState([...rows], (0, exact_js_1.parseMicros)(asOf, "asOf"));
384
+ const event = state ? String(state.event_type) : null;
385
+ return (event === "resolved" && state.outcome !== null && state.outcome !== undefined) || event === "voided";
386
+ }
387
+ /** The token an outcome names: a token_id of the market, else the one outcome whose label it is; with no market, only the position's own token. */
388
+ function tokenForOutcome(outcome, market, tokenId) {
389
+ if (!market)
390
+ return outcome === tokenId ? outcome : null;
391
+ const outcomes = market.outcomes ?? [];
392
+ const tokens = outcomes.map((o) => String(o.token_id));
393
+ if (tokens.includes(outcome))
394
+ return outcome;
395
+ const labelled = outcomes.filter((o) => String(o.label) === outcome).map((o) => String(o.token_id));
396
+ return labelled.length === 1 ? labelled[0] : null;
397
+ }
398
+ /** A result with every bigint as a number, for JSON: the shape of the Python SDK's to_dict(). An amount past 2^53 stays a decimal string. */
399
+ function backtestToJSON(result) {
400
+ const conv = (v) => {
401
+ if (typeof v === "bigint")
402
+ return v >= BigInt(Number.MIN_SAFE_INTEGER) && v <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : v.toString();
403
+ if (Array.isArray(v))
404
+ return v.map(conv);
405
+ if (v !== null && typeof v === "object")
406
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, conv(x)]));
407
+ return v;
408
+ };
409
+ return conv(result);
410
+ }
@@ -0,0 +1,255 @@
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
+ import { type BacktestResult, type Trade } from "./backtest.js";
16
+ import { type DownloadOptions } from "./download.js";
17
+ import { Stream, type StreamOptions } from "./stream.js";
18
+ import { route } from "./route.js";
19
+ import type { components } from "./generated/schema.js";
20
+ import type { FeeRowInput } from "./fees.js";
21
+ import { Kalshi, type KalshiOptions } from "./kalshi.js";
22
+ import { Paginated } from "./paginated.js";
23
+ import { type QuoteContext, type QuoteOptions } from "./quote.js";
24
+ import type { QuoteResult } from "./quote-math.js";
25
+ export { Paginated, type Page } from "./paginated.js";
26
+ export declare const DEFAULT_BASE_URL = "https://api.skewtape.com";
27
+ export declare const ENV_API_KEY = "SKEWTAPE_API_KEY";
28
+ type Schemas = components["schemas"];
29
+ export type Market = Schemas["Market"];
30
+ export type MatchedEvent = Schemas["MatchedEvent"];
31
+ export type MatchedEventMember = Schemas["MatchedEventMember"];
32
+ export type Fill = Schemas["Fill"];
33
+ export type Candle = Schemas["Candle"];
34
+ export type Resolution = Schemas["Resolution"];
35
+ export type Fee = Schemas["Fee"];
36
+ export type Venue = Schemas["Venue"];
37
+ export type Bundle = Schemas["Bundle"];
38
+ export type BundleFile = Schemas["BundleFile"];
39
+ export type DownloadURL = Schemas["DownloadURL"];
40
+ /** Options of sk.download.bundle: the plain fetch for the files, and progress per file. */
41
+ export interface BundleDownloadOptions {
42
+ /** The fetch for the files (the global one by default). The file host never sees the API key. */
43
+ fetch?: typeof fetch | undefined;
44
+ /** Called after each chunk with the file's path, the bytes so far and its size. */
45
+ onProgress?: ((path: string, done: number, total: number | undefined) => void) | undefined;
46
+ }
47
+ export interface SkewtapeOptions {
48
+ /** The API key; SKEWTAPE_API_KEY when left out. */
49
+ apiKey?: string;
50
+ baseUrl?: string;
51
+ /** How many times a 429 rate_limited is retried, after the server's Retry-After. Three by default. */
52
+ maxRetries?: number;
53
+ /** How long one request may take, in seconds; 30 by default. A request past it throws a SkewtapeError. */
54
+ timeout?: number;
55
+ /** The fetch to use; the global one by default. */
56
+ fetch?: typeof fetch;
57
+ /** How to wait, in seconds; a timer by default. Tests inject their own. */
58
+ sleep?: (seconds: number) => Promise<void>;
59
+ }
60
+ export interface MarketsOptions {
61
+ venue?: string;
62
+ marketId?: string[];
63
+ updatedSince?: Date | string;
64
+ /**
65
+ * Keeps the markets whose status is (or is not) resolved; applied on the
66
+ * client, so every page is still fetched, each a metered call: pass a venue
67
+ * or marketId with it. TODO(decision): a server-side status filter on
68
+ * /v1/markets would make it one request per page of results.
69
+ */
70
+ resolved?: boolean;
71
+ limit?: number;
72
+ }
73
+ export interface EventsOptions {
74
+ minConfidence?: number;
75
+ resolutionEqual?: boolean;
76
+ venue?: string;
77
+ status?: "approved" | "needs_rereview" | "retired";
78
+ limit?: number;
79
+ }
80
+ export interface FillsOptions {
81
+ since: Date | string;
82
+ /** Now by default. */
83
+ until?: Date | string;
84
+ venue?: string;
85
+ marketId?: string;
86
+ eventId?: string;
87
+ /** maker by default. */
88
+ leg?: "maker" | "taker" | "all";
89
+ limit?: number;
90
+ }
91
+ export interface CandlesOptions {
92
+ res: "1m" | "1h" | "1d";
93
+ since: Date | string;
94
+ until?: Date | string;
95
+ venue?: string;
96
+ marketId?: string;
97
+ eventId?: string;
98
+ limit?: number;
99
+ }
100
+ export interface ResolutionsOptions {
101
+ venue?: string;
102
+ /** Up to 100 market ids. */
103
+ marketId?: string[];
104
+ createdSince?: Date | string;
105
+ limit?: number;
106
+ }
107
+ export interface FeesOptions {
108
+ venue?: string;
109
+ limit?: number;
110
+ }
111
+ /**
112
+ * Options of sk.backtest: asOf (now by default), the history that prices
113
+ * trades without a price and marks open positions (fills by default, Builder
114
+ * and Pro; candles at candleRes, 1h by default, any size on Builder and Pro
115
+ * and Polymarket 1d only on Free and History; none), the window looked back
116
+ * before each such time (a day by default), voidPayout and onMissingFee as
117
+ * in runBacktest, and any of the inputs to use instead of fetching them.
118
+ */
119
+ export interface SkBacktestOptions {
120
+ asOf?: Date | string;
121
+ history?: "fills" | "candles" | "none";
122
+ candleRes?: "1m" | "1h" | "1d";
123
+ lookbackSeconds?: number;
124
+ voidPayout?: string | number;
125
+ onMissingFee?: "error" | "zero";
126
+ fees?: Iterable<FeeRowInput>;
127
+ markets?: Iterable<Record<string, unknown>>;
128
+ resolutions?: Iterable<Record<string, unknown>>;
129
+ fills?: Iterable<Record<string, unknown>>;
130
+ candles?: Iterable<Record<string, unknown>>;
131
+ }
132
+ /** How many of an event's members are active. */
133
+ export declare function activeMembers(event: MatchedEvent): number;
134
+ export declare class Skewtape {
135
+ #private;
136
+ readonly baseUrl: string;
137
+ readonly maxRetries: number;
138
+ readonly timeout: number;
139
+ private readonly api;
140
+ private readonly sleep;
141
+ private readonly userSleep;
142
+ constructor(options?: SkewtapeOptions);
143
+ /**
144
+ * Run one request: a 429 whose envelope says rate_limited (or carries no
145
+ * envelope, as a proxy's would) retried up to maxRetries times after the
146
+ * server's Retry-After (one second without it); a 2xx returned as parsed;
147
+ * anything else, a quota_exceeded 429 included, thrown at once from the
148
+ * error envelope. A request past the timeout is a SkewtapeError.
149
+ */
150
+ private call;
151
+ /** sk.markets({venue, resolved}) lists markets; sk.markets.get(venue, marketId) reads one. */
152
+ readonly markets: ((options?: MarketsOptions) => Paginated<Market>) & {
153
+ get: (venue: string, marketId: string) => Promise<Market>;
154
+ };
155
+ /** sk.events({minConfidence, resolutionEqual}) lists matched events; sk.events.get(eventId) reads one. */
156
+ readonly events: ((options?: EventsOptions) => Paginated<MatchedEvent>) & {
157
+ get: (eventId: string) => Promise<MatchedEvent>;
158
+ };
159
+ /** 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. */
160
+ readonly pairs: ((options?: EventsOptions) => Paginated<MatchedEvent>) & {
161
+ get: (eventId: string) => Promise<MatchedEvent>;
162
+ };
163
+ private eventsPage;
164
+ /** sk.fills({eventId, since}) lists fills from since to until (now by default), maker legs by default. */
165
+ fills(options: FillsOptions): Paginated<Fill>;
166
+ /** sk.candles({res, since}) lists candles of one size from since to until. */
167
+ candles(options: CandlesOptions): Paginated<Candle>;
168
+ /** sk.resolutions({venue, marketId, createdSince}) lists resolution events, of up to 100 markets when marketId is given. */
169
+ resolutions(options?: ResolutionsOptions): Paginated<Resolution>;
170
+ /** sk.fees({venue}) lists the fee schedule rows. */
171
+ fees(options?: FeesOptions): Paginated<Fee>;
172
+ /** sk.venues() lists the venues with their rights and flags. */
173
+ venues(): Promise<Venue[]>;
174
+ /** sk.quoteContext(eventId) reads a matched event's quote context: its active members' tokens, outcome maps and fee rows (one metered data call). */
175
+ quoteContext(eventId: string): Promise<QuoteContext>;
176
+ /**
177
+ * sk.quote(eventId, {outcome, side, size}) is the best venue, or split
178
+ * across venues, for size contracts of one outcome once each venue's taker
179
+ * fee is counted, in micro-units: the plan and its legs, every reachable
180
+ * venue alone, the members left out and why, and warnings (rule_mismatch,
181
+ * fee_unknown, partial). One call to Skewtape for the context; the books
182
+ * are read from each venue with a plain fetch that never carries the key.
183
+ * It places nothing. A rule mismatch throws RuleMismatchError unless
184
+ * allowRuleMismatch; no readable book throws VenueUnreachableError.
185
+ */
186
+ quote(eventId: string, options: QuoteOptions): Promise<QuoteResult>;
187
+ /**
188
+ * sk.backtest(trades, {asOf}) replays trades the caller supplies and gives
189
+ * their fee-aware P&L (runBacktest, which this feeds). It is arithmetic on
190
+ * history: it forecasts nothing, suggests no trade and optimises nothing.
191
+ * Unless passed in, it reads the fee rows of the trades' venues, their
192
+ * markets and those markets' resolution events (a request per 100
193
+ * markets), and the history window up to each trade without a price, and
194
+ * up to asOf for a market its resolutions do not settle by then, per
195
+ * market. A candle window starts a candle earlier, since a candle prices a
196
+ * time once it has ended. A backtest whose trades have prices and whose
197
+ * markets are settled reads no history. A window with no row at or before
198
+ * a trade's time is a BacktestError price_missing: widen lookbackSeconds
199
+ * or give the price.
200
+ */
201
+ backtest(trades: Iterable<Trade>, options?: SkBacktestOptions): Promise<BacktestResult>;
202
+ /**
203
+ * sk.stream({topics}) is the live feed (Builder and Pro), an async iterable
204
+ * of the server's messages that reconnects by itself: it resumes from the
205
+ * last seq it yielded, so nothing is missed or sent twice, and drops a
206
+ * trade it already yielded. venues, markets and events filter as the feed's
207
+ * subscribe does; resumeFrom starts from a seq kept earlier; maxReconnects
208
+ * bounds the failed connections in a row. It uses the platform's WebSocket;
209
+ * on Node 20 pass one (the ws package's): {WebSocket}.
210
+ */
211
+ stream(options: StreamOptions): Stream;
212
+ /**
213
+ * sk.kalshi() is the optional live Kalshi client, under the user's own
214
+ * Kalshi membership ({accessKey, privateKey} sign its calls; without them
215
+ * they are public requests). It calls Kalshi's host from this machine and
216
+ * shares nothing with this client, not the API key: Skewtape's Kalshi data
217
+ * ships from sk.markets, sk.fills, sk.candles and sk.resolutions, under the
218
+ * Kalshi data licence; this is a reading of the live venue beside it.
219
+ */
220
+ kalshi(options?: KalshiOptions): Kalshi;
221
+ /** sk.route: an unsigned order with your own code or fee (route.ts); it sends nothing, the API key included. */
222
+ readonly route: typeof route;
223
+ /** sk.geoblock: the venues' own checks (geoblock.ts); they never send the API key. */
224
+ readonly geoblock: {
225
+ readonly polymarket: typeof import("./geoblock.js").polymarketGeoblock;
226
+ };
227
+ /**
228
+ * The History snapshot and the monthly deltas, file by file, with an API key
229
+ * on the Builder or Pro plan (a History purchase downloads from the
230
+ * dashboard; a key on Free or History is a ForbiddenPlanError naming
231
+ * builder):
232
+ * - sk.download.bundles() lists the bundles the account may download, each
233
+ * with its files' paths, sizes and sha256 (GET /v1/bundles);
234
+ * - sk.download.url(bundle, path) is a file's link, valid for an hour and
235
+ * logged against the account (POST /v1/downloads/{bundle}/url);
236
+ * - sk.download.file(bundle, path, dest) fetches that link to dest, resuming
237
+ * a partial download and checking the sha256;
238
+ * - sk.download.bundle(bundle, folder) does that for every file, skipping
239
+ * those already there, then checks the folder against its
240
+ * CHECKSUMS.sha256;
241
+ * - sk.download(url, dest, {sha256}) fetches a link already in hand, such as
242
+ * one the dashboard gave, and sk.download.verify(folder) checks a folder.
243
+ * A link carries no key: files are fetched with a plain fetch (options.fetch
244
+ * to pass one), so the file host never sees the API key.
245
+ */
246
+ readonly download: ((url: string, dest: string, options?: DownloadOptions) => Promise<string>) & {
247
+ verify: (folder: string) => Promise<string[]>;
248
+ bundles: () => Promise<Bundle[]>;
249
+ url: (bundle: string, path: string) => Promise<DownloadURL>;
250
+ file: (bundle: string, path: string, dest: string, options?: DownloadOptions) => Promise<string>;
251
+ bundle: (bundle: string, folder: string, options?: BundleDownloadOptions) => Promise<string>;
252
+ };
253
+ private findBundle;
254
+ private bundleFile;
255
+ }