@rekt-trading/wheelman 0.0.0-stage → 1.0.1
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/mcp.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// A local MCP server on stdio: the CLI's commands as tools, each answering with the same envelope.
|
|
2
|
+
// Read tools always. `open` and `close` only when a session key is configured (they then trade with
|
|
3
|
+
// it, never with the owner's key), or with `wheelman mcp --paper` (they then trade on paper only).
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
import * as cmd from "./commands.js";
|
|
6
|
+
import { MARKETS, parseConfig } from "./config.js";
|
|
7
|
+
import { Refusal, envelopeOf, toJson } from "./errors.js";
|
|
8
|
+
import { redact } from "./journal.js";
|
|
9
|
+
const VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
10
|
+
const order = {
|
|
11
|
+
market: { type: 'string', enum: MARKETS, description: 'the market' },
|
|
12
|
+
side: { type: 'string', enum: ['long', 'short'] },
|
|
13
|
+
usd: { type: 'string', description: 'what leaves the wallet, in USDC, like "1.50"' },
|
|
14
|
+
target: { type: 'number', description: 'take-profit as a multiple of the stake (2 or more); omit for none' },
|
|
15
|
+
timer: { type: 'number', description: 'the position timer in seconds (26 or more); omit for none' },
|
|
16
|
+
minute: { type: 'boolean', description: 'a Minute round instead of a Knockout position' },
|
|
17
|
+
};
|
|
18
|
+
const modes = {
|
|
19
|
+
paper: { type: 'boolean', description: 'simulated fills; sends nothing' },
|
|
20
|
+
dry_run: { type: 'boolean', description: 'build and simulate on mainnet; sends nothing' },
|
|
21
|
+
};
|
|
22
|
+
const args = (a) => ({
|
|
23
|
+
market: a.market, side: a.side, usd: a.usd === undefined ? undefined : String(a.usd),
|
|
24
|
+
target: a.target, timer: a.timer, minute: a.minute === true, id: a.id === undefined ? undefined : String(a.id),
|
|
25
|
+
paper: a.paper === true, dryRun: a.dry_run === true,
|
|
26
|
+
});
|
|
27
|
+
const READ = [
|
|
28
|
+
{ name: 'markets', description: 'Every market: open or not and why, stake bounds, leverage, fees, room left on each side.',
|
|
29
|
+
inputSchema: { type: 'object', properties: {} }, annotations: { readOnlyHint: true, openWorldHint: true }, run: (ctx) => cmd.markets(ctx) },
|
|
30
|
+
{ name: 'preview', description: 'What an open costs and what it pays at its target and at its barrier, after every fee. Sends nothing.',
|
|
31
|
+
inputSchema: { type: 'object', properties: order, required: ['market', 'side', 'usd'] }, annotations: { readOnlyHint: true, openWorldHint: true },
|
|
32
|
+
run: (ctx, a) => cmd.preview(ctx, args(a)) },
|
|
33
|
+
{ name: 'positions', description: 'The wallet\'s open positions and Minute rounds, its balances and today\'s result (paper: the paper account).',
|
|
34
|
+
inputSchema: { type: 'object', properties: { paper: modes.paper } }, annotations: { readOnlyHint: true, openWorldHint: true },
|
|
35
|
+
run: (ctx, a) => cmd.positions(ctx, args(a)) },
|
|
36
|
+
{ name: 'session_status', description: 'Where the session key stands: active, expired or ended, what it may still spend, when it expires.',
|
|
37
|
+
inputSchema: { type: 'object', properties: {} }, annotations: { readOnlyHint: true, openWorldHint: true }, run: (ctx) => cmd.sessionStatusCommand(ctx) },
|
|
38
|
+
];
|
|
39
|
+
const trading = (paperOnly) => {
|
|
40
|
+
const force = (a) => (paperOnly ? { ...a, paper: true } : a);
|
|
41
|
+
const note = paperOnly ? ' Paper only: simulated fills, nothing is sent.' : ' Signed with the session key, inside its allowance and expiry, after the risk limits.';
|
|
42
|
+
return [
|
|
43
|
+
{ name: 'open', description: `Open a Knockout position (or a Minute round with minute: true).${note}`,
|
|
44
|
+
inputSchema: { type: 'object', properties: { ...order, ...modes }, required: ['market', 'side', 'usd'] },
|
|
45
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }, run: (ctx, a) => cmd.open(ctx, args(force(a))) },
|
|
46
|
+
{ name: 'close', description: `Ask the venue to close a Knockout position by its id.${note}`,
|
|
47
|
+
inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'the position id (its seq)' }, market: order.market, ...modes }, required: ['id'] },
|
|
48
|
+
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, run: (ctx, a) => cmd.close(ctx, args(force(a))) },
|
|
49
|
+
];
|
|
50
|
+
};
|
|
51
|
+
/** The tools this server offers: trading tools only with a session key, or on paper. `--paper` wins over a session key. */
|
|
52
|
+
function toolsFor(ctx, paper) {
|
|
53
|
+
let session = false;
|
|
54
|
+
try {
|
|
55
|
+
session = parseConfig(ctx.env, {}, ctx.strategies).session !== null;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// a bad configuration still serves the read tools, which then say what is wrong
|
|
59
|
+
}
|
|
60
|
+
return paper ? [...READ, ...trading(true)] : session ? [...READ, ...trading(false)] : READ;
|
|
61
|
+
}
|
|
62
|
+
export async function serve(ctx, o) {
|
|
63
|
+
const output = o.output ?? process.stdout;
|
|
64
|
+
const tools = toolsFor(ctx, o.paper);
|
|
65
|
+
const send = (message) => output.write(`${redact(toJson(message))}\n`);
|
|
66
|
+
const lines = createInterface({ input: o.input ?? process.stdin, crlfDelay: Infinity });
|
|
67
|
+
const pending = [];
|
|
68
|
+
const answer = async (m) => {
|
|
69
|
+
const reply = (result) => send({ jsonrpc: '2.0', id: m.id, result });
|
|
70
|
+
const fail = (code, message) => send({ jsonrpc: '2.0', id: m.id, error: { code, message } });
|
|
71
|
+
switch (m.method) {
|
|
72
|
+
case 'initialize': {
|
|
73
|
+
const asked = String(m.params?.protocolVersion ?? '');
|
|
74
|
+
return reply({
|
|
75
|
+
protocolVersion: VERSIONS.includes(asked) ? asked : VERSIONS[0], capabilities: { tools: {} },
|
|
76
|
+
serverInfo: { name: 'wheelman', version: '1.0.0' },
|
|
77
|
+
instructions: 'Wheelman trades on Rekt Knockout and Minute. Every tool answers with {ok, data} or {ok: false, error: {category, code, message, retryable}}. Retry only when retryable is true.',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
case 'ping':
|
|
81
|
+
return reply({});
|
|
82
|
+
case 'tools/list':
|
|
83
|
+
return reply({ tools: tools.map(({ run: _run, ...t }) => t) });
|
|
84
|
+
case 'tools/call': {
|
|
85
|
+
const tool = tools.find((t) => t.name === m.params?.name);
|
|
86
|
+
if (tool === undefined)
|
|
87
|
+
return fail(-32602, `unknown tool ${String(m.params?.name)}`);
|
|
88
|
+
let out;
|
|
89
|
+
try {
|
|
90
|
+
out = { ok: true, data: await tool.run(ctx, m.params?.arguments ?? {}) };
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
out = envelopeOf(e instanceof Error || e instanceof Refusal ? e : new Error(String(e)));
|
|
94
|
+
}
|
|
95
|
+
return reply({ content: [{ type: 'text', text: toJson(out) }], isError: !out.ok });
|
|
96
|
+
}
|
|
97
|
+
default:
|
|
98
|
+
if (m.id !== undefined)
|
|
99
|
+
return fail(-32601, `unknown method ${String(m.method)}`);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
for await (const line of lines) {
|
|
103
|
+
if (line.trim() === '')
|
|
104
|
+
continue;
|
|
105
|
+
let m;
|
|
106
|
+
try {
|
|
107
|
+
m = JSON.parse(line);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
// A notification (no id) gets no answer; requests are answered as they finish.
|
|
114
|
+
pending.push(answer(m).then(() => undefined));
|
|
115
|
+
}
|
|
116
|
+
await Promise.all(pending);
|
|
117
|
+
}
|
package/dist/minute.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// Minute rounds, in the same shape as the Knockout client: rounds, preview, round, history, build.
|
|
2
|
+
// A round runs on Minute's own clock and has no early exit; the venue's keepers settle it.
|
|
3
|
+
import { PublicKey } from '@solana/web3.js';
|
|
4
|
+
import { PROGRAM_ID, assetId, collateralForTotal, configPda, connectionReader, decodeConfig, decodeFeeTermsTable, decodeMarket, decodeTraderAccount, decodeVault, feeTermsTablePda, findBySeq, marketPda, memoReader, parseUsdc, pricingRemainingAccounts, readTradeHistory, toBase58, toHex, vaultPda, withFeeTermsTable, } from '@rekt-trading/1000x';
|
|
5
|
+
import { ROUND_STATUS, decodeMinuteConfig, decodeMinuteEvent, decodePlayerAccount, minuteConfigPda, minuteEventPayloads, minuteIx, minutePlayerPda, minutePlayerTokenPda, minuteTraderBookFor, } from '@rekt-trading/1000x'; // Minute's API ships in the same package
|
|
6
|
+
import { ata, bundleOf, marketSymbol } from "./client.js";
|
|
7
|
+
import { Refusal } from "./errors.js";
|
|
8
|
+
import { payoutAt, scaled, termsFor } from "./paper.js";
|
|
9
|
+
import { CLOCK, transact } from "./rpc.js";
|
|
10
|
+
export function createMinuteClient(o) {
|
|
11
|
+
const owner = o.owner;
|
|
12
|
+
const player = minutePlayerPda(owner);
|
|
13
|
+
const book = minuteTraderBookFor(owner, player.bump).positions;
|
|
14
|
+
const custody = minutePlayerTokenPda(player.address).address;
|
|
15
|
+
const session = o.signer !== null && !o.signer.publicKey.equals(owner);
|
|
16
|
+
const signer = o.signer?.publicKey ?? owner;
|
|
17
|
+
const sender = { rpc: o.rpc, payer: signer, signer: o.signer, maxPriorityFee: o.maxPriorityFee ?? 100_000, tip: o.tip ?? null };
|
|
18
|
+
const reader = memoReader(connectionReader(o.rpc.conn), o.store === undefined ? {} : { store: o.store });
|
|
19
|
+
let lookupTables = null;
|
|
20
|
+
async function read(symbol) {
|
|
21
|
+
const market = marketPda(assetId(symbol)).address;
|
|
22
|
+
const [c, v, m, f, mc, p, k] = await o.rpc.conn.getMultipleAccountsInfo([configPda().address, vaultPda().address, market, feeTermsTablePda(market).address, minuteConfigPda().address, player.address, CLOCK], 'confirmed');
|
|
23
|
+
if (c === null || v === null || mc === null)
|
|
24
|
+
throw new Refusal('config', 'VENUE_MISSING', 'the venue or Minute config is missing: is RPC_URL a mainnet endpoint?');
|
|
25
|
+
if (m === null)
|
|
26
|
+
throw new Refusal('config', 'NO_SUCH_MARKET', `${symbol} is not listed on the venue`);
|
|
27
|
+
return {
|
|
28
|
+
config: decodeConfig(new Uint8Array(c.data)), vault: decodeVault(new Uint8Array(v.data)), market: decodeMarket(new Uint8Array(m.data)),
|
|
29
|
+
feeTable: f === null ? null : decodeFeeTermsTable(new Uint8Array(f.data)), minute: decodeMinuteConfig(new Uint8Array(mc.data)),
|
|
30
|
+
playerExists: p !== null, nowUnix: Buffer.from(k.data).readBigInt64LE(32),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
async function rounds() {
|
|
34
|
+
const [p, b] = await o.rpc.conn.getMultipleAccountsInfo([player.address, book], 'confirmed');
|
|
35
|
+
if (p === null || b === null)
|
|
36
|
+
return [];
|
|
37
|
+
const venueBook = decodeTraderAccount(new Uint8Array(b.data));
|
|
38
|
+
return decodePlayerAccount(new Uint8Array(p.data)).rounds.flatMap((r) => {
|
|
39
|
+
// A round whose venue position is gone has ended; Minute records it later.
|
|
40
|
+
const v = r.status === ROUND_STATUS.LIVE ? findBySeq(venueBook, r.seq) : null;
|
|
41
|
+
if (v === null)
|
|
42
|
+
return [];
|
|
43
|
+
return [{
|
|
44
|
+
seq: r.seq, market: marketSymbol(r.market), side: r.direction === 0 ? 'long' : 'short', total: r.openingGross, stake: r.stake,
|
|
45
|
+
entryPrice: v.entryPrice === 0n ? null : Number(v.entryPrice) * 10 ** v.entryExpo, openedAt: Number(r.openedAtUnix), deadline: Number(r.deadlineUnix),
|
|
46
|
+
}];
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async function preview(order) {
|
|
50
|
+
const r = await read(order.market);
|
|
51
|
+
const total = typeof order.usd === 'bigint' ? order.usd : parseUsdc(order.usd);
|
|
52
|
+
const t = termsFor({ ...r, nowUnix: r.nowUnix }, 'minute', order.side, total, 0, 0);
|
|
53
|
+
const at = { ...t, engine: { ...t.engine, entryPrice: scaled(1) } };
|
|
54
|
+
return {
|
|
55
|
+
market: order.market, side: order.side, total, stake: t.engine.collateral, leverage: Number(t.engine.tier), timer: t.timerS,
|
|
56
|
+
target: r.minute.params.rungBps === 0 ? null : r.minute.params.rungBps / 10_000,
|
|
57
|
+
payoutAtTarget: r.minute.params.rungBps === 0 ? null : payoutAt(at, 1, 'takeProfit'), payoutAtBarrier: payoutAt(at, 1, 'knockout'),
|
|
58
|
+
minuteFees: { entryBps: r.minute.params.entryFeeBps, exitBps: r.minute.params.exitFeeBps },
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
async function buildRound(order) {
|
|
62
|
+
const r = await read(order.market);
|
|
63
|
+
const m = r.minute;
|
|
64
|
+
if (!r.market.minuteEnabled || r.market.paused || m.pausedOpens || r.config.paused) {
|
|
65
|
+
throw new Refusal('venue', 'MINUTE_CLOSED', `${order.market} takes no Minute round now`, true, 60_000);
|
|
66
|
+
}
|
|
67
|
+
const total = typeof order.usd === 'bigint' ? order.usd : parseUsdc(order.usd);
|
|
68
|
+
if (total < m.params.minStake || total > m.params.maxStake)
|
|
69
|
+
throw new Refusal('venue', 'StakeOutOfRange', 'the total is outside Minute\'s stake bounds');
|
|
70
|
+
const predicted = collateralForTotal(total - (total * BigInt(m.params.entryFeeBps)) / 10000n, r.config.params.entryFeeBps).collateral;
|
|
71
|
+
const walletToken = toHex(ata(owner, new PublicKey(toBase58(m.usdcMint))));
|
|
72
|
+
const accounts = {
|
|
73
|
+
config: toHex(minuteConfigPda().address), player: toHex(player.address), player_token: toHex(custody), positions: toHex(book),
|
|
74
|
+
knockout_vault: toHex(vaultPda().address), knockout_vault_token: r.vault.tokenAccount, knockout_program: toHex(new PublicKey(PROGRAM_ID)),
|
|
75
|
+
};
|
|
76
|
+
const built = [];
|
|
77
|
+
if (!r.playerExists) {
|
|
78
|
+
// Once per player, signed and paid by the player.
|
|
79
|
+
if (session)
|
|
80
|
+
throw new Refusal('session', 'NO_PLAYER', 'the owner has no Minute account yet: the owner plays one round first');
|
|
81
|
+
built.push(minuteIx.initPlayer({ ...accounts, payer: toHex(owner), player_wallet: toHex(owner), usdc_mint: m.usdcMint }, { book_slots: m.params.defaultBookSlots, round_slots: m.params.defaultRoundSlots, referrer: '00'.repeat(32) }));
|
|
82
|
+
}
|
|
83
|
+
// A session key pays, and spends the owner's USDC as the SPL delegate the owner approved.
|
|
84
|
+
built.push(minuteIx.openRound({ ...accounts, payer: toHex(signer), player_wallet: toHex(owner), funder: toHex(signer), wallet_token: walletToken,
|
|
85
|
+
knockout_config: toHex(configPda().address), knockout_market: toHex(marketPda(assetId(order.market)).address), knockout_protocol_token: r.config.treasury }, { game_kind: 0, direction: order.side === 'long' ? 0 : 1, total_in: total, min_collateral_out: predicted }, withFeeTermsTable(pricingRemainingAccounts(r.market), r.market, r.config, 'open')));
|
|
86
|
+
// A round names Minute's accounts and the venue's: compile it against Minute's lookup table (frozen, read once).
|
|
87
|
+
lookupTables ??= await (async () => {
|
|
88
|
+
const t = (await o.rpc.conn.getAddressLookupTable(new PublicKey(toBase58(m.lookupTable)), { commitment: 'confirmed' })).value;
|
|
89
|
+
return t === null ? [] : [t];
|
|
90
|
+
})();
|
|
91
|
+
return { ...bundleOf(built), lookupTables };
|
|
92
|
+
}
|
|
93
|
+
const settlementOf = (t, minute, gross) => {
|
|
94
|
+
// A round's result also pays Minute's own fees: its entry fee from the total, its exit fee from the payout.
|
|
95
|
+
const total = gross ?? (t.stake * 10000n) / (10000n - BigInt(minute.params.entryFeeBps));
|
|
96
|
+
const payout = t.pnl.payout - (t.pnl.payout * BigInt(minute.params.exitFeeBps)) / 10000n;
|
|
97
|
+
return { seq: t.seq, market: marketSymbol(t.market), side: t.direction, stake: total, payout, pnl: payout - total, reason: t.reason, settledAt: t.settledAt, signature: t.signature };
|
|
98
|
+
};
|
|
99
|
+
async function history(opts = {}) {
|
|
100
|
+
let limit = opts.limit ?? 100;
|
|
101
|
+
if (opts.since !== undefined) {
|
|
102
|
+
const sigs = await o.rpc.conn.getSignaturesForAddress(book, { limit: 1000 }, 'confirmed');
|
|
103
|
+
limit = sigs.filter((s) => (s.blockTime ?? 0) >= opts.since).length;
|
|
104
|
+
if (limit === 0)
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
const [c, mc] = await o.rpc.conn.getMultipleAccountsInfo([configPda().address, minuteConfigPda().address], 'confirmed');
|
|
108
|
+
const h = await readTradeHistory(reader, player.address, decodeConfig(new Uint8Array(c.data)), { limit });
|
|
109
|
+
const minute = decodeMinuteConfig(new Uint8Array(mc.data));
|
|
110
|
+
return h.trades.filter((t) => opts.since === undefined || (t.settledAt ?? 0) >= opts.since).map((t) => settlementOf(t, minute, null));
|
|
111
|
+
}
|
|
112
|
+
async function settlement(seq, gross = null) {
|
|
113
|
+
const [c, mc] = await o.rpc.conn.getMultipleAccountsInfo([configPda().address, minuteConfigPda().address], 'confirmed');
|
|
114
|
+
const h = await readTradeHistory(reader, player.address, decodeConfig(new Uint8Array(c.data)), { limit: 25 });
|
|
115
|
+
const t = h.trades.find((x) => x.seq === seq);
|
|
116
|
+
if (t !== undefined)
|
|
117
|
+
return settlementOf(t, decodeMinuteConfig(new Uint8Array(mc.data)), gross);
|
|
118
|
+
const v = h.voidedOpens.find((x) => x.seq === seq);
|
|
119
|
+
return v === undefined ? null : {
|
|
120
|
+
seq, market: marketSymbol(v.market), side: null, stake: gross ?? v.stake, payout: v.stakeReturned, pnl: v.stakeReturned - (gross ?? v.stake),
|
|
121
|
+
reason: `returned (${v.reason})`, settledAt: v.blockTime, signature: v.signature,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
owner,
|
|
126
|
+
player: player.address,
|
|
127
|
+
book,
|
|
128
|
+
custody,
|
|
129
|
+
rounds,
|
|
130
|
+
preview,
|
|
131
|
+
history,
|
|
132
|
+
settlement,
|
|
133
|
+
async round(order) {
|
|
134
|
+
const sent = await transact(sender, await buildRound(order), true);
|
|
135
|
+
const opened = minuteEventPayloads(sent.logs).map(decodeMinuteEvent).find((e) => e?.name === 'RoundOpened');
|
|
136
|
+
return { seq: opened?.event?.seq ?? 0n, signature: sent.signature };
|
|
137
|
+
},
|
|
138
|
+
build: { round: buildRound },
|
|
139
|
+
};
|
|
140
|
+
}
|
package/dist/paper.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Paper trading: the same commands, risk guard and loop, against simulated fills. Nothing is sent.
|
|
2
|
+
// Every result is priced by the SDK's own settlement arithmetic (`settle`), with the terms a real
|
|
3
|
+
// position freezes at open: the barrier, the target, the exit fee and the market's fee terms (the
|
|
4
|
+
// share of a gain the venue keeps). A Minute round also pays Minute's own fees. Two things differ
|
|
5
|
+
// from live: the fill is the next price the bot sees (not the venue's), and a one-shot command
|
|
6
|
+
// checks the barrier only at the prices it sees (`wheelman run --paper` sees every tick).
|
|
7
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { dirname } from 'node:path';
|
|
9
|
+
import { assetId, barrierMicroBps, collateralForTotal, configPda, decodeConfig, decodeFeeTermsTable, decodeMarket, feeTermsTablePda, marketPda, exitFeeBpsFor, favourableMove, governedFrom, openFeeTerms, openPreview, settle, sizeForTotal, } from '@rekt-trading/1000x';
|
|
10
|
+
import { decodeMinuteConfig, minuteConfigPda } from '@rekt-trading/1000x'; // Minute's API ships in the same package
|
|
11
|
+
import { CLOCK } from "./rpc.js";
|
|
12
|
+
import { Refusal } from "./errors.js";
|
|
13
|
+
import { log } from "./journal.js";
|
|
14
|
+
import { usd } from "./risk.js";
|
|
15
|
+
/** The venue state that prices a paper open, in one read. */
|
|
16
|
+
export async function readVenue(rpc, symbol) {
|
|
17
|
+
const market = marketPda(assetId(symbol)).address;
|
|
18
|
+
const [c, m, f, mc, k] = await rpc.conn.getMultipleAccountsInfo([configPda().address, market, feeTermsTablePda(market).address, minuteConfigPda().address, CLOCK], 'confirmed');
|
|
19
|
+
if (c === null)
|
|
20
|
+
throw new Refusal('config', 'VENUE_MISSING', 'the venue config is missing: is RPC_URL a mainnet endpoint?');
|
|
21
|
+
if (m === null)
|
|
22
|
+
throw new Refusal('config', 'NO_SUCH_MARKET', `${symbol} is not listed on the venue`);
|
|
23
|
+
return {
|
|
24
|
+
config: decodeConfig(new Uint8Array(c.data)), market: decodeMarket(new Uint8Array(m.data)),
|
|
25
|
+
feeTable: f === null ? null : decodeFeeTermsTable(new Uint8Array(f.data)), minute: mc === null ? null : decodeMinuteConfig(new Uint8Array(mc.data)),
|
|
26
|
+
nowUnix: Buffer.from(k.data).readBigInt64LE(32),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** Prices are numbers outside the engine and bigint inside it, on one fixed scale. */
|
|
30
|
+
export const scaled = (price) => BigInt(Math.round(price * 1e8));
|
|
31
|
+
/**
|
|
32
|
+
* The terms an open of `total` (what leaves the wallet) freezes now. A Minute round takes Minute's
|
|
33
|
+
* own target, timer and leverage, and pays Minute's entry fee from inside the total.
|
|
34
|
+
*/
|
|
35
|
+
export function termsFor(v, game, side, total, takeProfitX, timerS) {
|
|
36
|
+
const p = v.config.params;
|
|
37
|
+
const m = game === 'minute' ? v.minute : null;
|
|
38
|
+
if (game === 'minute' && m === null)
|
|
39
|
+
throw new Refusal('venue', 'MINUTE_MISSING', 'the Minute config is missing');
|
|
40
|
+
let collateral;
|
|
41
|
+
if (m !== null) {
|
|
42
|
+
collateral = collateralForTotal(total - (total * BigInt(m.params.entryFeeBps)) / 10000n, p.entryFeeBps).collateral;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
const size = sizeForTotal(total, p);
|
|
46
|
+
if (size.refusal !== null)
|
|
47
|
+
throw new Refusal('venue', size.refusal.id, `${size.refusal.label}: ${size.refusal.detail}`);
|
|
48
|
+
collateral = size.collateral;
|
|
49
|
+
}
|
|
50
|
+
const rungBps = m !== null ? m.params.rungBps : Math.round(takeProfitX * 10_000);
|
|
51
|
+
const timer = m !== null ? m.params.initialTimerS : timerS;
|
|
52
|
+
const preview = openPreview(v.config, v.market, collateral, rungBps, v.nowUnix, timer > 0 ? timer : null, m?.params.tier ?? 0);
|
|
53
|
+
const fee = openFeeTerms(v.config, v.market, v.feeTable);
|
|
54
|
+
// An open under fee terms freezes the terms' loss rate as its exit-fee bound; otherwise the market's
|
|
55
|
+
// rate, or the venue's. (The program's rule; the SDK has no builder for an open's engine position.)
|
|
56
|
+
const exitFeeBps = fee.kind === 'terms' ? BigInt(fee.entry.lossBps) : exitFeeBpsFor(BigInt(v.market.exitFeeBps), p.exitFeeBps);
|
|
57
|
+
return {
|
|
58
|
+
// Built the way the SDK builds an engine position from a book slot.
|
|
59
|
+
engine: {
|
|
60
|
+
collateral, tier: preview.tier, direction: side, entryPrice: 0n, muBps: p.muBps,
|
|
61
|
+
exitFeeBps, payoutCapMultiple: p.payoutCapMultiple,
|
|
62
|
+
takeProfit: preview.takeProfitMicroBp, rungBps, userTimerSet: timer > 0,
|
|
63
|
+
},
|
|
64
|
+
feeTerms: fee.kind === 'terms' ? fee.entry : null,
|
|
65
|
+
governed: governedFrom(v.config, v.nowUnix),
|
|
66
|
+
minute: m === null ? null : { entryBps: m.params.entryFeeBps, exitBps: m.params.exitFeeBps },
|
|
67
|
+
timerS: timer,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** What the trader receives at `price` for `reason`: the SDK's settlement, net of every fee it models. */
|
|
71
|
+
export function payoutAt(t, price, reason) {
|
|
72
|
+
const terminal = reason === 'knockout' ? 'knockedOut' : reason === 'takeProfit' ? 'tookProfit' : 'live';
|
|
73
|
+
const paid = settle(t.engine, scaled(price), reason, t.governed, terminal, 'current', undefined, t.feeTerms ?? undefined).payouts.trader;
|
|
74
|
+
return t.minute === null ? paid : paid - (paid * BigInt(t.minute.exitBps)) / 10000n;
|
|
75
|
+
}
|
|
76
|
+
/** Which end, if any, this price brings: the barrier first, then the target, the timer, a close. */
|
|
77
|
+
export function endAt(t, price, timerDue, closeDue) {
|
|
78
|
+
const moved = favourableMove(t.engine, scaled(price));
|
|
79
|
+
if (moved <= -barrierMicroBps(t.engine.tier, t.engine.muBps))
|
|
80
|
+
return 'knockout';
|
|
81
|
+
if (t.engine.takeProfit !== null && moved >= t.engine.takeProfit)
|
|
82
|
+
return 'takeProfit';
|
|
83
|
+
if (timerDue)
|
|
84
|
+
return 'userExpiry';
|
|
85
|
+
if (closeDue)
|
|
86
|
+
return 'voluntary';
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
/** A paper account. `price` freezes the venue's terms for each open. */
|
|
90
|
+
export class Paper {
|
|
91
|
+
cash;
|
|
92
|
+
open = [];
|
|
93
|
+
closed = [];
|
|
94
|
+
seq = 0;
|
|
95
|
+
market;
|
|
96
|
+
price;
|
|
97
|
+
constructor(cash, market, price) {
|
|
98
|
+
this.cash = cash;
|
|
99
|
+
this.market = market;
|
|
100
|
+
this.price = price;
|
|
101
|
+
}
|
|
102
|
+
/** Fill every order placed before this tick at its price, and end what this price ends. */
|
|
103
|
+
mark(t) {
|
|
104
|
+
const done = [];
|
|
105
|
+
for (const p of [...this.open]) {
|
|
106
|
+
if (p.market !== t.market)
|
|
107
|
+
continue;
|
|
108
|
+
if (p.entry === null) {
|
|
109
|
+
if (t.time > p.placedAt) {
|
|
110
|
+
p.entry = t.price;
|
|
111
|
+
p.openedMs = t.time;
|
|
112
|
+
p.terms.engine.entryPrice = scaled(t.price);
|
|
113
|
+
}
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const timerDue = p.terms.timerS > 0 && t.time >= p.openedMs + p.terms.timerS * 1000;
|
|
117
|
+
const reason = endAt(p.terms, t.price, timerDue, p.closeAt !== null && t.time > p.closeAt);
|
|
118
|
+
if (reason === null)
|
|
119
|
+
continue;
|
|
120
|
+
const payout = payoutAt(p.terms, t.price, reason);
|
|
121
|
+
this.open.splice(this.open.indexOf(p), 1);
|
|
122
|
+
this.cash += payout;
|
|
123
|
+
const c = { id: p.id, game: p.game, market: p.market, side: p.side, stake: p.stake, entry: p.entry, exit: t.price, reason, payout, pnl: payout - p.stake, time: t.time };
|
|
124
|
+
this.closed.push(c);
|
|
125
|
+
done.push(c);
|
|
126
|
+
}
|
|
127
|
+
return done;
|
|
128
|
+
}
|
|
129
|
+
/** Place orders and close requests. Returns the ids of the orders placed. */
|
|
130
|
+
place(intents, now) {
|
|
131
|
+
const ids = [];
|
|
132
|
+
for (const i of intents) {
|
|
133
|
+
if (i.kind === 'close') {
|
|
134
|
+
const p = this.open.find((x) => x.id === i.id);
|
|
135
|
+
if (p === undefined)
|
|
136
|
+
throw new Refusal('paper', 'NO_SUCH_POSITION', `paper position ${i.id} is not open`);
|
|
137
|
+
if (p.entry === null)
|
|
138
|
+
throw new Refusal('paper', 'NOT_FILLED', `paper position ${i.id} is an order that waits for its price`, true, 5_000);
|
|
139
|
+
p.closeAt ??= now;
|
|
140
|
+
p.closing = true;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (i.stake > this.cash)
|
|
144
|
+
throw new Refusal('paper', 'NOT_ENOUGH_USDC', `the paper account holds ${usd(this.cash)}`);
|
|
145
|
+
const terms = this.price(i);
|
|
146
|
+
const id = String(++this.seq);
|
|
147
|
+
this.open.push({
|
|
148
|
+
id, game: i.kind === 'round' ? 'minute' : 'knockout', market: this.market, side: i.side, stake: i.stake, entry: null,
|
|
149
|
+
openedMs: now, closing: false, placedAt: now, closeAt: null, terms,
|
|
150
|
+
});
|
|
151
|
+
this.cash -= i.stake;
|
|
152
|
+
ids.push(id);
|
|
153
|
+
}
|
|
154
|
+
return ids;
|
|
155
|
+
}
|
|
156
|
+
positions() {
|
|
157
|
+
return this.open.map(({ id, game, side, stake, entry, openedMs, closing }) => ({ id, game, side, stake, entry, openedMs, closing }));
|
|
158
|
+
}
|
|
159
|
+
/** Today's result (UTC), from the paper account's own closes. */
|
|
160
|
+
realizedSince(sinceMs) {
|
|
161
|
+
return this.closed.filter((c) => c.time >= sinceMs).reduce((s, c) => s + c.pnl, 0n);
|
|
162
|
+
}
|
|
163
|
+
book(todayPnl) {
|
|
164
|
+
return { open: this.open.length, atStake: this.open.reduce((s, p) => s + p.stake, 0n), free: this.cash, held: 0n, todayPnl, sol: 1 };
|
|
165
|
+
}
|
|
166
|
+
// The Broker interface, so the loop runs on paper unchanged.
|
|
167
|
+
async onTick(t) {
|
|
168
|
+
let pnl = 0n;
|
|
169
|
+
for (const c of this.mark(t)) {
|
|
170
|
+
pnl += c.pnl;
|
|
171
|
+
log('paper-close', { ...c, stake: usd(c.stake), payout: usd(c.payout), pnl: usd(c.pnl) });
|
|
172
|
+
}
|
|
173
|
+
return pnl;
|
|
174
|
+
}
|
|
175
|
+
async beforeAct() { }
|
|
176
|
+
async execute(intents, now) {
|
|
177
|
+
try {
|
|
178
|
+
const ids = this.place(intents, now);
|
|
179
|
+
for (const { kind, ...i } of intents)
|
|
180
|
+
log('paper-intent', { intent: kind, ...i, ...('stake' in i ? { stake: usd(i.stake) } : {}) });
|
|
181
|
+
if (ids.length > 0)
|
|
182
|
+
log('paper-open', { ids });
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
if (!(e instanceof Refusal))
|
|
187
|
+
throw e;
|
|
188
|
+
log('refused', { code: e.code, message: e.message });
|
|
189
|
+
return now + e.waitMs;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** Counts and the result: facts about this paper account, not a forecast. */
|
|
193
|
+
summary() {
|
|
194
|
+
const by = (reason) => this.closed.filter((c) => c.reason === reason).length;
|
|
195
|
+
return {
|
|
196
|
+
opened: this.closed.length + this.open.length, closed: this.closed.length, open: this.open.length,
|
|
197
|
+
knockout: by('knockout'), takeProfit: by('takeProfit'), timer: by('userExpiry'), close: by('voluntary'),
|
|
198
|
+
result: this.closed.reduce((s, c) => s + c.pnl, 0n), usdc: this.cash,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
// A paper account kept in a file, for one-shot commands. bigint is written as "123n".
|
|
202
|
+
static load(path, cash, market, price) {
|
|
203
|
+
const paper = new Paper(cash, market, price);
|
|
204
|
+
let text;
|
|
205
|
+
try {
|
|
206
|
+
text = readFileSync(path, 'utf8');
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return paper;
|
|
210
|
+
}
|
|
211
|
+
const s = JSON.parse(text, (_k, v) => (typeof v === 'string' && /^-?\d+n$/.test(v) ? BigInt(v.slice(0, -1)) : v));
|
|
212
|
+
Object.assign(paper, { cash: s.cash, open: s.open, closed: s.closed, seq: s.seq });
|
|
213
|
+
return paper;
|
|
214
|
+
}
|
|
215
|
+
save(path) {
|
|
216
|
+
const state = { cash: this.cash, open: this.open, closed: this.closed, seq: this.seq };
|
|
217
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
218
|
+
writeFileSync(path, JSON.stringify(state, (_k, v) => (typeof v === 'bigint' ? `${v}n` : v), 1));
|
|
219
|
+
}
|
|
220
|
+
}
|