@rekt-trading/wheelman 0.0.0-stage → 1.0.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/.env.example +75 -0
- package/LICENSE +191 -0
- package/README.md +287 -2
- package/dist/account.js +162 -0
- package/dist/cli.js +163 -0
- package/dist/client.js +245 -0
- package/dist/commands.js +332 -0
- package/dist/config.js +256 -0
- package/dist/errors.js +24 -0
- package/dist/journal.js +63 -0
- package/dist/mcp.js +117 -0
- package/dist/minute.js +140 -0
- package/dist/paper.js +220 -0
- package/dist/prices.js +374 -0
- package/dist/risk.js +60 -0
- package/dist/rpc.js +321 -0
- package/dist/runner.js +189 -0
- package/dist/setup.js +133 -0
- package/dist/strategies/index.js +34 -0
- package/dist/strategies/knockout.js +111 -0
- package/dist/strategies/minute.js +53 -0
- package/dist/strategies/template.js +24 -0
- package/package.json +57 -4
- package/skills/wheelman/SKILL.md +61 -0
package/dist/prices.js
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
// Prices for the strategy's signal. The venue fills every open at its own next price, so the bot
|
|
2
|
+
// needs no signed price: any good public price works, and a price from your own Pyth key works too.
|
|
3
|
+
// PRICE_SOURCE picks the adapter.
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
/**
|
|
6
|
+
* A recorded tape, one JSON object a line: {"time": <ms or ISO text>, "market": "BTC", "price": 1.23}.
|
|
7
|
+
* Lines for other markets are skipped. The bot's clock is the tape's clock.
|
|
8
|
+
*/
|
|
9
|
+
export function replay(file) {
|
|
10
|
+
return {
|
|
11
|
+
markets: ['BTC', 'ETH', 'SOL', 'XRP', 'XAU'],
|
|
12
|
+
async *ticks(markets) {
|
|
13
|
+
const lines = readFileSync(file, 'utf8').split('\n');
|
|
14
|
+
for (const [i, line] of lines.entries()) {
|
|
15
|
+
if (line.trim() === '')
|
|
16
|
+
continue;
|
|
17
|
+
const row = JSON.parse(line);
|
|
18
|
+
const time = typeof row.time === 'number' ? row.time : Date.parse(row.time);
|
|
19
|
+
if (!Number.isFinite(time) || !(row.price > 0))
|
|
20
|
+
throw new Error(`${file} line ${i + 1}: needs a time and a positive price`);
|
|
21
|
+
if (markets.includes(row.market))
|
|
22
|
+
yield { market: row.market, price: row.price, time };
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
async latest(market) {
|
|
26
|
+
let last = null;
|
|
27
|
+
for await (const t of this.ticks([market], new AbortController().signal))
|
|
28
|
+
last = t;
|
|
29
|
+
if (last === null)
|
|
30
|
+
throw new Error(`${file} has no ${market} price`);
|
|
31
|
+
return last;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Coinbase Exchange's public ticker websocket. No key and no account. It reconnects with a backoff
|
|
37
|
+
* (1 s, doubling to 30 s, with jitter), and it reconnects when a minute passes with no ticker.
|
|
38
|
+
*/
|
|
39
|
+
export function coinbase(url = 'wss://ws-feed.exchange.coinbase.com', Socket = WebSocket) {
|
|
40
|
+
return {
|
|
41
|
+
markets: ['BTC', 'ETH', 'SOL', 'XRP'],
|
|
42
|
+
async latest(market) {
|
|
43
|
+
const res = await fetch(`https://api.exchange.coinbase.com/products/${market}-USD/ticker`, { signal: AbortSignal.timeout(10_000) });
|
|
44
|
+
const body = (await res.json());
|
|
45
|
+
if (!res.ok || body.price === undefined)
|
|
46
|
+
throw new Error(`no ${market} price from the exchange (HTTP ${res.status})`);
|
|
47
|
+
return { market, price: Number(body.price), time: Date.now() };
|
|
48
|
+
},
|
|
49
|
+
async *ticks(markets, signal) {
|
|
50
|
+
const queue = [];
|
|
51
|
+
let wake = null;
|
|
52
|
+
const push = (t) => {
|
|
53
|
+
queue.push(t);
|
|
54
|
+
wake?.();
|
|
55
|
+
};
|
|
56
|
+
let failures = 0;
|
|
57
|
+
let current = null;
|
|
58
|
+
signal.addEventListener('abort', () => {
|
|
59
|
+
current?.close();
|
|
60
|
+
wake?.();
|
|
61
|
+
}, { once: true });
|
|
62
|
+
const connect = () => {
|
|
63
|
+
if (signal.aborted)
|
|
64
|
+
return;
|
|
65
|
+
const ws = new Socket(url);
|
|
66
|
+
current = ws;
|
|
67
|
+
let watchdog = setTimeout(() => ws.close(), 60_000);
|
|
68
|
+
ws.onopen = () => {
|
|
69
|
+
ws.send(JSON.stringify({ type: 'subscribe', product_ids: markets.map((m) => `${m}-USD`), channels: ['ticker'] }));
|
|
70
|
+
};
|
|
71
|
+
ws.onmessage = (e) => {
|
|
72
|
+
const m = JSON.parse(String(e.data));
|
|
73
|
+
if (m.type !== 'ticker' || m.product_id === undefined || m.price === undefined)
|
|
74
|
+
return;
|
|
75
|
+
failures = 0;
|
|
76
|
+
clearTimeout(watchdog);
|
|
77
|
+
watchdog = setTimeout(() => ws.close(), 60_000);
|
|
78
|
+
const time = m.time === undefined ? Date.now() : Date.parse(m.time);
|
|
79
|
+
push({ market: m.product_id.replace(/-USD$/, ''), price: Number(m.price), time });
|
|
80
|
+
};
|
|
81
|
+
ws.onclose = () => {
|
|
82
|
+
clearTimeout(watchdog);
|
|
83
|
+
if (signal.aborted)
|
|
84
|
+
return;
|
|
85
|
+
const wait = Math.min(30_000, 1000 * 2 ** failures++) * (0.75 + Math.random() * 0.5);
|
|
86
|
+
setTimeout(connect, wait);
|
|
87
|
+
};
|
|
88
|
+
ws.onerror = () => ws.close();
|
|
89
|
+
};
|
|
90
|
+
connect();
|
|
91
|
+
while (!signal.aborted) {
|
|
92
|
+
const next = queue.shift();
|
|
93
|
+
if (next !== undefined) {
|
|
94
|
+
yield next;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
await new Promise((r) => (wake = r));
|
|
98
|
+
wake = null;
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** Pyth Pro's three stream endpoints. A client needs one of them; it moves to the next when one fails. */
|
|
104
|
+
export const PYTH_ROUTERS = [
|
|
105
|
+
'wss://pyth-lazer-0.dourolabs.app/v1/stream',
|
|
106
|
+
'wss://pyth-lazer-1.dourolabs.app/v1/stream',
|
|
107
|
+
'wss://pyth-lazer-2.dourolabs.app/v1/stream',
|
|
108
|
+
];
|
|
109
|
+
/** Pyth's public feed list. It needs no key. */
|
|
110
|
+
export const PYTH_SYMBOLS_URL = 'https://pyth.dourolabs.app/v1/symbols';
|
|
111
|
+
/** The slowest channel Pyth offers is valid for every feed, and the History keeps one price a second. */
|
|
112
|
+
const PYTH_CHANNEL = 'fixed_rate@1000ms';
|
|
113
|
+
/** Failures in a row, with no price between them, after which the key is the likely cause and the feed says so. */
|
|
114
|
+
const PYTH_GIVE_UP = 6;
|
|
115
|
+
/**
|
|
116
|
+
* The Pyth feed id of one market. The market's symbol is looked up in Pyth's public feed list, and a feed is taken
|
|
117
|
+
* only when exactly one stable feed is quoted in USD under that symbol, so nothing here is a table of markets that
|
|
118
|
+
* can go stale. A market the list cannot settle is refused with the way to name its feed.
|
|
119
|
+
*/
|
|
120
|
+
export function pythFeedFor(market, listing) {
|
|
121
|
+
const stable = listing.filter((f) => f.state === 'stable' && typeof f.symbol === 'string' && Number.isInteger(f.pyth_lazer_id));
|
|
122
|
+
const quoted = stable.filter((f) => new RegExp(`^[A-Za-z]+(?:\\.[A-Za-z]+)*\\.${market}/USD$`).test(f.symbol));
|
|
123
|
+
for (const prefix of ['Crypto', 'Metal']) {
|
|
124
|
+
const own = quoted.filter((f) => f.symbol === `${prefix}.${market}/USD`);
|
|
125
|
+
if (own.length === 1)
|
|
126
|
+
return own[0].pyth_lazer_id;
|
|
127
|
+
}
|
|
128
|
+
if (quoted.length === 1)
|
|
129
|
+
return quoted[0].pyth_lazer_id;
|
|
130
|
+
throw new Error(quoted.length === 0
|
|
131
|
+
? `Pyth lists no stable ${market}/USD feed: name one with PYTH_FEEDS=${market}=<Pyth feed id>`
|
|
132
|
+
: `Pyth lists ${quoted.length} ${market}/USD feeds: name the one you want with PYTH_FEEDS=${market}=<Pyth feed id>`);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Pyth Pro's price stream, with the caller's own key. One connection, one subscription to every market asked for.
|
|
136
|
+
* A market is resolved to a feed id on first use (see pythFeedFor) unless PYTH_FEEDS names it. It reconnects with
|
|
137
|
+
* the same backoff as the exchange feed and moves to the next router. After PYTH_GIVE_UP failures in a row with no
|
|
138
|
+
* price in between it stops and says the key is the likely cause, instead of retrying for ever.
|
|
139
|
+
*/
|
|
140
|
+
export function pyth(opts) {
|
|
141
|
+
const routers = opts.routers ?? PYTH_ROUTERS;
|
|
142
|
+
const Socket = opts.Socket ?? WebSocket;
|
|
143
|
+
const get = opts.fetchImpl ?? fetch;
|
|
144
|
+
const listed = new Map(Object.entries(opts.feeds ?? {}));
|
|
145
|
+
const resolve = async (market) => {
|
|
146
|
+
const known = listed.get(market);
|
|
147
|
+
if (known !== undefined)
|
|
148
|
+
return known;
|
|
149
|
+
const res = await get(`${opts.symbolsUrl ?? PYTH_SYMBOLS_URL}?query=${encodeURIComponent(market)}`, { signal: AbortSignal.timeout(15_000) });
|
|
150
|
+
if (!res.ok)
|
|
151
|
+
throw new Error(`Pyth's feed list answered HTTP ${res.status}: name the feed with PYTH_FEEDS=${market}=<Pyth feed id>`);
|
|
152
|
+
const id = pythFeedFor(market, (await res.json()));
|
|
153
|
+
listed.set(market, id);
|
|
154
|
+
return id;
|
|
155
|
+
};
|
|
156
|
+
const source = {
|
|
157
|
+
// Any market Pyth quotes: the list is read when a market is first asked for, not fixed here.
|
|
158
|
+
markets: [],
|
|
159
|
+
async latest(market) {
|
|
160
|
+
const stop = new AbortController();
|
|
161
|
+
const timer = setTimeout(() => stop.abort(), 15_000);
|
|
162
|
+
try {
|
|
163
|
+
for await (const t of source.ticks([market], stop.signal))
|
|
164
|
+
return t;
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
clearTimeout(timer);
|
|
168
|
+
stop.abort();
|
|
169
|
+
}
|
|
170
|
+
throw new Error(`no ${market} price from Pyth within 15 s`);
|
|
171
|
+
},
|
|
172
|
+
async *ticks(markets, signal) {
|
|
173
|
+
const marketOf = new Map();
|
|
174
|
+
for (const m of markets)
|
|
175
|
+
marketOf.set(await resolve(m), m);
|
|
176
|
+
const queue = [];
|
|
177
|
+
let wake = null;
|
|
178
|
+
const push = (t) => {
|
|
179
|
+
queue.push(t);
|
|
180
|
+
wake?.();
|
|
181
|
+
};
|
|
182
|
+
let failures = 0;
|
|
183
|
+
let attempt = 0;
|
|
184
|
+
let lastServerError = '';
|
|
185
|
+
let current = null;
|
|
186
|
+
signal.addEventListener('abort', () => {
|
|
187
|
+
current?.close();
|
|
188
|
+
wake?.();
|
|
189
|
+
}, { once: true });
|
|
190
|
+
const connect = () => {
|
|
191
|
+
if (signal.aborted)
|
|
192
|
+
return;
|
|
193
|
+
// The key rides the standard subprotocol list; no header and no URL parameter carries it.
|
|
194
|
+
const ws = new Socket(routers[attempt++ % routers.length], ['pyth-lazer-auth', opts.apiKey]);
|
|
195
|
+
current = ws;
|
|
196
|
+
let sawPrice = false;
|
|
197
|
+
let watchdog = setTimeout(() => ws.close(), 60_000);
|
|
198
|
+
ws.onopen = () => {
|
|
199
|
+
ws.send(JSON.stringify({
|
|
200
|
+
type: 'subscribe',
|
|
201
|
+
subscriptionId: 1,
|
|
202
|
+
priceFeedIds: [...marketOf.keys()],
|
|
203
|
+
properties: ['price', 'exponent'],
|
|
204
|
+
formats: [],
|
|
205
|
+
channel: PYTH_CHANNEL,
|
|
206
|
+
ignoreInvalidFeeds: false,
|
|
207
|
+
}));
|
|
208
|
+
};
|
|
209
|
+
ws.onmessage = (e) => {
|
|
210
|
+
clearTimeout(watchdog);
|
|
211
|
+
watchdog = setTimeout(() => ws.close(), 60_000);
|
|
212
|
+
let m;
|
|
213
|
+
try {
|
|
214
|
+
m = JSON.parse(String(e.data));
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (m.type === 'subscriptionError' || m.type === 'error') {
|
|
220
|
+
lastServerError = `${m.type}: ${typeof m.error === 'string' ? m.error.slice(0, 160) : 'unspecified'}`;
|
|
221
|
+
ws.close();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (m.type !== 'streamUpdated' || m.parsed?.priceFeeds === undefined)
|
|
225
|
+
return;
|
|
226
|
+
const time = Number(m.parsed.timestampUs) / 1000;
|
|
227
|
+
for (const f of m.parsed.priceFeeds) {
|
|
228
|
+
const market = marketOf.get(f.priceFeedId ?? -1);
|
|
229
|
+
if (market === undefined || f.price === undefined || typeof f.exponent !== 'number')
|
|
230
|
+
continue;
|
|
231
|
+
// Divide for a negative exponent: 4012345 / 1000 is the nearest number to 4012.345, 4012345 * 0.001 is not.
|
|
232
|
+
const price = f.exponent < 0 ? Number(f.price) / 10 ** -f.exponent : Number(f.price) * 10 ** f.exponent;
|
|
233
|
+
if (!(price > 0) || !Number.isFinite(price))
|
|
234
|
+
continue;
|
|
235
|
+
sawPrice = true;
|
|
236
|
+
failures = 0;
|
|
237
|
+
push({ market, price, time: Number.isFinite(time) ? time : Date.now() });
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
ws.onclose = () => {
|
|
241
|
+
clearTimeout(watchdog);
|
|
242
|
+
if (signal.aborted)
|
|
243
|
+
return;
|
|
244
|
+
if (!sawPrice && ++failures >= PYTH_GIVE_UP) {
|
|
245
|
+
push(new Error(`Pyth closed the connection ${failures} times without sending a price: check that PYTH_API_KEY is a valid Pyth Pro key` +
|
|
246
|
+
(lastServerError === '' ? '' : ` (last message from Pyth: ${lastServerError})`)));
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
const wait = opts.retryMs?.(failures) ?? Math.min(30_000, 1000 * 2 ** Math.min(failures, 5)) * (0.75 + Math.random() * 0.5);
|
|
250
|
+
setTimeout(connect, wait);
|
|
251
|
+
};
|
|
252
|
+
ws.onerror = () => ws.close();
|
|
253
|
+
};
|
|
254
|
+
connect();
|
|
255
|
+
while (!signal.aborted) {
|
|
256
|
+
const next = queue.shift();
|
|
257
|
+
if (next instanceof Error)
|
|
258
|
+
throw next;
|
|
259
|
+
if (next !== undefined) {
|
|
260
|
+
yield next;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
await new Promise((r) => (wake = r));
|
|
264
|
+
wake = null;
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
return source;
|
|
269
|
+
}
|
|
270
|
+
/** The caller's own Pyth key: PYTH_API_KEY, or PYTH_API_KEY_FILE naming a file that holds it. Null when neither is set. */
|
|
271
|
+
export function pythKey(env) {
|
|
272
|
+
const direct = env.PYTH_API_KEY?.trim();
|
|
273
|
+
if (direct !== undefined && direct !== '')
|
|
274
|
+
return direct;
|
|
275
|
+
const path = env.PYTH_API_KEY_FILE?.trim();
|
|
276
|
+
if (path === undefined || path === '')
|
|
277
|
+
return null;
|
|
278
|
+
let key;
|
|
279
|
+
try {
|
|
280
|
+
key = readFileSync(path, 'utf8').trim();
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
throw new Error('PYTH_API_KEY_FILE names a file this process cannot read');
|
|
284
|
+
}
|
|
285
|
+
if (key === '')
|
|
286
|
+
throw new Error('PYTH_API_KEY_FILE names an empty file');
|
|
287
|
+
return key;
|
|
288
|
+
}
|
|
289
|
+
/** PYTH_FEEDS: `BTC=1,XAU=346`. A market the public feed list cannot settle is named here. */
|
|
290
|
+
export function pythFeeds(text) {
|
|
291
|
+
const out = {};
|
|
292
|
+
for (const part of (text ?? '').split(',').map((p) => p.trim()).filter((p) => p !== '')) {
|
|
293
|
+
const m = /^([A-Za-z0-9]+)=(\d+)$/.exec(part);
|
|
294
|
+
if (m === null)
|
|
295
|
+
throw new Error(`PYTH_FEEDS entry ${part.slice(0, 20)} is not <market>=<feed id>`);
|
|
296
|
+
out[m[1].toUpperCase()] = Number(m[2]);
|
|
297
|
+
}
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* What PRICE_SOURCE means for this environment. `auto` is the preset for a caller who may have a Pyth key: Pyth
|
|
302
|
+
* when a key is set, the public exchange feed when not. Everything else is itself.
|
|
303
|
+
*/
|
|
304
|
+
export function resolveSourceName(name, env) {
|
|
305
|
+
if (name !== 'auto')
|
|
306
|
+
return name;
|
|
307
|
+
return pythKey(env) === null ? 'coinbase' : 'pyth';
|
|
308
|
+
}
|
|
309
|
+
export const PRICE_SOURCES = ['coinbase', 'pyth', 'auto', 'replay'];
|
|
310
|
+
export function priceSource(name, replayFile, env = {}) {
|
|
311
|
+
const which = resolveSourceName(name, env);
|
|
312
|
+
if (which === 'replay') {
|
|
313
|
+
if (replayFile === undefined)
|
|
314
|
+
throw new Error('PRICE_SOURCE=replay needs REPLAY_FILE');
|
|
315
|
+
return replay(replayFile);
|
|
316
|
+
}
|
|
317
|
+
if (which === 'coinbase')
|
|
318
|
+
return coinbase();
|
|
319
|
+
if (which === 'pyth') {
|
|
320
|
+
const apiKey = pythKey(env);
|
|
321
|
+
if (apiKey === null)
|
|
322
|
+
throw new Error('PRICE_SOURCE=pyth needs your Pyth key: set PYTH_API_KEY, or PYTH_API_KEY_FILE');
|
|
323
|
+
return pyth({ apiKey, feeds: pythFeeds(env.PYTH_FEEDS) });
|
|
324
|
+
}
|
|
325
|
+
throw new Error(`PRICE_SOURCE must be ${PRICE_SOURCES.join(', ')}, not ${name}`);
|
|
326
|
+
}
|
|
327
|
+
/** The recent prices of one market, for priceAgo and range. */
|
|
328
|
+
export class History {
|
|
329
|
+
points = [];
|
|
330
|
+
keepMs;
|
|
331
|
+
constructor(keepMs) {
|
|
332
|
+
this.keepMs = keepMs;
|
|
333
|
+
}
|
|
334
|
+
/** Keep one price a second: a later price in the same second replaces the earlier one. */
|
|
335
|
+
add(t) {
|
|
336
|
+
const last = this.points.at(-1);
|
|
337
|
+
if (last !== undefined && t.time < last.time)
|
|
338
|
+
return;
|
|
339
|
+
if (last !== undefined && Math.floor(last.time / 1000) === Math.floor(t.time / 1000))
|
|
340
|
+
last.price = t.price;
|
|
341
|
+
else
|
|
342
|
+
this.points.push({ time: t.time, price: t.price });
|
|
343
|
+
const cut = t.time - this.keepMs;
|
|
344
|
+
let drop = 0;
|
|
345
|
+
while (drop < this.points.length - 1 && this.points[drop + 1].time <= cut)
|
|
346
|
+
drop++;
|
|
347
|
+
if (drop > 0)
|
|
348
|
+
this.points.splice(0, drop);
|
|
349
|
+
}
|
|
350
|
+
/** The last price at or before `now - seconds`. */
|
|
351
|
+
priceAgo(now, seconds) {
|
|
352
|
+
const at = now - seconds * 1000;
|
|
353
|
+
let found = null;
|
|
354
|
+
for (const p of this.points) {
|
|
355
|
+
if (p.time > at)
|
|
356
|
+
break;
|
|
357
|
+
found = p.price;
|
|
358
|
+
}
|
|
359
|
+
return found;
|
|
360
|
+
}
|
|
361
|
+
range(now, seconds) {
|
|
362
|
+
if (this.priceAgo(now, seconds) === null)
|
|
363
|
+
return null;
|
|
364
|
+
let low = Infinity;
|
|
365
|
+
let high = -Infinity;
|
|
366
|
+
for (const p of this.points) {
|
|
367
|
+
if (p.time < now - seconds * 1000)
|
|
368
|
+
continue;
|
|
369
|
+
low = Math.min(low, p.price);
|
|
370
|
+
high = Math.max(high, p.price);
|
|
371
|
+
}
|
|
372
|
+
return low === Infinity ? null : { low, high };
|
|
373
|
+
}
|
|
374
|
+
}
|
package/dist/risk.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export const MIN_SOL = 0.01;
|
|
2
|
+
export function guard(intents, book, limits) {
|
|
3
|
+
const allowed = [];
|
|
4
|
+
const refused = [];
|
|
5
|
+
let open = book.open;
|
|
6
|
+
let atStake = book.atStake;
|
|
7
|
+
let free = book.free;
|
|
8
|
+
const lossToday = book.todayPnl < 0n ? -book.todayPnl : 0n;
|
|
9
|
+
const why = (stake) => {
|
|
10
|
+
if (stake <= 0n)
|
|
11
|
+
return 'the stake is not positive';
|
|
12
|
+
if (stake > limits.maxStake)
|
|
13
|
+
return `the stake is above MAX_STAKE_USDC (${usd(limits.maxStake)})`;
|
|
14
|
+
if (open + 1 > limits.maxOpen)
|
|
15
|
+
return `MAX_OPEN (${limits.maxOpen}) positions are open`;
|
|
16
|
+
if (lossToday + atStake + stake > limits.dailyLoss) {
|
|
17
|
+
return `daily loss stop: lost ${usd(lossToday)} today, ${usd(atStake)} at stake, limit ${usd(limits.dailyLoss)}`;
|
|
18
|
+
}
|
|
19
|
+
if (stake > free)
|
|
20
|
+
return `the wallet holds ${usd(free)} USDC`;
|
|
21
|
+
if (free + book.held - stake < limits.minBalance)
|
|
22
|
+
return `MIN_BALANCE_USDC (${usd(limits.minBalance)}) would be passed`;
|
|
23
|
+
if (book.sol < MIN_SOL)
|
|
24
|
+
return `the wallet holds ${book.sol} SOL; fees and rent need ${MIN_SOL}`;
|
|
25
|
+
return null;
|
|
26
|
+
};
|
|
27
|
+
// Intents that share a group (the two sides of a straddle) pass together or not at all.
|
|
28
|
+
const groups = new Map();
|
|
29
|
+
intents.forEach((intent, i) => {
|
|
30
|
+
const key = intent.kind === 'open' && intent.group !== undefined ? `group ${intent.group}` : `intent ${i}`;
|
|
31
|
+
groups.set(key, [...(groups.get(key) ?? []), intent]);
|
|
32
|
+
});
|
|
33
|
+
for (const members of groups.values()) {
|
|
34
|
+
const before = { open, atStake, free };
|
|
35
|
+
let refusal = null;
|
|
36
|
+
for (const intent of members) {
|
|
37
|
+
if (intent.kind === 'close')
|
|
38
|
+
continue;
|
|
39
|
+
refusal = why(intent.stake);
|
|
40
|
+
if (refusal !== null)
|
|
41
|
+
break;
|
|
42
|
+
open += 1;
|
|
43
|
+
atStake += intent.stake;
|
|
44
|
+
free -= intent.stake;
|
|
45
|
+
}
|
|
46
|
+
if (refusal === null)
|
|
47
|
+
allowed.push(...members);
|
|
48
|
+
else {
|
|
49
|
+
({ open, atStake, free } = before);
|
|
50
|
+
for (const intent of members)
|
|
51
|
+
refused.push({ intent, why: refusal });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return { allowed, refused };
|
|
55
|
+
}
|
|
56
|
+
export const usd = (n) => {
|
|
57
|
+
const sign = n < 0n ? '-' : '';
|
|
58
|
+
const a = n < 0n ? -n : n;
|
|
59
|
+
return `${sign}$${a / 1000000n}.${(a % 1000000n).toString().padStart(6, '0').slice(0, 2)}`;
|
|
60
|
+
};
|