@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/rpc.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
// RPC for any provider. The rules: stream first and poll last; read only the bot's own accounts;
|
|
10
|
+
// one rate limit and one backoff per endpoint; `confirmed` on every call; send with
|
|
11
|
+
// maxRetries 0 and one bounded rebroadcast; never log a key.
|
|
12
|
+
import { ComputeBudgetProgram, Connection, PublicKey, SystemProgram, TransactionMessage, VersionedTransaction, } from '@solana/web3.js';
|
|
13
|
+
import { PACKET_LIMIT_BYTES, PROGRAM_ID, confirmSignature, connectionSignatureReader, errorForCode, minuteErrorForCode, programErrorCode, } from '@rekt-trading/1000x';
|
|
14
|
+
import { Refusal } from "./errors.js";
|
|
15
|
+
import { hostOf, log, redact } from "./journal.js";
|
|
16
|
+
/** The Clock sysvar: slot and unix time in the same read as the accounts. */
|
|
17
|
+
export const CLOCK = new PublicKey('SysvarC1ock11111111111111111111111111111111');
|
|
18
|
+
const MAINNET_GENESIS = '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d';
|
|
19
|
+
const ATTEMPTS = 5;
|
|
20
|
+
/** An endpoint that failed 5 times. Nothing was sent by the failing call, so it is retryable. */
|
|
21
|
+
export class RpcExhausted extends Refusal {
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super('rpc', 'RPC_UNAVAILABLE', message, true, 60_000);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
27
|
+
/** Wait 1 s, doubling to 30 s, with 25 % jitter either way. */
|
|
28
|
+
export const backoffMs = (attempt, rand = Math.random) => Math.min(30_000, 1000 * 2 ** attempt) * (0.75 + rand() * 0.5);
|
|
29
|
+
/** A token bucket: at most `perSecond` requests a second, shared by every caller of one endpoint. */
|
|
30
|
+
function bucket(perSecond) {
|
|
31
|
+
let tokens = perSecond;
|
|
32
|
+
let last = Date.now();
|
|
33
|
+
return async function take() {
|
|
34
|
+
for (;;) {
|
|
35
|
+
const now = Date.now();
|
|
36
|
+
tokens = Math.min(perSecond, tokens + ((now - last) / 1000) * perSecond);
|
|
37
|
+
last = now;
|
|
38
|
+
if (tokens >= 1) {
|
|
39
|
+
tokens -= 1;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await sleep(((1 - tokens) / perSecond) * 1000);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A fetch for one endpoint, with its standby. HTTP 429, a 5xx, JSON-RPC -32005 or a network error
|
|
48
|
+
* waits and tries again, 5 times, then the standby takes over for 60 s; then the bot stops loudly.
|
|
49
|
+
* The primary and the standby are never used at the same time.
|
|
50
|
+
*/
|
|
51
|
+
export function gatedFetch(primary, standby, perSecond, fetcher = fetch, pause = sleep) {
|
|
52
|
+
const take = bucket(perSecond);
|
|
53
|
+
let primaryDownUntil = 0;
|
|
54
|
+
return async (_input, init) => {
|
|
55
|
+
const urls = standby !== null && Date.now() < primaryDownUntil ? [standby] : [primary, ...(standby === null ? [] : [standby])];
|
|
56
|
+
let problem = '';
|
|
57
|
+
for (const url of urls) {
|
|
58
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
|
59
|
+
await take();
|
|
60
|
+
try {
|
|
61
|
+
const res = await fetcher(url, init);
|
|
62
|
+
const body = await res.text();
|
|
63
|
+
if (res.status !== 429 && res.status < 500 && !/"code"\s*:\s*-32005/.test(body)) {
|
|
64
|
+
return new Response(body, { status: res.status, headers: { 'content-type': 'application/json' } });
|
|
65
|
+
}
|
|
66
|
+
problem = `HTTP ${res.status}`;
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
problem = e.message;
|
|
70
|
+
}
|
|
71
|
+
if (attempt < ATTEMPTS - 1)
|
|
72
|
+
await pause(backoffMs(attempt));
|
|
73
|
+
}
|
|
74
|
+
if (url === primary && standby !== null) {
|
|
75
|
+
primaryDownUntil = Date.now() + 60_000;
|
|
76
|
+
log('rpc-standby', { from: hostOf(primary), to: hostOf(standby) });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
throw new RpcExhausted(redact(`${urls.map(hostOf).join(' and ')} failed ${ATTEMPTS} times: ${problem}`));
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
export function makeRpc(cfg) {
|
|
83
|
+
const reads = gatedFetch(cfg.rpcUrl, cfg.fallbackUrl, cfg.maxRps);
|
|
84
|
+
// Sends have their own gate, so reads never delay a send.
|
|
85
|
+
const sends = cfg.sendUrl === cfg.rpcUrl ? gatedFetch(cfg.rpcUrl, cfg.fallbackUrl, cfg.maxRps) : gatedFetch(cfg.sendUrl, null, cfg.maxRps);
|
|
86
|
+
const conn = new Connection(cfg.rpcUrl, { commitment: 'confirmed', fetch: reads, disableRetryOnRateLimit: true });
|
|
87
|
+
const send = new Connection(cfg.sendUrl, { commitment: 'confirmed', fetch: sends, disableRetryOnRateLimit: true });
|
|
88
|
+
return {
|
|
89
|
+
conn,
|
|
90
|
+
send,
|
|
91
|
+
host: hostOf(cfg.rpcUrl),
|
|
92
|
+
async call(method, params) {
|
|
93
|
+
const res = await reads(cfg.rpcUrl, {
|
|
94
|
+
method: 'POST',
|
|
95
|
+
headers: { 'content-type': 'application/json' },
|
|
96
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
|
|
97
|
+
});
|
|
98
|
+
const body = (await res.json());
|
|
99
|
+
if (body.error !== undefined)
|
|
100
|
+
throw new Error(redact(`${method}: ${body.error.message ?? 'error'}`));
|
|
101
|
+
return body.result;
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** Refuse to run against any cluster but mainnet. */
|
|
106
|
+
export async function checkCluster(rpc) {
|
|
107
|
+
const genesis = await rpc.conn.getGenesisHash();
|
|
108
|
+
if (genesis !== MAINNET_GENESIS)
|
|
109
|
+
throw new Refusal('config', 'NOT_MAINNET', `${rpc.host} is not a Solana mainnet endpoint (genesis ${genesis})`);
|
|
110
|
+
}
|
|
111
|
+
let feeCache = null;
|
|
112
|
+
/** The priority fee in micro-lamports per compute unit, cached 10 s, never above `max`. */
|
|
113
|
+
async function priorityFee(rpc, writable, max) {
|
|
114
|
+
const key = writable.map((k) => k.toBase58()).join();
|
|
115
|
+
if (feeCache !== null && feeCache.key === key && Date.now() - feeCache.at < 10_000)
|
|
116
|
+
return feeCache.fee;
|
|
117
|
+
let fee;
|
|
118
|
+
if (rpc.host.endsWith('helius-rpc.com')) {
|
|
119
|
+
const r = (await rpc.call('getPriorityFeeEstimate', [{ accountKeys: writable.map((k) => k.toBase58()), options: { recommended: true } }]));
|
|
120
|
+
fee = r.priorityFeeEstimate ?? 0;
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
const samples = (await rpc.conn.getRecentPrioritizationFees({ lockedWritableAccounts: writable })).map((s) => s.prioritizationFee).sort((a, b) => a - b);
|
|
124
|
+
fee = samples.length === 0 ? 0 : samples[Math.floor(samples.length * 0.75)];
|
|
125
|
+
}
|
|
126
|
+
fee = Math.min(max, Math.ceil(fee));
|
|
127
|
+
feeCache = { at: Date.now(), key, fee };
|
|
128
|
+
return fee;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Send signed bytes with maxRetries 0, send the same bytes again every 2 s, and stop when the
|
|
132
|
+
* cluster confirms the signature or the blockhash expires (judged by getEpochInfo's block height).
|
|
133
|
+
*/
|
|
134
|
+
async function sendAndConfirm(rpc, tx, lastValidBlockHeight) {
|
|
135
|
+
const bytes = tx.serialize();
|
|
136
|
+
const options = { skipPreflight: true, maxRetries: 0 };
|
|
137
|
+
const signature = await rpc.send.sendRawTransaction(bytes, options);
|
|
138
|
+
let done = false;
|
|
139
|
+
const again = (async () => {
|
|
140
|
+
while (!done) {
|
|
141
|
+
await sleep(2000);
|
|
142
|
+
if (!done)
|
|
143
|
+
await rpc.send.sendRawTransaction(bytes, options).catch(() => undefined);
|
|
144
|
+
}
|
|
145
|
+
})();
|
|
146
|
+
try {
|
|
147
|
+
const out = await confirmSignature(connectionSignatureReader(rpc.conn), signature, lastValidBlockHeight, {
|
|
148
|
+
waitMs: 150_000,
|
|
149
|
+
pollMs: 1000,
|
|
150
|
+
heightAfterMs: 30_000,
|
|
151
|
+
heightEveryMs: 5000,
|
|
152
|
+
});
|
|
153
|
+
return { signature, out };
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
done = true;
|
|
157
|
+
await again;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const blockhashes = new WeakMap();
|
|
161
|
+
const WAIT = { immediately: 5_000, 'after-state-changes': 30_000, 'after-governance': 600_000, never: 600_000 };
|
|
162
|
+
/**
|
|
163
|
+
* The one path every transaction takes: the compute budget, the priority fee, an optional tip,
|
|
164
|
+
* the size check, a simulation, and (when `send`) one send with a bounded rebroadcast, confirmed
|
|
165
|
+
* by the cluster. A refusal at any step throws a Refusal; nothing is sent after a failed simulation.
|
|
166
|
+
*/
|
|
167
|
+
export async function transact(s, bundle, send) {
|
|
168
|
+
const writable = [...new Set(bundle.instructions.flatMap((x) => x.keys.filter((k) => k.isWritable).map((k) => k.pubkey.toBase58())))];
|
|
169
|
+
const fee = await priorityFee(s.rpc, writable.map((k) => new PublicKey(k)), s.maxPriorityFee);
|
|
170
|
+
const list = [
|
|
171
|
+
ComputeBudgetProgram.setComputeUnitLimit({ units: bundle.computeUnits }),
|
|
172
|
+
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: fee }),
|
|
173
|
+
...bundle.instructions,
|
|
174
|
+
];
|
|
175
|
+
if (s.tip !== null && s.tip.lamports > 0)
|
|
176
|
+
list.push(SystemProgram.transfer({ fromPubkey: s.payer, toPubkey: s.tip.account, lamports: s.tip.lamports }));
|
|
177
|
+
let hash = blockhashes.get(s.rpc);
|
|
178
|
+
if (hash === undefined || Date.now() - hash.at > 5_000) {
|
|
179
|
+
hash = { at: Date.now(), ...(await s.rpc.conn.getLatestBlockhash('confirmed')) };
|
|
180
|
+
blockhashes.set(s.rpc, hash);
|
|
181
|
+
}
|
|
182
|
+
const tx = new VersionedTransaction(new TransactionMessage({ payerKey: s.payer, recentBlockhash: hash.blockhash, instructions: list }).compileToV0Message(bundle.lookupTables ?? []));
|
|
183
|
+
if (s.signer !== null)
|
|
184
|
+
tx.sign([s.signer, ...(s.cosigners ?? [])]);
|
|
185
|
+
const bytes = tx.serialize().length;
|
|
186
|
+
if (bytes > PACKET_LIMIT_BYTES)
|
|
187
|
+
throw new Refusal('send', 'TOO_LARGE', `the transaction is ${bytes} bytes; the limit is ${PACKET_LIMIT_BYTES}`);
|
|
188
|
+
// Simulate first, always. Without a key (a dry run), skip the signature check.
|
|
189
|
+
const sim = await s.rpc.conn.simulateTransaction(tx, { commitment: 'confirmed', sigVerify: s.signer !== null, replaceRecentBlockhash: s.signer === null });
|
|
190
|
+
if (sim.value.err !== null)
|
|
191
|
+
throw refusalOf(sim.value.err, sim.value.logs ?? []);
|
|
192
|
+
const units = sim.value.unitsConsumed ?? 0;
|
|
193
|
+
if (!send)
|
|
194
|
+
return { signature: null, units, bytes, logs: sim.value.logs ?? [] };
|
|
195
|
+
if (s.signer === null)
|
|
196
|
+
throw new Refusal('config', 'NO_SIGNER', 'there is no key to sign with');
|
|
197
|
+
const { signature, out } = await sendAndConfirm(s.rpc, tx, hash.lastValidBlockHeight);
|
|
198
|
+
blockhashes.delete(s.rpc);
|
|
199
|
+
// An expired blockhash with no landing can never land: a resend is safe. An unknown is not.
|
|
200
|
+
if (out.confirmation === 'expired')
|
|
201
|
+
throw new Refusal('send', 'EXPIRED', `${signature} did not land before its blockhash expired`, true, 5_000);
|
|
202
|
+
if (out.confirmation !== 'confirmed') {
|
|
203
|
+
throw new Refusal('send', 'UNCONFIRMED', `${signature} is not confirmed: read your positions before you send again`, false, 60_000);
|
|
204
|
+
}
|
|
205
|
+
if (out.err !== null)
|
|
206
|
+
throw refusalOf(out.err, out.landed?.logMessages ?? []);
|
|
207
|
+
return { signature, units: out.landed?.computeUnits ?? units, bytes, logs: out.landed?.logMessages ?? [] };
|
|
208
|
+
}
|
|
209
|
+
/** Name a failure with the SDK's catalogue, from the program that failed. */
|
|
210
|
+
function refusalOf(err, logs) {
|
|
211
|
+
const code = programErrorCode(err);
|
|
212
|
+
const failed = logs.find((l) => / failed: /.test(l)) ?? '';
|
|
213
|
+
if (code === null)
|
|
214
|
+
return new Refusal('venue', 'TRANSACTION_ERROR', JSON.stringify(err), false);
|
|
215
|
+
if (failed.includes('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA')) {
|
|
216
|
+
return new Refusal('venue', 'TOKEN_TRANSFER_FAILED', `the USDC transfer failed (token error ${code}): does the wallet hold the stake?`, true);
|
|
217
|
+
}
|
|
218
|
+
if (failed !== '' && !failed.includes(PROGRAM_ID)) {
|
|
219
|
+
const m = minuteErrorForCode(code);
|
|
220
|
+
// Minute's refusals carry no retry class; these three clear when the state changes.
|
|
221
|
+
const later = ['OpensPaused', 'VenueOpensPaused', 'NoFreeRoundSlot'].includes(m?.name ?? '');
|
|
222
|
+
if (m !== null)
|
|
223
|
+
return new Refusal('venue', m.name, `Minute ${m.name} (${code}): ${m.msg ?? ''}`.trim(), later);
|
|
224
|
+
}
|
|
225
|
+
const v = errorForCode(code);
|
|
226
|
+
if (v === null)
|
|
227
|
+
return new Refusal('venue', `ERROR_${code}`, `the program refused with code ${code}`, false);
|
|
228
|
+
const retryable = v.retryable === 'immediately' || v.retryable === 'after-state-changes';
|
|
229
|
+
return new Refusal('venue', v.name, `${v.name} (${code}): ${v.fix}`, retryable, WAIT[v.retryable] ?? 60_000);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Wake the bot when one of its accounts changes: a websocket accountSubscribe, or a Yellowstone
|
|
233
|
+
* gRPC stream when GRPC_URL is set. A hint only says "read now"; the bot then reads the accounts
|
|
234
|
+
* over HTTP. After every (re)connect it reads once, because a stream has no replay.
|
|
235
|
+
*/
|
|
236
|
+
export async function watch(cfg, accounts, onHint, signal) {
|
|
237
|
+
if (cfg.grpcUrl !== null)
|
|
238
|
+
return grpcWatch(cfg.grpcUrl, cfg.grpcToken, accounts, onHint, signal);
|
|
239
|
+
let failures = 0;
|
|
240
|
+
let current = null;
|
|
241
|
+
signal.addEventListener('abort', () => current?.close(), { once: true });
|
|
242
|
+
const open = () => {
|
|
243
|
+
if (signal.aborted)
|
|
244
|
+
return;
|
|
245
|
+
const ws = new WebSocket(cfg.wsUrl);
|
|
246
|
+
current = ws;
|
|
247
|
+
ws.onopen = () => {
|
|
248
|
+
accounts.forEach((a, i) => {
|
|
249
|
+
ws.send(JSON.stringify({ jsonrpc: '2.0', id: i + 1, method: 'accountSubscribe', params: [a.toBase58(), { encoding: 'base64', commitment: 'confirmed' }] }));
|
|
250
|
+
});
|
|
251
|
+
};
|
|
252
|
+
let acked = 0;
|
|
253
|
+
ws.onmessage = (e) => {
|
|
254
|
+
const m = JSON.parse(String(e.data));
|
|
255
|
+
if (m.method === 'accountNotification')
|
|
256
|
+
onHint('account changed');
|
|
257
|
+
else if (m.error !== undefined)
|
|
258
|
+
log('stream-refused', { detail: redact(m.error.message ?? 'error') });
|
|
259
|
+
else if (m.id !== undefined && ++acked === accounts.length) {
|
|
260
|
+
failures = 0;
|
|
261
|
+
onHint('stream subscribed');
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
ws.onclose = () => {
|
|
265
|
+
if (signal.aborted)
|
|
266
|
+
return;
|
|
267
|
+
log('stream-closed', { host: hostOf(cfg.wsUrl) });
|
|
268
|
+
setTimeout(open, backoffMs(failures++));
|
|
269
|
+
};
|
|
270
|
+
ws.onerror = () => ws.close();
|
|
271
|
+
};
|
|
272
|
+
open();
|
|
273
|
+
}
|
|
274
|
+
async function grpcWatch(url, token, accounts, onHint, signal) {
|
|
275
|
+
const name = '@triton-one/yellowstone-grpc';
|
|
276
|
+
let mod;
|
|
277
|
+
try {
|
|
278
|
+
mod = await import(__rewriteRelativeImportExtension(name));
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
throw new Error(`GRPC_URL needs the gRPC client: run npm install ${name}`);
|
|
282
|
+
}
|
|
283
|
+
let failures = 0;
|
|
284
|
+
const open = async () => {
|
|
285
|
+
if (signal.aborted)
|
|
286
|
+
return;
|
|
287
|
+
try {
|
|
288
|
+
const client = new mod.default(url, token ?? undefined, undefined);
|
|
289
|
+
await client.connect();
|
|
290
|
+
const stream = await client.subscribe();
|
|
291
|
+
signal.addEventListener('abort', () => stream.destroy(), { once: true });
|
|
292
|
+
const retry = () => {
|
|
293
|
+
if (signal.aborted)
|
|
294
|
+
return;
|
|
295
|
+
log('stream-closed', { host: hostOf(url) });
|
|
296
|
+
setTimeout(open, backoffMs(failures++));
|
|
297
|
+
};
|
|
298
|
+
stream.on('error', () => stream.destroy());
|
|
299
|
+
stream.on('close', retry);
|
|
300
|
+
stream.on('data', (u) => u.account !== undefined && onHint('account changed'));
|
|
301
|
+
// The bot's own accounts only, never an empty filter (that would stream everything).
|
|
302
|
+
const request = {
|
|
303
|
+
accounts: { bot: { account: accounts.map((a) => a.toBase58()), owner: [], filters: [] } },
|
|
304
|
+
slots: {}, transactions: {}, transactionsStatus: {}, blocks: {}, blocksMeta: {}, entry: {},
|
|
305
|
+
accountsDataSlice: [], commitment: mod.CommitmentLevel.CONFIRMED,
|
|
306
|
+
};
|
|
307
|
+
stream.write(request, (err) => {
|
|
308
|
+
if (err)
|
|
309
|
+
return stream.destroy();
|
|
310
|
+
failures = 0;
|
|
311
|
+
onHint('stream subscribed');
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
log('stream-refused', { host: hostOf(url), detail: redact(e.message) });
|
|
316
|
+
setTimeout(open, backoffMs(failures++));
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
// Load the client now, so a missing package stops the bot at start.
|
|
320
|
+
void open();
|
|
321
|
+
}
|
package/dist/runner.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// The bot: prices in, one strategy call a second, the risk guard, then a broker (live or paper).
|
|
2
|
+
// `wheelman run` drives it; the one-shot commands call the same broker methods.
|
|
3
|
+
import { usd as money, guard } from "./risk.js";
|
|
4
|
+
import { balances, collect } from "./account.js";
|
|
5
|
+
import { Refusal } from "./errors.js";
|
|
6
|
+
import { log } from "./journal.js";
|
|
7
|
+
import { History } from "./prices.js";
|
|
8
|
+
/** The slow read that backs up the stream: the bot reads its accounts at least this often. */
|
|
9
|
+
const POLL_MS = 30_000;
|
|
10
|
+
const utcDay = (ms) => Math.floor(ms / 86_400_000);
|
|
11
|
+
export const dayStart = (ms = Date.now()) => utcDay(ms) * 86_400;
|
|
12
|
+
export async function trade(o) {
|
|
13
|
+
const history = new History(2 * 3600 * 1000);
|
|
14
|
+
const memory = {};
|
|
15
|
+
const lastRefusal = new Map();
|
|
16
|
+
let todayPnl = o.todayPnl ?? 0n;
|
|
17
|
+
let lastEval = 0;
|
|
18
|
+
let holdUntil = 0;
|
|
19
|
+
let day = null;
|
|
20
|
+
for await (const tick of o.source.ticks([o.market], o.signal)) {
|
|
21
|
+
if (tick.market !== o.market)
|
|
22
|
+
continue;
|
|
23
|
+
history.add(tick);
|
|
24
|
+
day ??= utcDay(tick.time);
|
|
25
|
+
if (utcDay(tick.time) !== day) {
|
|
26
|
+
day = utcDay(tick.time);
|
|
27
|
+
todayPnl = 0n;
|
|
28
|
+
log('new-day', {});
|
|
29
|
+
}
|
|
30
|
+
todayPnl += await o.broker.onTick(tick);
|
|
31
|
+
if (tick.time - lastEval < 1000)
|
|
32
|
+
continue;
|
|
33
|
+
lastEval = tick.time;
|
|
34
|
+
const ctx = {
|
|
35
|
+
now: tick.time, market: o.market, price: tick.price,
|
|
36
|
+
priceAgo: (s) => history.priceAgo(tick.time, s), range: (s) => history.range(tick.time, s),
|
|
37
|
+
positions: o.broker.positions(), params: o.params, memory,
|
|
38
|
+
};
|
|
39
|
+
const intents = o.strategy.onTick(ctx);
|
|
40
|
+
if (intents.length === 0 || tick.time < holdUntil)
|
|
41
|
+
continue;
|
|
42
|
+
await o.broker.beforeAct();
|
|
43
|
+
const verdict = guard(intents, o.broker.book(todayPnl), o.limits);
|
|
44
|
+
for (const r of verdict.refused) {
|
|
45
|
+
if (tick.time - (lastRefusal.get(r.why) ?? -Infinity) < 60_000)
|
|
46
|
+
continue;
|
|
47
|
+
lastRefusal.set(r.why, tick.time);
|
|
48
|
+
log('risk-refused', { intent: r.intent.kind, why: r.why });
|
|
49
|
+
}
|
|
50
|
+
if (verdict.allowed.length > 0)
|
|
51
|
+
holdUntil = Math.max(holdUntil, await o.broker.execute(verdict.allowed, tick.time));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** The live broker: the chain is the state, read on a stream hint, before each send, and every 30 s. */
|
|
55
|
+
export class Live {
|
|
56
|
+
h;
|
|
57
|
+
market;
|
|
58
|
+
dirty = true;
|
|
59
|
+
lastRead = 0;
|
|
60
|
+
lastCollect = 0;
|
|
61
|
+
realized = 0n;
|
|
62
|
+
held = [];
|
|
63
|
+
known = new Map(); // open id -> stake, to see a position end
|
|
64
|
+
ended = new Map();
|
|
65
|
+
wallet = { usdc: 0n, owed: 0n, custody: 0n, payerSol: 0 };
|
|
66
|
+
constructor(h, market) {
|
|
67
|
+
this.h = h;
|
|
68
|
+
this.market = market;
|
|
69
|
+
}
|
|
70
|
+
wake() {
|
|
71
|
+
this.dirty = true;
|
|
72
|
+
}
|
|
73
|
+
async onTick() {
|
|
74
|
+
if (this.dirty || Date.now() - this.lastRead > POLL_MS)
|
|
75
|
+
await this.refresh();
|
|
76
|
+
const r = this.realized;
|
|
77
|
+
this.realized = 0n;
|
|
78
|
+
return r;
|
|
79
|
+
}
|
|
80
|
+
positions() {
|
|
81
|
+
return this.held.filter((p) => p.market === this.market);
|
|
82
|
+
}
|
|
83
|
+
book(todayPnl) {
|
|
84
|
+
return {
|
|
85
|
+
open: this.held.length, atStake: this.held.reduce((s, p) => s + p.stake, 0n),
|
|
86
|
+
free: this.wallet.usdc, held: this.wallet.owed + this.wallet.custody, todayPnl, sol: this.wallet.payerSol,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async beforeAct() {
|
|
90
|
+
await this.refresh();
|
|
91
|
+
}
|
|
92
|
+
async execute(intents, now) {
|
|
93
|
+
let hold = 0;
|
|
94
|
+
for (const batch of batches(intents)) {
|
|
95
|
+
try {
|
|
96
|
+
log('sent', { ...(await sendBatch(this.h, this.market, batch)) });
|
|
97
|
+
}
|
|
98
|
+
catch (e) {
|
|
99
|
+
if (!(e instanceof Refusal))
|
|
100
|
+
throw e;
|
|
101
|
+
log('refused', { category: e.category, code: e.code, message: e.message, retryable: e.retryable });
|
|
102
|
+
hold = Math.max(hold, now + e.waitMs);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
this.dirty = true;
|
|
106
|
+
return hold;
|
|
107
|
+
}
|
|
108
|
+
/** Read the chain, and account for every position that ended since the last read. */
|
|
109
|
+
async refresh() {
|
|
110
|
+
const [held, b] = await Promise.all([heldBy(this.h), balances(this.h.rpc, this.h.owner, this.h.sender.payer)]);
|
|
111
|
+
this.held = held;
|
|
112
|
+
this.wallet = b;
|
|
113
|
+
this.lastRead = Date.now();
|
|
114
|
+
this.dirty = false;
|
|
115
|
+
const now = new Set(held.map((p) => p.id));
|
|
116
|
+
for (const [id, stake] of this.known)
|
|
117
|
+
if (!now.has(id))
|
|
118
|
+
this.ended.set(id, { stake, tries: 0 });
|
|
119
|
+
this.known = new Map(held.map((p) => [p.id, p.stake]));
|
|
120
|
+
for (const [id, e] of this.ended) {
|
|
121
|
+
const s = this.h.game === 'minute' ? await this.h.minute.settlement(BigInt(id), e.stake) : await this.h.knockout.settlement(BigInt(id));
|
|
122
|
+
if (s !== null) {
|
|
123
|
+
this.realized += s.pnl;
|
|
124
|
+
log('closed', { id, reason: s.reason, payout: money(s.payout), pnl: money(s.pnl) });
|
|
125
|
+
this.ended.delete(id);
|
|
126
|
+
}
|
|
127
|
+
else if (++e.tries >= 10) {
|
|
128
|
+
// Not found after ten reads: count the whole stake as lost, so the loss stop errs safe.
|
|
129
|
+
this.realized -= e.stake;
|
|
130
|
+
log('closed', { id, reason: 'not found on chain; counted as a loss', pnl: money(-e.stake) });
|
|
131
|
+
this.ended.delete(id);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (b.owed + b.custody > 0n && Date.now() - this.lastCollect > 300_000) {
|
|
135
|
+
this.lastCollect = Date.now();
|
|
136
|
+
try {
|
|
137
|
+
const c = await collect(this.h.sender, this.h.owner, true);
|
|
138
|
+
if (c !== null)
|
|
139
|
+
log('collected', { signature: c.signature });
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
if (!(e instanceof Refusal))
|
|
143
|
+
throw e;
|
|
144
|
+
log('refused', { category: e.category, code: e.code, message: e.message });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** Every position and live round of the wallet, on every market. */
|
|
150
|
+
export async function heldBy(h) {
|
|
151
|
+
if (h.game === 'minute') {
|
|
152
|
+
return (await h.minute.rounds()).map((r) => ({
|
|
153
|
+
id: r.seq.toString(), game: 'minute', market: r.market, side: r.side, stake: r.total, entry: r.entryPrice, openedMs: r.openedAt * 1000, closing: false,
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
return (await h.knockout.positions()).map((p) => ({
|
|
157
|
+
id: p.seq.toString(), game: 'knockout', market: p.market, side: p.side, stake: p.stake, entry: p.entryPrice,
|
|
158
|
+
openedMs: p.openedAt * 1000, closing: p.state.startsWith('Exit') || p.state.startsWith('Stamped'),
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
161
|
+
/** Today's realized result (UTC), from the chain. */
|
|
162
|
+
export async function realizedToday(h) {
|
|
163
|
+
const since = dayStart();
|
|
164
|
+
const list = h.game === 'minute' ? await h.minute.history({ since }) : await h.knockout.history({ since });
|
|
165
|
+
return list.reduce((s, x) => s + x.pnl, 0n);
|
|
166
|
+
}
|
|
167
|
+
/** Intents that share a group (the two sides of a straddle) go in one transaction. */
|
|
168
|
+
function batches(intents) {
|
|
169
|
+
const out = new Map();
|
|
170
|
+
intents.forEach((i, n) => {
|
|
171
|
+
const key = i.kind === 'open' && i.group !== undefined ? `group ${i.group}` : `intent ${n}`;
|
|
172
|
+
out.set(key, [...(out.get(key) ?? []), i]);
|
|
173
|
+
});
|
|
174
|
+
return [...out.values()];
|
|
175
|
+
}
|
|
176
|
+
const orderOf = (market, i) => ({ market, side: i.side, usd: i.stake, target: i.takeProfitX, timer: i.timerS });
|
|
177
|
+
/** Send one batch of intents: one transaction. */
|
|
178
|
+
export async function sendBatch(h, market, batch) {
|
|
179
|
+
const first = batch[0];
|
|
180
|
+
if (first.kind === 'close')
|
|
181
|
+
return { what: 'close', id: first.id, ...(await h.knockout.close(BigInt(first.id))) };
|
|
182
|
+
if (first.kind === 'round') {
|
|
183
|
+
const r = await h.minute.round({ market, side: first.side, usd: first.stake });
|
|
184
|
+
return { what: 'round', seq: r.seq.toString(), signature: r.signature };
|
|
185
|
+
}
|
|
186
|
+
const orders = batch.filter((i) => i.kind === 'open').map((i) => orderOf(market, i));
|
|
187
|
+
const opened = await h.knockout.open(orders);
|
|
188
|
+
return { what: 'open', signature: opened.signature, seqs: opened.seqs.map(String) };
|
|
189
|
+
}
|
package/dist/setup.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Onboarding: wheelman setup asks each question, with a default and a bound
|
|
2
|
+
// wheelman setup --yes takes every answer from the environment (for agents and scripts)
|
|
3
|
+
// It writes .env (mode 600) and, if asked, a new wallet file (mode 600). It never prints a secret.
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { createInterface } from 'node:readline/promises';
|
|
6
|
+
import { Keypair, PublicKey } from '@solana/web3.js';
|
|
7
|
+
import { PROGRAM_ID, parseUsdc } from '@rekt-trading/1000x';
|
|
8
|
+
import { MINUTE_PROGRAM_ID } from '@rekt-trading/1000x'; // Minute's API ships in the same package
|
|
9
|
+
import { ConfigError, MARKETS, loadKeypair, parseConfig, parseParam } from "./config.js";
|
|
10
|
+
import { redact } from "./journal.js";
|
|
11
|
+
import { MIN_SOL, usd } from "./risk.js";
|
|
12
|
+
import { makeRpc } from "./rpc.js";
|
|
13
|
+
import { registry } from "./strategies/index.js";
|
|
14
|
+
const LOGO = String.raw `
|
|
15
|
+
__ __ _ _
|
|
16
|
+
\ \ / /| |_ ___ ___ | | _ __ __ _ _ _
|
|
17
|
+
\ \/\/ / | ' \ / -_)/ -_)| || ' \ / _' || ' \
|
|
18
|
+
\_/\_/ |_||_|\___|\___||_||_|_|_|\__,_||_||_|
|
|
19
|
+
Wheelman, the Rekt trading bot and CLI
|
|
20
|
+
`;
|
|
21
|
+
const WALLET_FILE = 'wallets/bot-keypair.json';
|
|
22
|
+
const DOCS = 'https://docs.rekt.money';
|
|
23
|
+
export async function setup(o) {
|
|
24
|
+
const { yes, force, say } = o;
|
|
25
|
+
const env = {};
|
|
26
|
+
const rl = yes ? null : createInterface({ input: process.stdin, output: process.stdout });
|
|
27
|
+
const ask = async (question, def, check = () => null) => {
|
|
28
|
+
for (;;) {
|
|
29
|
+
const answer = rl === null ? (def ?? '') : ((await rl.question(`${question}${def === undefined || def === '' ? '' : ` [${def}]`}: `)).trim() || (def ?? ''));
|
|
30
|
+
const problem = answer === '' ? 'an answer is required' : check(answer);
|
|
31
|
+
if (problem === null)
|
|
32
|
+
return answer;
|
|
33
|
+
if (rl === null)
|
|
34
|
+
throw new ConfigError(`${question}: ${problem}`);
|
|
35
|
+
say(` ${problem}`);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const from = (name) => process.env[name]?.trim() || undefined;
|
|
39
|
+
say(LOGO);
|
|
40
|
+
say(`Answers go to .env (mode 600). Every variable is in .env.example. Docs: ${DOCS}\n`);
|
|
41
|
+
if (existsSync('.env') && !force) {
|
|
42
|
+
if (rl === null)
|
|
43
|
+
throw new ConfigError('.env exists: run with --force to replace it');
|
|
44
|
+
if ((await ask('.env exists. Replace it? (yes/no)', 'no')) !== 'yes') {
|
|
45
|
+
rl.close();
|
|
46
|
+
return { wrote: null };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// 1. The wallet. Only the address is ever shown.
|
|
50
|
+
let wallet;
|
|
51
|
+
const existing = from('KEYPAIR_PATH') ?? (existsSync(WALLET_FILE) ? WALLET_FILE : undefined);
|
|
52
|
+
const choice = existing !== undefined ? 'keep' : from('WALLET_IMPORT') !== undefined ? 'import' : 'create';
|
|
53
|
+
const how = await ask('Wallet: create, import or keep', choice, (v) => (['create', 'import', 'keep'].includes(v) ? null : 'create, import or keep'));
|
|
54
|
+
if (how === 'keep') {
|
|
55
|
+
const path = await ask('Keypair file', existing, (v) => (existsSync(v) ? null : 'no such file'));
|
|
56
|
+
wallet = loadKeypair(readFileSync(path, 'utf8'));
|
|
57
|
+
env.KEYPAIR_PATH = path;
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
if (existsSync(WALLET_FILE))
|
|
61
|
+
throw new ConfigError(`${WALLET_FILE} exists: choose keep, or move it first`);
|
|
62
|
+
wallet = how === 'import'
|
|
63
|
+
? loadKeypair(readFileSync(await ask('Keypair file to import', from('WALLET_IMPORT'), (v) => (existsSync(v) ? null : 'no such file')), 'utf8'))
|
|
64
|
+
: Keypair.generate();
|
|
65
|
+
mkdirSync('wallets', { recursive: true, mode: 0o700 });
|
|
66
|
+
writeFileSync(WALLET_FILE, JSON.stringify(Array.from(wallet.secretKey)), { mode: 0o600, flag: 'wx' });
|
|
67
|
+
env.KEYPAIR_PATH = WALLET_FILE;
|
|
68
|
+
say(` wrote ${WALLET_FILE} (mode 600). Back it up: it is the only copy of this wallet's key.`);
|
|
69
|
+
}
|
|
70
|
+
say(` wallet address: ${wallet.publicKey.toBase58()}\n`);
|
|
71
|
+
// 2. RPC: the user's own endpoint. There is no default and no shared key.
|
|
72
|
+
env.RPC_URL = await ask('RPC_URL, your HTTPS RPC endpoint (Helius, Triton, QuickNode, your own node)', from('RPC_URL'), (v) => /^(https:\/\/|http:\/\/localhost[:/])/.test(v) ? null : 'it must start with https://');
|
|
73
|
+
for (const name of ['RPC_WS_URL', 'GRPC_URL', 'GRPC_TOKEN', 'SEND_URL', 'RPC_FALLBACK_URL', 'SEND_TIP_LAMPORTS', 'SEND_TIP_ACCOUNT']) {
|
|
74
|
+
const v = from(name);
|
|
75
|
+
if (v !== undefined)
|
|
76
|
+
env[name] = v;
|
|
77
|
+
}
|
|
78
|
+
// 3. The public values come from the SDK; nothing to type.
|
|
79
|
+
say(`\n Knockout program ${PROGRAM_ID}\n Minute program ${MINUTE_PROGRAM_ID}\n Every governed value is read from the chain at run time.\n`);
|
|
80
|
+
// 4. Game, market, strategy and its parameters.
|
|
81
|
+
const strategies = await registry();
|
|
82
|
+
const game = await ask('Game: knockout or minute', from('STRATEGY') === undefined ? 'knockout' : strategies.get(from('STRATEGY'))?.game, (v) => v === 'knockout' || v === 'minute' ? null : 'knockout or minute');
|
|
83
|
+
const ids = [...strategies.values()].filter((s) => s.game === game).map((s) => s.id);
|
|
84
|
+
for (const id of ids)
|
|
85
|
+
say(` ${id}: ${strategies.get(id).description}`);
|
|
86
|
+
env.STRATEGY = await ask('Strategy', from('STRATEGY') ?? ids[0], (v) => (ids.includes(v) ? null : `one of ${ids.join(', ')}`));
|
|
87
|
+
env.MARKET = (await ask(`Market (${MARKETS.slice(0, 4).join(', ')})`, from('MARKET') ?? 'BTC', (v) => MARKETS.slice(0, 4).includes(v.toUpperCase()) ? null : `one of ${MARKETS.slice(0, 4).join(', ')}`)).toUpperCase();
|
|
88
|
+
const strategy = strategies.get(env.STRATEGY);
|
|
89
|
+
for (const [key, p] of Object.entries(strategy.params)) {
|
|
90
|
+
const name = `PARAM_${key.toUpperCase()}`;
|
|
91
|
+
const bound = p.kind === 'choice' ? p.choices.join(', ') : `${p.min} to ${p.max}${p.kind === 'number' && p.zeroOff ? ', or 0' : ''}`;
|
|
92
|
+
env[name] = await ask(`${key}: ${p.help} (${bound})`, from(name) ?? p.default, (v) => {
|
|
93
|
+
const r = parseParam(name, p, v);
|
|
94
|
+
return 'problem' in r ? r.problem : null;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
// 5. Risk limits. A loss stop is required.
|
|
98
|
+
const stake = env.PARAM_STAKE_USDC ?? '1';
|
|
99
|
+
const amount = (v) => {
|
|
100
|
+
try {
|
|
101
|
+
return parseUsdc(v) >= 0n ? null : 'not an amount';
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return 'an amount of USDC, like 1.50';
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
env.MAX_STAKE_USDC = await ask('MAX_STAKE_USDC, the largest stake of one trade', from('MAX_STAKE_USDC') ?? stake, amount);
|
|
108
|
+
env.MAX_OPEN = await ask('MAX_OPEN, the most positions open at once (1 to 12)', from('MAX_OPEN') ?? '2', (v) => /^([1-9]|1[0-2])$/.test(v) ? null : 'a whole number from 1 to 12');
|
|
109
|
+
env.DAILY_LOSS_USDC = await ask('DAILY_LOSS_USDC, stop opening when today\'s loss would pass this (required)', from('DAILY_LOSS_USDC'), (v) => amount(v) ?? (parseUsdc(v) > 0n ? null : 'the bot runs only with a loss stop above 0'));
|
|
110
|
+
env.MIN_BALANCE_USDC = await ask('MIN_BALANCE_USDC, never let the wallet drop below this', from('MIN_BALANCE_USDC') ?? '0', amount);
|
|
111
|
+
rl?.close();
|
|
112
|
+
// 6. Check the whole configuration the way `wheelman run` will, then write it.
|
|
113
|
+
parseConfig(env, { strategy: true, limits: true, key: 'signer' }, strategies);
|
|
114
|
+
const lines = ['# Written by wheelman setup. Every variable is documented in .env.example.', ...Object.entries(env).map(([k, v]) => `${k}=${v}`)];
|
|
115
|
+
writeFileSync('.env', `${lines.join('\n')}\n`, { mode: 0o600 });
|
|
116
|
+
chmodSync('.env', 0o600);
|
|
117
|
+
say('\nwrote .env (mode 600)');
|
|
118
|
+
// 7. The funding check: SOL for fees and rent, USDC for stakes.
|
|
119
|
+
let funding = null;
|
|
120
|
+
try {
|
|
121
|
+
const rpc = makeRpc({ rpcUrl: env.RPC_URL, fallbackUrl: null, sendUrl: env.RPC_URL, maxRps: 5 });
|
|
122
|
+
const usdc = PublicKey.findProgramAddressSync([wallet.publicKey.toBytes(), new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA').toBytes(), new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v').toBytes()], new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'))[0];
|
|
123
|
+
const [sol, token] = await rpc.conn.getMultipleAccountsInfo([wallet.publicKey, usdc], 'confirmed');
|
|
124
|
+
const held = token === null ? 0n : Buffer.from(token.data).readBigUInt64LE(64);
|
|
125
|
+
funding = { sol: (sol?.lamports ?? 0) / 1e9, usdc: usd(held) };
|
|
126
|
+
say(`funding: ${(sol?.lamports ?? 0) / 1e9} SOL (needs ${MIN_SOL} for fees and rent), ${usd(held)} USDC (needs at least ${usd(parseUsdc(stake))})`);
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
say(`funding: could not read the wallet: ${redact(e.message)}`);
|
|
130
|
+
}
|
|
131
|
+
say('\nNext: wheelman run --paper (simulated fills, sends nothing)\n wheelman run --dry-run (builds and simulates the real transactions, sends nothing)\n wheelman run (trades)');
|
|
132
|
+
return { wrote: '.env', wallet: wallet.publicKey.toBase58(), keypairPath: env.KEYPAIR_PATH, funding };
|
|
133
|
+
}
|