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.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -0
  3. package/dist/cjs/backtest.d.ts +146 -0
  4. package/dist/cjs/backtest.js +410 -0
  5. package/dist/cjs/client.d.ts +255 -0
  6. package/dist/cjs/client.js +447 -0
  7. package/dist/cjs/download.d.ts +33 -0
  8. package/dist/cjs/download.js +160 -0
  9. package/dist/cjs/errors.d.ts +76 -0
  10. package/dist/cjs/errors.js +159 -0
  11. package/dist/cjs/exact.d.ts +36 -0
  12. package/dist/cjs/exact.js +168 -0
  13. package/dist/cjs/fees.d.ts +68 -0
  14. package/dist/cjs/fees.js +196 -0
  15. package/dist/cjs/geoblock.d.ts +48 -0
  16. package/dist/cjs/geoblock.js +78 -0
  17. package/dist/cjs/index.d.ts +31 -0
  18. package/dist/cjs/index.js +98 -0
  19. package/dist/cjs/kalshi.d.ts +261 -0
  20. package/dist/cjs/kalshi.js +416 -0
  21. package/dist/cjs/keccak.d.ts +10 -0
  22. package/dist/cjs/keccak.js +84 -0
  23. package/dist/cjs/msgpack.d.ts +15 -0
  24. package/dist/cjs/msgpack.js +112 -0
  25. package/dist/cjs/package.json +1 -0
  26. package/dist/cjs/paginated.d.ts +26 -0
  27. package/dist/cjs/paginated.js +51 -0
  28. package/dist/cjs/quote-math.d.ts +146 -0
  29. package/dist/cjs/quote-math.js +446 -0
  30. package/dist/cjs/quote.d.ts +108 -0
  31. package/dist/cjs/quote.js +307 -0
  32. package/dist/cjs/route-hyperliquid.d.ts +228 -0
  33. package/dist/cjs/route-hyperliquid.js +387 -0
  34. package/dist/cjs/route.d.ts +297 -0
  35. package/dist/cjs/route.js +516 -0
  36. package/dist/cjs/stream.d.ts +99 -0
  37. package/dist/cjs/stream.js +529 -0
  38. package/dist/cjs/version.d.ts +6 -0
  39. package/dist/cjs/version.js +9 -0
  40. package/dist/esm/backtest.d.ts +146 -0
  41. package/dist/esm/backtest.js +403 -0
  42. package/dist/esm/client.d.ts +255 -0
  43. package/dist/esm/client.js +441 -0
  44. package/dist/esm/download.d.ts +33 -0
  45. package/dist/esm/download.js +155 -0
  46. package/dist/esm/errors.d.ts +76 -0
  47. package/dist/esm/errors.js +142 -0
  48. package/dist/esm/exact.d.ts +36 -0
  49. package/dist/esm/exact.js +158 -0
  50. package/dist/esm/fees.d.ts +68 -0
  51. package/dist/esm/fees.js +185 -0
  52. package/dist/esm/geoblock.d.ts +48 -0
  53. package/dist/esm/geoblock.js +74 -0
  54. package/dist/esm/index.d.ts +31 -0
  55. package/dist/esm/index.js +30 -0
  56. package/dist/esm/kalshi.d.ts +261 -0
  57. package/dist/esm/kalshi.js +404 -0
  58. package/dist/esm/keccak.d.ts +10 -0
  59. package/dist/esm/keccak.js +80 -0
  60. package/dist/esm/msgpack.d.ts +15 -0
  61. package/dist/esm/msgpack.js +109 -0
  62. package/dist/esm/paginated.d.ts +26 -0
  63. package/dist/esm/paginated.js +47 -0
  64. package/dist/esm/quote-math.d.ts +146 -0
  65. package/dist/esm/quote-math.js +437 -0
  66. package/dist/esm/quote.d.ts +108 -0
  67. package/dist/esm/quote.js +297 -0
  68. package/dist/esm/route-hyperliquid.d.ts +228 -0
  69. package/dist/esm/route-hyperliquid.js +376 -0
  70. package/dist/esm/route.d.ts +297 -0
  71. package/dist/esm/route.js +507 -0
  72. package/dist/esm/stream.d.ts +99 -0
  73. package/dist/esm/stream.js +524 -0
  74. package/dist/esm/version.d.ts +6 -0
  75. package/dist/esm/version.js +6 -0
  76. package/package.json +48 -1
  77. package/src/backtest.ts +490 -0
  78. package/src/client.ts +595 -0
  79. package/src/download.ts +161 -0
  80. package/src/errors.ts +143 -0
  81. package/src/exact.ts +159 -0
  82. package/src/fees.ts +189 -0
  83. package/src/generated/schema.d.ts +2500 -0
  84. package/src/geoblock.ts +90 -0
  85. package/src/index.ts +146 -0
  86. package/src/kalshi.ts +563 -0
  87. package/src/keccak.ts +82 -0
  88. package/src/msgpack.ts +83 -0
  89. package/src/paginated.ts +51 -0
  90. package/src/quote-math.ts +555 -0
  91. package/src/quote.ts +324 -0
  92. package/src/route-hyperliquid.ts +457 -0
  93. package/src/route.ts +631 -0
  94. package/src/stream.ts +539 -0
  95. package/src/version.ts +6 -0
