@perpbrain/sdk 0.0.0-stage → 0.1.2
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 +25 -2
- package/dist/cjs/card.d.ts +2 -0
- package/dist/cjs/card.js +311 -0
- package/dist/cjs/cli.d.ts +3 -0
- package/dist/cjs/cli.js +33 -0
- package/dist/cjs/guarded.d.ts +12 -0
- package/dist/cjs/guarded.js +52 -0
- package/dist/cjs/guards.d.ts +154 -0
- package/dist/cjs/guards.js +855 -0
- package/dist/cjs/index.d.ts +16 -0
- package/dist/cjs/index.js +66 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/receipt.d.ts +45 -0
- package/dist/cjs/receipt.js +855 -0
- package/dist/cjs/study.d.ts +29 -0
- package/dist/cjs/study.js +259 -0
- package/dist/cjs/vendor/costs.d.ts +64 -0
- package/dist/cjs/vendor/costs.js +247 -0
- package/dist/cjs/vendor/execution.d.ts +44 -0
- package/dist/cjs/vendor/execution.js +132 -0
- package/dist/cjs/vendor/fees.d.ts +17 -0
- package/dist/cjs/vendor/fees.js +82 -0
- package/dist/cjs/vendor/funding_adapter.d.ts +11 -0
- package/dist/cjs/vendor/funding_adapter.js +33 -0
- package/dist/cjs/vendor/info.d.ts +24 -0
- package/dist/cjs/vendor/info.js +55 -0
- package/dist/cjs/vendor/queries.d.ts +69 -0
- package/dist/cjs/vendor/queries.js +210 -0
- package/dist/cjs/vendor/rateLimit.d.ts +14 -0
- package/dist/cjs/vendor/rateLimit.js +57 -0
- package/dist/cjs/vendor/simDefaults.d.ts +31 -0
- package/dist/cjs/vendor/simDefaults.js +49 -0
- package/dist/cjs/vendor/simulate.d.ts +130 -0
- package/dist/cjs/vendor/simulate.js +610 -0
- package/dist/esm/card.d.ts +2 -0
- package/dist/esm/card.js +308 -0
- package/dist/esm/cli.d.ts +3 -0
- package/dist/esm/cli.js +31 -0
- package/dist/esm/guarded.d.ts +12 -0
- package/dist/esm/guarded.js +49 -0
- package/dist/esm/guards.d.ts +154 -0
- package/dist/esm/guards.js +841 -0
- package/dist/esm/index.d.ts +16 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/receipt.d.ts +45 -0
- package/dist/esm/receipt.js +839 -0
- package/dist/esm/study.d.ts +29 -0
- package/dist/esm/study.js +249 -0
- package/dist/esm/vendor/costs.d.ts +64 -0
- package/dist/esm/vendor/costs.js +240 -0
- package/dist/esm/vendor/execution.d.ts +44 -0
- package/dist/esm/vendor/execution.js +122 -0
- package/dist/esm/vendor/fees.d.ts +17 -0
- package/dist/esm/vendor/fees.js +74 -0
- package/dist/esm/vendor/funding_adapter.d.ts +11 -0
- package/dist/esm/vendor/funding_adapter.js +30 -0
- package/dist/esm/vendor/info.d.ts +24 -0
- package/dist/esm/vendor/info.js +49 -0
- package/dist/esm/vendor/queries.d.ts +69 -0
- package/dist/esm/vendor/queries.js +196 -0
- package/dist/esm/vendor/rateLimit.d.ts +14 -0
- package/dist/esm/vendor/rateLimit.js +53 -0
- package/dist/esm/vendor/simDefaults.d.ts +31 -0
- package/dist/esm/vendor/simDefaults.js +44 -0
- package/dist/esm/vendor/simulate.d.ts +130 -0
- package/dist/esm/vendor/simulate.js +605 -0
- package/package.json +64 -4
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Multiple-testing accounting for strategy research receipts. */
|
|
2
|
+
export interface StudyObservation {
|
|
3
|
+
time_ms: number;
|
|
4
|
+
outcome_r: string;
|
|
5
|
+
turnover: string;
|
|
6
|
+
}
|
|
7
|
+
export interface StudyAccounting {
|
|
8
|
+
label: "SIMULATED";
|
|
9
|
+
variants_tried: number;
|
|
10
|
+
observation_count: number;
|
|
11
|
+
sharpe_ratio: string;
|
|
12
|
+
deflated_sharpe_ratio: string;
|
|
13
|
+
queue_position: "NOT_MODELLED";
|
|
14
|
+
liquidation: "NOT_MODELLED";
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* "fixed18": receipts v5+, the integer algorithm shared exactly with Python
|
|
18
|
+
* (python/perpbrain-read/src/perpbrain_read/sim/fixed.py, issue 3). "float": receipts v1-v4,
|
|
19
|
+
* the original float arithmetic (kept so old receipts verify as before).
|
|
20
|
+
*/
|
|
21
|
+
export type StudyNumerics = "float" | "fixed18";
|
|
22
|
+
export declare function studyAccounting(observations: readonly StudyObservation[], variantsTried: number, numerics?: StudyNumerics): StudyAccounting;
|
|
23
|
+
export declare function expectedMaxSharpe(variantsTried: number, observationCount: number): number;
|
|
24
|
+
export declare const AS241_FIXED: Readonly<Record<"a" | "b" | "c" | "d" | "e" | "f", readonly bigint[]>>;
|
|
25
|
+
export declare function fixedSharpe(values: readonly bigint[]): bigint;
|
|
26
|
+
export declare function fixedExpectedMaxSharpe(variantsTried: number, observationCount: number): bigint;
|
|
27
|
+
export declare function fixedNormalQuantile(p: bigint): bigint;
|
|
28
|
+
export declare function fln(value: bigint): bigint;
|
|
29
|
+
export declare function fsqrt(value: bigint): bigint;
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** Multiple-testing accounting for strategy research receipts. */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.AS241_FIXED = void 0;
|
|
5
|
+
exports.studyAccounting = studyAccounting;
|
|
6
|
+
exports.expectedMaxSharpe = expectedMaxSharpe;
|
|
7
|
+
exports.fixedSharpe = fixedSharpe;
|
|
8
|
+
exports.fixedExpectedMaxSharpe = fixedExpectedMaxSharpe;
|
|
9
|
+
exports.fixedNormalQuantile = fixedNormalQuantile;
|
|
10
|
+
exports.fln = fln;
|
|
11
|
+
exports.fsqrt = fsqrt;
|
|
12
|
+
const EULER_GAMMA = 0.5772156649015329;
|
|
13
|
+
function studyAccounting(observations, variantsTried, numerics = "fixed18") {
|
|
14
|
+
if (!Number.isInteger(variantsTried) || variantsTried < 1) {
|
|
15
|
+
throw new Error("variants_tried must be at least 1");
|
|
16
|
+
}
|
|
17
|
+
const ordered = orderedObservations(observations);
|
|
18
|
+
if (numerics === "fixed18") {
|
|
19
|
+
return fixedStudy(ordered, variantsTried);
|
|
20
|
+
}
|
|
21
|
+
const outcomes = ordered.map((row) => decimal(row.outcome_r, "outcome_r"));
|
|
22
|
+
const count = outcomes.length;
|
|
23
|
+
if (count < 2) {
|
|
24
|
+
throw new Error("at least two observations are required");
|
|
25
|
+
}
|
|
26
|
+
const mean = outcomes.reduce((sum, item) => sum + item, 0) / count;
|
|
27
|
+
const variance = outcomes.reduce((sum, item) => sum + (item - mean) ** 2, 0) / (count - 1);
|
|
28
|
+
const raw = variance <= 0 ? 0 : mean / Math.sqrt(variance);
|
|
29
|
+
const deflated = raw - expectedMaxSharpe(variantsTried, count);
|
|
30
|
+
return {
|
|
31
|
+
label: "SIMULATED",
|
|
32
|
+
variants_tried: variantsTried,
|
|
33
|
+
observation_count: count,
|
|
34
|
+
sharpe_ratio: plain(raw),
|
|
35
|
+
deflated_sharpe_ratio: plain(deflated),
|
|
36
|
+
queue_position: "NOT_MODELLED",
|
|
37
|
+
liquidation: "NOT_MODELLED",
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function expectedMaxSharpe(variantsTried, observationCount) {
|
|
41
|
+
if (variantsTried < 1) {
|
|
42
|
+
throw new Error("variants_tried must be at least 1");
|
|
43
|
+
}
|
|
44
|
+
if (observationCount < 2) {
|
|
45
|
+
throw new Error("at least two observations are required");
|
|
46
|
+
}
|
|
47
|
+
if (variantsTried === 1) {
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
const z1 = inverseNormalCdf(1 - 1 / variantsTried);
|
|
51
|
+
const z2 = inverseNormalCdf(1 - 1 / (variantsTried * Math.E));
|
|
52
|
+
const peak = (1 - EULER_GAMMA) * z1 + EULER_GAMMA * z2;
|
|
53
|
+
return peak / Math.sqrt(observationCount);
|
|
54
|
+
}
|
|
55
|
+
function orderedObservations(observations) {
|
|
56
|
+
if (observations.length < 2) {
|
|
57
|
+
throw new Error("at least two observations are required");
|
|
58
|
+
}
|
|
59
|
+
return [...observations].sort((left, right) => left.time_ms - right.time_ms);
|
|
60
|
+
}
|
|
61
|
+
function decimal(value, label) {
|
|
62
|
+
const parsed = Number(value);
|
|
63
|
+
if (!Number.isFinite(parsed)) {
|
|
64
|
+
throw new Error(`${label} must be a decimal`);
|
|
65
|
+
}
|
|
66
|
+
return parsed;
|
|
67
|
+
}
|
|
68
|
+
function plain(value) {
|
|
69
|
+
const text = value.toString();
|
|
70
|
+
if (!text.includes(".")) {
|
|
71
|
+
return text;
|
|
72
|
+
}
|
|
73
|
+
return text.replace(/0+$/, "").replace(/\.$/, "");
|
|
74
|
+
}
|
|
75
|
+
function inverseNormalCdf(probability) {
|
|
76
|
+
// Acklam's approximation for the normal quantile.
|
|
77
|
+
const a = [
|
|
78
|
+
-3.969683028665376e1, 2.209460984245205e2, -2.759285084469642e2, 1.383577518672690e2,
|
|
79
|
+
-3.066479806614716e1, 2.506628277459239e0,
|
|
80
|
+
];
|
|
81
|
+
const b = [-5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1, -1.328068155288572e1];
|
|
82
|
+
const c = [
|
|
83
|
+
-7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838e0, -2.549732539343734e0,
|
|
84
|
+
4.374664141464968e0, 2.938163982698783e0,
|
|
85
|
+
];
|
|
86
|
+
const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996e0, 3.754408661907416e0];
|
|
87
|
+
const pLow = 0.02425;
|
|
88
|
+
const pHigh = 1 - pLow;
|
|
89
|
+
if (probability < pLow) {
|
|
90
|
+
const q = Math.sqrt(-2 * Math.log(probability));
|
|
91
|
+
return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
|
|
92
|
+
((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
|
|
93
|
+
}
|
|
94
|
+
if (probability <= pHigh) {
|
|
95
|
+
const q = probability - 0.5;
|
|
96
|
+
const r = q * q;
|
|
97
|
+
return ((((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q) / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
|
|
98
|
+
}
|
|
99
|
+
const q = Math.sqrt(-2 * Math.log(1 - probability));
|
|
100
|
+
return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /
|
|
101
|
+
((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
|
|
102
|
+
}
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// Fixed-point study statistics. Operation for operation the same as Python's sim/fixed.py:
|
|
105
|
+
// 10^18-scaled bigint values, every division truncating toward zero (bigint semantics).
|
|
106
|
+
const ONE = 10n ** 18n;
|
|
107
|
+
const BPS_HALF = ONE / 2n;
|
|
108
|
+
const EULER_GAMMA_FIXED = 577215664901532860n;
|
|
109
|
+
const E_FIXED = 2718281828459045235n;
|
|
110
|
+
const LN2_FIXED = 693147180559945309n;
|
|
111
|
+
// AS241 (Wichura 1988) coefficients, constant term first, truncated to 18 decimals.
|
|
112
|
+
exports.AS241_FIXED = {
|
|
113
|
+
a: [3387132872796366608n, 133141667891784377450n, 1971590950306551442700n, 13731693765509461125000n, 45921953931549871457000n, 67265770927008700853000n, 33430575583588128105000n, 2509080928730122672700n],
|
|
114
|
+
b: [1000000000000000000n, 42313330701600911252n, 687187007492057908300n, 5394196021424751107700n, 21213794301586595867000n, 39307895800092710610000n, 28729085735721942674000n, 5226495278852854561000n],
|
|
115
|
+
c: [1423437110749683577n, 4630337846156545295n, 5769497221460691405n, 3647848324763204605n, 1270458252452368382n, 241780725177450611n, 22723844989269184n, 774545014278341n],
|
|
116
|
+
d: [1000000000000000000n, 2053191626637758821n, 1676384830183803849n, 689767334985100004n, 148103976427480074n, 15198666563616457n, 547593808499534n, 1050750071n],
|
|
117
|
+
e: [6657904643501103777n, 5463784911164114369n, 1784826539917291335n, 296560571828504891n, 26532189526576123n, 1242660947388078n, 27115555687434n, 201033439929n],
|
|
118
|
+
f: [1000000000000000000n, 599832206555887937n, 136929880922735805n, 14875361290850614n, 786869131145613n, 18463183175100n, 142151175831n, 2044n],
|
|
119
|
+
};
|
|
120
|
+
function fixedStudy(ordered, variantsTried) {
|
|
121
|
+
const values = ordered.map((row) => parseFixed(row.outcome_r));
|
|
122
|
+
const raw = fixedSharpe(values);
|
|
123
|
+
const deflated = raw - fixedExpectedMaxSharpe(variantsTried, values.length);
|
|
124
|
+
return {
|
|
125
|
+
label: "SIMULATED",
|
|
126
|
+
variants_tried: variantsTried,
|
|
127
|
+
observation_count: values.length,
|
|
128
|
+
sharpe_ratio: formatFixed(raw),
|
|
129
|
+
deflated_sharpe_ratio: formatFixed(deflated),
|
|
130
|
+
queue_position: "NOT_MODELLED",
|
|
131
|
+
liquidation: "NOT_MODELLED",
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function fixedSharpe(values) {
|
|
135
|
+
const count = BigInt(values.length);
|
|
136
|
+
const mean = values.reduce((sum, item) => sum + item, 0n) / count;
|
|
137
|
+
const variance = values.reduce((sum, item) => sum + fmul(item - mean, item - mean), 0n) / (count - 1n);
|
|
138
|
+
if (variance <= 0n) {
|
|
139
|
+
return 0n;
|
|
140
|
+
}
|
|
141
|
+
return fdiv(mean, fsqrt(variance));
|
|
142
|
+
}
|
|
143
|
+
function fixedExpectedMaxSharpe(variantsTried, observationCount) {
|
|
144
|
+
if (variantsTried === 1) {
|
|
145
|
+
return 0n;
|
|
146
|
+
}
|
|
147
|
+
const n = BigInt(variantsTried);
|
|
148
|
+
const p1 = ONE - ONE / n;
|
|
149
|
+
const p2 = ONE - (ONE * ONE) / (n * E_FIXED);
|
|
150
|
+
const z1 = fixedNormalQuantile(p1);
|
|
151
|
+
const z2 = fixedNormalQuantile(p2);
|
|
152
|
+
const peak = fmul(ONE - EULER_GAMMA_FIXED, z1) + fmul(EULER_GAMMA_FIXED, z2);
|
|
153
|
+
return fdiv(peak, fsqrt(BigInt(observationCount) * ONE));
|
|
154
|
+
}
|
|
155
|
+
function fixedNormalQuantile(p) {
|
|
156
|
+
if (p <= 0n || p >= ONE) {
|
|
157
|
+
throw new Error("probability must be in (0, 1)");
|
|
158
|
+
}
|
|
159
|
+
const q = p - BPS_HALF;
|
|
160
|
+
if (abs(q) <= 425000000000000000n) {
|
|
161
|
+
const r = 180625000000000000n - fmul(q, q);
|
|
162
|
+
return fdiv(fmul(q, poly(exports.AS241_FIXED.a, r)), poly(exports.AS241_FIXED.b, r));
|
|
163
|
+
}
|
|
164
|
+
let r = q < 0n ? p : ONE - p;
|
|
165
|
+
r = fsqrt(-fln(r));
|
|
166
|
+
let value;
|
|
167
|
+
if (r <= 5n * ONE) {
|
|
168
|
+
r -= 1600000000000000000n;
|
|
169
|
+
value = fdiv(poly(exports.AS241_FIXED.c, r), poly(exports.AS241_FIXED.d, r));
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
r -= 5n * ONE;
|
|
173
|
+
value = fdiv(poly(exports.AS241_FIXED.e, r), poly(exports.AS241_FIXED.f, r));
|
|
174
|
+
}
|
|
175
|
+
return q < 0n ? -value : value;
|
|
176
|
+
}
|
|
177
|
+
function fln(value) {
|
|
178
|
+
if (value <= 0n) {
|
|
179
|
+
throw new Error("log of a non-positive value");
|
|
180
|
+
}
|
|
181
|
+
let exponent = 0n;
|
|
182
|
+
let mantissa = value;
|
|
183
|
+
while (mantissa < ONE) {
|
|
184
|
+
mantissa *= 2n;
|
|
185
|
+
exponent -= 1n;
|
|
186
|
+
}
|
|
187
|
+
while (mantissa >= 2n * ONE) {
|
|
188
|
+
mantissa /= 2n;
|
|
189
|
+
exponent += 1n;
|
|
190
|
+
}
|
|
191
|
+
const s = fdiv(mantissa - ONE, mantissa + ONE);
|
|
192
|
+
const square = fmul(s, s);
|
|
193
|
+
let term = s;
|
|
194
|
+
let total = 0n;
|
|
195
|
+
let k = 1n;
|
|
196
|
+
while (term !== 0n) {
|
|
197
|
+
total += term / k;
|
|
198
|
+
term = fmul(term, square);
|
|
199
|
+
k += 2n;
|
|
200
|
+
}
|
|
201
|
+
return exponent * LN2_FIXED + 2n * total;
|
|
202
|
+
}
|
|
203
|
+
function fsqrt(value) {
|
|
204
|
+
if (value < 0n) {
|
|
205
|
+
throw new Error("square root of a negative value");
|
|
206
|
+
}
|
|
207
|
+
return isqrt(value * ONE);
|
|
208
|
+
}
|
|
209
|
+
function isqrt(n) {
|
|
210
|
+
if (n < 2n) {
|
|
211
|
+
return n;
|
|
212
|
+
}
|
|
213
|
+
// Newton's method from above converges to floor(sqrt(n)) (same result as Python math.isqrt).
|
|
214
|
+
let x = 1n << BigInt(Math.ceil(n.toString(2).length / 2));
|
|
215
|
+
for (;;) {
|
|
216
|
+
const y = (x + n / x) / 2n;
|
|
217
|
+
if (y >= x) {
|
|
218
|
+
return x;
|
|
219
|
+
}
|
|
220
|
+
x = y;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function poly(coefficients, x) {
|
|
224
|
+
let total = 0n;
|
|
225
|
+
for (let index = coefficients.length - 1; index >= 0; index -= 1) {
|
|
226
|
+
total = fmul(total, x) + coefficients[index];
|
|
227
|
+
}
|
|
228
|
+
return total;
|
|
229
|
+
}
|
|
230
|
+
function fmul(left, right) {
|
|
231
|
+
return (left * right) / ONE;
|
|
232
|
+
}
|
|
233
|
+
function fdiv(left, right) {
|
|
234
|
+
return (left * ONE) / right;
|
|
235
|
+
}
|
|
236
|
+
function abs(value) {
|
|
237
|
+
return value < 0n ? -value : value;
|
|
238
|
+
}
|
|
239
|
+
function parseFixed(text) {
|
|
240
|
+
if (!/^-?\d+(\.\d+)?$/.test(text)) {
|
|
241
|
+
throw new Error("outcome_r must be a decimal");
|
|
242
|
+
}
|
|
243
|
+
const negative = text.startsWith("-");
|
|
244
|
+
const body = negative ? text.slice(1) : text;
|
|
245
|
+
const [whole = "0", frac = ""] = body.split(".");
|
|
246
|
+
if (frac.length > 18) {
|
|
247
|
+
throw new Error("decimal scale exceeded");
|
|
248
|
+
}
|
|
249
|
+
const value = BigInt(whole) * ONE + BigInt(frac.padEnd(18, "0"));
|
|
250
|
+
return negative ? -value : value;
|
|
251
|
+
}
|
|
252
|
+
function formatFixed(value) {
|
|
253
|
+
const negative = value < 0n;
|
|
254
|
+
const magnitude = negative ? -value : value;
|
|
255
|
+
const whole = magnitude / ONE;
|
|
256
|
+
const frac = (magnitude % ONE).toString().padStart(18, "0").replace(/0+$/, "");
|
|
257
|
+
const text = frac.length === 0 ? whole.toString() : `${whole.toString()}.${frac}`;
|
|
258
|
+
return negative ? `-${text}` : text;
|
|
259
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Execution-cost breakdown. Fees, book-walk slippage versus mid, and funding paid or received. */
|
|
2
|
+
import type { Book, Fill, FundingPayment } from "./simulate.ts";
|
|
3
|
+
export declare const COST_SCHEMA_VERSION = 1;
|
|
4
|
+
export declare const NOT_RECORDED = "not recorded";
|
|
5
|
+
export interface NotModelledItem {
|
|
6
|
+
item: "queue_position" | "liquidation";
|
|
7
|
+
status: "NOT_MODELLED";
|
|
8
|
+
}
|
|
9
|
+
export interface TradeCost {
|
|
10
|
+
index: number;
|
|
11
|
+
kind: string;
|
|
12
|
+
side: string;
|
|
13
|
+
liquidity: string;
|
|
14
|
+
fee_version: string;
|
|
15
|
+
taker_bps: string;
|
|
16
|
+
maker_bps: string;
|
|
17
|
+
fee_usd: string;
|
|
18
|
+
taker_fee_usd: string;
|
|
19
|
+
maker_fee_usd: string;
|
|
20
|
+
slippage_vs_mid_usd: string | null;
|
|
21
|
+
}
|
|
22
|
+
export interface TierFee {
|
|
23
|
+
fee_version: string;
|
|
24
|
+
taker_bps: string;
|
|
25
|
+
maker_bps: string;
|
|
26
|
+
taker_usd: string;
|
|
27
|
+
maker_usd: string;
|
|
28
|
+
fee_usd: string;
|
|
29
|
+
}
|
|
30
|
+
export interface FundingCost {
|
|
31
|
+
time_ms: number;
|
|
32
|
+
payment_usd: string;
|
|
33
|
+
paid_usd: string;
|
|
34
|
+
received_usd: string;
|
|
35
|
+
}
|
|
36
|
+
export interface CostBreakdown {
|
|
37
|
+
schema_version: number;
|
|
38
|
+
label: "SIMULATED";
|
|
39
|
+
trades: TradeCost[];
|
|
40
|
+
fees_by_tier: TierFee[];
|
|
41
|
+
fees_usd: string;
|
|
42
|
+
mid_usd: string | null;
|
|
43
|
+
slippage_vs_mid_usd: string | null;
|
|
44
|
+
funding_payments: FundingCost[];
|
|
45
|
+
funding_paid_usd: string;
|
|
46
|
+
funding_received_usd: string;
|
|
47
|
+
not_modelled: NotModelledItem[];
|
|
48
|
+
}
|
|
49
|
+
interface CostSource {
|
|
50
|
+
fills?: readonly Fill[];
|
|
51
|
+
feeVersion?: string;
|
|
52
|
+
fee_version?: string;
|
|
53
|
+
takerBps?: string;
|
|
54
|
+
taker_bps?: string;
|
|
55
|
+
makerBps?: string;
|
|
56
|
+
maker_bps?: string;
|
|
57
|
+
fundingPayments?: readonly FundingPayment[];
|
|
58
|
+
funding_payments?: readonly FundingPayment[];
|
|
59
|
+
}
|
|
60
|
+
export declare function notModelledItems(): NotModelledItem[];
|
|
61
|
+
export declare function executionCost(result: CostSource, book: Book): CostBreakdown;
|
|
62
|
+
export declare function costsText(breakdown: CostBreakdown): string;
|
|
63
|
+
export declare function tierText(breakdown: CostBreakdown): string;
|
|
64
|
+
export {};
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** Execution-cost breakdown. Fees, book-walk slippage versus mid, and funding paid or received. */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.NOT_RECORDED = exports.COST_SCHEMA_VERSION = void 0;
|
|
5
|
+
exports.notModelledItems = notModelledItems;
|
|
6
|
+
exports.executionCost = executionCost;
|
|
7
|
+
exports.costsText = costsText;
|
|
8
|
+
exports.tierText = tierText;
|
|
9
|
+
exports.COST_SCHEMA_VERSION = 1;
|
|
10
|
+
exports.NOT_RECORDED = "not recorded";
|
|
11
|
+
const SCALE = 36n;
|
|
12
|
+
const FACTOR = 10n ** SCALE;
|
|
13
|
+
function notModelledItems() {
|
|
14
|
+
return [
|
|
15
|
+
{ item: "queue_position", status: "NOT_MODELLED" },
|
|
16
|
+
{ item: "liquidation", status: "NOT_MODELLED" },
|
|
17
|
+
];
|
|
18
|
+
}
|
|
19
|
+
function executionCost(result, book) {
|
|
20
|
+
const mid = bookMid(book);
|
|
21
|
+
const trades = tradesOf(result, mid);
|
|
22
|
+
const tiers = tiersOf(trades, result);
|
|
23
|
+
const funding = fundingOf(result.funding_payments ?? result.fundingPayments);
|
|
24
|
+
const paid = funding.reduce((sum, row) => add(sum, parseDecimal(row.paid_usd)), 0n);
|
|
25
|
+
const received = funding.reduce((sum, row) => add(sum, parseDecimal(row.received_usd)), 0n);
|
|
26
|
+
const fees = trades.reduce((sum, trade) => add(sum, parseDecimal(trade.fee_usd)), 0n);
|
|
27
|
+
return {
|
|
28
|
+
schema_version: exports.COST_SCHEMA_VERSION,
|
|
29
|
+
label: "SIMULATED",
|
|
30
|
+
trades,
|
|
31
|
+
fees_by_tier: tiers,
|
|
32
|
+
fees_usd: formatDecimal(fees),
|
|
33
|
+
mid_usd: mid === null ? null : formatDecimal(mid),
|
|
34
|
+
slippage_vs_mid_usd: aggregateSlippage(trades),
|
|
35
|
+
funding_payments: funding,
|
|
36
|
+
funding_paid_usd: formatDecimal(paid),
|
|
37
|
+
funding_received_usd: formatDecimal(received),
|
|
38
|
+
not_modelled: notModelledItems(),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function costsText(breakdown) {
|
|
42
|
+
const slip = breakdown.slippage_vs_mid_usd === null ? exports.NOT_RECORDED : breakdown.slippage_vs_mid_usd;
|
|
43
|
+
return `fees ${breakdown.fees_usd} · vs mid ${slip} · paid ${breakdown.funding_paid_usd} · received ${breakdown.funding_received_usd}`;
|
|
44
|
+
}
|
|
45
|
+
function tierText(breakdown) {
|
|
46
|
+
if (breakdown.fees_by_tier.length === 0) {
|
|
47
|
+
return exports.NOT_RECORDED;
|
|
48
|
+
}
|
|
49
|
+
return breakdown.fees_by_tier
|
|
50
|
+
.map((row) => `${row.fee_version} · taker ${row.taker_usd} · maker ${row.maker_usd}`)
|
|
51
|
+
.join(" | ");
|
|
52
|
+
}
|
|
53
|
+
function tradesOf(result, mid) {
|
|
54
|
+
const fills = result.fills ?? [];
|
|
55
|
+
return fills.map((fill, index) => {
|
|
56
|
+
const schedule = scheduleOf(fill, result);
|
|
57
|
+
const fee = parseDecimal(fill.fee);
|
|
58
|
+
const takerFee = fill.liquidity === "taker" ? fee : 0n;
|
|
59
|
+
const makerFee = fill.liquidity === "maker" ? fee : 0n;
|
|
60
|
+
if (fill.liquidity !== "taker" && fill.liquidity !== "maker") {
|
|
61
|
+
throw new Error("liquidity must be taker or maker");
|
|
62
|
+
}
|
|
63
|
+
const slip = slippageOf(fill, mid);
|
|
64
|
+
return {
|
|
65
|
+
index,
|
|
66
|
+
kind: fill.kind,
|
|
67
|
+
side: fill.side,
|
|
68
|
+
liquidity: fill.liquidity,
|
|
69
|
+
fee_version: schedule.version,
|
|
70
|
+
taker_bps: schedule.takerBps,
|
|
71
|
+
maker_bps: schedule.makerBps,
|
|
72
|
+
fee_usd: formatDecimal(fee),
|
|
73
|
+
taker_fee_usd: formatDecimal(takerFee),
|
|
74
|
+
maker_fee_usd: formatDecimal(makerFee),
|
|
75
|
+
slippage_vs_mid_usd: slip === null ? null : formatDecimal(slip),
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
function tiersOf(trades, result) {
|
|
80
|
+
const groups = new Map();
|
|
81
|
+
const order = [];
|
|
82
|
+
for (const trade of trades) {
|
|
83
|
+
const version = trade.fee_version;
|
|
84
|
+
let row = groups.get(version);
|
|
85
|
+
if (row === undefined) {
|
|
86
|
+
row = {
|
|
87
|
+
fee_version: version,
|
|
88
|
+
taker_bps: trade.taker_bps,
|
|
89
|
+
maker_bps: trade.maker_bps,
|
|
90
|
+
taker_usd: "0",
|
|
91
|
+
maker_usd: "0",
|
|
92
|
+
fee_usd: "0",
|
|
93
|
+
};
|
|
94
|
+
groups.set(version, row);
|
|
95
|
+
order.push(version);
|
|
96
|
+
}
|
|
97
|
+
row.taker_usd = formatDecimal(add(parseDecimal(row.taker_usd), parseDecimal(trade.taker_fee_usd)));
|
|
98
|
+
row.maker_usd = formatDecimal(add(parseDecimal(row.maker_usd), parseDecimal(trade.maker_fee_usd)));
|
|
99
|
+
row.fee_usd = formatDecimal(add(parseDecimal(row.fee_usd), parseDecimal(trade.fee_usd)));
|
|
100
|
+
}
|
|
101
|
+
if (order.length > 0) {
|
|
102
|
+
return order.map((version) => {
|
|
103
|
+
const row = groups.get(version);
|
|
104
|
+
if (row === undefined) {
|
|
105
|
+
throw new Error("fee tier missing");
|
|
106
|
+
}
|
|
107
|
+
return row;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
const version = textOf(result.fee_version ?? result.feeVersion);
|
|
111
|
+
if (version === "") {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
return [
|
|
115
|
+
{
|
|
116
|
+
fee_version: version,
|
|
117
|
+
taker_bps: textOf(result.taker_bps ?? result.takerBps),
|
|
118
|
+
maker_bps: textOf(result.maker_bps ?? result.makerBps),
|
|
119
|
+
taker_usd: "0",
|
|
120
|
+
maker_usd: "0",
|
|
121
|
+
fee_usd: "0",
|
|
122
|
+
},
|
|
123
|
+
];
|
|
124
|
+
}
|
|
125
|
+
function fundingOf(value) {
|
|
126
|
+
if (value === undefined) {
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
return value.map((item) => {
|
|
130
|
+
const payment = parseDecimal(item.payment_usd);
|
|
131
|
+
const paid = payment < 0n ? -payment : 0n;
|
|
132
|
+
const received = payment > 0n ? payment : 0n;
|
|
133
|
+
return {
|
|
134
|
+
time_ms: item.time_ms,
|
|
135
|
+
payment_usd: formatDecimal(payment),
|
|
136
|
+
paid_usd: formatDecimal(paid),
|
|
137
|
+
received_usd: formatDecimal(received),
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
function aggregateSlippage(trades) {
|
|
142
|
+
if (trades.length === 0) {
|
|
143
|
+
return "0";
|
|
144
|
+
}
|
|
145
|
+
let total = 0n;
|
|
146
|
+
for (const trade of trades) {
|
|
147
|
+
if (trade.slippage_vs_mid_usd === null) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
total = add(total, parseDecimal(trade.slippage_vs_mid_usd));
|
|
151
|
+
}
|
|
152
|
+
return formatDecimal(total);
|
|
153
|
+
}
|
|
154
|
+
function slippageOf(fill, mid) {
|
|
155
|
+
if (mid === null) {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
let total = 0n;
|
|
159
|
+
for (const leg of fill.legs) {
|
|
160
|
+
const qty = parseDecimal(leg.size);
|
|
161
|
+
const px = parseDecimal(leg.price);
|
|
162
|
+
if (fill.side === "buy") {
|
|
163
|
+
total = add(total, mul(sub(px, mid), qty));
|
|
164
|
+
}
|
|
165
|
+
else if (fill.side === "sell") {
|
|
166
|
+
total = add(total, mul(sub(mid, px), qty));
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
throw new Error("side must be buy or sell");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return total;
|
|
173
|
+
}
|
|
174
|
+
function bookMid(book) {
|
|
175
|
+
const bid = touch(book.bids, true);
|
|
176
|
+
const ask = touch(book.asks, false);
|
|
177
|
+
if (bid === null || ask === null) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
return div2(add(bid, ask));
|
|
181
|
+
}
|
|
182
|
+
function touch(levels, highest) {
|
|
183
|
+
if (levels === undefined || levels.length === 0) {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
let chosen = null;
|
|
187
|
+
for (const level of levels) {
|
|
188
|
+
const px = parseDecimal(level.px);
|
|
189
|
+
if (chosen === null || (highest ? px > chosen : px < chosen)) {
|
|
190
|
+
chosen = px;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return chosen;
|
|
194
|
+
}
|
|
195
|
+
function scheduleOf(fill, result) {
|
|
196
|
+
return {
|
|
197
|
+
version: fallback(fill.fee_version, result.fee_version ?? result.feeVersion),
|
|
198
|
+
takerBps: fallback(fill.taker_bps, result.taker_bps ?? result.takerBps),
|
|
199
|
+
makerBps: fallback(fill.maker_bps, result.maker_bps ?? result.makerBps),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function fallback(primary, secondary) {
|
|
203
|
+
if (primary !== undefined && primary !== "") {
|
|
204
|
+
return primary;
|
|
205
|
+
}
|
|
206
|
+
return secondary ?? "";
|
|
207
|
+
}
|
|
208
|
+
function textOf(value) {
|
|
209
|
+
return value ?? "";
|
|
210
|
+
}
|
|
211
|
+
function parseDecimal(text) {
|
|
212
|
+
if (!/^-?\d+(\.\d+)?$/.test(text)) {
|
|
213
|
+
throw new Error("decimal required");
|
|
214
|
+
}
|
|
215
|
+
const negative = text.startsWith("-");
|
|
216
|
+
const body = negative ? text.slice(1) : text;
|
|
217
|
+
const [whole, frac = ""] = body.split(".");
|
|
218
|
+
if (frac.length > Number(SCALE)) {
|
|
219
|
+
throw new Error("decimal scale exceeded");
|
|
220
|
+
}
|
|
221
|
+
const padded = frac + "0".repeat(Number(SCALE) - frac.length);
|
|
222
|
+
const value = BigInt(whole) * FACTOR + BigInt(padded);
|
|
223
|
+
return negative ? -value : value;
|
|
224
|
+
}
|
|
225
|
+
function formatDecimal(value) {
|
|
226
|
+
const negative = value < 0n;
|
|
227
|
+
const abs = negative ? -value : value;
|
|
228
|
+
const whole = abs / FACTOR;
|
|
229
|
+
const frac = (abs % FACTOR).toString().padStart(Number(SCALE), "0").replace(/0+$/, "");
|
|
230
|
+
const text = frac.length === 0 ? whole.toString() : `${whole.toString()}.${frac}`;
|
|
231
|
+
return negative ? `-${text}` : text;
|
|
232
|
+
}
|
|
233
|
+
function add(left, right) {
|
|
234
|
+
return left + right;
|
|
235
|
+
}
|
|
236
|
+
function sub(left, right) {
|
|
237
|
+
return left - right;
|
|
238
|
+
}
|
|
239
|
+
function mul(left, right) {
|
|
240
|
+
return (left * right) / FACTOR;
|
|
241
|
+
}
|
|
242
|
+
function div2(value) {
|
|
243
|
+
if (value % 2n !== 0n) {
|
|
244
|
+
throw new Error("decimal scale exceeded");
|
|
245
|
+
}
|
|
246
|
+
return value / 2n;
|
|
247
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Execution assumptions for book-based fills (slippage floors and book metadata). */
|
|
2
|
+
export declare const DEFAULT_MIN_STOP_SLIPPAGE_BPS = "10";
|
|
3
|
+
export declare const DEFAULT_MIN_TAKER_SLIPPAGE_BPS = "0";
|
|
4
|
+
export declare const NON_HISTORICAL_BOOK_LABEL = "non_historical_book";
|
|
5
|
+
export type OrderSide = "buy" | "sell";
|
|
6
|
+
export interface Book {
|
|
7
|
+
bids: Array<{
|
|
8
|
+
px: string;
|
|
9
|
+
sz: string;
|
|
10
|
+
}>;
|
|
11
|
+
asks: Array<{
|
|
12
|
+
px: string;
|
|
13
|
+
sz: string;
|
|
14
|
+
}>;
|
|
15
|
+
timeMs?: number;
|
|
16
|
+
historical?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface Bar {
|
|
19
|
+
open: string;
|
|
20
|
+
high: string;
|
|
21
|
+
low: string;
|
|
22
|
+
close: string;
|
|
23
|
+
timeMs?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface ExecutionConfig {
|
|
26
|
+
minStopSlippageBps?: string;
|
|
27
|
+
minTakerSlippageBps?: string;
|
|
28
|
+
volatilitySlippageScale?: string;
|
|
29
|
+
bookTimeMismatch?: "warn" | "fail";
|
|
30
|
+
}
|
|
31
|
+
export declare function normalizedExecution(config: ExecutionConfig | null | undefined): ExecutionConfig;
|
|
32
|
+
/** Stop slippage floor in bps. "0" disables it; the default is version-pinned. */
|
|
33
|
+
export declare function minStopBps(config: ExecutionConfig, fallback?: string): string;
|
|
34
|
+
export declare function minTakerBps(config: ExecutionConfig): string;
|
|
35
|
+
export declare function volatilityScale(config: ExecutionConfig): string | null;
|
|
36
|
+
export declare function bookLabels(book: Book): string[];
|
|
37
|
+
export declare function checkBookTime(book: Book, bar: Bar, config: ExecutionConfig, warnings: string[]): void;
|
|
38
|
+
export declare function applySlippageFloor(side: OrderSide, anchor: bigint, legs: Array<{
|
|
39
|
+
qty: bigint;
|
|
40
|
+
px: bigint;
|
|
41
|
+
}>, minBps: string, bar: Bar | null, volScale: string | null): Array<{
|
|
42
|
+
qty: bigint;
|
|
43
|
+
px: bigint;
|
|
44
|
+
}>;
|