skewtape 0.0.1 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +182 -0
- package/dist/cjs/backtest.d.ts +146 -0
- package/dist/cjs/backtest.js +410 -0
- package/dist/cjs/client.d.ts +255 -0
- package/dist/cjs/client.js +447 -0
- package/dist/cjs/download.d.ts +33 -0
- package/dist/cjs/download.js +160 -0
- package/dist/cjs/errors.d.ts +76 -0
- package/dist/cjs/errors.js +159 -0
- package/dist/cjs/exact.d.ts +36 -0
- package/dist/cjs/exact.js +168 -0
- package/dist/cjs/fees.d.ts +68 -0
- package/dist/cjs/fees.js +196 -0
- package/dist/cjs/geoblock.d.ts +48 -0
- package/dist/cjs/geoblock.js +78 -0
- package/dist/cjs/index.d.ts +31 -0
- package/dist/cjs/index.js +98 -0
- package/dist/cjs/kalshi.d.ts +261 -0
- package/dist/cjs/kalshi.js +416 -0
- package/dist/cjs/keccak.d.ts +10 -0
- package/dist/cjs/keccak.js +84 -0
- package/dist/cjs/msgpack.d.ts +15 -0
- package/dist/cjs/msgpack.js +112 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/paginated.d.ts +26 -0
- package/dist/cjs/paginated.js +51 -0
- package/dist/cjs/quote-math.d.ts +146 -0
- package/dist/cjs/quote-math.js +446 -0
- package/dist/cjs/quote.d.ts +108 -0
- package/dist/cjs/quote.js +307 -0
- package/dist/cjs/route-hyperliquid.d.ts +228 -0
- package/dist/cjs/route-hyperliquid.js +387 -0
- package/dist/cjs/route.d.ts +297 -0
- package/dist/cjs/route.js +516 -0
- package/dist/cjs/stream.d.ts +99 -0
- package/dist/cjs/stream.js +529 -0
- package/dist/cjs/version.d.ts +6 -0
- package/dist/cjs/version.js +9 -0
- package/dist/esm/backtest.d.ts +146 -0
- package/dist/esm/backtest.js +403 -0
- package/dist/esm/client.d.ts +255 -0
- package/dist/esm/client.js +441 -0
- package/dist/esm/download.d.ts +33 -0
- package/dist/esm/download.js +155 -0
- package/dist/esm/errors.d.ts +76 -0
- package/dist/esm/errors.js +142 -0
- package/dist/esm/exact.d.ts +36 -0
- package/dist/esm/exact.js +158 -0
- package/dist/esm/fees.d.ts +68 -0
- package/dist/esm/fees.js +185 -0
- package/dist/esm/geoblock.d.ts +48 -0
- package/dist/esm/geoblock.js +74 -0
- package/dist/esm/index.d.ts +31 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/kalshi.d.ts +261 -0
- package/dist/esm/kalshi.js +404 -0
- package/dist/esm/keccak.d.ts +10 -0
- package/dist/esm/keccak.js +80 -0
- package/dist/esm/msgpack.d.ts +15 -0
- package/dist/esm/msgpack.js +109 -0
- package/dist/esm/paginated.d.ts +26 -0
- package/dist/esm/paginated.js +47 -0
- package/dist/esm/quote-math.d.ts +146 -0
- package/dist/esm/quote-math.js +437 -0
- package/dist/esm/quote.d.ts +108 -0
- package/dist/esm/quote.js +297 -0
- package/dist/esm/route-hyperliquid.d.ts +228 -0
- package/dist/esm/route-hyperliquid.js +376 -0
- package/dist/esm/route.d.ts +297 -0
- package/dist/esm/route.js +507 -0
- package/dist/esm/stream.d.ts +99 -0
- package/dist/esm/stream.js +524 -0
- package/dist/esm/version.d.ts +6 -0
- package/dist/esm/version.js +6 -0
- package/package.json +48 -1
- package/src/backtest.ts +490 -0
- package/src/client.ts +595 -0
- package/src/download.ts +161 -0
- package/src/errors.ts +143 -0
- package/src/exact.ts +159 -0
- package/src/fees.ts +189 -0
- package/src/generated/schema.d.ts +2500 -0
- package/src/geoblock.ts +90 -0
- package/src/index.ts +146 -0
- package/src/kalshi.ts +563 -0
- package/src/keccak.ts +82 -0
- package/src/msgpack.ts +83 -0
- package/src/paginated.ts +51 -0
- package/src/quote-math.ts +555 -0
- package/src/quote.ts +324 -0
- package/src/route-hyperliquid.ts +457 -0
- package/src/route.ts +631 -0
- package/src/stream.ts +539 -0
- package/src/version.ts +6 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paginated lists: the shape every list of the Skewtape client and of the
|
|
3
|
+
* Kalshi client comes back as. for await yields every item, fetching each
|
|
4
|
+
* page as the one before runs out; nothing is fetched until it is iterated.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* A list the API pages: for await yields every item, fetching each page as
|
|
8
|
+
* the one before runs out. Nothing is fetched until it is iterated.
|
|
9
|
+
*/
|
|
10
|
+
export class Paginated {
|
|
11
|
+
fetchPage;
|
|
12
|
+
keep;
|
|
13
|
+
constructor(fetchPage, keep) {
|
|
14
|
+
this.fetchPage = fetchPage;
|
|
15
|
+
this.keep = keep;
|
|
16
|
+
}
|
|
17
|
+
/** The pages as the API returns them; a client-side filter (markets resolved, pairs) applies to each. */
|
|
18
|
+
async *pages() {
|
|
19
|
+
let cursor;
|
|
20
|
+
for (;;) {
|
|
21
|
+
let page = await this.fetchPage(cursor);
|
|
22
|
+
if (this.keep)
|
|
23
|
+
page = { items: page.items.filter(this.keep), nextCursor: page.nextCursor };
|
|
24
|
+
yield page;
|
|
25
|
+
if (!page.nextCursor)
|
|
26
|
+
return;
|
|
27
|
+
cursor = page.nextCursor;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async *[Symbol.asyncIterator]() {
|
|
31
|
+
for await (const page of this.pages())
|
|
32
|
+
yield* page.items;
|
|
33
|
+
}
|
|
34
|
+
/** The first item, or undefined when there is none. */
|
|
35
|
+
async first() {
|
|
36
|
+
for await (const item of this)
|
|
37
|
+
return item;
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
/** Every item, in one array. */
|
|
41
|
+
async toArray() {
|
|
42
|
+
const out = [];
|
|
43
|
+
for await (const item of this)
|
|
44
|
+
out.push(item);
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic of sk.quote: the port of tape's internal/quote and the taker
|
|
3
|
+
* fee formulas of internal/fees, in integers (BigInt inside, exact
|
|
4
|
+
* rationals for the fees). It reads no book and calls no host; quote.ts
|
|
5
|
+
* assembles its input from the quote context and the books it read.
|
|
6
|
+
* conformance/quote.json (mirrored to testdata/quote_conformance.json) holds
|
|
7
|
+
* the vectors both SDKs pass.
|
|
8
|
+
*
|
|
9
|
+
* Units: prices in micro-dollars per contract (0 to 1,000,000), sizes in
|
|
10
|
+
* micro-contracts (1,000,000 a contract), money in micro-dollars, all safe
|
|
11
|
+
* integers at the boundary. Fees are computed at 6 decimals for every venue.
|
|
12
|
+
*/
|
|
13
|
+
import { SkewtapeError } from "./errors.js";
|
|
14
|
+
export declare const MICRO = 1000000;
|
|
15
|
+
export type Side = "buy" | "sell";
|
|
16
|
+
export type FeeStatus = "ok" | "no_row" | "masked" | "blocked";
|
|
17
|
+
export type FeePer = "order" | "level";
|
|
18
|
+
export type Plan = "venue" | "split" | "none";
|
|
19
|
+
export type QuoteErrorCode = "rule_mismatch" | "venue_unreachable" | "invalid_input";
|
|
20
|
+
/** 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. */
|
|
21
|
+
export declare class QuoteError extends SkewtapeError {
|
|
22
|
+
readonly detail: string;
|
|
23
|
+
constructor(code: QuoteErrorCode, detail: string);
|
|
24
|
+
}
|
|
25
|
+
/** The members do not resolve alike (resolution_equal is false) and the caller did not allow it; detail is the rule note. */
|
|
26
|
+
export declare class RuleMismatchError extends QuoteError {
|
|
27
|
+
constructor(detail: string);
|
|
28
|
+
}
|
|
29
|
+
/** No member's book could be read; detail names each venue and why. */
|
|
30
|
+
export declare class VenueUnreachableError extends QuoteError {
|
|
31
|
+
constructor(detail: string);
|
|
32
|
+
}
|
|
33
|
+
/** A side, size, level or member that breaks the input's rules. */
|
|
34
|
+
export declare class InvalidQuoteInputError extends QuoteError {
|
|
35
|
+
constructor(detail: string);
|
|
36
|
+
}
|
|
37
|
+
export interface Level {
|
|
38
|
+
price_micros: number;
|
|
39
|
+
size_micro: number;
|
|
40
|
+
}
|
|
41
|
+
/** The side of a member's book the order takes (asks for a buy, bids for a sell), in any order, with the venue's minimum order and size step (0 for none). */
|
|
42
|
+
export interface Book {
|
|
43
|
+
/** null reads as no level, as Go writes an empty list. */
|
|
44
|
+
levels: Level[] | null;
|
|
45
|
+
min_size_micro?: number;
|
|
46
|
+
size_step_micro?: number;
|
|
47
|
+
}
|
|
48
|
+
/** The part of a fee row a quote computes with. */
|
|
49
|
+
export interface FeeSchedule {
|
|
50
|
+
formula: string;
|
|
51
|
+
rounding: string;
|
|
52
|
+
taker_params: Record<string, number>;
|
|
53
|
+
min_fee_micros?: number | null;
|
|
54
|
+
}
|
|
55
|
+
/** One member of the quote with the book read for its outcome's token; book null when the venue could not be reached, unreachable saying why. */
|
|
56
|
+
export interface QuoteMember {
|
|
57
|
+
venue: string;
|
|
58
|
+
market_id: string;
|
|
59
|
+
token_id: string;
|
|
60
|
+
fee_status: string;
|
|
61
|
+
fee_per: string;
|
|
62
|
+
fee?: FeeSchedule | null;
|
|
63
|
+
book?: Book | null;
|
|
64
|
+
blocked?: boolean;
|
|
65
|
+
unreachable?: string;
|
|
66
|
+
}
|
|
67
|
+
export interface QuoteInput {
|
|
68
|
+
event_id: string;
|
|
69
|
+
side: string;
|
|
70
|
+
size_micro: number;
|
|
71
|
+
resolution_equal: boolean;
|
|
72
|
+
rule_note: string;
|
|
73
|
+
allow_rule_mismatch?: boolean;
|
|
74
|
+
members: QuoteMember[];
|
|
75
|
+
}
|
|
76
|
+
/** One venue's share of a plan, walked on its book. */
|
|
77
|
+
export interface Leg {
|
|
78
|
+
venue: string;
|
|
79
|
+
market_id: string;
|
|
80
|
+
token_id: string;
|
|
81
|
+
size_micro: number;
|
|
82
|
+
notional_micros: number;
|
|
83
|
+
fee_micros: number;
|
|
84
|
+
net_micros: number;
|
|
85
|
+
avg_price_micros: number;
|
|
86
|
+
net_avg_price_micros: number;
|
|
87
|
+
fee_status: string;
|
|
88
|
+
}
|
|
89
|
+
/** One reachable member alone: its depth on the side and what the size would fill there. */
|
|
90
|
+
export interface VenueQuote extends Leg {
|
|
91
|
+
depth_micro: number;
|
|
92
|
+
}
|
|
93
|
+
export interface Skip {
|
|
94
|
+
venue: string;
|
|
95
|
+
market_id: string;
|
|
96
|
+
reason: "venue_unreachable" | "blocked";
|
|
97
|
+
detail?: string;
|
|
98
|
+
}
|
|
99
|
+
/** The best plan, its totals and legs, every reachable member alone, the members left out and the warnings. A quote places nothing. */
|
|
100
|
+
export interface QuoteResult {
|
|
101
|
+
event_id: string;
|
|
102
|
+
side: string;
|
|
103
|
+
size_micro: number;
|
|
104
|
+
plan: Plan;
|
|
105
|
+
filled_micro: number;
|
|
106
|
+
notional_micros: number;
|
|
107
|
+
fee_micros: number;
|
|
108
|
+
net_micros: number;
|
|
109
|
+
avg_price_micros: number;
|
|
110
|
+
net_avg_price_micros: number;
|
|
111
|
+
legs: Leg[];
|
|
112
|
+
venues: VenueQuote[];
|
|
113
|
+
skipped: Skip[];
|
|
114
|
+
warnings: string[];
|
|
115
|
+
}
|
|
116
|
+
/** The taker fee in micro-dollars for size micro-contracts against notional micro-dollars, as tape's fees.ComputeTakerFee at 6 decimals. */
|
|
117
|
+
export declare function takerFeeMicros(fee: FeeSchedule, size: number, notional: number): number;
|
|
118
|
+
/**
|
|
119
|
+
* The best plan for q, as tape's internal/quote.Quote computes it:
|
|
120
|
+
*
|
|
121
|
+
* 1. A side other than buy or sell, a size of 0 or less, a level priced
|
|
122
|
+
* outside 0 to 1,000,000 or sized 0 or less, or a member with an unknown
|
|
123
|
+
* fee status or basis throws InvalidQuoteInputError.
|
|
124
|
+
* 2. resolution_equal false throws RuleMismatchError with the rule note,
|
|
125
|
+
* unless allow_rule_mismatch; then the result warns.
|
|
126
|
+
* 3. A blocked member is skipped, and so is one with no book
|
|
127
|
+
* (venue_unreachable, with its reason); none left and one unreachable
|
|
128
|
+
* throws VenueUnreachableError naming each.
|
|
129
|
+
* 4. Each leg's notional is the exact sum of size x price rounded once (up
|
|
130
|
+
* for a buy, down for a sell); its fee is the row's on the leg's totals
|
|
131
|
+
* (fee_per order) or on each level's fill (level). A fee status other than
|
|
132
|
+
* ok has no fee to count: unknown, never zero. When a member whose fee is
|
|
133
|
+
* known can fill some of the size alone, a fee-unknown member is left out
|
|
134
|
+
* of the split and the best plan (a price before fees is never compared
|
|
135
|
+
* with one after them), still quoted alone in venues before fees, and
|
|
136
|
+
* warns fee_unknown; otherwise the members are compared before fees and
|
|
137
|
+
* the warning says no fee is counted.
|
|
138
|
+
* 5. Each member alone fills the size or its depth, cut to its size step,
|
|
139
|
+
* nothing under its minimum; every reachable member is in venues.
|
|
140
|
+
* 6. The split ranks every level by price plus the exact fee of one contract
|
|
141
|
+
* (minus it for a sell), takes them in order, cuts each share to its step
|
|
142
|
+
* and leaves out a member under its minimum.
|
|
143
|
+
* 7. The best plan fills the most, then nets the least (buy) or the most
|
|
144
|
+
* (sell), then has the fewer legs; a partial fill warns.
|
|
145
|
+
*/
|
|
146
|
+
export declare function computeQuote(q: QuoteInput): QuoteResult;
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic of sk.quote: the port of tape's internal/quote and the taker
|
|
3
|
+
* fee formulas of internal/fees, in integers (BigInt inside, exact
|
|
4
|
+
* rationals for the fees). It reads no book and calls no host; quote.ts
|
|
5
|
+
* assembles its input from the quote context and the books it read.
|
|
6
|
+
* conformance/quote.json (mirrored to testdata/quote_conformance.json) holds
|
|
7
|
+
* the vectors both SDKs pass.
|
|
8
|
+
*
|
|
9
|
+
* Units: prices in micro-dollars per contract (0 to 1,000,000), sizes in
|
|
10
|
+
* micro-contracts (1,000,000 a contract), money in micro-dollars, all safe
|
|
11
|
+
* integers at the boundary. Fees are computed at 6 decimals for every venue.
|
|
12
|
+
*/
|
|
13
|
+
import { SkewtapeError } from "./errors.js";
|
|
14
|
+
import { FeeError, exactFee, takerFeeOf } from "./fees.js";
|
|
15
|
+
export const MICRO = 1_000_000;
|
|
16
|
+
const MICRO_N = 1000000n;
|
|
17
|
+
/** 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. */
|
|
18
|
+
export class QuoteError extends SkewtapeError {
|
|
19
|
+
detail;
|
|
20
|
+
constructor(code, detail) {
|
|
21
|
+
super(detail || code, { code });
|
|
22
|
+
this.detail = detail;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** The members do not resolve alike (resolution_equal is false) and the caller did not allow it; detail is the rule note. */
|
|
26
|
+
export class RuleMismatchError extends QuoteError {
|
|
27
|
+
constructor(detail) {
|
|
28
|
+
super("rule_mismatch", detail);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** No member's book could be read; detail names each venue and why. */
|
|
32
|
+
export class VenueUnreachableError extends QuoteError {
|
|
33
|
+
constructor(detail) {
|
|
34
|
+
super("venue_unreachable", detail);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** A side, size, level or member that breaks the input's rules. */
|
|
38
|
+
export class InvalidQuoteInputError extends QuoteError {
|
|
39
|
+
constructor(detail) {
|
|
40
|
+
super("invalid_input", detail);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function rat(num, den) {
|
|
44
|
+
return den < 0n ? { num: -num, den: -den } : { num, den };
|
|
45
|
+
}
|
|
46
|
+
function addRat(a, b) {
|
|
47
|
+
return rat(a.num * b.den + b.num * a.den, a.den * b.den);
|
|
48
|
+
}
|
|
49
|
+
function subRat(a, b) {
|
|
50
|
+
return rat(a.num * b.den - b.num * a.den, a.den * b.den);
|
|
51
|
+
}
|
|
52
|
+
function cmpRat(a, b) {
|
|
53
|
+
const l = a.num * b.den;
|
|
54
|
+
const r = b.num * a.den;
|
|
55
|
+
return l < r ? -1 : l > r ? 1 : 0;
|
|
56
|
+
}
|
|
57
|
+
/** Floor division and remainder for a positive divisor (Go's DivMod, Python's divmod). */
|
|
58
|
+
function divmod(num, den) {
|
|
59
|
+
let q = num / den;
|
|
60
|
+
let r = num % den;
|
|
61
|
+
if (r < 0n) {
|
|
62
|
+
q -= 1n;
|
|
63
|
+
r += den;
|
|
64
|
+
}
|
|
65
|
+
return [q, r];
|
|
66
|
+
}
|
|
67
|
+
function divRound(num, den, up) {
|
|
68
|
+
const [q, r] = divmod(num, den);
|
|
69
|
+
return up && r !== 0n ? q + 1n : q;
|
|
70
|
+
}
|
|
71
|
+
function safe(v, what) {
|
|
72
|
+
const n = Number(v);
|
|
73
|
+
if (!Number.isSafeInteger(n))
|
|
74
|
+
throw new InvalidQuoteInputError(`${what} ${v} is past the safe integer range`);
|
|
75
|
+
return n;
|
|
76
|
+
}
|
|
77
|
+
function int(v, what) {
|
|
78
|
+
if (!Number.isSafeInteger(v))
|
|
79
|
+
throw new InvalidQuoteInputError(`${what} ${v} is not a safe integer`);
|
|
80
|
+
return BigInt(v);
|
|
81
|
+
}
|
|
82
|
+
// The fee formulas: fees.ts, the one port of tape's internal/fees that the
|
|
83
|
+
// backtest uses too, at 6 decimals (micro-contracts and micro-dollars). Its
|
|
84
|
+
// FeeError is this module's InvalidQuoteInputError.
|
|
85
|
+
const MICRO_DECIMALS = 6;
|
|
86
|
+
/** fee's terms as fees.ts reads them, each parameter a safe integer. */
|
|
87
|
+
function termsOf(fee) {
|
|
88
|
+
const takerParams = {};
|
|
89
|
+
for (const [k, v] of Object.entries(fee.taker_params ?? {}))
|
|
90
|
+
takerParams[k] = int(v, k);
|
|
91
|
+
const min = fee.min_fee_micros;
|
|
92
|
+
return { formula: fee.formula, rounding: fee.rounding, takerParams, minFeeMicros: min === undefined || min === null ? null : int(min, "min_fee_micros") };
|
|
93
|
+
}
|
|
94
|
+
function asQuoteError(run) {
|
|
95
|
+
try {
|
|
96
|
+
return run();
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
if (err instanceof FeeError)
|
|
100
|
+
throw new InvalidQuoteInputError(err.message);
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function checkFeeInputs(size, notional) {
|
|
105
|
+
if (size <= 0n)
|
|
106
|
+
throw new InvalidQuoteInputError("a fee needs a positive size");
|
|
107
|
+
if (notional < 0n || notional > size)
|
|
108
|
+
throw new InvalidQuoteInputError("a fee's notional is out of range");
|
|
109
|
+
}
|
|
110
|
+
/** The taker fee of fee's formula for size micro-contracts against notional micro-dollars, exact, before rounding and any minimum. */
|
|
111
|
+
function exactTakerFee(fee, size, notional) {
|
|
112
|
+
checkFeeInputs(size, notional);
|
|
113
|
+
return asQuoteError(() => {
|
|
114
|
+
const f = exactFee(fee.formula, termsOf(fee).takerParams, size, notional);
|
|
115
|
+
return rat(f.n, f.d);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/** 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. */
|
|
119
|
+
function computeTakerFee(fee, size, notional) {
|
|
120
|
+
checkFeeInputs(size, notional);
|
|
121
|
+
return asQuoteError(() => takerFeeOf(termsOf(fee), size, notional, MICRO_DECIMALS));
|
|
122
|
+
}
|
|
123
|
+
/** The taker fee in micro-dollars for size micro-contracts against notional micro-dollars, as tape's fees.ComputeTakerFee at 6 decimals. */
|
|
124
|
+
export function takerFeeMicros(fee, size, notional) {
|
|
125
|
+
return safe(computeTakerFee(fee, int(size, "size"), int(notional, "notional")), "fee");
|
|
126
|
+
}
|
|
127
|
+
function validate(q) {
|
|
128
|
+
if (q.side !== "buy" && q.side !== "sell")
|
|
129
|
+
throw new InvalidQuoteInputError(`side ${JSON.stringify(q.side)} is neither buy nor sell`);
|
|
130
|
+
if (!(q.size_micro > 0))
|
|
131
|
+
throw new InvalidQuoteInputError(`size ${q.size_micro} is not positive`);
|
|
132
|
+
int(q.size_micro, "size");
|
|
133
|
+
for (const m of q.members) {
|
|
134
|
+
if (m.fee_status === "ok") {
|
|
135
|
+
if (!m.fee)
|
|
136
|
+
throw new InvalidQuoteInputError(`${m.venue}: fee status ok with no fee row`);
|
|
137
|
+
}
|
|
138
|
+
else if (m.fee_status !== "no_row" && m.fee_status !== "masked" && m.fee_status !== "blocked") {
|
|
139
|
+
throw new InvalidQuoteInputError(`${m.venue}: fee status ${JSON.stringify(m.fee_status)}`);
|
|
140
|
+
}
|
|
141
|
+
if (m.fee_per !== "order" && m.fee_per !== "level")
|
|
142
|
+
throw new InvalidQuoteInputError(`${m.venue}: fee basis ${JSON.stringify(m.fee_per)}`);
|
|
143
|
+
const b = m.book;
|
|
144
|
+
if (!b)
|
|
145
|
+
continue;
|
|
146
|
+
if ((b.min_size_micro ?? 0) < 0 || (b.size_step_micro ?? 0) < 0)
|
|
147
|
+
throw new InvalidQuoteInputError(`${m.venue}: a negative minimum or step`);
|
|
148
|
+
for (const l of b.levels ?? []) {
|
|
149
|
+
if (l.price_micros < 0 || l.price_micros > MICRO || !(l.size_micro > 0))
|
|
150
|
+
throw new InvalidQuoteInputError(`${m.venue}: level ${l.size_micro} at ${l.price_micros}`);
|
|
151
|
+
int(l.price_micros, "price");
|
|
152
|
+
int(l.size_micro, "size");
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function fit(m, size) {
|
|
157
|
+
let q = size;
|
|
158
|
+
if (m.step > 1n)
|
|
159
|
+
q -= q % m.step;
|
|
160
|
+
return q < m.minSize ? 0n : q;
|
|
161
|
+
}
|
|
162
|
+
function perContract(amount, size, side) {
|
|
163
|
+
if (size === 0n)
|
|
164
|
+
return 0n;
|
|
165
|
+
return divRound(amount * MICRO_N, size, side === "buy");
|
|
166
|
+
}
|
|
167
|
+
function walk(m, size, side) {
|
|
168
|
+
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 };
|
|
169
|
+
if (size === 0n)
|
|
170
|
+
return leg;
|
|
171
|
+
const takes = [];
|
|
172
|
+
let left = size;
|
|
173
|
+
for (const l of m.levels) {
|
|
174
|
+
if (left === 0n)
|
|
175
|
+
break;
|
|
176
|
+
const t = left < l.size ? left : l.size;
|
|
177
|
+
takes.push([t, l.price]);
|
|
178
|
+
left -= t;
|
|
179
|
+
}
|
|
180
|
+
const up = side === "buy";
|
|
181
|
+
leg.notional = divRound(takes.reduce((s, [t, p]) => s + t * p, 0n), MICRO_N, up);
|
|
182
|
+
if (m.fee) {
|
|
183
|
+
if (m.m.fee_per === "order") {
|
|
184
|
+
leg.fee = computeTakerFee(m.fee, size, leg.notional);
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
for (const [t, p] of takes)
|
|
188
|
+
leg.fee += computeTakerFee(m.fee, t, divRound(t * p, MICRO_N, up));
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
leg.net = up ? leg.notional + leg.fee : leg.notional - leg.fee;
|
|
192
|
+
return leg;
|
|
193
|
+
}
|
|
194
|
+
function rank(quotable, excluded, q) {
|
|
195
|
+
const buy = q.side === "buy";
|
|
196
|
+
const ranked = [];
|
|
197
|
+
quotable.forEach((m, i) => {
|
|
198
|
+
if (excluded.has(i))
|
|
199
|
+
return;
|
|
200
|
+
for (const l of m.levels) {
|
|
201
|
+
let key = rat(l.price, 1n);
|
|
202
|
+
if (m.fee) {
|
|
203
|
+
const f = exactTakerFee(m.fee, MICRO_N, l.price);
|
|
204
|
+
key = buy ? addRat(key, f) : subRat(key, f);
|
|
205
|
+
}
|
|
206
|
+
ranked.push({ key, i, seq: ranked.length, level: l });
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
// Best net first; ties to the earlier member, then the better price, then
|
|
210
|
+
// the order the levels were taken in (a stable sort, as in Go).
|
|
211
|
+
ranked.sort((a, b) => {
|
|
212
|
+
let c = cmpRat(a.key, b.key);
|
|
213
|
+
if (!buy)
|
|
214
|
+
c = -c;
|
|
215
|
+
if (c !== 0)
|
|
216
|
+
return c;
|
|
217
|
+
if (a.i !== b.i)
|
|
218
|
+
return a.i - b.i;
|
|
219
|
+
if (a.level.price !== b.level.price)
|
|
220
|
+
return (a.level.price < b.level.price ? -1 : 1) * (buy ? 1 : -1);
|
|
221
|
+
return a.seq - b.seq;
|
|
222
|
+
});
|
|
223
|
+
const alloc = quotable.map(() => 0n);
|
|
224
|
+
let left = BigInt(q.size_micro);
|
|
225
|
+
for (const r of ranked) {
|
|
226
|
+
if (left === 0n)
|
|
227
|
+
break;
|
|
228
|
+
const t = left < r.level.size ? left : r.level.size;
|
|
229
|
+
alloc[r.i] = (alloc[r.i] ?? 0n) + t;
|
|
230
|
+
left -= t;
|
|
231
|
+
}
|
|
232
|
+
return alloc;
|
|
233
|
+
}
|
|
234
|
+
function splitPlan(quotable, q) {
|
|
235
|
+
const excluded = new Set();
|
|
236
|
+
for (let n = 0; n < quotable.length; n++) {
|
|
237
|
+
const alloc = rank(quotable, excluded, q);
|
|
238
|
+
let again = false;
|
|
239
|
+
alloc.forEach((a, i) => {
|
|
240
|
+
if (a > 0n && fit(quotable[i], a) === 0n) {
|
|
241
|
+
excluded.add(i);
|
|
242
|
+
again = true;
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
if (again)
|
|
246
|
+
continue;
|
|
247
|
+
const legs = [];
|
|
248
|
+
alloc.forEach((a, i) => {
|
|
249
|
+
const m = quotable[i];
|
|
250
|
+
const share = fit(m, a);
|
|
251
|
+
if (share > 0n)
|
|
252
|
+
legs.push(walk(m, share, q.side));
|
|
253
|
+
});
|
|
254
|
+
return legs;
|
|
255
|
+
}
|
|
256
|
+
return [];
|
|
257
|
+
}
|
|
258
|
+
function bestPlan(plans, side) {
|
|
259
|
+
let best = null;
|
|
260
|
+
let bestFilled = 0n;
|
|
261
|
+
let bestNet = 0n;
|
|
262
|
+
for (const p of plans) {
|
|
263
|
+
const filled = p.reduce((s, l) => s + l.size, 0n);
|
|
264
|
+
const net = p.reduce((s, l) => s + l.net, 0n);
|
|
265
|
+
if (filled === 0n)
|
|
266
|
+
continue;
|
|
267
|
+
let better = best === null || filled > bestFilled;
|
|
268
|
+
if (!better && filled === bestFilled) {
|
|
269
|
+
if ((side === "buy" && net < bestNet) || (side === "sell" && net > bestNet))
|
|
270
|
+
better = true;
|
|
271
|
+
else if (net === bestNet)
|
|
272
|
+
better = p.length < (best?.length ?? 0);
|
|
273
|
+
}
|
|
274
|
+
if (better) {
|
|
275
|
+
best = p;
|
|
276
|
+
bestFilled = filled;
|
|
277
|
+
bestNet = net;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return best;
|
|
281
|
+
}
|
|
282
|
+
function legOut(l, side) {
|
|
283
|
+
return {
|
|
284
|
+
venue: l.venue,
|
|
285
|
+
market_id: l.market_id,
|
|
286
|
+
token_id: l.token_id,
|
|
287
|
+
size_micro: safe(l.size, "size"),
|
|
288
|
+
notional_micros: safe(l.notional, "notional"),
|
|
289
|
+
fee_micros: safe(l.fee, "fee"),
|
|
290
|
+
net_micros: safe(l.net, "net"),
|
|
291
|
+
avg_price_micros: safe(perContract(l.notional, l.size, side), "price"),
|
|
292
|
+
net_avg_price_micros: safe(perContract(l.net, l.size, side), "price"),
|
|
293
|
+
fee_status: l.fee_status,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* The best plan for q, as tape's internal/quote.Quote computes it:
|
|
298
|
+
*
|
|
299
|
+
* 1. A side other than buy or sell, a size of 0 or less, a level priced
|
|
300
|
+
* outside 0 to 1,000,000 or sized 0 or less, or a member with an unknown
|
|
301
|
+
* fee status or basis throws InvalidQuoteInputError.
|
|
302
|
+
* 2. resolution_equal false throws RuleMismatchError with the rule note,
|
|
303
|
+
* unless allow_rule_mismatch; then the result warns.
|
|
304
|
+
* 3. A blocked member is skipped, and so is one with no book
|
|
305
|
+
* (venue_unreachable, with its reason); none left and one unreachable
|
|
306
|
+
* throws VenueUnreachableError naming each.
|
|
307
|
+
* 4. Each leg's notional is the exact sum of size x price rounded once (up
|
|
308
|
+
* for a buy, down for a sell); its fee is the row's on the leg's totals
|
|
309
|
+
* (fee_per order) or on each level's fill (level). A fee status other than
|
|
310
|
+
* ok has no fee to count: unknown, never zero. When a member whose fee is
|
|
311
|
+
* known can fill some of the size alone, a fee-unknown member is left out
|
|
312
|
+
* of the split and the best plan (a price before fees is never compared
|
|
313
|
+
* with one after them), still quoted alone in venues before fees, and
|
|
314
|
+
* warns fee_unknown; otherwise the members are compared before fees and
|
|
315
|
+
* the warning says no fee is counted.
|
|
316
|
+
* 5. Each member alone fills the size or its depth, cut to its size step,
|
|
317
|
+
* nothing under its minimum; every reachable member is in venues.
|
|
318
|
+
* 6. The split ranks every level by price plus the exact fee of one contract
|
|
319
|
+
* (minus it for a sell), takes them in order, cuts each share to its step
|
|
320
|
+
* and leaves out a member under its minimum.
|
|
321
|
+
* 7. The best plan fills the most, then nets the least (buy) or the most
|
|
322
|
+
* (sell), then has the fewer legs; a partial fill warns.
|
|
323
|
+
*/
|
|
324
|
+
export function computeQuote(q) {
|
|
325
|
+
validate(q);
|
|
326
|
+
if (!q.resolution_equal && !q.allow_rule_mismatch)
|
|
327
|
+
throw new RuleMismatchError(q.rule_note);
|
|
328
|
+
const res = {
|
|
329
|
+
event_id: q.event_id,
|
|
330
|
+
side: q.side,
|
|
331
|
+
size_micro: q.size_micro,
|
|
332
|
+
plan: "none",
|
|
333
|
+
filled_micro: 0,
|
|
334
|
+
notional_micros: 0,
|
|
335
|
+
fee_micros: 0,
|
|
336
|
+
net_micros: 0,
|
|
337
|
+
avg_price_micros: 0,
|
|
338
|
+
net_avg_price_micros: 0,
|
|
339
|
+
legs: [],
|
|
340
|
+
venues: [],
|
|
341
|
+
skipped: [],
|
|
342
|
+
warnings: [],
|
|
343
|
+
};
|
|
344
|
+
if (!q.resolution_equal)
|
|
345
|
+
res.warnings.push(`rule_mismatch: ${q.rule_note}`);
|
|
346
|
+
const quotable = [];
|
|
347
|
+
const unreachable = [];
|
|
348
|
+
for (const m of q.members) {
|
|
349
|
+
if (m.blocked || m.fee_status === "blocked") {
|
|
350
|
+
res.skipped.push({ venue: m.venue, market_id: m.market_id, reason: "blocked" });
|
|
351
|
+
}
|
|
352
|
+
else if (!m.book) {
|
|
353
|
+
const skip = { venue: m.venue, market_id: m.market_id, reason: "venue_unreachable" };
|
|
354
|
+
if (m.unreachable)
|
|
355
|
+
skip.detail = m.unreachable;
|
|
356
|
+
res.skipped.push(skip);
|
|
357
|
+
unreachable.push(m.unreachable ? `${m.venue} (${m.unreachable})` : m.venue);
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
const buy = q.side === "buy";
|
|
361
|
+
// A stable sort: equal prices keep their order.
|
|
362
|
+
const levels = (m.book.levels ?? [])
|
|
363
|
+
.map((l) => ({ price: BigInt(l.price_micros), size: BigInt(l.size_micro) }))
|
|
364
|
+
.sort((a, b) => (a.price === b.price ? 0 : (a.price < b.price ? -1 : 1) * (buy ? 1 : -1)));
|
|
365
|
+
const fee = m.fee_status === "ok" ? (m.fee ?? null) : null;
|
|
366
|
+
quotable.push({
|
|
367
|
+
m,
|
|
368
|
+
levels,
|
|
369
|
+
depth: levels.reduce((s, l) => s + l.size, 0n),
|
|
370
|
+
fee,
|
|
371
|
+
minSize: BigInt(m.book.min_size_micro ?? 0),
|
|
372
|
+
step: BigInt(m.book.size_step_micro ?? 0),
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (quotable.length === 0) {
|
|
377
|
+
if (unreachable.length > 0)
|
|
378
|
+
throw new VenueUnreachableError(unreachable.join("; "));
|
|
379
|
+
return res;
|
|
380
|
+
}
|
|
381
|
+
const size = BigInt(q.size_micro);
|
|
382
|
+
// A fee is compared only with fees: when a member whose fee is known can
|
|
383
|
+
// fill some of the size alone, the plans leave out the members whose fee is
|
|
384
|
+
// unknown (step 4).
|
|
385
|
+
const feeKnown = quotable.some((m) => m.fee !== null && fit(m, size < m.depth ? size : m.depth) > 0n);
|
|
386
|
+
const planned = [];
|
|
387
|
+
const plans = [];
|
|
388
|
+
let leftOut = false;
|
|
389
|
+
for (const m of quotable) {
|
|
390
|
+
const alloc = fit(m, size < m.depth ? size : m.depth);
|
|
391
|
+
const leg = walk(m, alloc, q.side);
|
|
392
|
+
res.venues.push({ depth_micro: safe(m.depth, "depth"), ...legOut(leg, q.side) });
|
|
393
|
+
if (m.fee === null && feeKnown) {
|
|
394
|
+
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`);
|
|
395
|
+
leftOut = true;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
if (m.fee === null)
|
|
399
|
+
res.warnings.push(`fee_unknown: ${m.m.venue} (${m.m.fee_status}): its fee is not counted`);
|
|
400
|
+
planned.push(m);
|
|
401
|
+
if (alloc > 0n)
|
|
402
|
+
plans.push([leg]);
|
|
403
|
+
}
|
|
404
|
+
const split = splitPlan(planned, q);
|
|
405
|
+
if (split.length > 1)
|
|
406
|
+
plans.push(split);
|
|
407
|
+
const best = bestPlan(plans, q.side);
|
|
408
|
+
if (!best) {
|
|
409
|
+
res.warnings.push(`partial: the books hold 0 of ${q.size_micro} micro-contracts on this side`);
|
|
410
|
+
return res;
|
|
411
|
+
}
|
|
412
|
+
let filled = 0n;
|
|
413
|
+
let notional = 0n;
|
|
414
|
+
let fee = 0n;
|
|
415
|
+
let net = 0n;
|
|
416
|
+
for (const l of best) {
|
|
417
|
+
filled += l.size;
|
|
418
|
+
notional += l.notional;
|
|
419
|
+
fee += l.fee;
|
|
420
|
+
net += l.net;
|
|
421
|
+
}
|
|
422
|
+
res.legs = best.map((l) => legOut(l, q.side));
|
|
423
|
+
res.filled_micro = safe(filled, "size");
|
|
424
|
+
res.notional_micros = safe(notional, "notional");
|
|
425
|
+
res.fee_micros = safe(fee, "fee");
|
|
426
|
+
res.net_micros = safe(net, "net");
|
|
427
|
+
res.avg_price_micros = safe(perContract(notional, filled, q.side), "price");
|
|
428
|
+
res.net_avg_price_micros = safe(perContract(net, filled, q.side), "price");
|
|
429
|
+
res.plan = best.length > 1 ? "split" : "venue";
|
|
430
|
+
if (filled < size && leftOut) {
|
|
431
|
+
res.warnings.push(`partial: the plan fills ${filled} of ${q.size_micro} micro-contracts on this side, without the venues whose fee is unknown`);
|
|
432
|
+
}
|
|
433
|
+
else if (filled < size) {
|
|
434
|
+
res.warnings.push(`partial: the books hold ${filled} of ${q.size_micro} micro-contracts on this side`);
|
|
435
|
+
}
|
|
436
|
+
return res;
|
|
437
|
+
}
|