@@ -0,0 +1,446 @@
1
+ "use strict";
2
+ /**
3
+ * The arithmetic of sk.quote: the port of tape's internal/quote and the taker
4
+ * fee formulas of internal/fees, in integers (BigInt inside, exact
5
+ * rationals for the fees). It reads no book and calls no host; quote.ts
6
+ * assembles its input from the quote context and the books it read.
7
+ * conformance/quote.json (mirrored to testdata/quote_conformance.json) holds
8
+ * the vectors both SDKs pass.
9
+ *
10
+ * Units: prices in micro-dollars per contract (0 to 1,000,000), sizes in
11
+ * micro-contracts (1,000,000 a contract), money in micro-dollars, all safe
12
+ * integers at the boundary. Fees are computed at 6 decimals for every venue.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.InvalidQuoteInputError = exports.VenueUnreachableError = exports.RuleMismatchError = exports.QuoteError = exports.MICRO = void 0;
16
+ exports.takerFeeMicros = takerFeeMicros;
17
+ exports.computeQuote = computeQuote;
18
+ const errors_js_1 = require("./errors.js");
19
+ const fees_js_1 = require("./fees.js");
20
+ exports.MICRO = 1_000_000;
21
+ const MICRO_N = 1000000n;
22
+ /** A quote that cannot be given; code is rule_mismatch, venue_unreachable or invalid_input, and detail the rule note, the venues and why, or what is invalid. */
23
+ class QuoteError extends errors_js_1.SkewtapeError {
24
+ detail;
25
+ constructor(code, detail) {
26
+ super(detail || code, { code });
27
+ this.detail = detail;
28
+ }
29
+ }
30
+ exports.QuoteError = QuoteError;
31
+ /** The members do not resolve alike (resolution_equal is false) and the caller did not allow it; detail is the rule note. */
32
+ class RuleMismatchError extends QuoteError {
33
+ constructor(detail) {
34
+ super("rule_mismatch", detail);
35
+ }
36
+ }
37
+ exports.RuleMismatchError = RuleMismatchError;
38
+ /** No member's book could be read; detail names each venue and why. */
39
+ class VenueUnreachableError extends QuoteError {
40
+ constructor(detail) {
41
+ super("venue_unreachable", detail);
42
+ }
43
+ }
44
+ exports.VenueUnreachableError = VenueUnreachableError;
45
+ /** A side, size, level or member that breaks the input's rules. */
46
+ class InvalidQuoteInputError extends QuoteError {
47
+ constructor(detail) {
48
+ super("invalid_input", detail);
49
+ }
50
+ }
51
+ exports.InvalidQuoteInputError = InvalidQuoteInputError;
52
+ function rat(num, den) {
53
+ return den < 0n ? { num: -num, den: -den } : { num, den };
54
+ }
55
+ function addRat(a, b) {
56
+ return rat(a.num * b.den + b.num * a.den, a.den * b.den);
57
+ }
58
+ function subRat(a, b) {
59
+ return rat(a.num * b.den - b.num * a.den, a.den * b.den);
60
+ }
61
+ function cmpRat(a, b) {
62
+ const l = a.num * b.den;
63
+ const r = b.num * a.den;
64
+ return l < r ? -1 : l > r ? 1 : 0;
65
+ }
66
+ /** Floor division and remainder for a positive divisor (Go's DivMod, Python's divmod). */
67
+ function divmod(num, den) {
68
+ let q = num / den;
69
+ let r = num % den;
70
+ if (r < 0n) {
71
+ q -= 1n;
72
+ r += den;
73
+ }
74
+ return [q, r];
75
+ }
76
+ function divRound(num, den, up) {
77
+ const [q, r] = divmod(num, den);
78
+ return up && r !== 0n ? q + 1n : q;
79
+ }
80
+ function safe(v, what) {
81
+ const n = Number(v);
82
+ if (!Number.isSafeInteger(n))
83
+ throw new InvalidQuoteInputError(`${what} ${v} is past the safe integer range`);
84
+ return n;
85
+ }
86
+ function int(v, what) {
87
+ if (!Number.isSafeInteger(v))
88
+ throw new InvalidQuoteInputError(`${what} ${v} is not a safe integer`);
89
+ return BigInt(v);
90
+ }
91
+ // The fee formulas: fees.ts, the one port of tape's internal/fees that the
92
+ // backtest uses too, at 6 decimals (micro-contracts and micro-dollars). Its
93
+ // FeeError is this module's InvalidQuoteInputError.
94
+ const MICRO_DECIMALS = 6;
95
+ /** fee's terms as fees.ts reads them, each parameter a safe integer. */
96
+ function termsOf(fee) {
97
+ const takerParams = {};
98
+ for (const [k, v] of Object.entries(fee.taker_params ?? {}))
99
+ takerParams[k] = int(v, k);
100
+ const min = fee.min_fee_micros;
101
+ return { formula: fee.formula, rounding: fee.rounding, takerParams, minFeeMicros: min === undefined || min === null ? null : int(min, "min_fee_micros") };
102
+ }
103
+ function asQuoteError(run) {
104
+ try {
105
+ return run();
106
+ }
107
+ catch (err) {
108
+ if (err instanceof fees_js_1.FeeError)
109
+ throw new InvalidQuoteInputError(err.message);
110
+ throw err;
111
+ }
112
+ }
113
+ function checkFeeInputs(size, notional) {
114
+ if (size <= 0n)
115
+ throw new InvalidQuoteInputError("a fee needs a positive size");
116
+ if (notional < 0n || notional > size)
117
+ throw new InvalidQuoteInputError("a fee's notional is out of range");
118
+ }
119
+ /** The taker fee of fee's formula for size micro-contracts against notional micro-dollars, exact, before rounding and any minimum. */
120
+ function exactTakerFee(fee, size, notional) {
121
+ checkFeeInputs(size, notional);
122
+ return asQuoteError(() => {
123
+ const f = (0, fees_js_1.exactFee)(fee.formula, termsOf(fee).takerParams, size, notional);
124
+ return rat(f.n, f.d);
125
+ });
126
+ }
127
+ /** The taker fee in micro-dollars: the exact fee rounded by the row to its round_step_micros (1 when absent), then raised to min_fee_micros when it is positive and below it. */
128
+ function computeTakerFee(fee, size, notional) {
129
+ checkFeeInputs(size, notional);
130
+ return asQuoteError(() => (0, fees_js_1.takerFeeOf)(termsOf(fee), size, notional, MICRO_DECIMALS));
131
+ }
132
+ /** The taker fee in micro-dollars for size micro-contracts against notional micro-dollars, as tape's fees.ComputeTakerFee at 6 decimals. */
133
+ function takerFeeMicros(fee, size, notional) {
134
+ return safe(computeTakerFee(fee, int(size, "size"), int(notional, "notional")), "fee");
135
+ }
136
+ function validate(q) {
137
+ if (q.side !== "buy" && q.side !== "sell")
138
+ throw new InvalidQuoteInputError(`side ${JSON.stringify(q.side)} is neither buy nor sell`);
139
+ if (!(q.size_micro > 0))
140
+ throw new InvalidQuoteInputError(`size ${q.size_micro} is not positive`);
141
+ int(q.size_micro, "size");
142
+ for (const m of q.members) {
143
+ if (m.fee_status === "ok") {
144
+ if (!m.fee)
145
+ throw new InvalidQuoteInputError(`${m.venue}: fee status ok with no fee row`);
146
+ }
147
+ else if (m.fee_status !== "no_row" && m.fee_status !== "masked" && m.fee_status !== "blocked") {
148
+ throw new InvalidQuoteInputError(`${m.venue}: fee status ${JSON.stringify(m.fee_status)}`);
149
+ }
150
+ if (m.fee_per !== "order" && m.fee_per !== "level")
151
+ throw new InvalidQuoteInputError(`${m.venue}: fee basis ${JSON.stringify(m.fee_per)}`);
152
+ const b = m.book;
153
+ if (!b)
154
+ continue;
155
+ if ((b.min_size_micro ?? 0) < 0 || (b.size_step_micro ?? 0) < 0)
156
+ throw new InvalidQuoteInputError(`${m.venue}: a negative minimum or step`);
157
+ for (const l of b.levels ?? []) {
158
+ if (l.price_micros < 0 || l.price_micros > exports.MICRO || !(l.size_micro > 0))
159
+ throw new InvalidQuoteInputError(`${m.venue}: level ${l.size_micro} at ${l.price_micros}`);
160
+ int(l.price_micros, "price");
161
+ int(l.size_micro, "size");
162
+ }
163
+ }
164
+ }
165
+ function fit(m, size) {
166
+ let q = size;
167
+ if (m.step > 1n)
168
+ q -= q % m.step;
169
+ return q < m.minSize ? 0n : q;
170
+ }
171
+ function perContract(amount, size, side) {
172
+ if (size === 0n)
173
+ return 0n;
174
+ return divRound(amount * MICRO_N, size, side === "buy");
175
+ }
176
+ function walk(m, size, side) {
177
+ const leg = { venue: m.m.venue, market_id: m.m.market_id, token_id: m.m.token_id, size, notional: 0n, fee: 0n, net: 0n, fee_status: m.m.fee_status };
178
+ if (size === 0n)
179
+ return leg;
180
+ const takes = [];
181
+ let left = size;
182
+ for (const l of m.levels) {
183
+ if (left === 0n)
184
+ break;
185
+ const t = left < l.size ? left : l.size;
186
+ takes.push([t, l.price]);
187
+ left -= t;
188
+ }
189
+ const up = side === "buy";
190
+ leg.notional = divRound(takes.reduce((s, [t, p]) => s + t * p, 0n), MICRO_N, up);
191
+ if (m.fee) {
192
+ if (m.m.fee_per === "order") {
193
+ leg.fee = computeTakerFee(m.fee, size, leg.notional);
194
+ }
195
+ else {
196
+ for (const [t, p] of takes)
197
+ leg.fee += computeTakerFee(m.fee, t, divRound(t * p, MICRO_N, up));
198
+ }
199
+ }
200
+ leg.net = up ? leg.notional + leg.fee : leg.notional - leg.fee;
201
+ return leg;
202
+ }
203
+ function rank(quotable, excluded, q) {
204
+ const buy = q.side === "buy";
205
+ const ranked = [];
206
+ quotable.forEach((m, i) => {
207
+ if (excluded.has(i))
208
+ return;
209
+ for (const l of m.levels) {
210
+ let key = rat(l.price, 1n);
211
+ if (m.fee) {
212
+ const f = exactTakerFee(m.fee, MICRO_N, l.price);
213
+ key = buy ? addRat(key, f) : subRat(key, f);
214
+ }
215
+ ranked.push({ key, i, seq: ranked.length, level: l });
216
+ }
217
+ });
218
+ // Best net first; ties to the earlier member, then the better price, then
219
+ // the order the levels were taken in (a stable sort, as in Go).
220
+ ranked.sort((a, b) => {
221
+ let c = cmpRat(a.key, b.key);
222
+ if (!buy)
223
+ c = -c;
224
+ if (c !== 0)
225
+ return c;
226
+ if (a.i !== b.i)
227
+ return a.i - b.i;
228
+ if (a.level.price !== b.level.price)
229
+ return (a.level.price < b.level.price ? -1 : 1) * (buy ? 1 : -1);
230
+ return a.seq - b.seq;
231
+ });
232
+ const alloc = quotable.map(() => 0n);
233
+ let left = BigInt(q.size_micro);
234
+ for (const r of ranked) {
235
+ if (left === 0n)
236
+ break;
237
+ const t = left < r.level.size ? left : r.level.size;
238
+ alloc[r.i] = (alloc[r.i] ?? 0n) + t;
239
+ left -= t;
240
+ }
241
+ return alloc;
242
+ }
243
+ function splitPlan(quotable, q) {
244
+ const excluded = new Set();
245
+ for (let n = 0; n < quotable.length; n++) {
246
+ const alloc = rank(quotable, excluded, q);
247
+ let again = false;
248
+ alloc.forEach((a, i) => {
249
+ if (a > 0n && fit(quotable[i], a) === 0n) {
250
+ excluded.add(i);
251
+ again = true;
252
+ }
253
+ });
254
+ if (again)
255
+ continue;
256
+ const legs = [];
257
+ alloc.forEach((a, i) => {
258
+ const m = quotable[i];
259
+ const share = fit(m, a);
260
+ if (share > 0n)
261
+ legs.push(walk(m, share, q.side));
262
+ });
263
+ return legs;
264
+ }
265
+ return [];
266
+ }
267
+ function bestPlan(plans, side) {
268
+ let best = null;
269
+ let bestFilled = 0n;
270
+ let bestNet = 0n;
271
+ for (const p of plans) {
272
+ const filled = p.reduce((s, l) => s + l.size, 0n);
273
+ const net = p.reduce((s, l) => s + l.net, 0n);
274
+ if (filled === 0n)
275
+ continue;
276
+ let better = best === null || filled > bestFilled;
277
+ if (!better && filled === bestFilled) {
278
+ if ((side === "buy" && net < bestNet) || (side === "sell" && net > bestNet))
279
+ better = true;
280
+ else if (net === bestNet)
281
+ better = p.length < (best?.length ?? 0);
282
+ }
283
+ if (better) {
284
+ best = p;
285
+ bestFilled = filled;
286
+ bestNet = net;
287
+ }
288
+ }
289
+ return best;
290
+ }
291
+ function legOut(l, side) {
292
+ return {
293
+ venue: l.venue,
294
+ market_id: l.market_id,
295
+ token_id: l.token_id,
296
+ size_micro: safe(l.size, "size"),
297
+ notional_micros: safe(l.notional, "notional"),
298
+ fee_micros: safe(l.fee, "fee"),
299
+ net_micros: safe(l.net, "net"),
300
+ avg_price_micros: safe(perContract(l.notional, l.size, side), "price"),
301
+ net_avg_price_micros: safe(perContract(l.net, l.size, side), "price"),
302
+ fee_status: l.fee_status,
303
+ };
304
+ }
305
+ /**
306
+ * The best plan for q, as tape's internal/quote.Quote computes it:
307
+ *
308
+ * 1. A side other than buy or sell, a size of 0 or less, a level priced
309
+ * outside 0 to 1,000,000 or sized 0 or less, or a member with an unknown
310
+ * fee status or basis throws InvalidQuoteInputError.
311
+ * 2. resolution_equal false throws RuleMismatchError with the rule note,
312
+ * unless allow_rule_mismatch; then the result warns.
313
+ * 3. A blocked member is skipped, and so is one with no book
314
+ * (venue_unreachable, with its reason); none left and one unreachable
315
+ * throws VenueUnreachableError naming each.
316
+ * 4. Each leg's notional is the exact sum of size x price rounded once (up
317
+ * for a buy, down for a sell); its fee is the row's on the leg's totals
318
+ * (fee_per order) or on each level's fill (level). A fee status other than
319
+ * ok has no fee to count: unknown, never zero. When a member whose fee is
320
+ * known can fill some of the size alone, a fee-unknown member is left out
321
+ * of the split and the best plan (a price before fees is never compared
322
+ * with one after them), still quoted alone in venues before fees, and
323
+ * warns fee_unknown; otherwise the members are compared before fees and
324
+ * the warning says no fee is counted.
325
+ * 5. Each member alone fills the size or its depth, cut to its size step,
326
+ * nothing under its minimum; every reachable member is in venues.
327
+ * 6. The split ranks every level by price plus the exact fee of one contract
328
+ * (minus it for a sell), takes them in order, cuts each share to its step
329
+ * and leaves out a member under its minimum.
330
+ * 7. The best plan fills the most, then nets the least (buy) or the most
331
+ * (sell), then has the fewer legs; a partial fill warns.
332
+ */
333
+ function computeQuote(q) {
334
+ validate(q);
335
+ if (!q.resolution_equal && !q.allow_rule_mismatch)
336
+ throw new RuleMismatchError(q.rule_note);
337
+ const res = {
338
+ event_id: q.event_id,
339
+ side: q.side,
340
+ size_micro: q.size_micro,
341
+ plan: "none",
342
+ filled_micro: 0,
343
+ notional_micros: 0,
344
+ fee_micros: 0,
345
+ net_micros: 0,
346
+ avg_price_micros: 0,
347
+ net_avg_price_micros: 0,
348
+ legs: [],
349
+ venues: [],
350
+ skipped: [],
351
+ warnings: [],
352
+ };
353
+ if (!q.resolution_equal)
354
+ res.warnings.push(`rule_mismatch: ${q.rule_note}`);
355
+ const quotable = [];
356
+ const unreachable = [];
357
+ for (const m of q.members) {
358
+ if (m.blocked || m.fee_status === "blocked") {
359
+ res.skipped.push({ venue: m.venue, market_id: m.market_id, reason: "blocked" });
360
+ }
361
+ else if (!m.book) {
362
+ const skip = { venue: m.venue, market_id: m.market_id, reason: "venue_unreachable" };
363
+ if (m.unreachable)
364
+ skip.detail = m.unreachable;
365
+ res.skipped.push(skip);
366
+ unreachable.push(m.unreachable ? `${m.venue} (${m.unreachable})` : m.venue);
367
+ }
368
+ else {
369
+ const buy = q.side === "buy";
370
+ // A stable sort: equal prices keep their order.
371
+ const levels = (m.book.levels ?? [])
372
+ .map((l) => ({ price: BigInt(l.price_micros), size: BigInt(l.size_micro) }))
373
+ .sort((a, b) => (a.price === b.price ? 0 : (a.price < b.price ? -1 : 1) * (buy ? 1 : -1)));
374
+ const fee = m.fee_status === "ok" ? (m.fee ?? null) : null;
375
+ quotable.push({
376
+ m,
377
+ levels,
378
+ depth: levels.reduce((s, l) => s + l.size, 0n),
379
+ fee,
380
+ minSize: BigInt(m.book.min_size_micro ?? 0),
381
+ step: BigInt(m.book.size_step_micro ?? 0),
382
+ });
383
+ }
384
+ }
385
+ if (quotable.length === 0) {
386
+ if (unreachable.length > 0)
387
+ throw new VenueUnreachableError(unreachable.join("; "));
388
+ return res;
389
+ }
390
+ const size = BigInt(q.size_micro);
391
+ // A fee is compared only with fees: when a member whose fee is known can
392
+ // fill some of the size alone, the plans leave out the members whose fee is
393
+ // unknown (step 4).
394
+ const feeKnown = quotable.some((m) => m.fee !== null && fit(m, size < m.depth ? size : m.depth) > 0n);
395
+ const planned = [];
396
+ const plans = [];
397
+ let leftOut = false;
398
+ for (const m of quotable) {
399
+ const alloc = fit(m, size < m.depth ? size : m.depth);
400
+ const leg = walk(m, alloc, q.side);
401
+ res.venues.push({ depth_micro: safe(m.depth, "depth"), ...legOut(leg, q.side) });
402
+ if (m.fee === null && feeKnown) {
403
+ res.warnings.push(`fee_unknown: ${m.m.venue} (${m.m.fee_status}): its fee is unknown, so it is left out of the plan; venues shows it alone, before fees`);
404
+ leftOut = true;
405
+ continue;
406
+ }
407
+ if (m.fee === null)
408
+ res.warnings.push(`fee_unknown: ${m.m.venue} (${m.m.fee_status}): its fee is not counted`);
409
+ planned.push(m);
410
+ if (alloc > 0n)
411
+ plans.push([leg]);
412
+ }
413
+ const split = splitPlan(planned, q);
414
+ if (split.length > 1)
415
+ plans.push(split);
416
+ const best = bestPlan(plans, q.side);
417
+ if (!best) {
418
+ res.warnings.push(`partial: the books hold 0 of ${q.size_micro} micro-contracts on this side`);
419
+ return res;
420
+ }
421
+ let filled = 0n;
422
+ let notional = 0n;
423
+ let fee = 0n;
424
+ let net = 0n;
425
+ for (const l of best) {
426
+ filled += l.size;
427
+ notional += l.notional;
428
+ fee += l.fee;
429
+ net += l.net;
430
+ }
431
+ res.legs = best.map((l) => legOut(l, q.side));
432
+ res.filled_micro = safe(filled, "size");
433
+ res.notional_micros = safe(notional, "notional");
434
+ res.fee_micros = safe(fee, "fee");
435
+ res.net_micros = safe(net, "net");
436
+ res.avg_price_micros = safe(perContract(notional, filled, q.side), "price");
437
+ res.net_avg_price_micros = safe(perContract(net, filled, q.side), "price");
438
+ res.plan = best.length > 1 ? "split" : "venue";
439
+ if (filled < size && leftOut) {
440
+ res.warnings.push(`partial: the plan fills ${filled} of ${q.size_micro} micro-contracts on this side, without the venues whose fee is unknown`);
441
+ }
442
+ else if (filled < size) {
443
+ res.warnings.push(`partial: the books hold ${filled} of ${q.size_micro} micro-contracts on this side`);
444
+ }
445
+ return res;
446
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * sk.quote(eventId, {outcome, side, size}): the best venue, or split across
3
+ * venues, to take a size of one outcome of a matched event once each venue's
4
+ * taker fee is counted. It places nothing.
5
+ *
6
+ * One call to Skewtape (GET /v1/quote-context/{event_id}, a metered data
7
+ * call) gives the members, their tokens, outcome maps and fee rows; the books
8
+ * are read from each venue, from this machine, with a plain fetch that never
9
+ * carries the Skewtape key. A venue that cannot be reached is left out and
10
+ * named (venue_unreachable); nothing routes around a block. The arithmetic is
11
+ * quote-math.ts, which passes tape's conformance vectors.
12
+ */
13
+ import type { components } from "./generated/schema.js";
14
+ import { MICRO, type Book, type QuoteResult } from "./quote-math.js";
15
+ export type QuoteContext = components["schemas"]["QuoteContext"];
16
+ export type QuoteContextMember = components["schemas"]["QuoteContextMember"];
17
+ export declare const POLYMARKET_CLOB_URL = "https://clob.polymarket.com";
18
+ /** Kalshi's smallest count where a market allows fractions: 0.01 contracts. */
19
+ export declare const KALSHI_FRACTION_MICRO = 10000;
20
+ /** A book reader could not read the book; message is the reason the quote names (venue_unreachable). */
21
+ export declare class BookUnavailable extends Error {
22
+ constructor(message: string);
23
+ }
24
+ /** What a book reader is asked for: the member's venue and market, the token of the outcome the quote takes, and the side (buy reads the asks, sell the bids). */
25
+ export interface BookRequest {
26
+ venue: string;
27
+ marketId: string;
28
+ tokenId: string;
29
+ side: "buy" | "sell";
30
+ }
31
+ /** Reads one book with fetchImpl, a plain fetch that carries no Skewtape key; throws BookUnavailable to leave the member out with a reason. */
32
+ export type BookReader = (request: BookRequest, fetchImpl: typeof fetch) => Promise<Book>;
33
+ export interface QuoteOptions {
34
+ /** The event's outcome to take, as the members' outcome maps name it ("yes", "no", ...). */
35
+ outcome: string;
36
+ side: "buy" | "sell";
37
+ /** Contracts, up to six decimals: a number or a decimal string. */
38
+ size: number | string;
39
+ /** Quote members that do not resolve alike, with a warning; refused by default. */
40
+ allowRuleMismatch?: boolean;
41
+ /** Readers by venue, used before the defaults (Polymarket's CLOB; Kalshi's public orderbook; kalshi_dflow through DFlow, not set up yet). */
42
+ bookReaders?: Record<string, BookReader>;
43
+ /** The fetch the books are read with; the global one by default. It must not carry the Skewtape key. */
44
+ venueFetch?: typeof fetch;
45
+ }
46
+ /**
47
+ * A decimal amount in millionths, exact when it has at most six decimals,
48
+ * otherwise rounded up or down. Strings are parsed exactly; a number goes
49
+ * through its shortest decimal form.
50
+ */
51
+ export declare function micros(value: number | string, up?: boolean): number;
52
+ /** How long a book read may take, the request and its body, in seconds. */
53
+ export declare const BOOK_TIMEOUT_SECONDS = 10;
54
+ /**
55
+ * The token's book from Polymarket's CLOB (GET /book?token_id=), the asks
56
+ * for a buy and the bids for a sell: levels as {"price", "size"} decimal
57
+ * strings, in dollars and contracts, as the CLOB's market channel sends them,
58
+ * and min_order_size in contracts. An ask's price rounds up and a bid's down
59
+ * past six decimals, and sizes down, so a quote never counts on more than the
60
+ * book holds.
61
+ *
62
+ * TODO(decision): the shape is the CLOB's book as the market channel's book
63
+ * event carries it (tape internal/venue/polymarket/live.go); the REST page
64
+ * could not be read on 14 Nov 2026 (docs.polymarket.com served an expired
65
+ * certificate). A staging recording of one /book reply confirms it, and shows
66
+ * whether the CLOB answers 404 for a token with no book (a closed market),
67
+ * which would then read as an empty book, not unreachable.
68
+ */
69
+ export declare const readPolymarketBook: BookReader;
70
+ /**
71
+ * A kalshi member's book from Kalshi's public orderbook (GET
72
+ * /markets/{ticker}/orderbook, through kalshi.ts with no key, one try).
73
+ * Kalshi lists bids only, yes and no: a no bid at p is a yes ask at 1 - p.
74
+ * So a buy of yes takes the no bids at 1 - p (rounded up past six decimals)
75
+ * and a buy of no the yes bids at 1 - p; a sell of yes takes the yes bids
76
+ * and a sell of no the no bids (rounded down). Counts are rounded down to
77
+ * millionths.
78
+ *
79
+ * The size step: Kalshi counts in hundredths of a contract where a market
80
+ * allows fractions and in whole contracts elsewhere (docs.kalshi.com,
81
+ * fixed-point migration, 5 Nov 2026), and names no field that says which. A
82
+ * book with a fractional count on either side is taken as fractional (0.01);
83
+ * any other as whole contracts, so a quote never counts on a size the market
84
+ * may refuse. Kalshi documents no minimum order beyond that.
85
+ */
86
+ export declare const readKalshiBook: BookReader;
87
+ /**
88
+ * A kalshi_dflow member trades through DFlow (ADR-0016), whose orderbook
89
+ * needs DFlow access, not set up yet, so the member is left out with that
90
+ * reason, plainly; nothing reads the book another way. (A kalshi member is
91
+ * read from Kalshi's own book: readKalshiBook.)
92
+ *
93
+ * TODO(decision): DFlow's orderbook endpoint, its shape and the key it needs
94
+ * (production access is by request). Until then a caller can pass its own
95
+ * reader in bookReaders.
96
+ */
97
+ export declare const readKalshiBookThroughDflow: BookReader;
98
+ export declare const DEFAULT_BOOK_READERS: Readonly<Record<string, BookReader>>;
99
+ /** The event's outcome names a quote can take, as the members' outcome maps name them. */
100
+ export declare function outcomesOf(context: QuoteContext): string[];
101
+ /**
102
+ * A quote on a context already read: each member's book read with its
103
+ * venue's reader (bookReaders first, then the defaults), then computeQuote.
104
+ * A member whose fee_status is blocked is left out without reading anything,
105
+ * and a rule mismatch is refused before any book is read.
106
+ */
107
+ export declare function quoteFromContext(context: QuoteContext, options: QuoteOptions): Promise<QuoteResult>;
108
+ export { MICRO };