@perpbrain/sdk 0.0.0-stage → 0.1.0
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 +16 -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 +15 -0
- package/dist/cjs/index.js +56 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/receipt.d.ts +13 -0
- package/dist/cjs/receipt.js +660 -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 +15 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/receipt.d.ts +13 -0
- package/dist/esm/receipt.js +653 -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
package/dist/esm/card.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/** SVG card for a verified simulation receipt. PNG is not produced. */
|
|
2
|
+
import { RECEIPT_KIND, RECEIPT_STATEMENT, sha256Json, verifyReceipt } from "./receipt.js";
|
|
3
|
+
import { costsText, executionCost, tierText } from "./vendor/costs.js";
|
|
4
|
+
const FOOTER = "Simulated. Limits you set; losses are still possible.";
|
|
5
|
+
const ABSENT = "not recorded";
|
|
6
|
+
const KNOWN_NOT_MODELLED = ["queue_position", "liquidation"];
|
|
7
|
+
export function renderReceiptCard(receipt, manifest, inputs) {
|
|
8
|
+
const report = verifyReceipt(receipt, manifest, inputs);
|
|
9
|
+
if (report.status !== "VERIFIED") {
|
|
10
|
+
throw new Error(report.mismatches.join("\n"));
|
|
11
|
+
}
|
|
12
|
+
return renderCardSvg(receipt);
|
|
13
|
+
}
|
|
14
|
+
function renderCardSvg(receipt) {
|
|
15
|
+
return svg(cardFields(receipt));
|
|
16
|
+
}
|
|
17
|
+
function cardFields(receipt) {
|
|
18
|
+
if (!isObject(receipt)) {
|
|
19
|
+
throw new Error("receipt mismatch");
|
|
20
|
+
}
|
|
21
|
+
requireReceipt(receipt);
|
|
22
|
+
const inputs = mapping(receipt.inputs);
|
|
23
|
+
const overfit = readOverfit(receipt.overfit);
|
|
24
|
+
const costs = costsOf(receipt.result, inputs.book);
|
|
25
|
+
return {
|
|
26
|
+
strategy: strategyOf(receipt, inputs).toUpperCase(),
|
|
27
|
+
market: marketOf(receipt, inputs),
|
|
28
|
+
period: periodOf(receipt, inputs),
|
|
29
|
+
tape_verification: tapeOf(receipt.tape_verification),
|
|
30
|
+
receipt_hash: sha256Json(receipt),
|
|
31
|
+
limits: limitsOf(receipt.limits),
|
|
32
|
+
not_modelled: notModelled(receipt.result),
|
|
33
|
+
out_of_sample: overfit.split,
|
|
34
|
+
costs: costs.costs,
|
|
35
|
+
tier: costs.tier,
|
|
36
|
+
too_good: overfit.warning,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function costsOf(result, book) {
|
|
40
|
+
try {
|
|
41
|
+
const breakdown = executionCost(costSource(result), bookSource(book));
|
|
42
|
+
return { costs: costsText(breakdown), tier: tierText(breakdown) };
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return { costs: ABSENT, tier: ABSENT };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function costSource(value) {
|
|
49
|
+
const body = mapping(value);
|
|
50
|
+
return {
|
|
51
|
+
fills: Array.isArray(body.fills) ? body.fills : [],
|
|
52
|
+
fee_version: typeof body.fee_version === "string" ? body.fee_version : undefined,
|
|
53
|
+
taker_bps: typeof body.taker_bps === "string" ? body.taker_bps : undefined,
|
|
54
|
+
maker_bps: typeof body.maker_bps === "string" ? body.maker_bps : undefined,
|
|
55
|
+
funding_payments: Array.isArray(body.funding_payments) ? body.funding_payments : [],
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function bookSource(value) {
|
|
59
|
+
const body = mapping(value);
|
|
60
|
+
const bids = Array.isArray(body.bids) ? body.bids : [];
|
|
61
|
+
const asks = Array.isArray(body.asks) ? body.asks : [];
|
|
62
|
+
return { bids, asks };
|
|
63
|
+
}
|
|
64
|
+
function requireReceipt(receipt) {
|
|
65
|
+
const version = receipt.version;
|
|
66
|
+
if (typeof version !== "number" || !Number.isInteger(version) || (version !== 1 && version !== 2 && version !== 3 && version !== 4 && version !== 5)) {
|
|
67
|
+
throw new Error("version mismatch");
|
|
68
|
+
}
|
|
69
|
+
if (receipt.kind !== RECEIPT_KIND) {
|
|
70
|
+
throw new Error("kind mismatch");
|
|
71
|
+
}
|
|
72
|
+
if (receipt.label !== "SIMULATED") {
|
|
73
|
+
throw new Error("label mismatch");
|
|
74
|
+
}
|
|
75
|
+
if (receipt.statement !== RECEIPT_STATEMENT) {
|
|
76
|
+
throw new Error("statement mismatch");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function strategyOf(receipt, inputs) {
|
|
80
|
+
for (const source of [receipt, inputs]) {
|
|
81
|
+
const text = nonempty(source.strategy);
|
|
82
|
+
if (text !== null) {
|
|
83
|
+
return text;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return ABSENT;
|
|
87
|
+
}
|
|
88
|
+
function marketOf(receipt, inputs) {
|
|
89
|
+
const fromResult = nonempty(mapping(receipt.result).market);
|
|
90
|
+
if (fromResult !== null) {
|
|
91
|
+
return fromResult;
|
|
92
|
+
}
|
|
93
|
+
const fallback = nonempty(inputs.market);
|
|
94
|
+
if (fallback !== null) {
|
|
95
|
+
return fallback;
|
|
96
|
+
}
|
|
97
|
+
return ABSENT;
|
|
98
|
+
}
|
|
99
|
+
function periodOf(receipt, inputs) {
|
|
100
|
+
const explicit = nonempty(receipt.period);
|
|
101
|
+
if (explicit !== null) {
|
|
102
|
+
return explicit;
|
|
103
|
+
}
|
|
104
|
+
const stamps = [];
|
|
105
|
+
const bars = inputs.bars;
|
|
106
|
+
if (Array.isArray(bars)) {
|
|
107
|
+
for (const bar of bars) {
|
|
108
|
+
if (!isObject(bar)) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const stamp = bar.time_ms;
|
|
112
|
+
if (typeof stamp === "number" && Number.isInteger(stamp)) {
|
|
113
|
+
stamps.push(stamp);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (stamps.length === 0) {
|
|
118
|
+
return ABSENT;
|
|
119
|
+
}
|
|
120
|
+
const start = formatMs(Math.min(...stamps));
|
|
121
|
+
const end = formatMs(Math.max(...stamps));
|
|
122
|
+
if (start === end) {
|
|
123
|
+
return start;
|
|
124
|
+
}
|
|
125
|
+
return `${start} \u2013 ${end}`;
|
|
126
|
+
}
|
|
127
|
+
function formatMs(stamp) {
|
|
128
|
+
const moment = new Date(stamp);
|
|
129
|
+
const year = moment.getUTCFullYear().toString().padStart(4, "0");
|
|
130
|
+
const month = (moment.getUTCMonth() + 1).toString().padStart(2, "0");
|
|
131
|
+
const day = moment.getUTCDate().toString().padStart(2, "0");
|
|
132
|
+
const hour = moment.getUTCHours().toString().padStart(2, "0");
|
|
133
|
+
const minute = moment.getUTCMinutes().toString().padStart(2, "0");
|
|
134
|
+
return `${year}-${month}-${day} ${hour}:${minute} UTC`;
|
|
135
|
+
}
|
|
136
|
+
function tapeOf(value) {
|
|
137
|
+
return nonempty(value) ?? ABSENT;
|
|
138
|
+
}
|
|
139
|
+
function limitsOf(value) {
|
|
140
|
+
const limits = mapping(value);
|
|
141
|
+
if (Object.keys(limits).length === 0) {
|
|
142
|
+
return `${ABSENT} \u00b7 ${ABSENT}`;
|
|
143
|
+
}
|
|
144
|
+
const preset = nonempty(limits.preset) ?? ABSENT;
|
|
145
|
+
let flag = ABSENT;
|
|
146
|
+
if (limits.loosened === true) {
|
|
147
|
+
flag = "loosened";
|
|
148
|
+
}
|
|
149
|
+
else if (limits.loosened === false) {
|
|
150
|
+
flag = "not loosened";
|
|
151
|
+
}
|
|
152
|
+
return `${preset} \u00b7 ${flag}`;
|
|
153
|
+
}
|
|
154
|
+
function notModelled(result) {
|
|
155
|
+
const found = [];
|
|
156
|
+
walkNotModelled(result, found);
|
|
157
|
+
const ordered = KNOWN_NOT_MODELLED.filter((name) => found.includes(name));
|
|
158
|
+
const extra = found.filter((name) => !KNOWN_NOT_MODELLED.includes(name)).sort();
|
|
159
|
+
const names = [...ordered, ...extra];
|
|
160
|
+
if (names.length === 0) {
|
|
161
|
+
return "none";
|
|
162
|
+
}
|
|
163
|
+
return names.join(", ");
|
|
164
|
+
}
|
|
165
|
+
function walkNotModelled(value, found) {
|
|
166
|
+
if (isObject(value)) {
|
|
167
|
+
const itemName = value.item;
|
|
168
|
+
const status = value.status;
|
|
169
|
+
if (typeof itemName === "string" && status === "NOT_MODELLED" && !found.includes(itemName)) {
|
|
170
|
+
found.push(itemName);
|
|
171
|
+
}
|
|
172
|
+
for (const [key, item] of Object.entries(value)) {
|
|
173
|
+
if (item === "NOT_MODELLED" && key !== "status" && !found.includes(key)) {
|
|
174
|
+
found.push(key);
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
walkNotModelled(item, found);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (Array.isArray(value)) {
|
|
183
|
+
for (const item of value) {
|
|
184
|
+
walkNotModelled(item, found);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function readOverfit(value) {
|
|
189
|
+
const body = mapping(value);
|
|
190
|
+
if (Object.keys(body).length === 0) {
|
|
191
|
+
return { split: ABSENT, warning: null };
|
|
192
|
+
}
|
|
193
|
+
const ratio = nonempty(body.in_sample_ratio);
|
|
194
|
+
const inside = countOf(mapping(body.in_sample));
|
|
195
|
+
const outside = countOf(mapping(body.out_of_sample));
|
|
196
|
+
const split = ratio === null || inside === null || outside === null
|
|
197
|
+
? ABSENT
|
|
198
|
+
: `${ratio} \u00b7 ${inside} in-sample \u00b7 ${outside} out-of-sample`;
|
|
199
|
+
return { split, warning: warningOf(body.warnings) };
|
|
200
|
+
}
|
|
201
|
+
function countOf(body) {
|
|
202
|
+
const count = body.count;
|
|
203
|
+
if (typeof count === "number" && Number.isInteger(count)) {
|
|
204
|
+
return count;
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
function warningOf(value) {
|
|
209
|
+
if (!Array.isArray(value)) {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
const reasons = [];
|
|
213
|
+
for (const item of value) {
|
|
214
|
+
if (!isObject(item) || item.code !== "too_good_to_be_true") {
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const reason = nonempty(item.reason);
|
|
218
|
+
const text = reason === null ? "too_good_to_be_true" : reason;
|
|
219
|
+
if (!reasons.includes(text)) {
|
|
220
|
+
reasons.push(text);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (reasons.length === 0) {
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
return `too_good_to_be_true \u00b7 ${reasons.join(", ")}`;
|
|
227
|
+
}
|
|
228
|
+
function svg(view) {
|
|
229
|
+
const lines = [
|
|
230
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
231
|
+
'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="900" viewBox="0 0 1200 900" role="img" aria-labelledby="title desc">',
|
|
232
|
+
`<title id="title">PERPBRAIN SIMULATED ${xml(view.strategy)}</title>`,
|
|
233
|
+
`<desc id="desc">${xml(FOOTER)}</desc>`,
|
|
234
|
+
"<style>",
|
|
235
|
+
'@import url("https://fonts.googleapis.com/css2?family=Archivo:wght@400;500;600&family=Michroma&display=swap");',
|
|
236
|
+
"</style>",
|
|
237
|
+
'<rect width="1200" height="900" fill="#10140f"/>',
|
|
238
|
+
'<rect width="8" height="900" fill="#d6ff3f"/>',
|
|
239
|
+
michroma(48, 76, 22, "#f3f1ea", "4", "PERPBRAIN"),
|
|
240
|
+
michroma(1152, 76, 16, "#d6ff3f", "2", "SIMULATED", "end"),
|
|
241
|
+
michroma(48, 156, 34, "#f3f1ea", "1", view.strategy),
|
|
242
|
+
archivo(48, 204, 22, "#b7b3a8", `${view.market} \u00b7 ${view.period}`),
|
|
243
|
+
'<line x1="48" y1="236" x2="1152" y2="236" stroke="#2a3128" stroke-width="1"/>',
|
|
244
|
+
];
|
|
245
|
+
let y = 292;
|
|
246
|
+
for (const [label, value, fill, size] of rows(view)) {
|
|
247
|
+
lines.push(michroma(48, y, 13, "#8e8a80", "1.5", label));
|
|
248
|
+
lines.push(archivo(300, y, size, fill, value));
|
|
249
|
+
y += 56;
|
|
250
|
+
}
|
|
251
|
+
lines.push(archivo(48, 848, 16, "#8e8a80", FOOTER));
|
|
252
|
+
lines.push("</svg>");
|
|
253
|
+
return `${lines.join("\n")}\n`;
|
|
254
|
+
}
|
|
255
|
+
function rows(view) {
|
|
256
|
+
const body = [
|
|
257
|
+
["TAPE", view.tape_verification, "#f3f1ea", 22],
|
|
258
|
+
["RECEIPT", view.receipt_hash, "#f3f1ea", 15],
|
|
259
|
+
["LIMITS", view.limits, "#f3f1ea", 22],
|
|
260
|
+
["NOT_MODELLED", view.not_modelled, "#f3f1ea", 22],
|
|
261
|
+
["OUT OF SAMPLE", view.out_of_sample, "#f3f1ea", 22],
|
|
262
|
+
["COSTS", view.costs, "#f3f1ea", 18],
|
|
263
|
+
["TIER", view.tier, "#f3f1ea", 16],
|
|
264
|
+
];
|
|
265
|
+
if (view.too_good !== null) {
|
|
266
|
+
body.push(["WARNING", view.too_good, "#d6ff3f", 22]);
|
|
267
|
+
}
|
|
268
|
+
return body;
|
|
269
|
+
}
|
|
270
|
+
function michroma(x, y, size, fill, spacing, text, anchor) {
|
|
271
|
+
const anchorAttr = anchor === undefined ? "" : ` text-anchor="${anchor}"`;
|
|
272
|
+
return (`<text font-family="Michroma, sans-serif" x="${x}" y="${y}" fill="${fill}" ` +
|
|
273
|
+
`font-size="${size}" letter-spacing="${spacing}"${anchorAttr}>${xml(text)}</text>`);
|
|
274
|
+
}
|
|
275
|
+
function archivo(x, y, size, fill, text) {
|
|
276
|
+
return (`<text font-family="Archivo, sans-serif" x="${x}" y="${y}" fill="${fill}" ` +
|
|
277
|
+
`font-size="${size}">${xml(text)}</text>`);
|
|
278
|
+
}
|
|
279
|
+
function mapping(value) {
|
|
280
|
+
if (!isObject(value)) {
|
|
281
|
+
return {};
|
|
282
|
+
}
|
|
283
|
+
return value;
|
|
284
|
+
}
|
|
285
|
+
function nonempty(value) {
|
|
286
|
+
if (typeof value !== "string") {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
const text = value
|
|
290
|
+
.split(/\s+/)
|
|
291
|
+
.filter((part) => part !== "")
|
|
292
|
+
.join(" ");
|
|
293
|
+
if (text === "") {
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
return text;
|
|
297
|
+
}
|
|
298
|
+
function isObject(value) {
|
|
299
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
300
|
+
}
|
|
301
|
+
function xml(value) {
|
|
302
|
+
return value
|
|
303
|
+
.replaceAll("&", "&")
|
|
304
|
+
.replaceAll("<", "<")
|
|
305
|
+
.replaceAll(">", ">")
|
|
306
|
+
.replaceAll('"', """)
|
|
307
|
+
.replaceAll("'", "'");
|
|
308
|
+
}
|
package/dist/esm/cli.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Launch the Python MCP server, or print install guidance. */
|
|
3
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
+
function pythonCommand() {
|
|
5
|
+
for (const command of ["python3", "python"]) {
|
|
6
|
+
const probe = spawnSync(command, ["-c", "import perpbrain.mcp"], { encoding: "utf8" });
|
|
7
|
+
if (probe.status === 0) {
|
|
8
|
+
return command;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
const command = pythonCommand();
|
|
14
|
+
if (command === null) {
|
|
15
|
+
process.stderr.write([
|
|
16
|
+
"PERPBRAIN MCP server was not found.",
|
|
17
|
+
"Install this repository, then start the server:",
|
|
18
|
+
" uv sync --all-packages",
|
|
19
|
+
" python -m perpbrain.mcp",
|
|
20
|
+
"Phase 1 is read-only and simulation-only. Do not set exchange keys.",
|
|
21
|
+
"",
|
|
22
|
+
].join("\n"));
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
const child = spawn(command, ["-m", "perpbrain.mcp"], { stdio: "inherit" });
|
|
26
|
+
child.on("exit", (code, signal) => {
|
|
27
|
+
if (signal !== null) {
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
process.exit(code ?? 1);
|
|
31
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Book simulation that records a fill only after the owner limits accept it. */
|
|
2
|
+
import { GuardSession, type PresetName } from "./guards.ts";
|
|
3
|
+
import { type Bar, type Book, type Decision, type FundingSample, type GuardContext, type SimulateResult } from "./vendor/simulate.ts";
|
|
4
|
+
export interface GuardedSimulateResult extends SimulateResult {
|
|
5
|
+
guardPreset: string;
|
|
6
|
+
limits: Record<string, unknown>;
|
|
7
|
+
effectiveLimitsPerCoin: Record<string, unknown>;
|
|
8
|
+
loosened: boolean;
|
|
9
|
+
limitsHash: string;
|
|
10
|
+
marketSnapshotId: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function guardedSimulate(market: string, decision: Decision, bars: Bar[], book: Book, feeVersion?: string | null, guardContext?: GuardContext | null, preset?: PresetName, session?: GuardSession | null, funding?: FundingSample[] | null, fundingIntervalMs?: number): GuardedSimulateResult;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/** Book simulation that records a fill only after the owner limits accept it. */
|
|
2
|
+
import { GuardBlocked, GuardSession, wireCode } from "./guards.js";
|
|
3
|
+
import { HL_FUNDING_INTERVAL_MS, simulate, } from "./vendor/simulate.js";
|
|
4
|
+
export function guardedSimulate(market, decision, bars, book, feeVersion = null, guardContext = null, preset = "standard", session = null, funding = null, fundingIntervalMs = HL_FUNDING_INTERVAL_MS) {
|
|
5
|
+
const active = session ?? GuardSession.fromConfig(preset);
|
|
6
|
+
const seen = [];
|
|
7
|
+
const guard = (intent) => {
|
|
8
|
+
const checked = {
|
|
9
|
+
coin: intent.coin,
|
|
10
|
+
notionalUsd: intent.notionalUsd,
|
|
11
|
+
leverage: intent.leverage,
|
|
12
|
+
openPositions: intent.openPositions,
|
|
13
|
+
slippageBps: intent.slippageBps,
|
|
14
|
+
ageMs: intent.ageMs,
|
|
15
|
+
dailyLossPct: intent.dailyLossPct,
|
|
16
|
+
opening: intent.opening,
|
|
17
|
+
orderSide: intent.orderSide,
|
|
18
|
+
nowMs: intent.nowMs,
|
|
19
|
+
};
|
|
20
|
+
const result = active.check(checked, { book: book });
|
|
21
|
+
seen.push(result);
|
|
22
|
+
return { ok: result.ok, violations: result.violations.map((item) => item.code) };
|
|
23
|
+
};
|
|
24
|
+
const simulated = simulate(market, decision, bars, book, feeVersion, guard, guardContext, funding, fundingIntervalMs);
|
|
25
|
+
const receipt = active.limits.receipt();
|
|
26
|
+
const body = {
|
|
27
|
+
...simulated,
|
|
28
|
+
guardPreset: String(receipt.guardPreset),
|
|
29
|
+
limits: receipt.limits,
|
|
30
|
+
effectiveLimitsPerCoin: receipt.effectiveLimitsPerCoin,
|
|
31
|
+
loosened: receipt.loosened === true,
|
|
32
|
+
limitsHash: String(receipt.limitsHash),
|
|
33
|
+
marketSnapshotId: String(receipt.marketSnapshotId),
|
|
34
|
+
};
|
|
35
|
+
const last = seen.at(-1);
|
|
36
|
+
if (last !== undefined && !last.ok) {
|
|
37
|
+
body.guardViolations = last.violations.map((item) => item.code);
|
|
38
|
+
const violation = last.violations[0];
|
|
39
|
+
if (violation === undefined) {
|
|
40
|
+
throw new Error("blocked result is missing a violation");
|
|
41
|
+
}
|
|
42
|
+
throw new GuardBlocked(last.violations, last.headroom, {
|
|
43
|
+
...body,
|
|
44
|
+
error: wireCode(violation.code),
|
|
45
|
+
headroom: last.headroom,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return body;
|
|
49
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/** Owner presets and a tighten-only runtime. Losses are still possible. */
|
|
2
|
+
export declare const STALE_BLOCK_MS = 2000;
|
|
3
|
+
export declare const STALE_HALT_MS = 5000;
|
|
4
|
+
export declare const TOP_OI_COUNT = 20;
|
|
5
|
+
export declare const HARD_MAX_DAILY_LOSS_PCT = "25";
|
|
6
|
+
export declare const HARD_MAX_SLIPPAGE_BPS = "300";
|
|
7
|
+
export declare const HARD_MAX_OPEN_POSITIONS = 50;
|
|
8
|
+
export declare const HARD_MAX_ORDER_RATE = 10;
|
|
9
|
+
export declare const CODES: readonly ["coin_not_allowed", "notional_exceeded", "aggregate_notional", "depth_cap", "leverage_exceeded", "open_positions_exceeded", "daily_stop_reduce_only", "slippage_exceeded", "order_rate", "stale_data", "stale_halt", "kill_switch"];
|
|
10
|
+
export type GuardCode = (typeof CODES)[number];
|
|
11
|
+
export type PresetName = "conservative" | "standard" | "pro";
|
|
12
|
+
export type IntentKind = "open" | "reduce" | "close";
|
|
13
|
+
export declare class GuardLoosenError extends Error {
|
|
14
|
+
readonly name = "GuardLoosenError";
|
|
15
|
+
}
|
|
16
|
+
export declare class GuardConfigError extends Error {
|
|
17
|
+
readonly name = "GuardConfigError";
|
|
18
|
+
}
|
|
19
|
+
export declare class GuardBlocked extends Error {
|
|
20
|
+
readonly name = "GuardBlocked";
|
|
21
|
+
readonly violations: readonly Violation[];
|
|
22
|
+
readonly headroom: Readonly<Record<string, string>>;
|
|
23
|
+
readonly result: Readonly<Record<string, unknown>>;
|
|
24
|
+
constructor(violations: readonly Violation[], headroom: Readonly<Record<string, string>>, result: Readonly<Record<string, unknown>>);
|
|
25
|
+
get code(): string;
|
|
26
|
+
}
|
|
27
|
+
export interface Violation {
|
|
28
|
+
readonly code: GuardCode;
|
|
29
|
+
readonly limit: string;
|
|
30
|
+
readonly actual: string;
|
|
31
|
+
}
|
|
32
|
+
export interface GuardResult {
|
|
33
|
+
readonly ok: boolean;
|
|
34
|
+
readonly violations: readonly Violation[];
|
|
35
|
+
readonly headroom: Readonly<Record<string, string>>;
|
|
36
|
+
}
|
|
37
|
+
export interface SimIntent {
|
|
38
|
+
readonly coin: string;
|
|
39
|
+
readonly notionalUsd: string;
|
|
40
|
+
readonly leverage: string;
|
|
41
|
+
readonly openPositions: number;
|
|
42
|
+
readonly slippageBps: string;
|
|
43
|
+
readonly ageMs: number;
|
|
44
|
+
readonly dailyLossUsd?: string;
|
|
45
|
+
readonly dailyLossPct?: string;
|
|
46
|
+
readonly opening?: boolean;
|
|
47
|
+
readonly orderSide?: "buy" | "sell";
|
|
48
|
+
readonly intentKind?: IntentKind;
|
|
49
|
+
readonly nowMs?: number;
|
|
50
|
+
}
|
|
51
|
+
export interface DepthLevel {
|
|
52
|
+
readonly px: string;
|
|
53
|
+
readonly sz: string;
|
|
54
|
+
}
|
|
55
|
+
export interface DepthBook {
|
|
56
|
+
readonly bids: readonly DepthLevel[];
|
|
57
|
+
readonly asks: readonly DepthLevel[];
|
|
58
|
+
}
|
|
59
|
+
export interface GuardOverrides {
|
|
60
|
+
readonly maxNotionalUsd?: unknown;
|
|
61
|
+
readonly maxLeverage?: unknown;
|
|
62
|
+
readonly maxOpenPositions?: unknown;
|
|
63
|
+
readonly dailyLossPct?: unknown;
|
|
64
|
+
readonly maxSlippageBps?: unknown;
|
|
65
|
+
readonly orderRatePerSec?: unknown;
|
|
66
|
+
readonly allowedCoins?: unknown;
|
|
67
|
+
}
|
|
68
|
+
export interface GuardLimits {
|
|
69
|
+
readonly preset: PresetName;
|
|
70
|
+
readonly maxLeverage: string;
|
|
71
|
+
readonly maxNotionalUsd: string | null;
|
|
72
|
+
readonly dailyLossPct: string;
|
|
73
|
+
readonly maxOpenPositions: number;
|
|
74
|
+
readonly maxSlippageBps: string;
|
|
75
|
+
readonly orderRatePerSec: number;
|
|
76
|
+
readonly allowedCoins: readonly string[];
|
|
77
|
+
}
|
|
78
|
+
export interface Guards extends GuardLimits {
|
|
79
|
+
readonly loosened: boolean;
|
|
80
|
+
readonly limitsHash: string;
|
|
81
|
+
tighten(overrides?: GuardOverrides): Guards;
|
|
82
|
+
check(intent: SimIntent, options?: CheckOptions): GuardResult;
|
|
83
|
+
receipt(snapshot?: MarketSnapshot): Record<string, unknown>;
|
|
84
|
+
effectiveLimits(snapshot?: MarketSnapshot): Record<string, unknown>;
|
|
85
|
+
}
|
|
86
|
+
export interface CheckOptions {
|
|
87
|
+
readonly book?: DepthBook | null;
|
|
88
|
+
readonly snapshot?: MarketSnapshot | null;
|
|
89
|
+
readonly nowMs?: number;
|
|
90
|
+
readonly killSwitch?: boolean;
|
|
91
|
+
readonly reduceOnly?: boolean;
|
|
92
|
+
readonly recentOrders?: number;
|
|
93
|
+
readonly portfolioNotionalUsd?: string;
|
|
94
|
+
readonly portfolioPositions?: number;
|
|
95
|
+
readonly portfolioCoinNotionalUsd?: string;
|
|
96
|
+
readonly record?: boolean;
|
|
97
|
+
}
|
|
98
|
+
interface Preset {
|
|
99
|
+
readonly maxLeverage: string;
|
|
100
|
+
readonly maxNotionalUsd: string;
|
|
101
|
+
readonly dailyLossPct: string;
|
|
102
|
+
readonly maxOpenPositions: number;
|
|
103
|
+
readonly maxSlippageBps: string;
|
|
104
|
+
readonly orderRatePerSec: number;
|
|
105
|
+
}
|
|
106
|
+
export declare const PRESETS: Readonly<Record<PresetName, Preset>>;
|
|
107
|
+
export interface CoinMeta {
|
|
108
|
+
readonly name: string;
|
|
109
|
+
readonly maxLeverage: number;
|
|
110
|
+
readonly openInterest: string;
|
|
111
|
+
}
|
|
112
|
+
export interface MarketSnapshot {
|
|
113
|
+
readonly snapshotId: string;
|
|
114
|
+
readonly coins: readonly CoinMeta[];
|
|
115
|
+
}
|
|
116
|
+
export declare function defaultSnapshot(): MarketSnapshot;
|
|
117
|
+
export declare function snapshotFromCoins(coins: readonly CoinMeta[]): MarketSnapshot;
|
|
118
|
+
export declare function wireCode(code: string): string;
|
|
119
|
+
export declare function nextUtcMidnightMs(nowMs: number): number;
|
|
120
|
+
export declare function defaultGuards(): Guards;
|
|
121
|
+
export declare function fromConfig(preset?: PresetName, overrides?: GuardOverrides | null, acknowledgeLoosenedLimits?: boolean, snapshot?: MarketSnapshot | null): Guards;
|
|
122
|
+
export declare class GuardSession {
|
|
123
|
+
limits: Guards;
|
|
124
|
+
owner: Guards;
|
|
125
|
+
killSwitch: boolean;
|
|
126
|
+
reduceOnlyUntilMs: number | null;
|
|
127
|
+
private orderTimesMs;
|
|
128
|
+
private positions;
|
|
129
|
+
constructor(limits: Guards, owner?: Guards | null, killSwitch?: boolean);
|
|
130
|
+
static fromConfig(preset?: PresetName, overrides?: GuardOverrides | null, acknowledgeLoosenedLimits?: boolean, snapshot?: MarketSnapshot | null): GuardSession;
|
|
131
|
+
tighten(overrides?: GuardOverrides): Guards;
|
|
132
|
+
engageKillSwitch(): void;
|
|
133
|
+
restart(preset?: PresetName, overrides?: GuardOverrides | null, acknowledgeLoosenedLimits?: boolean, snapshot?: MarketSnapshot | null): GuardSession;
|
|
134
|
+
reduceOnly(nowMs: number): boolean;
|
|
135
|
+
openPositionCount(): number;
|
|
136
|
+
aggregateNotionalUsd(): string;
|
|
137
|
+
coinNotional(coin: string): string;
|
|
138
|
+
portfolio(): {
|
|
139
|
+
openPositionCount: number;
|
|
140
|
+
aggregateNotionalUsd: string;
|
|
141
|
+
};
|
|
142
|
+
check(intent: SimIntent, options?: CheckOptions): GuardResult;
|
|
143
|
+
private aggregateNotional;
|
|
144
|
+
private remember;
|
|
145
|
+
headroom(nowMs?: number, snapshot?: MarketSnapshot | null): Readonly<Record<string, string>>;
|
|
146
|
+
}
|
|
147
|
+
export interface SurvivalDay {
|
|
148
|
+
readonly account: string;
|
|
149
|
+
readonly preset: string;
|
|
150
|
+
readonly lossPct: string;
|
|
151
|
+
readonly killSwitch: boolean;
|
|
152
|
+
}
|
|
153
|
+
export declare function survivalReport(days: readonly SurvivalDay[]): Record<string, unknown>;
|
|
154
|
+
export {};
|